Skip to content

Commit

Permalink
fix: unexpected event triggered when using ReactEditor.focus (#5677)
Browse files Browse the repository at this point in the history
* chore: reproduce the problem env

* fix: unexpected event triggered

* feat: onValueChange unit test
  • Loading branch information
WindRunnerMax authored Jul 15, 2024
1 parent 5838e36 commit a9a7040
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/mighty-trainers-juggle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'slate-react': patch
---

fix unexpected event triggered when using `ReactEditor.focus`
1 change: 0 additions & 1 deletion packages/slate-react/src/plugin/react-editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
37 changes: 37 additions & 0 deletions packages/slate-react/test/react-editor.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(
<Slate
editor={editor}
initialValue={initialValue}
onValueChange={onValueChange}
onChange={onChange}
onSelectionChange={onSlectionChange}
>
<Editable />
</Slate>
)
})

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()
})
})
})
})

0 comments on commit a9a7040

Please sign in to comment.