diff --git a/packages/slate-react/src/plugin/react-editor.ts b/packages/slate-react/src/plugin/react-editor.ts index 1d77d16a7fe..6399e654d17 100644 --- a/packages/slate-react/src/plugin/react-editor.ts +++ b/packages/slate-react/src/plugin/react-editor.ts @@ -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, @@ -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) diff --git a/packages/slate-react/src/utils/weak-maps.ts b/packages/slate-react/src/utils/weak-maps.ts index acad54176f7..3d101f8efeb 100644 --- a/packages/slate-react/src/utils/weak-maps.ts +++ b/packages/slate-react/src/utils/weak-maps.ts @@ -37,6 +37,7 @@ export const EDITOR_TO_KEY_TO_ELEMENT: WeakMap< export const IS_READ_ONLY: WeakMap = new WeakMap() export const IS_FOCUSED: WeakMap = new WeakMap() export const IS_COMPOSING: WeakMap = new WeakMap() +export const FOCUS_TIMER_HANDLE: WeakMap = new WeakMap() export const EDITOR_TO_USER_SELECTION: WeakMap< Editor,