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
feat(text editor/task states): autoformat custom task-state markers
Elian Doranb009d419b065
diff --git a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate.spec.ts b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate.spec.tsindex 86e8986d0d..1f65ad796b 100644--- a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate.spec.ts+++ b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate.spec.ts@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it } from "vitest";import { createTestEditor } from "../../../test/editor-kit.js";import TodoListMultistate from "./todo_list_multistate.js";+import TodoListMultistateAutoformat from "./todo_list_multistate_autoformat.js";import TodoListMultistateEditing from "./todo_list_multistate_editing.js";import TodoListMultistateToolbar from "./todo_list_multistate_toolbar.js";import TodoListMultistateUI from "./todo_list_multistate_ui.js";@@ -18,16 +19,18 @@ describe("TodoListMultistate", () => {expect(editor.plugins.get(TodoListMultistate)).toBeInstanceOf(TodoListMultistate);});- it("requires the three sub-plugins", () => {+ it("requires the sub-plugins", () => {const requires = TodoListMultistate.requires;expect(requires).toContain(TodoListMultistateEditing);expect(requires).toContain(TodoListMultistateUI);expect(requires).toContain(TodoListMultistateToolbar);+ expect(requires).toContain(TodoListMultistateAutoformat);});- it("loads all three sub-plugins via the editor", () => {+ it("loads all sub-plugins via the editor", () => {expect(editor.plugins.get(TodoListMultistateEditing)).toBeInstanceOf(TodoListMultistateEditing);expect(editor.plugins.get(TodoListMultistateUI)).toBeInstanceOf(TodoListMultistateUI);expect(editor.plugins.get(TodoListMultistateToolbar)).toBeInstanceOf(TodoListMultistateToolbar);+ expect(editor.plugins.get(TodoListMultistateAutoformat)).toBeInstanceOf(TodoListMultistateAutoformat);});});diff --git a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate.ts b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate.tsindex 04a65ec4e2..f3ef693ca9 100644--- a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate.ts+++ b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate.ts@@ -1,4 +1,5 @@import { Plugin } from "ckeditor5";+import TodoListMultistateAutoformat from "./todo_list_multistate_autoformat.js";import TodoListMultistateEditing from "./todo_list_multistate_editing.js";import TodoListMultistateToolbar from "./todo_list_multistate_toolbar.js";import TodoListMultistateUI from "./todo_list_multistate_ui.js";@@ -6,7 +7,7 @@ import TodoListMultistateUI from "./todo_list_multistate_ui.js";export default class TodoListMultistate extends Plugin {static get requires() {- return [TodoListMultistateEditing, TodoListMultistateUI, TodoListMultistateToolbar] as const;+ return [TodoListMultistateEditing, TodoListMultistateUI, TodoListMultistateToolbar, TodoListMultistateAutoformat] as const;}}diff --git a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_autoformat.spec.ts b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_autoformat.spec.tsnew file mode 100644index 0000000000..0feb831082--- /dev/null+++ b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_autoformat.spec.ts@@ -0,0 +1,106 @@+import { type TaskStateDef } from "@triliumnext/commons";+import { Autoformat, ClassicEditor, Essentials, List, Paragraph, TodoList, type ModelElement } from "ckeditor5";+import { beforeEach, describe, expect, it } from "vitest";++import { createTestEditor } from "../../../test/editor-kit.js";+import TodoListMultistateAutoformat from "./todo_list_multistate_autoformat.js";+import TodoListMultistateEditing, { TASK_STATE_ATTRIBUTE } from "./todo_list_multistate_editing.js";++const TODO_LIST_CHECKED_ATTRIBUTE = "todoListChecked";++async function createEditor(config: Record<string, unknown> = {}): Promise<ClassicEditor> {+ return await createTestEditor(+ [Essentials, Paragraph, List, TodoList, Autoformat, TodoListMultistateEditing, TodoListMultistateAutoformat],+ config+ );+}++/** Type `text` into the editor one character at a time, as real typing (and thus autoformat) would. */+function type(editor: ClassicEditor, text: string): void {+ for (const ch of text) {+ editor.execute("insertText", { text: ch });+ }+}++function getBlock(editor: ClassicEditor, index: number): ModelElement {+ const child = editor.model.document.getRoot()?.getChild(index);+ if (!child || !child.is("element")) {+ throw new Error(`No element block at index ${index}.`);+ }+ return child;+}++describe("TodoListMultistateAutoformat", () => {+ let editor: ClassicEditor;++ describe("with the default states", () => {+ beforeEach(async () => {+ editor = await createEditor();+ });++ it("loads the plugin", () => {+ expect(editor.plugins.get(TodoListMultistateAutoformat)).toBeInstanceOf(TodoListMultistateAutoformat);+ });++ it("turns `[/] ` into a todo item in the 'doing' state", () => {+ type(editor, "[/] ");+ const block = getBlock(editor, 0);+ expect(block.getAttribute("listType")).toBe("todo");+ expect(block.getAttribute(TASK_STATE_ATTRIBUTE)).toBe("doing");+ // "doing" is not a completed state, so the box stays unchecked.+ expect(block.getAttribute(TODO_LIST_CHECKED_ATTRIBUTE)).toBeFalsy();+ // The trigger text is consumed, leaving an empty task.+ expect(block.isEmpty).toBe(true);+ });++ it("turns `[-] ` into a todo item in the 'cancelled' state", () => {+ type(editor, "[-] ");+ const block = getBlock(editor, 0);+ expect(block.getAttribute("listType")).toBe("todo");+ expect(block.getAttribute(TASK_STATE_ATTRIBUTE)).toBe("cancelled");+ });++ it("escapes regex-metacharacter markers — `[?] ` becomes the 'maybe' state", () => {+ type(editor, "[?] ");+ const block = getBlock(editor, 0);+ expect(block.getAttribute("listType")).toBe("todo");+ expect(block.getAttribute(TASK_STATE_ATTRIBUTE)).toBe("maybe");+ });++ it("leaves the native `[ ]` / `[x]` markers to upstream (no custom state attached)", () => {+ type(editor, "[x] ");+ const block = getBlock(editor, 0);+ expect(block.getAttribute("listType")).toBe("todo");+ expect(block.hasAttribute(TASK_STATE_ATTRIBUTE)).toBe(false);+ expect(block.getAttribute(TODO_LIST_CHECKED_ATTRIBUTE)).toBe(true);+ });+ });++ describe("with custom states", () => {+ // A metacharacter marker (`*`) exercises escaping; a non-anchor state with no marker+ // exercises the skip branch; a hidden state must not get an autoformat rule.+ const CUSTOM_STATES: TaskStateDef[] = [+ { id: "_wip", name: "wip", title: "WIP", markdownSymbol: "*", isCompleted: false, icon: "bx bx-loader" },+ { id: "_nomark", name: "nomark", title: "No marker", markdownSymbol: "", isCompleted: false, icon: "bx bx-question-mark" },+ { id: "_hidden", name: "secret", title: "Secret", markdownSymbol: "h", isCompleted: false, icon: "bx bx-hide", isHidden: true }+ ];++ beforeEach(async () => {+ editor = await createEditor({ taskStates: CUSTOM_STATES });+ });++ it("autoformats a configured marker into its state", () => {+ type(editor, "[*] ");+ const block = getBlock(editor, 0);+ expect(block.getAttribute("listType")).toBe("todo");+ expect(block.getAttribute(TASK_STATE_ATTRIBUTE)).toBe("wip");+ });++ it("does not register a rule for a hidden state's marker", () => {+ type(editor, "[h] ");+ const block = getBlock(editor, 0);+ // No rule fired: still a plain paragraph carrying the literally typed text.+ expect(block.getAttribute("listType")).toBeUndefined();+ });+ });+});diff --git a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_autoformat.ts b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_autoformat.tsnew file mode 100644index 0000000000..0f45159bc0--- /dev/null+++ b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_autoformat.ts@@ -0,0 +1,57 @@+import { isAnchorState } from "@triliumnext/commons";+import { Autoformat, blockAutoformatEditing, Plugin, TodoList } from "ckeditor5";++import TodoListMultistateEditing, { getActiveTaskStates } from "./todo_list_multistate_editing.js";++/**+ * Keyboard autoformatting for the custom task states.+ *+ * Upstream CKEditor's `Autoformat` only knows the two native markers — typing+ * `[ ]` / `[x]` on an empty paragraph turns it into an unchecked / checked todo+ * item. This plugin extends that to every configured non-anchor state: typing+ * its markdown marker (e.g. `[/]` for "doing", `[-]` for "cancelled") converts+ * the paragraph into a todo item already carrying that state, mirroring how the+ * marker round-trips through markdown import/export. See+ * {@link https://github.com/TriliumNext/Trilium/issues/10556}.+ *+ * Each rule runs the native `todoList` command (paragraph → todo item) and then+ * `setTaskState`, matching the upstream `[x]` rule that chains `todoList` ++ * `checkTodoList`.+ */+export default class TodoListMultistateAutoformat extends Plugin {++ static get requires() {+ // Autoformat: the engine this hooks into. TodoList: the `todoList` command the+ // rules run. TodoListMultistateEditing: the `setTaskState` command and the+ // configured state list this reads.+ return [Autoformat, TodoList, TodoListMultistateEditing] as const;+ }++ afterInit() {+ const editor = this.editor;+ const autoformat = editor.plugins.get(Autoformat);++ for (const state of getActiveTaskStates(editor)) {+ // Anchor states (`none`/`done`) map to `[ ]`/`[x]`, already handled by+ // upstream — registering them here would double-fire. States without a+ // marker have nothing to trigger on.+ if (isAnchorState(state.name) || !state.markdownSymbol) {+ continue;+ }++ // `^\[\s?<marker>\s?\]\s$` — same optional-inner-space shape as upstream's+ // `[x]` rule, closed by the trailing space that completes the trigger.+ const pattern = new RegExp(`^\\[\\s?${escapeRegExp(state.markdownSymbol)}\\s?\\]\\s$`);+ blockAutoformatEditing(editor, autoformat, pattern, () => {+ editor.execute("todoList");+ editor.execute("setTaskState", { state: state.name });+ });+ }+ }++}++/** Escape a single marker character so regex metacharacters (e.g. `?`, `-`, `/`) match literally. */+function escapeRegExp(value: string): string {+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}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.tsindex efec714f14..350b361df7 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@@ -593,6 +593,15 @@ class SetTaskStateCommand extends Command {declare public value: string | null;+ constructor(editor: Editor) {+ super(editor);+ // Refresh before executing so a call made inside the same change block — e.g. the+ // autoformat callback that runs `todoList` and then `setTaskState` back to back —+ // sees the freshly-converted todo item rather than the stale pre-change `isEnabled`+ // (a disabled command's `execute` is a no-op). Mirrors upstream `CheckTodoListCommand`.+ this.on("execute", () => this.refresh(), { priority: "highest" });+ }+refresh() {const block = this._getTodoBlock();this.isEnabled = !!block;