2 * Copyright (c) Meta Platforms, Inc. and affiliates.
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
9 import type {LexicalEditor} from './LexicalEditor';
10 import type {NodeKey} from './LexicalNode';
11 import type {ElementNode} from './nodes/LexicalElementNode';
12 import type {TextNode} from './nodes/LexicalTextNode';
21 } from 'lexical/shared/environment';
22 import invariant from 'lexical/shared/invariant';
25 $getPreviousSelection,
36 CONTROLLED_TEXT_INSERTION_COMMAND,
39 DELETE_CHARACTER_COMMAND,
48 INSERT_LINE_BREAK_COMMAND,
49 INSERT_PARAGRAPH_COMMAND,
50 KEY_ARROW_DOWN_COMMAND,
51 KEY_ARROW_LEFT_COMMAND,
52 KEY_ARROW_RIGHT_COMMAND,
54 KEY_BACKSPACE_COMMAND,
67 SELECTION_CHANGE_COMMAND,
70 import {KEY_MODIFIER_COMMAND, SELECT_ALL_COMMAND} from './LexicalCommands';
72 COMPOSITION_START_CHAR,
77 } from './LexicalConstants';
79 $internalCreateRangeSelection,
81 } from './LexicalSelection';
82 import {getActiveEditor, updateEditor} from './LexicalUpdates';
86 $isSelectionCapturedInDecorator,
89 $shouldInsertTextAfterOrBeforeTextNode,
90 $updateSelectedTextFromDOM,
91 $updateTextNodeFromDOMContent,
97 getEditorPropertyFromDOMNode,
98 getEditorsToPropagate,
99 getNearestEditorFromDOMNode,
108 isDeleteLineBackward,
110 isDeleteWordBackward,
113 isFirefoxClipboardEvents,
128 isSelectionWithinEditor,
133 } from './LexicalUtils';
135 type RootElementRemoveHandles = Array<() => void>;
136 type RootElementEvents = Array<
139 Record<string, unknown> | ((event: Event, editor: LexicalEditor) => void),
142 const PASS_THROUGH_COMMAND = Object.freeze({});
143 const ANDROID_COMPOSITION_LATENCY = 30;
144 const rootElementEvents: RootElementEvents = [
145 ['keydown', onKeyDown],
146 ['pointerdown', onPointerDown],
147 ['compositionstart', onCompositionStart],
148 ['compositionend', onCompositionEnd],
151 ['cut', PASS_THROUGH_COMMAND],
152 ['copy', PASS_THROUGH_COMMAND],
153 ['dragstart', PASS_THROUGH_COMMAND],
154 ['dragover', PASS_THROUGH_COMMAND],
155 ['dragend', PASS_THROUGH_COMMAND],
156 ['paste', PASS_THROUGH_COMMAND],
157 ['focus', PASS_THROUGH_COMMAND],
158 ['blur', PASS_THROUGH_COMMAND],
159 ['drop', PASS_THROUGH_COMMAND],
162 if (CAN_USE_BEFORE_INPUT) {
163 rootElementEvents.push([
165 (event, editor) => onBeforeInput(event as InputEvent, editor),
169 let lastKeyDownTimeStamp = 0;
170 let lastKeyCode: null | string = null;
171 let lastBeforeInputInsertTextTimeStamp = 0;
172 let unprocessedBeforeInputData: null | string = null;
173 const rootElementsRegistered = new WeakMap<Document, number>();
174 let isSelectionChangeFromDOMUpdate = false;
175 let isSelectionChangeFromMouseDown = false;
176 let isInsertLineBreak = false;
177 let isFirefoxEndingComposition = false;
178 let collapsedSelectionFormat: [number, string, number, NodeKey, number] = [
186 // This function is used to determine if Lexical should attempt to override
187 // the default browser behavior for insertion of text and use its own internal
188 // heuristics. This is an extremely important function, and makes much of Lexical
189 // work as intended between different browsers and across word, line and character
190 // boundary/formats. It also is important for text replacement, node schemas and
191 // composition mechanics.
193 function $shouldPreventDefaultAndInsertText(
194 selection: RangeSelection,
195 domTargetRange: null | StaticRange,
198 isBeforeInput: boolean,
200 const anchor = selection.anchor;
201 const focus = selection.focus;
202 const anchorNode = anchor.getNode();
203 const editor = getActiveEditor();
204 const domSelection = getDOMSelection(editor._window);
205 const domAnchorNode = domSelection !== null ? domSelection.anchorNode : null;
206 const anchorKey = anchor.key;
207 const backingAnchorElement = editor.getElementByKey(anchorKey);
208 const textLength = text.length;
211 anchorKey !== focus.key ||
212 // If we're working with a non-text node.
213 !$isTextNode(anchorNode) ||
214 // If we are replacing a range with a single character or grapheme, and not composing.
216 (!CAN_USE_BEFORE_INPUT ||
217 // We check to see if there has been
218 // a recent beforeinput event for "textInput". If there has been one in the last
219 // 50ms then we proceed as normal. However, if there is not, then this is likely
220 // a dangling `input` event caused by execCommand('insertText').
221 lastBeforeInputInsertTextTimeStamp < timeStamp + 50)) ||
222 (anchorNode.isDirty() && textLength < 2) ||
223 doesContainGrapheme(text)) &&
224 anchor.offset !== focus.offset &&
225 !anchorNode.isComposing()) ||
226 // Any non standard text node.
227 $isTokenOrSegmented(anchorNode) ||
228 // If the text length is more than a single character and we're either
229 // dealing with this in "beforeinput" or where the node has already recently
230 // been changed (thus is dirty).
231 (anchorNode.isDirty() && textLength > 1) ||
232 // If the DOM selection element is not the same as the backing node during beforeinput.
233 ((isBeforeInput || !CAN_USE_BEFORE_INPUT) &&
234 backingAnchorElement !== null &&
235 !anchorNode.isComposing() &&
236 domAnchorNode !== getDOMTextNode(backingAnchorElement)) ||
237 // If TargetRange is not the same as the DOM selection; browser trying to edit random parts
239 (domSelection !== null &&
240 domTargetRange !== null &&
241 (!domTargetRange.collapsed ||
242 domTargetRange.startContainer !== domSelection.anchorNode ||
243 domTargetRange.startOffset !== domSelection.anchorOffset)) ||
244 // Check if we're changing from bold to italics, or some other format.
245 anchorNode.getFormat() !== selection.format ||
246 anchorNode.getStyle() !== selection.style ||
247 // One last set of heuristics to check against.
248 $shouldInsertTextAfterOrBeforeTextNode(selection, anchorNode)
252 function shouldSkipSelectionChange(
253 domNode: null | Node,
258 domNode.nodeValue !== null &&
259 domNode.nodeType === DOM_TEXT_TYPE &&
261 offset !== domNode.nodeValue.length
265 function onSelectionChange(
266 domSelection: Selection,
267 editor: LexicalEditor,
271 anchorNode: anchorDOM,
276 if (isSelectionChangeFromDOMUpdate) {
277 isSelectionChangeFromDOMUpdate = false;
279 // If native DOM selection is on a DOM element, then
280 // we should continue as usual, as Lexical's selection
281 // may have normalized to a better child. If the DOM
282 // element is a text node, we can safely apply this
283 // optimization and skip the selection change entirely.
284 // We also need to check if the offset is at the boundary,
285 // because in this case, we might need to normalize to a
288 shouldSkipSelectionChange(anchorDOM, anchorOffset) &&
289 shouldSkipSelectionChange(focusDOM, focusOffset)
294 updateEditor(editor, () => {
295 // Non-active editor don't need any extra logic for selection, it only needs update
296 // to reconcile selection (set it to null) to ensure that only one editor has non-null selection.
302 if (!isSelectionWithinEditor(editor, anchorDOM, focusDOM)) {
306 const selection = $getSelection();
308 // Update the selection format
309 if ($isRangeSelection(selection)) {
310 const anchor = selection.anchor;
311 const anchorNode = anchor.getNode();
313 if (selection.isCollapsed()) {
314 // Badly interpreted range selection when collapsed - #1482
316 domSelection.type === 'Range' &&
317 domSelection.anchorNode === domSelection.focusNode
319 selection.dirty = true;
322 // If we have marked a collapsed selection format, and we're
323 // within the given time range – then attempt to use that format
324 // instead of getting the format from the anchor node.
325 const windowEvent = getWindow(editor).event;
326 const currentTimeStamp = windowEvent
327 ? windowEvent.timeStamp
329 const [lastFormat, lastStyle, lastOffset, lastKey, timeStamp] =
330 collapsedSelectionFormat;
332 const root = $getRoot();
333 const isRootTextContentEmpty =
334 editor.isComposing() === false && root.getTextContent() === '';
337 currentTimeStamp < timeStamp + 200 &&
338 anchor.offset === lastOffset &&
339 anchor.key === lastKey
341 selection.format = lastFormat;
342 selection.style = lastStyle;
344 if (anchor.type === 'text') {
346 $isTextNode(anchorNode),
347 'Point.getNode() must return TextNode when type is text',
349 selection.format = anchorNode.getFormat();
350 selection.style = anchorNode.getStyle();
351 } else if (anchor.type === 'element' && !isRootTextContentEmpty) {
352 const lastNode = anchor.getNode();
353 selection.style = '';
355 lastNode instanceof ParagraphNode &&
356 lastNode.getChildrenSize() === 0
358 selection.format = lastNode.getTextFormat();
359 selection.style = lastNode.getTextStyle();
361 selection.format = 0;
366 const anchorKey = anchor.key;
367 const focus = selection.focus;
368 const focusKey = focus.key;
369 const nodes = selection.getNodes();
370 const nodesLength = nodes.length;
371 const isBackward = selection.isBackward();
372 const startOffset = isBackward ? focusOffset : anchorOffset;
373 const endOffset = isBackward ? anchorOffset : focusOffset;
374 const startKey = isBackward ? focusKey : anchorKey;
375 const endKey = isBackward ? anchorKey : focusKey;
376 let combinedFormat = IS_ALL_FORMATTING;
377 let hasTextNodes = false;
378 for (let i = 0; i < nodesLength; i++) {
379 const node = nodes[i];
380 const textContentSize = node.getTextContentSize();
383 textContentSize !== 0 &&
384 // Exclude empty text nodes at boundaries resulting from user's selection
387 node.__key === startKey &&
388 startOffset === textContentSize) ||
389 (i === nodesLength - 1 &&
390 node.__key === endKey &&
394 // TODO: what about style?
396 combinedFormat &= node.getFormat();
397 if (combinedFormat === 0) {
403 selection.format = hasTextNodes ? combinedFormat : 0;
407 dispatchCommand(editor, SELECTION_CHANGE_COMMAND, undefined);
411 // This is a work-around is mainly Chrome specific bug where if you select
412 // the contents of an empty block, you cannot easily unselect anything.
413 // This results in a tiny selection box that looks buggy/broken. This can
414 // also help other browsers when selection might "appear" lost, when it
416 function onClick(event: PointerEvent, editor: LexicalEditor): void {
417 updateEditor(editor, () => {
418 const selection = $getSelection();
419 const domSelection = getDOMSelection(editor._window);
420 const lastSelection = $getPreviousSelection();
423 if ($isRangeSelection(selection)) {
424 const anchor = selection.anchor;
425 const anchorNode = anchor.getNode();
428 anchor.type === 'element' &&
429 anchor.offset === 0 &&
430 selection.isCollapsed() &&
431 !$isRootNode(anchorNode) &&
432 $getRoot().getChildrenSize() === 1 &&
433 anchorNode.getTopLevelElementOrThrow().isEmpty() &&
434 lastSelection !== null &&
435 selection.is(lastSelection)
437 domSelection.removeAllRanges();
438 selection.dirty = true;
439 } else if (event.detail === 3 && !selection.isCollapsed()) {
440 // Tripple click causing selection to overflow into the nearest element. In that
441 // case visually it looks like a single element content is selected, focus node
442 // is actually at the beginning of the next element (if present) and any manipulations
443 // with selection (formatting) are affecting second element as well
444 const focus = selection.focus;
445 const focusNode = focus.getNode();
446 if (anchorNode !== focusNode) {
447 if ($isElementNode(anchorNode)) {
448 anchorNode.select(0);
450 anchorNode.getParentOrThrow().select(0);
454 } else if (event.pointerType === 'touch') {
455 // This is used to update the selection on touch devices when the user clicks on text after a
456 // node selection. See isSelectionChangeFromMouseDown for the inverse
457 const domAnchorNode = domSelection.anchorNode;
458 if (domAnchorNode !== null) {
459 const nodeType = domAnchorNode.nodeType;
460 // If the user is attempting to click selection back onto text, then
461 // we should attempt create a range selection.
462 // When we click on an empty paragraph node or the end of a paragraph that ends
463 // with an image/poll, the nodeType will be ELEMENT_NODE
464 if (nodeType === DOM_ELEMENT_TYPE || nodeType === DOM_TEXT_TYPE) {
465 const newSelection = $internalCreateRangeSelection(
471 $setSelection(newSelection);
477 dispatchCommand(editor, CLICK_COMMAND, event);
481 function onPointerDown(event: PointerEvent, editor: LexicalEditor) {
482 // TODO implement text drag & drop
483 const target = event.target;
484 const pointerType = event.pointerType;
485 if (target instanceof Node && pointerType !== 'touch') {
486 updateEditor(editor, () => {
487 // Drag & drop should not recompute selection until mouse up; otherwise the initially
488 // selected content is lost.
489 if (!$isSelectionCapturedInDecorator(target)) {
490 isSelectionChangeFromMouseDown = true;
496 function getTargetRange(event: InputEvent): null | StaticRange {
497 if (!event.getTargetRanges) {
500 const targetRanges = event.getTargetRanges();
501 if (targetRanges.length === 0) {
504 return targetRanges[0];
507 function $canRemoveText(
508 anchorNode: TextNode | ElementNode,
509 focusNode: TextNode | ElementNode,
512 anchorNode !== focusNode ||
513 $isElementNode(anchorNode) ||
514 $isElementNode(focusNode) ||
515 !anchorNode.isToken() ||
520 function isPossiblyAndroidKeyPress(timeStamp: number): boolean {
522 lastKeyCode === 'MediaLast' &&
523 timeStamp < lastKeyDownTimeStamp + ANDROID_COMPOSITION_LATENCY
527 function onBeforeInput(event: InputEvent, editor: LexicalEditor): void {
528 const inputType = event.inputType;
529 const targetRange = getTargetRange(event);
531 // We let the browser do its own thing for composition.
533 inputType === 'deleteCompositionText' ||
534 // If we're pasting in FF, we shouldn't get this event
535 // as the `paste` event should have triggered, unless the
536 // user has dom.event.clipboardevents.enabled disabled in
537 // about:config. In that case, we need to process the
538 // pasted content in the DOM mutation phase.
539 (IS_FIREFOX && isFirefoxClipboardEvents(editor))
542 } else if (inputType === 'insertCompositionText') {
546 updateEditor(editor, () => {
547 const selection = $getSelection();
549 if (inputType === 'deleteContentBackward') {
550 if (selection === null) {
551 // Use previous selection
552 const prevSelection = $getPreviousSelection();
554 if (!$isRangeSelection(prevSelection)) {
558 $setSelection(prevSelection.clone());
561 if ($isRangeSelection(selection)) {
562 const isSelectionAnchorSameAsFocus =
563 selection.anchor.key === selection.focus.key;
566 isPossiblyAndroidKeyPress(event.timeStamp) &&
567 editor.isComposing() &&
568 isSelectionAnchorSameAsFocus
570 $setCompositionKey(null);
571 lastKeyDownTimeStamp = 0;
572 // Fixes an Android bug where selection flickers when backspacing
574 updateEditor(editor, () => {
575 $setCompositionKey(null);
577 }, ANDROID_COMPOSITION_LATENCY);
578 if ($isRangeSelection(selection)) {
579 const anchorNode = selection.anchor.getNode();
580 anchorNode.markDirty();
582 $isTextNode(anchorNode),
583 'Anchor node must be a TextNode',
585 selection.style = anchorNode.getStyle();
588 $setCompositionKey(null);
589 event.preventDefault();
590 // Chromium Android at the moment seems to ignore the preventDefault
591 // on 'deleteContentBackward' and still deletes the content. Which leads
592 // to multiple deletions. So we let the browser handle the deletion in this case.
593 const selectedNodeText = selection.anchor.getNode().getTextContent();
594 const hasSelectedAllTextInNode =
595 selection.anchor.offset === 0 &&
596 selection.focus.offset === selectedNodeText.length;
597 const shouldLetBrowserHandleDelete =
599 isSelectionAnchorSameAsFocus &&
600 !hasSelectedAllTextInNode;
601 if (!shouldLetBrowserHandleDelete) {
602 dispatchCommand(editor, DELETE_CHARACTER_COMMAND, true);
609 if (!$isRangeSelection(selection)) {
613 const data = event.data;
615 // This represents the case when two beforeinput events are triggered at the same time (without a
616 // full event loop ending at input). This happens with MacOS with the default keyboard settings,
617 // a combination of autocorrection + autocapitalization.
618 // Having Lexical run everything in controlled mode would fix the issue without additional code
619 // but this would kill the massive performance win from the most common typing event.
620 // Alternatively, when this happens we can prematurely update our EditorState based on the DOM
621 // content, a job that would usually be the input event's responsibility.
622 if (unprocessedBeforeInputData !== null) {
623 $updateSelectedTextFromDOM(false, editor, unprocessedBeforeInputData);
627 (!selection.dirty || unprocessedBeforeInputData !== null) &&
628 selection.isCollapsed() &&
629 !$isRootNode(selection.anchor.getNode()) &&
632 selection.applyDOMRange(targetRange);
635 unprocessedBeforeInputData = null;
637 const anchor = selection.anchor;
638 const focus = selection.focus;
639 const anchorNode = anchor.getNode();
640 const focusNode = focus.getNode();
642 if (inputType === 'insertText' || inputType === 'insertTranspose') {
644 event.preventDefault();
645 dispatchCommand(editor, INSERT_LINE_BREAK_COMMAND, false);
646 } else if (data === DOUBLE_LINE_BREAK) {
647 event.preventDefault();
648 dispatchCommand(editor, INSERT_PARAGRAPH_COMMAND, undefined);
649 } else if (data == null && event.dataTransfer) {
650 // Gets around a Safari text replacement bug.
651 const text = event.dataTransfer.getData('text/plain');
652 event.preventDefault();
653 selection.insertRawText(text);
656 $shouldPreventDefaultAndInsertText(
664 event.preventDefault();
665 dispatchCommand(editor, CONTROLLED_TEXT_INSERTION_COMMAND, data);
667 unprocessedBeforeInputData = data;
669 lastBeforeInputInsertTextTimeStamp = event.timeStamp;
673 // Prevent the browser from carrying out
674 // the input event, so we can control the
676 event.preventDefault();
679 case 'insertFromYank':
680 case 'insertFromDrop':
681 case 'insertReplacementText': {
682 dispatchCommand(editor, CONTROLLED_TEXT_INSERTION_COMMAND, event);
686 case 'insertFromComposition': {
687 // This is the end of composition
688 $setCompositionKey(null);
689 dispatchCommand(editor, CONTROLLED_TEXT_INSERTION_COMMAND, event);
693 case 'insertLineBreak': {
695 $setCompositionKey(null);
696 dispatchCommand(editor, INSERT_LINE_BREAK_COMMAND, false);
700 case 'insertParagraph': {
702 $setCompositionKey(null);
704 // Safari does not provide the type "insertLineBreak".
705 // So instead, we need to infer it from the keyboard event.
706 // We do not apply this logic to iOS to allow newline auto-capitalization
707 // work without creating linebreaks when pressing Enter
708 if (isInsertLineBreak && !IS_IOS) {
709 isInsertLineBreak = false;
710 dispatchCommand(editor, INSERT_LINE_BREAK_COMMAND, false);
712 dispatchCommand(editor, INSERT_PARAGRAPH_COMMAND, undefined);
718 case 'insertFromPaste':
719 case 'insertFromPasteAsQuotation': {
720 dispatchCommand(editor, PASTE_COMMAND, event);
724 case 'deleteByComposition': {
725 if ($canRemoveText(anchorNode, focusNode)) {
726 dispatchCommand(editor, REMOVE_TEXT_COMMAND, event);
733 case 'deleteByCut': {
734 dispatchCommand(editor, REMOVE_TEXT_COMMAND, event);
738 case 'deleteContent': {
739 dispatchCommand(editor, DELETE_CHARACTER_COMMAND, false);
743 case 'deleteWordBackward': {
744 dispatchCommand(editor, DELETE_WORD_COMMAND, true);
748 case 'deleteWordForward': {
749 dispatchCommand(editor, DELETE_WORD_COMMAND, false);
753 case 'deleteHardLineBackward':
754 case 'deleteSoftLineBackward': {
755 dispatchCommand(editor, DELETE_LINE_COMMAND, true);
759 case 'deleteContentForward':
760 case 'deleteHardLineForward':
761 case 'deleteSoftLineForward': {
762 dispatchCommand(editor, DELETE_LINE_COMMAND, false);
766 case 'formatStrikeThrough': {
767 dispatchCommand(editor, FORMAT_TEXT_COMMAND, 'strikethrough');
772 dispatchCommand(editor, FORMAT_TEXT_COMMAND, 'bold');
776 case 'formatItalic': {
777 dispatchCommand(editor, FORMAT_TEXT_COMMAND, 'italic');
781 case 'formatUnderline': {
782 dispatchCommand(editor, FORMAT_TEXT_COMMAND, 'underline');
786 case 'historyUndo': {
787 dispatchCommand(editor, UNDO_COMMAND, undefined);
791 case 'historyRedo': {
792 dispatchCommand(editor, REDO_COMMAND, undefined);
802 function onInput(event: InputEvent, editor: LexicalEditor): void {
803 // We don't want the onInput to bubble, in the case of nested editors.
804 event.stopPropagation();
805 updateEditor(editor, () => {
806 const selection = $getSelection();
807 const data = event.data;
808 const targetRange = getTargetRange(event);
812 $isRangeSelection(selection) &&
813 $shouldPreventDefaultAndInsertText(
821 // Given we're over-riding the default behavior, we will need
822 // to ensure to disable composition before dispatching the
823 // insertText command for when changing the sequence for FF.
824 if (isFirefoxEndingComposition) {
825 $onCompositionEndImpl(editor, data);
826 isFirefoxEndingComposition = false;
828 const anchor = selection.anchor;
829 const anchorNode = anchor.getNode();
830 const domSelection = getDOMSelection(editor._window);
831 if (domSelection === null) {
834 const isBackward = selection.isBackward();
835 const startOffset = isBackward
836 ? selection.anchor.offset
837 : selection.focus.offset;
838 const endOffset = isBackward
839 ? selection.focus.offset
840 : selection.anchor.offset;
841 // If the content is the same as inserted, then don't dispatch an insertion.
842 // Given onInput doesn't take the current selection (it uses the previous)
843 // we can compare that against what the DOM currently says.
845 !CAN_USE_BEFORE_INPUT ||
846 selection.isCollapsed() ||
847 !$isTextNode(anchorNode) ||
848 domSelection.anchorNode === null ||
849 anchorNode.getTextContent().slice(0, startOffset) +
851 anchorNode.getTextContent().slice(startOffset + endOffset) !==
852 getAnchorTextFromDOM(domSelection.anchorNode)
854 dispatchCommand(editor, CONTROLLED_TEXT_INSERTION_COMMAND, data);
857 const textLength = data.length;
859 // Another hack for FF, as it's possible that the IME is still
860 // open, even though compositionend has already fired (sigh).
864 event.inputType === 'insertCompositionText' &&
865 !editor.isComposing()
867 selection.anchor.offset -= textLength;
870 // This ensures consistency on Android.
871 if (!IS_SAFARI && !IS_IOS && !IS_APPLE_WEBKIT && editor.isComposing()) {
872 lastKeyDownTimeStamp = 0;
873 $setCompositionKey(null);
876 const characterData = data !== null ? data : undefined;
877 $updateSelectedTextFromDOM(false, editor, characterData);
879 // onInput always fires after onCompositionEnd for FF.
880 if (isFirefoxEndingComposition) {
881 $onCompositionEndImpl(editor, data || undefined);
882 isFirefoxEndingComposition = false;
886 // Also flush any other mutations that might have occurred
890 unprocessedBeforeInputData = null;
893 function onCompositionStart(
894 event: CompositionEvent,
895 editor: LexicalEditor,
897 updateEditor(editor, () => {
898 const selection = $getSelection();
900 if ($isRangeSelection(selection) && !editor.isComposing()) {
901 const anchor = selection.anchor;
902 const node = selection.anchor.getNode();
903 $setCompositionKey(anchor.key);
906 // If it has been 30ms since the last keydown, then we should
907 // apply the empty space heuristic. We can't do this for Safari,
908 // as the keydown fires after composition start.
909 event.timeStamp < lastKeyDownTimeStamp + ANDROID_COMPOSITION_LATENCY ||
910 // FF has issues around composing multibyte characters, so we also
911 // need to invoke the empty space heuristic below.
912 anchor.type === 'element' ||
913 !selection.isCollapsed() ||
914 ($isTextNode(node) && node.getStyle() !== selection.style)
916 // We insert a zero width character, ready for the composition
917 // to get inserted into the new node we create. If
918 // we don't do this, Safari will fail on us because
919 // there is no text node matching the selection.
922 CONTROLLED_TEXT_INSERTION_COMMAND,
923 COMPOSITION_START_CHAR,
930 function $onCompositionEndImpl(editor: LexicalEditor, data?: string): void {
931 const compositionKey = editor._compositionKey;
932 $setCompositionKey(null);
934 // Handle termination of composition.
935 if (compositionKey !== null && data != null) {
936 // Composition can sometimes move to an adjacent DOM node when backspacing.
937 // So check for the empty case.
939 const node = $getNodeByKey(compositionKey);
940 const textNode = getDOMTextNode(editor.getElementByKey(compositionKey));
944 textNode.nodeValue !== null &&
947 $updateTextNodeFromDOMContent(
959 // Composition can sometimes be that of a new line. In which case, we need to
960 // handle that accordingly.
961 if (data[data.length - 1] === '\n') {
962 const selection = $getSelection();
964 if ($isRangeSelection(selection)) {
965 // If the last character is a line break, we also need to insert
967 const focus = selection.focus;
968 selection.anchor.set(focus.key, focus.offset, focus.type);
969 dispatchCommand(editor, KEY_ENTER_COMMAND, null);
975 $updateSelectedTextFromDOM(true, editor, data);
978 function onCompositionEnd(
979 event: CompositionEvent,
980 editor: LexicalEditor,
982 // Firefox fires onCompositionEnd before onInput, but Chrome/Webkit,
983 // fire onInput before onCompositionEnd. To ensure the sequence works
984 // like Chrome/Webkit we use the isFirefoxEndingComposition flag to
985 // defer handling of onCompositionEnd in Firefox till we have processed
986 // the logic in onInput.
988 isFirefoxEndingComposition = true;
990 updateEditor(editor, () => {
991 $onCompositionEndImpl(editor, event.data);
996 function onKeyDown(event: KeyboardEvent, editor: LexicalEditor): void {
997 lastKeyDownTimeStamp = event.timeStamp;
998 lastKeyCode = event.key;
999 if (editor.isComposing()) {
1003 const {key, shiftKey, ctrlKey, metaKey, altKey} = event;
1005 if (dispatchCommand(editor, KEY_DOWN_COMMAND, event)) {
1013 if (isMoveForward(key, ctrlKey, altKey, metaKey)) {
1014 dispatchCommand(editor, KEY_ARROW_RIGHT_COMMAND, event);
1015 } else if (isMoveToEnd(key, ctrlKey, shiftKey, altKey, metaKey)) {
1016 dispatchCommand(editor, MOVE_TO_END, event);
1017 } else if (isMoveBackward(key, ctrlKey, altKey, metaKey)) {
1018 dispatchCommand(editor, KEY_ARROW_LEFT_COMMAND, event);
1019 } else if (isMoveToStart(key, ctrlKey, shiftKey, altKey, metaKey)) {
1020 dispatchCommand(editor, MOVE_TO_START, event);
1021 } else if (isMoveUp(key, ctrlKey, metaKey)) {
1022 dispatchCommand(editor, KEY_ARROW_UP_COMMAND, event);
1023 } else if (isMoveDown(key, ctrlKey, metaKey)) {
1024 dispatchCommand(editor, KEY_ARROW_DOWN_COMMAND, event);
1025 } else if (isLineBreak(key, shiftKey)) {
1026 isInsertLineBreak = true;
1027 dispatchCommand(editor, KEY_ENTER_COMMAND, event);
1028 } else if (isSpace(key)) {
1029 dispatchCommand(editor, KEY_SPACE_COMMAND, event);
1030 } else if (isOpenLineBreak(key, ctrlKey)) {
1031 event.preventDefault();
1032 isInsertLineBreak = true;
1033 dispatchCommand(editor, INSERT_LINE_BREAK_COMMAND, true);
1034 } else if (isParagraph(key, shiftKey)) {
1035 isInsertLineBreak = false;
1036 dispatchCommand(editor, KEY_ENTER_COMMAND, event);
1037 } else if (isDeleteBackward(key, altKey, metaKey, ctrlKey)) {
1038 if (isBackspace(key)) {
1039 dispatchCommand(editor, KEY_BACKSPACE_COMMAND, event);
1041 event.preventDefault();
1042 dispatchCommand(editor, DELETE_CHARACTER_COMMAND, true);
1044 } else if (isEscape(key)) {
1045 dispatchCommand(editor, KEY_ESCAPE_COMMAND, event);
1046 } else if (isDeleteForward(key, ctrlKey, shiftKey, altKey, metaKey)) {
1047 if (isDelete(key)) {
1048 dispatchCommand(editor, KEY_DELETE_COMMAND, event);
1050 event.preventDefault();
1051 dispatchCommand(editor, DELETE_CHARACTER_COMMAND, false);
1053 } else if (isDeleteWordBackward(key, altKey, ctrlKey)) {
1054 event.preventDefault();
1055 dispatchCommand(editor, DELETE_WORD_COMMAND, true);
1056 } else if (isDeleteWordForward(key, altKey, ctrlKey)) {
1057 event.preventDefault();
1058 dispatchCommand(editor, DELETE_WORD_COMMAND, false);
1059 } else if (isDeleteLineBackward(key, metaKey)) {
1060 event.preventDefault();
1061 dispatchCommand(editor, DELETE_LINE_COMMAND, true);
1062 } else if (isDeleteLineForward(key, metaKey)) {
1063 event.preventDefault();
1064 dispatchCommand(editor, DELETE_LINE_COMMAND, false);
1065 } else if (isBold(key, altKey, metaKey, ctrlKey)) {
1066 event.preventDefault();
1067 dispatchCommand(editor, FORMAT_TEXT_COMMAND, 'bold');
1068 } else if (isUnderline(key, altKey, metaKey, ctrlKey)) {
1069 event.preventDefault();
1070 dispatchCommand(editor, FORMAT_TEXT_COMMAND, 'underline');
1071 } else if (isItalic(key, altKey, metaKey, ctrlKey)) {
1072 event.preventDefault();
1073 dispatchCommand(editor, FORMAT_TEXT_COMMAND, 'italic');
1074 } else if (isTab(key, altKey, ctrlKey, metaKey)) {
1075 dispatchCommand(editor, KEY_TAB_COMMAND, event);
1076 } else if (isUndo(key, shiftKey, metaKey, ctrlKey)) {
1077 event.preventDefault();
1078 dispatchCommand(editor, UNDO_COMMAND, undefined);
1079 } else if (isRedo(key, shiftKey, metaKey, ctrlKey)) {
1080 event.preventDefault();
1081 dispatchCommand(editor, REDO_COMMAND, undefined);
1083 const prevSelection = editor._editorState._selection;
1084 if ($isNodeSelection(prevSelection)) {
1085 if (isCopy(key, shiftKey, metaKey, ctrlKey)) {
1086 event.preventDefault();
1087 dispatchCommand(editor, COPY_COMMAND, event);
1088 } else if (isCut(key, shiftKey, metaKey, ctrlKey)) {
1089 event.preventDefault();
1090 dispatchCommand(editor, CUT_COMMAND, event);
1091 } else if (isSelectAll(key, metaKey, ctrlKey)) {
1092 event.preventDefault();
1093 dispatchCommand(editor, SELECT_ALL_COMMAND, event);
1095 // FF does it well (no need to override behavior)
1096 } else if (!IS_FIREFOX && isSelectAll(key, metaKey, ctrlKey)) {
1097 event.preventDefault();
1098 dispatchCommand(editor, SELECT_ALL_COMMAND, event);
1102 if (isModifier(ctrlKey, shiftKey, altKey, metaKey)) {
1103 dispatchCommand(editor, KEY_MODIFIER_COMMAND, event);
1107 function getRootElementRemoveHandles(
1108 rootElement: HTMLElement,
1109 ): RootElementRemoveHandles {
1110 // @ts-expect-error: internal field
1111 let eventHandles = rootElement.__lexicalEventHandles;
1113 if (eventHandles === undefined) {
1115 // @ts-expect-error: internal field
1116 rootElement.__lexicalEventHandles = eventHandles;
1119 return eventHandles;
1122 // Mapping root editors to their active nested editors, contains nested editors
1123 // mapping only, so if root editor is selected map will have no reference to free up memory
1124 const activeNestedEditorsMap: Map<string, LexicalEditor> = new Map();
1126 function onDocumentSelectionChange(event: Event): void {
1127 const target = event.target as null | Element | Document;
1128 const targetWindow =
1131 : target.nodeType === 9
1132 ? (target as Document).defaultView
1133 : (target as Element).ownerDocument.defaultView;
1134 const domSelection = getDOMSelection(targetWindow);
1135 if (domSelection === null) {
1138 const nextActiveEditor = getNearestEditorFromDOMNode(domSelection.anchorNode);
1139 if (nextActiveEditor === null) {
1143 if (isSelectionChangeFromMouseDown) {
1144 isSelectionChangeFromMouseDown = false;
1145 updateEditor(nextActiveEditor, () => {
1146 const lastSelection = $getPreviousSelection();
1147 const domAnchorNode = domSelection.anchorNode;
1148 if (domAnchorNode === null) {
1151 const nodeType = domAnchorNode.nodeType;
1152 // If the user is attempting to click selection back onto text, then
1153 // we should attempt create a range selection.
1154 // When we click on an empty paragraph node or the end of a paragraph that ends
1155 // with an image/poll, the nodeType will be ELEMENT_NODE
1156 if (nodeType !== DOM_ELEMENT_TYPE && nodeType !== DOM_TEXT_TYPE) {
1159 const newSelection = $internalCreateRangeSelection(
1165 $setSelection(newSelection);
1169 // When editor receives selection change event, we're checking if
1170 // it has any sibling editors (within same parent editor) that were active
1171 // before, and trigger selection change on it to nullify selection.
1172 const editors = getEditorsToPropagate(nextActiveEditor);
1173 const rootEditor = editors[editors.length - 1];
1174 const rootEditorKey = rootEditor._key;
1175 const activeNestedEditor = activeNestedEditorsMap.get(rootEditorKey);
1176 const prevActiveEditor = activeNestedEditor || rootEditor;
1178 if (prevActiveEditor !== nextActiveEditor) {
1179 onSelectionChange(domSelection, prevActiveEditor, false);
1182 onSelectionChange(domSelection, nextActiveEditor, true);
1184 // If newly selected editor is nested, then add it to the map, clean map otherwise
1185 if (nextActiveEditor !== rootEditor) {
1186 activeNestedEditorsMap.set(rootEditorKey, nextActiveEditor);
1187 } else if (activeNestedEditor) {
1188 activeNestedEditorsMap.delete(rootEditorKey);
1192 function stopLexicalPropagation(event: Event): void {
1193 // We attach a special property to ensure the same event doesn't re-fire
1194 // for parent editors.
1196 event._lexicalHandled = true;
1199 function hasStoppedLexicalPropagation(event: Event): boolean {
1201 const stopped = event._lexicalHandled === true;
1205 export type EventHandler = (event: Event, editor: LexicalEditor) => void;
1207 export function addRootElementEvents(
1208 rootElement: HTMLElement,
1209 editor: LexicalEditor,
1211 // We only want to have a single global selectionchange event handler, shared
1212 // between all editor instances.
1213 const doc = rootElement.ownerDocument;
1214 const documentRootElementsCount = rootElementsRegistered.get(doc);
1216 documentRootElementsCount === undefined ||
1217 documentRootElementsCount < 1
1219 doc.addEventListener('selectionchange', onDocumentSelectionChange);
1221 rootElementsRegistered.set(doc, (documentRootElementsCount || 0) + 1);
1223 // @ts-expect-error: internal field
1224 rootElement.__lexicalEditor = editor;
1225 const removeHandles = getRootElementRemoveHandles(rootElement);
1227 for (let i = 0; i < rootElementEvents.length; i++) {
1228 const [eventName, onEvent] = rootElementEvents[i];
1229 const eventHandler =
1230 typeof onEvent === 'function'
1231 ? (event: Event) => {
1232 if (hasStoppedLexicalPropagation(event)) {
1235 stopLexicalPropagation(event);
1236 if (editor.isEditable() || eventName === 'click') {
1237 onEvent(event, editor);
1240 : (event: Event) => {
1241 if (hasStoppedLexicalPropagation(event)) {
1244 stopLexicalPropagation(event);
1245 const isEditable = editor.isEditable();
1246 switch (eventName) {
1250 dispatchCommand(editor, CUT_COMMAND, event as ClipboardEvent)
1254 return dispatchCommand(
1257 event as ClipboardEvent,
1266 event as ClipboardEvent,
1273 dispatchCommand(editor, DRAGSTART_COMMAND, event as DragEvent)
1279 dispatchCommand(editor, DRAGOVER_COMMAND, event as DragEvent)
1285 dispatchCommand(editor, DRAGEND_COMMAND, event as DragEvent)
1291 dispatchCommand(editor, FOCUS_COMMAND, event as FocusEvent)
1297 dispatchCommand(editor, BLUR_COMMAND, event as FocusEvent)
1304 dispatchCommand(editor, DROP_COMMAND, event as DragEvent)
1308 rootElement.addEventListener(eventName, eventHandler);
1309 removeHandles.push(() => {
1310 rootElement.removeEventListener(eventName, eventHandler);
1315 export function removeRootElementEvents(rootElement: HTMLElement): void {
1316 const doc = rootElement.ownerDocument;
1317 const documentRootElementsCount = rootElementsRegistered.get(doc);
1319 documentRootElementsCount !== undefined,
1320 'Root element not registered',
1323 // We only want to have a single global selectionchange event handler, shared
1324 // between all editor instances.
1325 const newCount = documentRootElementsCount - 1;
1326 invariant(newCount >= 0, 'Root element count less than 0');
1327 rootElementsRegistered.set(doc, newCount);
1328 if (newCount === 0) {
1329 doc.removeEventListener('selectionchange', onDocumentSelectionChange);
1332 const editor = getEditorPropertyFromDOMNode(rootElement);
1334 if (isLexicalEditor(editor)) {
1335 cleanActiveNestedEditorsMap(editor);
1336 // @ts-expect-error: internal field
1337 rootElement.__lexicalEditor = null;
1338 } else if (editor) {
1341 'Attempted to remove event handlers from a node that does not belong to this build of Lexical',
1345 const removeHandles = getRootElementRemoveHandles(rootElement);
1347 for (let i = 0; i < removeHandles.length; i++) {
1351 // @ts-expect-error: internal field
1352 rootElement.__lexicalEventHandles = [];
1355 function cleanActiveNestedEditorsMap(editor: LexicalEditor) {
1356 if (editor._parentEditor !== null) {
1357 // For nested editor cleanup map if this editor was marked as active
1358 const editors = getEditorsToPropagate(editor);
1359 const rootEditor = editors[editors.length - 1];
1360 const rootEditorKey = rootEditor._key;
1362 if (activeNestedEditorsMap.get(rootEditorKey) === editor) {
1363 activeNestedEditorsMap.delete(rootEditorKey);
1366 // For top-level editors cleanup map
1367 activeNestedEditorsMap.delete(editor._key);
1371 export function markSelectionChangeFromDOMUpdate(): void {
1372 isSelectionChangeFromDOMUpdate = true;
1375 export function markCollapsedSelectionFormat(
1382 collapsedSelectionFormat = [format, style, offset, key, timeStamp];