Skip to content

Build your personal knowledge base with Trilium Notes

fix(client): let the window close after editing a deleted note

Elian Doran42cb910ed0ff
diff --git a/apps/client/src/widgets/note_title.spec.tsx b/apps/client/src/widgets/note_title.spec.tsx
index 6d865e486d..80fe576684 100644
--- a/apps/client/src/widgets/note_title.spec.tsx
+++ b/apps/client/src/widgets/note_title.spec.tsx
@@ -3,12 +3,16 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import Component from "../components/component";
import NoteContext from "../components/note_context";
+import froca from "../services/froca";
import protectedSessionHolder from "../services/protected_session_holder";
+import server from "../services/server";
import { buildNote } from "../test/easy-froca";
import { renderInto } from "../test/render";
import NoteTitleWidget from "./note_title";
import { NoteContextContext, ParentComponent } from "./react/react_utils";
+vi.stubGlobal("logError", vi.fn());
+
vi.mock("../services/i18n", async (importOriginal) => ({
...(await importOriginal<typeof import("../services/i18n")>()),
t: (key: string) => key
@@ -58,4 +62,37 @@ describe("NoteTitleWidget", () => {
expect(input.classList.contains("protected-title")).toBe(false);
expect(input.readOnly).toBe(false);
});
+
+ it("drops a title change to a note deleted before it saves", async () => {
+ const put = vi.spyOn(server, "put").mockRejectedValue(new Error("Note not found"));
+ const note = buildNote({ title: "Doomed" });
+ const noteContext = new NoteContext("ntx-title");
+ noteContext.noteId = note.noteId;
+ noteContext.viewScope = { viewMode: "default" };
+ const parent = new Component();
+
+ let container: HTMLElement | undefined;
+ await act(async () => {
+ container = renderInto(
+ <ParentComponent.Provider value={parent}>
+ <NoteContextContext.Provider value={noteContext}>
+ <NoteTitleWidget />
+ </NoteContextContext.Provider>
+ </ParentComponent.Provider>
+ );
+ });
+ const input = container?.querySelector<HTMLInputElement>("input.note-title");
+ expect(input?.readOnly).toBe(false);
+
+ act(() => {
+ if (!input) return;
+ input.value = "Renamed";
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ delete froca.notes[note.noteId];
+ await act(async () => {
+ await parent.handleEvent("beforeNoteSwitch", { noteContext } as never);
+ });
+ expect(put).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/client/src/widgets/note_title.tsx b/apps/client/src/widgets/note_title.tsx
index 91b8d96513..1a341e9dfc 100644
--- a/apps/client/src/widgets/note_title.tsx
+++ b/apps/client/src/widgets/note_title.tsx
@@ -5,6 +5,7 @@ import { useEffect, useRef, useState } from "preact/hooks";
import appContext from "../components/app_context";
import branches from "../services/branches";
+import froca from "../services/froca";
import { t } from "../services/i18n";
import protected_session_holder from "../services/protected_session_holder";
import server from "../services/server";
@@ -44,7 +45,8 @@ export default function NoteTitleWidget(props: {className?: string}) {
// Save changes to title.
const spacedUpdate = useSpacedUpdate(async () => {
- if (!note) {
+ // A deleted note is gone from `froca`, and the server refuses its changes.
+ if (!note || !(note.noteId in froca.notes)) {
return;
}
protected_session_holder.touchProtectedSessionIfNecessary(note);
diff --git a/apps/client/src/widgets/react/editor_save_race.spec.tsx b/apps/client/src/widgets/react/editor_save_race.spec.tsx
index 74e952ae1c..131b5b3c72 100644
--- a/apps/client/src/widgets/react/editor_save_race.spec.tsx
+++ b/apps/client/src/widgets/react/editor_save_race.spec.tsx
@@ -23,6 +23,7 @@ import Component from "../../components/component";
import NoteContext from "../../components/note_context";
import FBlob from "../../entities/fblob";
import type FNote from "../../entities/fnote";
+import froca from "../../services/froca";
import LoadResults from "../../services/load_results";
import server from "../../services/server";
import type SpacedUpdate from "../../services/spaced_update";
@@ -213,6 +214,25 @@ describe("note switch save race (#9614)", () => {
expect(editor.content).toBe("BBB");
});
+ it("drops a change to a note deleted before it saves, so the window can still close", async () => {
+ const harness = setupEditorHarness();
+ cleanupContainer = harness.container;
+ const { noteA, editor, show } = harness;
+ await show(noteA);
+ const put = vi.fn(async () => {
+ throw new Error(`Note '${noteA.noteId}' is not available for change!`);
+ });
+ server.put = put as typeof server.put;
+
+ editor.content = "AAA edited";
+ getSpacedUpdate().scheduleUpdate();
+ delete froca.notes[noteA.noteId];
+ await vi.advanceTimersByTimeAsync(1500);
+
+ expect(put).not.toHaveBeenCalled();
+ expect(getSpacedUpdate().isAllSavedAndTriggerUpdate()).toBe(true);
+ });
+
it("keeps unsaved changes when another editor saves the note, and reloads an editor without any", async () => {
const harness = setupEditorHarness({ withParent: true });
cleanupContainer = harness.container;
diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsx
index c423795a86..313bb8b905 100644
--- a/apps/client/src/widgets/react/hooks.tsx
+++ b/apps/client/src/widgets/react/hooks.tsx
@@ -162,6 +162,8 @@ export function useEditorSpacedUpdate({
// for read only notes, or if note is not yet available (e.g. lazy creation); a visitor of a
// shared page cannot save
if (data === undefined || !note || note.type !== noteType || isShare) return;
+ // A deleted note is gone from `froca`, and the server refuses its changes.
+ if (!(note.noteId in froca.notes)) return;
protected_session_holder.touchProtectedSessionIfNecessary(note);
@@ -288,7 +290,7 @@ export function useBlobEditorSpacedUpdate({ note, noteType, noteContext, getData
const commit = useCallback(async (data: Blob | undefined) => {
// for read only notes
- if (data === undefined || note.type !== noteType) return;
+ if (data === undefined || note.type !== noteType || !(note.noteId in froca.notes)) return;
protected_session_holder.touchProtectedSessionIfNecessary(note);
await server.upload(`notes/${note.noteId}/file?replace=${replaceWithoutRevision ? "1" : "0"}`, new File([ data ], note.title, { type: note.mime }), parentComponent?.componentId);
diff --git a/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.ts b/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.ts
index b8c77516da..4f3f225acc 100644
--- a/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/attachment_saves.spec.ts
@@ -1,6 +1,6 @@
import { h, render } from "preact";
import { act } from "preact/test-utils";
-import { describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import Component from "../../../components/component";
import type NoteContext from "../../../components/note_context";
@@ -18,6 +18,16 @@ vi.mock("../../../services/server", () => ({
default: { get: async () => [], post: serverPost, put: serverPut }
}));
+const frocaNotes = vi.hoisted((): Record<string, unknown> => ({}));
+vi.mock("../../../services/froca", () => ({ default: { notes: frocaNotes } }));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ for (const noteId of [ "note1", "code1" ]) {
+ frocaNotes[noteId] = {};
+ }
+});
+
const drawing = {
attachmentId: "drawing1",
ownerId: "note1",
@@ -169,6 +179,24 @@ describe("useAttachmentEditor", () => {
expect(serverPost).toHaveBeenCalledTimes(2);
expect(serverPost).toHaveBeenLastCalledWith(...savedRequest("second"));
});
+
+ it("drops the changes to a note deleted before they save", async () => {
+ component = new Component();
+ const container = document.createElement("div");
+ await act(() => {
+ render(h(ParentComponent.Provider, { value: component }, h(Probe, {})), container);
+ });
+
+ editor?.scheduleSave(drawing, () => "first");
+ delete frocaNotes.note1;
+ await act(async () => {
+ await component.handleEvent("beforeNoteSwitch", { noteContext } as never);
+ });
+ expect(serverPost).not.toHaveBeenCalled();
+ expect(editor?.getUnsavedContent("drawing1")).toBeUndefined();
+ expect(noteContext.setContextData).toHaveBeenLastCalledWith("saveState", { state: "saved" });
+ await act(() => render(null, container));
+ });
});
describe("NoteSaves", () => {
@@ -292,6 +320,24 @@ describe("useNoteEditor", () => {
expect(serverPut).toHaveBeenLastCalledWith(
"notes/code1/data", { content: "second" }, component.componentId);
});
+
+ it("drops the change to a note deleted before it saves", async () => {
+ component = new Component();
+ const container = document.createElement("div");
+ await act(() => {
+ render(h(ParentComponent.Provider, { value: component }, h(Probe, {})), container);
+ });
+
+ editor?.scheduleSave(code, () => "first");
+ delete frocaNotes.code1;
+ await act(async () => {
+ await component.handleEvent("beforeNoteSwitch", { noteContext } as never);
+ });
+ expect(serverPut).not.toHaveBeenCalled();
+ expect(editor?.getUnsavedContent("code1")).toBeUndefined();
+ expect(editor?.getSaveState("code1")).toBe("saved");
+ await act(() => render(null, container));
+ });
});
describe("InlineSourceSaves", () => {
diff --git a/apps/client/src/widgets/type_widgets/text/attachment_saves.ts b/apps/client/src/widgets/type_widgets/text/attachment_saves.ts
index 00b5c70722..cb4ac240f7 100644
--- a/apps/client/src/widgets/type_widgets/text/attachment_saves.ts
+++ b/apps/client/src/widgets/type_widgets/text/attachment_saves.ts
@@ -4,6 +4,7 @@ import type { default as NoteContext, SaveState } from "../../../components/note
import type FAttachment from "../../../entities/fattachment";
import type FNote from "../../../entities/fnote";
import type { AttachmentEditor, NoteEditor } from "../../../services/content_renderer";
+import froca from "../../../services/froca";
import protected_session_holder from "../../../services/protected_session_holder";
import server from "../../../services/server";
import SpacedUpdate from "../../../services/spaced_update";
@@ -271,6 +272,11 @@ export function useAttachmentEditor(
const prepare = useCallback(() => saves.collect(), [ saves ]);
const commit = useCallback(async (attachments: SavedAttachments) => {
+ // A deleted note is gone from `froca`, and the server refuses its changes.
+ if (!(note.noteId in froca.notes)) {
+ saves.markSaved(attachments);
+ return;
+ }
protected_session_holder.touchProtectedSessionIfNecessary(note);
for (const attachment of attachments) {
await server.post(
@@ -317,7 +323,8 @@ export function useNoteEditor(noteContext: NoteContext | null | undefined): Note
const [ spacedUpdate ] = useState(() => new SpacedUpdate<SavedNote[]>({
key: null,
prepare: () => saves.collect(),
- commit: (notes) => saves.save(notes, ({ note, content }) => {
+ commit: (notes) => saves.save(notes, async ({ note, content }) => {
+ if (!(note.noteId in froca.notes)) return;
protected_session_holder.touchProtectedSessionIfNecessary(note);
return server.put(`notes/${note.noteId}/data`, { content }, saves.componentId);
})