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(toast): support attaching reference notes to a toast
Elian Doran67d67d206bcc
diff --git a/apps/client/src/services/frontend_script_api.spec.ts b/apps/client/src/services/frontend_script_api.spec.tsindex 5ec6360d88..11f5de5566 100644--- a/apps/client/src/services/frontend_script_api.spec.ts+++ b/apps/client/src/services/frontend_script_api.spec.ts@@ -199,6 +199,44 @@ describe("runOnBackend / __runOnBackendInner", () => {expect(triggerCommand).toHaveBeenCalledWith("showOptions", { section: "_optionsSecurity" });});+ it("lists the attempting scripts as reference notes and accumulates them across attempts", async () => {+ vi.spyOn(options, "is").mockReturnValue(false);+ const showPersistent = vi.spyOn(toastService, "showPersistent").mockImplementation(() => {});+ const noteA = buildNote({ title: "Script A" });+ const noteB = buildNote({ title: "Script B" });+ const attempt = (startNote: FNote) =>+ expect(makeApi({ startNote }).runOnBackend(() => {}, [])).rejects.toBeInstanceOf(BackendScriptingDisabledError);++ // Start from a clean list: trigger one attempt then remove the toast, clearing any residue+ // accumulated by earlier tests sharing this module-level set.+ await attempt(noteA);+ showPersistent.mock.calls.at(-1)?.[0].onRemove?.();++ await attempt(noteA);+ await attempt(noteB);++ // 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?.onRemove).toBeTypeOf("function");+ });++ it("clears the accumulated scripts when the toast is removed", async () => {+ vi.spyOn(options, "is").mockReturnValue(false);+ const showPersistent = vi.spyOn(toastService, "showPersistent").mockImplementation(() => {});+ const noteA = buildNote({ title: "Script A" });+ const noteB = buildNote({ title: "Script B" });+ const attempt = (startNote: FNote) =>+ expect(makeApi({ startNote }).runOnBackend(() => {}, [])).rejects.toBeInstanceOf(BackendScriptingDisabledError);++ await attempt(noteA);+ // Simulate the toast being removed (auto-hide or dismiss) — this should reset the list.+ showPersistent.mock.calls.at(-1)?.[0].onRemove?.();++ await attempt(noteB);+ expect(showPersistent.mock.calls.at(-1)?.[0].noteIds).toEqual([ noteB.noteId ]);+ });+it("serializes a sync function, posts it, waits for sync and returns the result", async () => {const post = vi.spyOn(server, "post").mockResolvedValue({ success: true, executionResult: 42 } as never);const start = buildNote({ title: "S" });diff --git a/apps/client/src/services/frontend_script_api.ts b/apps/client/src/services/frontend_script_api.tsindex 9b55a5e62b..5683684197 100644--- a/apps/client/src/services/frontend_script_api.ts+++ b/apps/client/src/services/frontend_script_api.ts@@ -599,7 +599,7 @@ function FrontendScriptApi(this: Api, startNote: FNote, currentNote: FNote, orig// server never returns a 500, show a single deduplicated toast (fixed id) instead of one// generic HTTP-error toast per failing script, and throw a typed error callers can detect.if (!options.is("backendScriptingEnabled")) {- showBackendScriptingDisabledToast();+ showBackendScriptingDisabledToast(startNote.noteId);throw new BackendScriptingDisabledError();}@@ -819,13 +819,21 @@ export class BackendScriptingDisabledError extends Error {}}-function showBackendScriptingDisabledToast() {+// The scripts that attempted a backend call while it was disabled, accumulated so the single+// deduplicated toast can list all of them as reference links. Cleared when the toast is removed.+const backendScriptingAttempts = new Set<string>();++function showBackendScriptingDisabledToast(noteId: string) {+ backendScriptingAttempts.add(noteId);toastService.showPersistent({id: "backend-scripting-disabled",icon: "bx bx-code-block",title: t("frontend_script_api.backend_scripting_disabled_title"),message: t("frontend_script_api.backend_scripting_disabled_message"),- timeout: 15_000,+ notesHeading: t("frontend_script_api.backend_scripting_disabled_notes_heading"),+ noteIds: [ ...backendScriptingAttempts ],+ timeout: 60_000,+ onRemove: () => backendScriptingAttempts.clear(),buttons: [{text: t("frontend_script_api.backend_scripting_disabled_open_settings"),diff --git a/apps/client/src/services/toast.spec.ts b/apps/client/src/services/toast.spec.tsindex 01878449c3..3729edd9b0 100644--- a/apps/client/src/services/toast.spec.ts+++ b/apps/client/src/services/toast.spec.ts@@ -95,6 +95,25 @@ describe("toast store", () => {expect(toasts.value).toHaveLength(0);});+ it("fires onRemove exactly once when a toast is removed", () => {+ const onRemove = vi.fn();+ toast.showPersistent({ id: "with-callback", icon: "i", message: "M", onRemove });++ removeToastFromStore("with-callback");+ expect(onRemove).toHaveBeenCalledTimes(1);+ expect(toasts.value).toHaveLength(0);++ // A second removal for the same (now absent) id must not fire the callback again.+ removeToastFromStore("with-callback");+ expect(onRemove).toHaveBeenCalledTimes(1);+ });++ it("does not require onRemove and skips it for toasts without one", () => {+ toast.showPersistent({ id: "no-callback", icon: "i", message: "M" });+ expect(() => removeToastFromStore("no-callback")).not.toThrow();+ expect(toasts.value).toHaveLength(0);+ });+it("showErrorForScriptNote uses note title/icon and wires the open-script button", async () => {const note = buildNote({ title: "My Script" });// Force a deterministic icon for assertion.diff --git a/apps/client/src/services/toast.ts b/apps/client/src/services/toast.tsindex 68d90f5df8..d404495fd9 100644--- a/apps/client/src/services/toast.ts+++ b/apps/client/src/services/toast.ts@@ -18,6 +18,18 @@ export interface ToastOptions {* dismissable × there reads as "cancel", which it isn't. Defaults to dismissable.*/dismissible?: 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.+ */+ noteIds?: string[];+ /** Optional heading rendered above the {@link noteIds} 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}).+ */+ onRemove?: () => void;buttons?: {text: string;onClick: (api: { dismissToast: () => void }) => void;@@ -108,6 +120,14 @@ function updateToast(id: string, partial: Partial<ToastOptions>) {}export function removeToastFromStore(id: string) {+ // Centralized removal point, so onRemove fires exactly once regardless of the removal path+ // (auto-hide timeout, close button, or closePersistent). find-then-filter guards against a+ // double fire when both the timeout and a manual dismiss race for the same id.+ const removed = toasts.value.find(toast => toast.id === id);+ if (!removed) {+ return;+ }+ removed.onRemove?.();toasts.value = toasts.value.filter(toast => toast.id !== id);}//#endregiondiff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex a68aba7e83..05bec9bfb7 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2402,6 +2402,7 @@"sync_warning": "You're passing a synchronous function to `api.runAsyncOnBackendWithManualTransactionHandling()`,\\nwhile you should likely use `api.runOnBackend()` instead.","backend_scripting_disabled_title": "Backend scripting is disabled","backend_scripting_disabled_message": "A script tried to run code on the server, but backend scripting is turned off for security reasons. Enable it in Options → Security if you trust this script.",+ "backend_scripting_disabled_notes_heading": "Scripts that tried to run backend code:","backend_scripting_disabled_open_settings": "Open security settings"},"ws": {diff --git a/apps/client/src/widgets/Toast.css b/apps/client/src/widgets/Toast.cssindex aef8727f3b..26d5ef5287 100644--- a/apps/client/src/widgets/Toast.css+++ b/apps/client/src/widgets/Toast.css@@ -78,6 +78,32 @@}}+ .toast-notes {+ padding: 0 var(--bs-toast-padding-x) var(--bs-toast-padding-y) var(--bs-toast-padding-x);+ user-select: text;++ .toast-notes-heading {+ opacity: 0.75;+ margin-bottom: 0.25em;+ }++ .toast-notes-list {+ display: flex;+ flex-direction: column;+ gap: 0.15em;++ a {+ color: inherit;+ }++ .note-path {+ display: block;+ opacity: 0.5;+ margin-inline-start: 2.1em;+ }+ }+ }+.toast-progress {position: absolute;bottom: 0;@@ -88,4 +114,3 @@transition: width 0.1s linear;}}-diff --git a/apps/client/src/widgets/Toast.tsx b/apps/client/src/widgets/Toast.tsxindex 4553313807..58de016084 100644--- a/apps/client/src/widgets/Toast.tsx+++ b/apps/client/src/widgets/Toast.tsx@@ -6,6 +6,7 @@ import { useEffect } from "preact/hooks";import { removeToastFromStore, ToastOptionsWithRequiredId, toasts } from "../services/toast";import Button from "./react/Button";import Icon from "./react/Icon";+import NoteLink from "./react/NoteLink";export default function ToastContainer() {return (@@ -15,7 +16,7 @@ export default function ToastContainer() {);}-function Toast({ id, title, timeout, progress, message, icon, buttons, dismissible }: ToastOptionsWithRequiredId) {+function Toast({ id, title, timeout, progress, message, icon, buttons, dismissible, noteIds, notesHeading }: ToastOptionsWithRequiredId) {// Autohide.useEffect(() => {if (!timeout || timeout <= 0) return;@@ -62,6 +63,17 @@ function Toast({ id, title, timeout, progress, message, icon, buttons, dismissib</div>)}+ {noteIds && noteIds.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 />+ ))}+ </div>+ </div>+ )}+{buttons && (<div class="toast-buttons">{buttons.map(({ text, onClick }) => (