]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/lexical/core/nodes/LexicalTextNode.ts
43bef7e83c0a960a6dfb56b742204101411d13d2
[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     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');
633     }
634     if (this.hasFormat('italic')) {
635       element = wrapElementWith(element, 'i');
636     }
637     if (this.hasFormat('strikethrough')) {
638       element = wrapElementWith(element, 's');
639     }
640     if (this.hasFormat('underline')) {
641       element = wrapElementWith(element, 'u');
642     }
643
644     return {
645       element,
646     };
647   }
648
649   exportJSON(): SerializedTextNode {
650     return {
651       detail: this.getDetail(),
652       format: this.getFormat(),
653       mode: this.getMode(),
654       style: this.getStyle(),
655       text: this.getTextContent(),
656       type: 'text',
657       version: 1,
658     };
659   }
660
661   // Mutators
662   selectionTransform(
663     prevSelection: null | BaseSelection,
664     nextSelection: RangeSelection,
665   ): void {
666     return;
667   }
668
669   /**
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}
673    *
674    * @param format - TextFormatType or 32-bit integer representing the node format.
675    *
676    * @returns this TextNode.
677    * // TODO 0.12 This should just be a `string`.
678    */
679   setFormat(format: TextFormatType | number): this {
680     const self = this.getWritable();
681     self.__format =
682       typeof format === 'string' ? TEXT_TYPE_TO_FORMAT[format] : format;
683     return self;
684   }
685
686   /**
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}
691    *
692    * @param detail - TextDetailType or 32-bit integer representing the node detail.
693    *
694    * @returns this TextNode.
695    * // TODO 0.12 This should just be a `string`.
696    */
697   setDetail(detail: TextDetailType | number): this {
698     const self = this.getWritable();
699     self.__detail =
700       typeof detail === 'string' ? DETAIL_TYPE_TO_DETAIL[detail] : detail;
701     return self;
702   }
703
704   /**
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.
707    *
708    * @param style - CSSText to be applied to the underlying HTMLElement.
709    *
710    * @returns this TextNode.
711    */
712   setStyle(style: string): this {
713     const self = this.getWritable();
714     self.__style = style;
715     return self;
716   }
717
718   /**
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.
722    *
723    * @param type - TextFormatType to toggle.
724    *
725    * @returns this TextNode.
726    */
727   toggleFormat(type: TextFormatType): this {
728     const format = this.getFormat();
729     const newFormat = toggleTextFormatType(format, type, null);
730     return this.setFormat(newFormat);
731   }
732
733   /**
734    * Toggles the directionless detail value of the node. Prefer using this method over setDetail.
735    *
736    * @returns this TextNode.
737    */
738   toggleDirectionless(): this {
739     const self = this.getWritable();
740     self.__detail ^= IS_DIRECTIONLESS;
741     return self;
742   }
743
744   /**
745    * Toggles the unmergeable detail value of the node. Prefer using this method over setDetail.
746    *
747    * @returns this TextNode.
748    */
749   toggleUnmergeable(): this {
750     const self = this.getWritable();
751     self.__detail ^= IS_UNMERGEABLE;
752     return self;
753   }
754
755   /**
756    * Sets the mode of the node.
757    *
758    * @returns this TextNode.
759    */
760   setMode(type: TextModeType): this {
761     const mode = TEXT_MODE_TO_TYPE[type];
762     if (this.__mode === mode) {
763       return this;
764     }
765     const self = this.getWritable();
766     self.__mode = mode;
767     return self;
768   }
769
770   /**
771    * Sets the text content of the node.
772    *
773    * @param text - the string to set as the text value of the node.
774    *
775    * @returns this TextNode.
776    */
777   setTextContent(text: string): this {
778     if (this.__text === text) {
779       return this;
780     }
781     const self = this.getWritable();
782     self.__text = text;
783     return self;
784   }
785
786   /**
787    * Sets the current Lexical selection to be a RangeSelection with anchor and focus on this TextNode at the provided offsets.
788    *
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.
791    *
792    * @returns the new RangeSelection.
793    */
794   select(_anchorOffset?: number, _focusOffset?: number): RangeSelection {
795     errorOnReadOnly();
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;
805       }
806       if (focusOffset === undefined) {
807         focusOffset = lastOffset;
808       }
809     } else {
810       anchorOffset = 0;
811       focusOffset = 0;
812     }
813     if (!$isRangeSelection(selection)) {
814       return $internalMakeRangeSelection(
815         key,
816         anchorOffset,
817         key,
818         focusOffset,
819         'text',
820         'text',
821       );
822     } else {
823       const compositionKey = $getCompositionKey();
824       if (
825         compositionKey === selection.anchor.key ||
826         compositionKey === selection.focus.key
827       ) {
828         $setCompositionKey(key);
829       }
830       selection.setTextNodeRange(this, anchorOffset, this, focusOffset);
831     }
832     return selection;
833   }
834
835   selectStart(): RangeSelection {
836     return this.select(0, 0);
837   }
838
839   selectEnd(): RangeSelection {
840     const size = this.getTextContentSize();
841     return this.select(size, size);
842   }
843
844   /**
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.
847    *
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.
852    *
853    * @returns this TextNode.
854    */
855   spliceText(
856     offset: number,
857     delCount: number,
858     newText: string,
859     moveSelection?: boolean,
860   ): TextNode {
861     const writableSelf = this.getWritable();
862     const text = writableSelf.__text;
863     const handledTextLength = newText.length;
864     let index = offset;
865     if (index < 0) {
866       index = handledTextLength + index;
867       if (index < 0) {
868         index = 0;
869       }
870     }
871     const selection = $getSelection();
872     if (moveSelection && $isRangeSelection(selection)) {
873       const newOffset = offset + handledTextLength;
874       selection.setTextNodeRange(
875         writableSelf,
876         newOffset,
877         writableSelf,
878         newOffset,
879       );
880     }
881
882     const updatedText =
883       text.slice(0, index) + newText + text.slice(index + delCount);
884
885     writableSelf.__text = updatedText;
886     return writableSelf;
887   }
888
889   /**
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.
893    *
894    * @returns true if text can be inserted before the node, false otherwise.
895    */
896   canInsertTextBefore(): boolean {
897     return true;
898   }
899
900   /**
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.
904    *
905    * @returns true if text can be inserted after the node, false otherwise.
906    */
907   canInsertTextAfter(): boolean {
908     return true;
909   }
910
911   /**
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.
914    *
915    * @param splitOffsets - rest param of the text content character offsets at which this node should be split.
916    *
917    * @returns an Array containing the newly-created TextNodes.
918    */
919   splitText(...splitOffsets: Array<number>): Array<TextNode> {
920     errorOnReadOnly();
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);
926     const parts = [];
927     const textLength = textContent.length;
928     let string = '';
929     for (let i = 0; i < textLength; i++) {
930       if (string !== '' && offsetsSet.has(i)) {
931         parts.push(string);
932         string = '';
933       }
934       string += textContent[i];
935     }
936     if (string !== '') {
937       parts.push(string);
938     }
939     const partsLength = parts.length;
940     if (partsLength === 0) {
941       return [];
942     } else if (parts[0] === textContent) {
943       return [self];
944     }
945     const firstPart = parts[0];
946     const parent = self.getParent();
947     let writableNode;
948     const format = self.getFormat();
949     const style = self.getStyle();
950     const detail = self.__detail;
951     let hasReplacedSelf = false;
952
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;
960     } else {
961       // For the first part, update the existing node
962       writableNode = self.getWritable();
963       writableNode.__text = firstPart;
964     }
965
966     // Handle selection
967     const selection = $getSelection();
968
969     // Then handle all other parts
970     const splitNodes: TextNode[] = [writableNode];
971     let textSize = firstPart.length;
972
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;
982
983       if ($isRangeSelection(selection)) {
984         const anchor = selection.anchor;
985         const focus = selection.focus;
986
987         if (
988           anchor.key === key &&
989           anchor.type === 'text' &&
990           anchor.offset > textSize &&
991           anchor.offset <= nextTextSize
992         ) {
993           anchor.key = siblingKey;
994           anchor.offset -= textSize;
995           selection.dirty = true;
996         }
997         if (
998           focus.key === key &&
999           focus.type === 'text' &&
1000           focus.offset > textSize &&
1001           focus.offset <= nextTextSize
1002         ) {
1003           focus.key = siblingKey;
1004           focus.offset -= textSize;
1005           selection.dirty = true;
1006         }
1007       }
1008       if (compositionKey === key) {
1009         $setCompositionKey(siblingKey);
1010       }
1011       textSize = nextTextSize;
1012       splitNodes.push(sibling);
1013     }
1014
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);
1022         this.remove();
1023       } else {
1024         writableParent.splice(insertionIndex, 1, splitNodes);
1025       }
1026
1027       if ($isRangeSelection(selection)) {
1028         $updateElementSelectionOnCreateDeleteNode(
1029           selection,
1030           parent,
1031           insertionIndex,
1032           partsLength - 1,
1033         );
1034       }
1035     }
1036
1037     return splitNodes;
1038   }
1039
1040   /**
1041    * Merges the target TextNode into this TextNode, removing the target node.
1042    *
1043    * @param target - the TextNode to merge into this one.
1044    *
1045    * @returns this TextNode.
1046    */
1047   mergeWithSibling(target: TextNode): TextNode {
1048     const isBefore = target === this.getPreviousSibling();
1049     if (!isBefore && target !== this.getNextSibling()) {
1050       invariant(
1051         false,
1052         'mergeWithSibling: sibling must be a previous or next sibling',
1053       );
1054     }
1055     const key = this.__key;
1056     const targetKey = target.__key;
1057     const text = this.__text;
1058     const textLength = text.length;
1059     const compositionKey = $getCompositionKey();
1060
1061     if (compositionKey === targetKey) {
1062       $setCompositionKey(key);
1063     }
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(
1070           anchor,
1071           isBefore,
1072           key,
1073           target,
1074           textLength,
1075         );
1076         selection.dirty = true;
1077       }
1078       if (focus !== null && focus.key === targetKey) {
1079         adjustPointOffsetForMergedSibling(
1080           focus,
1081           isBefore,
1082           key,
1083           target,
1084           textLength,
1085         );
1086         selection.dirty = true;
1087       }
1088     }
1089     const targetText = target.__text;
1090     const newText = isBefore ? targetText + text : text + targetText;
1091     this.setTextContent(newText);
1092     const writableSelf = this.getWritable();
1093     target.remove();
1094     return writableSelf;
1095   }
1096
1097   /**
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.
1101    *
1102    * @returns true if the node is to be treated as a "text entity", false otherwise.
1103    */
1104   isTextEntity(): boolean {
1105     return false;
1106   }
1107 }
1108
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;
1113
1114   return {
1115     forChild: applyTextFormatFromStyle(style),
1116     node: null,
1117   };
1118 }
1119
1120 function convertBringAttentionToElement(
1121   domNode: HTMLElement,
1122 ): DOMConversionOutput {
1123   // domNode is a <b> since we matched it by nodeName
1124   const b = domNode;
1125   // Google Docs wraps all copied HTML in a <b> with font-weight normal
1126   const hasNormalFontWeight = b.style.fontWeight === 'normal';
1127
1128   return {
1129     forChild: applyTextFormatFromStyle(
1130       b.style,
1131       hasNormalFontWeight ? undefined : 'bold',
1132     ),
1133     node: null,
1134   };
1135 }
1136
1137 const preParentCache = new WeakMap<Node, null | Node>();
1138
1139 function isNodePre(node: Node): boolean {
1140   return (
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'))
1146   );
1147 }
1148
1149 export function findParentPreDOMNode(node: Node) {
1150   let cached;
1151   let parent = node.parentNode;
1152   const visited = [node];
1153   while (
1154     parent !== null &&
1155     (cached = preParentCache.get(parent)) === undefined &&
1156     !isNodePre(parent)
1157   ) {
1158     visited.push(parent);
1159     parent = parent.parentNode;
1160   }
1161   const resultNode = cached === undefined ? parent : cached;
1162   for (let i = 0; i < visited.length; i++) {
1163     preParentCache.set(visited[i], resultNode);
1164   }
1165   return resultNode;
1166 }
1167
1168 function $convertTextDOMNode(domNode: Node): DOMConversionOutput {
1169   const domNode_ = domNode as Text;
1170   const parentDom = domNode.parentElement;
1171   invariant(
1172     parentDom !== null,
1173     'Expected parentElement of Text not to be null',
1174   );
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));
1189       }
1190     }
1191     return {node: nodes};
1192   }
1193   textContent = textContent.replace(/\r/g, '').replace(/[ \t\n]+/g, ' ');
1194   if (textContent === '') {
1195     return {node: null};
1196   }
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;
1203     while (
1204       previousText !== null &&
1205       (previousText = findTextInLine(previousText, false)) !== null
1206     ) {
1207       const previousTextContent = previousText.textContent || '';
1208       if (previousTextContent.length > 0) {
1209         if (/[ \t\n]$/.test(previousTextContent)) {
1210           textContent = textContent.slice(1);
1211         }
1212         isStartOfLine = false;
1213         break;
1214       }
1215     }
1216     if (isStartOfLine) {
1217       textContent = textContent.slice(1);
1218     }
1219   }
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;
1224     while (
1225       nextText !== null &&
1226       (nextText = findTextInLine(nextText, true)) !== null
1227     ) {
1228       const nextTextContent = (nextText.textContent || '').replace(
1229         /^( |\t|\r?\n)+/,
1230         '',
1231       );
1232       if (nextTextContent.length > 0) {
1233         isEndOfLine = false;
1234         break;
1235       }
1236     }
1237     if (isEndOfLine) {
1238       textContent = textContent.slice(0, textContent.length - 1);
1239     }
1240   }
1241   if (textContent === '') {
1242     return {node: null};
1243   }
1244   return {node: $createTextNode(textContent)};
1245 }
1246
1247 function findTextInLine(text: Text, forward: boolean): null | Text {
1248   let node: Node = text;
1249   // eslint-disable-next-line no-constant-condition
1250   while (true) {
1251     let sibling: null | Node;
1252     while (
1253       (sibling = forward ? node.nextSibling : node.previousSibling) === null
1254     ) {
1255       const parentElement = node.parentElement;
1256       if (parentElement === null) {
1257         return null;
1258       }
1259       node = parentElement;
1260     }
1261     node = sibling;
1262     if (node.nodeType === DOM_ELEMENT_TYPE) {
1263       const display = (node as HTMLElement).style.display;
1264       if (
1265         (display === '' && !isInlineDomNode(node)) ||
1266         (display !== '' && !display.startsWith('inline'))
1267       ) {
1268         return null;
1269       }
1270     }
1271     let descendant: null | Node = node;
1272     while ((descendant = forward ? node.firstChild : node.lastChild) !== null) {
1273       node = descendant;
1274     }
1275     if (node.nodeType === DOM_TEXT_TYPE) {
1276       return node as Text;
1277     } else if (node.nodeName === 'BR') {
1278       return null;
1279     }
1280   }
1281 }
1282
1283 const nodeNameToTextFormat: Record<string, TextFormatType> = {
1284   code: 'code',
1285   em: 'italic',
1286   i: 'italic',
1287   s: 'strikethrough',
1288   strong: 'bold',
1289   sub: 'subscript',
1290   sup: 'superscript',
1291   u: 'underline',
1292 };
1293
1294 function convertTextFormatElement(domNode: HTMLElement): DOMConversionOutput {
1295   const format = nodeNameToTextFormat[domNode.nodeName.toLowerCase()];
1296   if (format === undefined) {
1297     return {node: null};
1298   }
1299   return {
1300     forChild: applyTextFormatFromStyle(domNode.style, format),
1301     node: null,
1302   };
1303 }
1304
1305 export function $createTextNode(text = ''): TextNode {
1306   return $applyNodeReplacement(new TextNode(text));
1307 }
1308
1309 export function $isTextNode(
1310   node: LexicalNode | null | undefined,
1311 ): node is TextNode {
1312   return node instanceof TextNode;
1313 }
1314
1315 function applyTextFormatFromStyle(
1316   style: CSSStyleDeclaration,
1317   shouldApply?: TextFormatType,
1318 ) {
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;
1331
1332   return (lexicalNode: LexicalNode) => {
1333     if (!$isTextNode(lexicalNode)) {
1334       return lexicalNode;
1335     }
1336     if (hasBoldFontWeight && !lexicalNode.hasFormat('bold')) {
1337       lexicalNode.toggleFormat('bold');
1338     }
1339     if (
1340       hasLinethroughTextDecoration &&
1341       !lexicalNode.hasFormat('strikethrough')
1342     ) {
1343       lexicalNode.toggleFormat('strikethrough');
1344     }
1345     if (hasItalicFontStyle && !lexicalNode.hasFormat('italic')) {
1346       lexicalNode.toggleFormat('italic');
1347     }
1348     if (hasUnderlineTextDecoration && !lexicalNode.hasFormat('underline')) {
1349       lexicalNode.toggleFormat('underline');
1350     }
1351     if (verticalAlign === 'sub' && !lexicalNode.hasFormat('subscript')) {
1352       lexicalNode.toggleFormat('subscript');
1353     }
1354     if (verticalAlign === 'super' && !lexicalNode.hasFormat('superscript')) {
1355       lexicalNode.toggleFormat('superscript');
1356     }
1357
1358     if (shouldApply && !lexicalNode.hasFormat(shouldApply)) {
1359       lexicalNode.toggleFormat(shouldApply);
1360     }
1361
1362     return lexicalNode;
1363   };
1364 }