1
0
mirror of https://github.com/ianstormtaylor/slate.git synced 2025-08-11 09:43:58 +02:00

enable eslint hooks rules (#5363)

This commit is contained in:
Anthony Ciccarello
2023-03-17 10:45:54 -07:00
committed by GitHub
parent 556a4565d2
commit d42cd005db
15 changed files with 264 additions and 195 deletions

View File

@@ -69,6 +69,7 @@ import {
import { RestoreDOM } from './restore-dom/restore-dom'
import { useAndroidInputManager } from '../hooks/android-input-manager/use-android-input-manager'
import { useTrackUserInput } from '../hooks/use-track-user-input'
import { AndroidInputManager } from '../hooks/android-input-manager/android-input-manager'
type DeferredOperation = () => void
@@ -181,70 +182,82 @@ export const Editable = (props: EditableProps) => {
}
}, [autoFocus])
/**
* The AndroidInputManager object has a cyclical dependency on onDOMSelectionChange
*
* It is defined as a reference to simplify hook dependencies and clarify that
* it needs to be initialized.
*/
const androidInputManagerRef = useRef<
AndroidInputManager | null | undefined
>()
// Listen on the native `selectionchange` event to be able to update any time
// the selection changes. This is required because React's `onSelect` is leaky
// and non-standard so it doesn't fire until after a selection has been
// released. This causes issues in situations where another change happens
// while a selection is being dragged.
const onDOMSelectionChange = useCallback(
throttle(() => {
if (
(IS_ANDROID || !ReactEditor.isComposing(editor)) &&
(!state.isUpdatingSelection || androidInputManager?.isFlushing()) &&
!state.isDraggingInternally
) {
const root = ReactEditor.findDocumentOrShadowRoot(editor)
const { activeElement } = root
const el = ReactEditor.toDOMNode(editor, editor)
const domSelection = root.getSelection()
const onDOMSelectionChange = useMemo(
() =>
throttle(() => {
const androidInputManager = androidInputManagerRef.current
if (
(IS_ANDROID || !ReactEditor.isComposing(editor)) &&
(!state.isUpdatingSelection || androidInputManager?.isFlushing()) &&
!state.isDraggingInternally
) {
const root = ReactEditor.findDocumentOrShadowRoot(editor)
const { activeElement } = root
const el = ReactEditor.toDOMNode(editor, editor)
const domSelection = root.getSelection()
if (activeElement === el) {
state.latestElement = activeElement
IS_FOCUSED.set(editor, true)
} else {
IS_FOCUSED.delete(editor)
}
if (activeElement === el) {
state.latestElement = activeElement
IS_FOCUSED.set(editor, true)
} else {
IS_FOCUSED.delete(editor)
}
if (!domSelection) {
return Transforms.deselect(editor)
}
if (!domSelection) {
return Transforms.deselect(editor)
}
const { anchorNode, focusNode } = domSelection
const { anchorNode, focusNode } = domSelection
const anchorNodeSelectable =
ReactEditor.hasEditableTarget(editor, anchorNode) ||
ReactEditor.isTargetInsideNonReadonlyVoid(editor, anchorNode)
const anchorNodeSelectable =
ReactEditor.hasEditableTarget(editor, anchorNode) ||
ReactEditor.isTargetInsideNonReadonlyVoid(editor, anchorNode)
const focusNodeSelectable =
ReactEditor.hasEditableTarget(editor, focusNode) ||
ReactEditor.isTargetInsideNonReadonlyVoid(editor, focusNode)
const focusNodeSelectable =
ReactEditor.hasEditableTarget(editor, focusNode) ||
ReactEditor.isTargetInsideNonReadonlyVoid(editor, focusNode)
if (anchorNodeSelectable && focusNodeSelectable) {
const range = ReactEditor.toSlateRange(editor, domSelection, {
exactMatch: false,
suppressThrow: true,
})
if (anchorNodeSelectable && focusNodeSelectable) {
const range = ReactEditor.toSlateRange(editor, domSelection, {
exactMatch: false,
suppressThrow: true,
})
if (range) {
if (
!ReactEditor.isComposing(editor) &&
!androidInputManager?.hasPendingChanges() &&
!androidInputManager?.isFlushing()
) {
Transforms.select(editor, range)
} else {
androidInputManager?.handleUserSelect(range)
if (range) {
if (
!ReactEditor.isComposing(editor) &&
!androidInputManager?.hasPendingChanges() &&
!androidInputManager?.isFlushing()
) {
Transforms.select(editor, range)
} else {
androidInputManager?.handleUserSelect(range)
}
}
}
}
// Deselect the editor if the dom selection is not selectable in readonly mode
if (readOnly && (!anchorNodeSelectable || !focusNodeSelectable)) {
Transforms.deselect(editor)
// Deselect the editor if the dom selection is not selectable in readonly mode
if (readOnly && (!anchorNodeSelectable || !focusNodeSelectable)) {
Transforms.deselect(editor)
}
}
}
}, 100),
[readOnly]
}, 100),
[editor, readOnly, state]
)
const scheduleOnDOMSelectionChange = useMemo(
@@ -252,7 +265,7 @@ export const Editable = (props: EditableProps) => {
[onDOMSelectionChange]
)
const androidInputManager = useAndroidInputManager({
androidInputManagerRef.current = useAndroidInputManager({
node: ref,
onDOMSelectionChange,
scheduleOnDOMSelectionChange,
@@ -278,7 +291,7 @@ export const Editable = (props: EditableProps) => {
if (
!domSelection ||
!ReactEditor.isFocused(editor) ||
androidInputManager?.hasPendingAction()
androidInputManagerRef.current?.hasPendingAction()
) {
return
}
@@ -376,7 +389,8 @@ export const Editable = (props: EditableProps) => {
}
const newDomRange = setDomSelection()
const ensureSelection = androidInputManager?.isFlushing() === 'action'
const ensureSelection =
androidInputManagerRef.current?.isFlushing() === 'action'
if (!IS_ANDROID || !ensureSelection) {
setTimeout(() => {
@@ -444,8 +458,8 @@ export const Editable = (props: EditableProps) => {
!isDOMEventHandled(event, propsOnDOMBeforeInput)
) {
// COMPAT: BeforeInput events aren't cancelable on android, so we have to handle them differently using the android input manager.
if (androidInputManager) {
return androidInputManager.handleDOMBeforeInput(event)
if (androidInputManagerRef.current) {
return androidInputManagerRef.current.handleDOMBeforeInput(event)
}
// Some IMEs/Chrome extensions like e.g. Grammarly set the selection immediately before
@@ -699,7 +713,14 @@ export const Editable = (props: EditableProps) => {
}
}
},
[readOnly, propsOnDOMBeforeInput]
[
editor,
onDOMSelectionChange,
onUserInput,
propsOnDOMBeforeInput,
readOnly,
scheduleOnDOMSelectionChange,
]
)
const callbackRef = useCallback(
@@ -728,7 +749,12 @@ export const Editable = (props: EditableProps) => {
ref.current = node
},
[ref, onDOMBeforeInput, onDOMSelectionChange, scheduleOnDOMSelectionChange]
[
onDOMSelectionChange,
scheduleOnDOMSelectionChange,
editor,
onDOMBeforeInput,
]
)
// Attach a native DOM event handler for `selectionchange`, because React's
@@ -899,27 +925,30 @@ export const Editable = (props: EditableProps) => {
}
}
},
[readOnly]
[attributes.onBeforeInput, editor, readOnly]
)}
onInput={useCallback((event: React.FormEvent<HTMLDivElement>) => {
if (isEventHandled(event, attributes.onInput)) {
return
}
onInput={useCallback(
(event: React.FormEvent<HTMLDivElement>) => {
if (isEventHandled(event, attributes.onInput)) {
return
}
if (androidInputManager) {
androidInputManager.handleInput()
return
}
if (androidInputManagerRef.current) {
androidInputManagerRef.current.handleInput()
return
}
// Flush native operations, as native events will have propogated
// and we can correctly compare DOM text values in components
// to stop rendering, so that browser functions like autocorrect
// and spellcheck work as expected.
for (const op of deferredOperations.current) {
op()
}
deferredOperations.current = []
}, [])}
// Flush native operations, as native events will have propogated
// and we can correctly compare DOM text values in components
// to stop rendering, so that browser functions like autocorrect
// and spellcheck work as expected.
for (const op of deferredOperations.current) {
op()
}
deferredOperations.current = []
},
[attributes.onInput]
)}
onBlur={useCallback(
(event: React.FocusEvent<HTMLDivElement>) => {
if (
@@ -984,7 +1013,13 @@ export const Editable = (props: EditableProps) => {
IS_FOCUSED.delete(editor)
},
[readOnly, attributes.onBlur]
[
readOnly,
state.isUpdatingSelection,
state.latestElement,
editor,
attributes.onBlur,
]
)}
onClick={useCallback(
(event: React.MouseEvent<HTMLDivElement>) => {
@@ -1045,7 +1080,7 @@ export const Editable = (props: EditableProps) => {
}
}
},
[readOnly, attributes.onClick]
[editor, attributes.onClick, readOnly]
)}
onCompositionEnd={useCallback(
(event: React.CompositionEvent<HTMLDivElement>) => {
@@ -1055,7 +1090,7 @@ export const Editable = (props: EditableProps) => {
IS_COMPOSING.set(editor, false)
}
androidInputManager?.handleCompositionEnd(event)
androidInputManagerRef.current?.handleCompositionEnd(event)
if (
isEventHandled(event, attributes.onCompositionEnd) ||
@@ -1097,7 +1132,7 @@ export const Editable = (props: EditableProps) => {
}
}
},
[attributes.onCompositionEnd]
[attributes.onCompositionEnd, editor]
)}
onCompositionUpdate={useCallback(
(event: React.CompositionEvent<HTMLDivElement>) => {
@@ -1111,12 +1146,12 @@ export const Editable = (props: EditableProps) => {
}
}
},
[attributes.onCompositionUpdate]
[attributes.onCompositionUpdate, editor]
)}
onCompositionStart={useCallback(
(event: React.CompositionEvent<HTMLDivElement>) => {
if (ReactEditor.hasSelectableTarget(editor, event.target)) {
androidInputManager?.handleCompositionStart(event)
androidInputManagerRef.current?.handleCompositionStart(event)
if (
isEventHandled(event, attributes.onCompositionStart) ||
@@ -1151,7 +1186,7 @@ export const Editable = (props: EditableProps) => {
}
}
},
[attributes.onCompositionStart]
[attributes.onCompositionStart, editor]
)}
onCopy={useCallback(
(event: React.ClipboardEvent<HTMLDivElement>) => {
@@ -1168,7 +1203,7 @@ export const Editable = (props: EditableProps) => {
)
}
},
[attributes.onCopy]
[attributes.onCopy, editor]
)}
onCut={useCallback(
(event: React.ClipboardEvent<HTMLDivElement>) => {
@@ -1198,7 +1233,7 @@ export const Editable = (props: EditableProps) => {
}
}
},
[readOnly, attributes.onCut]
[readOnly, editor, attributes.onCut]
)}
onDragOver={useCallback(
(event: React.DragEvent<HTMLDivElement>) => {
@@ -1216,7 +1251,7 @@ export const Editable = (props: EditableProps) => {
}
}
},
[attributes.onDragOver]
[attributes.onDragOver, editor]
)}
onDragStart={useCallback(
(event: React.DragEvent<HTMLDivElement>) => {
@@ -1247,7 +1282,7 @@ export const Editable = (props: EditableProps) => {
)
}
},
[readOnly, attributes.onDragStart]
[readOnly, editor, attributes.onDragStart, state]
)}
onDrop={useCallback(
(event: React.DragEvent<HTMLDivElement>) => {
@@ -1290,7 +1325,7 @@ export const Editable = (props: EditableProps) => {
state.isDraggingInternally = false
},
[readOnly, attributes.onDrop]
[readOnly, editor, attributes.onDrop, state]
)}
onDragEnd={useCallback(
(event: React.DragEvent<HTMLDivElement>) => {
@@ -1308,7 +1343,7 @@ export const Editable = (props: EditableProps) => {
// Note: `onDragEnd` is only called when `onDrop` is not called
state.isDraggingInternally = false
},
[readOnly, attributes.onDragEnd]
[readOnly, state, attributes, editor]
)}
onFocus={useCallback(
(event: React.FocusEvent<HTMLDivElement>) => {
@@ -1333,7 +1368,7 @@ export const Editable = (props: EditableProps) => {
IS_FOCUSED.set(editor, true)
}
},
[readOnly, attributes.onFocus]
[readOnly, state, editor, attributes.onFocus]
)}
onKeyDown={useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
@@ -1341,7 +1376,7 @@ export const Editable = (props: EditableProps) => {
!readOnly &&
ReactEditor.hasEditableTarget(editor, event.target)
) {
androidInputManager?.handleKeyDown(event)
androidInputManagerRef.current?.handleKeyDown(event)
const { nativeEvent } = event
@@ -1608,7 +1643,7 @@ export const Editable = (props: EditableProps) => {
}
}
},
[readOnly, attributes.onKeyDown]
[readOnly, editor, attributes.onKeyDown]
)}
onPaste={useCallback(
(event: React.ClipboardEvent<HTMLDivElement>) => {
@@ -1634,7 +1669,7 @@ export const Editable = (props: EditableProps) => {
}
}
},
[readOnly, attributes.onPaste]
[readOnly, editor, attributes.onPaste]
)}
>
<Children

View File

@@ -83,7 +83,7 @@ const Leaf = (props: {
return () => {
EDITOR_TO_PLACEHOLDER_ELEMENT.delete(editor)
}
}, [placeholderRef, leaf])
}, [placeholderRef, leaf, editor])
let children = (
<String isLast={isLast} leaf={leaf} parent={parent} text={text} />

View File

@@ -5,7 +5,7 @@ import { FocusedContext } from '../hooks/use-focused'
import { EditorContext } from '../hooks/use-slate-static'
import { SlateContext, SlateContextValue } from '../hooks/use-slate'
import {
getSelectorContext,
useSelectorContext,
SlateSelectorContext,
} from '../hooks/use-slate-selector'
import { EDITOR_TO_ON_CHANGE } from '../utils/weak-maps'
@@ -47,7 +47,7 @@ export const Slate = (props: {
const {
selectorContext,
onChange: handleSelectorChange,
} = getSelectorContext(editor)
} = useSelectorContext(editor)
const onContextChange = useCallback(() => {
if (onChange) {
@@ -59,7 +59,7 @@ export const Slate = (props: {
editor,
}))
handleSelectorChange(editor)
}, [onChange])
}, [editor, handleSelectorChange, onChange])
useEffect(() => {
EDITOR_TO_ON_CHANGE.set(editor, onContextChange)
@@ -68,13 +68,13 @@ export const Slate = (props: {
EDITOR_TO_ON_CHANGE.set(editor, () => {})
unmountRef.current = true
}
}, [onContextChange])
}, [editor, onContextChange])
const [isFocused, setIsFocused] = useState(ReactEditor.isFocused(editor))
useEffect(() => {
setIsFocused(ReactEditor.isFocused(editor))
})
}, [editor])
useIsomorphicLayoutEffect(() => {
const fn = () => setIsFocused(ReactEditor.isFocused(editor))

View File

@@ -22,34 +22,33 @@ const MUTATION_OBSERVER_CONFIG: MutationObserverInit = {
characterData: true,
}
export function useAndroidInputManager({
node,
...options
}: UseAndroidInputManagerOptions) {
if (!IS_ANDROID) {
return null
}
export const useAndroidInputManager = !IS_ANDROID
? () => null
: ({ node, ...options }: UseAndroidInputManagerOptions) => {
if (!IS_ANDROID) {
return null
}
const editor = useSlateStatic()
const isMounted = useIsMounted()
const editor = useSlateStatic()
const isMounted = useIsMounted()
const [inputManager] = useState(() =>
createAndroidInputManager({
editor,
...options,
})
)
const [inputManager] = useState(() =>
createAndroidInputManager({
editor,
...options,
})
)
useMutationObserver(
node,
inputManager.handleDomMutations,
MUTATION_OBSERVER_CONFIG
)
useMutationObserver(
node,
inputManager.handleDomMutations,
MUTATION_OBSERVER_CONFIG
)
EDITOR_TO_SCHEDULE_FLUSH.set(editor, inputManager.scheduleFlush)
if (isMounted) {
inputManager.flush()
}
EDITOR_TO_SCHEDULE_FLUSH.set(editor, inputManager.scheduleFlush)
if (isMounted) {
inputManager.flush()
}
return inputManager
}
return inputManager
}

View File

@@ -23,5 +23,5 @@ export function useMutationObserver(
mutationObserver.observe(node.current, options)
return () => mutationObserver.disconnect()
}, [])
}, [mutationObserver, node, options])
}

