Skip to content

Build your personal knowledge base with Trilium Notes

custom task states: refactor

Adorian Doranee42aa0c676d
diff --git a/apps/client/src/services/task_states.ts b/apps/client/src/services/task_states.ts
new file mode 100644
index 0000000000..c9cc5cdf14
--- /dev/null
+++ b/apps/client/src/services/task_states.ts
@@ -0,0 +1,68 @@
+import {
+ DEFAULT_TASK_STATES,
+ DONE_STATE_ID,
+ DONE_TASK_STATE,
+ NONE_STATE_ID,
+ NONE_TASK_STATE,
+ TASK_STATES_CONTAINER_ID,
+ type TaskStateDef,
+ type TaskStateValidationError,
+ validateTaskStates
+} from "@triliumnext/commons";
+
+import appContext from "../components/app_context.js";
+import froca from "./froca.js";
+import { showError } from "./toast.js";
+
+let validationReported = false;
+
+/** Surfaces dropped-task-state warnings once per session — as a toast and in the console. */
+function reportValidationErrors(errors: TaskStateValidationError[]) {
+ if (validationReported || errors.length === 0) {
+ return;
+ }
+ validationReported = true;
+ for (const error of errors) {
+ showError(error.message);
+ }
+}
+
+/**
+ * Enumerates the configured task states from the `_taskStates` hidden subtree,
+ * dropping invalid definitions and reporting them once. Shared by the text
+ * editor, kanban and the todo collection view.
+ */
+export async function getTaskStateDefinitions(): Promise<TaskStateDef[]> {
+ const container = await froca.getNote(TASK_STATES_CONTAINER_ID);
+ if (!container) {
+ return DEFAULT_TASK_STATES;
+ }
+
+ const states = (await container.getChildNotes()).map((note): TaskStateDef => {
+ if (note.noteId === NONE_STATE_ID) {
+ return NONE_TASK_STATE;
+ }
+ if (note.noteId === DONE_STATE_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
+ };
+ });
+
+ const {valid, errors} = validateTaskStates(states);
+ reportValidationErrors(errors);
+ return valid.length ? valid : DEFAULT_TASK_STATES;
+}
+
+/** Opens the "Task States" configuration note in a new tab, hoisted to it. */
+export function openCustomTaskStateConfig(): void {
+ void appContext.tabManager.openInNewTab(TASK_STATES_CONTAINER_ID, TASK_STATES_CONTAINER_ID, true);
+}
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index c358690e66..62f62e47eb 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -1,12 +1,10 @@
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, type TaskStateValidationError, validateTaskStates } from "@triliumnext/commons";
+import { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } 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 { getTaskStateDefinitions, openCustomTaskStateConfig } from "../../../services/task_states.js";
import { getMermaidConfig } from "../../../services/mermaid.js";
import { default as mimeTypesService, getHighlightJsNameForMime } from "../../../services/mime_types.js";
import noteAutocompleteService, { type Suggestion } from "../../../services/note_autocomplete.js";
@@ -178,10 +176,8 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
};
// User-configurable todo task states (from the `_taskStates` hidden subtree).
- (config as Record<string, unknown>).taskStates = await fetchTaskStates();
- (config as Record<string, unknown>).editTaskStates = () => {
- void appContext.tabManager.openInNewTab("_taskStates", "_taskStates", true);
- };
+ (config as Record<string, unknown>).taskStates = await getTaskStateDefinitions();
+ (config as Record<string, unknown>).editTaskStates = openCustomTaskStateConfig;
// The app's i18n translate function, so plugins can resolve Trilium translation keys.
(config as Record<string, unknown>).translate = (key: string) => t(key);
@@ -238,50 +234,6 @@ 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 => {
- if (note.noteId === "_taskStateNone") {
- return NONE_TASK_STATE;
- }
- if (note.noteId === "_taskStateDone") {
- 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
- };
- });
-
- const {valid, errors} = validateTaskStates(states);
- reportTaskStateValidationErrors(errors);
- return valid.length ? valid : 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() {
const userLanguages = mimeTypesService
.getMimeTypes()
diff --git a/packages/commons/src/lib/task_states.ts b/packages/commons/src/lib/task_states.ts
index 5c4436a2d5..75448f525d 100644
--- a/packages/commons/src/lib/task_states.ts
+++ b/packages/commons/src/lib/task_states.ts
@@ -30,6 +30,8 @@ export const NONE_STATE_NAME = "none";
/** Reserved name of the built-in checked anchor state. */
export const DONE_STATE_NAME = "done";
+/** Hidden-subtree note that contains the task state definitions. */
+export const TASK_STATES_CONTAINER_ID = "_taskStates";
/** Note id of the built-in unchecked anchor state. */
export const NONE_STATE_ID = "_taskStateNone";
/** Note id of the built-in checked anchor state. */
diff --git a/packages/trilium-core/src/services/task_states.ts b/packages/trilium-core/src/services/task_states.ts
index 0ba1b47d50..50fa2fb685 100644
--- a/packages/trilium-core/src/services/task_states.ts
+++ b/packages/trilium-core/src/services/task_states.ts
@@ -1,24 +1,18 @@
-import { DEFAULT_CUSTOM_TASK_STATES, DEFAULT_TASK_STATES, DONE_TASK_STATE, isAnchorState, NONE_TASK_STATE, type TaskStateDef, validateTaskStates } from "@triliumnext/commons";
+import { DEFAULT_CUSTOM_TASK_STATES, DEFAULT_TASK_STATES, DONE_STATE_ID, DONE_TASK_STATE, isAnchorState, NONE_STATE_ID, NONE_TASK_STATE, TASK_STATES_CONTAINER_ID, type TaskStateDef, validateTaskStates } from "@triliumnext/commons";
import { t } from "i18next";
import becca from "../becca/becca.js";
import BAttribute from "../becca/entities/battribute.js";
+import type BNote from "../becca/entities/bnote.js";
import { getIconPacks } from "./icon_packs.js";
import noteService from "./notes.js";
-export const TASK_STATES_CONTAINER_ID = "_taskStates";
-const NONE_NOTE_ID = "_taskStateNone";
-const DONE_NOTE_ID = "_taskStateDone";
-
-function noteIdForState(name: string): string {
- return `_taskState${name.charAt(0).toUpperCase()}${name.slice(1)}`;
-}
-
/**
* Returns the task states from the `_taskStates` hidden subtree, in note order.
* The `none`/`done` anchor notes map to their fixed built-in definitions; other
- * children are read from their promoted attributes. Falls back to
- * {@link DEFAULT_TASK_STATES} when the container is missing or empty.
+ * children are read from their promoted attributes. Invalid custom states are
+ * dropped. 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];
@@ -27,10 +21,10 @@ export function getTaskStates(): TaskStateDef[] {
}
const states = container.getChildNotes().map((note): TaskStateDef => {
- if (note.noteId === NONE_NOTE_ID) {
+ if (note.noteId === NONE_STATE_ID) {
return NONE_TASK_STATE;
}
- if (note.noteId === DONE_NOTE_ID) {
+ if (note.noteId === DONE_STATE_ID) {
return DONE_TASK_STATE;
}
return {
@@ -49,6 +43,42 @@ export function getTaskStates(): TaskStateDef[] {
return valid.length ? valid : DEFAULT_TASK_STATES;
}
+/**
+ * Creates a single task-state definition note under the `_taskStates` container,
+ * with its promoted attributes. Reusable for seeding and for adding states from
+ * any feature (text editor, kanban, todo collection view).
+ */
+export function createTaskStateNote(state: TaskStateDef, options: {noteId?: string; title?: string} = {}): BNote {
+ const {note} = noteService.createNewNote({
+ noteId: options.noteId,
+ title: options.title ?? state.title,
+ type: "text",
+ parentNoteId: TASK_STATES_CONTAINER_ID,
+ content: "",
+ ignoreForbiddenParents: true
+ });
+
+ const labels: Record<string, string> = {
+ iconClass: state.icon,
+ stateName: state.name,
+ markdownSymbol: state.markdownSymbol,
+ checkboxValue: String(state.checkboxValue),
+ color: 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();
+ }
+
+ return note;
+}
+
/**
* Seeds the customizable default task states under the `_taskStates` container
* and applies the default ordering across all states (anchors included). Called
@@ -62,37 +92,12 @@ export function seedDefaultTaskStates() {
};
for (const state of DEFAULT_CUSTOM_TASK_STATES) {
- const {note} = noteService.createNewNote({
- noteId: noteIdForState(state.name),
- title: t(titleKeys[state.name]),
- type: "text",
- parentNoteId: TASK_STATES_CONTAINER_ID,
- content: "",
- ignoreForbiddenParents: true
- });
-
- const labels: Record<string, string> = {
- iconClass: state.icon,
- stateName: state.name,
- markdownSymbol: state.markdownSymbol,
- checkboxValue: String(state.checkboxValue),
- color: 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();
- }
+ createTaskStateNote(state, {noteId: state.id, title: t(titleKeys[state.name])});
}
// Apply the default ordering (None, Doing, Done, Maybe, Cancelled) across all states.
DEFAULT_TASK_STATES.forEach((state, index) => {
- const note = becca.notes[noteIdForState(state.name)];
+ const note = state.id ? becca.notes[state.id] : undefined;
const branch = note?.getParentBranches().find((b) => b.parentNoteId === TASK_STATES_CONTAINER_ID);
if (branch) {
branch.notePosition = index * 10;