/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ import type { AnyLexicalCommand, InputState, LexicalCommand, LexicalEditor, } from './LexicalEditor'; import type {KeyboardShortcutMatch} from './LexicalKeyboardShortcuts'; import type {LexicalNode, NodeKey} from './LexicalNode'; import type {ElementNode} from './nodes/LexicalElementNode'; import type {TextNode} from './nodes/LexicalTextNode'; import invariant from '@lexical/internal/invariant'; import warnOnlyOnce from '@lexical/internal/warnOnlyOnce'; import { $createRangeSelection, $createTextNode, $getChildCaret, $getPreviousSelection, $getRoot, $getSelection, $getSiblingCaret, $isBlockElementNode, $isDecoratorNode, $isElementNode, $isLineBreakNode, $isNodeSelection, $isRangeSelection, $isRootNode, $isTabNode, $isTextNode, $setCompositionKey, $setPointFromCaret, BLUR_COMMAND, type CaretDirection, CLICK_COMMAND, COMMAND_PRIORITY_EDITOR, COMPOSITION_END_TAG, COMPOSITION_START_TAG, CONTROLLED_TEXT_INSERTION_COMMAND, COPY_COMMAND, CUT_COMMAND, DELETE_CHARACTER_COMMAND, DELETE_LINE_COMMAND, DELETE_WORD_COMMAND, DRAGEND_COMMAND, DRAGOVER_COMMAND, DRAGSTART_COMMAND, DROP_COMMAND, FOCUS_COMMAND, FORMAT_TEXT_COMMAND, INSERT_LINE_BREAK_COMMAND, INSERT_PARAGRAPH_COMMAND, KEY_ARROW_DOWN_COMMAND, KEY_ARROW_LEFT_COMMAND, KEY_ARROW_RIGHT_COMMAND, KEY_ARROW_UP_COMMAND, KEY_BACKSPACE_COMMAND, KEY_DELETE_COMMAND, KEY_DOWN_COMMAND, KEY_ENTER_COMMAND, KEY_ESCAPE_COMMAND, KEY_SPACE_COMMAND, KEY_TAB_COMMAND, MOVE_TO_END, MOVE_TO_START, PASTE_COMMAND, REDO_COMMAND, REMOVE_TEXT_COMMAND, type SiblingCaret, SKIP_SELECTION_FOCUS_TAG, UNDO_COMMAND, } from '.'; import { CAN_USE_BEFORE_INPUT, IS_ANDROID_CHROME, IS_APPLE, IS_APPLE_WEBKIT, IS_CHROME, IS_FIREFOX, IS_IOS, IS_SAFARI, } from './environment'; import { BEFORE_INPUT_COMMAND, COMPOSITION_END_COMMAND, COMPOSITION_START_COMMAND, INPUT_COMMAND, KEY_MODIFIER_COMMAND, SELECT_ALL_COMMAND, } from './LexicalCommands'; import { COMPOSITION_START_CHAR, DOM_ELEMENT_TYPE, DOUBLE_LINE_BREAK, IS_ALL_FORMATTING, } from './LexicalConstants'; import { compileKeyboardShortcuts, CONTROL_OR_ALT, CONTROL_OR_META, } from './LexicalKeyboardShortcuts'; import {createRefCountedRegistry} from './LexicalRefCountedRegistry'; import { $createPoint, $createRangeSelectionFromDom, $getPointSlotFrame, $internalCreateRangeSelection, $internalRefreshSelectionFormatAndStyle, $internalResolveSelectionPoint, $isSameFrame, $prepareCompositionTarget, type RangeSelection, } from './LexicalSelection'; import { $dispatchSelectionChangeCommand, getActiveEditor, updateEditorSync, } from './LexicalUpdates'; import { $addUpdateTag, $findMatchingParent, $flushMutations, $getAdjacentNode, $getDOMTextNode, $getNearestNodeFromDOMNode, $getNodeByKey, $isEventFromEmbeddedInput, $isSelectionCapturedInDecoratorInput, $isTokenOrSegmented, $isTokenOrTab, $setSelection, $shouldInsertTextAfterOrBeforeTextNode, $updateSelectedTextFromDOM, $updateTextNodeFromDOMContent, dispatchCommand, doesContainSurrogatePair, type DOMSelectionBoundaryPoints, getActiveElementDeep, getAnchorTextFromDOM, getComposedEventTarget, getDOMOwnerDocument, getDOMSelection, getDOMSelectionFromTarget, getDOMSelectionPoints, getEditorPropertyFromDOMNode, getEditorsToPropagate, getNearestEditorFromDOMNode, getParentElement, getWindow, isDOMCapturingSelection, isDOMDocumentNode, isDOMNode, isDOMShadowRoot, isDOMTextNode, isFirefoxClipboardEvents, isHTMLElement, isLexicalEditor, isModifier, isSelectionWithinEditor, type KeyboardEventModifierMask, } from './LexicalUtils'; import {mergeRegister} from './utils/mergeRegister'; import {registerEventListener} from './utils/registerEventListener'; import {registerEventListeners} from './utils/registerEventListeners'; type RootElementRemoveHandles = (() => void)[]; // Each root element event is handled by a function or dispatched as a // command. A method type, so that a handler can take the event's own type. type RootElementEvents = Record< string, | AnyLexicalCommand | {handle(event: Event, editor: LexicalEditor): void}['handle'] >; const ANDROID_COMPOSITION_LATENCY = 30; // Node can be moved between documents (for example using createPortal), so we // need to track the document each root element was originally registered on. const rootElementToDocument = new WeakMap(); // Per-document state read by the shared `selectionchange` handler, keyed by the // document each root element was registered against: // - `editors` is the candidate set `onDocumentSelectionChange` attributes the // event to, using each editor's shadow-aware anchor rather than guessing from // `Selection.anchorNode` (retargeted to a light-DOM ancestor inside a shadow // tree). // - `hasShadowEditor` caches whether any editor here is shadow-mounted // (`undefined` = needs recompute), so the handler avoids an O(editors) // `getRootNode()` scan per selectionchange. Invalidated whenever the editor // set changes — which, via setRootElement, is where an editor's root (and // thus its shadow-mounted status) is rebound. interface DocumentRegistration { editors: Set; hasShadowEditor: boolean | undefined; } const documentRegistrations = new WeakMap(); // The single shared `selectionchange` listener per document, reference counted // across all editors registered against that document: attached when the first // root element is registered and removed when the last one is unregistered. const documentSelectionChange = createRefCountedRegistry((doc: Document) => { doc.addEventListener('selectionchange', onDocumentSelectionChange); return () => doc.removeEventListener('selectionchange', onDocumentSelectionChange); }); // This function is used to determine if Lexical should attempt to override // the default browser behavior for insertion of text and use its own internal // heuristics. This is an extremely important function, and makes much of Lexical // work as intended between different browsers and across word, line and character // boundary/formats. It also is important for text replacement, node schemas and // composition mechanics. function $shouldPreventDefaultAndInsertText( selection: RangeSelection, domTargetRange: null | StaticRange, text: string, timeStamp: number, isBeforeInput: boolean, cachedDOMSelectionPoints?: DOMSelectionBoundaryPoints | null, ): boolean { const anchor = selection.anchor; const focus = selection.focus; const anchorNode = anchor.getNode(); const editor = getActiveEditor(); let domSelectionPoints: DOMSelectionBoundaryPoints | null; if (cachedDOMSelectionPoints !== undefined) { domSelectionPoints = cachedDOMSelectionPoints; } else { const domSelection = getDOMSelection(getWindow(editor)); domSelectionPoints = domSelection !== null ? getDOMSelectionPoints(domSelection, editor._rootElement) : null; } const domAnchorNode = domSelectionPoints !== null ? domSelectionPoints.anchorNode : null; const anchorKey = anchor.key; const backingAnchorElement = editor.getElementByKey(anchorKey); const textLength = text.length; return ( anchorKey !== focus.key || // If we're working with a non-text node. !$isTextNode(anchorNode) || // If we are replacing a range with a single character or grapheme, and not composing. (((!isBeforeInput && (!CAN_USE_BEFORE_INPUT || // We check to see if there has been // a recent beforeinput event for "textInput". If there has been one in the last // 50ms then we proceed as normal. However, if there is not, then this is likely // a dangling `input` event caused by execCommand('insertText'). editor._inputState.lastBeforeInputInsertTextTimeStamp < timeStamp + 50)) || (anchorNode.isDirty() && textLength < 2) || // TODO consider if there are other scenarios when multiple code units // should be addressed here doesContainSurrogatePair(text)) && anchor.offset !== focus.offset && !anchorNode.isComposing()) || // Any non standard text node. $isTokenOrSegmented(anchorNode) || // If the text length is more than a single character and we're either // dealing with this in "beforeinput" or where the node has already recently // been changed (thus is dirty). (anchorNode.isDirty() && textLength > 1) || // If the DOM selection element is not the same as the backing node during beforeinput. ((isBeforeInput || !CAN_USE_BEFORE_INPUT) && backingAnchorElement !== null && !anchorNode.isComposing() && domAnchorNode !== $getDOMTextNode(anchorNode, backingAnchorElement, editor)) || // If TargetRange is not the same as the DOM selection; browser trying to edit random parts // of the editor. (domSelectionPoints !== null && domTargetRange !== null && (!domTargetRange.collapsed || domTargetRange.startContainer !== domSelectionPoints.anchorNode || domTargetRange.startOffset !== domSelectionPoints.anchorOffset)) || // Check if we're changing from bold to italics, or some other format. (!anchorNode.isComposing() && (anchorNode.getFormat() !== selection.format || anchorNode.getStyle() !== selection.style)) || // One last set of heuristics to check against. $shouldInsertTextAfterOrBeforeTextNode(selection, anchorNode) ); } function shouldSkipSelectionChange( domNode: null | Node, offset: number, ): boolean { return ( isDOMTextNode(domNode) && domNode.nodeValue !== null && offset !== 0 && offset !== domNode.nodeValue.length ); } function onSelectionChange( domSelection: Selection, editor: LexicalEditor, isActive: boolean, ): void { // Shadow-aware boundary points so isSelectionWithinEditor below isn't // fooled by the retargeted shadow host into dropping the selection. const { anchorNode: anchorDOM, anchorOffset, focusNode: focusDOM, focusOffset, } = getDOMSelectionPoints(domSelection, editor._rootElement); const inputState = editor._inputState; if (inputState.isSelectionChangeFromDOMUpdate) { inputState.isSelectionChangeFromDOMUpdate = false; const appliedPoints = inputState.selectionChangeFromDOMUpdatePoints; inputState.selectionChangeFromDOMUpdatePoints = null; // If native DOM selection is on a DOM element, then // we should continue as usual, as Lexical's selection // may have normalized to a better child. If the DOM // element is a text node, we can safely apply this // optimization and skip the selection change entirely. // We also need to check if the offset is at the boundary, // because in this case, we might need to normalize to a // sibling instead. // // The skip is only safe when this event actually observes the selection // the reconciler applied. The flag can outlive its own event — WebKit // fires no selectionchange when the applied selection matches what the // DOM already had — and then the next real user selection (e.g. a click // into text after select-all) would be swallowed here. if ( shouldSkipSelectionChange(anchorDOM, anchorOffset) && shouldSkipSelectionChange(focusDOM, focusOffset) && !inputState.postDeleteSelectionToRestore && (appliedPoints === null || (appliedPoints.anchorNode === anchorDOM && appliedPoints.anchorOffset === anchorOffset && appliedPoints.focusNode === focusDOM && appliedPoints.focusOffset === focusOffset)) ) { return; } } updateEditorSync(editor, () => { // Non-active editor don't need any extra logic for selection, it only needs update // to reconcile selection (set it to null) to ensure that only one editor has non-null selection. if (!isActive) { $setSelection(null); return; } if (!isSelectionWithinEditor(editor, anchorDOM, focusDOM)) { return; } // Not for a press that a listener after the editor's cancelled, which // the browser does not select from either. const drag = inputState.mouseDrag; if (drag && !(drag.type === 'mousedown' && drag.defaultPrevented)) { $adjustMouseDrag(editor, drag, focusDOM); } // Whether the adjustment for the drag's latest mouse event moved the // selection from the DOM's, which notified it. const isAdjusted = adjustedMouseEvents.has(drag as MouseEvent); let selection = $getSelection(); // Restore selection in the event of incorrect rightward shift after deletion if ( inputState.postDeleteSelectionToRestore && $isRangeSelection(selection) && selection.isCollapsed() ) { const curAnchor = selection.anchor; const prevAnchor = inputState.postDeleteSelectionToRestore.anchor; if ( // Rightward shift in same node (curAnchor.key === prevAnchor.key && curAnchor.offset === prevAnchor.offset + 1) || // Or rightward shift into sibling node (curAnchor.offset === 1 && prevAnchor.getNode().is(curAnchor.getNode().getPreviousSibling())) ) { // Restore selection selection = inputState.postDeleteSelectionToRestore.clone(); $setSelection(selection); } } inputState.postDeleteSelectionToRestore = null; // Update the selection format if ($isRangeSelection(selection)) { const anchor = selection.anchor; if (selection.isCollapsed()) { // Badly interpreted range selection when collapsed - #1482 if (domSelection.type === 'Range' && anchorDOM === focusDOM) { selection.dirty = true; } $updateCollapsedSelectionFormatStyle(editor, selection); } else { const anchorKey = anchor.key; const focus = selection.focus; const focusKey = focus.key; const nodes = selection.getNodes(); const nodesLength = nodes.length; const isBackward = selection.isBackward(); // Its own offsets, which go with its keys, where it is not the DOM's. const [anchorAt, focusAt] = isAdjusted ? [anchor.offset, focus.offset] : [anchorOffset, focusOffset]; const startOffset = isBackward ? focusAt : anchorAt; const endOffset = isBackward ? anchorAt : focusAt; const startKey = isBackward ? focusKey : anchorKey; const endKey = isBackward ? anchorKey : focusKey; let combinedFormat = IS_ALL_FORMATTING; let hasTextNodes = false; for (let i = 0; i < nodesLength; i++) { const node = nodes[i]; const textContentSize = node.getTextContentSize(); if ( $isTextNode(node) && textContentSize !== 0 && // Exclude empty text nodes at boundaries resulting from user's selection !( (i === 0 && node.__key === startKey && startOffset === textContentSize) || (i === nodesLength - 1 && node.__key === endKey && endOffset === 0) ) ) { // TODO: what about style? hasTextNodes = true; combinedFormat &= node.getFormat(); if (combinedFormat === 0) { break; } } } selection.format = hasTextNodes ? combinedFormat : 0; } } // Not again when the adjustment notified it. $dispatchSelectionChangeCommand( editor, selection, selection !== null && ((selection.dirty && !isAdjusted) || !$isRangeSelection(selection)), ); }); } function $updateSelectionFormatStyle( selection: RangeSelection, format: number, style: string, ) { if (selection.format !== format || selection.style !== style) { selection.format = format; selection.style = style; selection.dirty = true; } } function $updateSelectionFormatStyleFromTextNode( selection: RangeSelection, node: TextNode, ) { const format = node.getFormat(); const style = node.getStyle(); $updateSelectionFormatStyle(selection, format, style); } /** * Gives a caret the format and style of where it is, as a selectionchange * does, unless the editor has just put it there with its own. */ function $updateCollapsedSelectionFormatStyle( editor: LexicalEditor, selection: RangeSelection, ): void { const anchor = selection.anchor; const anchorNode = anchor.getNode(); // If we have marked a collapsed selection format, and we're // within the given time range – then attempt to use that format // instead of getting the format from the anchor node. const windowEvent = getWindow(editor).event; const currentTimeStamp = windowEvent ? windowEvent.timeStamp : performance.now(); const { format: lastFormat, style: lastStyle, offset: lastOffset, key: lastKey, timeStamp, } = editor._inputState.collapsedSelectionFormat; if ( currentTimeStamp < timeStamp + 200 && anchor.offset === lastOffset && anchor.key === lastKey ) { $updateSelectionFormatStyle(selection, lastFormat, lastStyle); } else if (anchor.type === 'text') { invariant( $isTextNode(anchorNode), 'Point.getNode() must return TextNode when type is text', ); $updateSelectionFormatStyleFromTextNode(selection, anchorNode); } else if ( // An element point, unless nothing is composing and the root has no text editor.isComposing() || $getRoot().getTextContent() !== '' ) { invariant( $isElementNode(anchorNode), 'Point.getNode() must return ElementNode when type is element', ); if ( // This previously applied to all ParagraphNode anchorNode.isEmpty() ) { $internalRefreshSelectionFormatAndStyle(selection, ''); } else { $updateSelectionFormatStyle(selection, selection.format, ''); } } } // This is a work-around is mainly Chrome specific bug where if you select // the contents of an empty block, you cannot easily unselect anything. // This results in a tiny selection box that looks buggy/broken. This can // also help other browsers when selection might "appear" lost, when it // really isn't. function onClick(event: PointerEvent, editor: LexicalEditor): void { updateEditorSync(editor, () => { const selection = $getSelection(); const domSelection = getDOMSelection(getWindow(editor)); const lastSelection = $getPreviousSelection(); if (domSelection) { if ($isRangeSelection(selection)) { const anchor = selection.anchor; const anchorNode = anchor.getNode(); if ( anchor.type === 'element' && anchor.offset === 0 && selection.isCollapsed() && !$isRootNode(anchorNode) && $getRoot().getChildrenSize() === 1 && anchorNode.getTopLevelElementOrThrow().isEmpty() && lastSelection !== null && selection.is(lastSelection) ) { domSelection.removeAllRanges(); selection.dirty = true; } } else if ( event.pointerType === 'touch' || event.pointerType === 'pen' || // iOS reports the click that follows a tap with pointerType 'mouse', // and fires it before the selectionchange for the caret the tap just // placed. Without this, the NodeSelection survives into CLICK_COMMAND, // where rich text clears it and the reconciler removes that caret, so // the keyboard opens with no caret to reveal and the page jumps. The // tap's pointerdown is still 'touch' (or 'pen'); an iPadOS trackpad // click is handled by selectionchange like any other mouse click. (IS_IOS && editor._inputState.lastPointerType !== 'mouse') ) { // This is used to update the selection on touch devices (including Apple Pencil) when the user clicks on text after a // node selection. See isSelectionChangeFromMouseDown for the inverse const domSelectionPoints = getDOMSelectionPoints( domSelection, editor._rootElement, ); const domAnchorNode = domSelectionPoints.anchorNode; // If the user is attempting to click selection back onto text, then // we should attempt create a range selection. // When we click on an empty paragraph node or the end of a paragraph that ends // with an image/poll, the nodeType will be ELEMENT_NODE if (isHTMLElement(domAnchorNode) || isDOMTextNode(domAnchorNode)) { const newSelection = $internalCreateRangeSelection( lastSelection, domSelection, editor, event, ); $setSelection(newSelection); } } } // Firefox produces no DOM range when clicking between block-level // decorators (rangeCount === 0). Use click coordinates to compute // the correct child offset. Only act when the click landed directly // on the root element (not inside a child like a table cell). if (IS_FIREFOX && domSelection !== null && domSelection.rangeCount === 0) { const rootElement = editor._rootElement; if (rootElement !== null && event.target === rootElement) { const clientY = event.clientY; let offset = rootElement.childNodes.length; for (let i = 0; i < rootElement.childNodes.length; i++) { const child = rootElement.childNodes[i]; if (isHTMLElement(child)) { const rect = child.getBoundingClientRect(); if (clientY <= (rect.top + rect.bottom) / 2) { offset = i; break; } } } domSelection.setBaseAndExtent(rootElement, offset, rootElement, offset); const newSelection = $internalCreateRangeSelection( lastSelection, domSelection, editor, event, ); if (newSelection !== null) { $setSelection(newSelection); } else { domSelection.removeAllRanges(); } } } dispatchCommand(editor, CLICK_COMMAND, event); }); } // How far a touch may move and still count as a tap rather than a scroll. const TAP_SLOP_PX = 10; // Elements that take a tap (focus, text input, or their own controls) instead // of letting it fall through to the editor. `[tabindex]` includes // tabindex="-1", which makes an element focusable by tap but not by Tab. const FOCUSABLE_SELECTOR = 'input:not(:disabled),textarea:not(:disabled),select:not(:disabled),' + 'button:not(:disabled),a[href],area[href],label,summary,iframe,object,' + 'embed,audio[controls],video[controls],[tabindex],' + '[contenteditable]:not([contenteditable="false"])'; // iOS only. A tap on a decorator (an image, say) would focus the editor, and // iOS answers that focus by opening the keyboard and scrolling to reveal the // caret. A decorator is selected with a NodeSelection, which leaves no DOM // caret, so iOS reveals the top of the editor instead and the page jumps // (facebook/lexical#9112). Cancelling the mousedown keeps the keyboard closed; // the click still follows, so CLICK_COMMAND handlers select the node as usual. // // When the editor did not have focus, it is focused from code instead, with // `inputmode="none"` so no keyboard opens and `preventScroll` so nothing // moves. Keys from an iPad hardware keyboard (Backspace to delete the image) // then reach the editor. The root's own `inputmode` comes back with the next // press that isn't cancelled, or when the editor loses focus. A tap on text // first blurs the editor (see onTouchEndIOS), so that the tap focuses it again // and iOS opens the keyboard with the caret in view. A trackpad or mouse press // is left alone. // // Only taps that would focus the editor through a decorator are cancelled. // Something that takes the tap itself (a button, an input, a nested editor, an // embed) keeps the default. So does an element outside any decorator, such as // a `setDOMUnmanaged({captureSelection: true})` widget in an element node; one // inside a decorator needs a tabindex to keep native focus. A closed shadow // root hides its controls and the tap is retargeted to its host, so a widget // like that needs a tabindex on its host too. function onMouseDownIOS(event: Event, editor: LexicalEditor): void { const rootElement = editor.getRootElement(); if (rootElement === null) { return; } if (!isDecoratorTapIOS(event, editor, rootElement)) { restoreInputModeIOS(editor, rootElement); return; } event.preventDefault(); if (getActiveElementDeep(rootElement.ownerDocument) !== rootElement) { if (editor._inputState.savedInputMode === undefined) { editor._inputState.savedInputMode = rootElement.getAttribute('inputmode'); } rootElement.setAttribute('inputmode', 'none'); rootElement.focus({preventScroll: true}); } } function isDecoratorTapIOS( event: Event, editor: LexicalEditor, rootElement: HTMLElement, ): boolean { if (editor._inputState.lastPointerType === 'mouse') { return false; } const target = getComposedEventTarget(event); if (!isDOMNode(target)) { return false; } // Walk up to the editor root, crossing open shadow roots. let inDecorator = false; for ( let node: Node | null = target; node !== null; node = getParentElement(node) ) { if (node === rootElement) { return inDecorator; } if (node.nodeType === DOM_ELEMENT_TYPE) { const element = node as Element; if (element.matches(FOCUSABLE_SELECTOR)) { return false; } if (element.getAttribute('data-lexical-decorator') === 'true') { inDecorator = true; } } } return false; } // iOS only. After onMouseDownIOS focused the editor with inputmode="none", // only removing the attribute would open the keyboard over the caret: iOS // reveals the caret when a tap focuses the editor, not when the keyboard opens // later. So a tap on anything but a decorator blurs the editor at touchend, // before iOS handles the tap, and the tap then focuses it afresh. The // compatibility mousedown comes too late for that. function onTouchEndIOS( event: TouchEvent, editor: LexicalEditor, rootElement: HTMLElement, ): void { if (editor._inputState.savedInputMode === undefined) { return; } if (!isDecoratorTapIOS(event, editor, rootElement)) { if (getActiveElementDeep(rootElement.ownerDocument) === rootElement) { rootElement.blur(); } restoreInputModeIOS(editor, rootElement); } } /** @internal Puts back the root's own `inputmode` (see onMouseDownIOS). */ export function restoreInputModeIOS( editor: LexicalEditor, rootElement: HTMLElement, ): void { const savedInputMode = editor._inputState.savedInputMode; if (savedInputMode !== undefined) { editor._inputState.savedInputMode = undefined; if (savedInputMode === null) { rootElement.removeAttribute('inputmode'); } else { rootElement.setAttribute('inputmode', savedInputMode); } } } // Calls onTap at the touchend of a single touch that didn't move, so a // scroll or a pinch is not a tap. Captured, so a decorator that stops its // touch events from propagating can't hide them. function registerTapListenerIOS( rootElement: HTMLElement, onTap: (event: TouchEvent) => void, ): () => void { let start: {x: number; y: number} | null = null; const options = {capture: true, passive: true}; return mergeRegister( registerEventListener( rootElement, 'touchstart', event => { const touch = event.touches.length === 1 ? event.touches[0] : null; start = touch ? {x: touch.clientX, y: touch.clientY} : null; }, options, ), registerEventListener( rootElement, 'touchend', event => { const touch = event.changedTouches[0]; if ( start !== null && touch && event.touches.length === 0 && Math.abs(touch.clientX - start.x) <= TAP_SLOP_PX && Math.abs(touch.clientY - start.y) <= TAP_SLOP_PX ) { onTap(event); } start = null; }, options, ), ); } function onPointerDown(event: PointerEvent, editor: LexicalEditor) { // TODO implement text drag & drop // Resolve to the composed target so a pointerdown inside a decorator's // open shadow root reports the real internal element rather than the // outer shadow host the engine retargets to. const target = getComposedEventTarget(event); const pointerType = event.pointerType; if ( isDOMNode(target) && pointerType !== 'touch' && pointerType !== 'pen' && event.button === 0 ) { updateEditorSync(editor, () => { // Drag & drop should not recompute selection until mouse up; otherwise the initially // selected content is lost. if (!isDOMCapturingSelection(target, editor)) { editor._inputState.isSelectionChangeFromMouseDown = true; } }); } } // The press and moves of mouse drags for which $adjustMouseDrag moved the // selection. const adjustedMouseEvents = new WeakSet(); /** * Puts the focus of a mouse press or drag beside the inline decorator that * the pointer is over, or is beyond at the start or end of a line, where * browsers often find no position, or one inside it or on another line * (#7158). A drag keeps its anchor, and a press without Shift collapses. */ function $adjustMouseDrag( editor: LexicalEditor, event: MouseEvent, focusDOM: Node | null = null, ): void { const selection = $getSelection(); const before = selection && selection.clone(); $moveMouseDragFocus(editor, event, focusDOM); const after = $getSelection(); const drag = editor._inputState.mouseDrag; if (drag && after && !after.is(before)) { adjustedMouseEvents.add(drag); } // A caret that a press moves to another node takes its format and style, // as from a selectionchange. if (event.type === 'mousedown' && $isRangeSelection(after)) { $internalRefreshSelectionFormatAndStyle( after, $isRangeSelection(before) ? before.anchor.key : '', ); } } function $moveMouseDragFocus( editor: LexicalEditor, event: MouseEvent, focusDOM: Node | null, ): void { const previous = $getPreviousSelection(); const isPress = event.type === 'mousedown'; const isCaret = isPress && !event.shiftKey; const decorator = focusDOM && $getNearestNodeFromDOMNode(focusDOM); // A focus that the browser put inside a decorator goes back for a drag // (unless a table selected cells) and before it for a click, in the DOM // too. A Shift press keeps what the platform chose. if ($isDecoratorNode(decorator)) { if (!isPress) { if ($isRangeSelection(previous)) { $setSelection(previous.clone()); } } else if (isCaret && decorator.isInline()) { decorator.selectPrevious(); } } const current = $getSelection(); // A point in DOM that no node renders (an extension's badge at the end of // a line) leaves no selection. A decorator at the pointer still places one: // from nothing for a click, else keeping the previous anchor. const selection = current || (isCaret ? $createRangeSelection() : $isRangeSelection(previous) ? previous.clone() : null); const root = editor.getRootElement(); const doc = root && root.getRootNode(); if ( !$isRangeSelection(selection) || // A press on a selection can drag it. (macOS drags only after 150 ms, and // a quicker drag from there selects text without this adjustment.) (isCaret && !selection.isCollapsed()) || !(isDOMDocumentNode(doc) || isDOMShadowRoot(doc)) ) { return; } const {anchor, focus} = selection; // A Shift press keeps the anchor the platform chose (macOS: the far end). if (!isPress && $isRangeSelection(previous)) { const {key, offset, type} = previous.anchor; anchor.set(key, offset, type, true); } const {clientX: x, clientY: y} = event; // Not in a document without layout (jsdom). const target = doc.elementFromPoint && doc.elementFromPoint(x, y); const hit = target && $getNearestNodeFromDOMNode(target); const $leaf = (node: LexicalNode | null, dir: CaretDirection) => $isElementNode(node) ? dir === 'next' ? node.getLastDescendant() : node.getFirstDescendant() : node; // The node under the pointer (null in this list), then, when the pointer is // over a block rather than its content, a caret at each end of each of its // children, facing the node beside it there, for the decorator at that end, // which the pointer must be beyond at the edge of a line. const candidates: (SiblingCaret | null)[] = [null]; const block = $isElementNode(hit) && !hit.isInline() && ($isRootNode(hit) ? $findMatchingParent(focus.getNode(), $isBlockElementNode) : hit); for (const caret of block ? $getChildCaret(block, 'next') : []) { candidates.push($getSiblingCaret(caret.origin, 'previous'), caret); } const win = getWindow(editor); const range = win.document.createRange(); let offLine: LexicalNode | null = null; for (const caret of candidates) { const node = caret ? $leaf(caret.origin, caret.direction) : hit; if (!$isDecoratorNode(node) || !node.isInline() || node === offLine) { continue; } const dom = editor.getElementByKey(node.getKey()); if (!dom) { continue; } // The box of what it draws, which can be larger than its element (an // image in a span) or smaller (text in a box, or nothing). range.selectNodeContents(dom); const contents = range.getBoundingClientRect(); const rect = dom.getBoundingClientRect(); const {bottom, left, right, top} = contents.height > rect.height ? contents : rect; // Off the pointer's line, and so not measured again for its other edge. if (caret && (y < top || y > bottom)) { offLine = node; continue; } // By its line's direction, as a chip of code can have its own. const isRtl = win.getComputedStyle(getParentElement(dom) || dom).direction === 'rtl'; const isAfter = x * 2 > left + right !== isRtl; const dir = isAfter ? 'next' : 'previous'; // On its line, the nearest box of the node beside it there (none at a // line break) is beyond it, and where the line wraps between them, past // its middle. A node without a box tells neither. const sib = caret && caret.getNodeAtCaret(); const sibDOM = sib && editor.getElementByKey(sib.getKey()); const sibRects = sibDOM ? sibDOM.getClientRects() : []; const sibRect: DOMRect | undefined = sibRects[isAfter ? 0 : sibRects.length - 1]; if ( !caret || // A float is at the edge of no line. (caret.direction === dir && win.getComputedStyle(dom).cssFloat === 'none' && (!sib || $isLineBreakNode(sib) || (sibRect && (isAfter === isRtl ? sibRect.right * 2 > left + right : sibRect.left * 2 < left + right)))) ) { // A focus already beside it stays, as WebKit reports no move to a // point it takes for the same one. if (!node.is($leaf($getAdjacentNode(focus, isAfter), dir))) { const beside = $getSiblingCaret(node, dir); $setPointFromCaret(focus, beside); if (isCaret) { $setPointFromCaret(anchor, beside); } } if (!current) { $setSelection(selection); } return; } } // Chromium restarts a drag from its press when the editor has moved the // selection, and a press beyond a decorator then puts both points inside // it, so the focus goes to the position at the pointer instead. if ($isDecoratorNode(decorator) && !isPress) { const ownerDoc = win.document; const caret = ownerDoc.caretPositionFromPoint && ownerDoc.caretPositionFromPoint(x, y, { shadowRoots: isDOMShadowRoot(doc) ? [doc] : [], }); const resolved = caret && $internalResolveSelectionPoint( caret.offsetNode, caret.offset, null, editor, ); if (resolved) { const [{key, offset, type}] = resolved; focus.set(key, offset, type); } } } function getTargetRange(event: InputEvent): null | StaticRange { if (!event.getTargetRanges) { return null; } const targetRanges = event.getTargetRanges(); if (targetRanges.length === 0) { return null; } return targetRanges[0]; } // When a macOS text replacement is accepted, Chrome and Firefox fire input events for the key press that // triggered the acceptance *before* the one for the replacement text. This causes the caret to be placed // before the acceptance boundary. This function moves the caret past the acceptance boundary. function $maybeMoveSelectionPastTrailingAcceptanceBoundary( insertedText: string | null | undefined, ): void { const {lastKeyCode} = getActiveEditor()._inputState; if (insertedText == null || insertedText.length <= 1 || lastKeyCode == null) { return; } const characterToSearchFor = lastKeyCode.length === 1 ? lastKeyCode : lastKeyCode === 'Enter' ? '\n' : lastKeyCode === 'Tab' ? '\t' : null; if (!characterToSearchFor) { return; } const selection = $getSelection(); if (!$isRangeSelection(selection) || !selection.isCollapsed()) { return; } const anchorNode = selection.anchor.getNode(); if (!$isTextNode(anchorNode)) { return; } const {offset} = selection.anchor; if (anchorNode.getTextContentSize() === offset) { const nextSibling = anchorNode.getNextSibling(); if (characterToSearchFor === '\n') { // iOS fires insertReplacementText *before* the Enter's insertParagraph, so no // acceptance boundary exists yet; moving here lands the caret in the block that // already followed, and Enter then splits that one instead. if (IS_IOS) { return; } if ($isLineBreakNode(nextSibling)) { nextSibling.selectEnd(); } else if (!nextSibling) { const block = $findMatchingParent(anchorNode, $isBlockElementNode); const nextBlock = block && block.getNextSibling(); if ($isElementNode(nextBlock)) { nextBlock.selectStart(); } } } else if (characterToSearchFor === '\t') { if ($isTabNode(nextSibling)) { nextSibling.selectEnd(); } } else if ( $isTextNode(nextSibling) && nextSibling.getTextContent()[0] === characterToSearchFor ) { nextSibling.select(1, 1); } } else if (anchorNode.getTextContent()[offset] === characterToSearchFor) { anchorNode.select(offset + 1, offset + 1); } } function $canRemoveText( anchorNode: TextNode | ElementNode, focusNode: TextNode | ElementNode, ): boolean { return ( anchorNode !== focusNode || $isElementNode(anchorNode) || $isElementNode(focusNode) || !$isTokenOrTab(anchorNode) || !$isTokenOrTab(focusNode) ); } function isPossiblyAndroidKeyPress( inputState: InputState, timeStamp: number, ): boolean { return ( inputState.lastKeyCode === 'MediaLast' && timeStamp < inputState.lastKeyDownTimeStamp + ANDROID_COMPOSITION_LATENCY ); } function clearHandledSelectionCommandInsertText(inputState: InputState): void { inputState.isInsertTextAfterHandledSelectionCommand = false; if (inputState.handledSelectionCommandTimeoutId !== null) { clearTimeout(inputState.handledSelectionCommandTimeoutId); inputState.handledSelectionCommandTimeoutId = null; } } function markHandledSelectionCommandInsertText(inputState: InputState): void { // Only desktop Chrome on macOS accepts pending system text replacements // after these commands. Elsewhere, the next insertText may be real input. if (!IS_APPLE || IS_IOS || !IS_CHROME) { return; } clearHandledSelectionCommandInsertText(inputState); inputState.isInsertTextAfterHandledSelectionCommand = true; inputState.handledSelectionCommandTimeoutId = setTimeout( () => clearHandledSelectionCommandInsertText(inputState), 0, ); } export function registerDefaultCommandHandlers(editor: LexicalEditor) { editor.registerCommand( BEFORE_INPUT_COMMAND, $handleBeforeInput, COMMAND_PRIORITY_EDITOR, ); editor.registerCommand(INPUT_COMMAND, $handleInput, COMMAND_PRIORITY_EDITOR); editor.registerCommand( COMPOSITION_START_COMMAND, $handleCompositionStart, COMMAND_PRIORITY_EDITOR, ); editor.registerCommand( COMPOSITION_END_COMMAND, $handleCompositionEnd, COMMAND_PRIORITY_EDITOR, ); editor.registerCommand( KEY_DOWN_COMMAND, $handleKeyDown, COMMAND_PRIORITY_EDITOR, ); } /** * Returns true when a `beforeinput` / `input` event belongs to a native * control (e.g. an `` or `