1
0
silverbullet/packages/plugs/markdown/util.ts

56 lines
1.3 KiB
TypeScript
Raw Normal View History

2022-04-25 08:33:38 +00:00
import {
findNodeOfType,
renderToText,
replaceNodesMatching,
} from "@silverbulletmd/common/tree";
2022-04-25 09:24:13 +00:00
import { parseMarkdown } from "@silverbulletmd/plugos-silverbullet-syscall/markdown";
export function encodePageUrl(name: string): string {
return name.replaceAll(" ", "_");
}
2022-09-01 08:17:20 +00:00
export async function cleanMarkdown(
text: string,
validPages?: string[]
): Promise<string> {
let mdTree = await parseMarkdown(text);
replaceNodesMatching(mdTree, (n) => {
if (n.type === "WikiLink") {
const page = n.children![1].children![0].text!;
2022-09-01 08:17:20 +00:00
if (validPages && !validPages.includes(page)) {
return {
// HACK
text: `_${page}_`,
};
}
return {
// HACK
text: `[${page}](/${encodePageUrl(page)})`,
};
}
// Simply get rid of these
2022-09-01 08:17:20 +00:00
if (
n.type === "CommentBlock" ||
n.type === "Comment" ||
n.type === "NamedAnchor"
) {
return null;
}
2022-09-01 08:17:20 +00:00
if (n.type === "Hashtag") {
return {
text: `__${n.children![0].text}__`,
};
}
if (n.type === "FencedCode") {
let codeInfoNode = findNodeOfType(n, "CodeInfo");
if (!codeInfoNode) {
return;
}
if (codeInfoNode.children![0].text === "meta") {
return null;
}
}
});
return renderToText(mdTree);
}