An open source design system that's fully customizable and agent ready
TypeScript
feat(Table): content-aware column widths, auto layout for children mode, default wrap (#2105)
Cindy Zhangac290922f12f
diff --git a/packages/core/src/Markdown/XDSMarkdown.tsx b/packages/core/src/Markdown/XDSMarkdown.tsxindex c9685ed9af..659f7e448a 100644--- a/packages/core/src/Markdown/XDSMarkdown.tsx+++ b/packages/core/src/Markdown/XDSMarkdown.tsx@@ -202,6 +202,14 @@ const dynamicStyles = stylex.create({blockAlign: (marginInline: string) => ({marginInline,}),+ cellMinWidth: (minWidth: string) => ({+ minWidth,+ }),+});++const cellAlignStyles = stylex.create({+ center: {textAlign: 'center'},+ right: {textAlign: 'right'},});const styles = stylex.create({@@ -969,6 +977,26 @@ function getElementSpacing(// Block renderer// ---------------------------------------------------------------------------+/**+ * Compute per-column min-widths from table AST content.+ * Buckets: ≤6 chars → 60px, 7–15 → 80px, >15 → 120px.+ */+function computeTableColumnMinWidths(node: {+ headers: {children: InlineNode[]}[];+ rows: {children: InlineNode[]}[][];+}): number[] {+ return node.headers.map((h, colIdx) => {+ let maxLen = countInlineTextLength(h.children);+ for (const row of node.rows) {+ if (row[colIdx]) {+ const len = countInlineTextLength(row[colIdx].children);+ if (len > maxLen) maxLen = len;+ }+ }+ return maxLen <= 6 ? 60 : maxLen <= 15 ? 80 : 120;+ });+}+function renderBlock(node: BlockNode,index: number,@@ -1346,19 +1374,13 @@ function renderBlock();}case 'table': {+ const colMinWidths = computeTableColumnMinWidths(node);+return (<divkey={index}{...stylex.props(- styles.tableWrapper,spacing,- styles.blockIndent,- contentWidthValue != null- ? dynamicStyles.blockWidth(contentWidthValue)- : null,- BLOCK_ALIGN_MARGIN[contentAlign] != null- ? dynamicStyles.blockAlign(BLOCK_ALIGN_MARGIN[contentAlign]!)- : null,isFirst && styles.noMarginBlockStart,isLast && styles.noMarginBlockEnd,)}>@@ -1368,13 +1390,11 @@ function renderBlock({node.headers.map((h, i) => (<XDSTableHeaderCellkey={i}- style={- node.alignments[i] === 'center'- ? {textAlign: 'center'}- : node.alignments[i] === 'right'- ? {textAlign: 'right'}- : undefined- }>+ {...stylex.props(+ dynamicStyles.cellMinWidth(`${colMinWidths[i]}px`),+ node.alignments[i] === 'center' && cellAlignStyles.center,+ node.alignments[i] === 'right' && cellAlignStyles.right,+ )}>{h.children.map((c, j) =>renderInline(c, j, onLinkClick, cursor, citationCtx, linkComponent, inlinePlugins, components),)}@@ -1389,13 +1409,10 @@ function renderBlock(const cells = row.map((cell, j) => (<XDSTableCellkey={j}- style={- node.alignments[j] === 'center'- ? {textAlign: 'center'}- : node.alignments[j] === 'right'- ? {textAlign: 'right'}- : undefined- }>+ {...stylex.props(+ node.alignments[j] === 'center' && cellAlignStyles.center,+ node.alignments[j] === 'right' && cellAlignStyles.right,+ )}>{cell.children.map((c, k) =>renderInline(c, k, onLinkClick, cursor, citationCtx, linkComponent, inlinePlugins, components),)}diff --git a/packages/core/src/Table/XDSBaseTable.tsx b/packages/core/src/Table/XDSBaseTable.tsxindex 25ed72c393..6b232f99ae 100644--- a/packages/core/src/Table/XDSBaseTable.tsx+++ b/packages/core/src/Table/XDSBaseTable.tsx@@ -49,6 +49,9 @@ const styles = stylex.create({borderSpacing: '0',tableLayout: 'fixed',},+ tableAutoLayout: {+ tableLayout: 'auto',+ },/*** Inline flex row that keeps the header label and any "after" slot content* (sort icons, filter buttons, etc.) on the same line with a small gap.@@ -308,7 +311,7 @@ function XDSBaseTableInner<T extends Record<string, unknown>>({// --- Plugin pipeline: table ---const tableRenderProps = applyPlugins(plugins, p => p.transformTable, {htmlProps: {...userTableProps},- styles: [styles.table],+ styles: children ? [styles.table, styles.tableAutoLayout] : [styles.table],} as TableRenderProps);// --- Plugin pipeline: header cells ---diff --git a/packages/core/src/Table/XDSTable.test.tsx b/packages/core/src/Table/XDSTable.test.tsxindex f73541adec..5551162ddb 100644--- a/packages/core/src/Table/XDSTable.test.tsx+++ b/packages/core/src/Table/XDSTable.test.tsx@@ -17,10 +17,11 @@ import {proportional,pixel,generateColumns,+ resolveColumnWidths,capitalize,DEFAULT_MIN_COLUMN_WIDTH,} from './columnUtils';-import type {TablePlugin, XDSTableColumn} from './types';+import type {TablePlugin, XDSTableColumn, ProportionalWidth} from './types';// =============================================================================// Test Data@@ -106,15 +107,80 @@ describe('columnUtils', () => {expect(generateColumns([])).toEqual([]);});- it('assigns proportional(1) width with default minWidth to each column', () => {+ it('assigns content-proportional widths based on data analysis', () => {const cols = generateColumns(users);+ // All columns should have proportional typefor (const col of cols) {- expect(col.width).toEqual({- type: 'proportional',- value: 1,- minWidth: DEFAULT_MIN_COLUMN_WIDTH,- });+ expect(col.width?.type).toBe('proportional');}+ // Columns with longer content should get higher proportion+ const emailCol = cols.find(c => c.key === 'email')!;+ const ageCol = cols.find(c => c.key === 'age')!;+ expect(emailCol.width!.value).toBeGreaterThan(ageCol.width!.value);+ });++ it('derives min-width from header or longest word', () => {+ const cols = generateColumns(users);+ for (const col of cols) {+ // Min-width should be at least the floor+ expect((col.width as ProportionalWidth).minWidth).toBeGreaterThanOrEqual(60);+ }+ });++ it('produces stable width values for known data', () => {+ const cols = generateColumns(users);+ // Snapshot: these values should remain stable over time.+ // name: "Charlie" (7 chars) → medium → proportion 2+ // age: "35" (2 chars) → short → proportion 1+ // email: "[email protected]" (19 chars) → long → proportion 3+ const nameCol = cols.find(c => c.key === 'name')!;+ const ageCol = cols.find(c => c.key === 'age')!;+ const emailCol = cols.find(c => c.key === 'email')!;++ expect(nameCol.width).toEqual({+ type: 'proportional',+ value: 2,+ minWidth: 60, // max("Name"=4, "Charlie"=7) * 8 = 56 → floor 60+ });+ expect(ageCol.width).toEqual({+ type: 'proportional',+ value: 1,+ minWidth: 60, // max("Age"=3, "35"=2) * 8 = 24 → floor 60+ });+ expect(emailCol.width).toEqual({+ type: 'proportional',+ value: 3,+ minWidth: 152, // max("Email"=5, "[email protected]"=19) * 8 = 152+ });+ });++ it('does not analyze non-string/number values', () => {+ const data = [+ {id: 1, meta: {nested: 'object'}, tags: ['a', 'b']},+ {id: 2, meta: {nested: 'thing'}, tags: ['c']},+ ];+ const cols = generateColumns(data);+ // meta and tags are objects/arrays — should get 0 content length+ // so their proportion comes only from header length+ const metaCol = cols.find(c => c.key === 'meta')!;+ const tagsCol = cols.find(c => c.key === 'tags')!;+ // Header "Meta" = 4, "Tags" = 4 — both should have same proportion+ expect((metaCol.width as ProportionalWidth).value).toBe(+ (tagsCol.width as ProportionalWidth).value,+ );+ });++ it('never overrides explicit column widths', () => {+ // generateColumns is only called when no columns prop is provided.+ // This test verifies the contract: explicit widths pass through unchanged.+ const explicit: XDSTableColumn<User>[] = [+ {key: 'name', header: 'Name', width: pixel(200)},+ {key: 'email', header: 'Email', width: proportional(3, {minWidth: 300})},+ ];+ // resolveColumnWidths should use the explicit values, not re-derive+ const resolved = resolveColumnWidths(explicit);+ expect(resolved.columns.get('name')?.style.width).toBe('200px');+ expect(resolved.columns.get('email')?.style.minWidth).toBe('300px');});});@@ -465,11 +531,13 @@ describe('XDSBaseTable', () => {});});- it('applies default minWidth on auto-generated columns', () => {+ it('applies content-derived minWidth on auto-generated columns', () => {render(<XDSBaseTable data={users} />);const headers = screen.getAllByRole('columnheader');for (const header of headers) {- expect(header).toHaveStyle({minWidth: `${DEFAULT_MIN_COLUMN_WIDTH}px`});+ // Each column should have a minWidth derived from content (at least 60px floor)+ const style = header.getAttribute('style') ?? '';+ expect(style).toContain('min-width');}});@@ -550,6 +618,27 @@ describe('XDSTable', () => {expect(wrapper!.className).toContain('xds-table-scroll-wrapper');});+ it('uses table-layout: auto in children mode', () => {+ const {container} = render(+ <XDSTable dividers="rows">+ <tbody>+ <tr><td>Content</td></tr>+ </tbody>+ </XDSTable>,+ );+ const table = container.querySelector('table');+ expect(table).toHaveStyle({tableLayout: 'auto'});+ });++ it('uses table-layout: fixed in data-driven mode', () => {+ const {container} = render(+ <XDSTable data={users} columns={columns} />,+ );+ const table = container.querySelector('table');+ expect(table).toHaveStyle({tableLayout: 'fixed'});+ });++it('renders all data values', () => {render(<XDSTable data={users} columns={columns} />);expect(screen.getByText('Alice')).toBeInTheDocument();@@ -732,13 +821,12 @@ describe('XDSTable', () => {);});- it('truncates text by default (textOverflow="truncate")', () => {+ it('wraps text by default (textOverflow="wrap")', () => {render(<XDSTable data={users} columns={columns} />);const cells = screen.getAllByRole('cell');- // Default-rendered cells contain an XDSText child element (a <span>)- const textEl = cells[0].querySelector('span');- expect(textEl).toBeTruthy();- expect(textEl).toHaveTextContent('Alice');+ // In wrap mode, no XDSText wrapper — content renders directly+ expect(cells[0]).toHaveTextContent('Alice');+ expect(cells[0]).not.toHaveAttribute('title');});it('wraps text when textOverflow="wrap"', () => {diff --git a/packages/core/src/Table/XDSTable.tsx b/packages/core/src/Table/XDSTable.tsxindex f407771924..cf97511b72 100644--- a/packages/core/src/Table/XDSTable.tsx+++ b/packages/core/src/Table/XDSTable.tsx@@ -85,7 +85,7 @@ export interface XDSTableProps<T extends Record<string, unknown>> extends Omit<** Header cells always truncate regardless of this setting.*- * @default 'truncate'+ * @default 'wrap'** @example* ```@@ -181,7 +181,7 @@ function XDSTableInner<T extends Record<string, unknown>>({isStriped = false,hasHover = false,verticalAlign = 'middle',- textOverflow = 'truncate',+ textOverflow = 'wrap',plugins: userPlugins,columns,data,diff --git a/packages/core/src/Table/columnUtils.ts b/packages/core/src/Table/columnUtils.tsindex 033442627d..c28a3e624a 100644--- a/packages/core/src/Table/columnUtils.ts+++ b/packages/core/src/Table/columnUtils.ts@@ -179,18 +179,98 @@ export function defaultCellRenderer<T extends Record<string, unknown>>(return String(value);}+/**+ * Estimate the display width of a value in characters.+ * Only measures string and number values — objects, arrays, and other+ * complex types return 0 (fall back to equal proportioning for that cell).+ */+function estimateContentLength(value: unknown): number {+ if (value == null) return 0;+ if (typeof value === 'string') return value.length;+ if (typeof value === 'number' || typeof value === 'boolean') return String(value).length;+ return 0;+}++/**+ * Find the longest single word in a value (for min-width estimation).+ * A "word" is a contiguous non-whitespace sequence.+ * Only measures string and number values — complex types return 0.+ */+function longestWord(value: unknown): number {+ if (value == null) return 0;+ if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') return 0;+ const str = String(value);+ let max = 0;+ let current = 0;+ for (let i = 0; i <= str.length; i++) {+ if (i === str.length || str[i] === ' ' || str[i] === '\t' || str[i] === '\n') {+ if (current > max) max = current;+ current = 0;+ } else {+ current++;+ }+ }+ return max;+}++/** Minimum floor for any column (px). Prevents collapse on narrow viewports. */+const MIN_COLUMN_FLOOR = 60;++/** Scale factor: approximate px per character for min-width calculation. */+const PX_PER_CHAR = 8;+/*** Auto-generate column definitions from the keys of the first data item.- * Each column gets `proportional(1)` width and a capitalized header.+ * Derives content-proportional widths by analyzing the header and first+ * few rows of data. Min-width is based on the longer of: header text+ * or the longest single word in values.*/export function generateColumns<T extends Record<string, unknown>>(data: T[],): XDSTableColumn<T>[] {if (data.length === 0) return [];const firstItem = data[0];- return Object.keys(firstItem).map(key => ({- key,- header: capitalize(key),- width: proportional(1),- }));+ const keys = Object.keys(firstItem);++ // Sample first few rows for content analysis+ const sampleRows = data.slice(0, Math.min(5, data.length));++ // Measure each column+ const measurements = keys.map(key => {+ const headerLen = capitalize(key).length;++ let maxContentLen = headerLen;+ let maxWordLen = headerLen; // header is a single "word" for min-width purposes++ for (const row of sampleRows) {+ const contentLen = estimateContentLength(row[key]);+ if (contentLen > maxContentLen) maxContentLen = contentLen;++ const wordLen = longestWord(row[key]);+ if (wordLen > maxWordLen) maxWordLen = wordLen;+ }++ return {key, headerLen, maxContentLen, maxWordLen};+ });++ return measurements.map(m => {+ // Bucket content length into proportional tiers:+ // 1 = short (≤6 chars: IDs, ages, booleans, status)+ // 2 = medium (7–15 chars: names, dates, short strings)+ // 3 = long (>15 chars: emails, URLs, descriptions)+ const proportion =+ m.maxContentLen <= 6 ? 1 : m.maxContentLen <= 15 ? 2 : 3;++ // Min-width: enough to fit header or longest word without wrapping+ const minWidth = Math.max(+ Math.max(m.headerLen, m.maxWordLen) * PX_PER_CHAR,+ MIN_COLUMN_FLOOR,+ );++ return {+ key: m.key,+ header: capitalize(m.key),+ width: proportional(proportion, {minWidth}),+ };+ });}diff --git a/packages/core/src/Table/types.ts b/packages/core/src/Table/types.tsindex 452dca116e..19fb2d315b 100644--- a/packages/core/src/Table/types.ts+++ b/packages/core/src/Table/types.ts@@ -395,7 +395,7 @@ export interface XDSBaseTableProps<T extends Record<string, unknown>> {* Only affects cells using the default renderer (no `renderCell`).* Cells with `renderCell` control their own overflow behavior.*- * @default 'truncate'+ * @default 'wrap'*/textOverflow?: 'wrap' | 'truncate';/**