1
0
silverbullet/plugs/markdown/markdown.ts

98 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-03-28 13:25:05 +00:00
import MarkdownIt from "markdown-it";
2022-04-05 15:02:17 +00:00
import { getText, hideRhs, showRhs } from "plugos-silverbullet-syscall/editor";
2022-04-04 13:25:07 +00:00
import * as clientStore from "plugos-silverbullet-syscall/clientStore";
2022-04-05 15:02:17 +00:00
import { parseMarkdown } from "plugos-silverbullet-syscall/markdown";
2022-04-11 18:34:09 +00:00
import { renderToText, replaceNodesMatching } from "../../common/tree";
2022-04-09 12:57:59 +00:00
const css = `
<style>
body {
font-family: georgia,times,serif;
font-size: 14pt;
max-width: 800px;
margin-left: auto;
margin-right: auto;
padding-left: 20px;
padding-right: 20px;
}
2022-04-10 09:04:07 +00:00
a[href] {
text-decoration: none;
}
2022-04-09 12:57:59 +00:00
blockquote {
border-left: 1px solid #333;
margin-left: 2px;
padding-left: 10px;
}
hr {
margin: 1em 0 1em 0;
text-align: center;
border-color: #777;
border-width: 0;
border-style: dotted;
}
hr:after {
content: "···";
letter-spacing: 1em;
}
</style>
`;
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(" ", "_");
}
2022-04-09 12:57:59 +00:00
export async function cleanMarkdown(text: string) {
2022-04-04 13:25:07 +00:00
let mdTree = await parseMarkdown(text);
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;
}
});
2022-04-11 18:34:09 +00:00
let html = md.render(renderToText(mdTree));
2022-04-09 12:57:59 +00:00
return html;
}
export async function updateMarkdownPreview() {
if (!(await clientStore.get("enableMarkdownPreview"))) {
return;
}
let text = await getText();
let html = await cleanMarkdown(text);
await showRhs(`<html><head>${css}</head><body>${html}</body></html>`, 2);
2022-03-28 13:25:05 +00:00
}
2022-04-04 13:25:07 +00:00
async function hideMarkdownPreview() {
await hideRhs();
}