/
LexicalEditor.ts
882 lines (772 loc) · 24.7 KB
/
LexicalEditor.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
/**
* 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 {EditorState, SerializedEditorState} from './LexicalEditorState';
import type {DOMConversion, LexicalNode, NodeKey} from './LexicalNode';
import getDOMSelection from 'shared/getDOMSelection';
import invariant from 'shared/invariant';
import {$getRoot, $getSelection, TextNode} from '.';
import {FULL_RECONCILE, NO_DIRTY_NODES} from './LexicalConstants';
import {createEmptyEditorState} from './LexicalEditorState';
import {addRootElementEvents, removeRootElementEvents} from './LexicalEvents';
import {flushRootMutations, initMutationObserver} from './LexicalMutations';
import {
commitPendingUpdates,
internalGetActiveEditor,
parseEditorState,
triggerListeners,
updateEditor,
} from './LexicalUpdates';
import {
createUID,
dispatchCommand,
getCachedClassNameArray,
getDefaultView,
markAllNodesAsDirty,
} from './LexicalUtils';
import {DecoratorNode} from './nodes/LexicalDecoratorNode';
import {LineBreakNode} from './nodes/LexicalLineBreakNode';
import {ParagraphNode} from './nodes/LexicalParagraphNode';
import {RootNode} from './nodes/LexicalRootNode';
export type Spread<T1, T2> = Omit<T2, keyof T1> & T1;
export type Klass<T extends LexicalNode> = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
new (...args: any[]): T;
} & Omit<LexicalNode, 'constructor'>;
export type EditorThemeClassName = string;
export type TextNodeThemeClasses = {
base?: EditorThemeClassName;
bold?: EditorThemeClassName;
code?: EditorThemeClassName;
italic?: EditorThemeClassName;
strikethrough?: EditorThemeClassName;
subscript?: EditorThemeClassName;
superscript?: EditorThemeClassName;
underline?: EditorThemeClassName;
underlineStrikethrough?: EditorThemeClassName;
};
export type EditorUpdateOptions = {
onUpdate?: () => void;
skipTransforms?: true;
tag?: string;
discrete?: true;
};
export type EditorSetOptions = {
tag?: string;
};
export type EditorFocusOptions = {
defaultSelection?: 'rootStart' | 'rootEnd';
};
export type EditorThemeClasses = {
characterLimit?: EditorThemeClassName;
code?: EditorThemeClassName;
codeHighlight?: Record<string, EditorThemeClassName>;
hashtag?: EditorThemeClassName;
heading?: {
h1?: EditorThemeClassName;
h2?: EditorThemeClassName;
h3?: EditorThemeClassName;
h4?: EditorThemeClassName;
h5?: EditorThemeClassName;
h6?: EditorThemeClassName;
};
image?: EditorThemeClassName;
link?: EditorThemeClassName;
list?: {
ul?: EditorThemeClassName;
ulDepth?: Array<EditorThemeClassName>;
ol?: EditorThemeClassName;
olDepth?: Array<EditorThemeClassName>;
listitem?: EditorThemeClassName;
listitemChecked?: EditorThemeClassName;
listitemUnchecked?: EditorThemeClassName;
nested?: {
list?: EditorThemeClassName;
listitem?: EditorThemeClassName;
};
};
ltr?: EditorThemeClassName;
mark?: EditorThemeClassName;
markOverlap?: EditorThemeClassName;
paragraph?: EditorThemeClassName;
quote?: EditorThemeClassName;
root?: EditorThemeClassName;
rtl?: EditorThemeClassName;
table?: EditorThemeClassName;
tableAddColumns?: EditorThemeClassName;
tableAddRows?: EditorThemeClassName;
tableCellActionButton?: EditorThemeClassName;
tableCellActionButtonContainer?: EditorThemeClassName;
tableCellPrimarySelected?: EditorThemeClassName;
tableCellSelected?: EditorThemeClassName;
tableCell?: EditorThemeClassName;
tableCellEditing?: EditorThemeClassName;
tableCellHeader?: EditorThemeClassName;
tableCellResizer?: EditorThemeClassName;
tableCellSortedIndicator?: EditorThemeClassName;
tableResizeRuler?: EditorThemeClassName;
tableRow?: EditorThemeClassName;
tableSelected?: EditorThemeClassName;
text?: TextNodeThemeClasses;
embedBlock?: {
base?: EditorThemeClassName;
focus?: EditorThemeClassName;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
};
export type EditorConfig = {
disableEvents?: boolean;
namespace: string;
theme: EditorThemeClasses;
};
export type RegisteredNodes = Map<string, RegisteredNode>;
export type RegisteredNode = {
klass: Klass<LexicalNode>;
transforms: Set<Transform<LexicalNode>>;
};
export type Transform<T extends LexicalNode> = (node: T) => void;
export type ErrorHandler = (error: Error) => void;
export type MutationListeners = Map<MutationListener, Klass<LexicalNode>>;
export type MutatedNodes = Map<Klass<LexicalNode>, Map<NodeKey, NodeMutation>>;
export type NodeMutation = 'created' | 'updated' | 'destroyed';
export type UpdateListener = (arg0: {
dirtyElements: Map<NodeKey, IntentionallyMarkedAsDirtyElement>;
dirtyLeaves: Set<NodeKey>;
editorState: EditorState;
normalizedNodes: Set<NodeKey>;
prevEditorState: EditorState;
tags: Set<string>;
}) => void;
export type DecoratorListener<T = never> = (
decorator: Record<NodeKey, T>,
) => void;
export type RootListener = (
rootElement: null | HTMLElement,
prevRootElement: null | HTMLElement,
) => void;
export type TextContentListener = (text: string) => void;
export type MutationListener = (
nodes: Map<NodeKey, NodeMutation>,
payload: {updateTags: Set<string>; dirtyLeaves: Set<string>},
) => void;
export type CommandListener<P> = (payload: P, editor: LexicalEditor) => boolean;
export type EditableListener = (editable: boolean) => void;
export type CommandListenerPriority = 0 | 1 | 2 | 3 | 4;
export const COMMAND_PRIORITY_EDITOR = 0;
export const COMMAND_PRIORITY_LOW = 1;
export const COMMAND_PRIORITY_NORMAL = 2;
export const COMMAND_PRIORITY_HIGH = 3;
export const COMMAND_PRIORITY_CRITICAL = 4;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export type LexicalCommand<TPayload> = {
type?: string;
};
/**
* Type helper for extracting the payload type from a command.
*
* @example
* ```ts
* const MY_COMMAND = createCommand<SomeType>();
*
* // ...
*
* editor.registerCommand(MY_COMMAND, payload => {
* // Type of `payload` is inferred here. But lets say we want to extract a function to delegate to
* handleMyCommand(editor, payload);
* return true;
* });
*
* function handleMyCommand(editor: LexicalEditor, payload: CommandPayloadType<typeof MY_COMMAND>) {
* // `payload` is of type `SomeType`, extracted from the command.
* }
* ```
*/
export type CommandPayloadType<TCommand extends LexicalCommand<unknown>> =
TCommand extends LexicalCommand<infer TPayload> ? TPayload : never;
type Commands = Map<
LexicalCommand<unknown>,
Array<Set<CommandListener<unknown>>>
>;
type Listeners = {
decorator: Set<DecoratorListener>;
mutation: MutationListeners;
editable: Set<EditableListener>;
root: Set<RootListener>;
textcontent: Set<TextContentListener>;
update: Set<UpdateListener>;
};
export type Listener =
| DecoratorListener
| EditableListener
| MutationListener
| RootListener
| TextContentListener
| UpdateListener;
export type ListenerType =
| 'update'
| 'root'
| 'decorator'
| 'textcontent'
| 'mutation'
| 'editable';
export type TransformerType = 'text' | 'decorator' | 'element' | 'root';
export type IntentionallyMarkedAsDirtyElement = boolean;
type DOMConversionCache = Map<
string,
Array<(node: Node) => DOMConversion | null>
>;
export type SerializedEditor = {
editorState: SerializedEditorState;
};
export function resetEditor(
editor: LexicalEditor,
prevRootElement: null | HTMLElement,
nextRootElement: null | HTMLElement,
pendingEditorState: EditorState,
): void {
const keyNodeMap = editor._keyToDOMMap;
keyNodeMap.clear();
editor._editorState = createEmptyEditorState();
editor._pendingEditorState = pendingEditorState;
editor._compositionKey = null;
editor._dirtyType = NO_DIRTY_NODES;
editor._cloneNotNeeded.clear();
editor._dirtyLeaves = new Set();
editor._dirtyElements.clear();
editor._normalizedNodes = new Set();
editor._updateTags = new Set();
editor._updates = [];
const observer = editor._observer;
if (observer !== null) {
observer.disconnect();
editor._observer = null;
}
// Remove all the DOM nodes from the root element
if (prevRootElement !== null) {
prevRootElement.textContent = '';
}
if (nextRootElement !== null) {
nextRootElement.textContent = '';
keyNodeMap.set('root', nextRootElement);
}
}
function initializeConversionCache(nodes: RegisteredNodes): DOMConversionCache {
const conversionCache = new Map();
const handledConversions = new Set();
nodes.forEach((node) => {
const importDOM =
node.klass.importDOM != null
? node.klass.importDOM.bind(node.klass)
: null;
if (importDOM == null || handledConversions.has(importDOM)) {
return;
}
handledConversions.add(importDOM);
const map = importDOM();
if (map !== null) {
Object.keys(map).forEach((key) => {
let currentCache = conversionCache.get(key);
if (currentCache === undefined) {
currentCache = [];
conversionCache.set(key, currentCache);
}
currentCache.push(map[key]);
});
}
});
return conversionCache;
}
export function createEditor(editorConfig?: {
disableEvents?: boolean;
editorState?: EditorState;
namespace?: string;
nodes?: ReadonlyArray<Klass<LexicalNode>>;
onError?: ErrorHandler;
parentEditor?: LexicalEditor;
editable?: boolean;
theme?: EditorThemeClasses;
}): LexicalEditor {
const config = editorConfig || {};
const activeEditor = internalGetActiveEditor();
const theme = config.theme || {};
const parentEditor =
editorConfig === undefined ? activeEditor : config.parentEditor || null;
const disableEvents = config.disableEvents || false;
const editorState = createEmptyEditorState();
const namespace =
config.namespace ||
(parentEditor !== null ? parentEditor._config.namespace : createUID());
const initialEditorState = config.editorState;
const nodes = [
RootNode,
TextNode,
LineBreakNode,
ParagraphNode,
...(config.nodes || []),
];
const onError = config.onError;
const isEditable = config.editable !== undefined ? config.editable : true;
let registeredNodes;
if (editorConfig === undefined && activeEditor !== null) {
registeredNodes = activeEditor._nodes;
} else {
registeredNodes = new Map();
for (let i = 0; i < nodes.length; i++) {
const klass = nodes[i];
// Ensure custom nodes implement required methods.
if (__DEV__) {
const name = klass.name;
if (name !== 'RootNode') {
const proto = klass.prototype;
['getType', 'clone'].forEach((method) => {
// eslint-disable-next-line no-prototype-builtins
if (!klass.hasOwnProperty(method)) {
console.warn(`${name} must implement static "${method}" method`);
}
});
if (
// eslint-disable-next-line no-prototype-builtins
!klass.hasOwnProperty('importDOM') &&
// eslint-disable-next-line no-prototype-builtins
klass.hasOwnProperty('exportDOM')
) {
console.warn(
`${name} should implement "importDOM" if using a custom "exportDOM" method to ensure HTML serialization (important for copy & paste) works as expected`,
);
}
if (proto instanceof DecoratorNode) {
// eslint-disable-next-line no-prototype-builtins
if (!proto.hasOwnProperty('decorate')) {
console.warn(
`${proto.constructor.name} must implement "decorate" method`,
);
}
}
if (
// eslint-disable-next-line no-prototype-builtins
!klass.hasOwnProperty('importJSON')
) {
console.warn(
`${name} should implement "importJSON" method to ensure JSON and default HTML serialization works as expected`,
);
}
if (
// eslint-disable-next-line no-prototype-builtins
!proto.hasOwnProperty('exportJSON')
) {
console.warn(
`${name} should implement "exportJSON" method to ensure JSON and default HTML serialization works as expected`,
);
}
}
}
const type = klass.getType();
registeredNodes.set(type, {
klass,
transforms: new Set(),
});
}
}
const editor = new LexicalEditor(
editorState,
parentEditor,
registeredNodes,
{
disableEvents,
namespace,
theme,
},
onError ? onError : console.error,
initializeConversionCache(registeredNodes),
isEditable,
);
if (initialEditorState !== undefined) {
editor._pendingEditorState = initialEditorState;
editor._dirtyType = FULL_RECONCILE;
}
return editor;
}
export class LexicalEditor {
_headless: boolean;
_parentEditor: null | LexicalEditor;
_rootElement: null | HTMLElement;
_editorState: EditorState;
_pendingEditorState: null | EditorState;
_compositionKey: null | NodeKey;
_deferred: Array<() => void>;
_keyToDOMMap: Map<NodeKey, HTMLElement>;
_updates: Array<[() => void, EditorUpdateOptions | undefined]>;
_updating: boolean;
_listeners: Listeners;
_commands: Commands;
_nodes: RegisteredNodes;
_decorators: Record<NodeKey, unknown>;
_pendingDecorators: null | Record<NodeKey, unknown>;
_config: EditorConfig;
_dirtyType: 0 | 1 | 2;
_cloneNotNeeded: Set<NodeKey>;
_dirtyLeaves: Set<NodeKey>;
_dirtyElements: Map<NodeKey, IntentionallyMarkedAsDirtyElement>;
_normalizedNodes: Set<NodeKey>;
_updateTags: Set<string>;
_observer: null | MutationObserver;
_key: string;
_onError: ErrorHandler;
_htmlConversions: DOMConversionCache;
_window: null | Window;
_editable: boolean;
constructor(
editorState: EditorState,
parentEditor: null | LexicalEditor,
nodes: RegisteredNodes,
config: EditorConfig,
onError: ErrorHandler,
htmlConversions: DOMConversionCache,
editable: boolean,
) {
this._parentEditor = parentEditor;
// The root element associated with this editor
this._rootElement = null;
// The current editor state
this._editorState = editorState;
// Handling of drafts and updates
this._pendingEditorState = null;
// Used to help co-ordinate selection and events
this._compositionKey = null;
this._deferred = [];
// Used during reconciliation
this._keyToDOMMap = new Map();
this._updates = [];
this._updating = false;
// Listeners
this._listeners = {
decorator: new Set(),
editable: new Set(),
mutation: new Map(),
root: new Set(),
textcontent: new Set(),
update: new Set(),
};
// Commands
this._commands = new Map();
// Editor configuration for theme/context.
this._config = config;
// Mapping of types to their nodes
this._nodes = nodes;
// React node decorators for portals
this._decorators = {};
this._pendingDecorators = null;
// Used to optimize reconciliation
this._dirtyType = NO_DIRTY_NODES;
this._cloneNotNeeded = new Set();
this._dirtyLeaves = new Set();
this._dirtyElements = new Map();
this._normalizedNodes = new Set();
this._updateTags = new Set();
// Handling of DOM mutations
this._observer = null;
// Used for identifying owning editors
this._key = createUID();
this._onError = onError;
this._htmlConversions = htmlConversions;
// We don't actually make use of the `editable` argument above.
// Doing so, causes e2e tests around the lock to fail.
this._editable = true;
this._headless = false;
this._window = null;
}
isComposing(): boolean {
return this._compositionKey != null;
}
registerUpdateListener(listener: UpdateListener): () => void {
const listenerSetOrMap = this._listeners.update;
listenerSetOrMap.add(listener);
return () => {
listenerSetOrMap.delete(listener);
};
}
registerEditableListener(listener: EditableListener): () => void {
const listenerSetOrMap = this._listeners.editable;
listenerSetOrMap.add(listener);
return () => {
listenerSetOrMap.delete(listener);
};
}
registerDecoratorListener<T>(listener: DecoratorListener<T>): () => void {
const listenerSetOrMap = this._listeners.decorator;
listenerSetOrMap.add(listener);
return () => {
listenerSetOrMap.delete(listener);
};
}
registerTextContentListener(listener: TextContentListener): () => void {
const listenerSetOrMap = this._listeners.textcontent;
listenerSetOrMap.add(listener);
return () => {
listenerSetOrMap.delete(listener);
};
}
registerRootListener(listener: RootListener): () => void {
const listenerSetOrMap = this._listeners.root;
listener(this._rootElement, null);
listenerSetOrMap.add(listener);
return () => {
listener(null, this._rootElement);
listenerSetOrMap.delete(listener);
};
}
registerCommand<P>(
command: LexicalCommand<P>,
listener: CommandListener<P>,
priority: CommandListenerPriority,
): () => void {
if (priority === undefined) {
invariant(false, 'Listener for type "command" requires a "priority".');
}
const commandsMap = this._commands;
if (!commandsMap.has(command)) {
commandsMap.set(command, [
new Set(),
new Set(),
new Set(),
new Set(),
new Set(),
]);
}
const listenersInPriorityOrder = commandsMap.get(command);
if (listenersInPriorityOrder === undefined) {
invariant(
false,
'registerCommand: Command %s not found in command map',
String(command),
);
}
const listeners = listenersInPriorityOrder[priority];
listeners.add(listener as CommandListener<unknown>);
return () => {
listeners.delete(listener as CommandListener<unknown>);
if (
listenersInPriorityOrder.every(
(listenersSet) => listenersSet.size === 0,
)
) {
commandsMap.delete(command);
}
};
}
registerMutationListener(
klass: Klass<LexicalNode>,
listener: MutationListener,
): () => void {
const registeredNode = this._nodes.get(klass.getType());
if (registeredNode === undefined) {
invariant(
false,
'Node %s has not been registered. Ensure node has been passed to createEditor.',
klass.name,
);
}
const mutations = this._listeners.mutation;
mutations.set(listener, klass);
return () => {
mutations.delete(listener);
};
}
registerNodeTransform<T extends LexicalNode>(
klass: Klass<T>,
listener: Transform<T>,
): () => void {
const type = klass.getType();
const registeredNode = this._nodes.get(type);
if (registeredNode === undefined) {
invariant(
false,
'Node %s has not been registered. Ensure node has been passed to createEditor.',
klass.name,
);
}
const transforms = registeredNode.transforms;
transforms.add(listener as Transform<LexicalNode>);
markAllNodesAsDirty(this, type);
return () => {
transforms.delete(listener as Transform<LexicalNode>);
};
}
hasNodes<T extends Klass<LexicalNode>>(nodes: Array<T>): boolean {
for (let i = 0; i < nodes.length; i++) {
const klass = nodes[i];
const type = klass.getType();
if (!this._nodes.has(type)) {
return false;
}
}
return true;
}
dispatchCommand<TCommand extends LexicalCommand<unknown>>(
type: TCommand,
payload: CommandPayloadType<TCommand>,
): boolean {
return dispatchCommand(this, type, payload);
}
getDecorators<T>(): Record<NodeKey, T> {
return this._decorators as Record<NodeKey, T>;
}
getRootElement(): null | HTMLElement {
return this._rootElement;
}
getKey(): string {
return this._key;
}
setRootElement(nextRootElement: null | HTMLElement): void {
const prevRootElement = this._rootElement;
if (nextRootElement !== prevRootElement) {
const classNames = getCachedClassNameArray(this._config.theme, 'root');
const pendingEditorState = this._pendingEditorState || this._editorState;
this._rootElement = nextRootElement;
resetEditor(this, prevRootElement, nextRootElement, pendingEditorState);
if (prevRootElement !== null) {
// TODO: remove this flag once we no longer use UEv2 internally
if (!this._config.disableEvents) {
removeRootElementEvents(prevRootElement);
}
if (classNames != null) {
prevRootElement.classList.remove(...classNames);
}
}
if (nextRootElement !== null) {
const windowObj = getDefaultView(nextRootElement);
const style = nextRootElement.style;
style.userSelect = 'text';
style.whiteSpace = 'pre-wrap';
style.wordBreak = 'break-word';
nextRootElement.setAttribute('data-lexical-editor', 'true');
this._window = windowObj;
this._dirtyType = FULL_RECONCILE;
initMutationObserver(this);
this._updateTags.add('history-merge');
commitPendingUpdates(this);
// TODO: remove this flag once we no longer use UEv2 internally
if (!this._config.disableEvents) {
addRootElementEvents(nextRootElement, this);
}
if (classNames != null) {
nextRootElement.classList.add(...classNames);
}
} else {
this._window = null;
}
triggerListeners('root', this, false, nextRootElement, prevRootElement);
}
}
getElementByKey(key: NodeKey): HTMLElement | null {
return this._keyToDOMMap.get(key) || null;
}
getEditorState(): EditorState {
return this._editorState;
}
setEditorState(editorState: EditorState, options?: EditorSetOptions): void {
if (editorState.isEmpty()) {
invariant(
false,
"setEditorState: the editor state is empty. Ensure the editor state's root node never becomes empty.",
);
}
flushRootMutations(this);
const pendingEditorState = this._pendingEditorState;
const tags = this._updateTags;
const tag = options !== undefined ? options.tag : null;
if (pendingEditorState !== null && !pendingEditorState.isEmpty()) {
if (tag != null) {
tags.add(tag);
}
commitPendingUpdates(this);
}
this._pendingEditorState = editorState;
this._dirtyType = FULL_RECONCILE;
this._dirtyElements.set('root', false);
this._compositionKey = null;
if (tag != null) {
tags.add(tag);
}
commitPendingUpdates(this);
}
parseEditorState(
maybeStringifiedEditorState: string | SerializedEditorState,
updateFn?: () => void,
): EditorState {
const serializedEditorState =
typeof maybeStringifiedEditorState === 'string'
? JSON.parse(maybeStringifiedEditorState)
: maybeStringifiedEditorState;
return parseEditorState(serializedEditorState, this, updateFn);
}
update(updateFn: () => void, options?: EditorUpdateOptions): void {
updateEditor(this, updateFn, options);
}
focus(callbackFn?: () => void, options: EditorFocusOptions = {}): void {
const rootElement = this._rootElement;
if (rootElement !== null) {
// This ensures that iOS does not trigger caps lock upon focus
rootElement.setAttribute('autocapitalize', 'off');
updateEditor(
this,
() => {
const selection = $getSelection();
const root = $getRoot();
if (selection !== null) {
// Marking the selection dirty will force the selection back to it
selection.dirty = true;
} else if (root.getChildrenSize() !== 0) {
if (options.defaultSelection === 'rootStart') {
root.selectStart();
} else {
root.selectEnd();
}
}
},
{
onUpdate: () => {
rootElement.removeAttribute('autocapitalize');
if (callbackFn) {
callbackFn();
}
},
},
);
// In the case where onUpdate doesn't fire (due to the focus update not
// occuring).
if (this._pendingEditorState === null) {
rootElement.removeAttribute('autocapitalize');
}
}
}
blur(): void {
const rootElement = this._rootElement;
if (rootElement !== null) {
rootElement.blur();
}
const domSelection = getDOMSelection();
if (domSelection !== null) {
domSelection.removeAllRanges();
}
}
isEditable(): boolean {
return this._editable;
}
setEditable(editable: boolean): void {
if (this._editable !== editable) {
this._editable = editable;
triggerListeners('editable', this, true, editable);
}
}
toJSON(): SerializedEditor {
return {
editorState: this._editorState.toJSON(),
};
}
}