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.
9 import {$createTableSelection} from '@lexical/table';
21 import {createTestEditor} from 'lexical/__tests__/utils';
22 import {createRef, useEffect, useMemo} from 'react';
23 import {createRoot, Root} from 'react-dom/client';
24 import * as ReactTestUtils from 'lexical/shared/react-test-utils';
26 describe('table selection', () => {
27 let originalText: TextNode;
28 let parsedParagraph: ParagraphNode;
29 let parsedRoot: RootNode;
30 let parsedText: TextNode;
31 let paragraphKey: string;
33 let parsedEditorState: EditorState;
35 let container: HTMLDivElement | null = null;
36 let editor: LexicalEditor | null = null;
39 container = document.createElement('div');
40 reactRoot = createRoot(container);
41 document.body.appendChild(container);
44 function useLexicalEditor(
45 rootElementRef: React.RefObject<HTMLDivElement>,
48 const editorInHook = useMemo(
52 onError: onError || jest.fn(),
55 bold: 'editor-text-bold',
56 italic: 'editor-text-italic',
57 underline: 'editor-text-underline',
65 const rootElement = rootElementRef.current;
67 editorInHook.setRootElement(rootElement);
68 }, [rootElementRef, editorInHook]);
73 function init(onError?: () => void) {
74 const ref = createRef<HTMLDivElement>();
77 editor = useLexicalEditor(ref, onError);
79 return <div ref={ref} contentEditable={true} />;
82 ReactTestUtils.act(() => {
83 reactRoot.render(<TestBase />);
87 async function update(fn: () => void) {
90 return Promise.resolve().then();
93 beforeEach(async () => {
97 const paragraph = $createParagraphNode();
98 originalText = $createTextNode('Hello world');
99 const selection = $createTableSelection();
101 originalText.getKey(),
102 originalText.getKey(),
103 originalText.getKey(),
105 $setSelection(selection);
106 paragraph.append(originalText);
107 $getRoot().append(paragraph);
110 const stringifiedEditorState = JSON.stringify(
111 editor!.getEditorState().toJSON(),
114 parsedEditorState = editor!.parseEditorState(stringifiedEditorState);
115 parsedEditorState.read(() => {
116 parsedRoot = $getRoot();
117 parsedParagraph = parsedRoot.getFirstChild()!;
118 paragraphKey = parsedParagraph.getKey();
119 parsedText = parsedParagraph.getFirstChild()!;
120 textKey = parsedText.getKey();
124 it('Parses the nodes of a stringified editor state', async () => {
125 expect(parsedRoot).toEqual({
128 __first: paragraphKey,
132 __last: paragraphKey,
140 expect(parsedParagraph).toEqual({
156 expect(parsedText).toEqual({
162 __parent: paragraphKey,
165 __text: 'Hello world',
170 it('Parses the text content of the editor state', async () => {
171 expect(parsedEditorState.read(() => $getRoot().__cachedText)).toBe(null);
172 expect(parsedEditorState.read(() => $getRoot().getTextContent())).toBe(