Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix(web): open internal note links in the target notebook (#581)

Thorsten Ruf640f9739974f
diff --git a/apps/web/src/components/EditorPaneErrorBoundary.test.mjs b/apps/web/src/components/EditorPaneErrorBoundary.test.mjs
index f637696d..ca8df625 100644
--- a/apps/web/src/components/EditorPaneErrorBoundary.test.mjs
+++ b/apps/web/src/components/EditorPaneErrorBoundary.test.mjs
@@ -16,7 +16,7 @@ describe("note editor failure containment", () => {
expect(rootBoundarySource).toContain("markRendererRecoveryRequired()");
expect(workspaceSource).toContain("rendererRecoveryMode ? null : selectedMemoId ?? memos[0]?.id ?? null");
- expect(workspaceSource).toContain("if (rendererRecoveryMode) {");
+ expect(workspaceSource).toContain("useMemoSelectionReconciliation({");
expect(workspaceSource).toContain("<EditorRecoveryPane />");
});
});
diff --git a/apps/web/src/components/WorkspaceApp.tsx b/apps/web/src/components/WorkspaceApp.tsx
index b47fa184..28ad24ed 100644
--- a/apps/web/src/components/WorkspaceApp.tsx
+++ b/apps/web/src/components/WorkspaceApp.tsx
@@ -123,6 +123,8 @@ import { useWorkspaceRoute } from "@/hooks/useWorkspaceRoute";
import { useNoteProse } from "@/hooks/useNoteProse";
import { useWorkspacePreferences } from "@/hooks/useWorkspacePreferences";
import { useWorkspaceSelection } from "@/hooks/useWorkspaceSelection";
+import { useMemoLinkNavigation } from "@/hooks/useMemoLinkNavigation";
+import { useMemoSelectionReconciliation } from "@/hooks/useMemoSelectionReconciliation";
import { useNotebookSelectionReconciliation } from "@/hooks/useNotebookSelectionReconciliation";
import { useWorkspaceQueuedSync } from "@/hooks/useWorkspaceQueuedSync";
import { useWorkspaceMemoRemoval } from "@/hooks/useWorkspaceMemoRemoval";
@@ -240,7 +242,7 @@ export const WorkspaceApp = ({
const autoSelectedDemoNotebookRef = useRef(false);
const [createdMemoEditId, setCreatedMemoEditId] = useState<string | null>(null);
const pendingCreatedMemoIdRef = useRef<string | null>(null);
- const pendingQuickSwitcherMemoIdRef = useRef<string | null>(desktopWorkspaceRestore?.selectedMemoId ?? null); // also companion/plugin opens not yet in the list
+ const pendingQuickSwitcherMemoIdRef = useRef<string | null>(desktopWorkspaceRestore?.selectedMemoId ?? null); // also link/companion/plugin opens not yet in the list
useEffect(() => {
if (!window.edgeeverDesktop?.isAvailable) return;
writeDesktopWorkspaceRestoreState({
@@ -1061,10 +1063,7 @@ export const WorkspaceApp = ({
});
const showDescendantNotes = useShowDescendantNotesPreference();
- useEffect(() => {
- // A changed scope must not retain hidden notes in bulk actions.
- clearMemoSelection();
- }, [showDescendantNotes, clearMemoSelection]);
+ const previousShowDescendantNotesRef = useRef(showDescendantNotes);
const selectedNotebookScopeIds = useMemo(
() => (selectedNotebookId && !selectedTag ? getNotebookScopeIds(notebooks, selectedNotebookId, showDescendantNotes) : []),
[notebooks, selectedNotebookId, selectedTag, showDescendantNotes]
@@ -1126,40 +1125,25 @@ export const WorkspaceApp = ({
selectedMemoIndex >= 0 && selectedMemoIndex < memos.length - 1 ? memos[selectedMemoIndex + 1]?.id : null;
const detailMemoId = rendererRecoveryMode ? null : selectedMemoId ?? memos[0]?.id ?? null;
- useEffect(() => {
- const selectedMemoInList = selectedMemoId ? memos.some((memo) => memo.id === selectedMemoId) : false;
-
- if (rendererRecoveryMode) {
- return;
- }
-
- if (creatingMemoSelectionRef.current || pendingCreatedMemoIdRef.current) {
- return;
- }
-
- if (pendingQuickSwitcherMemoIdRef.current) {
- if (!memos.some((memo) => memo.id === pendingQuickSwitcherMemoIdRef.current)) {
- return;
- }
- pendingQuickSwitcherMemoIdRef.current = null;
- }
-
- if (createdMemoEditId && selectedMemoId === createdMemoEditId) {
- // Keep the create request alive until the editor consumes it. The new
- // memo can appear in the list before its detail query has mounted the
- // editor, and clearing it here would lose the autofocus request.
- return;
- }
-
- if (memos.length === 0) {
- setSelectedMemoId(null);
- return;
- }
+ const clearPendingMemoSelection = useMemoSelectionReconciliation({
+ memos,
+ selectedMemoId,
+ setSelectedMemoId,
+ rendererRecoveryMode,
+ creatingMemoSelectionRef,
+ pendingCreatedMemoIdRef,
+ pendingOpenedMemoIdRef: pendingQuickSwitcherMemoIdRef,
+ createdMemoEditId,
+ });
- if (!selectedMemoId || !selectedMemoInList) {
- setSelectedMemoId(memos[0].id);
+ useEffect(() => {
+ // A changed scope must not retain hidden notes in single or bulk selection.
+ clearMemoSelection();
+ if (previousShowDescendantNotesRef.current !== showDescendantNotes) {
+ previousShowDescendantNotesRef.current = showDescendantNotes;
+ clearPendingMemoSelection();
}
- }, [createdMemoEditId, memos, rendererRecoveryMode, selectedMemoId]);
+ }, [showDescendantNotes, clearMemoSelection, clearPendingMemoSelection]);
useEffect(() => {
if (!rendererRecoveryMode || !selectedMemoId) return;
@@ -1213,6 +1197,7 @@ export const WorkspaceApp = ({
const createNotebookMutation = useMutation({
mutationFn: repository.createNotebook,
onSuccess: async (data) => {
+ clearPendingMemoSelection();
setSelectedTag(null);
setSelectedNotebookId(data.notebook.id);
setActivePane("memos");
@@ -2357,10 +2342,12 @@ export const WorkspaceApp = ({
};
const handleSelectNotebook = (notebookId: string) => {
+ clearPendingMemoSelection();
navigateWorkspaceHome();
setMemoView("notebook");
setSelectedTag(null);
setSelectedNotebookId(notebookId);
+ setRightView("editor");
setMobileBottomNavActive("home");
clearMemoSelection();
clearPendingCreatedMemo();
@@ -2370,6 +2357,7 @@ export const WorkspaceApp = ({
};
const handleSelectAllMemos = () => {
+ clearPendingMemoSelection();
navigateWorkspaceHome();
setMemoView("notebook");
setSelectedTag(null);
@@ -2384,6 +2372,7 @@ export const WorkspaceApp = ({
};
const handleMobileHome = () => {
+ clearPendingMemoSelection();
navigateWorkspaceHome();
if (memoView === "trash") {
setMemoView("notebook");
@@ -2399,6 +2388,7 @@ export const WorkspaceApp = ({
};
const handleSelectTag = (tag: string) => {
+ clearPendingMemoSelection();
navigateWorkspaceHome();
setMemoView("notebook");
setSelectedTag(tag);
@@ -2419,6 +2409,7 @@ export const WorkspaceApp = ({
}, []);
const handleGlobalSearch = useCallback(() => {
+ clearPendingMemoSelection();
navigateWorkspaceHome();
setMemoView("notebook");
setSelectedTag(null);
@@ -2427,7 +2418,7 @@ export const WorkspaceApp = ({
setRightView("editor");
clearMemoSelection();
handleMobileSearch();
- }, [clearMemoSelection, handleMobileSearch, navigateWorkspaceHome, setSelectedNotebookId]);
+ }, [clearMemoSelection, clearPendingMemoSelection, handleMobileSearch, navigateWorkspaceHome, setSelectedNotebookId]);
const handleOpenQuickSwitcherMemo = useCallback((memo: MemoSummary) => {
pendingQuickSwitcherMemoIdRef.current = memo.id;
@@ -2471,6 +2462,22 @@ export const WorkspaceApp = ({
}
}, [clearMemoSelection, clearPendingCreatedMemo, navigateWorkspaceHome, setSelectedMemoId, setSelectedNotebookId]);
+ const handleOpenLinkedMemo = useMemoLinkNavigation({
+ repository,
+ navigationScope: JSON.stringify([
+ route.pathname, route.search, memoView, selectedNotebookId, selectedMemoId,
+ selectedTag, search, memoFilterMode, activePane, rightView,
+ ]),
+ onOpen: (memo) => {
+ cacheMemoDetail(queryClient, memo, "notebook");
+ handleOpenPluginNote(memo.id, memo.notebookId);
+ },
+ onError: () => setAppNoticeDialog({
+ title: t("memoList.openMemo"),
+ description: t("workspaceDialogs.openMemoFailed"),
+ }),
+ });
+
useEffect(() => pluginHost.setNavigationAdapter({ openNote: handleOpenPluginNote }), [handleOpenPluginNote, pluginHost]);
useEffect(() => {
@@ -2480,12 +2487,28 @@ export const WorkspaceApp = ({
}, [pluginNavigationRequest, selectedMemoId]);
const handleCancelMobileSearch = () => {
+ clearPendingMemoSelection();
setSearch("");
setMobileBottomNavActive("home");
clearMemoSelection();
setActivePane("memos");
};
+ const handleSearchChange = (query: string) => {
+ if (query !== search) clearPendingMemoSelection();
+ setSearch(query);
+ };
+
+ const handleFilterModeChange = (mode: MemoFilterMode) => {
+ if (mode !== memoFilterMode) clearPendingMemoSelection();
+ setMemoFilterMode(mode);
+ };
+
+ const handleSortModeChange = (mode: MemoSortMode) => {
+ if (mode !== memoSortMode) clearPendingMemoSelection();
+ setMemoSortMode(mode);
+ };
+
const clearHiddenMobileSearch = () => {
if (!isDesktopViewport()) {
setSearch("");
@@ -2621,10 +2644,7 @@ export const WorkspaceApp = ({
if (command.startsWith("open-memo:")) {
const memoId = command.slice("open-memo:".length);
if (memoId) {
- navigateWorkspaceHome();
- setMemoView("notebook");
- setSelectedMemoId(memoId);
- setActivePane("editor");
+ void handleOpenLinkedMemo(memoId);
}
}
});
@@ -2649,7 +2669,7 @@ export const WorkspaceApp = ({
removeMarkdownListener();
removeScreenshotListener();
};
- }, [createMemoMutation, defaultMemoNotebookId, handleCreateMemo, handleCreateNotebook, handleGlobalSearch, notebooks, selectedNotebookId, toggleDesktopFocusMode]);
+ }, [createMemoMutation, defaultMemoNotebookId, handleCreateMemo, handleCreateNotebook, handleGlobalSearch, handleOpenLinkedMemo, notebooks, selectedNotebookId, toggleDesktopFocusMode]);
const handleWorkspaceBackRequest = useCallback(() => {
if (appNoticeDialog) {
@@ -3214,15 +3234,7 @@ export const WorkspaceApp = ({
view={memoView}
canCreateMemo={canCreateMemo}
isCreatingMemo={createMemoMutation.isPending}
- onSelect={(notebookId) => {
- navigateWorkspaceHome();
- setMemoView("notebook");
- setSelectedTag(null);
- setSelectedNotebookId(notebookId);
- clearMemoSelection();
- setRightView("editor");
- setActivePane("memos");
- }}
+ onSelect={handleSelectNotebook}
onCreateMemo={handleCreateMemo}
onCreateNotebook={handleCreateNotebook}
onRenameNotebook={handleRenameNotebook}
@@ -3246,6 +3258,7 @@ export const WorkspaceApp = ({
onOpenPluginManager={handleOpenPluginManager}
onOpenSettings={handleOpenSettings}
onOpenTrash={() => {
+ clearPendingMemoSelection();
navigateWorkspaceTrash();
setMemoView("trash");
setSelectedTag(null);
@@ -3309,8 +3322,8 @@ export const WorkspaceApp = ({
sortMode={memoSortMode}
mobileSearchActive={mobileSearchActive}
searchFocusToken={mobileSearchFocusToken}
- onFilterModeChange={setMemoFilterMode}
- onSortModeChange={setMemoSortMode}
+ onFilterModeChange={handleFilterModeChange}
+ onSortModeChange={handleSortModeChange}
onLoadMoreMemos={handleLoadMoreMemos}
canCreateMemo={canCreateMemo}
isLoading={memosQuery.isLoading}
@@ -3325,7 +3338,7 @@ export const WorkspaceApp = ({
multiSelectKeyDown={multiSelectKeyDown}
onRetry={() => void memosQuery.refetch()}
onOpenNotebookPicker={() => setMobileNotebookPickerOpen(true)}
- onSearch={setSearch}
+ onSearch={handleSearchChange}
onCancelMobileSearch={handleCancelMobileSearch}
onCreateMemo={handleCreateMemo}
onImportMarkdownFiles={(files) => void handleImportMarkdownFiles(files)}
@@ -3339,6 +3352,7 @@ export const WorkspaceApp = ({
isSyncingMemos={isManualMemoSyncing || isSyncingQueuedChanges || isPullRefreshing || memosQuery.isRefetching}
canSyncMemos={isOnline}
onOpenTrash={() => {
+ clearPendingMemoSelection();
navigateWorkspaceTrash();
setMemoView("trash");
setSelectedTag(null);
@@ -3353,6 +3367,7 @@ export const WorkspaceApp = ({
onBackFromTrash={handleSelectAllMemos}
onClearTag={handleSelectAllMemos}
onOpenMemo={(memoId) => {
+ clearPendingMemoSelection();
if (shouldNavigateHomeWhenOpeningMemo(memoView)) {
navigateWorkspaceHome();
}
@@ -3383,6 +3398,7 @@ export const WorkspaceApp = ({
onRestoreMemo={handleRestoreMemoFromList}
onMoveMemo={handleMoveMemoFromList}
onRequestDocumentAction={(memoId: string, action: MemoDocumentAction, printWindow?: Window | null) => {
+ clearPendingMemoSelection();
if (shouldNavigateHomeWhenOpeningMemo(memoView)) {
navigateWorkspaceHome();
}
@@ -3713,12 +3729,7 @@ export const WorkspaceApp = ({
onDocumentActionConsumed={(requestId) => {
setMemoDocumentActionRequest((current) => current?.id === requestId ? null : current);
}}
- onOpenMemo={(memoId) => {
- clearPendingCreatedMemo();
- setMemoView("notebook");
- setSelectedMemoId(memoId);
- setActivePane("editor");
- }}
+ onOpenMemo={handleOpenLinkedMemo}
imageCompressionEnabled={imageCompressionEnabled}
selectionActionBar={memoSelectionActionBar}
onBackToList={() => {
diff --git a/apps/web/src/hooks/useMemoLinkNavigation.test.mjs b/apps/web/src/hooks/useMemoLinkNavigation.test.mjs
new file mode 100644
index 00000000..d612059b
--- /dev/null
+++ b/apps/web/src/hooks/useMemoLinkNavigation.test.mjs
@@ -0,0 +1,169 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { act, createElement } from "react";
+import { createRoot } from "react-dom/client";
+import { parseHTML } from "linkedom";
+import { useMemoLinkNavigation } from "./useMemoLinkNavigation.ts";
+
+const globals = ["window", "document", "IS_REACT_ACT_ENVIRONMENT"];
+const originals = new Map(globals.map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
+let root;
+
+afterEach(async () => {
+ if (root) await act(async () => root.unmount());
+ root = undefined;
+ for (const [key, descriptor] of originals) {
+ if (descriptor) Object.defineProperty(globalThis, key, descriptor);
+ else delete globalThis[key];
+ }
+});
+
+const deferred = () => {
+ let resolve;
+ let reject;
+ const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
+ return { promise, resolve, reject };
+};
+
+const mount = async () => {
+ const { window } = parseHTML("<html><body><div id='root'></div></body></html>");
+ globalThis.window = window;
+ globalThis.document = window.document;
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true;
+ root = createRoot(window.document.getElementById("root"));
+ const requests = [];
+ const opened = [];
+ let errors = 0;
+ let openLink;
+ const repository = {
+ getMemo(id) {
+ const request = { id, ...deferred() };
+ requests.push(request);
+ return request.promise;
+ },
+ };
+ const Harness = ({ scope, repo }) => {
+ openLink = useMemoLinkNavigation({
+ repository: repo,
+ navigationScope: scope,
+ onOpen: (memo) => opened.push(memo),
+ onError: () => { errors += 1; },
+ });
+ return null;
+ };
+ const render = async (scope = "source-notebook/source-memo", repo = repository) => {
+ await act(async () => root.render(createElement(Harness, { scope, repo })));
+ };
+ await render();
+ return { render, requests, opened, errors: () => errors, open: (id) => openLink(id) };
+};
+
+describe("internal memo link navigation", () => {
+ test("resolves a target outside the current notebook/list before opening it", async () => {
+ const h = await mount();
+ const target = { id: "target", notebookId: "other-notebook", isDeleted: false };
+ const opening = h.open(target.id);
+ expect(h.requests.map((r) => r.id)).toEqual(["target"]);
+ expect(h.opened).toEqual([]);
+ await act(async () => {
+ h.requests[0].resolve({ memo: target });
+ await opening;
+ });
+ expect(h.opened).toEqual([target]);
+ expect(h.errors()).toBe(0);
+ });
+
+ test("the latest click wins when link targets finish loading out of order", async () => {
+ const h = await mount();
+ const first = h.open("first");
+ const second = h.open("second");
+ await act(async () => {
+ h.requests[1].resolve({ memo: { id: "second", notebookId: "second-notebook" } });
+ await second;
+ h.requests[0].resolve({ memo: { id: "first", notebookId: "first-notebook" } });
+ await first;
+ });
+ expect(h.opened.map((m) => m.id)).toEqual(["second"]);
+ });
+
+ test("ignores a late response after the user changes notebook and returns", async () => {
+ const h = await mount();
+ const opening = h.open("target");
+ await h.render("another-notebook/another-memo");
+ await h.render();
+ await act(async () => {
+ h.requests[0].resolve({ memo: { id: "target", notebookId: "other-notebook" } });
+ await opening;
+ });
+ expect(h.opened).toEqual([]);
+ });
+
+ test("an ordinary rerender while a link loads does not cancel it", async () => {
+ const h = await mount();
+ const opening = h.open("target");
+ await h.render();
+ await act(async () => {
+ h.requests[0].resolve({ memo: { id: "target", notebookId: "other-notebook" } });
+ await opening;
+ });
+ expect(h.opened.map((m) => m.id)).toEqual(["target"]);
+ });
+
+ test("keeps the current editor and reports missing targets and load errors", async () => {
+ const h = await mount();
+ const opening = h.open("missing");
+ await act(async () => {
+ h.requests[0].reject(new Error("404 or offline"));
+ await opening;
+ });
+ expect(h.opened).toEqual([]);
+ expect(h.errors()).toBe(1);
+ });
+
+ test("does not open a deleted target returned by a local repository", async () => {
+ const h = await mount();
+ const opening = h.open("deleted");
+ await act(async () => {
+ h.requests[0].resolve({ memo: { id: "deleted", notebookId: "other-notebook", isDeleted: true } });
+ await opening;
+ });
+ expect(h.opened).toEqual([]);
+ expect(h.errors()).toBe(1);
+ });
+
+ test("suppresses stale errors after a newer link was opened", async () => {
+ const h = await mount();
+ const first = h.open("first");
+ const second = h.open("second");
+ await act(async () => {
+ h.requests[0].reject(new Error("offline"));
+ await first;
+ h.requests[1].resolve({ memo: { id: "second", notebookId: "second-notebook" } });
+ await second;
+ });
+ expect(h.opened.map((m) => m.id)).toEqual(["second"]);
+ expect(h.errors()).toBe(0);
+ });
+
+ test("ignores pending targets from an account/repository that was replaced", async () => {
+ const h = await mount();
+ const opening = h.open("target");
+ await h.render("source-notebook/source-memo", { getMemo: async () => { throw new Error("other account"); } });
+ await act(async () => {
+ h.requests[0].resolve({ memo: { id: "target", notebookId: "other-notebook" } });
+ await opening;
+ });
+ expect(h.opened).toEqual([]);
+ expect(h.errors()).toBe(0);
+ });
+
+ test("does not navigate or display a late error after unmount", async () => {
+ const h = await mount();
+ const opening = h.open("target");
+ await act(async () => root.unmount());
+ root = undefined;
+ h.requests[0].reject(new Error("offline"));
+ await opening;
+ expect(h.opened).toEqual([]);
+ expect(h.errors()).toBe(0);
+ });
+});
diff --git a/apps/web/src/hooks/useMemoLinkNavigation.ts b/apps/web/src/hooks/useMemoLinkNavigation.ts
new file mode 100644
index 00000000..fa5e1436
--- /dev/null
+++ b/apps/web/src/hooks/useMemoLinkNavigation.ts
@@ -0,0 +1,45 @@
+import { useCallback, useEffect, useRef } from "react";
+import type { MemoDetail } from "@edgeever/shared";
+import type { EdgeEverRepository } from "@/lib/repository";
+
+// Resolve the notebook through the repository, not through the current (possibly
+// filtered or paginated) list. Keep the current editor until the target is ready.
+export const useMemoLinkNavigation = ({
+ repository,
+ navigationScope,
+ onOpen,
+ onError,
+}: {
+ repository: Pick<EdgeEverRepository, "getMemo">;
+ navigationScope: string;
+ onOpen: (memo: MemoDetail) => void;
+ onError: () => void;
+}) => {
+ const requestIdRef = useRef(0);
+ const latestRef = useRef({ repository, navigationScope, onOpen, onError });
+ latestRef.current = { repository, navigationScope, onOpen, onError };
+
+ // A notebook/list selection, account change, or unmount cancels an unresolved
+ // link so a late response cannot navigate away from the user's newer choice.
+ useEffect(() => () => { requestIdRef.current += 1; }, [repository, navigationScope]);
+
+ return useCallback(async (memoId: string) => {
+ const requestId = ++requestIdRef.current;
+ const origin = latestRef.current;
+ const isCurrent = () => requestId === requestIdRef.current
+ && origin.repository === latestRef.current.repository
+ && origin.navigationScope === latestRef.current.navigationScope;
+
+ try {
+ const { memo } = await origin.repository.getMemo(memoId);
+ if (!isCurrent()) return;
+ if (memo.isDeleted) {
+ latestRef.current.onError();
+ return;
+ }
+ latestRef.current.onOpen(memo);
+ } catch {
+ if (isCurrent()) latestRef.current.onError();
+ }
+ }, []);
+};
diff --git a/apps/web/src/hooks/useMemoSelectionReconciliation.test.mjs b/apps/web/src/hooks/useMemoSelectionReconciliation.test.mjs
new file mode 100644
index 00000000..1e3bfbfb
--- /dev/null
+++ b/apps/web/src/hooks/useMemoSelectionReconciliation.test.mjs
@@ -0,0 +1,170 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { act, createElement, useMemo, useRef, useState } from "react";
+import { createRoot } from "react-dom/client";
+import { parseHTML } from "linkedom";
+import { useMemoLinkNavigation } from "./useMemoLinkNavigation.ts";
+import { useMemoSelectionReconciliation } from "./useMemoSelectionReconciliation.ts";
+
+const globals = ["window", "document", "IS_REACT_ACT_ENVIRONMENT"];
+const originals = new Map(globals.map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
+let root;
+afterEach(async () => {
+ if (root) await act(async () => root.unmount());
+ root = undefined;
+ for (const [key, descriptor] of originals) {
+ if (descriptor) Object.defineProperty(globalThis, key, descriptor);
+ else delete globalThis[key];
+ }
+});
+
+const source = { id: "source", notebookId: "A" };
+const target = { id: "target-on-later-page", notebookId: "B", isDeleted: false };
+const firstB = { id: "first-B", notebookId: "B" };
+const firstC = { id: "first-C", notebookId: "C" };
+
+const mount = async (options = {}) => {
+ const { window } = parseHTML("<html><body><div id='root'></div></body></html>");
+ globalThis.window = window;
+ globalThis.document = window.document;
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true;
+ root = createRoot(window.document.getElementById("root"));
+ const repository = { getMemo: async () => ({ memo: target }) };
+ let api;
+ let lists = { A: [source], B: [firstB], C: [firstC], empty: [] };
+
+ const Harness = ({ lists }) => {
+ const [notebookId, setNotebookId] = useState("A");
+ const [selectedMemoId, setSelectedMemoId] = useState(options.initialMemoId === undefined ? source.id : options.initialMemoId);
+ const [filter, setFilter] = useState("");
+ const memos = useMemo(() => lists[filter || notebookId] ?? [], [lists, filter, notebookId]);
+ const pendingOpenedMemoIdRef = useRef(null);
+ const pendingCreatedMemoIdRef = useRef(options.pendingCreatedMemoId ?? null);
+ const creatingMemoSelectionRef = useRef(false);
+ const clearPendingMemoSelection = useMemoSelectionReconciliation({
+ memos, selectedMemoId, setSelectedMemoId,
+ rendererRecoveryMode: options.rendererRecoveryMode ?? false,
+ createdMemoEditId: options.createdMemoEditId ?? null,
+ pendingOpenedMemoIdRef, pendingCreatedMemoIdRef, creatingMemoSelectionRef,
+ });
+ const openLink = useMemoLinkNavigation({
+ repository,
+ navigationScope: JSON.stringify([notebookId, selectedMemoId, filter]),
+ onOpen: (memo) => {
+ pendingOpenedMemoIdRef.current = memo.id;
+ setNotebookId(memo.notebookId);
+ setFilter("");
+ setSelectedMemoId(memo.id);
+ },
+ onError: () => { throw new Error("Unexpected link error"); },
+ });
+ api = {
+ openLink,
+ selectNotebook(id) {
+ clearPendingMemoSelection();
+ setNotebookId(id);
+ },
+ changeFilter(value) {
+ clearPendingMemoSelection();
+ setFilter(value);
+ },
+ notebookId, selectedMemoId,
+ pendingId: () => pendingOpenedMemoIdRef.current,
+ };
+ return createElement("div", null, `${notebookId}:${selectedMemoId ?? "none"}`);
+ };
+ const render = async () => {
+ await act(async () => root.render(createElement(Harness, { lists })));
+ };
+ await render();
+ return {
+ state: () => api,
+ openTarget: async () => { await act(async () => api.openLink(target.id)); },
+ selectNotebook: async (id) => { await act(async () => api.selectNotebook(id)); },
+ changeFilter: async (filter) => { await act(async () => api.changeFilter(filter)); },
+ updateList: async (key, memos) => { lists = { ...lists, [key]: memos }; await render(); },
+ };
+};
+
+describe("pending linked-note selection and list reconciliation", () => {
+ test("A → B link outside B's first page → C selects C's note without loading more", async () => {
+ const h = await mount();
+ await h.openTarget();
+ expect(h.state().notebookId).toBe("B");
+ expect(h.state().selectedMemoId).toBe(target.id);
+ expect(h.state().pendingId()).toBe(target.id);
+
+ await h.selectNotebook("C");
+ expect(h.state().notebookId).toBe("C");
+ expect(h.state().pendingId()).toBeNull();
+ expect(h.state().selectedMemoId).toBe(firstC.id);
+ });
+
+ test("an empty destination clears the old linked note from the editor", async () => {
+ const h = await mount();
+ await h.openTarget();
+ await h.selectNotebook("empty");
+ expect(h.state().pendingId()).toBeNull();
+ expect(h.state().selectedMemoId).toBeNull();
+ });
+
+ test("explicitly reselecting B releases the guard even when its list is unchanged", async () => {
+ const h = await mount();
+ await h.openTarget();
+ await h.selectNotebook("B");
+ expect(h.state().pendingId()).toBeNull();
+ expect(h.state().selectedMemoId).toBe(firstB.id);
+ });
+
+ test("a deliberate filter change reconciles to that filter's results", async () => {
+ const h = await mount();
+ const filtered = { id: "matching-B", notebookId: "B" };
+ await h.updateList("search-results", [filtered]);
+ await h.openTarget();
+ await h.changeFilter("search-results");
+ expect(h.state().notebookId).toBe("B");
+ expect(h.state().pendingId()).toBeNull();
+ expect(h.state().selectedMemoId).toBe(filtered.id);
+ });
+
+ test("the programmatic link transition stays protected while B loads and paginates", async () => {
+ const h = await mount();
+ await h.openTarget();
+ await h.updateList("B", []);
+ expect(h.state().selectedMemoId).toBe(target.id);
+ expect(h.state().pendingId()).toBe(target.id);
+ await h.updateList("B", [firstB]);
+ expect(h.state().selectedMemoId).toBe(target.id);
+ expect(h.state().pendingId()).toBe(target.id);
+ await h.updateList("B", [firstB, target]);
+ expect(h.state().selectedMemoId).toBe(target.id);
+ expect(h.state().pendingId()).toBeNull();
+ });
+
+ test("ordinary list changes without a pending link retain a visible selected note", async () => {
+ const h = await mount();
+ await h.selectNotebook("C");
+ await h.updateList("C", [{ id: "new-first-C", notebookId: "C" }, firstC]);
+ expect(h.state().selectedMemoId).toBe(firstC.id);
+ });
+
+ test("renderer recovery never automatically selects the first available note", async () => {
+ const h = await mount({ rendererRecoveryMode: true, initialMemoId: null });
+ expect(h.state().selectedMemoId).toBeNull();
+ await h.updateList("A", [{ id: "another-A", notebookId: "A" }]);
+ expect(h.state().selectedMemoId).toBeNull();
+ });
+
+ test("an in-flight created note remains selected before its list entry arrives", async () => {
+ const h = await mount({ initialMemoId: "new-note", pendingCreatedMemoId: "new-note" });
+ expect(h.state().selectedMemoId).toBe("new-note");
+ await h.updateList("A", []);
+ expect(h.state().selectedMemoId).toBe("new-note");
+ });
+
+ test("a created note waiting for editor autofocus is not replaced by the first list note", async () => {
+ const h = await mount({ initialMemoId: "new-note", createdMemoEditId: "new-note" });
+ expect(h.state().selectedMemoId).toBe("new-note");
+ await h.updateList("A", [{ id: "another-A", notebookId: "A" }]);
+ expect(h.state().selectedMemoId).toBe("new-note");
+ });
+});
diff --git a/apps/web/src/hooks/useMemoSelectionReconciliation.ts b/apps/web/src/hooks/useMemoSelectionReconciliation.ts
new file mode 100644
index 00000000..b443fe0c
--- /dev/null
+++ b/apps/web/src/hooks/useMemoSelectionReconciliation.ts
@@ -0,0 +1,53 @@
+import { useCallback, useEffect, type RefObject } from "react";
+
+export const useMemoSelectionReconciliation = ({
+ memos,
+ selectedMemoId,
+ setSelectedMemoId,
+ rendererRecoveryMode,
+ creatingMemoSelectionRef,
+ pendingCreatedMemoIdRef,
+ pendingOpenedMemoIdRef,
+ createdMemoEditId,
+}: {
+ memos: ReadonlyArray<{ id: string }>;
+ selectedMemoId: string | null;
+ setSelectedMemoId: (id: string | null) => void;
+ rendererRecoveryMode: boolean;
+ creatingMemoSelectionRef: RefObject<boolean>;
+ pendingCreatedMemoIdRef: RefObject<string | null>;
+ pendingOpenedMemoIdRef: RefObject<string | null>;
+ createdMemoEditId: string | null;
+}) => {
+ // Call only for explicit list/notebook actions, never for a programmatic
+ // note open: its guard must survive the destination list's first page.
+ const clearPendingMemoSelection = useCallback(() => {
+ if (!pendingOpenedMemoIdRef.current) return;
+ pendingOpenedMemoIdRef.current = null;
+ // Reconcile even when the user reselects the same notebook/list identity.
+ setSelectedMemoId(null);
+ }, [pendingOpenedMemoIdRef, setSelectedMemoId]);
+
+ useEffect(() => {
+ const selectedMemoInList = selectedMemoId ? memos.some((memo) => memo.id === selectedMemoId) : false;
+ if (rendererRecoveryMode) return;
+ if (creatingMemoSelectionRef.current || pendingCreatedMemoIdRef.current) return;
+
+ if (pendingOpenedMemoIdRef.current) {
+ if (!memos.some((memo) => memo.id === pendingOpenedMemoIdRef.current)) return;
+ pendingOpenedMemoIdRef.current = null;
+ }
+
+ if (createdMemoEditId && selectedMemoId === createdMemoEditId) {
+ // Preserve the new note until the editor has consumed its autofocus request.
+ return;
+ }
+ if (memos.length === 0) {
+ setSelectedMemoId(null);
+ return;
+ }
+ if (!selectedMemoId || !selectedMemoInList) setSelectedMemoId(memos[0].id);
+ }, [createdMemoEditId, creatingMemoSelectionRef, memos, pendingCreatedMemoIdRef, pendingOpenedMemoIdRef, rendererRecoveryMode, selectedMemoId, setSelectedMemoId]);
+
+ return clearPendingMemoSelection;
+};
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 1e796286..9d5ca627 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -2816,6 +2816,7 @@ export const enUS = {
switchToNotebook: "Switch to {{name}}",
},
workspaceDialogs: {
+ openMemoFailed: "This note could not be opened. It may be unavailable or in Trash. Check your connection and try again.",
emptyTrashTitle: "Empty trash",
emptyTrashDescription: "All notes in Trash and still-linked attachments will be deleted. This action cannot be undone.",
emptyTrashConfirm: "Empty trash",
diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.ts
index 7343ac4c..6534f301 100644
--- a/packages/shared/src/i18n/ja.ts
+++ b/packages/shared/src/i18n/ja.ts
@@ -2805,6 +2805,7 @@ export const ja = {
switchToNotebook: "{{name}} に切り替え",
},
workspaceDialogs: {
+ openMemoFailed: "このノートを開けませんでした。利用できないか、ゴミ箱にある可能性があります。接続を確認して再試行してください。",
emptyTrashTitle: "ゴミ箱を空にする",
emptyTrashDescription: "ゴミ箱のすべてのノートと、まだ紐づいている添付が削除されます。この操作は取り消せません。",
emptyTrashConfirm: "ゴミ箱を空にする",
diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.ts
index f42ef207..dce63f7c 100644
--- a/packages/shared/src/i18n/pl.ts
+++ b/packages/shared/src/i18n/pl.ts
@@ -2805,6 +2805,7 @@ export const pl = {
switchToNotebook: "Przełącz na {{name}}",
},
workspaceDialogs: {
+ openMemoFailed: "Nie można otworzyć tej notatki. Może być niedostępna lub znajdować się w koszu. Sprawdź połączenie i spróbuj ponownie.",
emptyTrashTitle: "Opróżnij kosz",
emptyTrashDescription: "Wszystkie notatki w koszu i wciąż powiązane z nimi załączniki zostaną usunięte. Tej operacji nie można cofnąć.",
emptyTrashConfirm: "Opróżnij kosz",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index 689d81a4..bbafd6e9 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -2814,6 +2814,7 @@ export const zhCN = {
switchToNotebook: "切换到 {{name}}",
},
workspaceDialogs: {
+ openMemoFailed: "无法打开这条笔记。它可能已不可用或在回收站中。请检查连接后重试。",
emptyTrashTitle: "清空回收站",
emptyTrashDescription: "回收站中的全部笔记和仍关联的附件都会删除,这个操作不可恢复。",
emptyTrashConfirm: "清空回收站",