Skip to content

Build your personal knowledge base with Trilium Notes

feat(toast): annotate reference notes and improve dropped-task-state UX

Elian Dorana1a4af9b3b11
diff --git a/apps/client/src/services/backend_scripting.ts b/apps/client/src/services/backend_scripting.ts
index 5f80830b2b..400e4f0164 100644
--- a/apps/client/src/services/backend_scripting.ts
+++ b/apps/client/src/services/backend_scripting.ts
@@ -36,7 +36,7 @@ export function showBackendScriptingDisabledToast(noteId: string) {
title: t("frontend_script_api.backend_scripting_disabled_title"),
message: t("frontend_script_api.backend_scripting_disabled_message"),
notesHeading: t("frontend_script_api.backend_scripting_disabled_notes_heading"),
- noteIds: [ ...attempts ],
+ notes: [ ...attempts ],
wide: true,
timeout: 60_000,
onRemove: () => attempts.clear(),
diff --git a/apps/client/src/services/frontend_script_api.spec.ts b/apps/client/src/services/frontend_script_api.spec.ts
index 1f2055684b..09cc63b98b 100644
--- a/apps/client/src/services/frontend_script_api.spec.ts
+++ b/apps/client/src/services/frontend_script_api.spec.ts
@@ -224,7 +224,7 @@ describe("runOnBackend / __runOnBackendInner", () => {
// The latest (deduplicated) toast lists both attempting scripts as reference notes.
const lastOptions = showPersistent.mock.calls.at(-1)?.[0];
- expect(lastOptions?.noteIds).toEqual([ noteA.noteId, noteB.noteId ]);
+ expect(lastOptions?.notes).toEqual([ noteA.noteId, noteB.noteId ]);
expect(lastOptions?.onRemove).toBeTypeOf("function");
});
@@ -241,7 +241,7 @@ describe("runOnBackend / __runOnBackendInner", () => {
showPersistent.mock.calls.at(-1)?.[0].onRemove?.();
await attempt(noteB);
- expect(showPersistent.mock.calls.at(-1)?.[0].noteIds).toEqual([ noteB.noteId ]);
+ expect(showPersistent.mock.calls.at(-1)?.[0].notes).toEqual([ noteB.noteId ]);
});
it("serializes a sync function, posts it, waits for sync and returns the result", async () => {
diff --git a/apps/client/src/services/link.ts b/apps/client/src/services/link.ts
index f6929d07df..72c92405f9 100644
--- a/apps/client/src/services/link.ts
+++ b/apps/client/src/services/link.ts
@@ -72,6 +72,13 @@ interface CreateLinkOptions {
referenceLink?: boolean;
autoConvertToImage?: boolean;
viewScope?: ViewScope;
+ /**
+ * Inline text appended right after the link title (before the note path, which renders on its
+ * own line). Rendered as a `.note-link-suffix` span so it rides the title's baseline instead of
+ * being pushed into a column by the wider note-path block — e.g. an annotation on why the note
+ * is being shown.
+ */
+ titleSuffix?: string;
}
async function createLink(notePath: string | undefined, options: CreateLinkOptions = {}) {
@@ -156,6 +163,10 @@ async function createLink(notePath: string | undefined, options: CreateLinkOptio
$container.append($noteLink);
+ if (options.titleSuffix) {
+ $container.append($("<span>").addClass("note-link-suffix").text(options.titleSuffix));
+ }
+
if (showNotePath) {
let pathSegments: string[];
if (notePath == "root") {
diff --git a/apps/client/src/services/task_states.spec.ts b/apps/client/src/services/task_states.spec.ts
index 52ca5dede5..b7b21dff8e 100644
--- a/apps/client/src/services/task_states.spec.ts
+++ b/apps/client/src/services/task_states.spec.ts
@@ -11,7 +11,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import appContext from "../components/app_context.js";
import { buildNote } from "../test/easy-froca.js";
import froca from "./froca.js";
-import { showError } from "./toast.js";
+import toastService from "./toast.js";
vi.mock("./i18n.js", () => ({
// Echo the key so assertions stay on stable keys, not translated strings.
@@ -19,7 +19,10 @@ vi.mock("./i18n.js", () => ({
}));
vi.mock("./toast.js", () => ({
- showError: vi.fn()
+ default: {
+ showPersistent: vi.fn(),
+ closePersistent: vi.fn()
+ }
}));
const { getTaskStateDefinitions, openCustomTaskStateConfig } = await import("./task_states.js");
@@ -73,7 +76,7 @@ describe("getTaskStateDefinitions", () => {
// The archived child is never enumerated.
expect(result.some((s) => s.title === "Archived state")).toBe(false);
// No validation errors for a fully valid set.
- expect(showError).not.toHaveBeenCalled();
+ expect(toastService.showPersistent).not.toHaveBeenCalled();
expect(result.find((s) => s.id === "_taskStateDoing")).toEqual({
id: "_taskStateDoing",
@@ -100,7 +103,7 @@ describe("getTaskStateDefinitions", () => {
]);
const result = await getTaskStateDefinitions();
- expect(showError).not.toHaveBeenCalled();
+ expect(toastService.showPersistent).not.toHaveBeenCalled();
expect(result.find((s) => s.id === "_taskStateBare")).toEqual({
id: "_taskStateBare",
name: "bare",
@@ -113,7 +116,7 @@ describe("getTaskStateDefinitions", () => {
});
});
- it("reports each dropped state once via a toast, then never again", async () => {
+ it("reports dropped states in one persistent toast, deduplicates, re-reports on change and clears when fixed", async () => {
// Two non-archived states missing stateId/iconClass map to empty name/icon
// (covering the nullish-left branches), then get dropped by validation.
useContainer([
@@ -124,13 +127,40 @@ describe("getTaskStateDefinitions", () => {
const result = await getTaskStateDefinitions();
// No valid custom states remain -> falls back to the defaults.
expect(result).toBe(DEFAULT_TASK_STATES);
- expect(showError).toHaveBeenCalledTimes(2);
- // A second invocation must not re-report (the session-level latch is set).
- vi.mocked(showError).mockClear();
+ // A single persistent toast lists both dropped notes, each annotated with its reason.
+ expect(toastService.showPersistent).toHaveBeenCalledTimes(1);
+ const options = vi.mocked(toastService.showPersistent).mock.calls[0][0];
+ expect(options.id).toBe("task-states-validation");
+ expect(options.notes).toEqual([
+ { noteId: "_taskBadA", description: "text-editor.validation-errors.undefined-name" },
+ { noteId: "_taskBadB", description: "text-editor.validation-errors.undefined-name" }
+ ]);
+
+ // Its button opens the task-states config popup and dismisses the toast.
+ const triggerCommand = vi.fn();
+ (appContext as unknown as { triggerCommand: typeof triggerCommand }).triggerCommand = triggerCommand;
+ const dismissToast = vi.fn();
+ options.buttons?.[0].onClick({ dismissToast });
+ expect(triggerCommand).toHaveBeenCalledWith("openInTreePopup", expect.objectContaining({
+ noteIdOrPath: TASK_STATES_CONTAINER_ID
+ }));
+ expect(dismissToast).toHaveBeenCalled();
+
+ // An unchanged error set is not re-reported...
+ await getTaskStateDefinitions();
+ expect(toastService.showPersistent).toHaveBeenCalledTimes(1);
+
+ // ...but a different one is...
useContainer([{ id: "_taskBadC", title: "Bad C" }]);
await getTaskStateDefinitions();
- expect(showError).not.toHaveBeenCalled();
+ expect(toastService.showPersistent).toHaveBeenCalledTimes(2);
+
+ // ...and a clean set closes the toast without re-showing it.
+ useContainer([{ id: "_taskStateOk", title: "Ok", "#stateId": "ok", "#iconClass": "bx bx-x" }]);
+ await getTaskStateDefinitions();
+ expect(toastService.closePersistent).toHaveBeenCalledWith("task-states-validation");
+ expect(toastService.showPersistent).toHaveBeenCalledTimes(2);
});
});
diff --git a/apps/client/src/services/task_states.ts b/apps/client/src/services/task_states.ts
index 18f3f11c9c..56a96ff76c 100644
--- a/apps/client/src/services/task_states.ts
+++ b/apps/client/src/services/task_states.ts
@@ -13,20 +13,55 @@ import {
import appContext from "../components/app_context.js";
import froca from "./froca.js";
import { t } from "./i18n.js";
-import { showError } from "./toast.js";
+import toastService from "./toast.js";
-let validationReported = false;
+const VALIDATION_TOAST_ID = "task-states-validation";
-/** Surfaces dropped-task-state warnings once per session — as a toast and in the console. */
+/** The last reported error set, so the toast only re-surfaces when the situation changes. */
+let lastReportedSignature: string | null = null;
+
+/**
+ * Surfaces dropped-task-state warnings as a single persistent toast listing the offending
+ * definition notes as reference links, each annotated with its rejection reason. Re-shown only
+ * when the error set changes; closed as soon as validation comes back clean, so fixing the
+ * definitions gives immediate feedback.
+ */
function reportValidationErrors(errors: TaskStateValidationError[]) {
- if (validationReported || errors.length === 0) {
+ const signature = errors.map((error) => `${error.id}:${error.reason}`).sort().join(",");
+ if (signature === lastReportedSignature) {
return;
}
- validationReported = true;
- for (const error of errors) {
- const reason = t(`text-editor.validation-errors.${error.reason}`);
- showError(t("text-editor.task-state-dropped", {title: error.title, id: error.id, reason}));
+ lastReportedSignature = signature;
+
+ if (errors.length === 0) {
+ toastService.closePersistent(VALIDATION_TOAST_ID);
+ return;
}
+
+ toastService.showPersistent({
+ id: VALIDATION_TOAST_ID,
+ icon: "bx bx-list-check",
+ title: t("text-editor.task-state-dropped-title"),
+ message: t("text-editor.task-state-dropped-message", { count: errors.length }),
+ notesHeading: t("text-editor.task-state-dropped-heading"),
+ notes: errors
+ .filter((error) => error.id)
+ .map((error) => ({
+ noteId: error.id,
+ description: t(`text-editor.validation-errors.${error.reason}`)
+ })),
+ wide: true,
+ timeout: 60_000,
+ buttons: [
+ {
+ text: t("text-editor.task-state-dropped-configure"),
+ onClick: ({ dismissToast }) => {
+ openCustomTaskStateConfig();
+ dismissToast();
+ }
+ }
+ ]
+ });
}
/**
diff --git a/apps/client/src/services/toast.spec.ts b/apps/client/src/services/toast.spec.ts
index d07772d8f3..9707930c21 100644
--- a/apps/client/src/services/toast.spec.ts
+++ b/apps/client/src/services/toast.spec.ts
@@ -121,7 +121,7 @@ describe("toast store", () => {
message: "it failed",
timeout: 15000,
// The script note is attached as a reference link instead of a bespoke open-note button.
- noteIds: [ "scriptNote1" ]
+ notes: [ "scriptNote1" ]
});
expect(created?.buttons).toBeUndefined();
});
diff --git a/apps/client/src/services/toast.ts b/apps/client/src/services/toast.ts
index b9a7b9e949..b68878413d 100644
--- a/apps/client/src/services/toast.ts
+++ b/apps/client/src/services/toast.ts
@@ -3,6 +3,13 @@ import { signal } from "@preact/signals";
import { t } from "./i18n.js";
import utils, { randomString } from "./utils.js";
+/** A note rendered as a reference link in a toast body, with an optional annotation. */
+export interface ToastNoteReference {
+ noteId: string;
+ /** Short muted text rendered next to the link — e.g. why this note is being surfaced. */
+ description?: string;
+}
+
export interface ToastOptions {
id?: string;
icon: string;
@@ -20,19 +27,20 @@ export interface ToastOptions {
dismissible?: boolean;
/**
* When `true`, the toast renders with a wider maximum width than the default. Use for toasts with
- * richer content — e.g. a {@link noteIds} reference-link list — that reads poorly cramped.
+ * richer content — e.g. a {@link notes} reference-link list — that reads poorly cramped.
*/
wide?: boolean;
/**
* Notes to render as reference links in the toast body — e.g. the notes an action affected or that
* triggered the message. Each is shown with its icon and title and navigates to the note on click.
+ * A plain string is shorthand for a {@link ToastNoteReference} without annotation.
*/
- noteIds?: string[];
- /** Optional heading rendered above the {@link noteIds} reference-link list. */
+ notes?: (string | ToastNoteReference)[];
+ /** Optional heading rendered above the {@link notes} reference-link list. */
notesHeading?: string;
/**
* Invoked once when the toast is removed, whether it auto-hid after its timeout or was dismissed by the
- * user. Useful for resetting state that accumulated while the toast was live (see {@link noteIds}).
+ * user. Useful for resetting state that accumulated while the toast was live (see {@link notes}).
*/
onRemove?: () => void;
buttons?: {
@@ -97,7 +105,7 @@ export function showErrorForScriptNote(noteId: string, message: string, opts?: {
messageMonospace: opts?.monospace,
// The script note is shown as a reference link (icon + title, click to navigate) rather
// than a bespoke "open note" button; ctrl/middle-click still opens it in a new tab.
- noteIds: [ noteId ],
+ notes: [ noteId ],
timeout: 15_000
});
}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 75645911b8..6597c9477c 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3203,7 +3203,11 @@
"collapsible-tooltip": "Click on the arrow or press {{- shortcut}} to collapse/expand.",
"edit-states-tooltip": "Edit task states",
"unknown-task-state": "Undefined custom task state",
- "task-state-dropped": "Dropped custom task state definition \"{{title}}\" ({{id}}) due to: {{reason}}",
+ "task-state-dropped-title": "Invalid task states",
+ "task-state-dropped-message_one": "A custom task state definition is invalid and was ignored.",
+ "task-state-dropped-message_other": "{{count}} custom task state definitions are invalid and were ignored.",
+ "task-state-dropped-heading": "Ignored definitions:",
+ "task-state-dropped-configure": "Configure task states",
"validation-errors": {
"undefined-name": "undefined identifier",
"invalid-name": "invalid identifier",
diff --git a/apps/client/src/widgets/Toast.css b/apps/client/src/widgets/Toast.css
index c23965f93d..5443c102b5 100644
--- a/apps/client/src/widgets/Toast.css
+++ b/apps/client/src/widgets/Toast.css
@@ -115,6 +115,17 @@
opacity: 0.5;
margin-inline-start: 2.1em;
}
+
+ /* Annotation injected inline after the note title (see NoteLink's titleSuffix). It rides
+ the title's line; the block-level .note-path drops below both. */
+ .note-link-suffix {
+ opacity: 0.75;
+ font-size: 0.9em;
+
+ &::before {
+ content: " — ";
+ }
+ }
}
}
diff --git a/apps/client/src/widgets/Toast.spec.tsx b/apps/client/src/widgets/Toast.spec.tsx
index d7b4f44c27..225439836c 100644
--- a/apps/client/src/widgets/Toast.spec.tsx
+++ b/apps/client/src/widgets/Toast.spec.tsx
@@ -5,7 +5,13 @@ import { afterEach, describe, expect, it, vi } from "vitest";
// know that one is rendered per noteId.
vi.mock("./react/NoteLink", async () => {
const { h } = await import("preact");
- return { default: (props: { notePath: string }) => h("span", { class: "note-link-stub", "data-note-id": props.notePath }) };
+ return {
+ default: (props: { notePath: string; titleSuffix?: string }) => h(
+ "span",
+ { class: "note-link-stub", "data-note-id": props.notePath },
+ props.titleSuffix ? h("span", { class: "note-link-suffix" }, props.titleSuffix) : null
+ )
+ };
});
import { toasts, type ToastOptionsWithRequiredId } from "../services/toast";
@@ -39,7 +45,8 @@ describe("Toast rendering", () => {
message: "api.logg is not a function",
messageMonospace: true,
notesHeading: "Scripts that failed:",
- noteIds: [ "noteA", "noteB" ]
+ // One plain entry, one annotated — both render a link, only the latter a description.
+ notes: [ "noteA", { noteId: "noteB", description: "duplicate identifier" } ]
} ]);
const body = el.querySelector(".toast-body");
@@ -50,6 +57,13 @@ describe("Toast rendering", () => {
expect(notes).not.toBeNull();
expect(notes?.querySelector(".toast-notes-heading")?.textContent).toBe("Scripts that failed:");
expect(el.querySelectorAll(".note-link-stub")).toHaveLength(2);
+
+ // The annotation is injected inside the note link (as titleSuffix), not a sibling — only the
+ // annotated entry gets one, and it lives on that note's link.
+ const suffixes = el.querySelectorAll(".note-link-suffix");
+ expect(suffixes).toHaveLength(1);
+ expect(suffixes[0].textContent).toBe("duplicate identifier");
+ expect(suffixes[0].closest(".note-link-stub")?.getAttribute("data-note-id")).toBe("noteB");
});
it("omits the notes section and the monospace class when neither is provided", () => {
diff --git a/apps/client/src/widgets/Toast.tsx b/apps/client/src/widgets/Toast.tsx
index 6247733c64..a2bc6f4c1e 100644
--- a/apps/client/src/widgets/Toast.tsx
+++ b/apps/client/src/widgets/Toast.tsx
@@ -16,7 +16,7 @@ export default function ToastContainer() {
);
}
-function Toast({ id, title, timeout, progress, message, messageMonospace, icon, buttons, dismissible, wide, noteIds, notesHeading }: ToastOptionsWithRequiredId) {
+function Toast({ id, title, timeout, progress, message, messageMonospace, icon, buttons, dismissible, wide, notes, notesHeading }: ToastOptionsWithRequiredId) {
// Autohide.
useEffect(() => {
if (!timeout || timeout <= 0) return;
@@ -63,13 +63,15 @@ function Toast({ id, title, timeout, progress, message, messageMonospace, icon,
</div>
)}
- {noteIds && noteIds.length > 0 && (
+ {notes && notes.length > 0 && (
<div class="toast-notes">
{notesHeading && <div class="toast-notes-heading">{notesHeading}</div>}
<div class="toast-notes-list">
- {noteIds.map(noteId => (
- <NoteLink key={noteId} notePath={noteId} showNoteIcon noPreview showNotePath />
- ))}
+ {notes
+ .map(note => (typeof note === "string" ? { noteId: note } : note))
+ .map(({ noteId, description }) => (
+ <NoteLink key={noteId} notePath={noteId} showNoteIcon noPreview showNotePath titleSuffix={description} />
+ ))}
</div>
</div>
)}
diff --git a/apps/client/src/widgets/react/NoteLink.tsx b/apps/client/src/widgets/react/NoteLink.tsx
index c0efae5578..55505286ea 100644
--- a/apps/client/src/widgets/react/NoteLink.tsx
+++ b/apps/client/src/widgets/react/NoteLink.tsx
@@ -19,12 +19,14 @@ interface NoteLinkOpts {
highlightedTokens?: string[] | null | undefined;
// Override the text of the link, otherwise the note title is used.
title?: string;
+ /** Inline text appended right after the link title (before the note path). */
+ titleSuffix?: string;
viewScope?: ViewScope;
noContextMenu?: boolean;
onContextMenu?: (e: MouseEvent) => void;
}
-export default function NoteLink({ className, containerClassName, notePath, showNotePath, showNoteIcon, style, noPreview, noTnLink, highlightedTokens, title, viewScope, noContextMenu, onContextMenu }: NoteLinkOpts) {
+export default function NoteLink({ className, containerClassName, notePath, showNotePath, showNoteIcon, style, noPreview, noTnLink, highlightedTokens, title, titleSuffix, viewScope, noContextMenu, onContextMenu }: NoteLinkOpts) {
const stringifiedNotePath = Array.isArray(notePath) ? notePath.join("/") : notePath;
const noteId = stringifiedNotePath.split("/").at(-1);
const ref = useRef<HTMLSpanElement>(null);
@@ -35,11 +37,12 @@ export default function NoteLink({ className, containerClassName, notePath, show
useEffect(() => {
link.createLink(stringifiedNotePath, {
title,
+ titleSuffix,
showNotePath,
showNoteIcon,
viewScope
}).then(setJqueryEl);
- }, [ stringifiedNotePath, showNotePath, title, viewScope, noteTitle ]);
+ }, [ stringifiedNotePath, showNotePath, title, titleSuffix, viewScope, noteTitle ]);
useEffect(() => {
const el = jqueryEl?.[0];