silverbullet/plugs/markdown/util.ts

64 lines
1.5 KiB
TypeScript
Raw Permalink Normal View History

2022-04-25 16:33:38 +08:00
import {
findNodeOfType,
renderToText,
replaceNodesMatching,
} from "@silverbulletmd/silverbullet/lib/tree";
import { markdown } from "@silverbulletmd/silverbullet/syscalls";
import { isLocalPath } from "@silverbulletmd/silverbullet/lib/resolve";
export function encodePageUrl(name: string): string {
return name;
}
2022-09-01 16:17:20 +08:00
export async function cleanMarkdown(
text: string,
validPages?: string[],
2022-09-01 16:17:20 +08:00
): Promise<string> {
2022-10-14 21:11:33 +08:00
const mdTree = await markdown.parseMarkdown(text);
replaceNodesMatching(mdTree, (n) => {
if (n.type === "WikiLink") {
const page = n.children![1].children![0].text!;
2022-09-01 16:17:20 +08:00
if (validPages && !validPages.includes(page)) {
return {
// HACK
text: `_${page}_`,
};
}
return {
// HACK
text: `[${page}](/${encodePageUrl(page)})`,
};
}
// Simply get rid of these
2022-09-01 16:17:20 +08:00
if (
n.type === "CommentBlock" ||
n.type === "Comment" ||
n.type === "NamedAnchor"
) {
return null;
}
2022-09-01 16:17:20 +08:00
if (n.type === "Hashtag") {
return {
text: `__${n.children![0].text}__`,
};
}
2022-09-06 20:36:06 +08:00
if (n.type === "URL") {
const url = n.children![0].text!;
2024-05-28 02:33:41 +08:00
if (isLocalPath(url)) {
2022-09-12 20:50:37 +08:00
n.children![0].text = `fs/${url}`;
2022-09-06 20:36:06 +08:00
}
console.log("Link", url);
}
if (n.type === "FencedCode") {
const codeInfoNode = findNodeOfType(n, "CodeInfo");
if (!codeInfoNode) {
return;
}
if (codeInfoNode.children![0].text === "meta") {
return null;
}
}
});
return renderToText(mdTree);
}