]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/lexical/core/nodes/LexicalTextNode.ts
7f1b4f305154472bae7cc8a573bb10dbd3c6632e
[bookstack] / resources / js / wysiwyg / lexical / core / nodes / LexicalTextNode.ts
1 /**
2  * Copyright (c) Meta Platforms, Inc. and affiliates.
3  *
4  * This source code is licensed under the MIT license found in the
5  * LICENSE file in the root directory of this source tree.
6  *
7  */
8
9 import type {
10   EditorConfig,
11   KlassConstructor,
12   LexicalEditor,
13   Spread,
14   TextNodeThemeClasses,
15 } from '../LexicalEditor';
16 import type {
17   DOMConversionMap,
18   DOMConversionOutput,
19   DOMExportOutput,
20   NodeKey,
21   SerializedLexicalNode,
22 } from '../LexicalNode';
23 import type {BaseSelection, RangeSelection} from '../LexicalSelection';
24 import type {ElementNode} from './LexicalElementNode';
25
26 import {IS_FIREFOX} from 'lexical/shared/environment';
27 import invariant from 'lexical/shared/invariant';
28
29 import {
30   COMPOSITION_SUFFIX,
31   DETAIL_TYPE_TO_DETAIL,
32   DOM_ELEMENT_TYPE,
33   DOM_TEXT_TYPE,
34   IS_BOLD,
35   IS_CODE,
36   IS_DIRECTIONLESS,
37   IS_HIGHLIGHT,
38   IS_ITALIC,
39   IS_SEGMENTED,
40   IS_STRIKETHROUGH,
41   IS_SUBSCRIPT,
42   IS_SUPERSCRIPT,
43   IS_TOKEN,
44   IS_UNDERLINE,
45   IS_UNMERGEABLE,
46   TEXT_MODE_TO_TYPE,
47   TEXT_TYPE_TO_FORMAT,
48   TEXT_TYPE_TO_MODE,
49 } from '../LexicalConstants';
50 import {LexicalNode} from '../LexicalNode';
51 import {
52   $getSelection,
53   $internalMakeRangeSelection,
54   $isRangeSelection,
55   $updateElementSelectionOnCreateDeleteNode,
56   adjustPointOffsetForMergedSibling,
57 } from '../LexicalSelection';
58 import {errorOnReadOnly} from '../LexicalUpdates';
59 import {
60   $applyNodeReplacement,
61   $getCompositionKey,
62   $setCompositionKey,
63   getCachedClassNameArray,
64   internalMarkSiblingsAsDirty,
65   isHTMLElement,
66   isInlineDomNode,
67   toggleTextFormatType,
68 } from '../LexicalUtils';
69 import {$createLineBreakNode} from './LexicalLineBreakNode';
70 import {$createTabNode} from './LexicalTabNode';
71
72 export type SerializedTextNode = Spread<
73   {
74     detail: number;
75     format: number;
76     mode: TextModeType;
77     style: string;
78     text: string;
79   },
80   SerializedLexicalNode
81 >;
82
83 export type TextDetailType = 'directionless' | 'unmergable';
84
85 export type TextFormatType =
86   | 'bold'
87   | 'underline'
88   | 'strikethrough'
89   | 'italic'
90   | 'highlight'
91   | 'code'
92   | 'subscript'
93   | 'superscript';
94
95 export type TextModeType = 'normal' | 'token' | 'segmented';
96
97 export type TextMark = {end: null | number; id: string; start: null | number};
98
99 export type TextMarks = Array<TextMark>;
100
101 function getElementOuterTag(node: TextNode, format: number): string | null {
102   if (format & IS_CODE) {
103     return 'code';
104   }
105   if (format & IS_HIGHLIGHT) {
106     return 'mark';
107   }
108   if (format & IS_SUBSCRIPT) {
109     return 'sub';
110   }
111   if (format & IS_SUPERSCRIPT) {
112     return 'sup';
113   }
114   return null;
115 }
116
117 function getElementInnerTag(node: TextNode, format: number): string {
118   if (format & IS_BOLD) {
119     return 'strong';
120   }
121   if (format & IS_ITALIC) {
122     return 'em';
123   }
124   return 'span';
125 }
126
127 function setTextThemeClassNames(
128   tag: string,
129   prevFormat: number,
130   nextFormat: number,
131   dom: HTMLElement,
132   textClassNames: TextNodeThemeClasses,
133 ): void {
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);
139   }
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(
146     textClassNames,
147     'underlineStrikethrough',
148   );
149   let hasUnderlineStrikethrough = false;
150   const prevUnderlineStrikethrough =
151     prevFormat & IS_UNDERLINE && prevFormat & IS_STRIKETHROUGH;
152   const nextUnderlineStrikethrough =
153     nextFormat & IS_UNDERLINE && nextFormat & IS_STRIKETHROUGH;
154
155   if (classNames !== undefined) {
156     if (nextUnderlineStrikethrough) {
157       hasUnderlineStrikethrough = true;
158       if (!prevUnderlineStrikethrough) {
159         domClassList.add(...classNames);
160       }
161     } else if (prevUnderlineStrikethrough) {
162       domClassList.remove(...classNames);
163     }
164   }
165
166   for (const key in TEXT_TYPE_TO_FORMAT) {
167     const format = key;
168     const flag = TEXT_TYPE_TO_FORMAT[format];
169     classNames = getCachedClassNameArray(textClassNames, key);
170     if (classNames !== undefined) {
171       if (nextFormat & flag) {
172         if (
173           hasUnderlineStrikethrough &&
174           (key === 'underline' || key === 'strikethrough')
175         ) {
176           if (prevFormat & flag) {
177             domClassList.remove(...classNames);
178           }
179           continue;
180         }
181         if (
182           (prevFormat & flag) === 0 ||
183           (prevUnderlineStrikethrough && key === 'underline') ||
184           key === 'strikethrough'
185         ) {
186           domClassList.add(...classNames);
187         }
188       } else if (prevFormat & flag) {
189         domClassList.remove(...classNames);
190       }
191     }
192   }
193 }
194
195 function diffComposedText(a: string, b: string): [number, number, string] {
196   const aLength = a.length;
197   const bLength = b.length;
198   let left = 0;
199   let right = 0;
200
201   while (left < aLength && left < bLength && a[left] === b[left]) {
202     left++;
203   }
204   while (
205     right + left < aLength &&
206     right + left < bLength &&
207     a[aLength - right - 1] === b[bLength - right - 1]
208   ) {
209     right++;
210   }
211
212   return [left, aLength - left - right, b.slice(left, bLength - right)];
213 }
214
215 function setTextContent(
216   nextText: string,
217   dom: HTMLElement,
218   node: TextNode,
219 ): void {
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;
225
226   if (firstChild == null) {
227     dom.textContent = text;
228   } else {
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(
235           nodeValue as string,
236           text,
237         );
238         if (remove !== 0) {
239           // @ts-expect-error
240           firstChild.deleteData(index, remove);
241         }
242         // @ts-expect-error
243         firstChild.insertData(index, insert);
244       } else {
245         firstChild.nodeValue = text;
246       }
247     }
248   }
249 }
250
251 function createTextInnerDOM(
252   innerDOM: HTMLElement,
253   node: TextNode,
254   innerTag: string,
255   format: number,
256   text: string,
257   config: EditorConfig,
258 ): void {
259   setTextContent(text, innerDOM, node);
260   const theme = config.theme;
261   // Apply theme class names
262   const textClassNames = theme.text;
263
264   if (textClassNames !== undefined) {
265     setTextThemeClassNames(innerTag, 0, format, innerDOM, textClassNames);
266   }
267 }
268
269 function wrapElementWith(
270   element: HTMLElement | Text,
271   tag: string,
272 ): HTMLElement {
273   const el = document.createElement(tag);
274   el.appendChild(element);
275   return el;
276 }
277
278 // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
279 export interface TextNode {
280   getTopLevelElement(): ElementNode | null;
281   getTopLevelElementOrThrow(): ElementNode;
282 }
283
284 /** @noInheritDoc */
285 // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
286 export class TextNode extends LexicalNode {
287   ['constructor']!: KlassConstructor<typeof TextNode>;
288   __text: string;
289   /** @internal */
290   __format: number;
291   /** @internal */
292   __style: string;
293   /** @internal */
294   __mode: 0 | 1 | 2 | 3;
295   /** @internal */
296   __detail: number;
297
298   static getType(): string {
299     return 'text';
300   }
301
302   static clone(node: TextNode): TextNode {
303     return new TextNode(node.__text, node.__key);
304   }
305
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;
312   }
313
314   constructor(text: string, key?: NodeKey) {
315     super(key);
316     this.__text = text;
317     this.__format = 0;
318     this.__style = '';
319     this.__mode = 0;
320     this.__detail = 0;
321   }
322
323   /**
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.
326    *
327    * @returns a number representing the format of the text node.
328    */
329   getFormat(): number {
330     const self = this.getLatest();
331     return self.__format;
332   }
333
334   /**
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.
338    *
339    * @returns a number representing the detail of the text node.
340    */
341   getDetail(): number {
342     const self = this.getLatest();
343     return self.__detail;
344   }
345
346   /**
347    * Returns the mode (TextModeType) of the TextNode, which may be "normal", "token", or "segmented"
348    *
349    * @returns TextModeType.
350    */
351   getMode(): TextModeType {
352     const self = this.getLatest();
353     return TEXT_TYPE_TO_MODE[self.__mode];
354   }
355
356   /**
357    * Returns the styles currently applied to the node. This is analogous to CSSText in the DOM.
358    *
359    * @returns CSSText-like string of styles applied to the underlying DOM node.
360    */
361   getStyle(): string {
362     const self = this.getLatest();
363     return self.__style;
364   }
365
366   /**
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).
369    *
370    * @returns true if the node is in token mode, false otherwise.
371    */
372   isToken(): boolean {
373     const self = this.getLatest();
374     return self.__mode === IS_TOKEN;
375   }
376
377   /**
378    *
379    * @returns true if Lexical detects that an IME or other 3rd-party script is attempting to
380    * mutate the TextNode, false otherwise.
381    */
382   isComposing(): boolean {
383     return this.__key === $getCompositionKey();
384   }
385
386   /**
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".
389    *
390    * @returns true if the node is in segmented mode, false otherwise.
391    */
392   isSegmented(): boolean {
393     const self = this.getLatest();
394     return self.__mode === IS_SEGMENTED;
395   }
396   /**
397    * Returns whether or not the node is "directionless". Directionless nodes don't respect changes between RTL and LTR modes.
398    *
399    * @returns true if the node is directionless, false otherwise.
400    */
401   isDirectionless(): boolean {
402     const self = this.getLatest();
403     return (self.__detail & IS_DIRECTIONLESS) !== 0;
404   }
405   /**
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.
408    *
409    * @returns true if the node is unmergeable, false otherwise.
410    */
411   isUnmergeable(): boolean {
412     const self = this.getLatest();
413     return (self.__detail & IS_UNMERGEABLE) !== 0;
414   }
415
416   /**
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.
419    *
420    * @param type - the TextFormatType to check for.
421    *
422    * @returns true if the node has the provided format, false otherwise.
423    */
424   hasFormat(type: TextFormatType): boolean {
425     const formatFlag = TEXT_TYPE_TO_FORMAT[type];
426     return (this.getFormat() & formatFlag) !== 0;
427   }
428
429   /**
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).
432    *
433    * @returns true if the node is simple text, false otherwise.
434    */
435   isSimpleText(): boolean {
436     return this.__type === 'text' && this.__mode === 0;
437   }
438
439   /**
440    * Returns the text content of the node as a string.
441    *
442    * @returns a string representing the text content of the node.
443    */
444   getTextContent(): string {
445     const self = this.getLatest();
446     return self.__text;
447   }
448
449   /**
450    * Returns the format flags applied to the node as a 32-bit integer.
451    *
452    * @returns a number representing the TextFormatTypes applied to the node.
453    */
454   getFormatFlags(type: TextFormatType, alignWithFormat: null | number): number {
455     const self = this.getLatest();
456     const format = self.__format;
457     return toggleTextFormatType(format, type, alignWithFormat);
458   }
459
460   /**
461    *
462    * @returns true if the text node supports font styling, false otherwise.
463    */
464   canHaveFormat(): boolean {
465     return true;
466   }
467
468   // View
469
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);
476     let innerDOM = dom;
477     if (this.hasFormat('code')) {
478       dom.setAttribute('spellcheck', 'false');
479     }
480     if (outerTag !== null) {
481       innerDOM = document.createElement(innerTag);
482       dom.appendChild(innerDOM);
483     }
484     const text = this.__text;
485     createTextInnerDOM(innerDOM, this, innerTag, format, text, config);
486     const style = this.__style;
487     if (style !== '') {
488       dom.style.cssText = style;
489     }
490     return dom;
491   }
492
493   updateDOM(
494     prevNode: TextNode,
495     dom: HTMLElement,
496     config: EditorConfig,
497   ): boolean {
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;
507
508     if (prevTag !== nextTag) {
509       return true;
510     }
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');
516       }
517       const nextInnerDOM = document.createElement(nextInnerTag);
518       createTextInnerDOM(
519         nextInnerDOM,
520         this,
521         nextInnerTag,
522         nextFormat,
523         nextText,
524         config,
525       );
526       dom.replaceChild(nextInnerDOM, prevInnerDOM);
527       return false;
528     }
529     let innerDOM = dom;
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');
535         }
536       }
537     }
538     setTextContent(nextText, innerDOM, this);
539     const theme = config.theme;
540     // Apply theme class names
541     const textClassNames = theme.text;
542
543     if (textClassNames !== undefined && prevFormat !== nextFormat) {
544       setTextThemeClassNames(
545         nextInnerTag,
546         prevFormat,
547         nextFormat,
548         innerDOM,
549         textClassNames,
550       );
551     }
552     const prevStyle = prevNode.__style;
553     const nextStyle = this.__style;
554     if (prevStyle !== nextStyle) {
555       dom.style.cssText = nextStyle;
556     }
557     return false;
558   }
559
560   static importDOM(): DOMConversionMap | null {
561     return {
562       '#text': () => ({
563         conversion: $convertTextDOMNode,
564         priority: 0,
565       }),
566       b: () => ({
567         conversion: convertBringAttentionToElement,
568         priority: 0,
569       }),
570       code: () => ({
571         conversion: convertTextFormatElement,
572         priority: 0,
573       }),
574       em: () => ({
575         conversion: convertTextFormatElement,
576         priority: 0,
577       }),
578       i: () => ({
579         conversion: convertTextFormatElement,
580         priority: 0,
581       }),
582       s: () => ({
583         conversion: convertTextFormatElement,
584         priority: 0,
585       }),
586       span: () => ({
587         conversion: convertSpanElement,
588         priority: 0,
589       }),
590       strong: () => ({
591         conversion: convertTextFormatElement,
592         priority: 0,
593       }),
594       sub: () => ({
595         conversion: convertTextFormatElement,
596         priority: 0,
597       }),
598       sup: () => ({
599         conversion: convertTextFormatElement,
600         priority: 0,
601       }),
602       u: () => ({
603         conversion: convertTextFormatElement,
604         priority: 0,
605       }),
606     };
607   }
608
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);
615     return node;
616   }
617
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);
623     invariant(
624       element !== null && isHTMLElement(element),
625       'Expected TextNode createDOM to always return a HTMLElement',
626     );
627
628     // Wrap up to retain space if head/tail whitespace exists
629     const text = this.getTextContent();
630     if (/^\s|\s$/.test(text)) {
631       element.style.whiteSpace = 'pre-wrap';
632     }
633
634     // Strip editor theme classes
635     for (const className of Array.from(element.classList.values())) {
636       if (className.startsWith('editor-theme-')) {
637         element.classList.remove(className);
638       }
639     }
640     if (element.classList.length === 0) {
641       element.removeAttribute('class');
642     }
643
644     // Remove placeholder tag if redundant
645     if (element.nodeName === 'SPAN' && !element.getAttribute('style')) {
646       element = document.createTextNode(text);
647     }
648
649     // This is the only way to properly add support for most clients,
650     // even if it's semantically incorrect to have to resort to using
651     // <b>, <u>, <s>, <i> elements.
652     if (this.hasFormat('bold')) {
653       element = wrapElementWith(element, 'b');
654     }
655     if (this.hasFormat('italic')) {
656       element = wrapElementWith(element, 'em');
657     }
658     if (this.hasFormat('strikethrough')) {
659       element = wrapElementWith(element, 's');
660     }
661     if (this.hasFormat('underline')) {
662       element = wrapElementWith(element, 'u');
663     }
664
665     return {
666       element,
667     };
668   }
669
670   exportJSON(): SerializedTextNode {
671     return {
672       detail: this.getDetail(),
673       format: this.getFormat(),
674       mode: this.getMode(),
675       style: this.getStyle(),
676       text: this.getTextContent(),
677       type: 'text',
678       version: 1,
679     };
680   }
681
682   // Mutators
683   selectionTransform(
684     prevSelection: null | BaseSelection,
685     nextSelection: RangeSelection,
686   ): void {
687     return;
688   }
689
690   /**
691    * Sets the node format to the provided TextFormatType or 32-bit integer. Note that the TextFormatType
692    * version of the argument can only specify one format and doing so will remove all other formats that
693    * may be applied to the node. For toggling behavior, consider using {@link TextNode.toggleFormat}
694    *
695    * @param format - TextFormatType or 32-bit integer representing the node format.
696    *
697    * @returns this TextNode.
698    * // TODO 0.12 This should just be a `string`.
699    */
700   setFormat(format: TextFormatType | number): this {
701     const self = this.getWritable();
702     self.__format =
703       typeof format === 'string' ? TEXT_TYPE_TO_FORMAT[format] : format;
704     return self;
705   }
706
707   /**
708    * Sets the node detail to the provided TextDetailType or 32-bit integer. Note that the TextDetailType
709    * version of the argument can only specify one detail value and doing so will remove all other detail values that
710    * may be applied to the node. For toggling behavior, consider using {@link TextNode.toggleDirectionless}
711    * or {@link TextNode.toggleUnmergeable}
712    *
713    * @param detail - TextDetailType or 32-bit integer representing the node detail.
714    *
715    * @returns this TextNode.
716    * // TODO 0.12 This should just be a `string`.
717    */
718   setDetail(detail: TextDetailType | number): this {
719     const self = this.getWritable();
720     self.__detail =
721       typeof detail === 'string' ? DETAIL_TYPE_TO_DETAIL[detail] : detail;
722     return self;
723   }
724
725   /**
726    * Sets the node style to the provided CSSText-like string. Set this property as you
727    * would an HTMLElement style attribute to apply inline styles to the underlying DOM Element.
728    *
729    * @param style - CSSText to be applied to the underlying HTMLElement.
730    *
731    * @returns this TextNode.
732    */
733   setStyle(style: string): this {
734     const self = this.getWritable();
735     self.__style = style;
736     return self;
737   }
738
739   /**
740    * Applies the provided format to this TextNode if it's not present. Removes it if it's present.
741    * The subscript and superscript formats are mutually exclusive.
742    * Prefer using this method to turn specific formats on and off.
743    *
744    * @param type - TextFormatType to toggle.
745    *
746    * @returns this TextNode.
747    */
748   toggleFormat(type: TextFormatType): this {
749     const format = this.getFormat();
750     const newFormat = toggleTextFormatType(format, type, null);
751     return this.setFormat(newFormat);
752   }
753
754   /**
755    * Toggles the directionless detail value of the node. Prefer using this method over setDetail.
756    *
757    * @returns this TextNode.
758    */
759   toggleDirectionless(): this {
760     const self = this.getWritable();
761     self.__detail ^= IS_DIRECTIONLESS;
762     return self;
763   }
764
765   /**
766    * Toggles the unmergeable detail value of the node. Prefer using this method over setDetail.
767    *
768    * @returns this TextNode.
769    */
770   toggleUnmergeable(): this {
771     const self = this.getWritable();
772     self.__detail ^= IS_UNMERGEABLE;
773     return self;
774   }
775
776   /**
777    * Sets the mode of the node.
778    *
779    * @returns this TextNode.
780    */
781   setMode(type: TextModeType): this {
782     const mode = TEXT_MODE_TO_TYPE[type];
783     if (this.__mode === mode) {
784       return this;
785     }
786     const self = this.getWritable();
787     self.__mode = mode;
788     return self;
789   }
790
791   /**
792    * Sets the text content of the node.
793    *
794    * @param text - the string to set as the text value of the node.
795    *
796    * @returns this TextNode.
797    */
798   setTextContent(text: string): this {
799     if (this.__text === text) {
800       return this;
801     }
802     const self = this.getWritable();
803     self.__text = text;
804     return self;
805   }
806
807   /**
808    * Sets the current Lexical selection to be a RangeSelection with anchor and focus on this TextNode at the provided offsets.
809    *
810    * @param _anchorOffset - the offset at which the Selection anchor will be placed.
811    * @param _focusOffset - the offset at which the Selection focus will be placed.
812    *
813    * @returns the new RangeSelection.
814    */
815   select(_anchorOffset?: number, _focusOffset?: number): RangeSelection {
816     errorOnReadOnly();
817     let anchorOffset = _anchorOffset;
818     let focusOffset = _focusOffset;
819     const selection = $getSelection();
820     const text = this.getTextContent();
821     const key = this.__key;
822     if (typeof text === 'string') {
823       const lastOffset = text.length;
824       if (anchorOffset === undefined) {
825         anchorOffset = lastOffset;
826       }
827       if (focusOffset === undefined) {
828         focusOffset = lastOffset;
829       }
830     } else {
831       anchorOffset = 0;
832       focusOffset = 0;
833     }
834     if (!$isRangeSelection(selection)) {
835       return $internalMakeRangeSelection(
836         key,
837         anchorOffset,
838         key,
839         focusOffset,
840         'text',
841         'text',
842       );
843     } else {
844       const compositionKey = $getCompositionKey();
845       if (
846         compositionKey === selection.anchor.key ||
847         compositionKey === selection.focus.key
848       ) {
849         $setCompositionKey(key);
850       }
851       selection.setTextNodeRange(this, anchorOffset, this, focusOffset);
852     }
853     return selection;
854   }
855
856   selectStart(): RangeSelection {
857     return this.select(0, 0);
858   }
859
860   selectEnd(): RangeSelection {
861     const size = this.getTextContentSize();
862     return this.select(size, size);
863   }
864
865   /**
866    * Inserts the provided text into this TextNode at the provided offset, deleting the number of characters
867    * specified. Can optionally calculate a new selection after the operation is complete.
868    *
869    * @param offset - the offset at which the splice operation should begin.
870    * @param delCount - the number of characters to delete, starting from the offset.
871    * @param newText - the text to insert into the TextNode at the offset.
872    * @param moveSelection - optional, whether or not to move selection to the end of the inserted substring.
873    *
874    * @returns this TextNode.
875    */
876   spliceText(
877     offset: number,
878     delCount: number,
879     newText: string,
880     moveSelection?: boolean,
881   ): TextNode {
882     const writableSelf = this.getWritable();
883     const text = writableSelf.__text;
884     const handledTextLength = newText.length;
885     let index = offset;
886     if (index < 0) {
887       index = handledTextLength + index;
888       if (index < 0) {
889         index = 0;
890       }
891     }
892     const selection = $getSelection();
893     if (moveSelection && $isRangeSelection(selection)) {
894       const newOffset = offset + handledTextLength;
895       selection.setTextNodeRange(
896         writableSelf,
897         newOffset,
898         writableSelf,
899         newOffset,
900       );
901     }
902
903     const updatedText =
904       text.slice(0, index) + newText + text.slice(index + delCount);
905
906     writableSelf.__text = updatedText;
907     return writableSelf;
908   }
909
910   /**
911    * This method is meant to be overriden by TextNode subclasses to control the behavior of those nodes
912    * when a user event would cause text to be inserted before them in the editor. If true, Lexical will attempt
913    * to insert text into this node. If false, it will insert the text in a new sibling node.
914    *
915    * @returns true if text can be inserted before the node, false otherwise.
916    */
917   canInsertTextBefore(): boolean {
918     return true;
919   }
920
921   /**
922    * This method is meant to be overriden by TextNode subclasses to control the behavior of those nodes
923    * when a user event would cause text to be inserted after them in the editor. If true, Lexical will attempt
924    * to insert text into this node. If false, it will insert the text in a new sibling node.
925    *
926    * @returns true if text can be inserted after the node, false otherwise.
927    */
928   canInsertTextAfter(): boolean {
929     return true;
930   }
931
932   /**
933    * Splits this TextNode at the provided character offsets, forming new TextNodes from the substrings
934    * formed by the split, and inserting those new TextNodes into the editor, replacing the one that was split.
935    *
936    * @param splitOffsets - rest param of the text content character offsets at which this node should be split.
937    *
938    * @returns an Array containing the newly-created TextNodes.
939    */
940   splitText(...splitOffsets: Array<number>): Array<TextNode> {
941     errorOnReadOnly();
942     const self = this.getLatest();
943     const textContent = self.getTextContent();
944     const key = self.__key;
945     const compositionKey = $getCompositionKey();
946     const offsetsSet = new Set(splitOffsets);
947     const parts = [];
948     const textLength = textContent.length;
949     let string = '';
950     for (let i = 0; i < textLength; i++) {
951       if (string !== '' && offsetsSet.has(i)) {
952         parts.push(string);
953         string = '';
954       }
955       string += textContent[i];
956     }
957     if (string !== '') {
958       parts.push(string);
959     }
960     const partsLength = parts.length;
961     if (partsLength === 0) {
962       return [];
963     } else if (parts[0] === textContent) {
964       return [self];
965     }
966     const firstPart = parts[0];
967     const parent = self.getParent();
968     let writableNode;
969     const format = self.getFormat();
970     const style = self.getStyle();
971     const detail = self.__detail;
972     let hasReplacedSelf = false;
973
974     if (self.isSegmented()) {
975       // Create a new TextNode
976       writableNode = $createTextNode(firstPart);
977       writableNode.__format = format;
978       writableNode.__style = style;
979       writableNode.__detail = detail;
980       hasReplacedSelf = true;
981     } else {
982       // For the first part, update the existing node
983       writableNode = self.getWritable();
984       writableNode.__text = firstPart;
985     }
986
987     // Handle selection
988     const selection = $getSelection();
989
990     // Then handle all other parts
991     const splitNodes: TextNode[] = [writableNode];
992     let textSize = firstPart.length;
993
994     for (let i = 1; i < partsLength; i++) {
995       const part = parts[i];
996       const partSize = part.length;
997       const sibling = $createTextNode(part).getWritable();
998       sibling.__format = format;
999       sibling.__style = style;
1000       sibling.__detail = detail;
1001       const siblingKey = sibling.__key;
1002       const nextTextSize = textSize + partSize;
1003
1004       if ($isRangeSelection(selection)) {
1005         const anchor = selection.anchor;
1006         const focus = selection.focus;
1007
1008         if (
1009           anchor.key === key &&
1010           anchor.type === 'text' &&
1011           anchor.offset > textSize &&
1012           anchor.offset <= nextTextSize
1013         ) {
1014           anchor.key = siblingKey;
1015           anchor.offset -= textSize;
1016           selection.dirty = true;
1017         }
1018         if (
1019           focus.key === key &&
1020           focus.type === 'text' &&
1021           focus.offset > textSize &&
1022           focus.offset <= nextTextSize
1023         ) {
1024           focus.key = siblingKey;
1025           focus.offset -= textSize;
1026           selection.dirty = true;
1027         }
1028       }
1029       if (compositionKey === key) {
1030         $setCompositionKey(siblingKey);
1031       }
1032       textSize = nextTextSize;
1033       splitNodes.push(sibling);
1034     }
1035
1036     // Insert the nodes into the parent's children
1037     if (parent !== null) {
1038       internalMarkSiblingsAsDirty(this);
1039       const writableParent = parent.getWritable();
1040       const insertionIndex = this.getIndexWithinParent();
1041       if (hasReplacedSelf) {
1042         writableParent.splice(insertionIndex, 0, splitNodes);
1043         this.remove();
1044       } else {
1045         writableParent.splice(insertionIndex, 1, splitNodes);
1046       }
1047
1048       if ($isRangeSelection(selection)) {
1049         $updateElementSelectionOnCreateDeleteNode(
1050           selection,
1051           parent,
1052           insertionIndex,
1053           partsLength - 1,
1054         );
1055       }
1056     }
1057
1058     return splitNodes;
1059   }
1060
1061   /**
1062    * Merges the target TextNode into this TextNode, removing the target node.
1063    *
1064    * @param target - the TextNode to merge into this one.
1065    *
1066    * @returns this TextNode.
1067    */
1068   mergeWithSibling(target: TextNode): TextNode {
1069     const isBefore = target === this.getPreviousSibling();
1070     if (!isBefore && target !== this.getNextSibling()) {
1071       invariant(
1072         false,
1073         'mergeWithSibling: sibling must be a previous or next sibling',
1074       );
1075     }
1076     const key = this.__key;
1077     const targetKey = target.__key;
1078     const text = this.__text;
1079     const textLength = text.length;
1080     const compositionKey = $getCompositionKey();
1081
1082     if (compositionKey === targetKey) {
1083       $setCompositionKey(key);
1084     }
1085     const selection = $getSelection();
1086     if ($isRangeSelection(selection)) {
1087       const anchor = selection.anchor;
1088       const focus = selection.focus;
1089       if (anchor !== null && anchor.key === targetKey) {
1090         adjustPointOffsetForMergedSibling(
1091           anchor,
1092           isBefore,
1093           key,
1094           target,
1095           textLength,
1096         );
1097         selection.dirty = true;
1098       }
1099       if (focus !== null && focus.key === targetKey) {
1100         adjustPointOffsetForMergedSibling(
1101           focus,
1102           isBefore,
1103           key,
1104           target,
1105           textLength,
1106         );
1107         selection.dirty = true;
1108       }
1109     }
1110     const targetText = target.__text;
1111     const newText = isBefore ? targetText + text : text + targetText;
1112     this.setTextContent(newText);
1113     const writableSelf = this.getWritable();
1114     target.remove();
1115     return writableSelf;
1116   }
1117
1118   /**
1119    * This method is meant to be overriden by TextNode subclasses to control the behavior of those nodes
1120    * when used with the registerLexicalTextEntity function. If you're using registerLexicalTextEntity, the
1121    * node class that you create and replace matched text with should return true from this method.
1122    *
1123    * @returns true if the node is to be treated as a "text entity", false otherwise.
1124    */
1125   isTextEntity(): boolean {
1126     return false;
1127   }
1128 }
1129
1130 function convertSpanElement(domNode: HTMLSpanElement): DOMConversionOutput {
1131   // domNode is a <span> since we matched it by nodeName
1132   const span = domNode;
1133   const style = span.style;
1134
1135   return {
1136     forChild: applyTextFormatFromStyle(style),
1137     node: null,
1138   };
1139 }
1140
1141 function convertBringAttentionToElement(
1142   domNode: HTMLElement,
1143 ): DOMConversionOutput {
1144   // domNode is a <b> since we matched it by nodeName
1145   const b = domNode;
1146   // Google Docs wraps all copied HTML in a <b> with font-weight normal
1147   const hasNormalFontWeight = b.style.fontWeight === 'normal';
1148
1149   return {
1150     forChild: applyTextFormatFromStyle(
1151       b.style,
1152       hasNormalFontWeight ? undefined : 'bold',
1153     ),
1154     node: null,
1155   };
1156 }
1157
1158 const preParentCache = new WeakMap<Node, null | Node>();
1159
1160 function isNodePre(node: Node): boolean {
1161   return (
1162     node.nodeName === 'PRE' ||
1163     (node.nodeType === DOM_ELEMENT_TYPE &&
1164       (node as HTMLElement).style !== undefined &&
1165       (node as HTMLElement).style.whiteSpace !== undefined &&
1166       (node as HTMLElement).style.whiteSpace.startsWith('pre'))
1167   );
1168 }
1169
1170 export function findParentPreDOMNode(node: Node) {
1171   let cached;
1172   let parent = node.parentNode;
1173   const visited = [node];
1174   while (
1175     parent !== null &&
1176     (cached = preParentCache.get(parent)) === undefined &&
1177     !isNodePre(parent)
1178   ) {
1179     visited.push(parent);
1180     parent = parent.parentNode;
1181   }
1182   const resultNode = cached === undefined ? parent : cached;
1183   for (let i = 0; i < visited.length; i++) {
1184     preParentCache.set(visited[i], resultNode);
1185   }
1186   return resultNode;
1187 }
1188
1189 function $convertTextDOMNode(domNode: Node): DOMConversionOutput {
1190   const domNode_ = domNode as Text;
1191   const parentDom = domNode.parentElement;
1192   invariant(
1193     parentDom !== null,
1194     'Expected parentElement of Text not to be null',
1195   );
1196   let textContent = domNode_.textContent || '';
1197   // No collapse and preserve segment break for pre, pre-wrap and pre-line
1198   if (findParentPreDOMNode(domNode_) !== null) {
1199     const parts = textContent.split(/(\r?\n|\t)/);
1200     const nodes: Array<LexicalNode> = [];
1201     const length = parts.length;
1202     for (let i = 0; i < length; i++) {
1203       const part = parts[i];
1204       if (part === '\n' || part === '\r\n') {
1205         nodes.push($createLineBreakNode());
1206       } else if (part === '\t') {
1207         nodes.push($createTabNode());
1208       } else if (part !== '') {
1209         nodes.push($createTextNode(part));
1210       }
1211     }
1212     return {node: nodes};
1213   }
1214   textContent = textContent.replace(/\r/g, '').replace(/[ \t\n]+/g, ' ');
1215   if (textContent === '') {
1216     return {node: null};
1217   }
1218   if (textContent[0] === ' ') {
1219     // Traverse backward while in the same line. If content contains new line or tab -> pontential
1220     // delete, other elements can borrow from this one. Deletion depends on whether it's also the
1221     // last space (see next condition: textContent[textContent.length - 1] === ' '))
1222     let previousText: null | Text = domNode_;
1223     let isStartOfLine = true;
1224     while (
1225       previousText !== null &&
1226       (previousText = findTextInLine(previousText, false)) !== null
1227     ) {
1228       const previousTextContent = previousText.textContent || '';
1229       if (previousTextContent.length > 0) {
1230         if (/[ \t\n]$/.test(previousTextContent)) {
1231           textContent = textContent.slice(1);
1232         }
1233         isStartOfLine = false;
1234         break;
1235       }
1236     }
1237     if (isStartOfLine) {
1238       textContent = textContent.slice(1);
1239     }
1240   }
1241   if (textContent[textContent.length - 1] === ' ') {
1242     // Traverse forward while in the same line, preserve if next inline will require a space
1243     let nextText: null | Text = domNode_;
1244     let isEndOfLine = true;
1245     while (
1246       nextText !== null &&
1247       (nextText = findTextInLine(nextText, true)) !== null
1248     ) {
1249       const nextTextContent = (nextText.textContent || '').replace(
1250         /^( |\t|\r?\n)+/,
1251         '',
1252       );
1253       if (nextTextContent.length > 0) {
1254         isEndOfLine = false;
1255         break;
1256       }
1257     }
1258     if (isEndOfLine) {
1259       textContent = textContent.slice(0, textContent.length - 1);
1260     }
1261   }
1262   if (textContent === '') {
1263     return {node: null};
1264   }
1265   return {node: $createTextNode(textContent)};
1266 }
1267
1268 function findTextInLine(text: Text, forward: boolean): null | Text {
1269   let node: Node = text;
1270   // eslint-disable-next-line no-constant-condition
1271   while (true) {
1272     let sibling: null | Node;
1273     while (
1274       (sibling = forward ? node.nextSibling : node.previousSibling) === null
1275     ) {
1276       const parentElement = node.parentElement;
1277       if (parentElement === null) {
1278         return null;
1279       }
1280       node = parentElement;
1281     }
1282     node = sibling;
1283     if (node.nodeType === DOM_ELEMENT_TYPE) {
1284       const display = (node as HTMLElement).style.display;
1285       if (
1286         (display === '' && !isInlineDomNode(node)) ||
1287         (display !== '' && !display.startsWith('inline'))
1288       ) {
1289         return null;
1290       }
1291     }
1292     let descendant: null | Node = node;
1293     while ((descendant = forward ? node.firstChild : node.lastChild) !== null) {
1294       node = descendant;
1295     }
1296     if (node.nodeType === DOM_TEXT_TYPE) {
1297       return node as Text;
1298     } else if (node.nodeName === 'BR') {
1299       return null;
1300     }
1301   }
1302 }
1303
1304 const nodeNameToTextFormat: Record<string, TextFormatType> = {
1305   code: 'code',
1306   em: 'italic',
1307   i: 'italic',
1308   s: 'strikethrough',
1309   strong: 'bold',
1310   sub: 'subscript',
1311   sup: 'superscript',
1312   u: 'underline',
1313 };
1314
1315 function convertTextFormatElement(domNode: HTMLElement): DOMConversionOutput {
1316   const format = nodeNameToTextFormat[domNode.nodeName.toLowerCase()];
1317
1318   if (format === 'code' && domNode.closest('pre')) {
1319     return {node: null};
1320   }
1321
1322   if (format === undefined) {
1323     return {node: null};
1324   }
1325   return {
1326     forChild: applyTextFormatFromStyle(domNode.style, format),
1327     node: null,
1328   };
1329 }
1330
1331 export function $createTextNode(text = ''): TextNode {
1332   return $applyNodeReplacement(new TextNode(text));
1333 }
1334
1335 export function $isTextNode(
1336   node: LexicalNode | null | undefined,
1337 ): node is TextNode {
1338   return node instanceof TextNode;
1339 }
1340
1341 function applyTextFormatFromStyle(
1342   style: CSSStyleDeclaration,
1343   shouldApply?: TextFormatType,
1344 ) {
1345   const fontWeight = style.fontWeight;
1346   const textDecoration = style.textDecoration.split(' ');
1347   // Google Docs uses span tags + font-weight for bold text
1348   const hasBoldFontWeight = fontWeight === '700' || fontWeight === 'bold';
1349   // Google Docs uses span tags + text-decoration: line-through for strikethrough text
1350   const hasLinethroughTextDecoration = textDecoration.includes('line-through');
1351   // Google Docs uses span tags + font-style for italic text
1352   const hasItalicFontStyle = style.fontStyle === 'italic';
1353   // Google Docs uses span tags + text-decoration: underline for underline text
1354   const hasUnderlineTextDecoration = textDecoration.includes('underline');
1355   // Google Docs uses span tags + vertical-align to specify subscript and superscript
1356   const verticalAlign = style.verticalAlign;
1357
1358   // Styles to copy to node
1359   const color = style.color;
1360   const backgroundColor = style.backgroundColor;
1361
1362   return (lexicalNode: LexicalNode) => {
1363     if (!$isTextNode(lexicalNode)) {
1364       return lexicalNode;
1365     }
1366     if (hasBoldFontWeight && !lexicalNode.hasFormat('bold')) {
1367       lexicalNode.toggleFormat('bold');
1368     }
1369     if (
1370       hasLinethroughTextDecoration &&
1371       !lexicalNode.hasFormat('strikethrough')
1372     ) {
1373       lexicalNode.toggleFormat('strikethrough');
1374     }
1375     if (hasItalicFontStyle && !lexicalNode.hasFormat('italic')) {
1376       lexicalNode.toggleFormat('italic');
1377     }
1378     if (hasUnderlineTextDecoration && !lexicalNode.hasFormat('underline')) {
1379       lexicalNode.toggleFormat('underline');
1380     }
1381     if (verticalAlign === 'sub' && !lexicalNode.hasFormat('subscript')) {
1382       lexicalNode.toggleFormat('subscript');
1383     }
1384     if (verticalAlign === 'super' && !lexicalNode.hasFormat('superscript')) {
1385       lexicalNode.toggleFormat('superscript');
1386     }
1387
1388     // Apply styles
1389     let style = lexicalNode.getStyle();
1390     if (color) {
1391       style += `color: ${color};`;
1392     }
1393     if (backgroundColor && backgroundColor !== 'transparent') {
1394       style += `background-color: ${backgroundColor};`;
1395     }
1396     if (style) {
1397       lexicalNode.setStyle(style);
1398     }
1399
1400     if (shouldApply && !lexicalNode.hasFormat(shouldApply)) {
1401       lexicalNode.toggleFormat(shouldApply);
1402     }
1403
1404     return lexicalNode;
1405   };
1406 }