Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/text editor/custom task states: specify the state name as a tooltip for static HTML rendition (markdown to HTML conversion)
Adorian Doran34dafd3ac30c
diff --git a/packages/commons/src/lib/markdown_renderer.spec.ts b/packages/commons/src/lib/markdown_renderer.spec.tsindex f0e783f2e2..3e608c60b7 100644--- a/packages/commons/src/lib/markdown_renderer.spec.ts+++ b/packages/commons/src/lib/markdown_renderer.spec.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";import { CustomMarkdownRenderer, demoteHeadings, extractCodeBlocks, renderToHtml } from "./markdown_renderer.js";-import { DEFAULT_TASK_STATES, DONE_TASK_STATE, NONE_TASK_STATE } from "./task_states.js";+import { DEFAULT_TASK_STATES, DONE_TASK_STATE, NONE_TASK_STATE, type TaskStateDef } from "./task_states.js";/** Identity sanitizer so we can assert the raw rendered HTML. */const identity = (html: string) => html;@@ -288,9 +288,10 @@ describe("renderToHtml", () => {});describe("custom task states", () => {- it("recognizes a custom [/] marker as a 'doing' task", () => {+ it("recognizes a custom [/] marker as a 'doing' task and titles the <li> with the state's human name", () => {const html = render("- [/] x", "", { taskStates: DEFAULT_TASK_STATES });expect(html).toContain('data-trilium-task-state="doing"');+ expect(html).toContain('title="Doing"');expect(html).toContain('<input type="checkbox"disabled="disabled">');expect(html).toContain('<span class="todo-list__label__description">x</span>');// The `[/]` marker must be stripped from the visible text.@@ -300,15 +301,64 @@ describe("renderToHtml", () => {it("recognizes a custom [?] (maybe) marker", () => {const html = render("- [?] m", "", { taskStates: DEFAULT_TASK_STATES });expect(html).toContain('data-trilium-task-state="maybe"');+ expect(html).toContain('title="Maybe"');expect(html).toContain('<span class="todo-list__label__description">m</span>');});it("recognizes a custom [-] (cancelled) marker", () => {const html = render("- [-] c", "", { taskStates: DEFAULT_TASK_STATES });expect(html).toContain('data-trilium-task-state="cancelled"');+ expect(html).toContain('title="Cancelled"');expect(html).toContain('<span class="todo-list__label__description">c</span>');});+ it("emits no title attribute for the anchor states (native unchecked and checked)", () => {+ // Native `[ ]` and `[x]` never carry `data-trilium-task-state` and must not+ // carry a `title` either — the checkbox alone explains them.+ const unchecked = render("- [ ] u", "", { taskStates: DEFAULT_TASK_STATES });+ expect(unchecked).not.toContain(" title=");+ const checked = render("- [x] c", "", { taskStates: DEFAULT_TASK_STATES });+ expect(checked).not.toContain(" title=");+ });++ it("emits no title attribute for a state name the config doesn't define", () => {+ // "shipped" is unreachable from the default markdown symbols, but a+ // caller can still ask for it through an alternative `taskStates` list+ // that doesn't include it. Ensure the renderer skips the title lookup+ // rather than emitting `title="undefined"` or crashing.+ const customStates: TaskStateDef[] = [+ { id: "_shipped", name: "shipped", title: "Shipped", markdownSymbol: "!", isCompleted: true, icon: "bx bx-rocket" }+ ];+ const html = render("- [!] x", "", { taskStates: customStates });+ expect(html).toContain('title="Shipped"'); // sanity: known state IS titled+ // But re-rendering the same markdown against a config that doesn't+ // include `shipped` yields no title:+ const bareHtml = render(+ '<ul class="todo-list"><li data-trilium-task-state="shipped">…</li></ul>',+ "",+ { taskStates: [] }+ );+ expect(bareHtml).not.toContain("title=");+ });++ it("falls back to state.name when the state's title is empty", () => {+ const noTitleStates: TaskStateDef[] = [+ { id: "_bare", name: "bare", title: "", markdownSymbol: "b", isCompleted: false, icon: "bx bx-x" }+ ];+ const html = render("- [b] x", "", { taskStates: noTitleStates });+ expect(html).toContain('data-trilium-task-state="bare"');+ expect(html).toContain('title="bare"'); // fell back to name+ });++ it("HTML-escapes the state title (no XSS from a malicious config)", () => {+ const evilStates: TaskStateDef[] = [+ { id: "_x", name: "xss", title: '<script>alert(1)</script>', markdownSymbol: "!", isCompleted: false, icon: "bx bx-x" }+ ];+ const html = render("- [!] x", "", { taskStates: evilStates });+ expect(html).not.toContain("<script>");+ expect(html).toContain('title="<script>alert(1)</script>"');+ });+it("strips the custom marker across nested tokens for a loose item", () => {const html = render("- [/] x\n\n more text\n\n- [x] b", "", { taskStates: DEFAULT_TASK_STATES });expect(html).toContain('data-trilium-task-state="doing"');diff --git a/packages/commons/src/lib/markdown_renderer.ts b/packages/commons/src/lib/markdown_renderer.tsindex 7fde311f74..e1ad43a64b 100644--- a/packages/commons/src/lib/markdown_renderer.ts+++ b/packages/commons/src/lib/markdown_renderer.ts@@ -383,9 +383,21 @@ export class CustomMarkdownRenderer extends Renderer {/** Whether to recognise Obsidian's extended callout types, inline titles and fold markers. */readonly #obsidianCallouts: boolean;- constructor(options?: MarkedOptions & { obsidianCallouts?: boolean }) {+ /**+ * Configured state name → definition. Consulted by {@link listitem} to attach+ * the state's `title` (human-readable name) as an HTML `title` attribute on+ * the emitted `<li>`, matching the CKEditor data downcast — so shared,+ * read-only and exported HTML all show the same native tooltip on the+ * task item ("Doing", "Cancelled", …) when hovered.+ */+ readonly #stateByName: Map<string, TaskStateDef>;++ constructor(options?: MarkedOptions & { obsidianCallouts?: boolean; taskStates?: TaskStateDef[] }) {super(options);this.#obsidianCallouts = options?.obsidianCallouts ?? false;+ this.#stateByName = new Map(+ (options?.taskStates ?? DEFAULT_TASK_STATES).map((state) => [state.name, state])+ );}override heading(data: Tokens.Heading): string {@@ -433,6 +445,13 @@ export class CustomMarkdownRenderer extends Renderer {if (item.task) {const taskState = (item as TaskListItem)._taskState;const dataAttr = taskState ? ` data-trilium-task-state="${taskState}"` : "";+ // Native hover tooltip on the `<li>` — matches the CKEditor data+ // downcast, so shared / read-only / exported HTML all surface the+ // state's human-readable title when the task item is hovered.+ // Skipped when the state has no definition in the current config.+ const stateDef = taskState ? this.#stateByName.get(taskState) : undefined;+ const titleText = stateDef?.title || stateDef?.name;+ const titleAttr = titleText ? ` title="${escapeHtml(titleText)}"` : "";let itemBody = "";const checkbox = this.checkbox({ checked: !!item.checked, raw: "- [ ]", type: "checkbox" });if (item.loose) {@@ -455,7 +474,7 @@ export class CustomMarkdownRenderer extends Renderer {}itemBody += `<span class="todo-list__label__description">${this.parser.parse(item.tokens.filter((t) => t.type !== "checkbox"))}</span>`;- return `<li${dataAttr}><label class="todo-list__label">${itemBody}</label></li>`;+ return `<li${dataAttr}${titleAttr}><label class="todo-list__label">${itemBody}</label></li>`;}return super.listitem(item).trimEnd();@@ -568,7 +587,11 @@ export function renderToHtml(content: string, title: string, options: RenderToHt}marked.use({ extensions });- const renderer = options.renderer ?? new CustomMarkdownRenderer({ async: false, obsidianCallouts: options.obsidian });+ const renderer = options.renderer ?? new CustomMarkdownRenderer({+ async: false,+ obsidianCallouts: options.obsidian,+ taskStates: options.taskStates+ });let html = marked.parse(processedText, { async: false, renderer }) as string;html = restoreFromMap(html, formulaMap);