import { editor, markdown, YAML } from "$sb/syscalls.ts"; import { CodeWidgetContent } from "$sb/types.ts"; import { renderToText, traverseTree } from "$sb/lib/tree.ts"; const defaultHeaderThreshold = 0; type Header = { name: string; pos: number; level: number; }; type TocConfig = { minHeaders?: number; header?: boolean; }; export async function widget( bodyText: string, ): Promise { let config: TocConfig = {}; if (bodyText.trim() !== "") { config = await YAML.parse(bodyText); } const page = await editor.getCurrentPage(); const text = await editor.getText(); const tree = await markdown.parseMarkdown(text); const headers: Header[] = []; traverseTree(tree, (n) => { if (n.type?.startsWith("ATXHeading")) { headers.push({ name: n.children!.slice(1).map(renderToText).join("").trim(), pos: n.from!, level: +n.type[n.type.length - 1], }); return true; } return false; }); let headerThreshold = defaultHeaderThreshold; if (config.minHeaders) { headerThreshold = config.minHeaders; } if (headers.length < headerThreshold) { // Not enough headers, not showing TOC return null; } let headerText = "# Table of Contents\n"; if (config.header === false) { headerText = ""; } // console.log("Headers", headers); // Adjust level down if only sub-headers are used const minLevel = headers.reduce( (min, header) => Math.min(min, header.level), 6, ); const renderedMd = headerText + headers.map((header) => `${ " ".repeat((header.level - minLevel) * 2) }* [[${page}@${header.pos}|${header.name}]]` ).join("\n"); // console.log("Markdown", renderedMd); return { markdown: renderedMd, buttons: [ { description: "Edit", svg: ``, invokeFunction: "query.editButton", }, { description: "Reload", svg: ``, invokeFunction: "index.refreshWidgets", }, ], }; }