Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(richtext): RichTextView table scroll regions take a tab stop while they overflow (#6990)

Cindy Zhang4c503212111c
diff --git a/packages/richtext/src/RichTextView.tsx b/packages/richtext/src/RichTextView.tsx
index 5f8056bd13..c7ed1cbe1a 100644
--- a/packages/richtext/src/RichTextView.tsx
+++ b/packages/richtext/src/RichTextView.tsx
@@ -5,7 +5,8 @@
/**
* @file RichTextView.tsx
* @input Uses React, Lexical (lexical + @lexical/react, composed through
- * LexicalExtensionComposer), mergeProps from core utils, design tokens
+ * LexicalExtensionComposer), mergeProps from core utils, design tokens,
+ * TableScrollRegionPlugin
* @output Exports RichTextView component and RichTextViewProps
* @position Read-only renderer for serialized Lexical editor state, exposed to
* assistive technology as document content rather than a form field;
@@ -34,6 +35,7 @@ import {HeadingNode, QuoteNode} from '@lexical/rich-text';
import {LinkNode, AutoLinkNode} from '@lexical/link';
import {CodeNode, CodeHighlightNode} from '@lexical/code';
import {TableNode, TableRowNode, TableCellNode} from '@lexical/table';
+import {TableScrollRegionPlugin} from './TableScrollRegionPlugin';
import type {
AnyLexicalExtension,
Klass,
@@ -169,7 +171,9 @@ function SyncValuePlugin({value}: {value: string}): null {
*
* The output is document content, not a form field: headings, lists and links
* keep their own roles for assistive technology, and the view takes no label.
- * For a labelled, read-only field, use `<RichTextEditor isReadOnly />`.
+ * For a labelled, read-only field, use `<RichTextEditor isReadOnly />`. A
+ * table wider than the view scrolls inside a region named "Table" that takes a
+ * tab stop while it overflows, as core `Table` does.
*
* @example
* ```
@@ -290,6 +294,7 @@ export function RichTextView({
hasTabHandler={false}
hasHorizontalScroll
/>
+ <TableScrollRegionPlugin />
<RichTextPlugin
contentEditable={<ContentEditable {...VIEW_CONTENT_EDITABLE_PROPS} />}
placeholder={null}
diff --git a/packages/richtext/src/TableScrollRegionPlugin.test.tsx b/packages/richtext/src/TableScrollRegionPlugin.test.tsx
new file mode 100644
index 0000000000..06531ce156
--- /dev/null
+++ b/packages/richtext/src/TableScrollRegionPlugin.test.tsx
@@ -0,0 +1,138 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file TableScrollRegionPlugin.test.tsx
+ * @input Uses vitest, @testing-library/react, RichTextView, RichTextEditor and
+ * the Markdown serializer, with a controllable ResizeObserver
+ * @output Tests that a table's scroll wrapper in RichTextView is a named group
+ * that takes a tab stop only while the table overflows it, and that the
+ * editor's wrapper is left alone
+ * @position Testing; validates TableScrollRegionPlugin.tsx through RichTextView
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {act, render, waitFor} from '@testing-library/react';
+import {RichTextEditor} from './RichTextEditor';
+import {RichTextView} from './RichTextView';
+import {markdownToEditorStateJSON} from './markdownSerializers';
+
+const TABLE = markdownToEditorStateJSON(
+ '| Name | Role |\n| --- | --- |\n| Ada | Engineer |',
+);
+
+/** jsdom has no ResizeObserver; this one lets a test fire a resize. */
+const observers: Array<{callback: () => void; targets: Set<Element>}> = [];
+
+class TestResizeObserver {
+ private readonly entry: {callback: () => void; targets: Set<Element>};
+ constructor(callback: () => void) {
+ this.entry = {callback, targets: new Set()};
+ observers.push(this.entry);
+ }
+ observe(target: Element) {
+ this.entry.targets.add(target);
+ }
+ unobserve(target: Element) {
+ this.entry.targets.delete(target);
+ }
+ disconnect() {
+ this.entry.targets.clear();
+ }
+}
+
+function resize(element: Element) {
+ act(() => {
+ for (const observer of observers) {
+ if (observer.targets.has(element)) {
+ observer.callback();
+ }
+ }
+ });
+}
+
+/** jsdom lays nothing out, so widths are set by hand. */
+function setWidths(element: Element, scrollWidth: number, clientWidth: number) {
+ Object.defineProperty(element, 'scrollWidth', {
+ configurable: true,
+ value: scrollWidth,
+ });
+ Object.defineProperty(element, 'clientWidth', {
+ configurable: true,
+ value: clientWidth,
+ });
+}
+
+async function scrollWrapper(container: HTMLElement): Promise<HTMLElement> {
+ // TablePlugin re-renders existing tables into the wrapper after mount.
+ let wrapper: HTMLElement | null = null;
+ await waitFor(() => {
+ wrapper = container.querySelector('table')?.parentElement ?? null;
+ expect(wrapper?.tagName).toBe('DIV');
+ expect(wrapper?.getAttribute('contenteditable')).toBeNull();
+ });
+ return wrapper as unknown as HTMLElement;
+}
+
+describe('table scroll regions', () => {
+ beforeEach(() => {
+ observers.length = 0;
+ vi.stubGlobal('ResizeObserver', TestResizeObserver);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('names the table scroll region in RichTextView like core Table', async () => {
+ const {container} = render(<RichTextView value={TABLE} />);
+ const wrapper = await scrollWrapper(container);
+ await waitFor(() => {
+ expect(wrapper.getAttribute('role')).toBe('group');
+ });
+ expect(wrapper.getAttribute('aria-label')).toBe('Table');
+ });
+
+ it('adds a tab stop only while the table overflows its region', async () => {
+ const {container} = render(<RichTextView value={TABLE} />);
+ const wrapper = await scrollWrapper(container);
+ await waitFor(() => {
+ expect(wrapper.getAttribute('role')).toBe('group');
+ });
+ // A table that fits adds no stop.
+ expect(wrapper.hasAttribute('tabindex')).toBe(false);
+
+ setWidths(wrapper, 900, 340);
+ resize(wrapper);
+ expect(wrapper.getAttribute('tabindex')).toBe('0');
+
+ setWidths(wrapper, 340, 340);
+ resize(wrapper);
+ expect(wrapper.hasAttribute('tabindex')).toBe(false);
+ });
+
+ it('follows a table whose content grows', async () => {
+ const {container} = render(<RichTextView value={TABLE} />);
+ const wrapper = await scrollWrapper(container);
+ await waitFor(() => {
+ expect(wrapper.getAttribute('role')).toBe('group');
+ });
+ const table = wrapper.querySelector('table');
+ expect(table).not.toBeNull();
+
+ setWidths(wrapper, 900, 340);
+ resize(table as HTMLTableElement);
+ expect(wrapper.getAttribute('tabindex')).toBe('0');
+ });
+
+ it('leaves the editor’s table wrapper alone, so Escape then Tab still leaves the editor', async () => {
+ const {container} = render(
+ <RichTextEditor label="Notes" defaultValue={TABLE} />,
+ );
+ const wrapper = await scrollWrapper(container);
+ setWidths(wrapper, 900, 340);
+ resize(wrapper);
+ expect(wrapper.hasAttribute('role')).toBe(false);
+ expect(wrapper.hasAttribute('aria-label')).toBe(false);
+ expect(wrapper.hasAttribute('tabindex')).toBe(false);
+ });
+});
diff --git a/packages/richtext/src/TableScrollRegionPlugin.tsx b/packages/richtext/src/TableScrollRegionPlugin.tsx
new file mode 100644
index 0000000000..93a670845e
--- /dev/null
+++ b/packages/richtext/src/TableScrollRegionPlugin.tsx
@@ -0,0 +1,107 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file TableScrollRegionPlugin.tsx
+ * @input Lexical's TableNode mutations, the scroll wrapper that TablePlugin's
+ * horizontal-scroll mode renders around each table, and core's translator
+ * for the region's name.
+ * @output TableScrollRegionPlugin: gives each table's scroll wrapper the
+ * semantics of core Table's scroll region.
+ * @position Internal to @astryxdesign/richtext; rendered by RichTextView only.
+ * The editor needs none of this: its caret scrolls a wide table, and a tab
+ * stop inside the editable surface would break Escape-then-Tab.
+ */
+
+import {useEffect} from 'react';
+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
+import {TableNode} from '@lexical/table';
+import {useTranslator} from '@astryxdesign/core/i18n';
+
+interface TrackedRegion {
+ readonly wrapper: HTMLElement;
+ readonly observer: ResizeObserver | null;
+}
+
+/** A tab stop only while the table is wider than its wrapper. */
+function syncTabStop(wrapper: HTMLElement): void {
+ if (wrapper.scrollWidth > wrapper.clientWidth) {
+ wrapper.tabIndex = 0;
+ } else {
+ wrapper.removeAttribute('tabindex');
+ }
+}
+
+/**
+ * A read-only view has no caret, so nothing inside a wide table can scroll it
+ * from the keyboard. Like core Table's scroll region, each table's wrapper is
+ * a group named "Table" that takes a tab stop only while the table overflows
+ * it; a table that fits adds no stop. The tab stop is explicit, so browsers
+ * that do not make scroll containers focusable on their own still reach it.
+ */
+export function TableScrollRegionPlugin(): null {
+ const [editor] = useLexicalComposerContext();
+ const t = useTranslator();
+ const label = t('@astryx.table.label');
+
+ useEffect(() => {
+ const regions = new Map<string, TrackedRegion>();
+
+ const release = (key: string) => {
+ regions.get(key)?.observer?.disconnect();
+ regions.delete(key);
+ };
+
+ const track = (key: string) => {
+ // With horizontal scroll active, a table node's DOM is its wrapper.
+ const wrapper = editor.getElementByKey(key);
+ if (!(wrapper instanceof HTMLDivElement)) {
+ release(key);
+ return;
+ }
+ if (regions.get(key)?.wrapper === wrapper) {
+ syncTabStop(wrapper);
+ return;
+ }
+ release(key);
+ wrapper.setAttribute('role', 'group');
+ wrapper.setAttribute('aria-label', label);
+ let observer: ResizeObserver | null = null;
+ if (typeof ResizeObserver !== 'undefined') {
+ observer = new ResizeObserver(() => syncTabStop(wrapper));
+ // The wrapper resizes with its container, the table with its content.
+ observer.observe(wrapper);
+ const table = wrapper.querySelector(':scope > table');
+ if (table != null) {
+ observer.observe(table);
+ }
+ }
+ regions.set(key, {wrapper, observer});
+ syncTabStop(wrapper);
+ };
+
+ const unregister = editor.registerMutationListener(
+ TableNode,
+ mutations => {
+ for (const [key, mutation] of mutations) {
+ if (mutation === 'destroyed') {
+ release(key);
+ } else {
+ track(key);
+ }
+ }
+ },
+ {skipInitialization: false},
+ );
+
+ return () => {
+ unregister();
+ for (const key of [...regions.keys()]) {
+ release(key);
+ }
+ };
+ }, [editor, label]);
+
+ return null;
+}