Skip to content

Commit

Permalink
Fixed an issue with controlled value messing up editor.selection (#3652)
Browse files Browse the repository at this point in the history
* Fixed an issue with controlled value messing up editor.selection

* Create fifty-ducks-sip.md

Co-authored-by: Ian Storm Taylor <ian@ianstormtaylor.com>
  • Loading branch information
Andarist and ianstormtaylor authored Mar 31, 2021
1 parent d5b2d7f commit f3fb40c
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/fifty-ducks-sip.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'slate-react': patch
---

Fixed selection logic when a controlled editor's nodes change out from under it.
9 changes: 9 additions & 0 deletions packages/slate-react/src/components/editable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,15 @@ export const Editable = (props: EditableProps) => {
return
}

// when <Editable/> is being controlled through external value
// then its children might just change - DOM responds to it on its own
// but Slate's value is not being updated through any operation
// and thus it doesn't transform selection on its own
if (selection && !ReactEditor.hasRange(editor, selection)) {
editor.selection = ReactEditor.toSlateRange(editor, domSelection)
return
}

// Otherwise the DOM selection is out of sync, so update it.
const el = ReactEditor.toDOMNode(editor, editor)
state.isUpdatingSelection = true
Expand Down
8 changes: 8 additions & 0 deletions packages/slate-react/src/plugin/react-editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import { IS_CHROME } from '../utils/environment'
export interface ReactEditor extends BaseEditor {
insertData: (data: DataTransfer) => void
setFragmentData: (data: DataTransfer) => void
hasRange: (editor: ReactEditor, range: Range) => boolean
}

export const ReactEditor = {
Expand Down Expand Up @@ -573,4 +574,11 @@ export const ReactEditor = {

return { anchor, focus }
},

hasRange(editor: ReactEditor, range: Range): boolean {
const { anchor, focus } = range
return (
Editor.hasPath(editor, anchor.path) && Editor.hasPath(editor, focus.path)
)
},
}
4 changes: 4 additions & 0 deletions packages/slate/src/interfaces/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1060,6 +1060,10 @@ export const Editor: EditorInterface = {
return at
},

hasPath(editor: Editor, path: Path): boolean {
return Node.has(editor, path)
},

/**
* Create a mutable ref for a `Path` object, which will stay in sync as new
* operations are applied to the editor.
Expand Down

0 comments on commit f3fb40c

Please sign in to comment.