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
custom task states: validate custom task definitions
Adorian Doran2a83b3c202b3
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex 2f7ec36454..c358690e66 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -1,10 +1,11 @@import { buildExtraCommands, type EditorConfig, getCkLocale, loadPremiumPlugins, TemplateDefinition } from "@triliumnext/ckeditor5";import emojiDefinitionsUrl from "@triliumnext/ckeditor5/src/emoji_definitions/en.json?url";-import { ALLOWED_PROTOCOLS, DEFAULT_TASK_STATES, DISPLAYABLE_LOCALE_IDS, DONE_TASK_STATE, MIME_TYPE_AUTO, NONE_TASK_STATE, normalizeMimeTypeForCKEditor, type TaskStateDef } from "@triliumnext/commons";+import { ALLOWED_PROTOCOLS, DEFAULT_TASK_STATES, DISPLAYABLE_LOCALE_IDS, DONE_TASK_STATE, MIME_TYPE_AUTO, NONE_TASK_STATE, normalizeMimeTypeForCKEditor, type TaskStateDef, type TaskStateValidationError, validateTaskStates } from "@triliumnext/commons";import appContext from "../../../components/app_context.js";import froca from "../../../services/froca.js";import { copyTextWithToast } from "../../../services/clipboard_ext.js";+import { showError } from "../../../services/toast.js";import { t } from "../../../services/i18n.js";import { getMermaidConfig } from "../../../services/mermaid.js";import { default as mimeTypesService, getHighlightJsNameForMime } from "../../../services/mime_types.js";@@ -244,19 +245,16 @@ async function fetchTaskStates(): Promise<TaskStateDef[]> {}const states = (await container.getChildNotes())- .map((note): TaskStateDef | null => {+ .map((note): TaskStateDef => {if (note.noteId === "_taskStateNone") {return NONE_TASK_STATE;}if (note.noteId === "_taskStateDone") {return DONE_TASK_STATE;}- const name = note.getLabelValue("stateName");- if (!name) {- return null;- }return {- name,+ id: note.noteId,+ name: note.getLabelValue("stateName") ?? "",title: note.title,markdownSymbol: note.getLabelValue("markdownSymbol") ?? "",checkboxValue: note.getLabelValue("checkboxValue") === "true",@@ -264,10 +262,24 @@ async function fetchTaskStates(): Promise<TaskStateDef[]> {icon: note.getLabelValue("iconClass") ?? "",archived: note.isArchived};- })- .filter((state): state is TaskStateDef => state !== null);+ });++ const {valid, errors} = validateTaskStates(states);+ reportTaskStateValidationErrors(errors);+ return valid.length ? valid : DEFAULT_TASK_STATES;+}- return states.length ? states : DEFAULT_TASK_STATES;+let taskStateValidationReported = false;++/** Surfaces dropped-task-state warnings once per session — as a toast and in the console. */+function reportTaskStateValidationErrors(errors: TaskStateValidationError[]) {+ if (taskStateValidationReported || errors.length === 0) {+ return;+ }+ taskStateValidationReported = true;+ for (const error of errors) {+ showError(error.message);+ }}function buildListOfLanguages() {diff --git a/packages/commons/src/lib/task_states.spec.ts b/packages/commons/src/lib/task_states.spec.tsnew file mode 100644index 0000000000..c27a9fdde3--- /dev/null+++ b/packages/commons/src/lib/task_states.spec.ts@@ -0,0 +1,73 @@+import { describe, expect, it } from "vitest";++import { DONE_TASK_STATE, NONE_TASK_STATE, type TaskStateDef, validateTaskStates } from "./task_states.js";++function customState(overrides: Partial<TaskStateDef>): TaskStateDef {+ return {+ id: "_id",+ name: "doing",+ title: "Doing",+ markdownSymbol: "/",+ checkboxValue: false,+ color: "",+ icon: "bx bx-loader",+ ...overrides+ };+}++const SYMBOL_REASON = `the markdown symbol should be one character, excepting "[", " ", "X", and "]"`;++describe("validateTaskStates", () => {+ it("keeps anchors and valid custom states", () => {+ const states = [NONE_TASK_STATE, customState({ id: "a", name: "doing" }), DONE_TASK_STATE];+ const { valid, errors } = validateTaskStates(states);++ expect(errors).toHaveLength(0);+ expect(valid).toEqual(states);+ });++ it("drops invalid custom states with the matching reason", () => {+ const scenarios: Array<[Partial<TaskStateDef>, string]> = [+ [{ name: "" }, "undefined stateName"],+ [{ name: "in progress" }, "invalid stateName"],+ [{ name: "<b>" }, "invalid stateName"],+ [{ name: "done" }, "duplicate stateName"],+ [{ name: "none" }, "duplicate stateName"],+ [{ title: "" }, "missing title"],+ [{ icon: "" }, "missing icon"],+ [{ markdownSymbol: "//" }, SYMBOL_REASON],+ [{ markdownSymbol: " " }, SYMBOL_REASON],+ [{ markdownSymbol: "[" }, SYMBOL_REASON],+ [{ markdownSymbol: "X" }, SYMBOL_REASON]+ ];++ for (const [overrides, reason] of scenarios) {+ const { valid, errors } = validateTaskStates([customState(overrides)]);+ expect(valid).toHaveLength(0);+ expect(errors).toHaveLength(1);+ expect(errors[0].reason).toBe(reason);+ }+ });++ it("detects duplicates across custom states, keeping the first", () => {+ const first = customState({ id: "a", name: "doing", markdownSymbol: "/" });+ const dupName = customState({ id: "b", name: "doing", markdownSymbol: "?" });+ const dupSymbol = customState({ id: "c", name: "other", markdownSymbol: "/" });++ const { valid, errors } = validateTaskStates([first, dupName, dupSymbol]);++ expect(valid).toEqual([first]);+ expect(errors.map((e) => e.reason)).toEqual(["duplicate stateName", "duplicate markdown symbol"]);+ });++ it("builds the drop message", () => {+ const { errors } = validateTaskStates([customState({ id: "abc", title: "My State", name: "" })]);+ expect(errors[0].message).toBe(`Dropped custom task state definition "My State" (abc) due to: undefined stateName`);+ });++ it("allows a custom state with no markdown symbol", () => {+ const { valid, errors } = validateTaskStates([customState({ markdownSymbol: "" })]);+ expect(errors).toHaveLength(0);+ expect(valid).toHaveLength(1);+ });+});diff --git a/packages/commons/src/lib/task_states.ts b/packages/commons/src/lib/task_states.tsindex 9a8ab9da4d..5c4436a2d5 100644--- a/packages/commons/src/lib/task_states.ts+++ b/packages/commons/src/lib/task_states.ts@@ -7,6 +7,8 @@* customizable states for toolbar order and keyboard cycling.*/export interface TaskStateDef {+ /** The state note's id (used in validation messages; absent on hardcoded fallbacks). */+ id?: string;/** The `stateName` label value — used verbatim as the `data-trilium-task-state` attribute. */name: string;/** Human-readable display name (the state note's title). */@@ -28,6 +30,11 @@ export const NONE_STATE_NAME = "none";/** Reserved name of the built-in checked anchor state. */export const DONE_STATE_NAME = "done";+/** Note id of the built-in unchecked anchor state. */+export const NONE_STATE_ID = "_taskStateNone";+/** Note id of the built-in checked anchor state. */+export const DONE_STATE_ID = "_taskStateDone";+/** Whether `name` is a built-in anchor state (`none`/`done`) rather than a customizable one. */export function isAnchorState(name: string): boolean {return name === NONE_STATE_NAME || name === DONE_STATE_NAME;@@ -35,12 +42,12 @@ export function isAnchorState(name: string): boolean {/** The built-in unchecked anchor state. */export const NONE_TASK_STATE: TaskStateDef = {- name: NONE_STATE_NAME, title: "None", markdownSymbol: " ", checkboxValue: false, color: "", icon: "bx bx-checkbox"+ id: NONE_STATE_ID, name: NONE_STATE_NAME, title: "None", markdownSymbol: " ", checkboxValue: false, color: "", icon: "bx bx-checkbox"};/** The built-in checked anchor state. */export const DONE_TASK_STATE: TaskStateDef = {- name: DONE_STATE_NAME, title: "Done", markdownSymbol: "x", checkboxValue: true, color: "#4de64d", icon: "bx bx-check"+ id: DONE_STATE_ID, name: DONE_STATE_NAME, title: "Done", markdownSymbol: "x", checkboxValue: true, color: "#4de64d", icon: "bx bx-check"};/**@@ -48,9 +55,9 @@ export const DONE_TASK_STATE: TaskStateDef = {* installation.*/export const DEFAULT_CUSTOM_TASK_STATES: TaskStateDef[] = [- {name: "doing", title: "Doing", markdownSymbol: "/", checkboxValue: false, color: "#e6a23c", icon: "bx bx-loader"},- {name: "maybe", title: "Maybe", markdownSymbol: "?", checkboxValue: false, color: "#4d4de6", icon: "bx bx-question-mark"},- {name: "cancelled", title: "Cancelled", markdownSymbol: "-", checkboxValue: false, color: "#e64d4d", icon: "bx bx-block"}+ {id: "_taskStateDoing", name: "doing", title: "Doing", markdownSymbol: "/", checkboxValue: false, color: "#e6a23c", icon: "bx bx-loader"},+ {id: "_taskStateMaybe", name: "maybe", title: "Maybe", markdownSymbol: "?", checkboxValue: false, color: "#4d4de6", icon: "bx bx-question-mark"},+ {id: "_taskStateCancelled", name: "cancelled", title: "Cancelled", markdownSymbol: "-", checkboxValue: false, color: "#e64d4d", icon: "bx bx-block"}];/**@@ -64,3 +71,98 @@ export const DEFAULT_TASK_STATES: TaskStateDef[] = [DEFAULT_CUSTOM_TASK_STATES[1],DEFAULT_CUSTOM_TASK_STATES[2]];++/** A custom task state that failed validation and was dropped. */+export interface TaskStateValidationError {+ /** The dropped state note's id. */+ id: string;+ /** The dropped state's title (falls back to its name). */+ title: string;+ /** Short machine-ish reason. */+ reason: string;+ /** Ready-to-display message. */+ message: string;+}++export interface TaskStateValidationResult {+ /** The accepted states (anchors plus valid custom states), in input order. */+ valid: TaskStateDef[];+ /** Dropped custom states with their reasons. */+ errors: TaskStateValidationError[];+}++/** `stateName` is embedded in HTML attributes, CSS selectors and JSON — keep it strictly safe. */+const VALID_STATE_NAME_PATTERN = /^[A-Za-z0-9_-]+$/;+/** Symbols reserved by the markdown task-list syntax `- [ ]` / `- [x]`. */+const FORBIDDEN_MARKDOWN_SYMBOLS = new Set(["[", "]", " ", "x", "X"]);++function checkCustomState(+ state: TaskStateDef,+ seenNames: Set<string>,+ seenSymbols: Set<string>+): string | null {+ if (!state.name) {+ return "undefined stateName";+ }+ if (!VALID_STATE_NAME_PATTERN.test(state.name)) {+ return "invalid stateName";+ }+ if (seenNames.has(state.name)) {+ return "duplicate stateName";+ }+ if (!state.title) {+ return "missing title";+ }+ if (!state.icon) {+ return "missing icon";+ }+ if (state.markdownSymbol) {+ if (state.markdownSymbol.length !== 1 || FORBIDDEN_MARKDOWN_SYMBOLS.has(state.markdownSymbol)) {+ return `the markdown symbol should be one character, excepting "[", " ", "X", and "]"`;+ }+ if (seenSymbols.has(state.markdownSymbol)) {+ return "duplicate markdown symbol";+ }+ }+ return null;+}++/**+ * Validates custom task states, dropping invalid ones. Anchor states (`none`/`done`)+ * pass through untouched. Single pass — O(n) over a small set.+ */+export function validateTaskStates(states: TaskStateDef[]): TaskStateValidationResult {+ const valid: TaskStateDef[] = [];+ const errors: TaskStateValidationError[] = [];+ // Seed with the reserved anchor names so a custom state may not reuse them.+ const seenNames = new Set<string>([NONE_STATE_NAME, DONE_STATE_NAME]);+ const seenSymbols = new Set<string>();++ for (const state of states) {+ if (state.id === NONE_STATE_ID || state.id === DONE_STATE_ID) {+ valid.push(state);+ continue;+ }++ const reason = checkCustomState(state, seenNames, seenSymbols);+ if (reason) {+ const title = state.title || state.name || "";+ const id = state.id ?? "";+ errors.push({+ id,+ title,+ reason,+ message: `Dropped custom task state definition "${title}" (${id}) due to: ${reason}`+ });+ continue;+ }++ seenNames.add(state.name);+ if (state.markdownSymbol) {+ seenSymbols.add(state.markdownSymbol);+ }+ valid.push(state);+ }++ return { valid, errors };+}diff --git a/packages/trilium-core/src/services/task_states.ts b/packages/trilium-core/src/services/task_states.tsindex edc3d609c3..0ba1b47d50 100644--- a/packages/trilium-core/src/services/task_states.ts+++ b/packages/trilium-core/src/services/task_states.ts@@ -1,4 +1,4 @@-import { DEFAULT_CUSTOM_TASK_STATES, DEFAULT_TASK_STATES, DONE_TASK_STATE, isAnchorState, NONE_TASK_STATE, type TaskStateDef } from "@triliumnext/commons";+import { DEFAULT_CUSTOM_TASK_STATES, DEFAULT_TASK_STATES, DONE_TASK_STATE, isAnchorState, NONE_TASK_STATE, type TaskStateDef, validateTaskStates } from "@triliumnext/commons";import { t } from "i18next";import becca from "../becca/becca.js";@@ -26,31 +26,27 @@ export function getTaskStates(): TaskStateDef[] {return DEFAULT_TASK_STATES;}- const states = container.getChildNotes()- .map((note): TaskStateDef | null => {- if (note.noteId === NONE_NOTE_ID) {- return NONE_TASK_STATE;- }- if (note.noteId === DONE_NOTE_ID) {- return DONE_TASK_STATE;- }- const name = note.getLabelValue("stateName");- if (!name) {- return null;- }- return {- name,- title: note.title,- markdownSymbol: note.getLabelValue("markdownSymbol") ?? "",- checkboxValue: note.getLabelValue("checkboxValue") === "true",- color: note.getLabelValue("color") ?? "",- icon: note.getLabelValue("iconClass") ?? "",- archived: note.isArchived- };- })- .filter((state): state is TaskStateDef => state !== null);+ const states = container.getChildNotes().map((note): TaskStateDef => {+ if (note.noteId === NONE_NOTE_ID) {+ return NONE_TASK_STATE;+ }+ if (note.noteId === DONE_NOTE_ID) {+ return DONE_TASK_STATE;+ }+ return {+ id: note.noteId,+ name: note.getLabelValue("stateName") ?? "",+ title: note.title,+ markdownSymbol: note.getLabelValue("markdownSymbol") ?? "",+ checkboxValue: note.getLabelValue("checkboxValue") === "true",+ color: note.getLabelValue("color") ?? "",+ icon: note.getLabelValue("iconClass") ?? "",+ archived: note.isArchived+ };+ });- return states.length ? states : DEFAULT_TASK_STATES;+ const {valid} = validateTaskStates(states);+ return valid.length ? valid : DEFAULT_TASK_STATES;}/**