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.
15 } from '../LexicalEditor';
21 SerializedLexicalNode,
22 } from '../LexicalNode';
23 import type {BaseSelection, RangeSelection} from '../LexicalSelection';
24 import type {ElementNode} from './LexicalElementNode';
26 import {IS_FIREFOX} from 'lexical/shared/environment';
27 import invariant from 'lexical/shared/invariant';
31 DETAIL_TYPE_TO_DETAIL,
49 } from '../LexicalConstants';
50 import {LexicalNode} from '../LexicalNode';
53 $internalMakeRangeSelection,
55 $updateElementSelectionOnCreateDeleteNode,
56 adjustPointOffsetForMergedSibling,
57 } from '../LexicalSelection';
58 import {errorOnReadOnly} from '../LexicalUpdates';
60 $applyNodeReplacement,
63 getCachedClassNameArray,
64 internalMarkSiblingsAsDirty,
68 } from '../LexicalUtils';
69 import {$createLineBreakNode} from './LexicalLineBreakNode';
70 import {$createTabNode} from './LexicalTabNode';
72 export type SerializedTextNode = Spread<
83 export type TextDetailType = 'directionless' | 'unmergable';
85 export type TextFormatType =
95 export type TextModeType = 'normal' | 'token' | 'segmented';
97 export type TextMark = {end: null | number; id: string; start: null | number};
99 export type TextMarks = Array<TextMark>;
101 function getElementOuterTag(node: TextNode, format: number): string | null {
102 if (format & IS_CODE) {
105 if (format & IS_HIGHLIGHT) {
108 if (format & IS_SUBSCRIPT) {
111 if (format & IS_SUPERSCRIPT) {
117 function getElementInnerTag(node: TextNode, format: number): string {
118 if (format & IS_BOLD) {
121 if (format & IS_ITALIC) {
127 function setTextThemeClassNames(
132 textClassNames: TextNodeThemeClasses,
134 const domClassList = dom.classList;
135 // Firstly we handle the base theme.
136 let classNames = getCachedClassNameArray(textClassNames, 'base');
137 if (classNames !== undefined) {
138 domClassList.add(...classNames);
140 // Secondly we handle the special case: underline + strikethrough.
141 // We have to do this as we need a way to compose the fact that
142 // the same CSS property will need to be used: text-decoration.
143 // In an ideal world we shouldn't have to do this, but there's no
144 // easy workaround for many atomic CSS systems today.
145 classNames = getCachedClassNameArray(
147 'underlineStrikethrough',
149 let hasUnderlineStrikethrough = false;
150 const prevUnderlineStrikethrough =
151 prevFormat & IS_UNDERLINE && prevFormat & IS_STRIKETHROUGH;
152 const nextUnderlineStrikethrough =
153 nextFormat & IS_UNDERLINE && nextFormat & IS_STRIKETHROUGH;
155 if (classNames !== undefined) {
156 if (nextUnderlineStrikethrough) {
157 hasUnderlineStrikethrough = true;
158 if (!prevUnderlineStrikethrough) {
159 domClassList.add(...classNames);
161 } else if (prevUnderlineStrikethrough) {
162 domClassList.remove(...classNames);
166 for (const key in TEXT_TYPE_TO_FORMAT) {
168 const flag = TEXT_TYPE_TO_FORMAT[format];
169 classNames = getCachedClassNameArray(textClassNames, key);
170 if (classNames !== undefined) {
171 if (nextFormat & flag) {
173 hasUnderlineStrikethrough &&
174 (key === 'underline' || key === 'strikethrough')
176 if (prevFormat & flag) {
177 domClassList.remove(...classNames);
182 (prevFormat & flag) === 0 ||
183 (prevUnderlineStrikethrough && key === 'underline') ||
184 key === 'strikethrough'
186 domClassList.add(...classNames);
188 } else if (prevFormat & flag) {
189 domClassList.remove(...classNames);
195 function diffComposedText(a: string, b: string): [number, number, string] {
196 const aLength = a.length;
197 const bLength = b.length;
201 while (left < aLength && left < bLength && a[left] === b[left]) {
205 right + left < aLength &&
206 right + left < bLength &&
207 a[aLength - right - 1] === b[bLength - right - 1]
212 return [left, aLength - left - right, b.slice(left, bLength - right)];
215 function setTextContent(
220 const firstChild = dom.firstChild;
221 const isComposing = node.isComposing();
222 // Always add a suffix if we're composing a node
223 const suffix = isComposing ? COMPOSITION_SUFFIX : '';
224 const text: string = nextText + suffix;
226 if (firstChild == null) {
227 dom.textContent = text;
229 const nodeValue = firstChild.nodeValue;
230 if (nodeValue !== text) {
231 if (isComposing || IS_FIREFOX) {
232 // We also use the diff composed text for general text in FF to avoid
233 // the spellcheck red line from flickering.
234 const [index, remove, insert] = diffComposedText(
240 firstChild.deleteData(index, remove);
243 firstChild.insertData(index, insert);
245 firstChild.nodeValue = text;
251 function createTextInnerDOM(
252 innerDOM: HTMLElement,
257 config: EditorConfig,
259 setTextContent(text, innerDOM, node);
260 const theme = config.theme;
261 // Apply theme class names
262 const textClassNames = theme.text;
264 if (textClassNames !== undefined) {
265 setTextThemeClassNames(innerTag, 0, format, innerDOM, textClassNames);
269 function wrapElementWith(
270 element: HTMLElement | Text,
273 const el = document.createElement(tag);
274 el.appendChild(element);
278 // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
279 export interface TextNode {
280 getTopLevelElement(): ElementNode | null;
281 getTopLevelElementOrThrow(): ElementNode;
285 // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
286 export class TextNode extends LexicalNode {
287 ['constructor']!: KlassConstructor<typeof TextNode>;
294 __mode: 0 | 1 | 2 | 3;
298 static getType(): string {
302 static clone(node: TextNode): TextNode {
303 return new TextNode(node.__text, node.__key);
306 afterCloneFrom(prevNode: this): void {
307 super.afterCloneFrom(prevNode);
308 this.__format = prevNode.__format;
309 this.__style = prevNode.__style;
310 this.__mode = prevNode.__mode;
311 this.__detail = prevNode.__detail;
314 constructor(text: string, key?: NodeKey) {
324 * Returns a 32-bit integer that represents the TextFormatTypes currently applied to the
325 * TextNode. You probably don't want to use this method directly - consider using TextNode.hasFormat instead.
327 * @returns a number representing the format of the text node.
329 getFormat(): number {
330 const self = this.getLatest();
331 return self.__format;
335 * Returns a 32-bit integer that represents the TextDetailTypes currently applied to the
336 * TextNode. You probably don't want to use this method directly - consider using TextNode.isDirectionless
337 * or TextNode.isUnmergeable instead.
339 * @returns a number representing the detail of the text node.
341 getDetail(): number {
342 const self = this.getLatest();
343 return self.__detail;
347 * Returns the mode (TextModeType) of the TextNode, which may be "normal", "token", or "segmented"
349 * @returns TextModeType.
351 getMode(): TextModeType {
352 const self = this.getLatest();
353 return TEXT_TYPE_TO_MODE[self.__mode];
357 * Returns the styles currently applied to the node. This is analogous to CSSText in the DOM.
359 * @returns CSSText-like string of styles applied to the underlying DOM node.
362 const self = this.getLatest();
367 * Returns whether or not the node is in "token" mode. TextNodes in token mode can be navigated through character-by-character
368 * with a RangeSelection, but are deleted as a single entity (not invdividually by character).
370 * @returns true if the node is in token mode, false otherwise.
373 const self = this.getLatest();
374 return self.__mode === IS_TOKEN;
379 * @returns true if Lexical detects that an IME or other 3rd-party script is attempting to
380 * mutate the TextNode, false otherwise.
382 isComposing(): boolean {
383 return this.__key === $getCompositionKey();
387 * Returns whether or not the node is in "segemented" mode. TextNodes in segemented mode can be navigated through character-by-character
388 * with a RangeSelection, but are deleted in space-delimited "segments".
390 * @returns true if the node is in segmented mode, false otherwise.
392 isSegmented(): boolean {
393 const self = this.getLatest();
394 return self.__mode === IS_SEGMENTED;
397 * Returns whether or not the node is "directionless". Directionless nodes don't respect changes between RTL and LTR modes.
399 * @returns true if the node is directionless, false otherwise.
401 isDirectionless(): boolean {
402 const self = this.getLatest();
403 return (self.__detail & IS_DIRECTIONLESS) !== 0;
406 * Returns whether or not the node is unmergeable. In some scenarios, Lexical tries to merge
407 * adjacent TextNodes into a single TextNode. If a TextNode is unmergeable, this won't happen.
409 * @returns true if the node is unmergeable, false otherwise.
411 isUnmergeable(): boolean {
412 const self = this.getLatest();
413 return (self.__detail & IS_UNMERGEABLE) !== 0;
417 * Returns whether or not the node has the provided format applied. Use this with the human-readable TextFormatType
418 * string values to get the format of a TextNode.
420 * @param type - the TextFormatType to check for.
422 * @returns true if the node has the provided format, false otherwise.
424 hasFormat(type: TextFormatType): boolean {
425 const formatFlag = TEXT_TYPE_TO_FORMAT[type];
426 return (this.getFormat() & formatFlag) !== 0;
430 * Returns whether or not the node is simple text. Simple text is defined as a TextNode that has the string type "text"
431 * (i.e., not a subclass) and has no mode applied to it (i.e., not segmented or token).
433 * @returns true if the node is simple text, false otherwise.
435 isSimpleText(): boolean {
436 return this.__type === 'text' && this.__mode === 0;
440 * Returns the text content of the node as a string.
442 * @returns a string representing the text content of the node.
444 getTextContent(): string {
445 const self = this.getLatest();
450 * Returns the format flags applied to the node as a 32-bit integer.
452 * @returns a number representing the TextFormatTypes applied to the node.
454 getFormatFlags(type: TextFormatType, alignWithFormat: null | number): number {
455 const self = this.getLatest();
456 const format = self.__format;
457 return toggleTextFormatType(format, type, alignWithFormat);
462 * @returns true if the text node supports font styling, false otherwise.
464 canHaveFormat(): boolean {
470 createDOM(config: EditorConfig, editor?: LexicalEditor): HTMLElement {
471 const format = this.__format;
472 const outerTag = getElementOuterTag(this, format);
473 const innerTag = getElementInnerTag(this, format);
474 const tag = outerTag === null ? innerTag : outerTag;
475 const dom = document.createElement(tag);
477 if (this.hasFormat('code')) {
478 dom.setAttribute('spellcheck', 'false');
480 if (outerTag !== null) {
481 innerDOM = document.createElement(innerTag);
482 dom.appendChild(innerDOM);
484 const text = this.__text;
485 createTextInnerDOM(innerDOM, this, innerTag, format, text, config);
486 const style = this.__style;
488 dom.style.cssText = style;
496 config: EditorConfig,
498 const nextText = this.__text;
499 const prevFormat = prevNode.__format;
500 const nextFormat = this.__format;
501 const prevOuterTag = getElementOuterTag(this, prevFormat);
502 const nextOuterTag = getElementOuterTag(this, nextFormat);
503 const prevInnerTag = getElementInnerTag(this, prevFormat);
504 const nextInnerTag = getElementInnerTag(this, nextFormat);
505 const prevTag = prevOuterTag === null ? prevInnerTag : prevOuterTag;
506 const nextTag = nextOuterTag === null ? nextInnerTag : nextOuterTag;
508 if (prevTag !== nextTag) {
511 if (prevOuterTag === nextOuterTag && prevInnerTag !== nextInnerTag) {
512 // should always be an element
513 const prevInnerDOM: HTMLElement = dom.firstChild as HTMLElement;
514 if (prevInnerDOM == null) {
515 invariant(false, 'updateDOM: prevInnerDOM is null or undefined');
517 const nextInnerDOM = document.createElement(nextInnerTag);
526 dom.replaceChild(nextInnerDOM, prevInnerDOM);
530 if (nextOuterTag !== null) {
531 if (prevOuterTag !== null) {
532 innerDOM = dom.firstChild as HTMLElement;
533 if (innerDOM == null) {
534 invariant(false, 'updateDOM: innerDOM is null or undefined');
538 setTextContent(nextText, innerDOM, this);
539 const theme = config.theme;
540 // Apply theme class names
541 const textClassNames = theme.text;
543 if (textClassNames !== undefined && prevFormat !== nextFormat) {
544 setTextThemeClassNames(
552 const prevStyle = prevNode.__style;
553 const nextStyle = this.__style;
554 if (prevStyle !== nextStyle) {
555 dom.style.cssText = nextStyle;
560 static importDOM(): DOMConversionMap | null {
563 conversion: $convertTextDOMNode,
567 conversion: convertBringAttentionToElement,
571 conversion: convertTextFormatElement,
575 conversion: convertTextFormatElement,
579 conversion: convertTextFormatElement,
583 conversion: convertTextFormatElement,
587 conversion: convertSpanElement,
591 conversion: convertTextFormatElement,
595 conversion: convertTextFormatElement,
599 conversion: convertTextFormatElement,
603 conversion: convertTextFormatElement,
609 static importJSON(serializedNode: SerializedTextNode): TextNode {
610 const node = $createTextNode(serializedNode.text);
611 node.setFormat(serializedNode.format);
612 node.setDetail(serializedNode.detail);
613 node.setMode(serializedNode.mode);
614 node.setStyle(serializedNode.style);
618 // This improves Lexical's basic text output in copy+paste plus
619 // for headless mode where people might use Lexical to generate
620 // HTML content and not have the ability to use CSS classes.
621 exportDOM(editor: LexicalEditor): DOMExportOutput {
622 let {element} = super.exportDOM(editor);
624 element !== null && isHTMLElement(element),
625 'Expected TextNode createDOM to always return a HTMLElement',
627 element.style.whiteSpace = 'pre-wrap';
628 // This is the only way to properly add support for most clients,
629 // even if it's semantically incorrect to have to resort to using
630 // <b>, <u>, <s>, <i> elements.
631 if (this.hasFormat('bold')) {
632 element = wrapElementWith(element, 'b');
634 if (this.hasFormat('italic')) {
635 element = wrapElementWith(element, 'i');
637 if (this.hasFormat('strikethrough')) {
638 element = wrapElementWith(element, 's');
640 if (this.hasFormat('underline')) {
641 element = wrapElementWith(element, 'u');
649 exportJSON(): SerializedTextNode {
651 detail: this.getDetail(),
652 format: this.getFormat(),
653 mode: this.getMode(),
654 style: this.getStyle(),
655 text: this.getTextContent(),
663 prevSelection: null | BaseSelection,
664 nextSelection: RangeSelection,
670 * Sets the node format to the provided TextFormatType or 32-bit integer. Note that the TextFormatType
671 * version of the argument can only specify one format and doing so will remove all other formats that
672 * may be applied to the node. For toggling behavior, consider using {@link TextNode.toggleFormat}
674 * @param format - TextFormatType or 32-bit integer representing the node format.
676 * @returns this TextNode.
677 * // TODO 0.12 This should just be a `string`.
679 setFormat(format: TextFormatType | number): this {
680 const self = this.getWritable();
682 typeof format === 'string' ? TEXT_TYPE_TO_FORMAT[format] : format;
687 * Sets the node detail to the provided TextDetailType or 32-bit integer. Note that the TextDetailType
688 * version of the argument can only specify one detail value and doing so will remove all other detail values that
689 * may be applied to the node. For toggling behavior, consider using {@link TextNode.toggleDirectionless}
690 * or {@link TextNode.toggleUnmergeable}
692 * @param detail - TextDetailType or 32-bit integer representing the node detail.
694 * @returns this TextNode.
695 * // TODO 0.12 This should just be a `string`.
697 setDetail(detail: TextDetailType | number): this {
698 const self = this.getWritable();
700 typeof detail === 'string' ? DETAIL_TYPE_TO_DETAIL[detail] : detail;
705 * Sets the node style to the provided CSSText-like string. Set this property as you
706 * would an HTMLElement style attribute to apply inline styles to the underlying DOM Element.
708 * @param style - CSSText to be applied to the underlying HTMLElement.
710 * @returns this TextNode.
712 setStyle(style: string): this {
713 const self = this.getWritable();
714 self.__style = style;
719 * Applies the provided format to this TextNode if it's not present. Removes it if it's present.
720 * The subscript and superscript formats are mutually exclusive.
721 * Prefer using this method to turn specific formats on and off.
723 * @param type - TextFormatType to toggle.
725 * @returns this TextNode.
727 toggleFormat(type: TextFormatType): this {
728 const format = this.getFormat();
729 const newFormat = toggleTextFormatType(format, type, null);
730 return this.setFormat(newFormat);
734 * Toggles the directionless detail value of the node. Prefer using this method over setDetail.
736 * @returns this TextNode.
738 toggleDirectionless(): this {
739 const self = this.getWritable();
740 self.__detail ^= IS_DIRECTIONLESS;
745 * Toggles the unmergeable detail value of the node. Prefer using this method over setDetail.
747 * @returns this TextNode.
749 toggleUnmergeable(): this {
750 const self = this.getWritable();
751 self.__detail ^= IS_UNMERGEABLE;
756 * Sets the mode of the node.
758 * @returns this TextNode.
760 setMode(type: TextModeType): this {
761 const mode = TEXT_MODE_TO_TYPE[type];
762 if (this.__mode === mode) {
765 const self = this.getWritable();
771 * Sets the text content of the node.
773 * @param text - the string to set as the text value of the node.
775 * @returns this TextNode.
777 setTextContent(text: string): this {
778 if (this.__text === text) {
781 const self = this.getWritable();
787 * Sets the current Lexical selection to be a RangeSelection with anchor and focus on this TextNode at the provided offsets.
789 * @param _anchorOffset - the offset at which the Selection anchor will be placed.
790 * @param _focusOffset - the offset at which the Selection focus will be placed.
792 * @returns the new RangeSelection.
794 select(_anchorOffset?: number, _focusOffset?: number): RangeSelection {
796 let anchorOffset = _anchorOffset;
797 let focusOffset = _focusOffset;
798 const selection = $getSelection();
799 const text = this.getTextContent();
800 const key = this.__key;
801 if (typeof text === 'string') {
802 const lastOffset = text.length;
803 if (anchorOffset === undefined) {
804 anchorOffset = lastOffset;
806 if (focusOffset === undefined) {
807 focusOffset = lastOffset;
813 if (!$isRangeSelection(selection)) {
814 return $internalMakeRangeSelection(
823 const compositionKey = $getCompositionKey();
825 compositionKey === selection.anchor.key ||
826 compositionKey === selection.focus.key
828 $setCompositionKey(key);
830 selection.setTextNodeRange(this, anchorOffset, this, focusOffset);
835 selectStart(): RangeSelection {
836 return this.select(0, 0);
839 selectEnd(): RangeSelection {
840 const size = this.getTextContentSize();
841 return this.select(size, size);
845 * Inserts the provided text into this TextNode at the provided offset, deleting the number of characters
846 * specified. Can optionally calculate a new selection after the operation is complete.
848 * @param offset - the offset at which the splice operation should begin.
849 * @param delCount - the number of characters to delete, starting from the offset.
850 * @param newText - the text to insert into the TextNode at the offset.
851 * @param moveSelection - optional, whether or not to move selection to the end of the inserted substring.
853 * @returns this TextNode.
859 moveSelection?: boolean,
861 const writableSelf = this.getWritable();
862 const text = writableSelf.__text;
863 const handledTextLength = newText.length;
866 index = handledTextLength + index;
871 const selection = $getSelection();
872 if (moveSelection && $isRangeSelection(selection)) {
873 const newOffset = offset + handledTextLength;
874 selection.setTextNodeRange(
883 text.slice(0, index) + newText + text.slice(index + delCount);
885 writableSelf.__text = updatedText;
890 * This method is meant to be overriden by TextNode subclasses to control the behavior of those nodes
891 * when a user event would cause text to be inserted before them in the editor. If true, Lexical will attempt
892 * to insert text into this node. If false, it will insert the text in a new sibling node.
894 * @returns true if text can be inserted before the node, false otherwise.
896 canInsertTextBefore(): boolean {
901 * This method is meant to be overriden by TextNode subclasses to control the behavior of those nodes
902 * when a user event would cause text to be inserted after them in the editor. If true, Lexical will attempt
903 * to insert text into this node. If false, it will insert the text in a new sibling node.
905 * @returns true if text can be inserted after the node, false otherwise.
907 canInsertTextAfter(): boolean {
912 * Splits this TextNode at the provided character offsets, forming new TextNodes from the substrings
913 * formed by the split, and inserting those new TextNodes into the editor, replacing the one that was split.
915 * @param splitOffsets - rest param of the text content character offsets at which this node should be split.
917 * @returns an Array containing the newly-created TextNodes.
919 splitText(...splitOffsets: Array<number>): Array<TextNode> {
921 const self = this.getLatest();
922 const textContent = self.getTextContent();
923 const key = self.__key;
924 const compositionKey = $getCompositionKey();
925 const offsetsSet = new Set(splitOffsets);
927 const textLength = textContent.length;
929 for (let i = 0; i < textLength; i++) {
930 if (string !== '' && offsetsSet.has(i)) {
934 string += textContent[i];
939 const partsLength = parts.length;
940 if (partsLength === 0) {
942 } else if (parts[0] === textContent) {
945 const firstPart = parts[0];
946 const parent = self.getParent();
948 const format = self.getFormat();
949 const style = self.getStyle();
950 const detail = self.__detail;
951 let hasReplacedSelf = false;
953 if (self.isSegmented()) {
954 // Create a new TextNode
955 writableNode = $createTextNode(firstPart);
956 writableNode.__format = format;
957 writableNode.__style = style;
958 writableNode.__detail = detail;
959 hasReplacedSelf = true;
961 // For the first part, update the existing node
962 writableNode = self.getWritable();
963 writableNode.__text = firstPart;
967 const selection = $getSelection();
969 // Then handle all other parts
970 const splitNodes: TextNode[] = [writableNode];
971 let textSize = firstPart.length;
973 for (let i = 1; i < partsLength; i++) {
974 const part = parts[i];
975 const partSize = part.length;
976 const sibling = $createTextNode(part).getWritable();
977 sibling.__format = format;
978 sibling.__style = style;
979 sibling.__detail = detail;
980 const siblingKey = sibling.__key;
981 const nextTextSize = textSize + partSize;
983 if ($isRangeSelection(selection)) {
984 const anchor = selection.anchor;
985 const focus = selection.focus;
988 anchor.key === key &&
989 anchor.type === 'text' &&
990 anchor.offset > textSize &&
991 anchor.offset <= nextTextSize
993 anchor.key = siblingKey;
994 anchor.offset -= textSize;
995 selection.dirty = true;
999 focus.type === 'text' &&
1000 focus.offset > textSize &&
1001 focus.offset <= nextTextSize
1003 focus.key = siblingKey;
1004 focus.offset -= textSize;
1005 selection.dirty = true;
1008 if (compositionKey === key) {
1009 $setCompositionKey(siblingKey);
1011 textSize = nextTextSize;
1012 splitNodes.push(sibling);
1015 // Insert the nodes into the parent's children
1016 if (parent !== null) {
1017 internalMarkSiblingsAsDirty(this);
1018 const writableParent = parent.getWritable();
1019 const insertionIndex = this.getIndexWithinParent();
1020 if (hasReplacedSelf) {
1021 writableParent.splice(insertionIndex, 0, splitNodes);
1024 writableParent.splice(insertionIndex, 1, splitNodes);
1027 if ($isRangeSelection(selection)) {
1028 $updateElementSelectionOnCreateDeleteNode(
1041 * Merges the target TextNode into this TextNode, removing the target node.
1043 * @param target - the TextNode to merge into this one.
1045 * @returns this TextNode.
1047 mergeWithSibling(target: TextNode): TextNode {
1048 const isBefore = target === this.getPreviousSibling();
1049 if (!isBefore && target !== this.getNextSibling()) {
1052 'mergeWithSibling: sibling must be a previous or next sibling',
1055 const key = this.__key;
1056 const targetKey = target.__key;
1057 const text = this.__text;
1058 const textLength = text.length;
1059 const compositionKey = $getCompositionKey();
1061 if (compositionKey === targetKey) {
1062 $setCompositionKey(key);
1064 const selection = $getSelection();
1065 if ($isRangeSelection(selection)) {
1066 const anchor = selection.anchor;
1067 const focus = selection.focus;
1068 if (anchor !== null && anchor.key === targetKey) {
1069 adjustPointOffsetForMergedSibling(
1076 selection.dirty = true;
1078 if (focus !== null && focus.key === targetKey) {
1079 adjustPointOffsetForMergedSibling(
1086 selection.dirty = true;
1089 const targetText = target.__text;
1090 const newText = isBefore ? targetText + text : text + targetText;
1091 this.setTextContent(newText);
1092 const writableSelf = this.getWritable();
1094 return writableSelf;
1098 * This method is meant to be overriden by TextNode subclasses to control the behavior of those nodes
1099 * when used with the registerLexicalTextEntity function. If you're using registerLexicalTextEntity, the
1100 * node class that you create and replace matched text with should return true from this method.
1102 * @returns true if the node is to be treated as a "text entity", false otherwise.
1104 isTextEntity(): boolean {
1109 function convertSpanElement(domNode: HTMLSpanElement): DOMConversionOutput {
1110 // domNode is a <span> since we matched it by nodeName
1111 const span = domNode;
1112 const style = span.style;
1115 forChild: applyTextFormatFromStyle(style),
1120 function convertBringAttentionToElement(
1121 domNode: HTMLElement,
1122 ): DOMConversionOutput {
1123 // domNode is a <b> since we matched it by nodeName
1125 // Google Docs wraps all copied HTML in a <b> with font-weight normal
1126 const hasNormalFontWeight = b.style.fontWeight === 'normal';
1129 forChild: applyTextFormatFromStyle(
1131 hasNormalFontWeight ? undefined : 'bold',
1137 const preParentCache = new WeakMap<Node, null | Node>();
1139 function isNodePre(node: Node): boolean {
1141 node.nodeName === 'PRE' ||
1142 (node.nodeType === DOM_ELEMENT_TYPE &&
1143 (node as HTMLElement).style !== undefined &&
1144 (node as HTMLElement).style.whiteSpace !== undefined &&
1145 (node as HTMLElement).style.whiteSpace.startsWith('pre'))
1149 export function findParentPreDOMNode(node: Node) {
1151 let parent = node.parentNode;
1152 const visited = [node];
1155 (cached = preParentCache.get(parent)) === undefined &&
1158 visited.push(parent);
1159 parent = parent.parentNode;
1161 const resultNode = cached === undefined ? parent : cached;
1162 for (let i = 0; i < visited.length; i++) {
1163 preParentCache.set(visited[i], resultNode);
1168 function $convertTextDOMNode(domNode: Node): DOMConversionOutput {
1169 const domNode_ = domNode as Text;
1170 const parentDom = domNode.parentElement;
1173 'Expected parentElement of Text not to be null',
1175 let textContent = domNode_.textContent || '';
1176 // No collapse and preserve segment break for pre, pre-wrap and pre-line
1177 if (findParentPreDOMNode(domNode_) !== null) {
1178 const parts = textContent.split(/(\r?\n|\t)/);
1179 const nodes: Array<LexicalNode> = [];
1180 const length = parts.length;
1181 for (let i = 0; i < length; i++) {
1182 const part = parts[i];
1183 if (part === '\n' || part === '\r\n') {
1184 nodes.push($createLineBreakNode());
1185 } else if (part === '\t') {
1186 nodes.push($createTabNode());
1187 } else if (part !== '') {
1188 nodes.push($createTextNode(part));
1191 return {node: nodes};
1193 textContent = textContent.replace(/\r/g, '').replace(/[ \t\n]+/g, ' ');
1194 if (textContent === '') {
1195 return {node: null};
1197 if (textContent[0] === ' ') {
1198 // Traverse backward while in the same line. If content contains new line or tab -> pontential
1199 // delete, other elements can borrow from this one. Deletion depends on whether it's also the
1200 // last space (see next condition: textContent[textContent.length - 1] === ' '))
1201 let previousText: null | Text = domNode_;
1202 let isStartOfLine = true;
1204 previousText !== null &&
1205 (previousText = findTextInLine(previousText, false)) !== null
1207 const previousTextContent = previousText.textContent || '';
1208 if (previousTextContent.length > 0) {
1209 if (/[ \t\n]$/.test(previousTextContent)) {
1210 textContent = textContent.slice(1);
1212 isStartOfLine = false;
1216 if (isStartOfLine) {
1217 textContent = textContent.slice(1);
1220 if (textContent[textContent.length - 1] === ' ') {
1221 // Traverse forward while in the same line, preserve if next inline will require a space
1222 let nextText: null | Text = domNode_;
1223 let isEndOfLine = true;
1225 nextText !== null &&
1226 (nextText = findTextInLine(nextText, true)) !== null
1228 const nextTextContent = (nextText.textContent || '').replace(
1232 if (nextTextContent.length > 0) {
1233 isEndOfLine = false;
1238 textContent = textContent.slice(0, textContent.length - 1);
1241 if (textContent === '') {
1242 return {node: null};
1244 return {node: $createTextNode(textContent)};
1247 function findTextInLine(text: Text, forward: boolean): null | Text {
1248 let node: Node = text;
1249 // eslint-disable-next-line no-constant-condition
1251 let sibling: null | Node;
1253 (sibling = forward ? node.nextSibling : node.previousSibling) === null
1255 const parentElement = node.parentElement;
1256 if (parentElement === null) {
1259 node = parentElement;
1262 if (node.nodeType === DOM_ELEMENT_TYPE) {
1263 const display = (node as HTMLElement).style.display;
1265 (display === '' && !isInlineDomNode(node)) ||
1266 (display !== '' && !display.startsWith('inline'))
1271 let descendant: null | Node = node;
1272 while ((descendant = forward ? node.firstChild : node.lastChild) !== null) {
1275 if (node.nodeType === DOM_TEXT_TYPE) {
1276 return node as Text;
1277 } else if (node.nodeName === 'BR') {
1283 const nodeNameToTextFormat: Record<string, TextFormatType> = {
1294 function convertTextFormatElement(domNode: HTMLElement): DOMConversionOutput {
1295 const format = nodeNameToTextFormat[domNode.nodeName.toLowerCase()];
1296 if (format === undefined) {
1297 return {node: null};
1300 forChild: applyTextFormatFromStyle(domNode.style, format),
1305 export function $createTextNode(text = ''): TextNode {
1306 return $applyNodeReplacement(new TextNode(text));
1309 export function $isTextNode(
1310 node: LexicalNode | null | undefined,
1311 ): node is TextNode {
1312 return node instanceof TextNode;
1315 function applyTextFormatFromStyle(
1316 style: CSSStyleDeclaration,
1317 shouldApply?: TextFormatType,
1319 const fontWeight = style.fontWeight;
1320 const textDecoration = style.textDecoration.split(' ');
1321 // Google Docs uses span tags + font-weight for bold text
1322 const hasBoldFontWeight = fontWeight === '700' || fontWeight === 'bold';
1323 // Google Docs uses span tags + text-decoration: line-through for strikethrough text
1324 const hasLinethroughTextDecoration = textDecoration.includes('line-through');
1325 // Google Docs uses span tags + font-style for italic text
1326 const hasItalicFontStyle = style.fontStyle === 'italic';
1327 // Google Docs uses span tags + text-decoration: underline for underline text
1328 const hasUnderlineTextDecoration = textDecoration.includes('underline');
1329 // Google Docs uses span tags + vertical-align to specify subscript and superscript
1330 const verticalAlign = style.verticalAlign;
1332 return (lexicalNode: LexicalNode) => {
1333 if (!$isTextNode(lexicalNode)) {
1336 if (hasBoldFontWeight && !lexicalNode.hasFormat('bold')) {
1337 lexicalNode.toggleFormat('bold');
1340 hasLinethroughTextDecoration &&
1341 !lexicalNode.hasFormat('strikethrough')
1343 lexicalNode.toggleFormat('strikethrough');
1345 if (hasItalicFontStyle && !lexicalNode.hasFormat('italic')) {
1346 lexicalNode.toggleFormat('italic');
1348 if (hasUnderlineTextDecoration && !lexicalNode.hasFormat('underline')) {
1349 lexicalNode.toggleFormat('underline');
1351 if (verticalAlign === 'sub' && !lexicalNode.hasFormat('subscript')) {
1352 lexicalNode.toggleFormat('subscript');
1354 if (verticalAlign === 'super' && !lexicalNode.hasFormat('superscript')) {
1355 lexicalNode.toggleFormat('superscript');
1358 if (shouldApply && !lexicalNode.hasFormat(shouldApply)) {
1359 lexicalNode.toggleFormat(shouldApply);