An open source design system that's fully customizable and agent ready
TypeScript
fix(richtext): split RichTextEditor read-only from disabled and follow prop changes (#6980)
Cindy Zhang115f3e92fe42
diff --git a/packages/richtext/src/RichTextEditor.doc.mjs b/packages/richtext/src/RichTextEditor.doc.mjsindex 1ccfcc5564..d5207f2300 100644--- a/packages/richtext/src/RichTextEditor.doc.mjs+++ b/packages/richtext/src/RichTextEditor.doc.mjs@@ -57,13 +57,15 @@ export const docs = {{name: 'isReadOnly',type: 'boolean',- description: 'Whether the editor is read-only (non-editable).',+ description:+ 'Whether the editor is read-only (non-editable). Content stays at full opacity, in the tab order, and announced as read-only. Takes effect when changed after mount.',default: 'false',},{name: 'isDisabled',type: 'boolean',- description: 'Whether the editor is disabled (non-editable, dimmed).',+ description:+ 'Whether the editor is disabled: non-editable, dimmed, out of the tab order, and announced as disabled. Wins when isReadOnly is also set. Takes effect when changed after mount.',default: 'false',},{diff --git a/packages/richtext/src/RichTextEditor.test.tsx b/packages/richtext/src/RichTextEditor.test.tsxindex 1a37978bc0..0ef8f2a59e 100644--- a/packages/richtext/src/RichTextEditor.test.tsx+++ b/packages/richtext/src/RichTextEditor.test.tsx@@ -5,15 +5,16 @@* @input Uses vitest, @testing-library/react, RichTextEditor + RichTextView* @output Unit tests for the opt-in Lexical editor components, including* accessible label wiring, shared input visuals/status variants,- * placeholder semantics, canonical link-dialog layout, and top-toolbar- * ordering and horizontal scrolling+ * placeholder semantics, canonical link-dialog layout, top-toolbar+ * ordering and horizontal scrolling, and the read-only vs disabled split+ * with editable-state sync across prop toggles* @position Testing; validates RichTextEditor.tsx and RichTextView.tsx** SYNC: When the editor components change, update these tests to match.*/import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';-import {render, screen, waitFor, fireEvent} from '@testing-library/react';+import {render, screen, waitFor, fireEvent, act} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {createRef, useEffect} from 'react';import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';@@ -90,6 +91,18 @@ afterAll(() => {}});+// jsdom's Range does not implement getBoundingClientRect, which Lexical+// calls (via scroll-into-view) whenever it reconciles a selection while the+// editor is focused. Guarded stub shared by every describe that focuses the+// editor (Tab escape, imperative ref toggles).+function stubRangeRects() {+ beforeAll(() => {+ if (typeof Range.prototype.getBoundingClientRect !== 'function') {+ Range.prototype.getBoundingClientRect = () => new DOMRect();+ }+ });+}+// Small plugin that captures the editor instance so tests can drive real// Lexical updates (jsdom does not implement contenteditable editing).function CaptureEditor({onReady}: {onReady: (editor: LexicalEditor) => void}) {@@ -358,6 +371,39 @@ describe('RichTextEditor', () => {);});+ it('keeps a read-only editor reachable and announced as read-only', () => {+ render(<RichTextEditor label="Notes" isReadOnly />);+ const textbox = screen.getByRole('textbox');+ // A read-only textbox stays in the tab order so keyboard and+ // screen-reader users can reach, read, and copy its content.+ expect(textbox).toHaveAttribute('tabindex', '0');+ expect(textbox).toHaveAttribute('aria-readonly', 'true');+ expect(textbox).not.toHaveAttribute('aria-disabled');+ });++ it('does not dim a read-only editor with the disabled treatment', () => {+ const {container} = render(<RichTextEditor label="Notes" isReadOnly />);+ const wrapper = container.querySelector('.astryx-rich-text-editor');+ expect(wrapper).not.toBeNull();+ expect(getComputedStyle(wrapper as Element).opacity).not.toBe('0.5');+ });++ it('announces a disabled editor as disabled, not read-only', () => {+ render(<RichTextEditor label="Notes" isDisabled />);+ const textbox = screen.getByRole('textbox');+ expect(textbox).toHaveAttribute('aria-disabled', 'true');+ expect(textbox).not.toHaveAttribute('aria-readonly');+ // Disabled controls leave the tab order.+ expect(textbox).not.toHaveAttribute('tabindex', '0');+ });++ it('keeps the dimmed treatment on a disabled editor', () => {+ const {container} = render(<RichTextEditor label="Notes" isDisabled />);+ const wrapper = container.querySelector('.astryx-rich-text-editor');+ expect(wrapper).not.toBeNull();+ expect(getComputedStyle(wrapper as Element).opacity).toBe('0.5');+ });+it('marks the textbox invalid on error status', () => {render(<RichTextEditor@@ -779,15 +825,7 @@ describe('RichTextEditor', () => {describe('RichTextEditor Tab keyboard trap escape (WCAG 2.1.2)', () => {const DEFAULT_HINT = 'Press Escape then Tab to move focus out of the editor.';- beforeAll(() => {- // jsdom's Range does not implement getBoundingClientRect, which Lexical- // calls (via scroll-into-view) whenever it reconciles a collapsed- // selection while the editor is focused. Stub it so the focused-editor- // keyboard tests below can run without uncaught exceptions.- if (typeof Range.prototype.getBoundingClientRect !== 'function') {- Range.prototype.getBoundingClientRect = () => new DOMRect();- }- });+ stubRangeRects();/*** Renders the editor followed by a button, focuses the contenteditable and@@ -1669,3 +1707,227 @@ describe('RichTextEditorToolbar — new-tab links', () => {});});});++describe('editable state follows prop changes', () => {+ it('disables editing and announces it when isDisabled turns on after mount', () => {+ const {rerender} = render(<RichTextEditor label="Notes" />);+ expect(screen.getByRole('textbox')).toHaveAttribute(+ 'contenteditable',+ 'true',+ );+ rerender(<RichTextEditor label="Notes" isDisabled />);+ const textbox = screen.getByRole('textbox');+ // The surface must actually stop accepting input, not only announce it.+ expect(textbox).toHaveAttribute('contenteditable', 'false');+ expect(textbox).toHaveAttribute('aria-disabled', 'true');+ expect(textbox).not.toHaveAttribute('aria-readonly');+ });++ it('becomes editable when isReadOnly turns off after mount', () => {+ const {rerender} = render(<RichTextEditor label="Notes" isReadOnly />);+ expect(screen.getByRole('textbox')).toHaveAttribute(+ 'contenteditable',+ 'false',+ );+ rerender(<RichTextEditor label="Notes" />);+ const textbox = screen.getByRole('textbox');+ expect(textbox).toHaveAttribute('contenteditable', 'true');+ expect(textbox).not.toHaveAttribute('aria-readonly');+ });++ it("keeps Lexical's read-only announcement when a plugin disables editing", () => {+ let captured: LexicalEditor | null = null;+ render(+ <RichTextEditor+ label="Notes"+ plugins={<CaptureEditor onReady={editor => (captured = editor)} />}+ />,+ );+ act(() => {+ (captured as unknown as LexicalEditor).setEditable(false);+ });+ const textbox = screen.getByRole('textbox');+ expect(textbox).toHaveAttribute('contenteditable', 'false');+ // Neither prop is set, so the component must not clobber Lexical's own+ // state-derived aria-readonly with undefined.+ expect(textbox).toHaveAttribute('aria-readonly', 'true');+ });++ it('keeps a plugin that disables editing during mount in charge', () => {+ // The prop sync renders after `plugins`, so its mount effect runs after+ // theirs; it must only react to prop changes, never re-assert the mount+ // value over a plugin that already locked the editor.+ function DisableOnMount() {+ const [editor] = useLexicalComposerContext();+ useEffect(() => {+ editor.setEditable(false);+ }, [editor]);+ return null;+ }+ let captured: LexicalEditor | null = null;+ render(+ <RichTextEditor+ label="Notes"+ plugins={+ <>+ <DisableOnMount />+ <CaptureEditor onReady={editor => (captured = editor)} />+ </>+ }+ />,+ );+ expect((captured as unknown as LexicalEditor).isEditable()).toBe(false);+ expect(screen.getByRole('textbox')).toHaveAttribute(+ 'contenteditable',+ 'false',+ );+ });+});++describe('isReadOnly + isDisabled combined', () => {+ it('lets disabled win everywhere when both flags are set', () => {+ const {container} = render(+ <RichTextEditor label="Notes" isReadOnly isDisabled />,+ );+ const textbox = screen.getByRole('textbox');+ expect(textbox).toHaveAttribute('contenteditable', 'false');+ // Disabled semantics take precedence: announced disabled, never+ // read-only, and out of the tab order.+ expect(textbox).toHaveAttribute('aria-disabled', 'true');+ expect(textbox).not.toHaveAttribute('aria-readonly');+ expect(textbox).not.toHaveAttribute('tabindex', '0');+ const wrapper = container.querySelector('.astryx-rich-text-editor');+ expect(wrapper).not.toBeNull();+ expect(getComputedStyle(wrapper as Element).opacity).toBe('0.5');+ });++ it('swaps disabled semantics for read-only semantics on rerender', () => {+ const {container, rerender} = render(+ <RichTextEditor label="Notes" isDisabled />,+ );+ expect(screen.getByRole('textbox')).toHaveAttribute(+ 'aria-disabled',+ 'true',+ );++ rerender(<RichTextEditor label="Notes" isReadOnly />);+ const textbox = screen.getByRole('textbox');+ // Still non-editable, but the announcement and reachability flip from+ // disabled to read-only.+ expect(textbox).toHaveAttribute('contenteditable', 'false');+ expect(textbox).not.toHaveAttribute('aria-disabled');+ expect(textbox).toHaveAttribute('aria-readonly', 'true');+ expect(textbox).toHaveAttribute('tabindex', '0');+ // jsdom computes unset opacity as '' rather than '1', so assert the+ // dimmed rule no longer applies.+ const wrapper = container.querySelector('.astryx-rich-text-editor');+ expect(wrapper).not.toBeNull();+ expect(getComputedStyle(wrapper as Element).opacity).not.toBe('0.5');+ });+});++describe('imperative ref across editable prop toggles', () => {+ stubRangeRects();++ it('unlocks focus() once isDisabled is removed', async () => {+ const ref = createRef<RichTextEditorRef>();+ const {rerender} = render(+ <RichTextEditor ref={ref} label="Notes" isDisabled />,+ );+ const disabledTextbox = screen.getByRole('textbox');+ expect(disabledTextbox).toHaveAttribute('contenteditable', 'false');++ // While disabled, focus() is gated: no caret is placed in the editor.+ ref.current?.focus();+ await new Promise(resolve => setTimeout(resolve, 0));+ expect(document.activeElement).toBe(document.body);+ expect(+ disabledTextbox.contains(window.getSelection()?.anchorNode ?? null),+ ).toBe(false);++ rerender(<RichTextEditor ref={ref} label="Notes" />);+ const textbox = screen.getByRole('textbox');+ // The setEditable sync re-enables the surface, not just its styling.+ expect(textbox).toHaveAttribute('contenteditable', 'true');++ // Lexical focuses by placing the DOM selection inside the+ // contenteditable; jsdom does not move document.activeElement with it,+ // so assert the observable outcome: the caret lands in the textbox.+ ref.current?.focus();+ await waitFor(() => {+ const anchorNode = window.getSelection()?.anchorNode ?? null;+ expect(anchorNode).not.toBeNull();+ expect(textbox.contains(anchorNode)).toBe(true);+ });+ });+});++describe('read-only keyboard traversal (WCAG 2.1.2)', () => {+ it('lets Tab leave a read-only editor without the Escape step', async () => {+ const user = userEvent.setup();+ render(+ <>+ <button type="button">before</button>+ <RichTextEditor label="Notes" isReadOnly />+ <button type="button">after</button>+ </>,+ );++ screen.getByRole('button', {name: 'before'}).focus();+ await user.tab();+ expect(document.activeElement).toBe(screen.getByRole('textbox'));++ // A non-editable editor renders no Tab-escape hint, so there must be no+ // trap to escape: a bare Tab moves on.+ await user.tab();+ expect(document.activeElement).toBe(+ screen.getByRole('button', {name: 'after'}),+ );+ });++ it('skips a disabled editor entirely', async () => {+ const user = userEvent.setup();+ render(+ <>+ <button type="button">before</button>+ <RichTextEditor label="Notes" isDisabled />+ <button type="button">after</button>+ </>,+ );+ screen.getByRole('button', {name: 'before'}).focus();+ await user.tab();+ expect(document.activeElement).toBe(+ screen.getByRole('button', {name: 'after'}),+ );+ });+});++describe('toolbar follows the editable props after mount', () => {+ // The extension's `editable` is applied only when the composer builds the+ // editor, so without the setEditable sync the toolbar would stay at its+ // mount state while the wrapper styling and ARIA followed the props.+ it('re-enables and re-disables the formatting controls on rerender', () => {+ const {rerender} = render(+ <RichTextEditor+ label="Notes"+ isDisabled+ toolbar={<RichTextEditorToolbar />}+ />,+ );+ expect(screen.getByRole('button', {name: 'Bold'})).toBeDisabled();++ rerender(+ <RichTextEditor label="Notes" toolbar={<RichTextEditorToolbar />} />,+ );+ expect(screen.getByRole('button', {name: 'Bold'})).toBeEnabled();++ rerender(+ <RichTextEditor+ label="Notes"+ isReadOnly+ toolbar={<RichTextEditorToolbar />}+ />,+ );+ expect(screen.getByRole('button', {name: 'Bold'})).toBeDisabled();+ });+});diff --git a/packages/richtext/src/RichTextEditor.tsx b/packages/richtext/src/RichTextEditor.tsxindex 9bed8f0947..f0d153f116 100644--- a/packages/richtext/src/RichTextEditor.tsx+++ b/packages/richtext/src/RichTextEditor.tsx@@ -8,7 +8,8 @@* LexicalExtensionComposer), Field, VisuallyHidden, useInputStatusIcon,* mergeProps, design tokens* @output Exports an accessibly labelled RichTextEditor component with a flush- * top toolbar slot and configurable editable-surface minimum height, RichTextEditorProps,+ * top toolbar slot, configurable editable-surface minimum height, and distinct+ * read-only and disabled states that follow prop changes, RichTextEditorProps,* RichTextEditorStatus, RichTextEditorStatusType, RichTextEditorSize* @position Experimental (richtext) implementation; consumed by the package index.ts and* re-exported from @astryxdesign/richtext. Tested by RichTextEditor.test.tsx.@@ -330,12 +331,16 @@ export interface RichTextEditorProps extends Omit</** Placeholder text shown when the editor is empty. */placeholder?: string;/**- * Whether the editor is read-only (non-editable).+ * Whether the editor is read-only (non-editable). The content stays at full+ * opacity, in the tab order, and announced as read-only, so people can still+ * reach, read, and copy it. Takes effect when changed after mount.* @default false*/isReadOnly?: boolean;/**- * Whether the editor is disabled (non-editable, dimmed).+ * Whether the editor is disabled: non-editable, dimmed, out of the tab+ * order, and announced as disabled. Wins when `isReadOnly` is also set.+ * Takes effect when changed after mount.* @default false*/isDisabled?: boolean;@@ -616,7 +621,9 @@ export const RichTextEditor = forwardRef<stylex.props(inputWrapperStyles.base,styles.wrapper,- (isDisabled || isReadOnly) && inputWrapperStyles.disabled,+ // Only disabled is dimmed, matching TextArea: a read-only editor+ // keeps full-opacity text and stays keyboard-reachable.+ isDisabled && inputWrapperStyles.disabled,isDisabled && styles.disabled,status && inputStatusBorderStyles[status.type],status &&@@ -650,6 +657,8 @@ export const RichTextEditor = forwardRef<ariaDescribedBy={ariaDescribedBy}ariaRequired={isRequired && !isOptional}ariaInvalid={status?.type === 'error'}+ isReadOnly={isReadOnly}+ isDisabled={isDisabled}placeholderText={placeholder}placeholderID={placeholderID}minHeight={minHeight}@@ -835,6 +844,23 @@ function EditorRefBridge({transformers: Array<Transformer>;}): null {const [editor] = useLexicalComposerContext();++ // The extension applies `editable` once, when the composer builds the+ // editor, so a later isReadOnly/isDisabled change would leave+ // contenteditable at its mount value while the wrapper styling and ARIA+ // follow the props. Sync the editor on a prop change only: the mount value+ // is already applied, and this bridge renders after `plugins`, so+ // re-asserting it on mount would undo a plugin that set editability during+ // its own mount.+ const syncedEditableRef = useRef(editable);+ useEffect(() => {+ if (syncedEditableRef.current === editable) {+ return;+ }+ syncedEditableRef.current = editable;+ editor.setEditable(editable);+ }, [editor, editable]);+useImperativeHandle(editorRef,() => ({@@ -918,6 +944,8 @@ function EditorContentEditable({ariaDescribedBy,ariaRequired,ariaInvalid,+ isReadOnly,+ isDisabled,placeholderText,placeholderID,minHeight,@@ -929,6 +957,8 @@ function EditorContentEditable({ariaDescribedBy?: string;ariaRequired: boolean;ariaInvalid: boolean;+ isReadOnly: boolean;+ isDisabled: boolean;placeholderText?: string;placeholderID: string;minHeight: SizeValue;@@ -943,6 +973,18 @@ function EditorContentEditable({'aria-describedby': ariaDescribedBy,'aria-required': ariaRequired ? ('true' as const) : undefined,'aria-invalid': ariaInvalid ? ('true' as const) : undefined,+ // Lexical announces every non-editable surface as aria-readonly and+ // leaves it out of the tab order. Split the two states: read-only stays+ // reachable and is announced read-only; disabled is announced disabled+ // instead. These keys land after Lexical's computed attributes, so the+ // disabled branch's explicit `undefined` removes the wrong read-only+ // announcement. With neither prop set no keys are passed, so a plugin+ // that drives editor.setEditable keeps Lexical's own aria-readonly.+ ...(isDisabled+ ? {'aria-disabled': 'true' as const, 'aria-readonly': undefined}+ : isReadOnly+ ? {tabIndex: 0, 'aria-readonly': 'true' as const}+ : null),...stylex.props(styles.contentEditable,dynamicStyles.contentEditableMinHeight(minHeight),