import { editor, markdown, YAML } from "$sb/syscalls.ts"; import { CodeWidgetContent } from "$sb/types.ts"; import { renderToText, traverseTree } from "$sb/lib/tree.ts"; type Header = { name: string; pos: number; level: number; }; type TocConfig = { // Only show the TOC if there are at least this many headers minHeaders?: number; // Don't show the TOC if there are more than this many headers maxHeaders?: 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; }); if (config.minHeaders && headers.length < config.minHeaders) { // Not enough headers, not showing TOC return null; } if (config.maxHeaders && headers.length > config.maxHeaders) { // Too many 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", }, ], }; }