Files
smartmarkdown/ts/smartmarkdown.classes.mdparsedresult.ts
T

50 lines
1.5 KiB
TypeScript

import * as plugins from './smartmarkdown.plugins.js';
export type TFrontmatterData = Record<string, unknown>;
type TYamlNode = plugins.RootContent & {
type: 'yaml';
value: string;
};
const isYamlNode = (nodeArg: plugins.RootContent): nodeArg is TYamlNode => {
return nodeArg.type === 'yaml' && 'value' in nodeArg && typeof nodeArg.value === 'string';
};
export class MdParsedResult {
public static async createFromMarkdownString(mdStringArg: string): Promise<MdParsedResult> {
const mdParsedResult = new MdParsedResult();
await mdParsedResult.updateFromMarkdownString(mdStringArg);
return mdParsedResult;
}
public originalString = '';
public title = '';
public html = '';
public frontmatterData: TFrontmatterData = {};
public async updateFromMarkdownString(mdStringArg: string): Promise<void> {
this.originalString = mdStringArg;
let yamlString: string | undefined;
const result = await plugins.unified()
.use(plugins.remarkParse)
.use(plugins.remarkGfm)
.use(plugins.remarkFrontmatter, ['yaml', 'toml'])
.use(plugins.remarkStringify)
.use(plugins.remarkHtml)
.use((): plugins.Transformer<plugins.Root> => (tree) => {
const yamlChild = tree.children.find(isYamlNode);
if (yamlChild) {
yamlString = yamlChild.value;
}
})
.process(mdStringArg);
this.html = result.toString();
if (yamlString) {
this.frontmatterData = await plugins.smartyaml.yamlStringToObject(yamlString);
} else {
this.frontmatterData = {};
}
}
}