diff --git a/packages/lexical-extension/src/TabIndentationExtension.ts b/packages/lexical-extension/src/TabIndentationExtension.ts index 0d867d8d12f0..6275e6c5427f 100644 --- a/packages/lexical-extension/src/TabIndentationExtension.ts +++ b/packages/lexical-extension/src/TabIndentationExtension.ts @@ -19,15 +19,17 @@ import { COMMAND_PRIORITY_CRITICAL, COMMAND_PRIORITY_EDITOR, defineExtension, - type ElementNode, + ElementNode, INDENT_CONTENT_COMMAND, INSERT_TAB_COMMAND, KEY_TAB_COMMAND, + type Klass, type LexicalCommand, type LexicalEditor, mergeRegister, OUTDENT_CONTENT_COMMAND, type RangeSelection, + RootNode, safeCast, } from 'lexical'; @@ -70,10 +72,42 @@ function $defaultCanIndent(node: ElementNode) { return node.canIndent(); } +/** + * Indentation from anywhere other than the indent command must stay below + * maxIndent too (#5170), so clamp it with a transform on every block element + * type that may be indented. This applies to all content, not only pastes: + * the initial or loaded editor state, `setEditorState`, collaboration + * updates and nodes inserted from code. Registering marks every element + * dirty, so the whole document is checked (and clamped) once at that point. + */ +function registerMaxIndentTransforms( + editor: LexicalEditor, + maxIndent: number, + $getCanIndent: () => CanIndentPredicate, +): () => void { + const $clampIndent = (node: ElementNode) => { + if (node.getIndent() >= maxIndent && $getCanIndent()(node)) { + node.setIndent(maxIndent - 1); + } + }; + const removers: (() => void)[] = []; + for (const {klass} of editor._nodes.values()) { + if (klass.prototype instanceof ElementNode && klass !== RootNode) { + removers.push( + editor.registerNodeTransform(klass as Klass, $clampIndent), + ); + } + } + return mergeRegister(...removers); +} + /** * Registers a `KEY_TAB_COMMAND` handler that makes Tab and Shift+Tab indent and * outdent block elements (and otherwise insert a tab). Pass `maxIndent` to cap - * the indent depth and `$canIndent` to control which elements may be indented. + * the indent depth (indents below `maxIndent`), and `$canIndent` to control + * which elements may be indented. The `maxIndent` cap applies to any content, + * including pastes, loaded state, `setEditorState` and collaboration updates; + * deeper indents already in the document are clamped once on registration. * * @returns A cleanup function that unregisters the handler. */ @@ -84,7 +118,29 @@ export function registerTabIndentation( | CanIndentPredicate | ReadonlySignal = $defaultCanIndent, ) { + const $getCanIndent = () => + typeof $canIndent === 'function' ? $canIndent : $canIndent.peek(); + let unregisterClamp: () => void; + if (typeof maxIndent === 'number') { + unregisterClamp = maxIndent + ? registerMaxIndentTransforms(editor, maxIndent, $getCanIndent) + : () => {}; + } else if (maxIndent) { + unregisterClamp = effect(() => { + const currentMaxIndent = maxIndent.value; + if (currentMaxIndent) { + return registerMaxIndentTransforms( + editor, + currentMaxIndent, + $getCanIndent, + ); + } + }); + } else { + unregisterClamp = () => {}; + } return mergeRegister( + unregisterClamp, editor.registerCommand( KEY_TAB_COMMAND, event => { diff --git a/packages/lexical-extension/src/__tests__/unit/IndentationLimitsPaste.test.ts b/packages/lexical-extension/src/__tests__/unit/IndentationLimitsPaste.test.ts new file mode 100644 index 000000000000..1c517c5bae7f --- /dev/null +++ b/packages/lexical-extension/src/__tests__/unit/IndentationLimitsPaste.test.ts @@ -0,0 +1,221 @@ +/** + * 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 {$insertDataTransferForRichText} from '@lexical/clipboard'; +import {HistoryExtension} from '@lexical/history'; +import {$isListItemNode, ListExtension} from '@lexical/list'; +import {RichTextExtension} from '@lexical/rich-text'; +import { + $createParagraphNode, + $createTextNode, + $getRoot, + $getSelection, + $isElementNode, + $isParagraphNode, + configExtension, + defineExtension, + type ElementNode, + type LexicalEditor, + type LexicalNode, + UNDO_COMMAND, +} from 'lexical'; +import {assert, describe, expect, test} from 'vitest'; + +import {buildEditorFromExtensions, TabIndentationExtension} from '../../index'; + +// Pasted content must respect maxIndent too, not only the indent command +// (#5170). Indent command caps indentation at maxIndent - 1. +function createEditor( + maxIndent: null | number, + $canIndent?: (node: ElementNode) => boolean, +) { + return buildEditorFromExtensions( + defineExtension({ + dependencies: [ + RichTextExtension, + ListExtension, + HistoryExtension, + configExtension( + TabIndentationExtension, + $canIndent ? {$canIndent, maxIndent} : {maxIndent}, + ), + ], + name: 'IndentationLimitsPaste', + }), + ); +} + +function paste(editor: LexicalEditor, html: string) { + editor.update( + () => { + const paragraph = $createParagraphNode(); + $getRoot().clear().append(paragraph); + paragraph.select(); + }, + {discrete: true}, + ); + editor.update( + () => { + const selection = $getSelection(); + assert(selection !== null, 'Expected a selection'); + const dataTransfer = { + getData: (type: string) => (type === 'text/html' ? html : ''), + types: ['text/html'], + } as unknown as DataTransfer; + $insertDataTransferForRichText(dataTransfer, selection, editor); + }, + {discrete: true}, + ); +} + +function $blocks( + node: LexicalNode = $getRoot(), +): {indent: number; text: string; type: string}[] { + if ($isListItemNode(node) && $isElementNode(node.getFirstChild())) { + return node.getChildren().flatMap(child => $blocks(child)); + } + if ( + $isElementNode(node) && + !node.isInline() && + node + .getChildren() + .every(child => !$isElementNode(child) || child.isInline()) + ) { + return node.getTextContent() === '' + ? [] + : [ + { + indent: node.getIndent(), + text: node.getTextContent(), + type: node.getType(), + }, + ]; + } + return $isElementNode(node) + ? node.getChildren().flatMap(child => $blocks(child)) + : []; +} + +function nestedListHTML(depth: number): string { + let html = ''; + for (let i = depth; i >= 0; i--) { + html = ``; + } + return html; +} + +const indentedBlocksHTML = + '

two

' + + '

ten

' + + '

heading

'; + +describe('TabIndentationExtension maxIndent on paste (#5170)', () => { + test('clamps an over-indented initial editor state', () => { + using editor = buildEditorFromExtensions( + defineExtension({ + $initialEditorState: () => { + $getRoot().append( + $createParagraphNode().setIndent(1).append($createTextNode('one')), + $createParagraphNode().setIndent(9).append($createTextNode('nine')), + ); + }, + dependencies: [ + RichTextExtension, + configExtension(TabIndentationExtension, {maxIndent: 4}), + ], + name: 'IndentationLimitsInitialState', + }), + ); + expect(editor.read(() => $blocks())).toEqual([ + {indent: 1, text: 'one', type: 'paragraph'}, + {indent: 3, text: 'nine', type: 'paragraph'}, + ]); + }); + + test('clamps an over-indented state set with setEditorState', () => { + using editor = createEditor(4); + const json = JSON.stringify({ + root: { + children: [ + { + children: [ + { + detail: 0, + format: 0, + mode: 'normal', + style: '', + text: 'deep', + type: 'text', + version: 1, + }, + ], + direction: null, + format: '', + indent: 7, + type: 'paragraph', + version: 1, + }, + ], + direction: null, + format: '', + indent: 0, + type: 'root', + version: 1, + }, + }); + editor.setEditorState(editor.parseEditorState(json)); + expect(editor.read(() => $blocks())).toEqual([ + {indent: 3, text: 'deep', type: 'paragraph'}, + ]); + }); + + test('clamps a pasted nested list without losing items', () => { + using editor = createEditor(4); + paste(editor, nestedListHTML(6)); + expect(editor.read(() => $blocks())).toEqual( + [0, 1, 2, 3, 3, 3, 3].map((indent, i) => ({ + indent, + text: `level ${i}`, + type: 'listitem', + })), + ); + }); + + test('clamps pasted indented paragraphs and headings', () => { + using editor = createEditor(4); + paste(editor, indentedBlocksHTML); + expect(editor.read(() => $blocks())).toEqual([ + {indent: 2, text: 'two', type: 'paragraph'}, + {indent: 3, text: 'ten', type: 'paragraph'}, + {indent: 3, text: 'heading', type: 'heading'}, + ]); + }); + + test('leaves pasted indentation alone when maxIndent is null', () => { + using editor = createEditor(null); + paste(editor, nestedListHTML(6) + indentedBlocksHTML); + expect(editor.read(() => $blocks().map(({indent}) => indent))).toEqual([ + 0, 1, 2, 3, 4, 5, 6, 2, 10, 9, + ]); + }); + + test('only clamps nodes that the $canIndent predicate allows to indent', () => { + using editor = createEditor(4, node => !$isParagraphNode(node)); + paste(editor, indentedBlocksHTML); + expect(editor.read(() => $blocks().map(({indent}) => indent))).toEqual([ + 2, 10, 3, + ]); + }); + + test('clamps in the same history entry as the paste', () => { + using editor = createEditor(4); + paste(editor, indentedBlocksHTML); + editor.dispatchCommand(UNDO_COMMAND, undefined); + expect(editor.read(() => $getRoot().getTextContent())).toBe(''); + }); +}); diff --git a/packages/lexical-react/src/LexicalTabIndentationPlugin.tsx b/packages/lexical-react/src/LexicalTabIndentationPlugin.tsx index deffeec57fbd..eeeaab7b1808 100644 --- a/packages/lexical-react/src/LexicalTabIndentationPlugin.tsx +++ b/packages/lexical-react/src/LexicalTabIndentationPlugin.tsx @@ -11,7 +11,9 @@ import { registerTabIndentation, } from '@lexical/extension'; import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext'; -import {useEffect} from 'react'; +import {useEffect, useRef} from 'react'; + +import useLayoutEffect from './shared/useLayoutEffect'; export {registerTabIndentation}; @@ -35,9 +37,18 @@ export function TabIndentationPlugin({ $canIndent?: CanIndentPredicate; }): null { const [editor] = useLexicalComposerContext(); + // Registering re-checks the whole document against maxIndent, so keep the + // latest $canIndent in a ref instead of re-registering when it changes. + const $canIndentRef = useRef($canIndent); + useLayoutEffect(() => { + $canIndentRef.current = $canIndent; + }); useEffect(() => { - return registerTabIndentation(editor, maxIndent, $canIndent); - }, [editor, maxIndent, $canIndent]); + return registerTabIndentation(editor, maxIndent, node => { + const $currentCanIndent = $canIndentRef.current; + return $currentCanIndent ? $currentCanIndent(node) : node.canIndent(); + }); + }, [editor, maxIndent]); return null; } diff --git a/packages/lexical-react/src/__tests__/unit/LexicalTabIndentationPlugin.test.tsx b/packages/lexical-react/src/__tests__/unit/LexicalTabIndentationPlugin.test.tsx new file mode 100644 index 000000000000..17450302c258 --- /dev/null +++ b/packages/lexical-react/src/__tests__/unit/LexicalTabIndentationPlugin.test.tsx @@ -0,0 +1,133 @@ +/** + * 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 {LexicalComposer} from '@lexical/react/LexicalComposer'; +import {ContentEditable} from '@lexical/react/LexicalContentEditable'; +import {EditorRefPlugin} from '@lexical/react/LexicalEditorRefPlugin'; +import {RichTextPlugin} from '@lexical/react/LexicalRichTextPlugin'; +import {TabIndentationPlugin} from '@lexical/react/LexicalTabIndentationPlugin'; +import { + $createParagraphNode, + $createTextNode, + $getRoot, + $isParagraphNode, + type ElementNode, + type LexicalEditor, +} from 'lexical'; +import * as React from 'react'; +import {act, createRef} from 'react'; +import {createRoot, type Root} from 'react-dom/client'; +import {afterEach, assert, beforeEach, describe, expect, it, vi} from 'vitest'; + +describe('TabIndentationPlugin', () => { + let container: HTMLDivElement; + let reactRoot: Root; + + beforeEach(() => { + container = document.createElement('div'); + document.body.appendChild(container); + reactRoot = createRoot(container); + }); + + afterEach(async () => { + await act(async () => { + reactRoot.unmount(); + }); + container.remove(); + }); + + function App({ + $canIndent, + editorRef, + }: { + $canIndent?: (node: ElementNode) => boolean; + editorRef: React.RefObject; + }) { + return ( + { + throw error; + }, + }}> + + } + ErrorBoundary={({children}) => <>{children}} + /> + + + ); + } + + // Registering re-checks the whole document (#5170), so an inline + // $canIndent must not re-register on every render. + it('does not re-register when an inline $canIndent changes', async () => { + const editorRef = + createRef() as React.RefObject; + await act(async () => { + reactRoot.render( + node.canIndent()} editorRef={editorRef} />, + ); + }); + const editor = editorRef.current; + assert(editor !== null, 'Expected an editor'); + const registerNodeTransform = vi.spyOn(editor, 'registerNodeTransform'); + await act(async () => { + reactRoot.render( + !$isParagraphNode(node)} + editorRef={editorRef} + />, + ); + }); + expect(registerNodeTransform).not.toHaveBeenCalled(); + + // The latest predicate is still used: paragraphs are now left alone. + await act(async () => { + editor.update(() => { + $getRoot() + .clear() + .append( + $createParagraphNode().setIndent(9).append($createTextNode('x')), + ); + }); + }); + expect( + editor.read(() => + ($getRoot().getFirstChild() as ElementNode).getIndent(), + ), + ).toBe(9); + }); + + it('clamps with the default predicate', async () => { + const editorRef = + createRef() as React.RefObject; + await act(async () => { + reactRoot.render(); + }); + const editor = editorRef.current; + assert(editor !== null, 'Expected an editor'); + await act(async () => { + editor.update(() => { + $getRoot() + .clear() + .append( + $createParagraphNode().setIndent(9).append($createTextNode('x')), + ); + }); + }); + expect( + editor.read(() => + ($getRoot().getFirstChild() as ElementNode).getIndent(), + ), + ).toBe(3); + }); +});