Skip to content

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

fix(editor): preserve focus after note creation

tianma-if2c20889d856e
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index 001adca1..480c02c4 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -59,6 +59,11 @@ import { EditorToolbar } from "./EditorToolbar";
import { EditorOutline } from "./EditorOutline";
import { EditorTagPicker } from "./EditorTagPicker";
import { useAiBubbleMenu } from "./editor/useAiBubbleMenu";
+import {
+ createEditorInstanceMemoIdentity,
+ reconcileEditorInstanceMemoIdentity,
+ remapEditorInstanceMemoIdentity,
+} from "./editor/editor-instance-identity";
import {
createMarkdownModeSnapshot,
isMarkdownSourceUnchanged,
@@ -838,6 +843,14 @@ const RichEditorPane = ({
}
const hydratingRef = useRef(false);
const hydratedMemoIdRef = useRef<string | null>(null);
+ const editorInstanceMemoIdentityRef = useRef(
+ createEditorInstanceMemoIdentity(memo?.id ?? null),
+ );
+ editorInstanceMemoIdentityRef.current = reconcileEditorInstanceMemoIdentity(
+ editorInstanceMemoIdentityRef.current,
+ memo?.id ?? null,
+ );
+ const editorInstanceMemoKey = editorInstanceMemoIdentityRef.current.instanceKey;
/** Last content source applied to the editor — used to skip redundant setContent. */
const appliedEditorSourceKeyRef = useRef<string | null>(null);
const editingMemoIdRef = useRef<string | null>(memo?.id ?? null);
@@ -870,6 +883,10 @@ const RichEditorPane = ({
if (!nextMemoId || nextMemoId === currentMemo.id) return;
const previousMemoId = currentMemo.id;
+ editorInstanceMemoIdentityRef.current = remapEditorInstanceMemoIdentity(
+ editorInstanceMemoIdentityRef.current,
+ mappings,
+ );
memoRef.current = { ...currentMemo, id: nextMemoId };
if (editingMemoIdRef.current === previousMemoId) editingMemoIdRef.current = nextMemoId;
if (hydratedMemoIdRef.current === previousMemoId) {
@@ -1336,10 +1353,10 @@ const RichEditorPane = ({
},
},
}, [
- // A ProseMirror undo history belongs to exactly one memo. Reusing the same
- // Editor instance across memo switches lets Ctrl/Cmd+Z undo the hydration
- // transaction and restore another memo's entire document.
- memo?.id,
+ // A ProseMirror undo history belongs to exactly one logical memo. A newly
+ // created memo keeps the same instance while its local id is remapped to a
+ // durable id; an actual memo switch still receives a fresh undo history.
+ editorInstanceMemoKey,
]);
useEffect(() => {
diff --git a/apps/web/src/components/editor/editor-instance-identity.test.mjs b/apps/web/src/components/editor/editor-instance-identity.test.mjs
new file mode 100644
index 00000000..9658fb5b
--- /dev/null
+++ b/apps/web/src/components/editor/editor-instance-identity.test.mjs
@@ -0,0 +1,46 @@
+import { describe, expect, test } from "bun:test";
+import {
+ createEditorInstanceMemoIdentity,
+ reconcileEditorInstanceMemoIdentity,
+ remapEditorInstanceMemoIdentity,
+} from "./editor-instance-identity.ts";
+
+describe("editor instance memo identity", () => {
+ test("keeps the editor instance when a created memo receives its durable id", () => {
+ const localIdentity = createEditorInstanceMemoIdentity("local_memo_1");
+ const remappedIdentity = remapEditorInstanceMemoIdentity(
+ localIdentity,
+ new Map([["local_memo_1", "memo_remote_1"]]),
+ );
+ const identityDuringParentRerender = reconcileEditorInstanceMemoIdentity(
+ remappedIdentity,
+ "local_memo_1",
+ );
+ const reconciledIdentity = reconcileEditorInstanceMemoIdentity(
+ identityDuringParentRerender,
+ "memo_remote_1",
+ );
+
+ expect(reconciledIdentity.memoId).toBe("memo_remote_1");
+ expect(reconciledIdentity.instanceKey).toBe(localIdentity.instanceKey);
+ expect(reconciledIdentity).toBe(remappedIdentity);
+ });
+
+ test("changes the editor instance when the selected memo really changes", () => {
+ const firstIdentity = createEditorInstanceMemoIdentity("memo_1");
+ const secondIdentity = reconcileEditorInstanceMemoIdentity(firstIdentity, "memo_2");
+
+ expect(secondIdentity).toMatchObject({ memoId: "memo_2", instanceKey: "memo_2" });
+ expect(secondIdentity.aliases).toEqual(new Set(["memo_2"]));
+ expect(secondIdentity.instanceKey).not.toBe(firstIdentity.instanceKey);
+ });
+
+ test("ignores id mappings for a different memo", () => {
+ const identity = createEditorInstanceMemoIdentity("memo_1");
+
+ expect(remapEditorInstanceMemoIdentity(
+ identity,
+ new Map([["local_memo_2", "memo_remote_2"]]),
+ )).toBe(identity);
+ });
+});
diff --git a/apps/web/src/components/editor/editor-instance-identity.ts b/apps/web/src/components/editor/editor-instance-identity.ts
new file mode 100644
index 00000000..f872e4ae
--- /dev/null
+++ b/apps/web/src/components/editor/editor-instance-identity.ts
@@ -0,0 +1,38 @@
+export type EditorInstanceMemoIdentity = {
+ memoId: string | null;
+ instanceKey: string | null;
+ aliases: ReadonlySet<string>;
+};
+
+export const createEditorInstanceMemoIdentity = (
+ memoId: string | null,
+): EditorInstanceMemoIdentity => ({
+ memoId,
+ instanceKey: memoId,
+ aliases: new Set(memoId ? [memoId] : []),
+});
+
+export const reconcileEditorInstanceMemoIdentity = (
+ identity: EditorInstanceMemoIdentity,
+ memoId: string | null,
+): EditorInstanceMemoIdentity => (
+ identity.memoId === memoId || Boolean(memoId && identity.aliases.has(memoId))
+)
+ ? identity
+ : createEditorInstanceMemoIdentity(memoId);
+
+export const remapEditorInstanceMemoIdentity = (
+ identity: EditorInstanceMemoIdentity,
+ memoIdMappings: ReadonlyMap<string, string>,
+): EditorInstanceMemoIdentity => {
+ if (!identity.memoId) return identity;
+
+ const remappedMemoId = memoIdMappings.get(identity.memoId);
+ if (!remappedMemoId || remappedMemoId === identity.memoId) return identity;
+
+ return {
+ memoId: remappedMemoId,
+ instanceKey: identity.instanceKey,
+ aliases: new Set([...identity.aliases, remappedMemoId]),
+ };
+};
diff --git a/tests/e2e/new-memo-sync.spec.ts b/tests/e2e/new-memo-sync.spec.ts
index a3f9a684..8ad0d93d 100644
--- a/tests/e2e/new-memo-sync.spec.ts
+++ b/tests/e2e/new-memo-sync.spec.ts
@@ -177,6 +177,95 @@ const finishSyncAndVerifyReload = async (
};
test.describe("new memo synchronization", () => {
+ test("keeps the new memo editor mounted and focused while its local id is remapped", async ({ page }) => {
+ const heldCreate = await holdNextMemoCreate(page);
+ let memoId: string | null = null;
+
+ try {
+ await page.goto("/");
+ await page.getByRole("button", { name: "新建笔记", exact: true }).click();
+ await heldCreate.createStarted;
+
+ const editor = page.locator(".ProseMirror[contenteditable='true']");
+ await expect(editor).toBeEditable();
+ await editor.click();
+ await expect(editor).toBeFocused();
+
+ const editorObservation = page.evaluate(() => new Promise<{
+ disconnected: boolean;
+ focusLost: boolean;
+ mapping: Array<[string, string]>;
+ replaced: boolean;
+ stillFocused: boolean;
+ }>((resolve, reject) => {
+ const originalEditor = document.querySelector(".ProseMirror[contenteditable='true']");
+ if (!(originalEditor instanceof HTMLElement)) {
+ reject(new Error("Expected a mounted memo editor before id remapping"));
+ return;
+ }
+
+ let disconnected = false;
+ let focusLost = document.activeElement !== originalEditor;
+ let replaced = false;
+ const sampleEditorState = () => {
+ disconnected ||= !originalEditor.isConnected;
+ focusLost ||= document.activeElement !== originalEditor;
+ replaced ||= document.querySelector(".ProseMirror[contenteditable='true']") !== originalEditor;
+ };
+ const sampleInterval = window.setInterval(sampleEditorState, 5);
+ const mutationObserver = new MutationObserver(sampleEditorState);
+ mutationObserver.observe(document.body, { childList: true, subtree: true });
+ originalEditor.addEventListener("focusout", () => { focusLost = true; });
+
+ window.addEventListener("edgeever:memo-id-remapped", (event) => {
+ const detail = (event as CustomEvent<Map<string, string>>).detail;
+ window.setTimeout(() => {
+ sampleEditorState();
+ window.clearInterval(sampleInterval);
+ mutationObserver.disconnect();
+ resolve({
+ disconnected,
+ focusLost,
+ mapping: [...detail.entries()],
+ replaced,
+ stillFocused: document.activeElement === originalEditor,
+ });
+ }, 1_200);
+ }, { once: true });
+ }));
+
+ heldCreate.releaseCreate();
+ const createResponse = await heldCreate.createResponse;
+ expect(createResponse.status()).toBe(201);
+ const created = await createResponse.json() as { memo: { id: string } };
+ memoId = created.memo.id;
+
+ const observation = await editorObservation;
+ expect(observation.mapping).toContainEqual([expect.any(String), memoId]);
+ expect(observation.mapping[0]?.[0]).not.toBe(memoId);
+ expect(observation).toMatchObject({
+ disconnected: false,
+ focusLost: false,
+ replaced: false,
+ stillFocused: true,
+ });
+ await expect(editor).toBeFocused();
+ } finally {
+ heldCreate.releaseCreate();
+ if (!memoId) {
+ const createResponse = await heldCreate.createResponse.catch(() => null);
+ if (createResponse?.status() === 201) {
+ const created = await createResponse.json() as { memo: { id: string } };
+ memoId = created.memo.id;
+ }
+ }
+ if (memoId) {
+ await page.request.delete(`/api/v1/memos/${memoId}`);
+ await page.request.delete(`/api/v1/memos/${memoId}?permanent=1`);
+ }
+ }
+ });
+
test("rebases a second autosave after memo creation reaches cloud revision 1", async ({ page }) => {
const marker = `${Date.now()}-draft-only`;
const title = `E2E create race ${marker}`;