1
0
silverbullet/plugs/query/template.ts

60 lines
1.6 KiB
TypeScript
Raw Normal View History

import { WidgetContent } from "$sb/app_event.ts";
import { editor, handlebars, markdown, space, YAML } from "$sb/syscalls.ts";
2023-10-03 16:09:03 +00:00
import { rewritePageRefs } from "$sb/lib/resolve.ts";
import { renderMarkdownToHtml } from "../markdown/markdown_render.ts";
import { prepareJS, wrapHTML } from "./util.ts";
type TemplateConfig = {
// Pull the template from a page
page?: string;
// Or use a string directly
template?: string;
// Optional argument to pass
value?: any;
// If true, don't render the template, just use it as-is
raw?: boolean;
};
export async function widget(bodyText: string): Promise<WidgetContent> {
const pageMeta = await space.getPageMeta(await editor.getCurrentPage());
try {
const config: TemplateConfig = await YAML.parse(bodyText);
let templateText = config.template || "";
2023-10-03 16:09:03 +00:00
let templatePage = config.page;
if (templatePage) {
if (templatePage.startsWith("[[")) {
templatePage = templatePage.slice(2, -2);
}
2023-10-03 16:09:03 +00:00
templateText = await space.readPage(templatePage);
}
const rendered = config.raw
? templateText
: await handlebars.renderTemplate(
templateText,
config.value,
{
page: pageMeta,
},
);
const parsedMarkdown = await markdown.parseMarkdown(rendered);
2023-10-03 16:09:03 +00:00
if (templatePage) {
rewritePageRefs(parsedMarkdown, templatePage);
}
const html = renderMarkdownToHtml(parsedMarkdown, {
smartHardBreak: true,
});
return {
html: await wrapHTML(html),
script: await prepareJS(),
};
} catch (e: any) {
return {
html: `<b>Error:</b> ${e.message}`,
};
}
}