View File

@@ -112,17 +112,22 @@ export function useSlateSelector<T>(
/**
* Create selector context with editor updating on every editor change
*/
export function getSelectorContext(editor: Editor) {
export function useSelectorContext(editor: Editor) {
const eventListeners = useRef<EditorChangeHandler[]>([]).current
const slateRef = useRef<{
editor: Editor
}>({
editor,
}).current
const onChange = useCallback((editor: Editor) => {
slateRef.editor = editor
eventListeners.forEach((listener: EditorChangeHandler) => listener(editor))
}, [])
const onChange = useCallback(
(editor: Editor) => {
slateRef.editor = editor
eventListeners.forEach((listener: EditorChangeHandler) =>
listener(editor)
)
},
[eventListeners, slateRef]
)
const selectorContext = useMemo(() => {
return {

View File

@@ -21,7 +21,7 @@ export function useTrackUserInput() {
animationFrameIdRef.current = window.requestAnimationFrame(() => {
receivedUserInput.current = false
})
}, [])
}, [editor])
useEffect(() => () => cancelAnimationFrame(animationFrameIdRef.current), [])

View File

@@ -1,4 +1,4 @@
import React from 'react'
import React, { useEffect } from 'react'
import { createEditor, Element, Transforms } from 'slate'
import { create, act, ReactTestRenderer } from 'react-test-renderer'
import { Slate, withReact, Editable } from '../src'
@@ -22,7 +22,7 @@ describe('slate-react', () => {
test('should not unmount the node that gets split on a split_node operation', async () => {
const editor = withReact(createEditor())
const value = [{ type: 'block', children: [{ text: 'test' }] }]
const mounts = jest.fn<void, [Element]>()
const mounts = jest.fn()
let el: ReactTestRenderer
@@ -30,8 +30,8 @@ describe('slate-react', () => {
el = create(
<Slate editor={editor} value={value} onChange={() => {}}>
<Editable
renderElement={({ element, children }) => {
React.useEffect(() => mounts(element), [])
renderElement={({ children }) => {
useEffect(() => mounts(), [])
return children
}}
@@ -56,7 +56,7 @@ describe('slate-react', () => {
{ type: 'block', children: [{ text: 'te' }] },
{ type: 'block', children: [{ text: 'st' }] },
]
const mounts = jest.fn<void, [Element]>()
const mounts = jest.fn()
let el: ReactTestRenderer
@@ -64,8 +64,8 @@ describe('slate-react', () => {
el = create(
<Slate editor={editor} value={value} onChange={() => {}}>
<Editable
renderElement={({ element, children }) => {
React.useEffect(() => mounts(element), [])
renderElement={({ children }) => {
useEffect(() => mounts(), [])
return children
}}