1
0
silverbullet/plugs/markdown/markdown.ts

57 lines
1.6 KiB
TypeScript
Raw Normal View History

2022-03-28 13:25:05 +00:00
import MarkdownIt from "markdown-it";
2022-04-04 13:25:07 +00:00
import {getText, hideRhs, showRhs} from "plugos-silverbullet-syscall/editor";
import * as clientStore from "plugos-silverbullet-syscall/clientStore";
import {parseMarkdown} from "plugos-silverbullet-syscall/markdown";
import {addParentPointers, renderMarkdown, replaceNodesMatching,} from "../lib/tree";
2022-03-28 13:25:05 +00:00
var taskLists = require("markdown-it-task-lists");
const md = new MarkdownIt({
linkify: true,
html: false,
typographer: true,
}).use(taskLists);
2022-04-04 13:25:07 +00:00
export async function togglePreview() {
let currentValue = !!(await clientStore.get("enableMarkdownPreview"));
await clientStore.set("enableMarkdownPreview", !currentValue);
if (!currentValue) {
updateMarkdownPreview();
} else {
hideMarkdownPreview();
}
}
function encodePageUrl(name: string): string {
return name.replaceAll(" ", "_");
}
export async function updateMarkdownPreview() {
if (!(await clientStore.get("enableMarkdownPreview"))) {
return;
}
2022-04-01 15:07:08 +00:00
let text = await getText();
2022-04-04 13:25:07 +00:00
let mdTree = await parseMarkdown(text);
// console.log("The tree", mdTree);
addParentPointers(mdTree);
replaceNodesMatching(mdTree, (n) => {
if (n.type === "WikiLink") {
const page = n.children![1].children![0].text!;
return {
// HACK
text: `[${page}](/${encodePageUrl(page)})`,
};
}
// Simply get rid of these
if (n.type === "CommentBlock" || n.type === "Comment") {
return null;
}
});
let html = md.render(renderMarkdown(mdTree));
2022-04-04 16:33:13 +00:00
await showRhs(`<html><body>${html}</body></html>`, 1);
2022-03-28 13:25:05 +00:00
}
2022-04-04 13:25:07 +00:00
async function hideMarkdownPreview() {
await hideRhs();
}