2023-10-03 12:16:33 +00:00
|
|
|
import { WidgetContent } from "$sb/app_event.ts";
|
2023-11-02 11:51:09 +00:00
|
|
|
import { handlebars, markdown, space, system, YAML } from "$sb/syscalls.ts";
|
2023-10-03 16:09:03 +00:00
|
|
|
import { rewritePageRefs } from "$sb/lib/resolve.ts";
|
2023-10-06 12:40:09 +00:00
|
|
|
import { replaceTemplateVars } from "../template/template.ts";
|
2023-10-29 09:02:50 +00:00
|
|
|
import { renderToText } from "$sb/lib/tree.ts";
|
2023-10-03 12:16:33 +00:00
|
|
|
|
|
|
|
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;
|
|
|
|
};
|
|
|
|
|
2023-11-02 11:51:09 +00:00
|
|
|
export async function widget(
|
|
|
|
bodyText: string,
|
|
|
|
pageName: string,
|
|
|
|
): Promise<WidgetContent> {
|
|
|
|
const pageMeta = await space.getPageMeta(pageName);
|
2023-10-03 12:16:33 +00:00
|
|
|
|
|
|
|
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 12:16:33 +00:00
|
|
|
}
|
2023-10-03 16:09:03 +00:00
|
|
|
templateText = await space.readPage(templatePage);
|
2023-10-03 12:16:33 +00:00
|
|
|
}
|
|
|
|
|
2023-10-06 12:40:09 +00:00
|
|
|
const value = config.value
|
|
|
|
? JSON.parse(
|
|
|
|
await replaceTemplateVars(JSON.stringify(config.value), pageMeta),
|
|
|
|
)
|
|
|
|
: undefined;
|
|
|
|
|
2023-10-29 09:02:50 +00:00
|
|
|
let rendered = config.raw ? templateText : await handlebars.renderTemplate(
|
|
|
|
templateText,
|
|
|
|
value,
|
|
|
|
{
|
|
|
|
page: pageMeta,
|
|
|
|
},
|
|
|
|
);
|
2023-10-03 16:09:03 +00:00
|
|
|
|
|
|
|
if (templatePage) {
|
2023-10-29 09:02:50 +00:00
|
|
|
const parsedMarkdown = await markdown.parseMarkdown(rendered);
|
2023-10-03 16:09:03 +00:00
|
|
|
rewritePageRefs(parsedMarkdown, templatePage);
|
2023-10-29 09:02:50 +00:00
|
|
|
rendered = renderToText(parsedMarkdown);
|
2023-10-03 16:09:03 +00:00
|
|
|
}
|
2023-10-03 12:16:33 +00:00
|
|
|
|
2023-10-29 09:02:50 +00:00
|
|
|
return system.invokeFunction(
|
|
|
|
"markdown.markdownContentWidget",
|
|
|
|
rendered,
|
|
|
|
);
|
2023-10-03 12:16:33 +00:00
|
|
|
} catch (e: any) {
|
2023-10-29 09:02:50 +00:00
|
|
|
return system.invokeFunction(
|
|
|
|
"markdown.markdownContentWidget",
|
|
|
|
`**Error:** ${e.message}`,
|
|
|
|
);
|
2023-10-03 12:16:33 +00:00
|
|
|
}
|
|
|
|
}
|