2 * Copyright (c) Meta Platforms, Inc. and affiliates.
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
18 import {EditorState} from '../../LexicalEditorState';
19 import {$createRootNode, RootNode} from '../../nodes/LexicalRootNode';
20 import {initializeUnitTest} from '../utils';
22 describe('LexicalEditorState tests', () => {
23 initializeUnitTest((testEnv) => {
24 test('constructor', async () => {
25 const root = $createRootNode();
26 const nodeMap = new Map([['root', root]]);
28 const editorState = new EditorState(nodeMap);
29 expect(editorState._nodeMap).toBe(nodeMap);
30 expect(editorState._selection).toBe(null);
33 test('read()', async () => {
34 const {editor} = testEnv;
36 await editor.update(() => {
37 const paragraph = $createParagraphNode();
38 const text = $createTextNode('foo');
39 paragraph.append(text);
40 $getRoot().append(paragraph);
44 let paragraph!: ParagraphNode;
47 editor.getEditorState().read(() => {
49 paragraph = root.getFirstChild()!;
50 text = paragraph.getFirstChild()!;
53 expect(root).toEqual({
68 expect(paragraph).toEqual({
84 expect(text).toEqual({
96 expect(() => editor.getEditorState().read(() => $getEditor())).toThrow(
97 /Unable to find an active editor/,
100 editor.getEditorState().read(() => $getEditor(), {editor: editor}),
104 test('toJSON()', async () => {
105 const {editor} = testEnv;
107 await editor.update(() => {
108 const paragraph = $createParagraphNode();
109 const text = $createTextNode('Hello world');
111 paragraph.append(text);
112 $getRoot().append(paragraph);
115 expect(JSON.stringify(editor.getEditorState().toJSON())).toEqual(
116 `{"root":{"children":[{"children":[{"detail":0,"format":0,"mode":"normal","style":"","text":"Hello world","type":"text","version":1}],"direction":"ltr","format":"","indent":0,"type":"paragraph","version":1,"textFormat":0,"textStyle":""}],"direction":"ltr","format":"","indent":0,"type":"root","version":1}}`,
120 test('ensure garbage collection works as expected', async () => {
121 const {editor} = testEnv;
123 await editor.update(() => {
124 const paragraph = $createParagraphNode();
125 const text = $createTextNode('foo');
126 paragraph.append(text);
127 $getRoot().append(paragraph);
129 // Remove the first node, which should cause a GC for everything
131 await editor.update(() => {
132 $getRoot().getFirstChild()!.remove();
135 expect(editor.getEditorState()._nodeMap).toEqual(