Skip to content

Instantly share code, notes, and snippets.

@Eyas
Created January 23, 2020 03:12
Show Gist options
  • Save Eyas/66ed9409bb2f84dbba94779cfabd4c1a to your computer and use it in GitHub Desktop.
Save Eyas/66ed9409bb2f84dbba94779cfabd4c1a to your computer and use it in GitHub Desktop.
// Tag Management: Define functions describing what to do with HTML tags in our
// comments.
interface OnTag {
open(attrs: {[key: string]: string}): string;
close(): string;
}
// Some handlers for behaviors that apply to multiple tags:
const em: OnTag = { open: () => '_', close: () => '_' };
const strong = { open: () => '__', close: () => '__' };
// ...
// Our top-level tag handler.
const onTag = new Map<string, OnTag>([
['a', {open: (attrs) => `{@link ${attrs['href']} `, close: () => '}'}],
['em', em], ['i', em],
['strong', strong], ['b', strong],
// ...
]);
function parseComment(comment: string): string {
const result: string[] = [];
const parser = new Parser({
ontext: (text: string) => result.push(replace(text)),
onopentag: (tag: string, attrs: {[key: string]: string}) => {
const handler = onTag.get(tag);
if (!handler) {
throw new Error(`Unknown tag "${tag}".`);
}
if (handler.open) {
result.push(handler.open(attrs));
}
},
onclosetag: (tag: string) => {
const handler = onTag.get(tag);
assert(handler);
if (handler.close) {
result.push(handler.close());
}
}
});
parser.write(comment);
parser.end();
// ... turn result into 'lines'
return lines.length === 1 ? `* ${lines[0]} ` :
('*\n * ' + lines.join('\n * ') + '\n ');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment