Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ReactEditor.focus triggering onValueChange unexpectedly #5679

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
})
})
})
})
Loading