From 3205491c00552296cb5b2a5456005d0a0a26ef6c Mon Sep 17 00:00:00 2001 From: Bob Ippolito Date: Mon, 22 Jul 2024 15:56:47 -0700 Subject: [PATCH] Fix getCachedTypeToNodeMap to handle the empty and writable EditorState case --- packages/lexical/src/LexicalEditor.ts | 2 +- packages/lexical/src/LexicalUtils.ts | 6 ++++++ .../lexical/src/__tests__/unit/LexicalEditor.test.tsx | 10 +++++++++- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/packages/lexical/src/LexicalEditor.ts b/packages/lexical/src/LexicalEditor.ts index 4ee42ca838d..e08665f1c02 100644 --- a/packages/lexical/src/LexicalEditor.ts +++ b/packages/lexical/src/LexicalEditor.ts @@ -903,7 +903,7 @@ export class LexicalEditor { klass: Klass, ): void { const prevEditorState = this._editorState; - const nodeMap = getCachedTypeToNodeMap(this._editorState).get( + const nodeMap = getCachedTypeToNodeMap(prevEditorState).get( klass.getType(), ); if (!nodeMap) { diff --git a/packages/lexical/src/LexicalUtils.ts b/packages/lexical/src/LexicalUtils.ts index db227610851..30f0acd0bb9 100644 --- a/packages/lexical/src/LexicalUtils.ts +++ b/packages/lexical/src/LexicalUtils.ts @@ -1710,9 +1710,15 @@ export type TypeToNodeMap = Map; * Compute a cached Map of node type to nodes for a frozen EditorState */ const cachedNodeMaps = new WeakMap(); +const EMPTY_TYPE_TO_NODE_MAP: TypeToNodeMap = new Map(); export function getCachedTypeToNodeMap( editorState: EditorState, ): TypeToNodeMap { + // If this is a new Editor it may have a writable this._editorState + // with only a 'root' entry. + if (!editorState._readOnly && editorState.isEmpty()) { + return EMPTY_TYPE_TO_NODE_MAP; + } invariant( editorState._readOnly, 'getCachedTypeToNodeMap called with a writable EditorState', diff --git a/packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx b/packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx index aa63aa14ac5..3aacb0c1dcd 100644 --- a/packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx +++ b/packages/lexical/src/__tests__/unit/LexicalEditor.test.tsx @@ -35,6 +35,7 @@ import { COMMAND_PRIORITY_EDITOR, COMMAND_PRIORITY_LOW, createCommand, + createEditor, EditorState, ElementNode, type Klass, @@ -1807,7 +1808,14 @@ describe('LexicalEditor tests', () => { expect(textNodeMutation2[0].get(textNodeKeys[1])).toBe('destroyed'); expect(textNodeMutation2[0].get(textNodeKeys[2])).toBe('destroyed'); }); - + it('mutation listener on newly initialized editor', async () => { + editor = createEditor(); + const textNodeMutations = jest.fn(); + editor.registerMutationListener(TextNode, textNodeMutations, { + skipInitialization: false, + }); + expect(textNodeMutations.mock.calls.length).toBe(0); + }); it('mutation listener with setEditorState', async () => { init();