import { editor, markdown, space, system, YAML, } from "@silverbulletmd/silverbullet/syscalls"; import { loadPageObject, replaceTemplateVars } from "./page.ts"; import type { CodeWidgetContent, PageMeta } from "../../plug-api/types.ts"; import { renderTemplate } from "./plug_api.ts"; import { renderToText } from "@silverbulletmd/silverbullet/lib/tree"; import { isFederationPath, resolvePath, rewritePageRefs, rewritePageRefsInString, } from "@silverbulletmd/silverbullet/lib/resolve"; import { queryParsed } from "../query/api.ts"; import { parseQuery } from "../../plug-api/lib/parse_query.ts"; import { parsePageRef } from "@silverbulletmd/silverbullet/lib/page_ref"; type TemplateWidgetConfig = { // Pull the template from a page page?: string; // Include a page raw (without template processing) raw?: string; // Or use a string directly template?: string; // To feed data into the template you can either use a concrete value value?: any; // Or a query query?: string; }; export async function includeWidget( bodyText: string, pageName: string, ): Promise { const pageMeta: PageMeta = await loadPageObject(pageName); const spaceConfig = await system.getSpaceConfig(); try { const config: TemplateWidgetConfig = await YAML.parse(bodyText); let templateText = config.template || ""; let templatePage = config.page || (typeof config.raw !== "boolean" && config.raw); if (templatePage) { // Rewrite federation page references templatePage = rewritePageRefsInString(templatePage, pageName); if (templatePage.startsWith("[[")) { templatePage = templatePage.slice(2, -2); } if (!templatePage) { throw new Error("No page specified"); } try { templateText = await space.readPage(templatePage); } catch (e: any) { if (e.message === "Not found") { throw new Error(`Page "${templatePage}" not found`); } } } let value: any; if (config.value) { value = JSON.parse( await replaceTemplateVars( JSON.stringify(config.value), pageMeta, spaceConfig, ), ); } if (config.query) { const parsedQuery = await parseQuery( await replaceTemplateVars(config.query, pageMeta, spaceConfig), ); value = await queryParsed(parsedQuery); } let { text: rendered } = config.raw ? { text: templateText } : await renderTemplate( templateText, value, { page: pageMeta }, ); if (templatePage) { const parsedMarkdown = await markdown.parseMarkdown(rendered); rewritePageRefs(parsedMarkdown, templatePage); rendered = renderToText(parsedMarkdown); } return { markdown: rendered, buttons: [ { description: "Bake result", svg: ``, invokeFunction: ["query.bakeButton", bodyText], }, { description: "Edit", svg: ``, invokeFunction: ["query.editButton", bodyText], }, { description: "Reload", svg: ``, invokeFunction: ["query.refreshAllWidgets"], }, ], }; } catch (e: any) { return { markdown: `**Error:** ${e.message}`, }; } } export async function templateWidget( bodyText: string, pageName: string, ): Promise { // Check if this is a legacy syntax template widget (with YAML body) try { const parsedYaml = await YAML.parse(bodyText); if ( typeof parsedYaml === "object" && (parsedYaml.template || parsedYaml.page || parsedYaml.raw) ) { // Yeah... this looks like a legacy widget console.warn( "Found a template widget with legacy syntax, implicitly rewriting it to 'include'", ); return includeWidget(bodyText, pageName); } } catch { // Not a legacy widget, good! } const config = await system.getSpaceConfig(); const pageMeta: PageMeta = await loadPageObject(pageName); try { const { text: rendered } = await renderTemplate( bodyText, pageMeta, { page: pageMeta, config }, ); return { markdown: rendered, buttons: [ { description: "Bake result", svg: ``, invokeFunction: ["query.bakeButton", bodyText], }, { description: "Edit", svg: ``, invokeFunction: ["query.editButton", bodyText], }, { description: "Reload", svg: ``, invokeFunction: ["query.refreshAllWidgets"], }, ], }; } catch (e: any) { return { markdown: `**Error:** ${e.message}`, }; } } export async function transclusionWidget( bodyText: string, pageName: string, ): Promise { const config = await system.getSpaceConfig(); const pageMeta: PageMeta = await loadPageObject(pageName); let url: string | undefined = undefined; let match: RegExpExecArray | null; if ((match = /!?\[([^\]]*)\]\((.+)\)/g.exec(bodyText))) { [/* fullMatch */, /* alias */ , url] = match; } else if ( (match = /(!?\[\[)([^\]\|]+)(?:\|([^\]]+))?(\]\])/g.exec(bodyText)) ) { [/* fullMatch */, /* firstMark */ , url /* alias */] = match; if (!isFederationPath(url)) { url = "/" + url; } } try { if (!url) { throw new Error("Could not parse link"); } url = resolvePath(pageName, url, true); const templateText = `{{rewriteRefsAndFederationLinks([[${url}]], "${url}")}}`; const { text: rendered } = await renderTemplate( templateText, pageMeta, { page: pageMeta, config }, ); return { markdown: rendered, buttons: [ { description: "Bake result", svg: ``, invokeFunction: ["query.bakeButton", bodyText], }, { description: "Open Page", svg: ``, invokeFunction: ["template.navigateButton", url], }, { description: "Reload", svg: ``, invokeFunction: ["query.refreshAllWidgets", bodyText], }, ], }; } catch (e: any) { return { markdown: `**Error:** ${e.message}`, }; } } // Navigate to page in a transclusion widget export async function navigateButton(url: string) { const pageRef = parsePageRef(url); await editor.navigate(pageRef, false, false); }