Skip to content

Commit

Permalink
Run <Slate />'s focus event listeners after <Editable />'s focus hand…
Browse files Browse the repository at this point in the history
…lers in React >= 17 (#4920)

* use focusin and focusout without capture if react >= 17

See facebook/react#19186 for details on changes to `onFocus` and `onBlur`

* more accurate name for react version check const

* add changeset

* add comment about react >= 17 focus event listeners
  • Loading branch information
adri1wald committed Apr 3, 2022
1 parent 9892cf0 commit f6b7ca1
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 10 deletions.
5 changes: 5 additions & 0 deletions .changeset/five-emus-roll.md
@@ -0,0 +1,5 @@
---
'slate-react': patch
---

fix useFocused hook in react >= 17
28 changes: 18 additions & 10 deletions packages/slate-react/src/components/slate.tsx
Expand Up @@ -9,6 +9,7 @@ import {
SlateSelectorContext,
} from '../hooks/use-slate-selector'
import { EDITOR_TO_ON_CHANGE } from '../utils/weak-maps'
import { IS_REACT_VERSION_17_OR_ABOVE } from '../utils/environment'
import { useIsomorphicLayoutEffect } from '../hooks/use-isomorphic-layout-effect'

/**
Expand Down Expand Up @@ -73,16 +74,23 @@ export const Slate = (props: {

useIsomorphicLayoutEffect(() => {
const fn = () => setIsFocused(ReactEditor.isFocused(editor))
document.addEventListener('focus', fn, true)
return () => document.removeEventListener('focus', fn, true)
}, [])

useIsomorphicLayoutEffect(() => {
const fn = () => setIsFocused(ReactEditor.isFocused(editor))
document.addEventListener('blur', fn, true)
return () => {
document.removeEventListener('focus', fn, true)
document.removeEventListener('blur', fn, true)
if (IS_REACT_VERSION_17_OR_ABOVE) {
// In React >= 17 onFocus and onBlur listen to the focusin and focusout events during the bubbling phase.
// Therefore in order for <Editable />'s handlers to run first, which is necessary for ReactEditor.isFocused(editor)
// to return the correct value, we have to listen to the focusin and focusout events without useCapture here.
document.addEventListener('focusin', fn)
document.addEventListener('focusout', fn)
return () => {
document.removeEventListener('focusin', fn)
document.removeEventListener('focusout', fn)
}
} else {
document.addEventListener('focus', fn, true)
document.addEventListener('blur', fn, true)
return () => {
document.removeEventListener('focus', fn, true)
document.removeEventListener('blur', fn, true)
}
}
}, [])

Expand Down
5 changes: 5 additions & 0 deletions packages/slate-react/src/utils/environment.ts
@@ -1,3 +1,8 @@
import React from 'react'

export const IS_REACT_VERSION_17_OR_ABOVE =
parseInt(React.version.split('.')[0], 10) >= 17

export const IS_IOS =
typeof navigator !== 'undefined' &&
typeof window !== 'undefined' &&
Expand Down

0 comments on commit f6b7ca1

Please sign in to comment.