Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(page-editor): stop re-hydrating the editor after its own autosave (#20835)

Arvin Xu703039174aae
diff --git a/src/features/EditorCanvas/DocumentIdMode.test.tsx b/src/features/EditorCanvas/DocumentIdMode.test.tsx
index 349b2946ff8..7e9b9f10826 100644
--- a/src/features/EditorCanvas/DocumentIdMode.test.tsx
+++ b/src/features/EditorCanvas/DocumentIdMode.test.tsx
@@ -2,11 +2,13 @@
* @vitest-environment happy-dom
*/
import { act, render, screen, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { useDocumentStore } from '@/store/document';
import { editorSelectors } from '@/store/document/slices/editor';
import DocumentIdMode from './DocumentIdMode';
+import InternalEditor from './InternalEditor';
const handleContentChangeStore = vi.fn();
const performSave = vi.fn();
@@ -124,6 +126,88 @@ describe('DocumentIdMode', () => {
});
});
+ describe('re-hydration on a new remote version', () => {
+ const savedBody = { root: { children: [], type: 'root' } };
+ const remoteBody = { root: { children: [{ type: 'heading' }], type: 'root' } };
+
+ const renderAtVersion = (editor: any, version: string) => {
+ useFetchDocument.mockReturnValue(
+ createFetchDocumentResult({ data: { updatedAt: new Date(version) } }),
+ );
+ // A fresh `style` re-renders the memoized component, as the store subscription does.
+ return <DocumentIdMode documentId="doc-1" editor={editor} style={{}} />;
+ };
+
+ afterEach(() => {
+ useFetchDocument.mockImplementation(() => createFetchDocumentResult());
+ vi.mocked(useDocumentStore.getState).mockReturnValue({ documents: {} } as any);
+ });
+
+ it('should not reset the editor when the new version is its own save', async () => {
+ const editor = {
+ getDocument: vi.fn(() => savedBody),
+ getLexicalEditor: vi.fn(() => ({})),
+ } as any;
+ vi.mocked(useDocumentStore.getState).mockReturnValue({
+ documents: { 'doc-1': { editorData: savedBody } },
+ } as any);
+
+ const { rerender } = render(renderAtVersion(editor, '2026-10-12T00:00:00Z'));
+ await waitFor(() => expect(onEditorInit).toHaveBeenCalledTimes(1));
+
+ // The autosave mirrors its row into the detail replica, bumping updatedAt.
+ rerender(renderAtVersion(editor, '2026-10-12T00:00:05Z'));
+ await act(async () => {});
+
+ expect(onEditorInit).toHaveBeenCalledTimes(1);
+ });
+
+ it('should not hydrate again after the editor initialized through onInit', async () => {
+ // The editor is not ready on the first render, so InternalEditor's onInit does the
+ // first hydration and the mount effect bails out.
+ let lexicalReady = false;
+ const editor = {
+ getDocument: vi.fn(() => savedBody),
+ getLexicalEditor: vi.fn(() => (lexicalReady ? {} : undefined)),
+ } as any;
+ vi.mocked(useDocumentStore.getState).mockReturnValue({
+ documents: { 'doc-1': { editorData: savedBody } },
+ } as any);
+
+ const { rerender } = render(renderAtVersion(editor, '2026-10-12T00:00:00Z'));
+ expect(onEditorInit).not.toHaveBeenCalled();
+
+ lexicalReady = true;
+ act(() => {
+ vi.mocked(InternalEditor).mock.lastCall![0].onInit!(editor);
+ });
+ expect(onEditorInit).toHaveBeenCalledTimes(1);
+
+ // The autosave's version bump is the next render that re-reads isEditorInitialized.
+ rerender(renderAtVersion(editor, '2026-10-12T00:00:05Z'));
+ await act(async () => {});
+
+ expect(onEditorInit).toHaveBeenCalledTimes(1);
+ });
+
+ it('should re-hydrate when a remote body replaced the stored one', async () => {
+ const editor = {
+ getDocument: vi.fn(() => savedBody),
+ getLexicalEditor: vi.fn(() => ({})),
+ } as any;
+ vi.mocked(useDocumentStore.getState).mockReturnValue({
+ documents: { 'doc-1': { editorData: remoteBody } },
+ } as any);
+
+ const { rerender } = render(renderAtVersion(editor, '2026-10-12T00:00:00Z'));
+ await waitFor(() => expect(onEditorInit).toHaveBeenCalledTimes(1));
+
+ rerender(renderAtVersion(editor, '2026-10-12T00:00:05Z'));
+
+ await waitFor(() => expect(onEditorInit).toHaveBeenCalledTimes(2));
+ });
+ });
+
it('should pass topicId into document fetching options', () => {
const editor = {
getLexicalEditor: vi.fn(() => ({})),
diff --git a/src/features/EditorCanvas/DocumentIdMode.tsx b/src/features/EditorCanvas/DocumentIdMode.tsx
index 7b571452d01..2277b15b39f 100644
--- a/src/features/EditorCanvas/DocumentIdMode.tsx
+++ b/src/features/EditorCanvas/DocumentIdMode.tsx
@@ -1,6 +1,7 @@
'use client';
import { type IEditor } from '@lobehub/editor';
+import isEqual from 'fast-deep-equal';
import { memo, useCallback, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { createStoreUpdater } from 'zustand-utils';
@@ -68,15 +69,6 @@ const DocumentIdMode = memo<DocumentIdModeProps>(
useSaveDocumentHotkey(handleManualSave);
- const handleEditorInit = useCallback(
- (editorInstance: IEditor) => {
- void onEditorInit(editorInstance).finally(() => {
- onInit?.(editorInstance);
- });
- },
- [onEditorInit, onInit],
- );
-
// Use SWR hook for document fetching (auto-initializes via onSuccess in DocumentStore)
const {
data: remoteDocument,
@@ -134,6 +126,23 @@ const DocumentIdMode = memo<DocumentIdModeProps>(
const initializedDocIdRef = useRef<string | null>(null);
const hydratedVersionRef = useRef<string | undefined>(undefined);
+ const handleEditorInit = useCallback(
+ (editorInstance: IEditor) => {
+ // This is the first hydration whenever the editor mounts after the document
+ // loaded. Record it, or the effect below β€” whose `isEditorInitialized` is
+ // only re-read on a later render (e.g. the version bump of our own autosave)
+ // β€” treats the document as never hydrated and `setDocument`s it again,
+ // resetting the caret and selection mid-edit.
+ initializedDocIdRef.current = documentId;
+ hydratedVersionRef.current = remoteDocumentVersion;
+
+ void onEditorInit(editorInstance).finally(() => {
+ onInit?.(editorInstance);
+ });
+ },
+ [documentId, onEditorInit, onInit, remoteDocumentVersion],
+ );
+
// Critical fix: if the editor is already initialized, we need to manually call onEditorInit
// because the onInit callback only fires on the first editor initialization
useEffect(() => {
@@ -176,8 +185,17 @@ const DocumentIdMode = memo<DocumentIdModeProps>(
if (hydratedVersionRef.current === remoteDocumentVersion) return;
if (isDirty) return;
- const runId = ++initRunIdRef.current;
hydratedVersionRef.current = remoteDocumentVersion;
+
+ // Every autosave mirrors its row into the detail replica, so the version also
+ // moves on our own writes. The store body is synced from the editor on each
+ // change, so when it still matches the editor nothing remote was adopted:
+ // re-hydrating would only `setDocument` the same body and reset the caret and
+ // selection mid-edit.
+ const doc = useDocumentStore.getState().documents[documentId];
+ if (doc && isEqual(editor.getDocument('json'), doc.editorData)) return;
+
+ const runId = ++initRunIdRef.current;
contentChangeLockRef.current = true;
void onEditorInit(editor).finally(() => {