Skip to content

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

TypeScript

fix(richtext): give table columns core Markdown's readable width floors (#7005)

Cindy Zhangca77025847ba
diff --git a/packages/richtext/src/RichTextEditor.tsx b/packages/richtext/src/RichTextEditor.tsx
index 015d72b432..d38190fe25 100644
--- a/packages/richtext/src/RichTextEditor.tsx
+++ b/packages/richtext/src/RichTextEditor.tsx
@@ -73,6 +73,7 @@ import {MarkdownShortcutPlugin} from '@lexical/react/LexicalMarkdownShortcutPlug
import {OnChangePlugin} from '@lexical/react/LexicalOnChangePlugin';
import {TablePlugin} from '@lexical/react/LexicalTablePlugin';
import {HorizontalRuleExtension} from '@lexical/extension';
+import {TableColumnFloorPlugin} from './TableColumnFloorPlugin';
import {type Transformer} from '@lexical/markdown';
export type {Transformer} from '@lexical/markdown';
import {$generateHtmlFromNodes} from '@lexical/html';
@@ -686,6 +687,7 @@ export const RichTextEditor = forwardRef<
hasTabHandler={false}
hasHorizontalScroll
/>
+ <TableColumnFloorPlugin />
<TabIndentationPlugin />
<TabFocusEscapePlugin />
{hasMarkdownShortcuts && (
diff --git a/packages/richtext/src/RichTextView.tsx b/packages/richtext/src/RichTextView.tsx
index f7d7fd3cec..607bc5bfa2 100644
--- a/packages/richtext/src/RichTextView.tsx
+++ b/packages/richtext/src/RichTextView.tsx
@@ -31,6 +31,7 @@ import {ContentEditable} from '@lexical/react/LexicalContentEditable';
import {LexicalErrorBoundary} from '@lexical/react/LexicalErrorBoundary';
import {TablePlugin} from '@lexical/react/LexicalTablePlugin';
import {TableScrollRegionPlugin} from './TableScrollRegionPlugin';
+import {TableColumnFloorPlugin} from './TableColumnFloorPlugin';
import type {
AnyLexicalExtension,
Klass,
@@ -278,6 +279,7 @@ export function RichTextView({
hasHorizontalScroll
/>
<TableScrollRegionPlugin />
+ <TableColumnFloorPlugin />
<RichTextPlugin
contentEditable={<ContentEditable {...VIEW_CONTENT_EDITABLE_PROPS} />}
placeholder={null}
diff --git a/packages/richtext/src/TableColumnFloorPlugin.test.tsx b/packages/richtext/src/TableColumnFloorPlugin.test.tsx
new file mode 100644
index 0000000000..a25043b473
--- /dev/null
+++ b/packages/richtext/src/TableColumnFloorPlugin.test.tsx
@@ -0,0 +1,49 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect} from 'vitest';
+import {render, waitFor} from '@testing-library/react';
+import {RichTextEditor} from './RichTextEditor';
+import {RichTextView} from './RichTextView';
+import {markdownToEditorStateJSON} from './markdownSerializers';
+import {tableColumnFloors} from './TableColumnFloorPlugin';
+
+describe('table column floors (spec:AST-061 FR4)', () => {
+ it('lets the longest cell wrap to two lines, keeps a header on one line up to a cap, and stays bounded', () => {
+ expect(
+ tableColumnFloors([
+ // Header lengths, then body rows.
+ [4, 29, 2, 3],
+ [22, 5, 1, 120],
+ ]),
+ ).toEqual([
+ // 22 / 2 = 11
+ 11,
+ // header capped at 20, body 5/2 → 20
+ 20,
+ // the 4ch minimum
+ 4,
+ // 120 / 2 = 60, capped at 24
+ 24,
+ ]);
+ expect(tableColumnFloors([])).toEqual([]);
+ });
+
+ it('sets the floors on the header cells in the editor and the view', async () => {
+ const value = markdownToEditorStateJSON(
+ '| Name | Notes |\n| --- | --- |\n| Ada | Wrote the first published program |\n',
+ );
+ const {container} = render(
+ <>
+ <RichTextEditor label="Notes" defaultValue={value} />
+ <RichTextView value={value} />
+ </>,
+ );
+ await waitFor(() => {
+ const headers = [...container.querySelectorAll('th')];
+ expect(headers).toHaveLength(4);
+ expect(
+ headers.map(header => (header as HTMLElement).style.minWidth),
+ ).toEqual(['4ch', '17ch', '4ch', '17ch']);
+ });
+ });
+});
diff --git a/packages/richtext/src/TableColumnFloorPlugin.tsx b/packages/richtext/src/TableColumnFloorPlugin.tsx
new file mode 100644
index 0000000000..9af5d61c93
--- /dev/null
+++ b/packages/richtext/src/TableColumnFloorPlugin.tsx
@@ -0,0 +1,99 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file TableColumnFloorPlugin.tsx
+ * @input Uses @lexical/react (composer context), @lexical/table, and lexical.
+ * @output Exports TableColumnFloorPlugin, which gives each table column core
+ * Markdown's readable width floor, and tableColumnFloors, the rule itself.
+ * @position Rendered by RichTextEditor and RichTextView. Matches core
+ * Markdown's table column floors (spec:AST-061 FR4): automatic table layout
+ * already keeps every column at least as wide as its longest word, but a
+ * prose column's longest word is short, so a narrow table still wraps one
+ * word per line. The floor lets a column's longest cell wrap to about two
+ * lines instead, keeps a header label on one line up to a cap, and stays
+ * bounded so a table of short columns still fits; a wider table scrolls
+ * inside its wrapper. The floors are `ch` on content-box cells, so they
+ * follow the reader's font size and cell padding does not eat into them.
+ */
+
+import {useEffect} from 'react';
+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
+import {$isTableCellNode, $isTableNode, $isTableRowNode} from '@lexical/table';
+import {$getRoot} from 'lexical';
+
+const TABLE_COLUMN_MIN_CH = 4;
+const TABLE_COLUMN_MAX_CH = 24;
+const TABLE_COLUMN_TARGET_LINES = 2;
+const TABLE_HEADER_ONE_LINE_MAX_CH = 20;
+
+/**
+ * Each column's floor in `ch`, from the text length of every cell, header row
+ * first: the longest cell wraps to about two lines, the header reads on one
+ * line up to its cap, and every floor stays between the bounds.
+ */
+export function tableColumnFloors(
+ rows: ReadonlyArray<ReadonlyArray<number>>,
+): Array<number> {
+ const [header, ...body] = rows;
+ if (header == null) {
+ return [];
+ }
+ return header.map((headerLength, column) => {
+ const longest = Math.max(
+ headerLength,
+ ...body.map(row => row[column] ?? 0),
+ );
+ const bodyFloor = Math.ceil(longest / TABLE_COLUMN_TARGET_LINES);
+ const headerFloor = Math.min(headerLength, TABLE_HEADER_ONE_LINE_MAX_CH);
+ return Math.min(
+ TABLE_COLUMN_MAX_CH,
+ Math.max(TABLE_COLUMN_MIN_CH, bodyFloor, headerFloor),
+ );
+ });
+}
+
+/**
+ * Sets each top-level table's header cells to their column's floor after
+ * every update, so the floors follow edits.
+ */
+export function TableColumnFloorPlugin(): null {
+ const [editor] = useLexicalComposerContext();
+ useEffect(() => {
+ let frame = 0;
+ const apply = () => {
+ frame = 0;
+ editor.getEditorState().read(() => {
+ for (const table of $getRoot().getChildren().filter($isTableNode)) {
+ const rows = table
+ .getChildren()
+ .filter($isTableRowNode)
+ .map(row => row.getChildren().filter($isTableCellNode));
+ const floors = tableColumnFloors(
+ rows.map(cells => cells.map(cell => cell.getTextContentSize())),
+ );
+ rows[0]?.forEach((cell, column) => {
+ const element = editor.getElementByKey(cell.getKey());
+ const floor = `${floors[column]}ch`;
+ if (element != null && element.style.minWidth !== floor) {
+ element.style.minWidth = floor;
+ }
+ });
+ }
+ });
+ };
+ const schedule = () => {
+ if (frame === 0) {
+ frame = requestAnimationFrame(apply);
+ }
+ };
+ const unregister = editor.registerUpdateListener(schedule);
+ schedule();
+ return () => {
+ cancelAnimationFrame(frame);
+ unregister();
+ };
+ }, [editor]);
+ return null;
+}
diff --git a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts
index d396551352..de6704a300 100644
--- a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts
+++ b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts
@@ -410,10 +410,37 @@ for (const viewport of [PHONE, {width: 1280, height: 900}] as const) {
.filter(element => element.getBoundingClientRect().width > 0)
.map(element => {
const wrapper = element.parentElement as HTMLElement;
+ // The table's own width: its max-content width, measured
+ // with the inline width restored right after.
+ const previousWidth = element.style.width;
+ let intrinsic: number;
+ try {
+ element.style.width = 'max-content';
+ intrinsic = element.getBoundingClientRect().width;
+ } finally {
+ element.style.width = previousWidth;
+ }
+ // The widest the wrapper could be: the view's containing
+ // block, less the space between the view's edge and the
+ // wrapper.
+ const view = element.closest('[contenteditable]')
+ ?.parentElement as HTMLElement | null;
+ const host = view?.parentElement;
+ const hostStyle = host == null ? null : getComputedStyle(host);
+ const available =
+ host == null || hostStyle == null || view == null
+ ? 0
+ : host.clientWidth -
+ parseFloat(hostStyle.paddingLeft) -
+ parseFloat(hostStyle.paddingRight) -
+ (view.offsetWidth - wrapper.clientWidth);
return {
inView: element.closest('[contenteditable="false"]') != null,
clientWidth: wrapper.clientWidth,
scrollWidth: wrapper.scrollWidth,
+ intrinsic,
+ available,
+ restored: element.style.width === previousWidth,
};
}),
}));
@@ -439,11 +466,27 @@ for (const viewport of [PHONE, {width: 1280, height: 900}] as const) {
);
}
}
- if (columnCount === 2 && styles.view !== '') {
- // A shrink-to-fit host gives the view's small table its natural
- // width instead of stretching or collapsing it.
+ for (const wrapper of layout.wrappers) {
+ // Measuring the table left its style as it was.
+ expect(wrapper.restored, label).toBe(true);
+ }
+ if (styles.view !== '') {
+ // A shrink-to-fit host gives the view's table its natural width,
+ // up to the room it has: neither stretched nor collapsed. A small
+ // table is narrower than the room, so stretching it fails here.
const view = layout.wrappers.find(wrapper => wrapper.inView);
- expect(view?.clientWidth, label).toBeLessThan(viewport.width / 2);
+ if (columnCount === 2) {
+ expect(view?.intrinsic ?? 0, label).toBeLessThan(
+ (view?.available ?? 0) - 8,
+ );
+ }
+ expect(
+ Math.abs(
+ (view?.clientWidth ?? 0) -
+ Math.min(view?.intrinsic ?? 0, view?.available ?? 0),
+ ),
+ label,
+ ).toBeLessThanOrEqual(1);
}
}
}
@@ -523,6 +566,10 @@ test('side by side: shared blocks match core Markdown typography, spacing, and m
};
})(),
rule: styleOf(block('thematic-break', 'hr')),
+ // Each column's readable width floor, set on its header cell.
+ tableFloors: [
+ ...(block('table', 'table')?.querySelectorAll('th') ?? []),
+ ].map(cell => getComputedStyle(cell).minWidth),
// The text inside a header cell, where each surface draws it.
tableHeader: (() => {
const cell = block('table', 'table')?.querySelector('th');
@@ -567,6 +614,9 @@ test('side by side: shared blocks match core Markdown typography, spacing, and m
markdown.rule?.[property],
);
}
+ expect(richText.tableFloors, 'table column floors').toEqual(
+ markdown.tableFloors,
+ );
expect(richText.tableHeader, 'table header text').toEqual(
markdown.tableHeader,
);
diff --git a/packages/richtext/src/editorTheme.ts b/packages/richtext/src/editorTheme.ts
index 17856ab043..e2c370b760 100644
--- a/packages/richtext/src/editorTheme.ts
+++ b/packages/richtext/src/editorTheme.ts
@@ -316,6 +316,9 @@ const editorTheme = stylex.create({
},
},
tableCell: {
+ // Column floors (TableColumnFloorPlugin) size the text box, not the
+ // padding, as in core Markdown's tables.
+ boxSizing: 'content-box',
paddingBlock: spacingVars['--spacing-2'],
paddingInline: spacingVars['--spacing-2'],
textAlign: 'start',