import getDirection from 'direction' import debounce from 'lodash/debounce' import throttle from 'lodash/throttle' import React, { useCallback, useEffect, useMemo, useReducer, useRef, useState, forwardRef, ForwardedRef, } from 'react' import { JSX } from 'react' import scrollIntoView from 'scroll-into-view-if-needed' import { Editor, Element, Node, NodeEntry, Path, Range, Text, Transforms, DecoratedRange, LeafPosition, } from 'slate' import { useAndroidInputManager } from '../hooks/android-input-manager/use-android-input-manager' import useChildren from '../hooks/use-children' import { DecorateContext, useDecorateContext } from '../hooks/use-decorations' import { useIsomorphicLayoutEffect } from '../hooks/use-isomorphic-layout-effect' import { ReadOnlyContext } from '../hooks/use-read-only' import { useSlate } from '../hooks/use-slate' import { useTrackUserInput } from '../hooks/use-track-user-input' import { ReactEditor } from '../plugin/react-editor' import { TRIPLE_CLICK } from 'slate-dom' import { DOMElement, DOMRange, DOMText, getActiveElement, getDefaultView, getSelection, isDOMElement, isDOMNode, isPlainTextOnlyPaste, } from 'slate-dom' import { CAN_USE_DOM, HAS_BEFORE_INPUT_SUPPORT, IS_ANDROID, IS_CHROME, IS_FIREFOX, IS_FIREFOX_LEGACY, IS_IOS, IS_WEBKIT, IS_UC_MOBILE, IS_WECHATBROWSER, } from 'slate-dom' import { Hotkeys } from 'slate-dom' import { IS_NODE_MAP_DIRTY, EDITOR_TO_ELEMENT, EDITOR_TO_FORCE_RENDER, EDITOR_TO_PENDING_INSERTION_MARKS, EDITOR_TO_USER_MARKS, EDITOR_TO_USER_SELECTION, EDITOR_TO_WINDOW, ELEMENT_TO_NODE, IS_COMPOSING, IS_FOCUSED, IS_READ_ONLY, MARK_PLACEHOLDER_SYMBOL, NODE_TO_ELEMENT, PLACEHOLDER_SYMBOL, } from 'slate-dom' import { RestoreDOM } from './restore-dom/restore-dom' import { AndroidInputManager } from '../hooks/android-input-manager/android-input-manager' import { ComposingContext } from '../hooks/use-composing' import { useFlushDeferredSelectorsOnRender } from '../hooks/use-slate-selector' type DeferredOperation = () => void const Children = (props: Parameters[0]) => ( {useChildren(props)} ) /** * `RenderElementProps` are passed to the `renderElement` handler. */ export interface RenderElementProps { children: any element: Element attributes: { 'data-slate-node': 'element' 'data-slate-inline'?: true 'data-slate-void'?: true dir?: 'rtl' ref: any } } /** * `RenderChunkProps` are passed to the `renderChunk` handler */ export interface RenderChunkProps { highest: boolean lowest: boolean children: any attributes: { 'data-slate-chunk': true } } /** * `RenderLeafProps` are passed to the `renderLeaf` handler. */ export interface RenderLeafProps { children: any /** * The leaf node with any applied decorations. * If no decorations are applied, it will be identical to the `text` property. */ leaf: Text text: Text attributes: { 'data-slate-leaf': true } /** * The position of the leaf within the Text node, only present when the text node is split by decorations. */ leafPosition?: LeafPosition } /** * `RenderTextProps` are passed to the `renderText` handler. */ export interface RenderTextProps { text: Text children: any attributes: { 'data-slate-node': 'text' ref: any } } /** * `EditableProps` are passed to the `` component. */ export type EditableProps = { decorate?: (entry: NodeEntry) => DecoratedRange[] onDOMBeforeInput?: (event: InputEvent) => void placeholder?: string readOnly?: boolean role?: string style?: React.CSSProperties renderElement?: (props: RenderElementProps) => JSX.Element renderChunk?: (props: RenderChunkProps) => JSX.Element renderLeaf?: (props: RenderLeafProps) => JSX.Element renderText?: (props: RenderTextProps) => JSX.Element renderPlaceholder?: (props: RenderPlaceholderProps) => JSX.Element scrollSelectionIntoView?: (editor: ReactEditor, domRange: DOMRange) => void as?: React.ElementType disableDefaultStyles?: boolean } & React.TextareaHTMLAttributes /** * Editable. */ export const Editable = forwardRef( (props: EditableProps, forwardedRef: ForwardedRef) => { const defaultRenderPlaceholder = useCallback( (props: RenderPlaceholderProps) => , [] ) const { autoFocus, decorate = defaultDecorate, onDOMBeforeInput: propsOnDOMBeforeInput, placeholder, readOnly = false, renderElement, renderChunk, renderLeaf, renderText, renderPlaceholder = defaultRenderPlaceholder, scrollSelectionIntoView = defaultScrollSelectionIntoView, style: userStyle = {}, as: Component = 'div', disableDefaultStyles = false, ...attributes } = props const editor = useSlate() // Rerender editor when composition status changed const [isComposing, setIsComposing] = useState(false) const ref = useRef(null) const deferredOperations = useRef([]) const [placeholderHeight, setPlaceholderHeight] = useState< number | undefined >() const processing = useRef(false) const { onUserInput, receivedUserInput } = useTrackUserInput() const [, forceRender] = useReducer(s => s + 1, 0) EDITOR_TO_FORCE_RENDER.set(editor, forceRender) // Update internal state on each render. IS_READ_ONLY.set(editor, readOnly) // Keep track of some state for the event handler logic. const state = useMemo( () => ({ isDraggingInternally: false, isUpdatingSelection: false, latestElement: null as DOMElement | null, hasMarkPlaceholder: false, }), [] ) // The autoFocus TextareaHTMLAttribute doesn't do anything on a div, so it // needs to be manually focused. // // If this stops working in Firefox, make sure nothing is causing this // component to re-render during the initial mount. If the DOM selection is // set by `useIsomorphicLayoutEffect` before `onDOMSelectionChange` updates // `editor.selection`, the DOM selection can be removed accidentally. useEffect(() => { if (ref.current && autoFocus) { ref.current.focus() } }, [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 = useMemo( () => throttle(() => { if (IS_NODE_MAP_DIRTY.get(editor)) { onDOMSelectionChange() return } const el = ReactEditor.toDOMNode(editor, editor) const root = el.getRootNode() if (!processing.current && IS_WEBKIT && root instanceof ShadowRoot) { processing.current = true const active = getActiveElement() if (active) { document.execCommand('indent') } else { Transforms.deselect(editor) } processing.current = false return } 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 = getSelection(root) if (activeElement === el) { state.latestElement = activeElement IS_FOCUSED.set(editor, true) } else { IS_FOCUSED.delete(editor) } if (!domSelection) { return Transforms.deselect(editor) } const { anchorNode, focusNode } = domSelection const anchorNodeSelectable = ReactEditor.hasEditableTarget(editor, anchorNode) || ReactEditor.isTargetInsideNonReadonlyVoid(editor, anchorNode) const focusNodeInEditor = ReactEditor.hasTarget(editor, focusNode) if (anchorNodeSelectable && focusNodeInEditor) { 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) } } } // Deselect the editor if the dom selection is not selectable in readonly mode if (readOnly && (!anchorNodeSelectable || !focusNodeInEditor)) { Transforms.deselect(editor) } } }, 100), [editor, readOnly, state] ) const scheduleOnDOMSelectionChange = useMemo( () => debounce(onDOMSelectionChange, 0), [onDOMSelectionChange] ) androidInputManagerRef.current = useAndroidInputManager({ node: ref, onDOMSelectionChange, scheduleOnDOMSelectionChange, }) useIsomorphicLayoutEffect(() => { // Update element-related weak maps with the DOM element ref. let window if (ref.current && (window = getDefaultView(ref.current))) { EDITOR_TO_WINDOW.set(editor, window) EDITOR_TO_ELEMENT.set(editor, ref.current) NODE_TO_ELEMENT.set(editor, ref.current) ELEMENT_TO_NODE.set(ref.current, editor) } else { NODE_TO_ELEMENT.delete(editor) } // Make sure the DOM selection state is in sync. const { selection } = editor const root = ReactEditor.findDocumentOrShadowRoot(editor) const domSelection = getSelection(root) if ( !domSelection || !ReactEditor.isFocused(editor) || androidInputManagerRef.current?.hasPendingAction() ) { return } const setDomSelection = (forceChange?: boolean) => { const hasDomSelection = domSelection.type !== 'None' // If the DOM selection is properly unset, we're done. if (!selection && !hasDomSelection) { return } // Get anchorNode and focusNode const focusNode = domSelection.focusNode let anchorNode // COMPAT: In firefox the normal selection way does not work // (https://github.com/ianstormtaylor/slate/pull/5486#issue-1820720223) if (IS_FIREFOX && domSelection.rangeCount > 1) { const firstRange = domSelection.getRangeAt(0) const lastRange = domSelection.getRangeAt(domSelection.rangeCount - 1) // Right to left if (firstRange.startContainer === focusNode) { anchorNode = lastRange.endContainer } else { // Left to right anchorNode = firstRange.startContainer } } else { anchorNode = domSelection.anchorNode } // verify that the dom selection is in the editor const editorElement = EDITOR_TO_ELEMENT.get(editor)! let hasDomSelectionInEditor = false if ( editorElement.contains(anchorNode) && editorElement.contains(focusNode) ) { hasDomSelectionInEditor = true } // If the DOM selection is in the editor and the editor selection is already correct, we're done. if ( hasDomSelection && hasDomSelectionInEditor && selection && !forceChange ) { const slateRange = ReactEditor.toSlateRange(editor, domSelection, { exactMatch: true, // domSelection is not necessarily a valid Slate range // (e.g. when clicking on contentEditable:false element) suppressThrow: true, }) if (slateRange && Range.equals(slateRange, selection)) { if (!state.hasMarkPlaceholder) { return } // Ensure selection is inside the mark placeholder if ( anchorNode?.parentElement?.hasAttribute( 'data-slate-mark-placeholder' ) ) { return } } } // when is being controlled through external value // then its children might just change - DOM responds to it on its own // but Slate's value is not being updated through any operation // and thus it doesn't transform selection on its own if (selection && !ReactEditor.hasRange(editor, selection)) { editor.selection = ReactEditor.toSlateRange(editor, domSelection, { exactMatch: false, suppressThrow: true, }) return } // Otherwise the DOM selection is out of sync, so update it. state.isUpdatingSelection = true let newDomRange: DOMRange | null = null try { newDomRange = selection && ReactEditor.toDOMRange(editor, selection) } catch (e) { // Ignore, dom and state might be out of sync } if (newDomRange) { if (ReactEditor.isComposing(editor) && !IS_ANDROID) { domSelection.collapseToEnd() } else if (Range.isBackward(selection!)) { domSelection.setBaseAndExtent( newDomRange.endContainer, newDomRange.endOffset, newDomRange.startContainer, newDomRange.startOffset ) } else { domSelection.setBaseAndExtent( newDomRange.startContainer, newDomRange.startOffset, newDomRange.endContainer, newDomRange.endOffset ) } scrollSelectionIntoView(editor, newDomRange) } else { domSelection.removeAllRanges() } return newDomRange } // In firefox if there is more then 1 range and we call setDomSelection we remove the ability to select more cells in a table if (domSelection.rangeCount <= 1) { setDomSelection() } const ensureSelection = androidInputManagerRef.current?.isFlushing() === 'action' if (!IS_ANDROID || !ensureSelection) { setTimeout(() => { state.isUpdatingSelection = false }) return } let timeoutId: ReturnType | null = null const animationFrameId = requestAnimationFrame(() => { if (ensureSelection) { const ensureDomSelection = (forceChange?: boolean) => { try { const el = ReactEditor.toDOMNode(editor, editor) el.focus() setDomSelection(forceChange) } catch (e) { // Ignore, dom and state might be out of sync } } // Compat: Android IMEs try to force their selection by manually re-applying it even after we set it. // This essentially would make setting the slate selection during an update meaningless, so we force it // again here. We can't only do it in the setTimeout after the animation frame since that would cause a // visible flicker. ensureDomSelection() timeoutId = setTimeout(() => { // COMPAT: While setting the selection in an animation frame visually correctly sets the selection, // it doesn't update GBoards spellchecker state. We have to manually trigger a selection change after // the animation frame to ensure it displays the correct state. ensureDomSelection(true) state.isUpdatingSelection = false }) } }) return () => { cancelAnimationFrame(animationFrameId) if (timeoutId) { clearTimeout(timeoutId) } } }) // Listen on the native `beforeinput` event to get real "Level 2" events. This // is required because React's `beforeinput` is fake and never really attaches // to the real event sadly. (2019/11/01) // https://github.com/facebook/react/issues/11211 const onDOMBeforeInput = useCallback( (event: InputEvent) => { handleNativeHistoryEvents(editor, event) const el = ReactEditor.toDOMNode(editor, editor) const root = el.getRootNode() if (processing?.current && IS_WEBKIT && root instanceof ShadowRoot) { const ranges = event.getTargetRanges() const range = ranges[0] const newRange = new window.Range() newRange.setStart(range.startContainer, range.startOffset) newRange.setEnd(range.endContainer, range.endOffset) // Translate the DOM Range into a Slate Range const slateRange = ReactEditor.toSlateRange(editor, newRange, { exactMatch: false, suppressThrow: false, }) Transforms.select(editor, slateRange) event.preventDefault() event.stopImmediatePropagation() return } onUserInput() if ( !readOnly && ReactEditor.hasEditableTarget(editor, event.target) && !isDOMEventHandled(event, propsOnDOMBeforeInput) ) { // COMPAT: BeforeInput events aren't cancelable on android, so we have to handle them differently using the android input manager. if (androidInputManagerRef.current) { return androidInputManagerRef.current.handleDOMBeforeInput(event) } // Some IMEs/Chrome extensions like e.g. Grammarly set the selection immediately before // triggering a `beforeinput` expecting the change to be applied to the immediately before // set selection. scheduleOnDOMSelectionChange.flush() onDOMSelectionChange.flush() const { selection } = editor const { inputType: type } = event const data = (event as any).dataTransfer || event.data || undefined const isCompositionChange = type === 'insertCompositionText' || type === 'deleteCompositionText' // COMPAT: use composition change events as a hint to where we should insert // composition text if we aren't composing to work around https://github.com/ianstormtaylor/slate/issues/5038 if (isCompositionChange && ReactEditor.isComposing(editor)) { return } let native = false if ( type === 'insertText' && selection && Range.isCollapsed(selection) && // Only use native character insertion for single characters a-z or space for now. // Long-press events (hold a + press 4 = รค) to choose a special character otherwise // causes duplicate inserts. event.data && event.data.length === 1 && /[a-z ]/i.test(event.data) && // Chrome has issues correctly editing the start of nodes: https://bugs.chromium.org/p/chromium/issues/detail?id=1249405 // When there is an inline element, e.g. a link, and you select // right after it (the start of the next node). selection.anchor.offset !== 0 ) { native = true // Skip native if there are marks, as // `insertText` will insert a node, not just text. if (editor.marks) { native = false } // If the NODE_MAP is dirty, we can't trust the selection anchor (eg ReactEditor.toDOMPoint) if (!IS_NODE_MAP_DIRTY.get(editor)) { // Chrome also has issues correctly editing the end of anchor elements: https://bugs.chromium.org/p/chromium/issues/detail?id=1259100 // Therefore we don't allow native events to insert text at the end of anchor nodes. const { anchor } = selection const [node, offset] = ReactEditor.toDOMPoint(editor, anchor) const anchorNode = node.parentElement?.closest('a') const window = ReactEditor.getWindow(editor) if ( native && anchorNode && ReactEditor.hasDOMNode(editor, anchorNode) ) { // Find the last text node inside the anchor. const lastText = window?.document .createTreeWalker(anchorNode, NodeFilter.SHOW_TEXT) .lastChild() as DOMText | null if ( lastText === node && lastText.textContent?.length === offset ) { native = false } } // Chrome has issues with the presence of tab characters inside elements with whiteSpace = 'pre' // causing abnormal insert behavior: https://bugs.chromium.org/p/chromium/issues/detail?id=1219139 if ( native && node.parentElement && window?.getComputedStyle(node.parentElement)?.whiteSpace === 'pre' ) { const block = Editor.above(editor, { at: anchor.path, match: n => Element.isElement(n) && Editor.isBlock(editor, n), }) if (block && Node.string(block[0]).includes('\t')) { native = false } } } } // COMPAT: For the deleting forward/backward input types we don't want // to change the selection because it is the range that will be deleted, // and those commands determine that for themselves. // If the NODE_MAP is dirty, we can't trust the selection anchor (eg ReactEditor.toDOMPoint via ReactEditor.toSlateRange) if ( (!type.startsWith('delete') || type.startsWith('deleteBy')) && !IS_NODE_MAP_DIRTY.get(editor) ) { const [targetRange] = (event as any).getTargetRanges() if (targetRange) { const range = ReactEditor.toSlateRange(editor, targetRange, { exactMatch: false, suppressThrow: false, }) if (!selection || !Range.equals(selection, range)) { native = false const selectionRef = !isCompositionChange && editor.selection && Editor.rangeRef(editor, editor.selection) Transforms.select(editor, range) if (selectionRef) { EDITOR_TO_USER_SELECTION.set(editor, selectionRef) } } } } // Composition change types occur while a user is composing text and can't be // cancelled. Let them through and wait for the composition to end. if (isCompositionChange) { return } if (!native) { event.preventDefault() } // COMPAT: If the selection is expanded, even if the command seems like // a delete forward/backward command it should delete the selection. if ( selection && Range.isExpanded(selection) && type.startsWith('delete') ) { const direction = type.endsWith('Backward') ? 'backward' : 'forward' Editor.deleteFragment(editor, { direction }) return } switch (type) { case 'deleteByComposition': case 'deleteByCut': case 'deleteByDrag': { Editor.deleteFragment(editor) break } case 'deleteContent': case 'deleteContentForward': { Editor.deleteForward(editor) break } case 'deleteContentBackward': { Editor.deleteBackward(editor) break } case 'deleteEntireSoftLine': { Editor.deleteBackward(editor, { unit: 'line' }) Editor.deleteForward(editor, { unit: 'line' }) break } case 'deleteHardLineBackward': { Editor.deleteBackward(editor, { unit: 'block' }) break } case 'deleteSoftLineBackward': { Editor.deleteBackward(editor, { unit: 'line' }) break } case 'deleteHardLineForward': { Editor.deleteForward(editor, { unit: 'block' }) break } case 'deleteSoftLineForward': { Editor.deleteForward(editor, { unit: 'line' }) break } case 'deleteWordBackward': { Editor.deleteBackward(editor, { unit: 'word' }) break } case 'deleteWordForward': { Editor.deleteForward(editor, { unit: 'word' }) break } case 'insertLineBreak': Editor.insertSoftBreak(editor) break case 'insertParagraph': { Editor.insertBreak(editor) break } case 'insertFromComposition': case 'insertFromDrop': case 'insertFromPaste': case 'insertFromYank': case 'insertReplacementText': case 'insertText': { if (type === 'insertFromComposition') { // COMPAT: in Safari, `compositionend` is dispatched after the // `beforeinput` for "insertFromComposition". But if we wait for it // then we will abort because we're still composing and the selection // won't be updated properly. // https://www.w3.org/TR/input-events-2/ if (ReactEditor.isComposing(editor)) { setIsComposing(false) IS_COMPOSING.set(editor, false) } } // use a weak comparison instead of 'instanceof' to allow // programmatic access of paste events coming from external windows // like cypress where cy.window does not work realibly if (data?.constructor.name === 'DataTransfer') { ReactEditor.insertData(editor, data) } else if (typeof data === 'string') { // Only insertText operations use the native functionality, for now. // Potentially expand to single character deletes, as well. if (native) { deferredOperations.current.push(() => Editor.insertText(editor, data) ) } else { Editor.insertText(editor, data) } } break } } // Restore the actual user section if nothing manually set it. const toRestore = EDITOR_TO_USER_SELECTION.get(editor)?.unref() EDITOR_TO_USER_SELECTION.delete(editor) if ( toRestore && (!editor.selection || !Range.equals(editor.selection, toRestore)) ) { Transforms.select(editor, toRestore) } } }, [ editor, onDOMSelectionChange, onUserInput, propsOnDOMBeforeInput, readOnly, scheduleOnDOMSelectionChange, ] ) const callbackRef = useCallback( (node: HTMLDivElement | null) => { if (node == null) { onDOMSelectionChange.cancel() scheduleOnDOMSelectionChange.cancel() EDITOR_TO_ELEMENT.delete(editor) NODE_TO_ELEMENT.delete(editor) if (ref.current && HAS_BEFORE_INPUT_SUPPORT) { // @ts-ignore The `beforeinput` event isn't recognized. ref.current.removeEventListener('beforeinput', onDOMBeforeInput) } } else { // Attach a native DOM event handler for `beforeinput` events, because React's // built-in `onBeforeInput` is actually a leaky polyfill that doesn't expose // real `beforeinput` events sadly... (2019/11/04) // https://github.com/facebook/react/issues/11211 if (HAS_BEFORE_INPUT_SUPPORT) { // @ts-ignore The `beforeinput` event isn't recognized. node.addEventListener('beforeinput', onDOMBeforeInput) } } ref.current = node if (typeof forwardedRef === 'function') { forwardedRef(node) } else if (forwardedRef) { forwardedRef.current = node } }, [ onDOMSelectionChange, scheduleOnDOMSelectionChange, editor, onDOMBeforeInput, forwardedRef, ] ) useIsomorphicLayoutEffect(() => { const window = ReactEditor.getWindow(editor) // COMPAT: In Chrome, `selectionchange` events can fire when and //