import { codeWidget, editor, events } from "$sb/syscalls.ts"; import { parseQuery } from "$sb/lib/parse-query.ts"; import { loadPageObject, replaceTemplateVars } from "../template/page.ts"; import { resolvePath } from "$sb/lib/resolve.ts"; import { CodeWidgetContent } from "../../type/types.ts"; import { jsonToMDTable, renderQueryTemplate } from "../template/util.ts"; import { renderQuery } from "./api.ts"; export async function widget( bodyText: string, pageName: string, ): Promise { const pageObject = await loadPageObject(pageName); try { let resultMarkdown = ""; const parsedQuery = await parseQuery( await replaceTemplateVars(bodyText, pageObject), ); const results = await renderQuery(parsedQuery, { page: pageObject }); if (Array.isArray(results)) { resultMarkdown = jsonToMDTable(results); } else { resultMarkdown = results; } return { markdown: resultMarkdown, buttons: [ { description: "Edit", svg: ``, invokeFunction: "query.editButton", }, { description: "Reload", svg: ``, invokeFunction: "query.refreshAllWidgets", }, ], }; } catch (e: any) { return { markdown: `**Error:** ${e.message}` }; } } export function refreshAllWidgets() { codeWidget.refreshAll(); } export async function editButton(bodyText: string) { const text = await editor.getText(); // This is a it of a heuristic and will point to the wrong place if the same body text appears in multiple places, which is easy to replicate but unlikely to happen in the real world // A more accurate fix would be to update the widget (and therefore the index of where this widget appears) on every change, but this would be rather expensive. I think this is good enough. const bodyPos = text.indexOf("\n" + bodyText + "\n"); if (bodyPos === -1) { await editor.flashNotification("Could not find widget to edit", "error"); return; } await editor.moveCursor(bodyPos + 1); }