Skip to content

Commit

Permalink
use focusin and focusout without capture if react >= 17
Browse files Browse the repository at this point in the history
See facebook/react#19186 for details on changes to `onFocus` and `onBlur`
  • Loading branch information
adri1wald committed Mar 31, 2022
1 parent ce63a08 commit 146bff4
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
25 changes: 15 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_ABOVE_VERSION_17 } from '../utils/environment'
import { useIsomorphicLayoutEffect } from '../hooks/use-isomorphic-layout-effect'

/**
Expand Down Expand Up @@ -70,16 +71,20 @@ 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_ABOVE_VERSION_17) {
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_ABOVE_VERSION_17 =
parseInt(React.version.split('.')[0], 10) >= 17

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

0 comments on commit 146bff4

Please sign in to comment.