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.style = lastNode.getTextStyle();
360 selection.format = 0;
365 const anchorKey = anchor.key;
366 const focus = selection.focus;
367 const focusKey = focus.key;
368 const nodes = selection.getNodes();
369 const nodesLength = nodes.length;
370 const isBackward = selection.isBackward();
371 const startOffset = isBackward ? focusOffset : anchorOffset;
372 const endOffset = isBackward ? anchorOffset : focusOffset;
373 const startKey = isBackward ? focusKey : anchorKey;
374 const endKey = isBackward ? anchorKey : focusKey;
375 let combinedFormat = IS_ALL_FORMATTING;
376 let hasTextNodes = false;
377 for (let i = 0; i < nodesLength; i++) {
378 const node = nodes[i];
379 const textContentSize = node.getTextContentSize();
382 textContentSize !== 0 &&
383 // Exclude empty text nodes at boundaries resulting from user's selection
386 node.__key === startKey &&
387 startOffset === textContentSize) ||
388 (i === nodesLength - 1 &&
389 node.__key === endKey &&
393 // TODO: what about style?
395 combinedFormat &= node.getFormat();
396 if (combinedFormat === 0) {
402 selection.format = hasTextNodes ? combinedFormat : 0;
406 dispatchCommand(editor, SELECTION_CHANGE_COMMAND, undefined);
410 // This is a work-around is mainly Chrome specific bug where if you select
411 // the contents of an empty block, you cannot easily unselect anything.
412 // This results in a tiny selection box that looks buggy/broken. This can
413 // also help other browsers when selection might "appear" lost, when it
415 function onClick(event: PointerEvent, editor: LexicalEditor): void {
416 updateEditor(editor, () => {
417 const selection = $getSelection();
418 const domSelection = getDOMSelection(editor._window);
419 const lastSelection = $getPreviousSelection();
422 if ($isRangeSelection(selection)) {
423 const anchor = selection.anchor;
424 const anchorNode = anchor.getNode();
427 anchor.type === 'element' &&
428 anchor.offset === 0 &&
429 selection.isCollapsed() &&
430 !$isRootNode(anchorNode) &&
431 $getRoot().getChildrenSize() === 1 &&
432 anchorNode.getTopLevelElementOrThrow().isEmpty() &&
433 lastSelection !== null &&
434 selection.is(lastSelection)
436 domSelection.removeAllRanges();
437 selection.dirty = true;
438 } else if (event.detail === 3 && !selection.isCollapsed()) {
439 // Tripple click causing selection to overflow into the nearest element. In that
440 // case visually it looks like a single element content is selected, focus node
441 // is actually at the beginning of the next element (if present) and any manipulations
442 // with selection (formatting) are affecting second element as well
443 const focus = selection.focus;
444 const focusNode = focus.getNode();
445 if (anchorNode !== focusNode) {
446 if ($isElementNode(anchorNode)) {
447 anchorNode.select(0);
449 anchorNode.getParentOrThrow().select(0);
453 } else if (event.pointerType === 'touch') {
454 // This is used to update the selection on touch devices when the user clicks on text after a
455 // node selection. See isSelectionChangeFromMouseDown for the inverse
456 const domAnchorNode = domSelection.anchorNode;
457 if (domAnchorNode !== null) {
458 const nodeType = domAnchorNode.nodeType;
459 // If the user is attempting to click selection back onto text, then
460 // we should attempt create a range selection.
461 // When we click on an empty paragraph node or the end of a paragraph that ends
462 // with an image/poll, the nodeType will be ELEMENT_NODE
463 if (nodeType === DOM_ELEMENT_TYPE || nodeType === DOM_TEXT_TYPE) {
464 const newSelection = $internalCreateRangeSelection(
470 $setSelection(newSelection);
476 dispatchCommand(editor, CLICK_COMMAND, event);
480 function onPointerDown(event: PointerEvent, editor: LexicalEditor) {
481 // TODO implement text drag & drop
482 const target = event.target;
483 const pointerType = event.pointerType;
484 if (target instanceof Node && pointerType !== 'touch') {
485 updateEditor(editor, () => {
486 // Drag & drop should not recompute selection until mouse up; otherwise the initially
487 // selected content is lost.
488 if (!$isSelectionCapturedInDecorator(target)) {
489 isSelectionChangeFromMouseDown = true;
495 function getTargetRange(event: InputEvent): null | StaticRange {
496 if (!event.getTargetRanges) {
499 const targetRanges = event.getTargetRanges();
500 if (targetRanges.length === 0) {
503 return targetRanges[0];
506 function $canRemoveText(
507 anchorNode: TextNode | ElementNode,
508 focusNode: TextNode | ElementNode,
511 anchorNode !== focusNode ||
512 $isElementNode(anchorNode) ||
513 $isElementNode(focusNode) ||
514 !anchorNode.isToken() ||
519 function isPossiblyAndroidKeyPress(timeStamp: number): boolean {
521 lastKeyCode === 'MediaLast' &&
522 timeStamp < lastKeyDownTimeStamp + ANDROID_COMPOSITION_LATENCY
526 function onBeforeInput(event: InputEvent, editor: LexicalEditor): void {
527 const inputType = event.inputType;
528 const targetRange = getTargetRange(event);
530 // We let the browser do its own thing for composition.
532 inputType === 'deleteCompositionText' ||
533 // If we're pasting in FF, we shouldn't get this event
534 // as the `paste` event should have triggered, unless the
535 // user has dom.event.clipboardevents.enabled disabled in
536 // about:config. In that case, we need to process the
537 // pasted content in the DOM mutation phase.
538 (IS_FIREFOX && isFirefoxClipboardEvents(editor))
541 } else if (inputType === 'insertCompositionText') {
545 updateEditor(editor, () => {
546 const selection = $getSelection();
548 if (inputType === 'deleteContentBackward') {
549 if (selection === null) {
550 // Use previous selection
551 const prevSelection = $getPreviousSelection();
553 if (!$isRangeSelection(prevSelection)) {
557 $setSelection(prevSelection.clone());
560 if ($isRangeSelection(selection)) {
561 const isSelectionAnchorSameAsFocus =
562 selection.anchor.key === selection.focus.key;
565 isPossiblyAndroidKeyPress(event.timeStamp) &&
566 editor.isComposing() &&
567 isSelectionAnchorSameAsFocus
569 $setCompositionKey(null);
570 lastKeyDownTimeStamp = 0;
571 // Fixes an Android bug where selection flickers when backspacing
573 updateEditor(editor, () => {
574 $setCompositionKey(null);
576 }, ANDROID_COMPOSITION_LATENCY);
577 if ($isRangeSelection(selection)) {
578 const anchorNode = selection.anchor.getNode();
579 anchorNode.markDirty();
581 $isTextNode(anchorNode),
582 'Anchor node must be a TextNode',
584 selection.style = anchorNode.getStyle();
587 $setCompositionKey(null);
588 event.preventDefault();
589 // Chromium Android at the moment seems to ignore the preventDefault
590 // on 'deleteContentBackward' and still deletes the content. Which leads
591 // to multiple deletions. So we let the browser handle the deletion in this case.
592 const selectedNodeText = selection.anchor.getNode().getTextContent();
593 const hasSelectedAllTextInNode =
594 selection.anchor.offset === 0 &&
595 selection.focus.offset === selectedNodeText.length;
596 const shouldLetBrowserHandleDelete =
598 isSelectionAnchorSameAsFocus &&
599 !hasSelectedAllTextInNode;
600 if (!shouldLetBrowserHandleDelete) {
601 dispatchCommand(editor, DELETE_CHARACTER_COMMAND, true);
608 if (!$isRangeSelection(selection)) {
612 const data = event.data;
614 // This represents the case when two beforeinput events are triggered at the same time (without a
615 // full event loop ending at input). This happens with MacOS with the default keyboard settings,
616 // a combination of autocorrection + autocapitalization.
617 // Having Lexical run everything in controlled mode would fix the issue without additional code
618 // but this would kill the massive performance win from the most common typing event.
619 // Alternatively, when this happens we can prematurely update our EditorState based on the DOM
620 // content, a job that would usually be the input event's responsibility.
621 if (unprocessedBeforeInputData !== null) {
622 $updateSelectedTextFromDOM(false, editor, unprocessedBeforeInputData);
626 (!selection.dirty || unprocessedBeforeInputData !== null) &&
627 selection.isCollapsed() &&
628 !$isRootNode(selection.anchor.getNode()) &&
631 selection.applyDOMRange(targetRange);
634 unprocessedBeforeInputData = null;
636 const anchor = selection.anchor;
637 const focus = selection.focus;
638 const anchorNode = anchor.getNode();
639 const focusNode = focus.getNode();
641 if (inputType === 'insertText' || inputType === 'insertTranspose') {
643 event.preventDefault();
644 dispatchCommand(editor, INSERT_LINE_BREAK_COMMAND, false);
645 } else if (data === DOUBLE_LINE_BREAK) {
646 event.preventDefault();
647 dispatchCommand(editor, INSERT_PARAGRAPH_COMMAND, undefined);
648 } else if (data == null && event.dataTransfer) {
649 // Gets around a Safari text replacement bug.
650 const text = event.dataTransfer.getData('text/plain');
651 event.preventDefault();
652 selection.insertRawText(text);
655 $shouldPreventDefaultAndInsertText(
663 event.preventDefault();
664 dispatchCommand(editor, CONTROLLED_TEXT_INSERTION_COMMAND, data);
666 unprocessedBeforeInputData = data;
668 lastBeforeInputInsertTextTimeStamp = event.timeStamp;
672 // Prevent the browser from carrying out
673 // the input event, so we can control the
675 event.preventDefault();
678 case 'insertFromYank':
679 case 'insertFromDrop':
680 case 'insertReplacementText': {
681 dispatchCommand(editor, CONTROLLED_TEXT_INSERTION_COMMAND, event);
685 case 'insertFromComposition': {
686 // This is the end of composition
687 $setCompositionKey(null);
688 dispatchCommand(editor, CONTROLLED_TEXT_INSERTION_COMMAND, event);
692 case 'insertLineBreak': {
694 $setCompositionKey(null);
695 dispatchCommand(editor, INSERT_LINE_BREAK_COMMAND, false);
699 case 'insertParagraph': {
701 $setCompositionKey(null);
703 // Safari does not provide the type "insertLineBreak".
704 // So instead, we need to infer it from the keyboard event.
705 // We do not apply this logic to iOS to allow newline auto-capitalization
706 // work without creating linebreaks when pressing Enter
707 if (isInsertLineBreak && !IS_IOS) {
708 isInsertLineBreak = false;
709 dispatchCommand(editor, INSERT_LINE_BREAK_COMMAND, false);
711 dispatchCommand(editor, INSERT_PARAGRAPH_COMMAND, undefined);
717 case 'insertFromPaste':
718 case 'insertFromPasteAsQuotation': {
719 dispatchCommand(editor, PASTE_COMMAND, event);
723 case 'deleteByComposition': {
724 if ($canRemoveText(anchorNode, focusNode)) {
725 dispatchCommand(editor, REMOVE_TEXT_COMMAND, event);
732 case 'deleteByCut': {
733 dispatchCommand(editor, REMOVE_TEXT_COMMAND, event);
737 case 'deleteContent': {
738 dispatchCommand(editor, DELETE_CHARACTER_COMMAND, false);
742 case 'deleteWordBackward': {
743 dispatchCommand(editor, DELETE_WORD_COMMAND, true);
747 case 'deleteWordForward': {
748 dispatchCommand(editor, DELETE_WORD_COMMAND, false);
752 case 'deleteHardLineBackward':
753 case 'deleteSoftLineBackward': {
754 dispatchCommand(editor, DELETE_LINE_COMMAND, true);
758 case 'deleteContentForward':
759 case 'deleteHardLineForward':
760 case 'deleteSoftLineForward': {
761 dispatchCommand(editor, DELETE_LINE_COMMAND, false);
765 case 'formatStrikeThrough': {
766 dispatchCommand(editor, FORMAT_TEXT_COMMAND, 'strikethrough');
771 dispatchCommand(editor, FORMAT_TEXT_COMMAND, 'bold');
775 case 'formatItalic': {
776 dispatchCommand(editor, FORMAT_TEXT_COMMAND, 'italic');
780 case 'formatUnderline': {
781 dispatchCommand(editor, FORMAT_TEXT_COMMAND, 'underline');
785 case 'historyUndo': {
786 dispatchCommand(editor, UNDO_COMMAND, undefined);
790 case 'historyRedo': {
791 dispatchCommand(editor, REDO_COMMAND, undefined);
801 function onInput(event: InputEvent, editor: LexicalEditor): void {
802 // We don't want the onInput to bubble, in the case of nested editors.
803 event.stopPropagation();
804 updateEditor(editor, () => {
805 const selection = $getSelection();
806 const data = event.data;
807 const targetRange = getTargetRange(event);
811 $isRangeSelection(selection) &&
812 $shouldPreventDefaultAndInsertText(
820 // Given we're over-riding the default behavior, we will need
821 // to ensure to disable composition before dispatching the
822 // insertText command for when changing the sequence for FF.
823 if (isFirefoxEndingComposition) {
824 $onCompositionEndImpl(editor, data);
825 isFirefoxEndingComposition = false;
827 const anchor = selection.anchor;
828 const anchorNode = anchor.getNode();
829 const domSelection = getDOMSelection(editor._window);
830 if (domSelection === null) {
833 const isBackward = selection.isBackward();
834 const startOffset = isBackward
835 ? selection.anchor.offset
836 : selection.focus.offset;
837 const endOffset = isBackward
838 ? selection.focus.offset
839 : selection.anchor.offset;
840 // If the content is the same as inserted, then don't dispatch an insertion.
841 // Given onInput doesn't take the current selection (it uses the previous)
842 // we can compare that against what the DOM currently says.
844 !CAN_USE_BEFORE_INPUT ||
845 selection.isCollapsed() ||
846 !$isTextNode(anchorNode) ||
847 domSelection.anchorNode === null ||
848 anchorNode.getTextContent().slice(0, startOffset) +
850 anchorNode.getTextContent().slice(startOffset + endOffset) !==
851 getAnchorTextFromDOM(domSelection.anchorNode)
853 dispatchCommand(editor, CONTROLLED_TEXT_INSERTION_COMMAND, data);
856 const textLength = data.length;
858 // Another hack for FF, as it's possible that the IME is still
859 // open, even though compositionend has already fired (sigh).
863 event.inputType === 'insertCompositionText' &&
864 !editor.isComposing()
866 selection.anchor.offset -= textLength;
869 // This ensures consistency on Android.
870 if (!IS_SAFARI && !IS_IOS && !IS_APPLE_WEBKIT && editor.isComposing()) {
871 lastKeyDownTimeStamp = 0;
872 $setCompositionKey(null);
875 const characterData = data !== null ? data : undefined;
876 $updateSelectedTextFromDOM(false, editor, characterData);
878 // onInput always fires after onCompositionEnd for FF.
879 if (isFirefoxEndingComposition) {
880 $onCompositionEndImpl(editor, data || undefined);
881 isFirefoxEndingComposition = false;
885 // Also flush any other mutations that might have occurred
889 unprocessedBeforeInputData = null;
892 function onCompositionStart(
893 event: CompositionEvent,
894 editor: LexicalEditor,
896 updateEditor(editor, () => {
897 const selection = $getSelection();
899 if ($isRangeSelection(selection) && !editor.isComposing()) {
900 const anchor = selection.anchor;
901 const node = selection.anchor.getNode();
902 $setCompositionKey(anchor.key);
905 // If it has been 30ms since the last keydown, then we should
906 // apply the empty space heuristic. We can't do this for Safari,
907 // as the keydown fires after composition start.
908 event.timeStamp < lastKeyDownTimeStamp + ANDROID_COMPOSITION_LATENCY ||
909 // FF has issues around composing multibyte characters, so we also
910 // need to invoke the empty space heuristic below.
911 anchor.type === 'element' ||
912 !selection.isCollapsed() ||
913 ($isTextNode(node) && node.getStyle() !== selection.style)
915 // We insert a zero width character, ready for the composition
916 // to get inserted into the new node we create. If
917 // we don't do this, Safari will fail on us because
918 // there is no text node matching the selection.
921 CONTROLLED_TEXT_INSERTION_COMMAND,
922 COMPOSITION_START_CHAR,
929 function $onCompositionEndImpl(editor: LexicalEditor, data?: string): void {
930 const compositionKey = editor._compositionKey;
931 $setCompositionKey(null);
933 // Handle termination of composition.
934 if (compositionKey !== null && data != null) {
935 // Composition can sometimes move to an adjacent DOM node when backspacing.
936 // So check for the empty case.
938 const node = $getNodeByKey(compositionKey);
939 const textNode = getDOMTextNode(editor.getElementByKey(compositionKey));
943 textNode.nodeValue !== null &&
946 $updateTextNodeFromDOMContent(
958 // Composition can sometimes be that of a new line. In which case, we need to
959 // handle that accordingly.
960 if (data[data.length - 1] === '\n') {
961 const selection = $getSelection();
963 if ($isRangeSelection(selection)) {
964 // If the last character is a line break, we also need to insert
966 const focus = selection.focus;
967 selection.anchor.set(focus.key, focus.offset, focus.type);
968 dispatchCommand(editor, KEY_ENTER_COMMAND, null);
974 $updateSelectedTextFromDOM(true, editor, data);
977 function onCompositionEnd(
978 event: CompositionEvent,
979 editor: LexicalEditor,
981 // Firefox fires onCompositionEnd before onInput, but Chrome/Webkit,
982 // fire onInput before onCompositionEnd. To ensure the sequence works
983 // like Chrome/Webkit we use the isFirefoxEndingComposition flag to
984 // defer handling of onCompositionEnd in Firefox till we have processed
985 // the logic in onInput.
987 isFirefoxEndingComposition = true;
989 updateEditor(editor, () => {
990 $onCompositionEndImpl(editor, event.data);
995 function onKeyDown(event: KeyboardEvent, editor: LexicalEditor): void {
996 lastKeyDownTimeStamp = event.timeStamp;
997 lastKeyCode = event.key;
998 if (editor.isComposing()) {
1002 const {key, shiftKey, ctrlKey, metaKey, altKey} = event;
1004 if (dispatchCommand(editor, KEY_DOWN_COMMAND, event)) {
1012 if (isMoveForward(key, ctrlKey, altKey, metaKey)) {
1013 dispatchCommand(editor, KEY_ARROW_RIGHT_COMMAND, event);
1014 } else if (isMoveToEnd(key, ctrlKey, shiftKey, altKey, metaKey)) {
1015 dispatchCommand(editor, MOVE_TO_END, event);
1016 } else if (isMoveBackward(key, ctrlKey, altKey, metaKey)) {
1017 dispatchCommand(editor, KEY_ARROW_LEFT_COMMAND, event);
1018 } else if (isMoveToStart(key, ctrlKey, shiftKey, altKey, metaKey)) {
1019 dispatchCommand(editor, MOVE_TO_START, event);
1020 } else if (isMoveUp(key, ctrlKey, metaKey)) {
1021 dispatchCommand(editor, KEY_ARROW_UP_COMMAND, event);
1022 } else if (isMoveDown(key, ctrlKey, metaKey)) {
1023 dispatchCommand(editor, KEY_ARROW_DOWN_COMMAND, event);
1024 } else if (isLineBreak(key, shiftKey)) {
1025 isInsertLineBreak = true;
1026 dispatchCommand(editor, KEY_ENTER_COMMAND, event);
1027 } else if (isSpace(key)) {
1028 dispatchCommand(editor, KEY_SPACE_COMMAND, event);
1029 } else if (isOpenLineBreak(key, ctrlKey)) {
1030 event.preventDefault();
1031 isInsertLineBreak = true;
1032 dispatchCommand(editor, INSERT_LINE_BREAK_COMMAND, true);
1033 } else if (isParagraph(key, shiftKey)) {
1034 isInsertLineBreak = false;
1035 dispatchCommand(editor, KEY_ENTER_COMMAND, event);
1036 } else if (isDeleteBackward(key, altKey, metaKey, ctrlKey)) {
1037 if (isBackspace(key)) {
1038 dispatchCommand(editor, KEY_BACKSPACE_COMMAND, event);
1040 event.preventDefault();
1041 dispatchCommand(editor, DELETE_CHARACTER_COMMAND, true);
1043 } else if (isEscape(key)) {
1044 dispatchCommand(editor, KEY_ESCAPE_COMMAND, event);
1045 } else if (isDeleteForward(key, ctrlKey, shiftKey, altKey, metaKey)) {
1046 if (isDelete(key)) {
1047 dispatchCommand(editor, KEY_DELETE_COMMAND, event);
1049 event.preventDefault();
1050 dispatchCommand(editor, DELETE_CHARACTER_COMMAND, false);
1052 } else if (isDeleteWordBackward(key, altKey, ctrlKey)) {
1053 event.preventDefault();
1054 dispatchCommand(editor, DELETE_WORD_COMMAND, true);
1055 } else if (isDeleteWordForward(key, altKey, ctrlKey)) {
1056 event.preventDefault();
1057 dispatchCommand(editor, DELETE_WORD_COMMAND, false);
1058 } else if (isDeleteLineBackward(key, metaKey)) {
1059 event.preventDefault();
1060 dispatchCommand(editor, DELETE_LINE_COMMAND, true);
1061 } else if (isDeleteLineForward(key, metaKey)) {
1062 event.preventDefault();
1063 dispatchCommand(editor, DELETE_LINE_COMMAND, false);
1064 } else if (isBold(key, altKey, metaKey, ctrlKey)) {
1065 event.preventDefault();
1066 dispatchCommand(editor, FORMAT_TEXT_COMMAND, 'bold');
1067 } else if (isUnderline(key, altKey, metaKey, ctrlKey)) {
1068 event.preventDefault();
1069 dispatchCommand(editor, FORMAT_TEXT_COMMAND, 'underline');
1070 } else if (isItalic(key, altKey, metaKey, ctrlKey)) {
1071 event.preventDefault();
1072 dispatchCommand(editor, FORMAT_TEXT_COMMAND, 'italic');
1073 } else if (isTab(key, altKey, ctrlKey, metaKey)) {
1074 dispatchCommand(editor, KEY_TAB_COMMAND, event);
1075 } else if (isUndo(key, shiftKey, metaKey, ctrlKey)) {
1076 event.preventDefault();
1077 dispatchCommand(editor, UNDO_COMMAND, undefined);
1078 } else if (isRedo(key, shiftKey, metaKey, ctrlKey)) {
1079 event.preventDefault();
1080 dispatchCommand(editor, REDO_COMMAND, undefined);
1082 const prevSelection = editor._editorState._selection;
1083 if ($isNodeSelection(prevSelection)) {
1084 if (isCopy(key, shiftKey, metaKey, ctrlKey)) {
1085 event.preventDefault();
1086 dispatchCommand(editor, COPY_COMMAND, event);
1087 } else if (isCut(key, shiftKey, metaKey, ctrlKey)) {
1088 event.preventDefault();
1089 dispatchCommand(editor, CUT_COMMAND, event);
1090 } else if (isSelectAll(key, metaKey, ctrlKey)) {
1091 event.preventDefault();
1092 dispatchCommand(editor, SELECT_ALL_COMMAND, event);
1094 // FF does it well (no need to override behavior)
1095 } else if (!IS_FIREFOX && isSelectAll(key, metaKey, ctrlKey)) {
1096 event.preventDefault();
1097 dispatchCommand(editor, SELECT_ALL_COMMAND, event);
1101 if (isModifier(ctrlKey, shiftKey, altKey, metaKey)) {
1102 dispatchCommand(editor, KEY_MODIFIER_COMMAND, event);
1106 function getRootElementRemoveHandles(
1107 rootElement: HTMLElement,
1108 ): RootElementRemoveHandles {
1109 // @ts-expect-error: internal field
1110 let eventHandles = rootElement.__lexicalEventHandles;
1112 if (eventHandles === undefined) {
1114 // @ts-expect-error: internal field
1115 rootElement.__lexicalEventHandles = eventHandles;
1118 return eventHandles;
1121 // Mapping root editors to their active nested editors, contains nested editors
1122 // mapping only, so if root editor is selected map will have no reference to free up memory
1123 const activeNestedEditorsMap: Map<string, LexicalEditor> = new Map();
1125 function onDocumentSelectionChange(event: Event): void {
1126 const target = event.target as null | Element | Document;
1127 const targetWindow =
1130 : target.nodeType === 9
1131 ? (target as Document).defaultView
1132 : (target as Element).ownerDocument.defaultView;
1133 const domSelection = getDOMSelection(targetWindow);
1134 if (domSelection === null) {
1137 const nextActiveEditor = getNearestEditorFromDOMNode(domSelection.anchorNode);
1138 if (nextActiveEditor === null) {
1142 if (isSelectionChangeFromMouseDown) {
1143 isSelectionChangeFromMouseDown = false;
1144 updateEditor(nextActiveEditor, () => {
1145 const lastSelection = $getPreviousSelection();
1146 const domAnchorNode = domSelection.anchorNode;
1147 if (domAnchorNode === null) {
1150 const nodeType = domAnchorNode.nodeType;
1151 // If the user is attempting to click selection back onto text, then
1152 // we should attempt create a range selection.
1153 // When we click on an empty paragraph node or the end of a paragraph that ends
1154 // with an image/poll, the nodeType will be ELEMENT_NODE
1155 if (nodeType !== DOM_ELEMENT_TYPE && nodeType !== DOM_TEXT_TYPE) {
1158 const newSelection = $internalCreateRangeSelection(
1164 $setSelection(newSelection);
1168 // When editor receives selection change event, we're checking if
1169 // it has any sibling editors (within same parent editor) that were active
1170 // before, and trigger selection change on it to nullify selection.
1171 const editors = getEditorsToPropagate(nextActiveEditor);
1172 const rootEditor = editors[editors.length - 1];
1173 const rootEditorKey = rootEditor._key;
1174 const activeNestedEditor = activeNestedEditorsMap.get(rootEditorKey);
1175 const prevActiveEditor = activeNestedEditor || rootEditor;
1177 if (prevActiveEditor !== nextActiveEditor) {
1178 onSelectionChange(domSelection, prevActiveEditor, false);
1181 onSelectionChange(domSelection, nextActiveEditor, true);
1183 // If newly selected editor is nested, then add it to the map, clean map otherwise
1184 if (nextActiveEditor !== rootEditor) {
1185 activeNestedEditorsMap.set(rootEditorKey, nextActiveEditor);
1186 } else if (activeNestedEditor) {
1187 activeNestedEditorsMap.delete(rootEditorKey);
1191 function stopLexicalPropagation(event: Event): void {
1192 // We attach a special property to ensure the same event doesn't re-fire
1193 // for parent editors.
1195 event._lexicalHandled = true;
1198 function hasStoppedLexicalPropagation(event: Event): boolean {
1200 const stopped = event._lexicalHandled === true;
1204 export type EventHandler = (event: Event, editor: LexicalEditor) => void;
1206 export function addRootElementEvents(
1207 rootElement: HTMLElement,
1208 editor: LexicalEditor,
1210 // We only want to have a single global selectionchange event handler, shared
1211 // between all editor instances.
1212 const doc = rootElement.ownerDocument;
1213 const documentRootElementsCount = rootElementsRegistered.get(doc);
1215 documentRootElementsCount === undefined ||
1216 documentRootElementsCount < 1
1218 doc.addEventListener('selectionchange', onDocumentSelectionChange);
1220 rootElementsRegistered.set(doc, (documentRootElementsCount || 0) + 1);
1222 // @ts-expect-error: internal field
1223 rootElement.__lexicalEditor = editor;
1224 const removeHandles = getRootElementRemoveHandles(rootElement);
1226 for (let i = 0; i < rootElementEvents.length; i++) {
1227 const [eventName, onEvent] = rootElementEvents[i];
1228 const eventHandler =
1229 typeof onEvent === 'function'
1230 ? (event: Event) => {
1231 if (hasStoppedLexicalPropagation(event)) {
1234 stopLexicalPropagation(event);
1235 if (editor.isEditable() || eventName === 'click') {
1236 onEvent(event, editor);
1239 : (event: Event) => {
1240 if (hasStoppedLexicalPropagation(event)) {
1243 stopLexicalPropagation(event);
1244 const isEditable = editor.isEditable();
1245 switch (eventName) {
1249 dispatchCommand(editor, CUT_COMMAND, event as ClipboardEvent)
1253 return dispatchCommand(
1256 event as ClipboardEvent,
1265 event as ClipboardEvent,
1272 dispatchCommand(editor, DRAGSTART_COMMAND, event as DragEvent)
1278 dispatchCommand(editor, DRAGOVER_COMMAND, event as DragEvent)
1284 dispatchCommand(editor, DRAGEND_COMMAND, event as DragEvent)
1290 dispatchCommand(editor, FOCUS_COMMAND, event as FocusEvent)
1296 dispatchCommand(editor, BLUR_COMMAND, event as FocusEvent)
1303 dispatchCommand(editor, DROP_COMMAND, event as DragEvent)
1307 rootElement.addEventListener(eventName, eventHandler);
1308 removeHandles.push(() => {
1309 rootElement.removeEventListener(eventName, eventHandler);
1314 export function removeRootElementEvents(rootElement: HTMLElement): void {
1315 const doc = rootElement.ownerDocument;
1316 const documentRootElementsCount = rootElementsRegistered.get(doc);
1318 documentRootElementsCount !== undefined,
1319 'Root element not registered',
1322 // We only want to have a single global selectionchange event handler, shared
1323 // between all editor instances.
1324 const newCount = documentRootElementsCount - 1;
1325 invariant(newCount >= 0, 'Root element count less than 0');
1326 rootElementsRegistered.set(doc, newCount);
1327 if (newCount === 0) {
1328 doc.removeEventListener('selectionchange', onDocumentSelectionChange);
1331 const editor = getEditorPropertyFromDOMNode(rootElement);
1333 if (isLexicalEditor(editor)) {
1334 cleanActiveNestedEditorsMap(editor);
1335 // @ts-expect-error: internal field
1336 rootElement.__lexicalEditor = null;
1337 } else if (editor) {
1340 'Attempted to remove event handlers from a node that does not belong to this build of Lexical',
1344 const removeHandles = getRootElementRemoveHandles(rootElement);
1346 for (let i = 0; i < removeHandles.length; i++) {
1350 // @ts-expect-error: internal field
1351 rootElement.__lexicalEventHandles = [];
1354 function cleanActiveNestedEditorsMap(editor: LexicalEditor) {
1355 if (editor._parentEditor !== null) {
1356 // For nested editor cleanup map if this editor was marked as active
1357 const editors = getEditorsToPropagate(editor);
1358 const rootEditor = editors[editors.length - 1];
1359 const rootEditorKey = rootEditor._key;
1361 if (activeNestedEditorsMap.get(rootEditorKey) === editor) {
1362 activeNestedEditorsMap.delete(rootEditorKey);
1365 // For top-level editors cleanup map
1366 activeNestedEditorsMap.delete(editor._key);
1370 export function markSelectionChangeFromDOMUpdate(): void {
1371 isSelectionChangeFromDOMUpdate = true;
1374 export function markCollapsedSelectionFormat(
1381 collapsedSelectionFormat = [format, style, offset, key, timeStamp];