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
text editor/checkboxes: allow customizing the states
Adorian Doran981435899900
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.cssindex 3f67a166d7..26e4316041 100644--- a/apps/client/src/stylesheets/style.css+++ b/apps/client/src/stylesheets/style.css@@ -2549,10 +2549,6 @@ footer.webview-footer button {background-color: rgba(255, 200, 100, 0.25);}-.ck-content ul.todo-list > li[data-task-state="done"] {- background-color: rgba(130, 220, 130, 0.25);-}-.ck-content ul.todo-list > li[data-task-state="cancelled"] {background-color: rgba(180, 180, 180, 0.25);}diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex c54dbc09c2..3fa32486d1 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -1,7 +1,8 @@import { buildExtraCommands, type EditorConfig, getCkLocale, loadPremiumPlugins, TemplateDefinition } from "@triliumnext/ckeditor5";import emojiDefinitionsUrl from "@triliumnext/ckeditor5/src/emoji_definitions/en.json?url";-import { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";+import { ALLOWED_PROTOCOLS, DEFAULT_TASK_STATES, DISPLAYABLE_LOCALE_IDS, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor, type TaskStateDef } from "@triliumnext/commons";+import froca from "../../../services/froca.js";import { copyTextWithToast } from "../../../services/clipboard_ext.js";import { t } from "../../../services/i18n.js";import { getMermaidConfig } from "../../../services/mermaid.js";@@ -174,6 +175,9 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi...await getCkLocale(opts.uiLanguage)};+ // User-configurable todo task states (from the `_taskStates` hidden subtree).+ (config as Record<string, unknown>).taskStates = await fetchTaskStates();+// Set up content language.const { contentLanguage } = opts;if (contentLanguage) {@@ -226,6 +230,26 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi};}+async function fetchTaskStates(): Promise<TaskStateDef[]> {+ const container = await froca.getNote("_taskStates");+ if (!container) {+ return DEFAULT_TASK_STATES;+ }++ const states = (await container.getChildNotes())+ .map((note): TaskStateDef => ({+ name: note.getLabelValue("stateName") ?? "",+ title: note.title,+ markdownSymbol: note.getLabelValue("markdownSymbol") ?? "",+ checkboxValue: note.getLabelValue("checkboxValue") === "true",+ color: note.getLabelValue("color") ?? "",+ icon: note.getLabelValue("iconClass") ?? ""+ }))+ .filter((state) => state.name);++ return states.length ? states : DEFAULT_TASK_STATES;+}+function buildListOfLanguages() {const userLanguages = mimeTypesService.getMimeTypes()diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.jsonindex 09ac479360..02fd7656d9 100644--- a/apps/server/src/assets/translations/en/server.json+++ b/apps/server/src/assets/translations/en/server.json@@ -278,6 +278,10 @@"llm-chat-history-title": "AI Chat History","shared-notes-title": "Shared Notes","bulk-action-title": "Bulk Action",+ "task-states-title": "Task States",+ "task-state-doing": "Doing",+ "task-state-maybe": "Maybe",+ "task-state-cancelled": "Cancelled","backend-log-title": "Backend Log","custom-dictionary-title": "Custom Dictionary","user-hidden-title": "User Hidden",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 eec12cc285..7d088c5dbc 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@@ -1,20 +1,17 @@+import { DEFAULT_TASK_STATES, type TaskStateDef } from "@triliumnext/commons";import { Tooltip } from "bootstrap";-import { Command, ListEditing, Plugin, TodoList, type ModelElement, type ViewElement } from "ckeditor5";+import { Command, ListEditing, Plugin, TodoList, type Editor, type ModelElement, type ViewElement } from "ckeditor5";-export const TASK_STATES = ["none", "doing", "done", "maybe", "cancelled"] as const;-export type TaskState = typeof TASK_STATES[number];export const TASK_STATE_ATTRIBUTE = "taskState";const TODO_LIST_CHECKED_ATTRIBUTE = "todoListChecked";-function normaliseState(value: unknown): TaskState | null {- if (typeof value !== "string") {- return null;- }- const v = value.trim().toLowerCase();- if (v === "none") {- return null;- }- return (TASK_STATES as readonly string[]).includes(v) ? (v as TaskState) : null;+/**+ * The configured non-binary task states. `none` (unchecked) and `done` (checked)+ * are CKEditor's native checkbox behaviour and are not part of this list.+ */+export function getConfiguredTaskStates(editor: Editor): TaskStateDef[] {+ const states = editor.config.get("taskStates") as TaskStateDef[] | undefined;+ return states && states.length ? states : DEFAULT_TASK_STATES;}export default class TodoListMultistateEditing extends Plugin {@@ -25,6 +22,8 @@ export default class TodoListMultistateEditing extends Plugin {init() {const editor = this.editor;+ const states = getConfiguredTaskStates(editor);+ const stateByName = new Map(states.map((state) => [state.name, state]));editor.model.schema.extend("$block", {allowAttributes: TASK_STATE_ATTRIBUTE});@@ -35,9 +34,10 @@ export default class TodoListMultistateEditing extends Plugin {if (!command?.isEnabled) {return;}- const current = (command.value as TaskState | null) ?? "none";- const idx = TASK_STATES.indexOf(current);- const next = TASK_STATES[(idx + 1) % TASK_STATES.length];+ const cycle: (string | null)[] = [null, ...states.map((state) => state.name)];+ const current = (command.value as string | null) ?? null;+ const idx = cycle.indexOf(current);+ const next = cycle[(idx + 1) % cycle.length];editor.execute("setTaskState", {state: next});cancel();});@@ -47,9 +47,8 @@ export default class TodoListMultistateEditing extends Plugin {scope: "item",attributeName: TASK_STATE_ATTRIBUTE,setAttributeOnDowncast(writer, value, element) {- const state = normaliseState(value);- if (state) {- writer.setAttribute("data-task-state", state, element);+ if (typeof value === "string" && stateByName.has(value)) {+ writer.setAttribute("data-task-state", value, element);} else {writer.removeAttribute("data-task-state", element);}@@ -60,7 +59,10 @@ export default class TodoListMultistateEditing extends Plugin {view: {key: "data-task-state"},model: {key: TASK_STATE_ATTRIBUTE,- value: (viewElement: ViewElement) => normaliseState(viewElement.getAttribute("data-task-state"))+ value: (viewElement: ViewElement) => {+ const value = viewElement.getAttribute("data-task-state");+ return typeof value === "string" && stateByName.has(value) ? value : null;+ }}});@@ -101,24 +103,26 @@ export default class TodoListMultistateEditing extends Plugin {let changed = false;+ // A configured state forces the checkbox to its `checkboxValue`.for (const el of stateChanged) {- const shouldBeChecked = el.getAttribute(TASK_STATE_ATTRIBUTE) === "done";- if (!!el.getAttribute(TODO_LIST_CHECKED_ATTRIBUTE) !== shouldBeChecked) {- writer.setAttribute(TODO_LIST_CHECKED_ATTRIBUTE, shouldBeChecked, el);+ const stateName = el.getAttribute(TASK_STATE_ATTRIBUTE);+ const state = typeof stateName === "string" ? stateByName.get(stateName) : undefined;+ if (!state) {+ // State cleared — leave the native checkbox (none/done) untouched.+ continue;+ }+ if (!!el.getAttribute(TODO_LIST_CHECKED_ATTRIBUTE) !== state.checkboxValue) {+ writer.setAttribute(TODO_LIST_CHECKED_ATTRIBUTE, state.checkboxValue, el);changed = true;}}+ // Toggling the native checkbox drops any special state (back to native none/done).for (const el of checkedChanged) {if (stateChanged.has(el)) {continue;}- const checked = !!el.getAttribute(TODO_LIST_CHECKED_ATTRIBUTE);- const state = el.getAttribute(TASK_STATE_ATTRIBUTE);- if (checked && state !== "done") {- writer.setAttribute(TASK_STATE_ATTRIBUTE, "done", el);- changed = true;- } else if (!checked && state === "done") {+ if (el.getAttribute(TASK_STATE_ATTRIBUTE) !== undefined) {writer.removeAttribute(TASK_STATE_ATTRIBUTE, el);changed = true;}@@ -132,7 +136,7 @@ export default class TodoListMultistateEditing extends Plugin {class SetTaskStateCommand extends Command {- declare public value: TaskState | null;+ declare public value: string | null;refresh() {const block = this._getTodoBlock();@@ -142,12 +146,10 @@ class SetTaskStateCommand extends Command {return;}const stored = block.getAttribute(TASK_STATE_ATTRIBUTE);- this.value = typeof stored === "string" && (TASK_STATES as readonly string[]).includes(stored)- ? (stored as TaskState)- : "none";+ this.value = typeof stored === "string" ? stored : null;}- execute(options: {state: TaskState}) {+ execute(options: {state: string | null}) {const model = this.editor.model;const {state} = options;model.change((writer) => {@@ -155,7 +157,7 @@ class SetTaskStateCommand extends Command {if (block.getAttribute("listType") !== "todo") {continue;}- if (state === "none") {+ if (!state || state === "none") {writer.removeAttribute(TASK_STATE_ATTRIBUTE, block);} else {writer.setAttribute(TASK_STATE_ATTRIBUTE, state, block);diff --git a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_toolbar.ts b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_toolbar.tsindex a60bf717e8..a8279ae801 100644--- a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_toolbar.ts+++ b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_toolbar.ts@@ -8,7 +8,7 @@ import {type ModelElement,type ViewElement} from "ckeditor5";-import { TASK_STATES } from "./todo_list_multistate_editing.js";+import { getConfiguredTaskStates } from "./todo_list_multistate_editing.js";import TodoListMultistateUI from "./todo_list_multistate_ui.js";class TodoCheckboxContextMenuObserver extends DomEventObserver<"contextmenu"> {@@ -73,8 +73,9 @@ export default class TodoListMultistateToolbar extends Plugin {const editor = this.editor;const toolbar = new ToolbarView(editor.locale);toolbar.class = "task-state-toolbar";- for (const state of TASK_STATES) {- toolbar.items.add(editor.ui.componentFactory.create(`taskState:${state}`));+ toolbar.items.add(editor.ui.componentFactory.create("taskState:none"));+ for (const state of getConfiguredTaskStates(editor)) {+ toolbar.items.add(editor.ui.componentFactory.create(`taskState:${state.name}`));}return toolbar;}diff --git a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_ui.ts b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_ui.tsindex 86684077c6..df8201a18d 100644--- a/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_ui.ts+++ b/packages/ckeditor5/src/plugins/todo_list_multistate/todo_list_multistate_ui.ts@@ -1,13 +1,5 @@import { ButtonView, Plugin } from "ckeditor5";-import TodoListMultistateEditing, { TASK_STATES, type TaskState } from "./todo_list_multistate_editing.js";--const STATE_LABELS: Record<TaskState, string> = {- none: "None",- doing: "Doing",- done: "Done",- maybe: "Maybe",- cancelled: "Cancelled"-};+import TodoListMultistateEditing, { getConfiguredTaskStates } from "./todo_list_multistate_editing.js";export default class TodoListMultistateUI extends Plugin {@@ -19,20 +11,42 @@ export default class TodoListMultistateUI extends Plugin {const editor = this.editor;const command = editor.commands.get("setTaskState")!;- for (const state of TASK_STATES) {- const componentName = `taskState:${state}`;- editor.ui.componentFactory.add(componentName, (locale) => {+ // Clear button — drops back to the native none/done checkbox.+ editor.ui.componentFactory.add("taskState:none", (locale) => {+ const button = new ButtonView(locale);+ button.set({+ label: editor.t("Clear task state"),+ withText: false,+ tooltip: true,+ class: "ck-task-state-button ck-task-state-none"+ });+ button.bind("isOn").to(command, "value", (value) => value === null);+ button.bind("isEnabled").to(command, "isEnabled");+ button.on("execute", () => {+ editor.execute("setTaskState", {state: null});+ editor.editing.view.focus();+ });+ return button;+ });++ for (const state of getConfiguredTaskStates(editor)) {+ editor.ui.componentFactory.add(`taskState:${state.name}`, (locale) => {const button = new ButtonView(locale);button.set({- label: STATE_LABELS[state],+ label: state.title || state.name,withText: false,tooltip: true,- class: `ck-task-state-button ck-task-state-${state}`+ class: `ck-task-state-button ck-task-state-${state.name}`});- button.bind("isOn").to(command, "value", (value) => value === state);+ if (state.color) {+ button.extendTemplate({+ attributes: {style: `--task-state-color:${state.color}`}+ });+ }+ button.bind("isOn").to(command, "value", (value) => value === state.name);button.bind("isEnabled").to(command, "isEnabled");button.on("execute", () => {- editor.execute("setTaskState", {state: state as TaskState});+ editor.execute("setTaskState", {state: state.name});editor.editing.view.focus();});return button;diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.tsindex ebcf3ac56b..00f6566f78 100644--- a/packages/commons/src/index.ts+++ b/packages/commons/src/index.ts@@ -21,3 +21,4 @@ export * from "./lib/spreadsheet/render_to_html.js";export * from "./lib/llm_api.js";export * from "./lib/marked_extensions.js";export * from "./lib/markdown_renderer.js";+export * from "./lib/task_states.js";diff --git a/packages/commons/src/lib/markdown_renderer.ts b/packages/commons/src/lib/markdown_renderer.tsindex b92d81dadd..71e119a6da 100644--- a/packages/commons/src/lib/markdown_renderer.ts+++ b/packages/commons/src/lib/markdown_renderer.ts@@ -1,58 +1,76 @@import { Marked, Renderer, type Token, type Tokens } from "marked";import markedFootnote from "marked-footnote";-const MARKDOWN_MARKER_TO_TASK_STATE: Record<string, string> = {- "/": "doing",- "-": "cancelled",- "?": "maybe"-};-const TASK_MARKER_STRIP_PATTERN = /^\[[/?-]\]\s?/;-const TASK_MARKER_RAW_PATTERN = /^[ \t]*[-*+]\s+\[([/?-])\]\s?/;+import { DEFAULT_TASK_STATES, type TaskStateDef } from "./task_states.js";type TaskListItem = Tokens.ListItem & { _taskState?: string };-function stripTaskMarkerFromTokens(tokens: Token[] | undefined): void {+function escapeForCharClass(char: string): string {+ return char.replace(/[^\w]/g, (c) => `\\${c}`);+}++function stripTaskMarkerFromTokens(tokens: Token[] | undefined, stripPattern: RegExp): void {if (!tokens || tokens.length === 0) {return;}const first = tokens[0] as Token & { text?: string; raw?: string; tokens?: Token[] };if (typeof first.text === "string") {- first.text = first.text.replace(TASK_MARKER_STRIP_PATTERN, "");+ first.text = first.text.replace(stripPattern, "");}if (typeof first.raw === "string") {- first.raw = first.raw.replace(TASK_MARKER_STRIP_PATTERN, "");+ first.raw = first.raw.replace(stripPattern, "");}if (Array.isArray(first.tokens)) {- stripTaskMarkerFromTokens(first.tokens);+ stripTaskMarkerFromTokens(first.tokens, stripPattern);}}/**- * Marked `walkTokens` hook that recognises non-standard task markers `[/]`, `[-]`, `[?]`- * in list items (marked only understands `[x]`/`[ ]`). When found, the item is converted- * into a task item with `_taskState` carrying the corresponding state for downstream rendering.+ * Builds a marked `walkTokens` hook that recognises non-standard task markers+ * (e.g. `[/]`, `[-]`, `[?]`) derived from the configured task states — marked+ * itself only understands `[x]`/`[ ]`. A matched item is converted into a task+ * item with `_taskState` carrying the resolved state name for downstream rendering.*/-function detectCustomTaskState(token: Token): void {- if (token.type !== "list_item") {- return;- }- const item = token as TaskListItem;- if (item.task) {- return;- }- const match = TASK_MARKER_RAW_PATTERN.exec(item.raw);- if (!match) {- return;+function createTaskStateDetector(states: TaskStateDef[]): (token: Token) => void {+ const symbolToName = new Map<string, string>();+ for (const state of states) {+ const symbol = state.markdownSymbol;+ // `x` and ` ` are the native checked/unchecked markers handled by marked.+ if (symbol.length === 1 && symbol !== "x" && symbol !== " ") {+ symbolToName.set(symbol, state.name);+ }}- const state = MARKDOWN_MARKER_TO_TASK_STATE[match[1]];- if (!state) {- return;++ if (symbolToName.size === 0) {+ return () => {};}- item.task = true;- item.checked = false;- item._taskState = state;- item.text = item.text.replace(TASK_MARKER_STRIP_PATTERN, "");- stripTaskMarkerFromTokens(item.tokens);++ const charClass = [...symbolToName.keys()].map(escapeForCharClass).join("");+ const rawPattern = new RegExp(`^[ \\t]*[-*+]\\s+\\[([${charClass}])\\]\\s?`);+ const stripPattern = new RegExp(`^\\[[${charClass}]\\]\\s?`);++ return (token: Token): void => {+ if (token.type !== "list_item") {+ return;+ }+ const item = token as TaskListItem;+ if (item.task) {+ return;+ }+ const match = rawPattern.exec(item.raw);+ if (!match) {+ return;+ }+ const name = symbolToName.get(match[1]);+ if (!name) {+ return;+ }+ item.task = true;+ item.checked = false;+ item._taskState = name;+ item.text = item.text.replace(stripPattern, "");+ stripTaskMarkerFromTokens(item.tokens, stripPattern);+ };}import { getMimeTypeFromMarkdownName, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "./mime_type.js";@@ -111,6 +129,11 @@ export interface RenderToHtmlOptions {* marked attaches a parser to the renderer during parsing.*/renderer?: Renderer;+ /**+ * Configured todo task states, used to recognise non-standard task markers+ * (e.g. `[/]`) in list items. Defaults to {@link DEFAULT_TASK_STATES}.+ */+ taskStates?: TaskStateDef[];}function escapeHtml(str: string): string {@@ -349,7 +372,7 @@ export function renderToHtml(content: string, title: string, options: RenderToHtconst marked = new Marked({ async: false, gfm: true });marked.use(markedFootnote());- marked.use({ walkTokens: detectCustomTaskState });+ marked.use({ walkTokens: createTaskStateDetector(options.taskStates ?? DEFAULT_TASK_STATES) });marked.use({// Order is important, especially for wikilinks.extensions: [diff --git a/packages/commons/src/lib/task_states.ts b/packages/commons/src/lib/task_states.tsnew file mode 100644index 0000000000..5c9626c53d--- /dev/null+++ b/packages/commons/src/lib/task_states.ts@@ -0,0 +1,32 @@+/**+ * Definition of a configurable todo-list task state.+ *+ * The built-in `none` (unchecked) and `done` (checked) states are NOT task+ * states — they are CKEditor's native checkbox behaviour. Task states only+ * cover the non-binary states (e.g. "doing", "maybe", "cancelled").+ */+export interface TaskStateDef {+ /** The `stateName` label value — used verbatim as the `data-task-state` attribute. */+ name: string;+ /** Human-readable display name (the state note's title). */+ title: string;+ /** Single-character markdown marker, e.g. `/` for `- [/]`. */+ markdownSymbol: string;+ /** Whether the checkbox renders as checked while in this state. */+ checkboxValue: boolean;+ /** CSS color associated with the state, e.g. `#e6a23c`. */+ color: string;+ /** Icon class, e.g. `bx bx-loader`. */+ icon: string;+}++/**+ * Fallback task states, used wherever the user-defined states (stored as notes+ * in the `_taskStates` hidden subtree) are not reachable, and seeded as the+ * defaults on a fresh installation.+ */+export const DEFAULT_TASK_STATES: TaskStateDef[] = [+ {name: "doing", title: "Doing", markdownSymbol: "/", checkboxValue: false, color: "#e6a23c", icon: "bx bx-loader"},+ {name: "maybe", title: "Maybe", markdownSymbol: "?", checkboxValue: false, color: "#a06cd5", icon: "bx bx-help-circle"},+ {name: "cancelled", title: "Cancelled", markdownSymbol: "-", checkboxValue: false, color: "#909399", icon: "bx bx-x"}+];diff --git a/packages/share-theme/src/styles/base.css b/packages/share-theme/src/styles/base.cssindex 7f464cd1d5..155f720eac 100644--- a/packages/share-theme/src/styles/base.css+++ b/packages/share-theme/src/styles/base.css@@ -152,10 +152,6 @@ iframe.pdf-view {background-color: rgba(255, 200, 100, 0.25);}-.ck-content ul.todo-list > li[data-task-state="done"] {- background-color: rgba(130, 220, 130, 0.25);-}-.ck-content ul.todo-list > li[data-task-state="cancelled"] {background-color: rgba(180, 180, 180, 0.25);}diff --git a/packages/trilium-core/src/services/export/markdown.ts b/packages/trilium-core/src/services/export/markdown.tsindex a3417e0356..9e98948146 100644--- a/packages/trilium-core/src/services/export/markdown.ts+++ b/packages/trilium-core/src/services/export/markdown.ts@@ -1,9 +1,14 @@-import { ADMONITION_TYPE_MAPPINGS } from "@triliumnext/commons";+import { ADMONITION_TYPE_MAPPINGS, type TaskStateDef } from "@triliumnext/commons";import { gfm } from "@triliumnext/turndown-plugin-gfm";import Turnish, { type Rule } from "turnish";+import { getTaskStates } from "../task_states.js";+let instance: Turnish | null = null;+/** Task states for the current `toMarkdown` invocation, consulted by the list-item filter. */+let currentTaskStates: TaskStateDef[] = [];+export { ADMONITION_TYPE_MAPPINGS };export const DEFAULT_ADMONITION_TYPE = ADMONITION_TYPE_MAPPINGS.note;@@ -26,6 +31,8 @@ const fencedCodeBlockFilter: Rule = {};function toMarkdown(content: string) {+ currentTaskStates = getTaskStates();+if (instance === null) {instance = new Turnish({headingStyle: "atx",@@ -211,13 +218,6 @@ function buildFigureFilter(): Rule {};}-const TASK_STATE_TO_MARKDOWN_MARKER: Record<string, string> = {- doing: "/",- done: "x",- cancelled: "-",- maybe: "?"-};-// Keep in line with https://github.com/mixmark-io/turndown/blob/master/src/commonmark-rules.js.function buildListItemFilter(): Rule {return {@@ -234,7 +234,9 @@ function buildListItemFilter(): Rule {prefix = `${start ? Number(start) + index : index + 1}. `;} else if (parent.classList.contains("todo-list")) {const state = (node as HTMLElement).getAttribute("data-task-state");- const stateMarker = state ? TASK_STATE_TO_MARKDOWN_MARKER[state] : undefined;+ const stateMarker = state+ ? currentTaskStates.find((s) => s.name === state)?.markdownSymbol+ : undefined;if (stateMarker) {prefix = `- [${stateMarker}] `;} else {diff --git a/packages/trilium-core/src/services/hidden_subtree.ts b/packages/trilium-core/src/services/hidden_subtree.tsindex 075c18b114..d1181adb59 100644--- a/packages/trilium-core/src/services/hidden_subtree.ts+++ b/packages/trilium-core/src/services/hidden_subtree.ts@@ -12,6 +12,7 @@ import migrationService from "./migration.js";import noteService from "./notes.js";import { getLog } from "./log.js";import { getSql } from "./sql/index.js";+import { seedDefaultTaskStates } from "./task_states.js";export const LBTPL_ROOT = "_lbTplRoot";export const LBTPL_BASE = "_lbTplBase";@@ -84,6 +85,19 @@ function buildHiddenSubtreeDefinition(helpSubtree: HiddenSubtreeItem[]): HiddenStitle: t("hidden-subtree.bulk-action-title"),type: "doc"},+ {+ id: "_taskStates",+ title: t("hidden-subtree.task-states-title"),+ type: "book",+ icon: "bx-list-check",+ isExpanded: true,+ attributes: [+ { type: "label", name: "child:label:stateName", value: "promoted,single,text" },+ { type: "label", name: "child:label:markdownSymbol", value: "promoted,single,text" },+ { type: "label", name: "child:label:checkboxValue", value: "promoted,single,bool" },+ { type: "label", name: "child:label:color", value: "promoted,single,text" }+ ]+ },{id: "_backendLog",title: t("hidden-subtree.backend-log-title"),@@ -298,8 +312,16 @@ function checkHiddenSubtree(force = false, extraOpts: CheckHiddenExtraOpts = {})}getSql().transactional(() => {+ const taskStatesExisted = !!becca.notes["_taskStates"];+checkHiddenSubtreeRecursively("root", hiddenSubtreeDefinition, extraOpts);+ // Seed the default task states only the first time the container is created,+ // so that later user deletions stick instead of being recreated on startup.+ if (!taskStatesExisted) {+ seedDefaultTaskStates();+ }+try {cleanUpHelp(helpSubtree);} catch (e) {diff --git a/packages/trilium-core/src/services/import/markdown.ts b/packages/trilium-core/src/services/import/markdown.tsindex a90fb67c53..4d7d07c92b 100644--- a/packages/trilium-core/src/services/import/markdown.ts+++ b/packages/trilium-core/src/services/import/markdown.ts@@ -1,9 +1,13 @@import { renderToHtml as renderToHtmlShared } from "@triliumnext/commons";import { sanitizeHtml } from "../sanitizer.js";+import { getTaskStates } from "../task_states.js";function renderToHtml(content: string, title: string): string {- return renderToHtmlShared(content, title, { sanitize: sanitizeHtml });+ return renderToHtmlShared(content, title, {+ sanitize: sanitizeHtml,+ taskStates: getTaskStates()+ });}export default {diff --git a/packages/trilium-core/src/services/task_states.ts b/packages/trilium-core/src/services/task_states.tsnew file mode 100644index 0000000000..d86cb26eb0--- /dev/null+++ b/packages/trilium-core/src/services/task_states.ts@@ -0,0 +1,74 @@+import { DEFAULT_TASK_STATES, type TaskStateDef } from "@triliumnext/commons";+import { t } from "i18next";++import becca from "../becca/becca.js";+import BAttribute from "../becca/entities/battribute.js";+import noteService from "./notes.js";++export const TASK_STATES_CONTAINER_ID = "_taskStates";++/**+ * Returns the user-defined task states from the `_taskStates` hidden subtree,+ * in note order. Falls back to {@link DEFAULT_TASK_STATES} when the container+ * is missing or empty.+ */+export function getTaskStates(): TaskStateDef[] {+ const container = becca.notes[TASK_STATES_CONTAINER_ID];+ if (!container) {+ return DEFAULT_TASK_STATES;+ }++ const states = container.getChildNotes()+ .map((note): TaskStateDef => ({+ name: note.getLabelValue("stateName") ?? "",+ title: note.title,+ markdownSymbol: note.getLabelValue("markdownSymbol") ?? "",+ checkboxValue: note.getLabelValue("checkboxValue") === "true",+ color: note.getLabelValue("color") ?? "",+ icon: note.getLabelValue("iconClass") ?? ""+ }))+ .filter((state) => state.name);++ return states.length ? states : DEFAULT_TASK_STATES;+}++/**+ * Seeds the default task-state notes under the `_taskStates` container. Called+ * exactly once — when the container is first created — so user deletions stick.+ */+export function seedDefaultTaskStates() {+ const seeds: Array<{noteId: string; title: string; state: TaskStateDef}> = [+ {noteId: "_taskStateDoing", title: t("hidden-subtree.task-state-doing"), state: DEFAULT_TASK_STATES[0]},+ {noteId: "_taskStateMaybe", title: t("hidden-subtree.task-state-maybe"), state: DEFAULT_TASK_STATES[1]},+ {noteId: "_taskStateCancelled", title: t("hidden-subtree.task-state-cancelled"), state: DEFAULT_TASK_STATES[2]}+ ];++ for (const seed of seeds) {+ const {note} = noteService.createNewNote({+ noteId: seed.noteId,+ title: seed.title,+ type: "text",+ parentNoteId: TASK_STATES_CONTAINER_ID,+ content: "",+ ignoreForbiddenParents: true+ });++ const labels: Record<string, string> = {+ iconClass: seed.state.icon,+ stateName: seed.state.name,+ markdownSymbol: seed.state.markdownSymbol,+ checkboxValue: String(seed.state.checkboxValue),+ color: seed.state.color+ };++ for (const [name, value] of Object.entries(labels)) {+ new BAttribute({+ attributeId: `${note.noteId}_l${name}`,+ noteId: note.noteId,+ type: "label",+ name,+ value+ }).save();+ }+ }+}