2023-08-28 23:12:15 +08:00
|
|
|
import { asset, clientStore, editor, markdown, system } from "$sb/syscalls.ts";
|
2022-11-01 22:01:28 +08:00
|
|
|
import { renderMarkdownToHtml } from "./markdown_render.ts";
|
2024-05-28 02:33:41 +08:00
|
|
|
import { isLocalPath, resolvePath } from "$sb/lib/resolve.ts";
|
2023-11-02 23:09:25 +08:00
|
|
|
import { expandCodeWidgets } from "./api.ts";
|
2022-04-13 20:46:52 +08:00
|
|
|
|
|
|
|
export async function updateMarkdownPreview() {
|
2023-08-26 14:31:51 +08:00
|
|
|
if (!(await clientStore.get("enableMarkdownPreview"))) {
|
2022-04-13 20:46:52 +08:00
|
|
|
return;
|
|
|
|
}
|
2023-07-30 05:41:37 +08:00
|
|
|
const currentPage = await editor.getCurrentPage();
|
2022-10-14 21:11:33 +08:00
|
|
|
const text = await editor.getText();
|
2023-08-28 23:12:15 +08:00
|
|
|
const mdTree = await markdown.parseMarkdown(text);
|
2022-11-01 22:01:28 +08:00
|
|
|
// const cleanMd = await cleanMarkdown(text);
|
2024-01-15 23:43:12 +08:00
|
|
|
const css = await asset.readAsset("markdown", "assets/preview.css");
|
|
|
|
const js = await asset.readAsset("markdown", "assets/preview.js");
|
2023-11-02 23:09:25 +08:00
|
|
|
|
|
|
|
await expandCodeWidgets(mdTree, currentPage);
|
2023-05-26 20:04:32 +08:00
|
|
|
const html = renderMarkdownToHtml(mdTree, {
|
2022-11-01 22:01:28 +08:00
|
|
|
smartHardBreak: true,
|
|
|
|
annotationPositions: true,
|
2023-12-20 00:55:11 +08:00
|
|
|
translateUrls: (url) => {
|
2024-05-28 02:33:41 +08:00
|
|
|
if (isLocalPath(url)) {
|
|
|
|
url = resolvePath(currentPage, decodeURI(url));
|
2023-02-23 22:33:51 +08:00
|
|
|
}
|
|
|
|
return url;
|
|
|
|
},
|
2022-11-01 22:01:28 +08:00
|
|
|
});
|
2024-02-23 16:01:38 +08:00
|
|
|
const customStyles = await editor.getUiOption("customStyles");
|
|
|
|
const darkMode = await clientStore.get("darkMode");
|
|
|
|
const theme = darkMode ? "dark" : "light";
|
2022-10-14 21:11:33 +08:00
|
|
|
await editor.showPanel(
|
2022-09-30 23:05:45 +08:00
|
|
|
"rhs",
|
|
|
|
2,
|
2024-06-07 14:19:26 +08:00
|
|
|
`
|
|
|
|
<link rel="stylesheet" href="/.client/main.css" />
|
|
|
|
<style>
|
|
|
|
${css}
|
|
|
|
${customStyles ?? ""}
|
|
|
|
</style>
|
|
|
|
|
|
|
|
<div id="root" class="sb-preview">${html}</div>
|
|
|
|
`,
|
2024-02-23 16:01:38 +08:00
|
|
|
`
|
|
|
|
document.documentElement.dataset.theme = ${JSON.stringify(theme)};
|
|
|
|
|
|
|
|
${js}
|
|
|
|
`,
|
2022-04-13 20:46:52 +08:00
|
|
|
);
|
|
|
|
}
|
2022-11-01 22:01:28 +08:00
|
|
|
|
|
|
|
export async function previewClickHandler(e: any) {
|
|
|
|
const [eventName, arg] = JSON.parse(e);
|
|
|
|
// console.log("Got click", eventName, arg);
|
|
|
|
switch (eventName) {
|
|
|
|
case "pos":
|
|
|
|
// console.log("Moving cursor to", +arg);
|
|
|
|
await editor.moveCursor(+arg, true);
|
|
|
|
break;
|
|
|
|
case "command":
|
|
|
|
await system.invokeCommand(arg);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|