Skip to content

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

TypeScript

fix(Markdown): keep table columns at a content-derived width floor (#6708)

nynexman4464287212abc41a
diff --git a/.changeset/markdown-table-narrow-columns.md b/.changeset/markdown-table-narrow-columns.md
new file mode 100644
index 0000000000..604abc0314
--- /dev/null
+++ b/.changeset/markdown-table-narrow-columns.md
@@ -0,0 +1,16 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Markdown: table columns keep a content-derived width floor and headers stop truncating.
+
+A Markdown table in a narrow reading column no longer squashes every column to a
+few characters. Each column keeps a floor derived from its own content, measured
+in characters on the cell's text box, so a column is never narrower than its
+longest unbreakable token and cell padding does not eat into the floor.
+Identifiers, URLs, and inline code stay whole, header labels wrap instead of
+ellipsizing, and a table that is genuinely wider than its container scrolls in
+Table's own scroll region — which is now the table's only scroll viewport,
+accessible name, and keyboard stop.
+
+@nynexman4464
diff --git a/apps/storybook/stories/Markdown.stories.tsx b/apps/storybook/stories/Markdown.stories.tsx
index 06be80be1a..65e96229cb 100644
--- a/apps/storybook/stories/Markdown.stories.tsx
+++ b/apps/storybook/stories/Markdown.stories.tsx
@@ -4,6 +4,11 @@ import {useCallback, useEffect, useMemo, useState} from 'react';
import type {Meta, StoryObj} from '@storybook/react';
import {Markdown} from '@astryxdesign/core/Markdown';
import type {MarkdownComponents} from '@astryxdesign/core/Markdown';
+import {
+ ChatMessageList,
+ ChatMessage,
+ ChatMessageBubble,
+} from '@astryxdesign/core/Chat';
import {markdownSoftBreaksPlugin} from '@astryxdesign/core/Markdown/plugins';
import {Button} from '@astryxdesign/core/Button';
import {Link} from '@astryxdesign/core/Link';
@@ -254,6 +259,288 @@ export const TableFocused: Story = {
},
};
+/**
+ * Narrow-width table states.
+ *
+ * `width` is a control so one story covers the reading widths that matter:
+ * 320 and 390 are phone-sized reading columns, 528 is a side panel, and 1024
+ * is a roomy document. Density stays at the component default.
+ */
+const NARROW_WIDTH_ARG_TYPES = {
+ width: {
+ control: 'select' as const,
+ options: ['320', '390', '528', '1024'],
+ description: 'Width of the reading column the table renders inside, in px',
+ },
+};
+
+/** Six short columns: the table that must fit, not scroll, in a narrow column. */
+const SHORT_SIX_COLUMN_TABLE = [
+ '| Step | Time | Code | Tier | Runs | Team |',
+ '|---|---|---|---|---|---|',
+ '| Init | 12 ms | 200 | A | 3 | Core |',
+ '| Sync | 84 ms | 200 | A | 1 | Core |',
+ '| Lint | 2.1 s | 422 | B | 2 | Docs |',
+ '| Ship | 9.4 s | 200 | A | 1 | Docs |',
+].join('\n');
+
+/**
+ * Genuinely wide content: unbreakable identifiers, a long URL, inline code,
+ * and a long header over a short body column. This one is meant to scroll —
+ * in Table's Scroll region, with its tokens whole and its headers readable.
+ */
+const WIDE_TOKEN_TABLE = [
+ '| Identifier | Endpoint | Status | Accessibility status and remediation owner |',
+ '|---|---|---|---|',
+ '| D116586407 | https://example.com/v2/pipelines/build/runs/1284/logs | `needs_revision_before_landing_v2` | Pass |',
+ '| D116586999 | https://example.com/v2/pipelines/docs/runs/97/logs | `ContentNegotiationMiddleware` | Review |',
+].join('\n');
+
+function ReadingColumn({width, children}: {width: string; children: string}) {
+ return (
+ <div
+ style={{
+ width: Number(width),
+ maxWidth: '100%',
+ padding: 12,
+ outline: '1px dashed #c33',
+ }}>
+ <Markdown>{children}</Markdown>
+ </div>
+ );
+}
+
+export const TableNarrowShortColumns: StoryObj<{width: string}> = {
+ name: 'Table — six short columns',
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Six short columns fit the reading column instead of squashing. Each column keeps a content-derived floor in `ch` on its text box, so the floor means the same number of characters whatever the cell padding is, and a table this narrow never needs to scroll.',
+ },
+ },
+ },
+ argTypes: NARROW_WIDTH_ARG_TYPES,
+ args: {width: '390'},
+ render: ({width}) => (
+ <ReadingColumn width={width}>{SHORT_SIX_COLUMN_TABLE}</ReadingColumn>
+ ),
+};
+
+/**
+ * Six prose columns and no unbreakable tokens: min-content alone is only as
+ * wide as the longest word, so the readable floor is the whole story here.
+ */
+const SIX_PROSE_COLUMN_TABLE = [
+ '| Stage | What it does | When it runs | What it needs | What it emits | Who reads it |',
+ '|---|---|---|---|---|---|',
+ '| Parse | Turns the source text into blocks and inline nodes | On every edit | The raw document | A canonical tree | The renderer |',
+ '| Render | Maps each node in the tree onto a part | After a parse | A canonical tree | Rendered output | The reader |',
+].join('\n');
+
+/**
+ * Shapes that are easy to get wrong once a floor is computed from content:
+ * a header with no body rows at all, empty cells, one pathological token far
+ * past the floor cap, a cell mixing a link with inline code, and a table whose
+ * columns sit at opposite ends of the floor range.
+ */
+const EDGE_SHAPE_TABLES = [
+ '| Status | Owner |',
+ '|---|---|',
+ '',
+ '| A | B | C |',
+ '|---|---|---|',
+ '| | only the middle cell has content | |',
+ '',
+ '| Key | Value |',
+ '|---|---|',
+ `| digest | ${'a1b2c3d4e5'.repeat(18)} |`,
+ '',
+ '| Ref | Where it points |',
+ '|---|---|',
+ '| [the parser guide](https://example.com/docs/parser) and `parseDocument` | Both in one cell |',
+ '',
+ '| Id | Description |',
+ '|---|---|',
+ '| 7 | A column at the minimum floor next to one that reaches the cap and keeps going well past it |',
+].join('\n');
+
+export const TableNarrowProseColumns: StoryObj<{width: string}> = {
+ name: 'Table — six prose columns',
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Prose columns have no long tokens, so min-content alone would let six of them wrap one word per line. The readable floor — half the longest cell, capped — gives each column enough width to wrap to a couple of lines instead.',
+ },
+ },
+ },
+ argTypes: NARROW_WIDTH_ARG_TYPES,
+ args: {width: '390'},
+ render: ({width}) => (
+ <ReadingColumn width={width}>{SIX_PROSE_COLUMN_TABLE}</ReadingColumn>
+ ),
+};
+
+export const TableNarrowEdgeShapes: StoryObj<{width: string}> = {
+ name: 'Table — edge shapes',
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Five shapes that stress the column floor: a header row with no body, empty cells, a 180-character token far past the floor cap (the column grows to its min-content rather than breaking the token), a cell mixing a link with inline code, and a minimum-floor column beside a capped one.',
+ },
+ },
+ },
+ argTypes: NARROW_WIDTH_ARG_TYPES,
+ args: {width: '390'},
+ render: ({width}) => (
+ <ReadingColumn width={width}>{EDGE_SHAPE_TABLES}</ReadingColumn>
+ ),
+};
+
+// ---------------------------------------------------------------------------
+// Realistic tables
+//
+// The fixtures above are shaped to pin geometry — a column of empty cells, a
+// 180-character token. These are the documents people actually paste into a
+// narrow reading column, and they are what the width behavior is for.
+// ---------------------------------------------------------------------------
+
+/** An API reference: short method column, long paths, prose behavior. */
+const API_REFERENCE_TABLE = [
+ '| Method | Path | Behavior | Response |',
+ '|---|---|---|---|',
+ '| `GET` | `/v2/projects/{projectId}/documents` | Lists documents in the project, newest first. Paginates with `cursor`. | `200` `DocumentPage` |',
+ '| `POST` | `/v2/projects/{projectId}/documents` | Creates a document. Rejects a duplicate `slug` in the same project. | `201` `Document`, `409` on conflict |',
+ '| `PATCH` | `/v2/documents/{documentId}` | Updates title, body, or tags. Fields left out are untouched. | `200` `Document` |',
+ '| `DELETE` | `/v2/documents/{documentId}` | Soft-deletes the document; it stays readable for 30 days. | `204` no content |',
+].join('\n');
+
+/** A release dashboard: many short columns, one prose column, version strings. */
+const RELEASE_STATUS_TABLE = [
+ '| Service | Environment | Version | State | Updated | Owner |',
+ '|---|---|---|---|---|---|',
+ '| `web-gateway` | production | `4.12.0` | Healthy | 2 h ago | Platform |',
+ '| `web-gateway` | staging | `4.13.0-rc.2` | Rolling out | 11 min ago | Platform |',
+ '| `search-indexer` | production | `2.8.4` | Degraded — reindexing a shard after a failed migration | 40 min ago | Search |',
+ '| `notifications` | production | `1.30.1` | Healthy | 6 h ago | Messaging |',
+].join('\n');
+
+/** A comparison matrix: long headers over short cells, plus a prose column. */
+const FEATURE_COMPARISON_TABLE = [
+ '| Capability | Available on the free plan | Included in the team plan | Notes for administrators |',
+ '|---|---|---|---|',
+ '| Single sign-on | No | Yes | Requires a verified domain and a SAML or OIDC provider. |',
+ '| Audit log retention | 7 days | 400 days | Exportable as newline-delimited JSON from the admin console. |',
+ '| Scheduled exports | No | Yes | Runs nightly; a failed run retries twice before it alerts the owner. |',
+ '| Seats included | 3 | 25 | Additional seats are billed monthly and prorated. |',
+].join('\n');
+
+export const TableRealisticApiReference: StoryObj<{width: string}> = {
+ name: 'Table — API reference',
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'A real API reference in a narrow reading column: a two-character method column beside routes that must stay readable. The path column is floored by its own content, so `/v2/projects/{projectId}/documents` does not split across lines, and the table scrolls rather than squashing the method column to nothing.',
+ },
+ },
+ },
+ argTypes: NARROW_WIDTH_ARG_TYPES,
+ args: {width: '390'},
+ render: ({width}) => (
+ <ReadingColumn width={width}>{API_REFERENCE_TABLE}</ReadingColumn>
+ ),
+};
+
+export const TableRealisticReleaseStatus: StoryObj<{width: string}> = {
+ name: 'Table — release status',
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'A deployment dashboard pasted into a narrow column: six columns, most of them short, one carrying a sentence. Version strings such as `4.13.0-rc.2` stay whole, and the short columns keep their minimum floor instead of collapsing to a character apiece.',
+ },
+ },
+ },
+ argTypes: NARROW_WIDTH_ARG_TYPES,
+ args: {width: '390'},
+ render: ({width}) => (
+ <ReadingColumn width={width}>{RELEASE_STATUS_TABLE}</ReadingColumn>
+ ),
+};
+
+export const TableRealisticComparison: StoryObj<{width: string}> = {
+ name: 'Table — feature comparison',
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'A plan comparison matrix, where the headers are longer than the cells under them. Each header reads on one line up to its cap and wraps past it — never truncating to `Availabl…` — and a two-character cell such as `No` still gets a readable column.',
+ },
+ },
+ },
+ argTypes: NARROW_WIDTH_ARG_TYPES,
+ args: {width: '390'},
+ render: ({width}) => (
+ <ReadingColumn width={width}>{FEATURE_COMPARISON_TABLE}</ReadingColumn>
+ ),
+};
+
+export const TableNarrowWideContent: StoryObj<{width: string}> = {
+ name: 'Table — wide, token-heavy content',
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Long identifiers, a long URL, and inline code stay whole: the column is never narrower than its longest unbreakable token, and the table scrolls in Table’s own Scroll region rather than shredding words. Header labels wrap past their one-line cap instead of ellipsizing.',
+ },
+ },
+ },
+ argTypes: NARROW_WIDTH_ARG_TYPES,
+ args: {width: '390'},
+ render: ({width}) => (
+ <ReadingColumn width={width}>{WIDE_TOKEN_TABLE}</ReadingColumn>
+ ),
+};
+
+export const TableInChatMessage: StoryObj<{width: string}> = {
+ name: 'Table — in a chat message',
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'The narrow reading column as chat surfaces actually have it: a deployment status table — the kind an assistant answers with — inside a `ChatMessageBubble`, which already accepts Markdown as its content. The bubble constrains the message, and the table still keeps its column floors and scrolls inside Table’s own Scroll region — the bubble adds no second scroller.',
+ },
+ },
+ },
+ argTypes: NARROW_WIDTH_ARG_TYPES,
+ args: {width: '390'},
+ render: ({width}) => (
+ <div
+ style={{
+ width: Number(width),
+ maxWidth: '100%',
+ padding: 12,
+ outline: '1px dashed #c33',
+ }}>
+ <ChatMessageList>
+ <ChatMessage sender="user">
+ <ChatMessageBubble>
+ Which services are still rolling out?
+ </ChatMessageBubble>
+ </ChatMessage>
+ <ChatMessage sender="assistant">
+ <ChatMessageBubble>
+ <Markdown density="compact">{RELEASE_STATUS_TABLE}</Markdown>
+ </ChatMessageBubble>
+ </ChatMessage>
+ </ChatMessageList>
+ </div>
+ ),
+};
+
export const Streaming: Story = {
render: () => {
const text = STREAMING_RESPONSE;
diff --git a/docs/pr-assets/6708/chat-message-320.png b/docs/pr-assets/6708/chat-message-320.png
new file mode 100644
index 0000000000..251936de99
Binary files /dev/null and b/docs/pr-assets/6708/chat-message-320.png differ
diff --git a/docs/pr-assets/6708/chat-message-390.png b/docs/pr-assets/6708/chat-message-390.png
new file mode 100644
index 0000000000..60ff4e88e6
Binary files /dev/null and b/docs/pr-assets/6708/chat-message-390.png differ
diff --git a/docs/pr-assets/6708/realistic-tables-390.png b/docs/pr-assets/6708/realistic-tables-390.png
new file mode 100644
index 0000000000..a410267ea6
Binary files /dev/null and b/docs/pr-assets/6708/realistic-tables-390.png differ
diff --git a/docs/pr-assets/6708/short-columns-320-after.png b/docs/pr-assets/6708/short-columns-320-after.png
new file mode 100644
index 0000000000..a540583f55
Binary files /dev/null and b/docs/pr-assets/6708/short-columns-320-after.png differ
diff --git a/docs/pr-assets/6708/short-columns-320-before.png b/docs/pr-assets/6708/short-columns-320-before.png
new file mode 100644
index 0000000000..1104730180
Binary files /dev/null and b/docs/pr-assets/6708/short-columns-320-before.png differ
diff --git a/docs/pr-assets/6708/short-columns-390-after.png b/docs/pr-assets/6708/short-columns-390-after.png
new file mode 100644
index 0000000000..e47a6a3acf
Binary files /dev/null and b/docs/pr-assets/6708/short-columns-390-after.png differ
diff --git a/docs/pr-assets/6708/short-columns-390-before.png b/docs/pr-assets/6708/short-columns-390-before.png
new file mode 100644
index 0000000000..ecae17af47
Binary files /dev/null and b/docs/pr-assets/6708/short-columns-390-before.png differ
diff --git a/docs/pr-assets/6708/table-scroll-390-filmstrip.png b/docs/pr-assets/6708/table-scroll-390-filmstrip.png
new file mode 100644
index 0000000000..df99e149b5
Binary files /dev/null and b/docs/pr-assets/6708/table-scroll-390-filmstrip.png differ
diff --git a/docs/pr-assets/6708/wide-content-320-after.png b/docs/pr-assets/6708/wide-content-320-after.png
new file mode 100644
index 0000000000..bd6ad0d3d5
Binary files /dev/null and b/docs/pr-assets/6708/wide-content-320-after.png differ
diff --git a/docs/pr-assets/6708/wide-content-320-before.png b/docs/pr-assets/6708/wide-content-320-before.png
new file mode 100644
index 0000000000..79b2449ebd
Binary files /dev/null and b/docs/pr-assets/6708/wide-content-320-before.png differ
diff --git a/docs/pr-assets/6708/wide-content-390-after.png b/docs/pr-assets/6708/wide-content-390-after.png
new file mode 100644
index 0000000000..b314bc7540
Binary files /dev/null and b/docs/pr-assets/6708/wide-content-390-after.png differ
diff --git a/docs/pr-assets/6708/wide-content-390-before.png b/docs/pr-assets/6708/wide-content-390-before.png
new file mode 100644
index 0000000000..c7452f2b3d
Binary files /dev/null and b/docs/pr-assets/6708/wide-content-390-before.png differ
diff --git a/packages/core/src/Markdown/Markdown.doc.mjs b/packages/core/src/Markdown/Markdown.doc.mjs
index 92680abcd9..0104a6accf 100644
--- a/packages/core/src/Markdown/Markdown.doc.mjs
+++ b/packages/core/src/Markdown/Markdown.doc.mjs
@@ -41,7 +41,7 @@ const anatomy = [
name: 'Table',
required: false,
description:
- 'Scrollable table block rendered from Markdown rows and columns.',
+ 'Table block rendered from Markdown rows and columns; its Table child owns horizontal scrolling.',
},
{
name: 'Divider',
diff --git a/packages/core/src/Markdown/Markdown.test.tsx b/packages/core/src/Markdown/Markdown.test.tsx
index 2b878261e4..80c19930dc 100644
--- a/packages/core/src/Markdown/Markdown.test.tsx
+++ b/packages/core/src/Markdown/Markdown.test.tsx
@@ -461,15 +461,112 @@ describe('Markdown', () => {
expect(cells[1].querySelector('code')).toHaveTextContent('T | null');
});
- it('makes the table scroll wrapper keyboard-focusable', () => {
- render(<Markdown>{'| A | B |\n| --- | --- |\n| 1 | 2 |'}</Markdown>);
- const table = document.querySelector('table');
+ it('delegates table scrolling and focus to the Table-owned viewport', () => {
+ const {container} = render(
+ <Markdown>{'| A | B |\n| --- | --- |\n| 1 | 2 |'}</Markdown>,
+ );
+ const table = container.querySelector('table');
+ const markdownBlock = container.querySelector('.astryx-markdown-table');
+ const groups = container.querySelectorAll('[role="group"]');
+
expect(table).toBeInTheDocument();
- // The GFM table's outer overflow wrapper is keyboard-focusable so keyboard
- // users can horizontally scroll a wide table.
- const wrapper = table!.closest('[role="group"][tabindex="0"]');
- expect(wrapper).toBeTruthy();
- expect(wrapper).toHaveAttribute('aria-label', 'Table');
+ // Exactly one scroll region: Table's own, which also owns the name and
+ // (when it actually overflows) the tab stop. Markdown's block carries
+ // spacing and sizing only.
+ expect(groups).toHaveLength(1);
+ expect(groups[0]).toContainElement(table);
+ expect(groups[0]).toHaveAttribute('aria-label', 'Table');
+ expect(markdownBlock).not.toHaveAttribute('role');
+ expect(markdownBlock).not.toHaveAttribute('tabindex');
+ });
+
+ it('floors each table column from its own content, in ch', () => {
+ // The floor algorithm: max(4, ceil(longest cell / 2), min(header, 20)),
+ // capped at 24, expressed in `ch` so it follows the reader's font size.
+ // That the floor then survives cell padding and actually widens the
+ // column is geometry, and is proved in MarkdownTable.a11y.chromium.spec.ts.
+ const long = 'x'.repeat(120);
+ render(
+ <Markdown>
+ {`| Key | Meaning | Note |\n| --- | --- | --- |\n| id | Stable identifier never reused | ${long} |`}
+ </Markdown>,
+ );
+ const floors = Array.from(document.querySelectorAll('th')).map(th =>
+ th.getAttribute('style'),
+ );
+ expect(floors[0]).toMatch(/\b4ch\b/); // "Key" / "id" — short, min floor
+ expect(floors[1]).toMatch(/\b15ch\b/); // 30 chars → ceil(30 / 2)
+ expect(floors[2]).toMatch(/\b24ch\b/); // 120 chars → capped
+ // No fixed pixel bucket survives anywhere in the column floors.
+ expect(floors.join(' ')).not.toMatch(/\d+px/);
+ });
+
+ it('floors a short-bodied column from its header label, up to the cap', () => {
+ render(
+ <Markdown>
+ {
+ '| Component name | Accessibility status and remediation owner | X |\n| --- | --- | --- |\n| Button | Pass | 1 |'
+ }
+ </Markdown>,
+ );
+ const ths = Array.from(document.querySelectorAll('th'));
+ // 14-char label: the header floor (14ch) beats the body floor (3ch).
+ expect(ths[0].getAttribute('style')).toMatch(/\b14ch\b/);
+ // 42-char label: the header floor caps at 20ch, so the body floor
+ // (ceil(42 / 2) = 21ch) is what the column keeps.
+ expect(ths[1].getAttribute('style')).toMatch(/\b21ch\b/);
+ });
+
+ it('floors a header-only table from its labels alone', () => {
+ // No body rows: the body floor is computed over nothing, so the header
+ // label has to carry the column by itself rather than collapsing to the
+ // minimum (or throwing on an absent row).
+ render(<Markdown>{'| Status | Owner |\n| --- | --- |'}</Markdown>);
+ const ths = Array.from(document.querySelectorAll('th'));
+ expect(ths.map(th => th.textContent)).toEqual(['Status', 'Owner']);
+ expect(document.querySelectorAll('tbody tr')).toHaveLength(0);
+ expect(ths[0].getAttribute('style')).toMatch(/\b6ch\b/);
+ expect(ths[1].getAttribute('style')).toMatch(/\b5ch\b/);
+ });
+
+ it('floors a column of empty cells at the minimum', () => {
+ render(
+ <Markdown>
+ {'| A | B | C |\n| --- | --- | --- |\n| | middle only | |'}
+ </Markdown>,
+ );
+ const ths = Array.from(document.querySelectorAll('th'));
+ // Empty body cells contribute nothing; a one-character header still
+ // leaves the column at the 4ch minimum rather than at zero.
+ expect(ths[0].getAttribute('style')).toMatch(/\b4ch\b/);
+ expect(ths[2].getAttribute('style')).toMatch(/\b4ch\b/);
+ // 11 chars in the middle column → ceil(11 / 2) = 6ch.
+ expect(ths[1].getAttribute('style')).toMatch(/\b6ch\b/);
+ });
+
+ it('keeps inline code inside a table cell on the default Code part', () => {
+ render(
+ <Markdown>
+ {'| Status |\n| --- |\n| `needs_revision_before_landing_v2` |'}
+ </Markdown>,
+ );
+ const code = document.querySelector('tbody td code');
+ expect(code).toHaveTextContent('needs_revision_before_landing_v2');
+ });
+
+ it('lets a supplied inlineCode renderer own code inside table cells', () => {
+ const components: Partial<MarkdownComponents> = {
+ inlineCode: ({children}) => <kbd data-custom>{children}</kbd>,
+ };
+ render(
+ <Markdown components={components}>
+ {'| Status |\n| --- |\n| `x` |'}
+ </Markdown>,
+ );
+ expect(
+ document.querySelector('tbody td kbd[data-custom]'),
+ ).toHaveTextContent('x');
+ expect(document.querySelector('tbody td code')).toBeNull();
});
it('renders horizontal rules', () => {
diff --git a/packages/core/src/Markdown/Markdown.tsx b/packages/core/src/Markdown/Markdown.tsx
index e208301ec8..b8a93abe24 100644
--- a/packages/core/src/Markdown/Markdown.tsx
+++ b/packages/core/src/Markdown/Markdown.tsx
@@ -278,6 +278,61 @@ const cellAlignStyles = stylex.create({
end: {textAlign: 'end'},
});
+/**
+ * Cell sizing for Markdown's own default Table part, layered over Table's
+ * wrap-mode defaults.
+ *
+ * Table sizes wrap-mode cells with `max-width: 0` + `word-break: break-word`,
+ * and its header cell also applies nowrap + ellipsis. Those defaults zero every
+ * column's min-content contribution, so automatic layout divides the container
+ * equally: a six-column Markdown table squashes to a few characters per cell,
+ * identifiers split mid-word, header labels ellipsize, and nothing ever
+ * overflows into the Scroll region that exists to take the width.
+ *
+ * Here the cell reports an honest min-content, the header wraps instead of
+ * truncating, and `box-sizing: content-box` makes the per-column `ch` floor a
+ * floor on the text box rather than on the padded border box — so the floor
+ * means the same number of characters at every density, with no padding
+ * arithmetic to keep in sync with Table's own tokens.
+ *
+ * Data-driven `Table` keeps its released wrap mode; only Markdown's part is
+ * restyled.
+ */
+const markdownTableCellStyles = stylex.create({
+ cell: {
+ boxSizing: 'content-box',
+ maxWidth: 'none',
+ overflow: 'visible',
+ overflowWrap: 'break-word',
+ wordBreak: 'normal',
+ },
+ headerCell: {
+ boxSizing: 'content-box',
+ maxWidth: 'none',
+ overflow: 'visible',
+ overflowWrap: 'break-word',
+ textOverflow: 'clip',
+ whiteSpace: 'normal',
+ wordBreak: 'normal',
+ },
+ // Inline Code sets `word-break: break-word` so a long token cannot widen a
+ // paragraph. Inside a table cell that same rule zeroes the token's
+ // min-content and splits an identifier across lines; the cell keeps it whole
+ // and lets the column carry the width instead.
+ code: {
+ wordBreak: 'normal',
+ },
+});
+
+/**
+ * Default inline-code renderer inside Markdown table cells. Used only when the
+ * consumer supplies no `components.inlineCode`; a custom renderer owns its own
+ * wrapping rules.
+ */
+function MarkdownTableCellCode({children}: {children: string}) {
+ return <Code xstyle={markdownTableCellStyles.code}>{children}</Code>;
+}
+
const styles = stylex.create({
root: {
fontFamily: typographyVars['--font-family-body'],
@@ -418,7 +473,9 @@ const styles = stylex.create({
maxWidth: '100%',
},
tableWrapper: {
- overflowX: 'auto',
+ // No `overflow-x` here: Table's own Scroll region (`table-scroll-wrapper`)
+ // is the table's scroller, and this block is exactly as wide as it, so a
+ // second scroll container would only add a dead focus stop.
maxWidth: '100%',
'--container-padding-inline-start': '0px',
'--container-padding-inline-end': '0px',
@@ -1174,16 +1231,39 @@ function getElementSpacing(
// ---------------------------------------------------------------------------
/**
- * Compute per-column min-widths from table AST content.
- * Buckets: ≤6 chars → 60px, 7–15 → 80px, >15 → 120px.
+ * Content-derived width floors for a Markdown table's columns, in `ch`.
+ *
+ * Once the cells stop clamping themselves (see `markdownTableCellStyles`),
+ * automatic table layout already gives every column its min-content — the
+ * longest unbreakable token — so no identifier can split mid-word. That floor
+ * is honest but not readable: a prose column's longest word is short, so six
+ * prose columns in a narrow container still wrap one word per line. The
+ * readable floor lets a column's longest cell wrap to about two lines instead,
+ * scaled by that cell's own length and bounded so a table of short columns
+ * still fits its container.
+ *
+ * A header label adds its own floor, so a short-bodied column stays as wide as
+ * its label reads on one line, up to a cap past which the label wraps rather
+ * than widening the column further.
+ *
+ * The floors are `ch`, not `px`: they follow the reader's font size, and with
+ * `box-sizing: content-box` on the cells they are floors on the text box, so
+ * cell padding does not eat into them. Exact tuning lives here, not in the
+ * spec.
*/
+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;
+
function computeTableColumnMinWidths(node: RenderTable): number[] {
const [header, ...rows] = node.children;
if (header == null) {
return [];
}
return header.children.map((cell, colIdx) => {
- let maxLen = countInlineTextLength(cell.children);
+ const headerLen = countInlineTextLength(cell.children);
+ let maxLen = headerLen;
for (const row of rows) {
const rowCell = row.children[colIdx];
if (rowCell != null) {
@@ -1193,7 +1273,14 @@ function computeTableColumnMinWidths(node: RenderTable): number[] {
}
}
}
- return maxLen <= 6 ? 60 : maxLen <= 15 ? 80 : 120;
+ // Body floor: the longest cell wraps to about TARGET_LINES lines.
+ const bodyFloor = Math.ceil(maxLen / TABLE_COLUMN_TARGET_LINES);
+ // Header floor: the label reads on one line up to the one-line cap.
+ const headerFloor = Math.min(headerLen, TABLE_HEADER_ONE_LINE_MAX_CH);
+ return Math.min(
+ TABLE_COLUMN_MAX_CH,
+ Math.max(TABLE_COLUMN_MIN_CH, bodyFloor, headerFloor),
+ );
});
}
@@ -1643,17 +1730,21 @@ function renderBlock(
case 'table': {
const colMinWidths = computeTableColumnMinWidths(node);
const [header, ...rows] = node.children;
+ // Inline code inside a cell keeps its token whole, through the same
+ // `components` seam consumers use. A supplied renderer owns its own
+ // wrapping and is left alone.
+ const cellComponents: Partial<MarkdownComponents> | undefined =
+ components?.inlineCode != null
+ ? components
+ : {...components, inlineCode: MarkdownTableCellCode};
return (
<div
key={index}
- // Keyboard-focusable so keyboard users can scroll a horizontally
- // overflowing GFM table. Uses role="group" (not "region") so
- // multiple tables don't create duplicate same-named landmarks
- // (axe: landmark-unique).
- tabIndex={0}
- role="group"
- aria-label={t('@astryx.markdown.table')}
+ // No role, name, or tab stop here: Table's Scroll region owns the
+ // table's horizontal overflow, its accessible name, and its
+ // conditional keyboard focusability. This block only carries
+ // spacing, sizing, and alignment.
{...mergeProps(
themeProps('markdown-table', {density}),
stylex.props(
@@ -1677,7 +1768,8 @@ function renderBlock(
// eslint-disable-next-line @eslint-react/no-array-index-key -- markdown table columns are positional by definition
key={i}
xstyle={[
- dynamicStyles.cellMinWidth(`${colMinWidths[i]}px`),
+ markdownTableCellStyles.headerCell,
+ dynamicStyles.cellMinWidth(`${colMinWidths[i]}ch`),
node.align[i] === 'center' && cellAlignStyles.center,
node.align[i] === 'right' && cellAlignStyles.end,
]}>
@@ -1690,7 +1782,7 @@ function renderBlock(
citationCtx,
linkComponent,
inlinePlugins,
- components,
+ cellComponents,
preparedPlugins,
),
)}
@@ -1705,6 +1797,7 @@ function renderBlock(
// eslint-disable-next-line @eslint-react/no-array-index-key -- markdown table cells are positional by row and column
key={j}
xstyle={[
+ markdownTableCellStyles.cell,
node.align[j] === 'center' && cellAlignStyles.center,
node.align[j] === 'right' && cellAlignStyles.end,
]}>
@@ -1717,7 +1810,7 @@ function renderBlock(
citationCtx,
linkComponent,
inlinePlugins,
- components,
+ cellComponents,
preparedPlugins,
),
)}
diff --git a/packages/core/src/Markdown/MarkdownTable.a11y.chromium.spec.ts b/packages/core/src/Markdown/MarkdownTable.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..9ae4a8026b
--- /dev/null
+++ b/packages/core/src/Markdown/MarkdownTable.a11y.chromium.spec.ts
@@ -0,0 +1,726 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file MarkdownTable.a11y.chromium.spec.ts
+ * @input Uses the four narrow-width Markdown table stories and a built Storybook
+ * @output Real-Chromium geometry and focus evidence for Markdown table columns
+ * @position Layout and focus proof for `component:Markdown`'s table clause. A
+ * DOM emulator resolves no layout: it cannot say whether a column floor
+ * survived cell padding, whether a header wrapped or was cut, whether a token
+ * stayed on one line, or which element actually scrolls. Every expectation
+ * here is measured from a shipping engine.
+ *
+ * Build the Storybook first:
+ *
+ * pnpm storybook:build
+ * pnpm exec playwright test MarkdownTable.a11y.chromium.spec.ts
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {expect, test, type Page} from '@playwright/test';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+const OUTPUT = path.resolve('test-results/markdown-table-narrow');
+
+/** Reading widths: two phone-sized columns, a side panel, a roomy document. */
+const WIDTHS = [320, 390, 528, 1024] as const;
+
+const SHORT_COLUMNS_STORY = 'core-markdown--table-narrow-short-columns';
+const PROSE_COLUMNS_STORY = 'core-markdown--table-narrow-prose-columns';
+const EDGE_SHAPES_STORY = 'core-markdown--table-narrow-edge-shapes';
+const WIDE_CONTENT_STORY = 'core-markdown--table-narrow-wide-content';
+const CHAT_STORY = 'core-markdown--table-in-chat-message';
+
+/**
+ * The realistic documents: an API reference, a release dashboard, and a plan
+ * comparison matrix. The fixtures above pin geometry; these are what people
+ * actually paste into a narrow reading column.
+ */
+const API_STORY = 'core-markdown--table-realistic-api-reference';
+const RELEASE_STORY = 'core-markdown--table-realistic-release-status';
+const COMPARISON_STORY = 'core-markdown--table-realistic-comparison';
+
+const REALISTIC_STORIES = [API_STORY, RELEASE_STORY, COMPARISON_STORY];
+
+const ALL_STORIES = [
+ SHORT_COLUMNS_STORY,
+ PROSE_COLUMNS_STORY,
+ EDGE_SHAPES_STORY,
+ WIDE_CONTENT_STORY,
+ CHAT_STORY,
+ ...REALISTIC_STORIES,
+];
+
+/**
+ * A token this long with no break opportunity in it — an identifier, a status
+ * code, a snake_case value — must render on one line. Tokens carrying their own
+ * break opportunities (`-`, `/`, `.` in a URL) may legitimately wrap there, and
+ * are not what the fixed defect was about: the regression broke words at
+ * arbitrary characters.
+ */
+const LONG_TOKEN_CHARS = 10;
+const UNBREAKABLE_TOKEN = /^[A-Za-z0-9_]+$/;
+
+interface HeaderMetrics {
+ text: string;
+ clientWidth: number;
+ scrollWidth: number;
+ contentWidth: number;
+ lines: number;
+ textOverflow: string;
+ whiteSpace: string;
+}
+
+/** One Markdown table block, with the Table it owns. */
+interface TableMetrics {
+ index: number;
+ scrollerExists: boolean;
+ scrollWidth: number;
+ clientWidth: number;
+ overflowX: string;
+ role: string | null;
+ label: string | null;
+ tabIndex: string | null;
+ blockScrollWidth: number;
+ blockClientWidth: number;
+ blockOverflowX: string;
+ blockRole: string | null;
+ blockTabIndex: string | null;
+ groupsInBlock: number;
+ headers: HeaderMetrics[];
+ bodyCellLines: number[];
+ brokenTokens: string[];
+ chPx: number;
+}
+
+interface StoryMetrics {
+ tables: TableMetrics[];
+ groupsInStory: number;
+}
+
+let storybook: StaticServer;
+const evidence: Record<string, unknown>[] = [];
+
+test.beforeAll(async () => {
+ fs.rmSync(OUTPUT, {recursive: true, force: true});
+ fs.mkdirSync(OUTPUT, {recursive: true});
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+
+test.afterAll(async () => {
+ fs.writeFileSync(
+ path.join(OUTPUT, 'manifest.json'),
+ `${JSON.stringify({version: 2, measurements: evidence}, null, 2)}\n`,
+ );
+ await storybook?.close();
+});
+
+async function openStory(
+ page: Page,
+ storyId: string,
+ width: number,
+): Promise<void> {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=${storyId}&viewMode=story&args=width:${width}`,
+ {waitUntil: 'load'},
+ );
+ await page
+ .locator('#storybook-root table')
+ .first()
+ .waitFor({state: 'visible'});
+ // One frame, so layout for the story's width is settled before measuring.
+ await page.evaluate(
+ async () =>
+ new Promise<void>(resolve => requestAnimationFrame(() => resolve())),
+ );
+}
+
+/** Measure every Markdown table block in the story, in document order. */
+async function measure(
+ page: Page,
+ longTokenChars: number,
+): Promise<StoryMetrics> {
+ return page.evaluate(
+ ({minToken, tokenPattern}: {minToken: number; tokenPattern: string}) => {
+ const unbreakable = new RegExp(tokenPattern);
+ const root = document.querySelector('#storybook-root') as HTMLElement;
+
+ const lineCount = (element: Element): number => {
+ const range = document.createRange();
+ range.selectNodeContents(element);
+ const tops = new Set<number>();
+ for (const rect of Array.from(range.getClientRects())) {
+ if (rect.width > 0 || rect.height > 0) {
+ tops.add(Math.round(rect.top));
+ }
+ }
+ return Math.max(tops.size, 1);
+ };
+
+ const tables = Array.from(
+ root.querySelectorAll('.astryx-markdown-table'),
+ ).map((blockNode, index) => {
+ const block = blockNode as HTMLElement;
+ const scroller = block.querySelector('.astryx-table-scroll-wrapper');
+
+ const headers = Array.from(block.querySelectorAll('th')).map(th => {
+ const styles = getComputedStyle(th);
+ return {
+ text: (th.textContent ?? '').trim(),
+ clientWidth: th.clientWidth,
+ scrollWidth: th.scrollWidth,
+ contentWidth:
+ th.getBoundingClientRect().width -
+ parseFloat(styles.paddingLeft) -
+ parseFloat(styles.paddingRight),
+ lines: lineCount(th),
+ textOverflow: styles.textOverflow,
+ whiteSpace: styles.whiteSpace,
+ };
+ });
+
+ const bodyCellLines = Array.from(block.querySelectorAll('tbody td'))
+ .filter(cell => (cell.textContent ?? '').trim().length > 0)
+ .map(cell => lineCount(cell));
+
+ // A long token that renders across more than one line box was broken
+ // mid-word. Walk the real text nodes rather than trusting the markup.
+ const brokenTokens: string[] = [];
+ const body = block.querySelector('tbody');
+ if (body != null) {
+ const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT);
+ for (
+ let node = walker.nextNode();
+ node != null;
+ node = walker.nextNode()
+ ) {
+ const value = node.nodeValue ?? '';
+ const pattern = /\S+/g;
+ let match = pattern.exec(value);
+ while (match != null) {
+ if (match[0].length >= minToken && unbreakable.test(match[0])) {
+ const range = document.createRange();
+ range.setStart(node, match.index);
+ range.setEnd(node, match.index + match[0].length);
+ const tops = new Set<number>();
+ for (const rect of Array.from(range.getClientRects())) {
+ if (rect.width > 0) {
+ tops.add(Math.round(rect.top));
+ }
+ }
+ if (tops.size > 1) {
+ brokenTokens.push(match[0]);
+ }
+ }
+ match = pattern.exec(value);
+ }
+ }
+ }
+
+ // One `ch` in a header cell, measured rather than assumed.
+ let chPx = 0;
+ const firstHeader = block.querySelector('th');
+ if (firstHeader != null) {
+ const probe = document.createElement('span');
+ probe.style.cssText =
+ 'position:absolute;visibility:hidden;font:inherit';
+ probe.textContent = '0';
+ firstHeader.appendChild(probe);
+ chPx = probe.getBoundingClientRect().width;
+ probe.remove();
+ }
+
+ return {
+ index,
+ scrollerExists: scroller != null,
+ scrollWidth: scroller?.scrollWidth ?? 0,
+ clientWidth: scroller?.clientWidth ?? 0,
+ overflowX:
+ scroller == null ? '' : getComputedStyle(scroller).overflowX,
+ role: scroller?.getAttribute('role') ?? null,
+ label: scroller?.getAttribute('aria-label') ?? null,
+ tabIndex: scroller?.getAttribute('tabindex') ?? null,
+ blockScrollWidth: block.scrollWidth,
+ blockClientWidth: block.clientWidth,
+ blockOverflowX: getComputedStyle(block).overflowX,
+ blockRole: block.getAttribute('role'),
+ blockTabIndex: block.getAttribute('tabindex'),
+ groupsInBlock: block.querySelectorAll('[role="group"]').length,
+ headers,
+ bodyCellLines,
+ brokenTokens,
+ chPx,
+ };
+ });
+
+ return {
+ tables,
+ groupsInStory: root.querySelectorAll('[role="group"]').length,
+ };
+ },
+ {minToken: longTokenChars, tokenPattern: UNBREAKABLE_TOKEN.source},
+ );
+}
+
+/**
+ * Every table in every story, at every reading width: the invariants that must
+ * hold for all of them, whatever the table's shape.
+ */
+test('Markdown table columns keep their content floor and headers stay readable', async ({
+ page,
+}) => {
+ test.setTimeout(5 * 60 * 1000);
+ const failures: string[] = [];
+
+ for (const storyId of ALL_STORIES) {
+ for (const width of WIDTHS) {
+ await openStory(page, storyId, width);
+ const story = await measure(page, LONG_TOKEN_CHARS);
+ evidence.push({storyId, width, ...story});
+ // Evidence for review: what the reading column actually looks like.
+ await page
+ .locator('#storybook-root .astryx-markdown')
+ .screenshot({path: path.join(OUTPUT, `${storyId}-${width}.png`)});
+
+ const where = `${storyId} @${width}`;
+ if (story.tables.length === 0) {
+ failures.push(`${where}: no Markdown table block rendered`);
+ continue;
+ }
+ // One scroll region per table, and no others loose in the story.
+ if (story.groupsInStory !== story.tables.length) {
+ failures.push(
+ `${where}: ${story.groupsInStory} role="group" elements for ${story.tables.length} tables`,
+ );
+ }
+
+ for (const table of story.tables) {
+ const at = `${where} table ${table.index}`;
+ if (!table.scrollerExists) {
+ failures.push(`${at}: no Table scroll region rendered`);
+ continue;
+ }
+ if (table.groupsInBlock !== 1) {
+ failures.push(
+ `${at}: ${table.groupsInBlock} role="group" elements, expected 1`,
+ );
+ }
+ if (table.label !== 'Table') {
+ failures.push(`${at}: scroll region name is ${String(table.label)}`);
+ }
+ if (table.blockRole != null || table.blockTabIndex != null) {
+ failures.push(`${at}: Markdown's block still claims role/tabindex`);
+ }
+ // Markdown's own block never scrolls; Table's region is the scroller.
+ if (table.blockScrollWidth > table.blockClientWidth + 1) {
+ failures.push(
+ `${at}: Markdown's block overflows (${table.blockScrollWidth} > ${table.blockClientWidth})`,
+ );
+ }
+ if (table.blockOverflowX !== 'visible') {
+ failures.push(
+ `${at}: Markdown's block has overflow-x: ${table.blockOverflowX}`,
+ );
+ }
+
+ // Headers wrap; none is cut off or ellipsized.
+ for (const header of table.headers) {
+ if (header.textOverflow === 'ellipsis') {
+ failures.push(
+ `${at}: header "${header.text}" keeps text-overflow: ellipsis`,
+ );
+ }
+ if (header.whiteSpace === 'nowrap') {
+ failures.push(
+ `${at}: header "${header.text}" keeps white-space: nowrap`,
+ );
+ }
+ if (header.scrollWidth > header.clientWidth + 1) {
+ failures.push(
+ `${at}: header "${header.text}" overflows its cell (${header.scrollWidth} > ${header.clientWidth})`,
+ );
+ }
+ }
+
+ // Long identifiers, codes, and snake_case values keep their tokens
+ // whole — including the pathological one, far past the floor cap.
+ if (table.brokenTokens.length > 0) {
+ failures.push(
+ `${at}: tokens broken mid-word — ${table.brokenTokens.join(', ')}`,
+ );
+ }
+ }
+ }
+ }
+
+ expect(failures).toEqual([]);
+});
+
+test('six short columns fit a narrow reading column instead of scrolling', async ({
+ page,
+}) => {
+ for (const width of [390, 528, 1024]) {
+ await openStory(page, SHORT_COLUMNS_STORY, width);
+ const story = await measure(page, LONG_TOKEN_CHARS);
+ evidence.push({storyId: SHORT_COLUMNS_STORY, width, fits: true, ...story});
+ const table = story.tables[0];
+ expect(
+ table.scrollWidth,
+ `six short columns should fit at ${width}px`,
+ ).toBeLessThanOrEqual(table.clientWidth + 1);
+ }
+});
+
+test('prose columns wrap to a few readable lines, not one word per line', async ({
+ page,
+}) => {
+ // Six prose columns carry no long tokens, so min-content alone is just the
+ // longest word and every cell would wrap once per word. The readable floor
+ // is what keeps them legible; measure lines per cell rather than CSS.
+ await openStory(page, PROSE_COLUMNS_STORY, 390);
+ const story = await measure(page, LONG_TOKEN_CHARS);
+ evidence.push({
+ storyId: PROSE_COLUMNS_STORY,
+ width: 390,
+ prose: true,
+ ...story,
+ });
+ const table = story.tables[0];
+
+ // Every cell's longest word count is at least 8, so one-word-per-line would
+ // mean 8+ lines. The floor holds each cell to a handful.
+ const worst = Math.max(...table.bodyCellLines);
+ expect(worst, 'prose cells should wrap to a few lines').toBeLessThanOrEqual(
+ 6,
+ );
+ // The floor is real: each column keeps well more than the 4ch minimum.
+ for (const header of table.headers) {
+ expect(header.contentWidth).toBeGreaterThanOrEqual(4 * table.chPx - 1);
+ }
+});
+
+test('an edge-shape table keeps one scroll owner per table and one whole token', async ({
+ page,
+}) => {
+ // Five tables in one reading column: a header with no body rows, empty
+ // cells, a 180-character token, a link beside inline code, and a
+ // minimum-floor column next to a capped one.
+ await openStory(page, EDGE_SHAPES_STORY, 390);
+ const story = await measure(page, LONG_TOKEN_CHARS);
+ evidence.push({
+ storyId: EDGE_SHAPES_STORY,
+ width: 390,
+ edges: true,
+ ...story,
+ });
+
+ expect(story.tables).toHaveLength(5);
+ // Five tables, five scroll regions — no table borrows another's, and none
+ // of them is a bare block claiming a role.
+ expect(story.groupsInStory).toBe(5);
+ for (const table of story.tables) {
+ expect(table.groupsInBlock).toBe(1);
+ expect(table.blockRole).toBeNull();
+ expect(table.blockTabIndex).toBeNull();
+ }
+
+ // The header-only table still renders its header row and floors its columns.
+ const headerOnly = story.tables[0];
+ expect(headerOnly.headers.map(header => header.text)).toEqual([
+ 'Status',
+ 'Owner',
+ ]);
+ expect(headerOnly.bodyCellLines).toEqual([]);
+
+ // The pathological token is 180 characters — far past the 24ch floor cap —
+ // so the column grows to its min-content rather than breaking the token.
+ // Had the cap clamped it, ~24ch would have fit the reading column and the
+ // table would not scroll at all; instead it scrolls several screens wide.
+ // (Measured against the container, not against `ch`: the body font is
+ // proportional, so 180 characters is not 180 `ch`.)
+ const pathological = story.tables[2];
+ expect(pathological.brokenTokens).toEqual([]);
+ expect(pathological.scrollWidth).toBeGreaterThan(
+ pathological.clientWidth * 3,
+ );
+ expect(pathological.blockScrollWidth).toBeLessThanOrEqual(
+ pathological.blockClientWidth + 1,
+ );
+ expect(pathological.tabIndex).toBe('0');
+
+ // A cell mixing a link with inline code renders both, and the link text is
+ // not shredded.
+ const linkAndCode = story.tables[3];
+ expect(linkAndCode.brokenTokens).toEqual([]);
+ expect(
+ await page.locator('#storybook-root tbody a').first().isVisible(),
+ ).toBe(true);
+ expect(
+ await page.locator('#storybook-root tbody code').first().isVisible(),
+ ).toBe(true);
+});
+
+test('a wide table scrolls only in the Table scroll region, and by keyboard', async ({
+ page,
+}) => {
+ await openStory(page, WIDE_CONTENT_STORY, 390);
+ const story = await measure(page, LONG_TOKEN_CHARS);
+ evidence.push({
+ storyId: WIDE_CONTENT_STORY,
+ width: 390,
+ keyboard: true,
+ ...story,
+ });
+ const table = story.tables[0];
+
+ // The wide table really does overflow, and the overflow is Table's alone.
+ expect(story.groupsInStory).toBe(1);
+ expect(table.blockRole).toBeNull();
+ expect(table.blockTabIndex).toBeNull();
+ expect(table.scrollWidth).toBeGreaterThan(table.clientWidth);
+ expect(table.overflowX).toBe('auto');
+ expect(table.blockScrollWidth).toBeLessThanOrEqual(
+ table.blockClientWidth + 1,
+ );
+ // Focusable only because it scrolls.
+ expect(table.tabIndex).toBe('0');
+
+ const scroller = page.locator('.astryx-table-scroll-wrapper');
+ await scroller.evaluate(element => {
+ (element as HTMLElement).focus({preventScroll: true});
+ });
+ expect(
+ await page.evaluate(() =>
+ document.activeElement?.classList.contains('astryx-table-scroll-wrapper'),
+ ),
+ ).toBe(true);
+
+ const before = await scroller.evaluate(element => element.scrollLeft);
+ for (let press = 0; press < 8; press += 1) {
+ await page.keyboard.press('ArrowRight');
+ }
+ await page.waitForFunction(
+ previous =>
+ (document.querySelector('.astryx-table-scroll-wrapper') as HTMLElement)
+ .scrollLeft > previous,
+ before,
+ );
+ const after = await scroller.evaluate(element => element.scrollLeft);
+ expect(after).toBeGreaterThan(before);
+});
+
+/**
+ * The realistic documents at the two phone-sized reading widths: the states
+ * the fix exists for, asserted on the things a reader would notice.
+ */
+test('realistic tables stay readable at 320 and 390', async ({page}) => {
+ test.setTimeout(3 * 60 * 1000);
+ const failures: string[] = [];
+
+ for (const storyId of REALISTIC_STORIES) {
+ for (const width of [320, 390]) {
+ await openStory(page, storyId, width);
+ const story = await measure(page, LONG_TOKEN_CHARS);
+ evidence.push({storyId, width, realistic: true, ...story});
+ const table = story.tables[0];
+ const at = `${storyId} @${width}`;
+
+ // Exactly one scroll viewport owns overflow and focus.
+ if (story.groupsInStory !== 1) {
+ failures.push(
+ `${at}: ${story.groupsInStory} scroll regions, expected 1`,
+ );
+ }
+ if (table.label !== 'Table' || table.blockRole != null) {
+ failures.push(`${at}: the Table viewport is not the sole named region`);
+ }
+ // Focusable exactly when it scrolls, never otherwise.
+ const scrolls = table.scrollWidth > table.clientWidth + 1;
+ if (scrolls !== (table.tabIndex === '0')) {
+ failures.push(
+ `${at}: scrolls=${scrolls} but tabindex=${String(table.tabIndex)}`,
+ );
+ }
+
+ // Headers read: none truncated, none overflowing its cell.
+ for (const header of table.headers) {
+ if (
+ header.textOverflow === 'ellipsis' ||
+ header.whiteSpace === 'nowrap' ||
+ header.scrollWidth > header.clientWidth + 1
+ ) {
+ failures.push(`${at}: header "${header.text}" is not fully readable`);
+ }
+ }
+
+ // Identifiers, versions, and status codes stay whole.
+ if (table.brokenTokens.length > 0) {
+ failures.push(
+ `${at}: broken mid-word — ${table.brokenTokens.join(', ')}`,
+ );
+ }
+ }
+ }
+
+ expect(failures).toEqual([]);
+});
+
+test('an API reference keeps its routes whole and its method column readable', async ({
+ page,
+}) => {
+ // The shape that motivated the fix: a two-character method column beside
+ // routes far longer than any floor. Under the old fixed buckets the method
+ // column was padded to 60px while `/v2/projects/{projectId}/documents` was
+ // shredded; now the route column carries the width and the table scrolls.
+ await openStory(page, API_STORY, 390);
+ const story = await measure(page, LONG_TOKEN_CHARS);
+ evidence.push({storyId: API_STORY, width: 390, routes: true, ...story});
+ const table = story.tables[0];
+
+ const routeLines = await page.evaluate(() => {
+ const cells = Array.from(
+ document.querySelectorAll('#storybook-root tbody tr'),
+ ).map(row => row.children[1] as HTMLElement);
+ return cells.map(cell => {
+ const range = document.createRange();
+ range.selectNodeContents(cell);
+ const tops = new Set<number>();
+ for (const rect of Array.from(range.getClientRects())) {
+ if (rect.width > 0) {
+ tops.add(Math.round(rect.top));
+ }
+ }
+ return {text: (cell.textContent ?? '').trim(), lines: tops.size};
+ });
+ });
+ // Each route renders on a single line — not split across two.
+ for (const route of routeLines) {
+ expect(route.lines, `route ${route.text} should stay on one line`).toBe(1);
+ }
+
+ // The method column still reads: `DELETE` is not clipped to `DELE…`.
+ const method = table.headers[0];
+ expect(method.text).toBe('Method');
+ expect(method.scrollWidth).toBeLessThanOrEqual(method.clientWidth + 1);
+ // And the table takes the width it needs through its own scroll region.
+ expect(table.scrollWidth).toBeGreaterThan(table.clientWidth);
+ expect(table.tabIndex).toBe('0');
+ expect(table.blockScrollWidth).toBeLessThanOrEqual(
+ table.blockClientWidth + 1,
+ );
+});
+
+test('a comparison matrix keeps long headers readable over short cells', async ({
+ page,
+}) => {
+ // Headers longer than everything beneath them: the case where truncation
+ // used to make a column unreadable (`Availabl…`). The header drives the
+ // column's floor, so it reads in full rather than being cut; whether it
+ // then fits on one line is layout's business, and the wide-content story
+ // covers the case where a label is long enough to wrap.
+ await openStory(page, COMPARISON_STORY, 390);
+ const story = await measure(page, LONG_TOKEN_CHARS);
+ evidence.push({
+ storyId: COMPARISON_STORY,
+ width: 390,
+ longHeaders: true,
+ ...story,
+ });
+ const table = story.tables[0];
+
+ const freePlan = table.headers.find(header =>
+ header.text.startsWith('Available on'),
+ );
+ expect(freePlan, 'the long header should be present').toBeDefined();
+ // Reads in full: nothing clipped, nothing ellipsized, no nowrap clamp.
+ expect(freePlan?.textOverflow).not.toBe('ellipsis');
+ expect(freePlan?.whiteSpace).not.toBe('nowrap');
+ expect(freePlan?.scrollWidth).toBeLessThanOrEqual(
+ (freePlan?.clientWidth ?? 0) + 1,
+ );
+ // The header carries the column past its short cells: the label's own
+ // floor is 20ch (the one-line cap), far more than `No` would ask for.
+ expect(freePlan?.contentWidth).toBeGreaterThanOrEqual(20 * table.chPx - 1);
+ // Every other header is readable too, including the shortest column.
+ for (const header of table.headers) {
+ expect(header.scrollWidth).toBeLessThanOrEqual(header.clientWidth + 1);
+ expect(header.contentWidth).toBeGreaterThanOrEqual(4 * table.chPx - 1);
+ }
+});
+
+test('a chat message carries a realistic table with one scroll owner', async ({
+ page,
+}) => {
+ for (const width of [320, 390]) {
+ await openStory(page, CHAT_STORY, width);
+ const story = await measure(page, LONG_TOKEN_CHARS);
+ evidence.push({storyId: CHAT_STORY, width, chat: true, ...story});
+ const table = story.tables[0];
+
+ // The bubble adds no scroller of its own, and no second focus stop.
+ expect(story.groupsInStory).toBe(1);
+ expect(table.label).toBe('Table');
+ expect(table.blockRole).toBeNull();
+ expect(table.blockScrollWidth).toBeLessThanOrEqual(
+ table.blockClientWidth + 1,
+ );
+ // Version strings survive the narrowest bubble.
+ expect(table.brokenTokens).toEqual([]);
+ const bubbleOverflows = await page.evaluate(() => {
+ const bubble = document.querySelector('.astryx-chat-message-bubble');
+ return bubble == null
+ ? null
+ : bubble.scrollWidth > bubble.clientWidth + 1;
+ });
+ expect(bubbleOverflows).toBe(false);
+ }
+});
+
+test('a column floor survives the cell padding it sits behind', async ({
+ page,
+}) => {
+ // The floor is a `ch` count on the cell's text box. Border-box padding used
+ // to eat it: a 4ch floor delivered about 1.5 characters of text, and the old
+ // fixed buckets capped a column at 120px however long its content was.
+ // Measure the content box against the floor the renderer asked for.
+ await openStory(page, WIDE_CONTENT_STORY, 390);
+ const wideStory = await measure(page, LONG_TOKEN_CHARS);
+ evidence.push({
+ storyId: WIDE_CONTENT_STORY,
+ width: 390,
+ paddingCorrect: true,
+ ...wideStory,
+ });
+ const wide = wideStory.tables[0];
+ const identifier = wide.headers.find(header => header.text === 'Identifier');
+ const longLabel = wide.headers.find(header =>
+ header.text.startsWith('Accessibility status'),
+ );
+ // `D116586407` is ten characters and cannot break: the column carries it.
+ expect(identifier?.contentWidth).toBeGreaterThanOrEqual(10 * wide.chPx - 1);
+ // A 42-character label floors the column at 21ch (its body floor) and wraps.
+ expect(longLabel?.contentWidth).toBeGreaterThanOrEqual(20 * wide.chPx - 1);
+ expect(longLabel?.lines).toBeGreaterThan(1);
+
+ await openStory(page, SHORT_COLUMNS_STORY, 390);
+ const shortStory = await measure(page, LONG_TOKEN_CHARS);
+ evidence.push({
+ storyId: SHORT_COLUMNS_STORY,
+ width: 390,
+ paddingCorrect: true,
+ ...shortStory,
+ });
+ for (const header of shortStory.tables[0].headers) {
+ expect(
+ header.contentWidth,
+ `header "${header.text}" should keep at least 4ch of text box`,
+ ).toBeGreaterThanOrEqual(4 * shortStory.tables[0].chPx - 1);
+ }
+});