An open source design system that's fully customizable and agent ready
TypeScript
feat(table): add column alignment and row vertical alignment (#1362)
Kenton Quatman5002235282b2
diff --git a/apps/storybook/stories/Table.stories.tsx b/apps/storybook/stories/Table.stories.tsxindex fb8fb2b743..735be11c11 100644--- a/apps/storybook/stories/Table.stories.tsx+++ b/apps/storybook/stories/Table.stories.tsx@@ -116,6 +116,11 @@ const meta: Meta<typeof XDSTable> = {control: 'boolean',description: 'Highlight rows on hover',},+ verticalAlign: {+ control: 'select',+ options: ['middle', 'top', 'bottom'],+ description: 'Vertical alignment for body row cells',+ },},};@@ -628,3 +633,166 @@ export const StandaloneVsContainer: Story = {</div>),};++// =============================================================================+// Column Alignment+// =============================================================================++interface Transaction extends Record<string, unknown> {+ id: string;+ description: string;+ category: string;+ quantity: number;+ amount: string;+}++const transactions: Transaction[] = [+ {+ id: '1',+ description: 'Cloud hosting (monthly)',+ category: 'Infrastructure',+ quantity: 1,+ amount: '$2,400.00',+ },+ {+ id: '2',+ description: 'Design software licenses',+ category: 'Tools',+ quantity: 12,+ amount: '$1,188.00',+ },+ {+ id: '3',+ description: 'Team offsite catering',+ category: 'Events',+ quantity: 45,+ amount: '$3,150.00',+ },+ {+ id: '4',+ description: 'Ergonomic keyboards',+ category: 'Hardware',+ quantity: 8,+ amount: '$1,592.00',+ },+ {+ id: '5',+ description: 'Annual conference tickets',+ category: 'Travel',+ quantity: 3,+ amount: '$4,500.00',+ },+];++const alignedColumns: XDSTableColumn<Transaction>[] = [+ {key: 'description', header: 'Description', width: proportional(2)},+ {key: 'category', header: 'Category'},+ {key: 'quantity', header: 'Qty', align: 'center', width: pixel(80)},+ {key: 'amount', header: 'Amount', align: 'end', width: pixel(120)},+];++/**+ * Per-column horizontal alignment via the `align` prop.+ *+ * - `'start'` (default) — left in LTR, right in RTL+ * - `'center'` — centered text+ * - `'end'` — right in LTR, left in RTL+ *+ * Alignment applies to both the header `<th>` and body `<td>` cells.+ * Numeric columns typically use `align: 'end'`, while status or icon+ * columns work well with `align: 'center'`.+ */+export const ColumnAlignment: Story = {+ render: () => (+ <XDSTable+ data={transactions}+ columns={alignedColumns}+ idKey="id"+ hasHover+ dividers="rows"+ />+ ),+};++// =============================================================================+// Vertical Alignment+// =============================================================================++interface TeamMember extends Record<string, unknown> {+ id: string;+ name: string;+ bio: string;+ role: string;+}++const teamMembers: TeamMember[] = [+ {+ id: '1',+ name: 'Alice Johnson',+ bio: 'Full-stack engineer with 8 years of experience. Specializes in distributed systems and performance optimization. Previously at Stripe and Google.',+ role: 'Staff Engineer',+ },+ {+ id: '2',+ name: 'Bob Smith',+ bio: 'Product designer focused on design systems and accessibility.',+ role: 'Senior Designer',+ },+ {+ id: '3',+ name: 'Charlie Brown',+ bio: 'Engineering manager leading the platform team. Passionate about developer experience, tooling, and building inclusive teams that ship with confidence.',+ role: 'EM',+ },+];++const verticalAlignColumns: XDSTableColumn<TeamMember>[] = [+ {key: 'name', header: 'Name', width: pixel(140)},+ {+ key: 'bio',+ header: 'Bio',+ width: proportional(3),+ renderCell: item => (+ <span+ style={{+ whiteSpace: 'normal',+ overflow: 'visible',+ display: 'block',+ }}>+ {item.bio}+ </span>+ ),+ },+ {key: 'role', header: 'Role', align: 'end', width: pixel(140)},+];++/**+ * Compares all three `verticalAlign` options side by side.+ *+ * - `'middle'` (default) — vertically centers cell content+ * - `'top'` — aligns to the top, useful for multi-line cells+ * - `'bottom'` — aligns to the bottom+ *+ * Uses a multi-line "Bio" column with wrapping text to make+ * the vertical alignment difference visible.+ */+export const VerticalAlignment: Story = {+ render: () => (+ <div style={{display: 'flex', flexDirection: 'column', gap: '32px'}}>+ {(['middle', 'top', 'bottom'] as const).map(vAlign => (+ <div key={vAlign}>+ <p style={{margin: '0 0 8px', fontWeight: 600}}>+ verticalAlign="{vAlign}"+ </p>+ <XDSTable+ data={teamMembers}+ columns={verticalAlignColumns}+ idKey="id"+ verticalAlign={vAlign}+ dividers="rows"+ />+ </div>+ ))}+ </div>+ ),+};diff --git a/packages/core/src/Table/Table.doc.mjs b/packages/core/src/Table/Table.doc.mjsindex a4c9750f25..7b39729bf1 100644--- a/packages/core/src/Table/Table.doc.mjs+++ b/packages/core/src/Table/Table.doc.mjs@@ -12,6 +12,8 @@ export const docs = {'Plugin system — extend table behavior with composable transform plugins','Density variants: compact, balanced, spacious','Divider styles: rows, columns, grid, none',+ 'Column alignment: start (default), center, end — per-column via align prop',+ 'Row vertical alignment: middle (default), top, bottom — table-level via verticalAlign prop','Striped even rows and hover highlight via XDSTableContext','Selection via useXDSTableSelectionState + useXDSTableSelection — checkboxes, select-all, disabled row handling','Sorting via useXDSTableSortable — single or multi-column sort with header indicators',@@ -75,6 +77,19 @@ export const docs = {label: 'Auto-generated columns',code: `// Columns auto-generated from data keys with capitalized headers<XDSTable data={users} isStriped />`,+ },+ {+ label: 'Column alignment and vertical alignment',+ code: `<XDSTable+ data={transactions}+ columns={[+ { key: 'description', header: 'Description' },+ { key: 'quantity', header: 'Qty', align: 'center', width: pixel(80) },+ { key: 'amount', header: 'Amount', align: 'end', width: pixel(120) },+ ]}+ verticalAlign="top"+ density="balanced"+/>`,},{label: 'Rich cell content with renderCell',diff --git a/packages/core/src/Table/XDSBaseTable.tsx b/packages/core/src/Table/XDSBaseTable.tsxindex 0ce61c889c..38e013571d 100644--- a/packages/core/src/Table/XDSBaseTable.tsx+++ b/packages/core/src/Table/XDSBaseTable.tsx@@ -133,10 +133,16 @@ function TableRowInner<T extends Record<string, unknown>>({}: TableRowProps<T>): ReactElement {// Build cells firstconst cells = columns.map(col => {+ // Apply column alignment to body cells+ const initialCellHtmlProps: Record<string, unknown> = {};+ if (col.align) {+ initialCellHtmlProps.style = {textAlign: col.align};+ }+const cellRenderProps = applyPlugins(plugins,p => p.transformBodyCell,- {htmlProps: {}, styles: []} as BodyCellRenderProps,+ {htmlProps: initialCellHtmlProps, styles: []} as BodyCellRenderProps,col,item,);@@ -293,11 +299,19 @@ function XDSBaseTableInner<T extends Record<string, unknown>>({const headerCells = resolvedColumns.map(col => {const headerContent = col.header ?? col.key;+ // Build initial htmlProps with column alignment if specified+ const initialHeaderHtmlProps: Record<string, unknown> = {+ 'data-column-key': col.key,+ };+ if (col.align) {+ initialHeaderHtmlProps.style = {textAlign: col.align};+ }+const cellRenderProps = applyPlugins(plugins,p => p.transformHeaderCell,{- htmlProps: {'data-column-key': col.key},+ htmlProps: initialHeaderHtmlProps,styles: [],content: headerContent,} as HeaderCellRenderProps,diff --git a/packages/core/src/Table/XDSTable.test.tsx b/packages/core/src/Table/XDSTable.test.tsxindex 27bcfc9c4e..6173cdd0d4 100644--- a/packages/core/src/Table/XDSTable.test.tsx+++ b/packages/core/src/Table/XDSTable.test.tsx@@ -912,6 +912,110 @@ describe('XDSTableCell', () => {});});+// =============================================================================+// Column Alignment Tests+// =============================================================================++describe('column alignment', () => {+ it('applies textAlign to header and body cells via inline style', () => {+ const {container} = render(+ <XDSTable+ data={users}+ columns={[+ {key: 'name', header: 'Name'},+ {key: 'age', header: 'Age', align: 'end'},+ {key: 'email', header: 'Email', align: 'center'},+ ]}+ />,+ );++ const headerCells = container.querySelectorAll('th');+ // First column: no explicit align (default 'start' is handled by CSS default)+ expect(headerCells[0]).not.toHaveStyle({textAlign: 'end'});+ expect(headerCells[0]).not.toHaveStyle({textAlign: 'center'});+ // Second column: end aligned+ expect(headerCells[1]).toHaveStyle({textAlign: 'end'});+ // Third column: center aligned+ expect(headerCells[2]).toHaveStyle({textAlign: 'center'});++ const bodyRows = container.querySelectorAll('tbody tr');+ const firstRowCells = bodyRows[0].querySelectorAll('td');+ expect(firstRowCells[1]).toHaveStyle({textAlign: 'end'});+ expect(firstRowCells[2]).toHaveStyle({textAlign: 'center'});+ });++ it('defaults to start alignment when align is not specified', () => {+ const {container} = render(+ <XDSTable data={users} columns={[{key: 'name', header: 'Name'}]} />,+ );++ const headerCell = container.querySelector('th');+ // No textAlign inline style when default+ expect(headerCell?.style.textAlign).toBeFalsy();+ });++ it('applies align through the plugin pipeline on XDSBaseTable', () => {+ const {container} = render(+ <XDSBaseTable+ data={users}+ columns={[+ {key: 'name', header: 'Name', align: 'center'},+ {key: 'age', header: 'Age', align: 'end'},+ ]}+ />,+ );++ const headerCells = container.querySelectorAll('th');+ expect(headerCells[0]).toHaveStyle({textAlign: 'center'});+ expect(headerCells[1]).toHaveStyle({textAlign: 'end'});++ const bodyCells = container.querySelectorAll('tbody td');+ expect(bodyCells[0]).toHaveStyle({textAlign: 'center'});+ expect(bodyCells[1]).toHaveStyle({textAlign: 'end'});+ });+});++// =============================================================================+// Vertical Alignment Tests+// =============================================================================++describe('vertical alignment', () => {+ it('defaults to middle vertical alignment', () => {+ const {container} = render(+ <XDSTable data={users} columns={[{key: 'name', header: 'Name'}]} />,+ );++ const bodyCell = container.querySelector('tbody td');+ expect(bodyCell).toHaveStyle({verticalAlign: 'middle'});+ });++ it('applies top vertical alignment', () => {+ const {container} = render(+ <XDSTable+ data={users}+ columns={[{key: 'name', header: 'Name'}]}+ verticalAlign="top"+ />,+ );++ const bodyCell = container.querySelector('tbody td');+ expect(bodyCell).toHaveStyle({verticalAlign: 'top'});+ });++ it('applies bottom vertical alignment', () => {+ const {container} = render(+ <XDSTable+ data={users}+ columns={[{key: 'name', header: 'Name'}]}+ verticalAlign="bottom"+ />,+ );++ const bodyCell = container.querySelector('tbody td');+ expect(bodyCell).toHaveStyle({verticalAlign: 'bottom'});+ });+});+describe('emptyState', () => {it('renders default empty state when data is empty', () => {render(diff --git a/packages/core/src/Table/XDSTable.tsx b/packages/core/src/Table/XDSTable.tsxindex 982eab9758..3cb590bf6b 100644--- a/packages/core/src/Table/XDSTable.tsx+++ b/packages/core/src/Table/XDSTable.tsx@@ -24,6 +24,7 @@ import {XDSTableContext} from './XDSTableContext';import {useXDSBaseTablePlugins} from './useXDSBaseTablePlugins';import type {XDSBaseTableProps,+ XDSTableVerticalAlign,TablePlugin,TableRenderProps,TableRowComponentProps,@@ -62,6 +63,19 @@ export interface XDSTableProps<T extends Record<string, unknown>> extends Omit<isStriped?: boolean;/** Hover highlight on rows. @default false */hasHover?: boolean;+ /**+ * Vertical alignment for body row cells.+ * Controls `vertical-align` on `<td>` elements.+ *+ * @default 'middle'+ *+ * @example+ * ```+ * // Top-align rows for multi-line cell content+ * <XDSTable data={items} columns={columns} verticalAlign="top" />+ * ```+ */+ verticalAlign?: XDSTableVerticalAlign;/** Named plugins to extend table behavior */plugins?: Record<string, TablePlugin<T>>;}@@ -135,6 +149,7 @@ function XDSTableInner<T extends Record<string, unknown>>({dividers = 'rows',isStriped = false,hasHover = false,+ verticalAlign = 'middle',plugins: userPlugins,columns,data,@@ -149,8 +164,8 @@ function XDSTableInner<T extends Record<string, unknown>>({const mergedPlugins = useXDSBaseTablePlugins<T>(basePlugins, userPlugins);const contextValue = useMemo(- () => ({density, dividers, isStriped, hasHover}),- [density, dividers, isStriped, hasHover],+ () => ({density, dividers, isStriped, hasHover, verticalAlign}),+ [density, dividers, isStriped, hasHover, verticalAlign],);return (diff --git a/packages/core/src/Table/XDSTableCell.tsx b/packages/core/src/Table/XDSTableCell.tsxindex f835d994f8..88ba92d2e4 100644--- a/packages/core/src/Table/XDSTableCell.tsx+++ b/packages/core/src/Table/XDSTableCell.tsx@@ -90,6 +90,18 @@ const dividerColumnStyles = stylex.create({},});+const verticalAlignStyles = stylex.create({+ middle: {+ verticalAlign: 'middle',+ },+ top: {+ verticalAlign: 'top',+ },+ bottom: {+ verticalAlign: 'bottom',+ },+});+/*** XDSTableCell — a `<td>` wrapper for children/streaming mode.*@@ -108,6 +120,8 @@ export function XDSTableCell({children,xstyle,ref,+ className: incomingClassName,+ style: incomingStyle,...props}: XDSTableCellProps) {const ctx = useTableContext();@@ -117,7 +131,12 @@ export function XDSTableCell({<tdref={ref}{...props}- {...mergeProps(xdsClassName('table-cell'), stylex.props(xstyle))}>+ {...mergeProps(+ xdsClassName('table-cell'),+ stylex.props(xstyle),+ incomingClassName,+ incomingStyle as React.CSSProperties,+ )}>{children}</td>);@@ -127,6 +146,7 @@ export function XDSTableCell({densityStyles[ctx.density],overflowStyles.cell,containerEdgeStyles[ctx.density],+ verticalAlignStyles[ctx.verticalAlign],...buildDividerStyles(ctx, dividerRowStyles.cell, dividerColumnStyles.cell),];@@ -137,6 +157,8 @@ export function XDSTableCell({{...mergeProps(xdsClassName('table-cell'),stylex.props(...mergeXStyle(cellStyles, xstyle)),+ incomingClassName,+ incomingStyle as React.CSSProperties,)}>{children}</td>diff --git a/packages/core/src/Table/XDSTableContext.ts b/packages/core/src/Table/XDSTableContext.tsindex ca98ec464f..2910a14bcf 100644--- a/packages/core/src/Table/XDSTableContext.ts+++ b/packages/core/src/Table/XDSTableContext.ts@@ -13,14 +13,15 @@* - /packages/core/src/Table/index.ts (exports if types change)*/-import {createContext} from 'react';+import type {XDSTableVerticalAlign} from './types';export interface XDSTableContextValue {density: 'compact' | 'balanced' | 'spacious';dividers: 'rows' | 'columns' | 'grid' | 'none';isStriped: boolean;hasHover: boolean;+ verticalAlign: XDSTableVerticalAlign;}export const XDSTableContext = createContext<XDSTableContextValue | null>(null);diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.tsindex 31889fd1be..647f0a4685 100644--- a/packages/core/src/Table/index.ts+++ b/packages/core/src/Table/index.ts@@ -38,6 +38,8 @@ export {} from './columnUtils';export type {XDSTableColumn,+ XDSTableColumnAlign,+ XDSTableVerticalAlign,ColumnWidth,ProportionalWidth,PixelWidth,diff --git a/packages/core/src/Table/types.ts b/packages/core/src/Table/types.tsindex df7d497458..033f17fea8 100644--- a/packages/core/src/Table/types.ts+++ b/packages/core/src/Table/types.ts@@ -66,6 +66,30 @@ export interface XDSTableSortableColumnConfig {sortKey?: string;}+// =============================================================================+// Column Alignment+// =============================================================================++/**+ * Horizontal text alignment for a table column.+ * Applied to both the `<th>` and `<td>` elements.+ *+ * @default 'start'+ */+export type XDSTableColumnAlign = 'start' | 'center' | 'end';++// =============================================================================+// Row Vertical Alignment+// =============================================================================++/**+ * Vertical alignment for table body row cells.+ * Controls `vertical-align` on `<td>` elements.+ *+ * @default 'middle'+ */+export type XDSTableVerticalAlign = 'middle' | 'top' | 'bottom';+// =============================================================================// Column Definition// =============================================================================@@ -82,6 +106,22 @@ export interface XDSTableColumn<T extends Record<string, unknown>> {header?: ReactNode;/** Column width. Defaults to `proportional(1)`. */width?: ColumnWidth;+ /**+ * Horizontal text alignment for this column.+ * Applied to both the header `<th>` and body `<td>` cells.+ *+ * @default 'start'+ *+ * @example+ * ```+ * // Right-align a numeric column+ * { key: 'amount', header: 'Amount', align: 'end' }+ *+ * // Center-align a status column+ * { key: 'status', header: 'Status', align: 'center' }+ * ```+ */+ align?: XDSTableColumnAlign;/*** Sortable configuration for this column.* Set to `true` for default behavior (sortKey = column.key),