Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor/custom task states: indicate the name of the current state in the editor tooltip

Adorian Doran04022c9cffdd
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.css
index 67646713b8..7987852099 100644
--- a/apps/client/src/stylesheets/style.css
+++ b/apps/client/src/stylesheets/style.css
@@ -2916,6 +2916,26 @@ iframe.print-iframe {
height: var(--_checkbox-size);
}
+/* Inline-block slot for using .tn-task-checkbox inside flowing text (e.g. the
+ task-state line in the checkbox tooltip). Without a block-formatting
+ ancestor the inner span is inline and its ::before / ::after collapse to
+ zero size, showing only the glyph. */
+.tn-task-checkbox-inline {
+ display: inline-block;
+ margin-inline-start: 8px;
+ vertical-align: middle;
+ line-height: 0;
+}
+
+.tn-task-checkbox-inline > .tn-task-checkbox {
+ /* Scale the checkbox (and, via `calc(var(--_checkbox-size) * ratio)`,
+ its glyph) to the surrounding text size so it fits the tooltip line
+ instead of forcing the default 18px. */
+ --_checkbox-size: 1.1em;
+ display: block;
+ transform: translateY(-0.05em);
+}
+
/* Prevent variables from bleeding into nested items */
.ck-content .todo-list .todo-list {
--task-state-glyph: initial;
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index f85b6b101b..a75792016c 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3123,6 +3123,8 @@
},
"text-editor": {
"checkbox-tooltip": "Right click for more task states.\nPress {{shortcut}} to cycle between states.",
+ "checkbox-tooltip-state-label": "Task state:",
+ "checkbox-tooltip-state-unknown-suffix": "(missing definition)",
"collapsible-body-placeholder": "Type the content here...",
"collapsible-button-label": "Collapsible block",
"collapsible-handle-tooltip": "Drag to reposition the collapsible block",
diff --git a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_editing.spec.ts b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_editing.spec.ts
index 97547be7b1..1d14615fde 100644
--- a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_editing.spec.ts
+++ b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_editing.spec.ts
@@ -42,6 +42,27 @@ function pressCtrlShiftEnter(editor: ClassicEditor): void {
});
}
+/**
+ * The title string handed to Bootstrap Tooltip at construction time. Reading
+ * the private `_config.title` is stable in Bootstrap 5 and lets specs inspect
+ * the assembled HTML without triggering `show()`.
+ */
+function readTooltipTitle(editor: ClassicEditor): string {
+ const input = editor.editing.view.getDomRoot()?.querySelector<HTMLInputElement>('.todo-list__label input[type="checkbox"]');
+ if (!input) {
+ throw new Error("No todo checkbox found in the editing view.");
+ }
+ const tooltip = Tooltip.getInstance(input);
+ if (!tooltip) {
+ throw new Error("No Bootstrap tooltip on the todo checkbox.");
+ }
+ const title = (tooltip as unknown as { _config: { title: string } })._config.title;
+ if (typeof title !== "string") {
+ throw new Error("Tooltip title is not a string.");
+ }
+ return title;
+}
+
describe("TodoListMultistateEditing", () => {
let editor: ClassicEditor;
@@ -444,5 +465,86 @@ describe("TodoListMultistateEditing", () => {
expect(Tooltip.getInstance(currentInput)).not.toBeNull();
}
});
+
+ it("prepends the state prefix to the tooltip title when a configured state is set", () => {
+ translate.mockClear();
+ editor.execute("setTaskState", { state: "doing" });
+ expect(translate).toHaveBeenCalledWith("text-editor.checkbox-tooltip-state-label");
+ const title = readTooltipTitle(editor);
+ expect(title).toContain("<strong>Doing</strong>"); // state.title takes precedence
+ expect(title).toContain('data-trilium-task-state="doing"');
+ });
+
+ it("falls back to state.name in the state prefix when the title is empty", async () => {
+ // Rebuild the editor with a state whose title is missing so the `state.title || state.name` fallback fires.
+ await editor.destroy();
+ const noTitleStates: TaskStateDef[] = [
+ { id: "_bare", name: "bare", title: "", markdownSymbol: "b", isCompleted: false, icon: "bx bx-x" }
+ ];
+ editor = await createEditor({ taskStates: noTitleStates, translate });
+ setModelData(editor.model, TODO_FIXTURE);
+
+ editor.execute("setTaskState", { state: "bare" });
+ const title = readTooltipTitle(editor);
+ expect(title).toContain("<strong>bare</strong>");
+ });
+
+ it("uses the unknown-state suffix translation when the state has no definition", () => {
+ translate.mockClear();
+ editor.model.change((writer) => {
+ writer.setAttribute(TASK_STATE_ATTRIBUTE, "ghost", getBlock(editor, 0));
+ });
+ expect(translate).toHaveBeenCalledWith("text-editor.checkbox-tooltip-state-label");
+ expect(translate).toHaveBeenCalledWith("text-editor.checkbox-tooltip-state-unknown-suffix");
+ const title = readTooltipTitle(editor);
+ // The state name is inlined as text (no bold, no icon) followed by the translated suffix.
+ expect(title).toContain("ghost");
+ expect(title).not.toContain('data-trilium-task-state="ghost"');
+ });
+
+ it("omits the state prefix entirely for anchor states (unchecked / checked)", () => {
+ // Starting fixture has no taskState → anchor. Re-render explicitly and assert
+ // neither state-prefix key was consulted.
+ translate.mockClear();
+ editor.editing.view.forceRender();
+ expect(translate).not.toHaveBeenCalledWith("text-editor.checkbox-tooltip-state-label");
+ expect(translate).not.toHaveBeenCalledWith("text-editor.checkbox-tooltip-state-unknown-suffix");
+ });
+
+ it("refreshes the tooltip when only the state changes (the checkbox itself is not recreated)", () => {
+ const input = editor.editing.view.getDomRoot()?.querySelector<HTMLInputElement>('.todo-list__label input[type="checkbox"]');
+ expect(input).not.toBeNull();
+ const originalTooltip = input ? Tooltip.getInstance(input) : null;
+ expect(originalTooltip).not.toBeNull();
+ const disposeSpy = originalTooltip ? vi.spyOn(originalTooltip, "dispose") : null;
+
+ // 'doing' has isCompleted=false; the native checkbox stays unchecked, so the
+ // itemMarker downcast does NOT recreate the input element. The tooltip must
+ // still refresh to pick up the new state prefix.
+ editor.execute("setTaskState", { state: "doing" });
+
+ if (input) {
+ expect(input.isConnected).toBe(true);
+ const refreshed = Tooltip.getInstance(input);
+ expect(refreshed).not.toBeNull();
+ expect(refreshed).not.toBe(originalTooltip);
+ }
+ if (disposeSpy) {
+ expect(disposeSpy).toHaveBeenCalled();
+ }
+ });
+
+ it("keeps the same tooltip instance when a render fires without any state change", () => {
+ const input = editor.editing.view.getDomRoot()?.querySelector<HTMLInputElement>('.todo-list__label input[type="checkbox"]');
+ expect(input).not.toBeNull();
+ const before = input ? Tooltip.getInstance(input) : null;
+ expect(before).not.toBeNull();
+
+ editor.editing.view.forceRender();
+
+ if (input) {
+ expect(Tooltip.getInstance(input)).toBe(before);
+ }
+ });
});
});
diff --git a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_editing.ts b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_editing.ts
index 638e5f51c9..9500591e55 100644
--- a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_editing.ts
+++ b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_editing.ts
@@ -30,8 +30,12 @@ export default class TodoListMultistateEditing extends Plugin {
return [TodoList, ListEditing] as const;
}
- /** Checkboxes that currently have a tooltip attached, so stale ones can be disposed. */
- private readonly _checkboxTooltips = new Set<HTMLInputElement>();
+ /**
+ * Checkboxes that currently have a tooltip attached, mapped to the task state
+ * baked into their tooltip title. Used to dispose stale tooltips on detached
+ * checkboxes AND to refresh a tooltip when its checkbox's state changes.
+ */
+ private readonly _checkboxTooltips = new Map<HTMLInputElement, string | null>();
init() {
const editor = this.editor;
@@ -102,20 +106,32 @@ export default class TodoListMultistateEditing extends Plugin {
}
// CKEditor recreates the checkbox element when a todo item reconverts
// (e.g. on click); dispose tooltips left on the detached old checkboxes.
- for (const input of this._checkboxTooltips) {
+ for (const input of this._checkboxTooltips.keys()) {
if (!input.isConnected) {
Tooltip.getInstance(input)?.dispose();
this._checkboxTooltips.delete(input);
}
}
for (const input of domRoot.querySelectorAll<HTMLInputElement>(".todo-list__label input[type=\"checkbox\"]")) {
- if (!Tooltip.getInstance(input)) {
- const title = translate("text-editor.checkbox-tooltip", {
- shortcut: getEnvKeystrokeText("Ctrl+Shift+Enter")
- });
- new Tooltip(input, {title, customClass: "text-editor-content-tooltip"});
- this._checkboxTooltips.add(input);
+ const currentState = readTaskState(input);
+ // Skip if the tooltip is already up to date for this state.
+ if (Tooltip.getInstance(input) && this._checkboxTooltips.get(input) === currentState) {
+ continue;
}
+ Tooltip.getInstance(input)?.dispose();
+ const title = buildTooltipTitle(input, currentState, stateByName, translate);
+ new Tooltip(input, {
+ title,
+ html: true,
+ // Bootstrap's default sanitizer strips `data-*` attributes, which
+ // the tooltip's state-icon span relies on to render the correct
+ // colour/glyph. The HTML is built from translations we control
+ // (with user values interpolated through i18next's default
+ // escaping) so disabling the sanitizer is safe here.
+ sanitize: false,
+ customClass: "text-editor-content-tooltip"
+ });
+ this._checkboxTooltips.set(input, currentState);
}
});
@@ -186,7 +202,7 @@ export default class TodoListMultistateEditing extends Plugin {
}
override destroy() {
- for (const input of this._checkboxTooltips) {
+ for (const input of this._checkboxTooltips.keys()) {
Tooltip.getInstance(input)?.dispose();
}
this._checkboxTooltips.clear();
@@ -195,6 +211,85 @@ export default class TodoListMultistateEditing extends Plugin {
}
+type TranslateFn = (key: string, params?: Record<string, unknown>) => string;
+
+/**
+ * The task state applied to the todo item that owns the given checkbox. Anchor
+ * states (`none`/`done`) never carry a `data-trilium-task-state`, so this
+ * returns `null` for them.
+ */
+function readTaskState(input: HTMLInputElement): string | null {
+ const li = input.closest<HTMLElement>("li[data-trilium-task-state]");
+ return li?.getAttribute("data-trilium-task-state") ?? null;
+}
+
+/**
+ * Build the checkbox tooltip HTML. The base body (right-click hint + keyboard
+ * shortcut) is always present. For a non-anchor state, a "Task state: …" line
+ * is prepended. The state-line HTML is assembled here via the DOM API rather
+ * than in the translation, so translations stay plain text.
+ * - configured state → the state's own checkbox glyph + bold name;
+ * - unknown state (attribute set but no matching definition) → the raw name
+ * followed by a translated "(missing definition)" note.
+ */
+function buildTooltipTitle(
+ input: HTMLInputElement,
+ state: string | null,
+ stateByName: Map<string, TaskStateDef>,
+ translate: TranslateFn
+): string {
+ const body = translate("text-editor.checkbox-tooltip", {
+ shortcut: getEnvKeystrokeText("Ctrl+Shift+Enter")
+ }).replace(/\n/g, "<br>");
+ if (!state) {
+ return body;
+ }
+ const stateDef = stateByName.get(state);
+ const suffix = stateDef
+ ? buildKnownStateSuffixHtml(input.ownerDocument, state, stateDef.title || stateDef.name)
+ : buildUnknownStateSuffixHtml(
+ input.ownerDocument,
+ state,
+ translate("text-editor.checkbox-tooltip-state-unknown-suffix")
+ );
+ const label = translate("text-editor.checkbox-tooltip-state-label");
+ return `${label} ${suffix}<br><br>${body}`;
+}
+
+/**
+ * "<mini-checkbox> <strong>Name</strong>" — the icon and name flow inline
+ * after the "Task state:" label. Built via the DOM API so the state name
+ * is text-escaped by the browser rather than by hand.
+ */
+function buildKnownStateSuffixHtml(doc: Document, state: string, name: string): string {
+ const strong = doc.createElement("strong");
+ strong.textContent = name;
+ return `${buildStateIconElement(doc, state).outerHTML} ${strong.outerHTML}`;
+}
+
+/** "wontdo (missing definition)" — text-escaped via textContent. */
+function buildUnknownStateSuffixHtml(doc: Document, state: string, missingSuffix: string): string {
+ const span = doc.createElement("span");
+ span.textContent = `${state} ${missingSuffix}`;
+ return span.outerHTML;
+}
+
+/**
+ * A miniature checkbox glyph the tooltip can inline. `.tn-task-checkbox` provides
+ * the box + glyph rendering but needs an inline-block context (the class itself
+ * carries only width/height/position). The `.tn-task-checkbox-inline` wrapper
+ * gives it that slot so it renders correctly inside a text tooltip.
+ */
+function buildStateIconElement(doc: Document, state: string): HTMLSpanElement {
+ const wrapper = doc.createElement("span");
+ wrapper.className = "tn-task-checkbox-inline";
+ const inner = doc.createElement("span");
+ inner.className = "tn-task-checkbox";
+ inner.setAttribute("data-trilium-task-state", state);
+ wrapper.appendChild(inner);
+ return wrapper;
+}
+
class SetTaskStateCommand extends Command {
declare public value: string | null;