-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathLexicalTextNode.ts
1406 lines (1301 loc) · 40.2 KB
/
LexicalTextNode.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import type {
EditorConfig,
KlassConstructor,
LexicalEditor,
Spread,
TextNodeThemeClasses,
} from '../LexicalEditor';
import type {
DOMConversionMap,
DOMConversionOutput,
DOMExportOutput,
NodeKey,
SerializedLexicalNode,
} from '../LexicalNode';
import type {BaseSelection, RangeSelection} from '../LexicalSelection';
import type {ElementNode} from './LexicalElementNode';
import {IS_FIREFOX} from 'lexical/shared/environment';
import invariant from 'lexical/shared/invariant';
import {
COMPOSITION_SUFFIX,
DETAIL_TYPE_TO_DETAIL,
DOM_ELEMENT_TYPE,
DOM_TEXT_TYPE,
IS_BOLD,
IS_CODE,
IS_DIRECTIONLESS,
IS_HIGHLIGHT,
IS_ITALIC,
IS_SEGMENTED,
IS_STRIKETHROUGH,
IS_SUBSCRIPT,
IS_SUPERSCRIPT,
IS_TOKEN,
IS_UNDERLINE,
IS_UNMERGEABLE,
TEXT_MODE_TO_TYPE,
TEXT_TYPE_TO_FORMAT,
TEXT_TYPE_TO_MODE,
} from '../LexicalConstants';
import {LexicalNode} from '../LexicalNode';
import {
$getSelection,
$internalMakeRangeSelection,
$isRangeSelection,
$updateElementSelectionOnCreateDeleteNode,
adjustPointOffsetForMergedSibling,
} from '../LexicalSelection';
import {errorOnReadOnly} from '../LexicalUpdates';
import {
$applyNodeReplacement,
$getCompositionKey,
$setCompositionKey,
getCachedClassNameArray,
internalMarkSiblingsAsDirty,
isHTMLElement,
isInlineDomNode,
toggleTextFormatType,
} from '../LexicalUtils';
import {$createLineBreakNode} from './LexicalLineBreakNode';
import {$createTabNode} from './LexicalTabNode';
export type SerializedTextNode = Spread<
{
detail: number;
format: number;
mode: TextModeType;
style: string;
text: string;
},
SerializedLexicalNode
>;
export type TextDetailType = 'directionless' | 'unmergable';
export type TextFormatType =
| 'bold'
| 'underline'
| 'strikethrough'
| 'italic'
| 'highlight'
| 'code'
| 'subscript'
| 'superscript';
export type TextModeType = 'normal' | 'token' | 'segmented';
export type TextMark = {end: null | number; id: string; start: null | number};
export type TextMarks = Array<TextMark>;
function getElementOuterTag(node: TextNode, format: number): string | null {
if (format & IS_CODE) {
return 'code';
}
if (format & IS_HIGHLIGHT) {
return 'mark';
}
if (format & IS_SUBSCRIPT) {
return 'sub';
}
if (format & IS_SUPERSCRIPT) {
return 'sup';
}
return null;
}
function getElementInnerTag(node: TextNode, format: number): string {
if (format & IS_BOLD) {
return 'strong';
}
if (format & IS_ITALIC) {
return 'em';
}
return 'span';
}
function setTextThemeClassNames(
tag: string,
prevFormat: number,
nextFormat: number,
dom: HTMLElement,
textClassNames: TextNodeThemeClasses,
): void {
const domClassList = dom.classList;
// Firstly we handle the base theme.
let classNames = getCachedClassNameArray(textClassNames, 'base');
if (classNames !== undefined) {
domClassList.add(...classNames);
}
// Secondly we handle the special case: underline + strikethrough.
// We have to do this as we need a way to compose the fact that
// the same CSS property will need to be used: text-decoration.
// In an ideal world we shouldn't have to do this, but there's no
// easy workaround for many atomic CSS systems today.
classNames = getCachedClassNameArray(
textClassNames,
'underlineStrikethrough',
);
let hasUnderlineStrikethrough = false;
const prevUnderlineStrikethrough =
prevFormat & IS_UNDERLINE && prevFormat & IS_STRIKETHROUGH;
const nextUnderlineStrikethrough =
nextFormat & IS_UNDERLINE && nextFormat & IS_STRIKETHROUGH;
if (classNames !== undefined) {
if (nextUnderlineStrikethrough) {
hasUnderlineStrikethrough = true;
if (!prevUnderlineStrikethrough) {
domClassList.add(...classNames);
}
} else if (prevUnderlineStrikethrough) {
domClassList.remove(...classNames);
}
}
for (const key in TEXT_TYPE_TO_FORMAT) {
const format = key;
const flag = TEXT_TYPE_TO_FORMAT[format];
classNames = getCachedClassNameArray(textClassNames, key);
if (classNames !== undefined) {
if (nextFormat & flag) {
if (
hasUnderlineStrikethrough &&
(key === 'underline' || key === 'strikethrough')
) {
if (prevFormat & flag) {
domClassList.remove(...classNames);
}
continue;
}
if (
(prevFormat & flag) === 0 ||
(prevUnderlineStrikethrough && key === 'underline') ||
key === 'strikethrough'
) {
domClassList.add(...classNames);
}
} else if (prevFormat & flag) {
domClassList.remove(...classNames);
}
}
}
}
function diffComposedText(a: string, b: string): [number, number, string] {
const aLength = a.length;
const bLength = b.length;
let left = 0;
let right = 0;
while (left < aLength && left < bLength && a[left] === b[left]) {
left++;
}
while (
right + left < aLength &&
right + left < bLength &&
a[aLength - right - 1] === b[bLength - right - 1]
) {
right++;
}
return [left, aLength - left - right, b.slice(left, bLength - right)];
}
function setTextContent(
nextText: string,
dom: HTMLElement,
node: TextNode,
): void {
const firstChild = dom.firstChild;
const isComposing = node.isComposing();
// Always add a suffix if we're composing a node
const suffix = isComposing ? COMPOSITION_SUFFIX : '';
const text: string = nextText + suffix;
if (firstChild == null) {
dom.textContent = text;
} else {
const nodeValue = firstChild.nodeValue;
if (nodeValue !== text) {
if (isComposing || IS_FIREFOX) {
// We also use the diff composed text for general text in FF to avoid
// the spellcheck red line from flickering.
const [index, remove, insert] = diffComposedText(
nodeValue as string,
text,
);
if (remove !== 0) {
// @ts-expect-error
firstChild.deleteData(index, remove);
}
// @ts-expect-error
firstChild.insertData(index, insert);
} else {
firstChild.nodeValue = text;
}
}
}
}
function createTextInnerDOM(
innerDOM: HTMLElement,
node: TextNode,
innerTag: string,
format: number,
text: string,
config: EditorConfig,
): void {
setTextContent(text, innerDOM, node);
const theme = config.theme;
// Apply theme class names
const textClassNames = theme.text;
if (textClassNames !== undefined) {
setTextThemeClassNames(innerTag, 0, format, innerDOM, textClassNames);
}
}
function wrapElementWith(
element: HTMLElement | Text,
tag: string,
): HTMLElement {
const el = document.createElement(tag);
el.appendChild(element);
return el;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
export interface TextNode {
getTopLevelElement(): ElementNode | null;
getTopLevelElementOrThrow(): ElementNode;
}
/** @noInheritDoc */
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
export class TextNode extends LexicalNode {
['constructor']!: KlassConstructor<typeof TextNode>;
__text: string;
/** @internal */
__format: number;
/** @internal */
__style: string;
/** @internal */
__mode: 0 | 1 | 2 | 3;
/** @internal */
__detail: number;
static getType(): string {
return 'text';
}
static clone(node: TextNode): TextNode {
return new TextNode(node.__text, node.__key);
}
afterCloneFrom(prevNode: this): void {
super.afterCloneFrom(prevNode);
this.__format = prevNode.__format;
this.__style = prevNode.__style;
this.__mode = prevNode.__mode;
this.__detail = prevNode.__detail;
}
constructor(text: string, key?: NodeKey) {
super(key);
this.__text = text;
this.__format = 0;
this.__style = '';
this.__mode = 0;
this.__detail = 0;
}
/**
* Returns a 32-bit integer that represents the TextFormatTypes currently applied to the
* TextNode. You probably don't want to use this method directly - consider using TextNode.hasFormat instead.
*
* @returns a number representing the format of the text node.
*/
getFormat(): number {
const self = this.getLatest();
return self.__format;
}
/**
* Returns a 32-bit integer that represents the TextDetailTypes currently applied to the
* TextNode. You probably don't want to use this method directly - consider using TextNode.isDirectionless
* or TextNode.isUnmergeable instead.
*
* @returns a number representing the detail of the text node.
*/
getDetail(): number {
const self = this.getLatest();
return self.__detail;
}
/**
* Returns the mode (TextModeType) of the TextNode, which may be "normal", "token", or "segmented"
*
* @returns TextModeType.
*/
getMode(): TextModeType {
const self = this.getLatest();
return TEXT_TYPE_TO_MODE[self.__mode];
}
/**
* Returns the styles currently applied to the node. This is analogous to CSSText in the DOM.
*
* @returns CSSText-like string of styles applied to the underlying DOM node.
*/
getStyle(): string {
const self = this.getLatest();
return self.__style;
}
/**
* Returns whether or not the node is in "token" mode. TextNodes in token mode can be navigated through character-by-character
* with a RangeSelection, but are deleted as a single entity (not invdividually by character).
*
* @returns true if the node is in token mode, false otherwise.
*/
isToken(): boolean {
const self = this.getLatest();
return self.__mode === IS_TOKEN;
}
/**
*
* @returns true if Lexical detects that an IME or other 3rd-party script is attempting to
* mutate the TextNode, false otherwise.
*/
isComposing(): boolean {
return this.__key === $getCompositionKey();
}
/**
* Returns whether or not the node is in "segemented" mode. TextNodes in segemented mode can be navigated through character-by-character
* with a RangeSelection, but are deleted in space-delimited "segments".
*
* @returns true if the node is in segmented mode, false otherwise.
*/
isSegmented(): boolean {
const self = this.getLatest();
return self.__mode === IS_SEGMENTED;
}
/**
* Returns whether or not the node is "directionless". Directionless nodes don't respect changes between RTL and LTR modes.
*
* @returns true if the node is directionless, false otherwise.
*/
isDirectionless(): boolean {
const self = this.getLatest();
return (self.__detail & IS_DIRECTIONLESS) !== 0;
}
/**
* Returns whether or not the node is unmergeable. In some scenarios, Lexical tries to merge
* adjacent TextNodes into a single TextNode. If a TextNode is unmergeable, this won't happen.
*
* @returns true if the node is unmergeable, false otherwise.
*/
isUnmergeable(): boolean {
const self = this.getLatest();
return (self.__detail & IS_UNMERGEABLE) !== 0;
}
/**
* Returns whether or not the node has the provided format applied. Use this with the human-readable TextFormatType
* string values to get the format of a TextNode.
*
* @param type - the TextFormatType to check for.
*
* @returns true if the node has the provided format, false otherwise.
*/
hasFormat(type: TextFormatType): boolean {
const formatFlag = TEXT_TYPE_TO_FORMAT[type];
return (this.getFormat() & formatFlag) !== 0;
}
/**
* Returns whether or not the node is simple text. Simple text is defined as a TextNode that has the string type "text"
* (i.e., not a subclass) and has no mode applied to it (i.e., not segmented or token).
*
* @returns true if the node is simple text, false otherwise.
*/
isSimpleText(): boolean {
return this.__type === 'text' && this.__mode === 0;
}
/**
* Returns the text content of the node as a string.
*
* @returns a string representing the text content of the node.
*/
getTextContent(): string {
const self = this.getLatest();
return self.__text;
}
/**
* Returns the format flags applied to the node as a 32-bit integer.
*
* @returns a number representing the TextFormatTypes applied to the node.
*/
getFormatFlags(type: TextFormatType, alignWithFormat: null | number): number {
const self = this.getLatest();
const format = self.__format;
return toggleTextFormatType(format, type, alignWithFormat);
}
/**
*
* @returns true if the text node supports font styling, false otherwise.
*/
canHaveFormat(): boolean {
return true;
}
// View
createDOM(config: EditorConfig, editor?: LexicalEditor): HTMLElement {
const format = this.__format;
const outerTag = getElementOuterTag(this, format);
const innerTag = getElementInnerTag(this, format);
const tag = outerTag === null ? innerTag : outerTag;
const dom = document.createElement(tag);
let innerDOM = dom;
if (this.hasFormat('code')) {
dom.setAttribute('spellcheck', 'false');
}
if (outerTag !== null) {
innerDOM = document.createElement(innerTag);
dom.appendChild(innerDOM);
}
const text = this.__text;
createTextInnerDOM(innerDOM, this, innerTag, format, text, config);
const style = this.__style;
if (style !== '') {
dom.style.cssText = style;
}
return dom;
}
updateDOM(
prevNode: TextNode,
dom: HTMLElement,
config: EditorConfig,
): boolean {
const nextText = this.__text;
const prevFormat = prevNode.__format;
const nextFormat = this.__format;
const prevOuterTag = getElementOuterTag(this, prevFormat);
const nextOuterTag = getElementOuterTag(this, nextFormat);
const prevInnerTag = getElementInnerTag(this, prevFormat);
const nextInnerTag = getElementInnerTag(this, nextFormat);
const prevTag = prevOuterTag === null ? prevInnerTag : prevOuterTag;
const nextTag = nextOuterTag === null ? nextInnerTag : nextOuterTag;
if (prevTag !== nextTag) {
return true;
}
if (prevOuterTag === nextOuterTag && prevInnerTag !== nextInnerTag) {
// should always be an element
const prevInnerDOM: HTMLElement = dom.firstChild as HTMLElement;
if (prevInnerDOM == null) {
invariant(false, 'updateDOM: prevInnerDOM is null or undefined');
}
const nextInnerDOM = document.createElement(nextInnerTag);
createTextInnerDOM(
nextInnerDOM,
this,
nextInnerTag,
nextFormat,
nextText,
config,
);
dom.replaceChild(nextInnerDOM, prevInnerDOM);
return false;
}
let innerDOM = dom;
if (nextOuterTag !== null) {
if (prevOuterTag !== null) {
innerDOM = dom.firstChild as HTMLElement;
if (innerDOM == null) {
invariant(false, 'updateDOM: innerDOM is null or undefined');
}
}
}
setTextContent(nextText, innerDOM, this);
const theme = config.theme;
// Apply theme class names
const textClassNames = theme.text;
if (textClassNames !== undefined && prevFormat !== nextFormat) {
setTextThemeClassNames(
nextInnerTag,
prevFormat,
nextFormat,
innerDOM,
textClassNames,
);
}
const prevStyle = prevNode.__style;
const nextStyle = this.__style;
if (prevStyle !== nextStyle) {
dom.style.cssText = nextStyle;
}
return false;
}
static importDOM(): DOMConversionMap | null {
return {
'#text': () => ({
conversion: $convertTextDOMNode,
priority: 0,
}),
b: () => ({
conversion: convertBringAttentionToElement,
priority: 0,
}),
code: () => ({
conversion: convertTextFormatElement,
priority: 0,
}),
em: () => ({
conversion: convertTextFormatElement,
priority: 0,
}),
i: () => ({
conversion: convertTextFormatElement,
priority: 0,
}),
s: () => ({
conversion: convertTextFormatElement,
priority: 0,
}),
span: () => ({
conversion: convertSpanElement,
priority: 0,
}),
strong: () => ({
conversion: convertTextFormatElement,
priority: 0,
}),
sub: () => ({
conversion: convertTextFormatElement,
priority: 0,
}),
sup: () => ({
conversion: convertTextFormatElement,
priority: 0,
}),
u: () => ({
conversion: convertTextFormatElement,
priority: 0,
}),
};
}
static importJSON(serializedNode: SerializedTextNode): TextNode {
const node = $createTextNode(serializedNode.text);
node.setFormat(serializedNode.format);
node.setDetail(serializedNode.detail);
node.setMode(serializedNode.mode);
node.setStyle(serializedNode.style);
return node;
}
// This improves Lexical's basic text output in copy+paste plus
// for headless mode where people might use Lexical to generate
// HTML content and not have the ability to use CSS classes.
exportDOM(editor: LexicalEditor): DOMExportOutput {
let {element} = super.exportDOM(editor);
invariant(
element !== null && isHTMLElement(element),
'Expected TextNode createDOM to always return a HTMLElement',
);
// Wrap up to retain space if head/tail whitespace exists
const text = this.getTextContent();
if (/^\s|\s$/.test(text)) {
element.style.whiteSpace = 'pre-wrap';
}
// Strip editor theme classes
for (const className of Array.from(element.classList.values())) {
if (className.startsWith('editor-theme-')) {
element.classList.remove(className);
}
}
if (element.classList.length === 0) {
element.removeAttribute('class');
}
// Remove placeholder tag if redundant
if (element.nodeName === 'SPAN' && !element.getAttribute('style')) {
element = document.createTextNode(text);
}
// This is the only way to properly add support for most clients,
// even if it's semantically incorrect to have to resort to using
// <b>, <u>, <s>, <i> elements.
if (this.hasFormat('bold')) {
element = wrapElementWith(element, 'b');
}
if (this.hasFormat('italic')) {
element = wrapElementWith(element, 'em');
}
if (this.hasFormat('strikethrough')) {
element = wrapElementWith(element, 's');
}
if (this.hasFormat('underline')) {
element = wrapElementWith(element, 'u');
}
return {
element,
};
}
exportJSON(): SerializedTextNode {
return {
detail: this.getDetail(),
format: this.getFormat(),
mode: this.getMode(),
style: this.getStyle(),
text: this.getTextContent(),
type: 'text',
version: 1,
};
}
// Mutators
selectionTransform(
prevSelection: null | BaseSelection,
nextSelection: RangeSelection,
): void {
return;
}
/**
* Sets the node format to the provided TextFormatType or 32-bit integer. Note that the TextFormatType
* version of the argument can only specify one format and doing so will remove all other formats that
* may be applied to the node. For toggling behavior, consider using {@link TextNode.toggleFormat}
*
* @param format - TextFormatType or 32-bit integer representing the node format.
*
* @returns this TextNode.
* // TODO 0.12 This should just be a `string`.
*/
setFormat(format: TextFormatType | number): this {
const self = this.getWritable();
self.__format =
typeof format === 'string' ? TEXT_TYPE_TO_FORMAT[format] : format;
return self;
}
/**
* Sets the node detail to the provided TextDetailType or 32-bit integer. Note that the TextDetailType
* version of the argument can only specify one detail value and doing so will remove all other detail values that
* may be applied to the node. For toggling behavior, consider using {@link TextNode.toggleDirectionless}
* or {@link TextNode.toggleUnmergeable}
*
* @param detail - TextDetailType or 32-bit integer representing the node detail.
*
* @returns this TextNode.
* // TODO 0.12 This should just be a `string`.
*/
setDetail(detail: TextDetailType | number): this {
const self = this.getWritable();
self.__detail =
typeof detail === 'string' ? DETAIL_TYPE_TO_DETAIL[detail] : detail;
return self;
}
/**
* Sets the node style to the provided CSSText-like string. Set this property as you
* would an HTMLElement style attribute to apply inline styles to the underlying DOM Element.
*
* @param style - CSSText to be applied to the underlying HTMLElement.
*
* @returns this TextNode.
*/
setStyle(style: string): this {
const self = this.getWritable();
self.__style = style;
return self;
}
/**
* Applies the provided format to this TextNode if it's not present. Removes it if it's present.
* The subscript and superscript formats are mutually exclusive.
* Prefer using this method to turn specific formats on and off.
*
* @param type - TextFormatType to toggle.
*
* @returns this TextNode.
*/
toggleFormat(type: TextFormatType): this {
const format = this.getFormat();
const newFormat = toggleTextFormatType(format, type, null);
return this.setFormat(newFormat);
}
/**
* Toggles the directionless detail value of the node. Prefer using this method over setDetail.
*
* @returns this TextNode.
*/
toggleDirectionless(): this {
const self = this.getWritable();
self.__detail ^= IS_DIRECTIONLESS;
return self;
}
/**
* Toggles the unmergeable detail value of the node. Prefer using this method over setDetail.
*
* @returns this TextNode.
*/
toggleUnmergeable(): this {
const self = this.getWritable();
self.__detail ^= IS_UNMERGEABLE;
return self;
}
/**
* Sets the mode of the node.
*
* @returns this TextNode.
*/
setMode(type: TextModeType): this {
const mode = TEXT_MODE_TO_TYPE[type];
if (this.__mode === mode) {
return this;
}
const self = this.getWritable();
self.__mode = mode;
return self;
}
/**
* Sets the text content of the node.
*
* @param text - the string to set as the text value of the node.
*
* @returns this TextNode.
*/
setTextContent(text: string): this {
if (this.__text === text) {
return this;
}
const self = this.getWritable();
self.__text = text;
return self;
}
/**
* Sets the current Lexical selection to be a RangeSelection with anchor and focus on this TextNode at the provided offsets.
*
* @param _anchorOffset - the offset at which the Selection anchor will be placed.
* @param _focusOffset - the offset at which the Selection focus will be placed.
*
* @returns the new RangeSelection.
*/
select(_anchorOffset?: number, _focusOffset?: number): RangeSelection {
errorOnReadOnly();
let anchorOffset = _anchorOffset;
let focusOffset = _focusOffset;
const selection = $getSelection();
const text = this.getTextContent();
const key = this.__key;
if (typeof text === 'string') {
const lastOffset = text.length;
if (anchorOffset === undefined) {
anchorOffset = lastOffset;
}
if (focusOffset === undefined) {
focusOffset = lastOffset;
}
} else {
anchorOffset = 0;
focusOffset = 0;
}
if (!$isRangeSelection(selection)) {
return $internalMakeRangeSelection(
key,
anchorOffset,
key,
focusOffset,
'text',
'text',
);
} else {
const compositionKey = $getCompositionKey();
if (
compositionKey === selection.anchor.key ||
compositionKey === selection.focus.key
) {
$setCompositionKey(key);
}
selection.setTextNodeRange(this, anchorOffset, this, focusOffset);
}
return selection;
}
selectStart(): RangeSelection {
return this.select(0, 0);
}
selectEnd(): RangeSelection {
const size = this.getTextContentSize();
return this.select(size, size);
}
/**
* Inserts the provided text into this TextNode at the provided offset, deleting the number of characters
* specified. Can optionally calculate a new selection after the operation is complete.
*
* @param offset - the offset at which the splice operation should begin.
* @param delCount - the number of characters to delete, starting from the offset.
* @param newText - the text to insert into the TextNode at the offset.
* @param moveSelection - optional, whether or not to move selection to the end of the inserted substring.
*
* @returns this TextNode.
*/
spliceText(
offset: number,
delCount: number,
newText: string,
moveSelection?: boolean,
): TextNode {
const writableSelf = this.getWritable();
const text = writableSelf.__text;
const handledTextLength = newText.length;
let index = offset;
if (index < 0) {
index = handledTextLength + index;
if (index < 0) {
index = 0;
}
}
const selection = $getSelection();
if (moveSelection && $isRangeSelection(selection)) {
const newOffset = offset + handledTextLength;
selection.setTextNodeRange(
writableSelf,
newOffset,
writableSelf,
newOffset,
);
}
const updatedText =
text.slice(0, index) + newText + text.slice(index + delCount);
writableSelf.__text = updatedText;
return writableSelf;
}
/**
* This method is meant to be overriden by TextNode subclasses to control the behavior of those nodes
* when a user event would cause text to be inserted before them in the editor. If true, Lexical will attempt
* to insert text into this node. If false, it will insert the text in a new sibling node.
*
* @returns true if text can be inserted before the node, false otherwise.
*/
canInsertTextBefore(): boolean {
return true;
}
/**
* This method is meant to be overriden by TextNode subclasses to control the behavior of those nodes
* when a user event would cause text to be inserted after them in the editor. If true, Lexical will attempt
* to insert text into this node. If false, it will insert the text in a new sibling node.
*
* @returns true if text can be inserted after the node, false otherwise.
*/
canInsertTextAfter(): boolean {
return true;
}
/**
* Splits this TextNode at the provided character offsets, forming new TextNodes from the substrings
* formed by the split, and inserting those new TextNodes into the editor, replacing the one that was split.
*
* @param splitOffsets - rest param of the text content character offsets at which this node should be split.
*
* @returns an Array containing the newly-created TextNodes.
*/
splitText(...splitOffsets: Array<number>): Array<TextNode> {
errorOnReadOnly();
const self = this.getLatest();
const textContent = self.getTextContent();
const key = self.__key;
const compositionKey = $getCompositionKey();
const offsetsSet = new Set(splitOffsets);
const parts = [];
const textLength = textContent.length;
let string = '';
for (let i = 0; i < textLength; i++) {
if (string !== '' && offsetsSet.has(i)) {
parts.push(string);
string = '';
}
string += textContent[i];
}
if (string !== '') {
parts.push(string);
}
const partsLength = parts.length;
if (partsLength === 0) {
return [];
} else if (parts[0] === textContent) {
return [self];
}
const firstPart = parts[0];
const parent = self.getParent();
let writableNode;
const format = self.getFormat();
const style = self.getStyle();
const detail = self.__detail;
let hasReplacedSelf = false;
if (self.isSegmented()) {
// Create a new TextNode
writableNode = $createTextNode(firstPart);
writableNode.__format = format;
writableNode.__style = style;
writableNode.__detail = detail;
hasReplacedSelf = true;
} else {
// For the first part, update the existing node
writableNode = self.getWritable();
writableNode.__text = firstPart;
}
// Handle selection
const selection = $getSelection();
// Then handle all other parts
const splitNodes: TextNode[] = [writableNode];
let textSize = firstPart.length;
for (let i = 1; i < partsLength; i++) {
const part = parts[i];
const partSize = part.length;
const sibling = $createTextNode(part).getWritable();
sibling.__format = format;
sibling.__style = style;
sibling.__detail = detail;