Skip to content

Commit

Permalink
Fix ReactEditor.focus triggering onValueChange unexpectedly
Browse files Browse the repository at this point in the history
  • Loading branch information
WindRunnerMax committed Jul 10, 2024
1 parent 5838e36 commit 21aa5e3
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
8 changes: 7 additions & 1 deletion packages/slate-react/src/components/slate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,14 @@ export const Slate = (props: {
case 'set_selection':
onSelectionChange?.(editor.selection)
break
default:
case 'insert_node':
case 'remove_node':
case 'merge_node':
case 'split_node':
case 'move_node':
case 'set_node':
onValueChange?.(editor.children)
break
}

setContext(prevContext => ({
Expand Down
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
31 changes: 31 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,37 @@ 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 onValueChange = jest.fn()

act(() => {
render(
<Slate
editor={editor}
initialValue={initialValue}
onValueChange={onValueChange}
>
<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(onValueChange).not.toHaveBeenCalled()
})
})
})
})

0 comments on commit 21aa5e3

Please sign in to comment.