2022-04-25 08:33:38 +00:00
|
|
|
import {
|
|
|
|
findNodeOfType,
|
|
|
|
renderToText,
|
|
|
|
replaceNodesMatching,
|
2022-10-10 12:50:21 +00:00
|
|
|
} from "../../common/tree.ts";
|
|
|
|
import { parseMarkdown } from "../../syscall/silverbullet-syscall/markdown.ts";
|
2022-04-13 12:46:52 +00:00
|
|
|
|
|
|
|
export function encodePageUrl(name: string): string {
|
|
|
|
return name.replaceAll(" ", "_");
|
|
|
|
}
|
|
|
|
|
2022-09-01 08:17:20 +00:00
|
|
|
export async function cleanMarkdown(
|
|
|
|
text: string,
|
2022-10-10 12:50:21 +00:00
|
|
|
validPages?: string[],
|
2022-09-01 08:17:20 +00:00
|
|
|
): Promise<string> {
|
2022-10-10 12:50:21 +00:00
|
|
|
const mdTree = await parseMarkdown(text);
|
2022-04-13 12:46:52 +00:00
|
|
|
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}_`,
|
|
|
|
};
|
|
|
|
}
|
2022-04-13 12:46:52 +00:00
|
|
|
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"
|
|
|
|
) {
|
2022-04-13 12:46:52 +00:00
|
|
|
return null;
|
|
|
|
}
|
2022-09-01 08:17:20 +00:00
|
|
|
if (n.type === "Hashtag") {
|
|
|
|
return {
|
|
|
|
text: `__${n.children![0].text}__`,
|
|
|
|
};
|
|
|
|
}
|
2022-09-06 12:36:06 +00:00
|
|
|
if (n.type === "URL") {
|
|
|
|
const url = n.children![0].text!;
|
|
|
|
if (url.indexOf("://") === -1) {
|
2022-09-12 12:50:37 +00:00
|
|
|
n.children![0].text = `fs/${url}`;
|
2022-09-06 12:36:06 +00:00
|
|
|
}
|
|
|
|
console.log("Link", url);
|
|
|
|
}
|
2022-04-21 09:46:33 +00:00
|
|
|
if (n.type === "FencedCode") {
|
2022-10-10 12:50:21 +00:00
|
|
|
const codeInfoNode = findNodeOfType(n, "CodeInfo");
|
2022-04-21 09:46:33 +00:00
|
|
|
if (!codeInfoNode) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (codeInfoNode.children![0].text === "meta") {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
2022-04-13 12:46:52 +00:00
|
|
|
});
|
|
|
|
return renderToText(mdTree);
|
|
|
|
}
|