diff --git a/packages/lexical/src/LexicalEditor.ts b/packages/lexical/src/LexicalEditor.ts index d5026b467bf..be34223dfbf 100644 --- a/packages/lexical/src/LexicalEditor.ts +++ b/packages/lexical/src/LexicalEditor.ts @@ -1096,11 +1096,15 @@ export class LexicalEditor { } } } else { - // If content editable is unmounted we'll reset editor state back to original - // (or pending) editor state since there will be no reconciliation - this._editorState = pendingEditorState; - this._pendingEditorState = null; + // When the content editable is unmounted we will still trigger a + // reconciliation so that any pending updates are flushed, + // to match the previous state change when + // `_editorState = pendingEditorState` was used, but by + // using a commit we preserve the readOnly invariant + // for editor.getEditorState(). this._window = null; + this._updateTags.add('history-merge'); + $commitPendingUpdates(this); } triggerListeners('root', this, false, nextRootElement, prevRootElement); diff --git a/packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx b/packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx index dfd3724644a..a9a3eed4a60 100644 --- a/packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx +++ b/packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx @@ -1017,7 +1017,7 @@ describe('LexicalEditor tests', () => { }); expect(rootListener).toHaveBeenCalledTimes(3); - expect(updateListener).toHaveBeenCalledTimes(3); + expect(updateListener).toHaveBeenCalledTimes(4); expect(container.innerHTML).toBe( '

Change successful

', ); @@ -1032,7 +1032,13 @@ describe('LexicalEditor tests', () => { init(); const contentEditable = editor.getRootElement(); editor.setEditable(editable); + editor.update(() => { + // Cause the editor to become dirty, so we can ensure + // that the getEditorState()._readOnly invariant holds + $getRoot().markDirty(); + }); editor.setRootElement(null); + expect(editor.getEditorState()._readOnly).toBe(true); const editorState = editor.parseEditorState(JSON_EDITOR_STATE); editor.setEditorState(editorState); editor.update(() => {