|
9 | 9 | SlateSelectorContext,
|
10 | 10 | } from '../hooks/use-slate-selector'
|
11 | 11 | import { EDITOR_TO_ON_CHANGE } from '../utils/weak-maps'
|
| 12 | +import { IS_REACT_VERSION_17_OR_ABOVE } from '../utils/environment' |
12 | 13 | import { useIsomorphicLayoutEffect } from '../hooks/use-isomorphic-layout-effect'
|
13 | 14 |
|
14 | 15 | /**
|
@@ -73,16 +74,23 @@ export const Slate = (props: {
|
73 | 74 |
|
74 | 75 | useIsomorphicLayoutEffect(() => {
|
75 | 76 | const fn = () => setIsFocused(ReactEditor.isFocused(editor))
|
76 |
| - document.addEventListener('focus', fn, true) |
77 |
| - return () => document.removeEventListener('focus', fn, true) |
78 |
| - }, []) |
79 |
| - |
80 |
| - useIsomorphicLayoutEffect(() => { |
81 |
| - const fn = () => setIsFocused(ReactEditor.isFocused(editor)) |
82 |
| - document.addEventListener('blur', fn, true) |
83 |
| - return () => { |
84 |
| - document.removeEventListener('focus', fn, true) |
85 |
| - document.removeEventListener('blur', fn, true) |
| 77 | + if (IS_REACT_VERSION_17_OR_ABOVE) { |
| 78 | + // In React >= 17 onFocus and onBlur listen to the focusin and focusout events during the bubbling phase. |
| 79 | + // Therefore in order for <Editable />'s handlers to run first, which is necessary for ReactEditor.isFocused(editor) |
| 80 | + // to return the correct value, we have to listen to the focusin and focusout events without useCapture here. |
| 81 | + document.addEventListener('focusin', fn) |
| 82 | + document.addEventListener('focusout', fn) |
| 83 | + return () => { |
| 84 | + document.removeEventListener('focusin', fn) |
| 85 | + document.removeEventListener('focusout', fn) |
| 86 | + } |
| 87 | + } else { |
| 88 | + document.addEventListener('focus', fn, true) |
| 89 | + document.addEventListener('blur', fn, true) |
| 90 | + return () => { |
| 91 | + document.removeEventListener('focus', fn, true) |
| 92 | + document.removeEventListener('blur', fn, true) |
| 93 | + } |
86 | 94 | }
|
87 | 95 | }, [])
|
88 | 96 |
|
|
0 commit comments