diff --git a/.changeset/mighty-trainers-juggle.md b/.changeset/mighty-trainers-juggle.md new file mode 100644 index 000000000..4965917fb --- /dev/null +++ b/.changeset/mighty-trainers-juggle.md @@ -0,0 +1,5 @@ +--- +'slate-react': patch +--- + +fix unexpected event triggered when using `ReactEditor.focus` diff --git a/packages/slate-react/src/plugin/react-editor.ts b/packages/slate-react/src/plugin/react-editor.ts index 5c1d63dae..d2430211a 100644 --- a/packages/slate-react/src/plugin/react-editor.ts +++ b/packages/slate-react/src/plugin/react-editor.ts @@ -443,7 +443,6 @@ export const ReactEditor: ReactEditorInterface = { // Create a new selection in the top of the document if missing if (!editor.selection) { Transforms.select(editor, Editor.start(editor, [])) - editor.onChange() } // IS_FOCUSED should be set before calling el.focus() to ensure that // FocusedContext is updated to the correct value diff --git a/packages/slate-react/test/react-editor.spec.tsx b/packages/slate-react/test/react-editor.spec.tsx index 6ebd5c310..f7a2ede1b 100644 --- a/packages/slate-react/test/react-editor.spec.tsx +++ b/packages/slate-react/test/react-editor.spec.tsx @@ -85,6 +85,43 @@ describe('slate-react', () => { expect(windowSelection?.focusOffset).toBe(testSelection.focus.offset) }) }) + + test('should not trigger onValueChange when focus is called', async () => { + const editor = withReact(createEditor()) + const initialValue = [{ type: 'block', children: [{ text: 'test' }] }] + const onChange = jest.fn() + const onValueChange = jest.fn() + const onSlectionChange = jest.fn() + + act(() => { + render( + + + + ) + }) + + expect(editor.selection).toBe(null) + + await act(async () => { + ReactEditor.focus(editor) + }) + + expect(editor.selection).toEqual({ + anchor: { path: [0, 0], offset: 0 }, + focus: { path: [0, 0], offset: 0 }, + }) + + expect(onChange).toHaveBeenCalled() + expect(onSlectionChange).toHaveBeenCalled() + expect(onValueChange).not.toHaveBeenCalled() + }) }) }) })