From 146bff4c2224bc571f67799c1d5ba405322eb069 Mon Sep 17 00:00:00 2001 From: Adrien Wald Date: Thu, 31 Mar 2022 02:02:59 +0100 Subject: [PATCH] use focusin and focusout without capture if react >= 17 See https://github.com/facebook/react/pull/19186 for details on changes to `onFocus` and `onBlur` --- packages/slate-react/src/components/slate.tsx | 25 +++++++++++-------- packages/slate-react/src/utils/environment.ts | 5 ++++ 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/packages/slate-react/src/components/slate.tsx b/packages/slate-react/src/components/slate.tsx index ddaea451f3..fd19e56bbd 100644 --- a/packages/slate-react/src/components/slate.tsx +++ b/packages/slate-react/src/components/slate.tsx @@ -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' /** @@ -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) + } } }, []) diff --git a/packages/slate-react/src/utils/environment.ts b/packages/slate-react/src/utils/environment.ts index 7f78f135b9..75dc415ad5 100644 --- a/packages/slate-react/src/utils/environment.ts +++ b/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' &&