Skip to content

Commit

Permalink
Fix issue with slate-react static ReactEditor.focus method
Browse files Browse the repository at this point in the history
This will make sure we don't try to focus the editor while it's in the midst of applying operations.
If this is the case, retry setting focus in the next tick.
  • Loading branch information
skogsmaskin committed Oct 19, 2023
1 parent 0bdff51 commit cd93734
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
20 changes: 20 additions & 0 deletions packages/slate-react/src/plugin/react-editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
EDITOR_TO_SCHEDULE_FLUSH,
EDITOR_TO_WINDOW,
ELEMENT_TO_NODE,
FOCUS_TIMER_HANDLE,
IS_COMPOSING,
IS_FOCUSED,
IS_READ_ONLY,
Expand Down Expand Up @@ -412,6 +413,25 @@ export const ReactEditor: ReactEditorInterface = {
},

focus: editor => {
// If the editor has pending operations, focus should be requested after
// those changes are applied. Retry in the next tick if this is the case.
if (editor.operations.length > 0) {
const handle = FOCUS_TIMER_HANDLE.get(editor)
if (handle) {
clearTimeout(handle)
FOCUS_TIMER_HANDLE.delete(editor)
}
FOCUS_TIMER_HANDLE.set(
editor,
setTimeout(() => {
// Flush changes before trying to focus again
editor.onChange()
ReactEditor.focus(editor)
})
)
return
}

const el = ReactEditor.toDOMNode(editor, editor)
const root = ReactEditor.findDocumentOrShadowRoot(editor)
IS_FOCUSED.set(editor, true)
Expand Down
1 change: 1 addition & 0 deletions packages/slate-react/src/utils/weak-maps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export const EDITOR_TO_KEY_TO_ELEMENT: WeakMap<
export const IS_READ_ONLY: WeakMap<Editor, boolean> = new WeakMap()
export const IS_FOCUSED: WeakMap<Editor, boolean> = new WeakMap()
export const IS_COMPOSING: WeakMap<Editor, boolean> = new WeakMap()
export const FOCUS_TIMER_HANDLE: WeakMap<Editor, NodeJS.Timeout> = new WeakMap()

export const EDITOR_TO_USER_SELECTION: WeakMap<
Editor,
Expand Down

0 comments on commit cd93734

Please sign in to comment.