An open source design system that's fully customizable and agent ready
TypeScript
Add XDSTable component with plugin-based architecture (#94)
Cindy Zhang318a46bf6365
diff --git a/.context/explorations/rsc-utilities.md b/.context/explorations/rsc-utilities.mdnew file mode 100644index 0000000000..6b614618c8--- /dev/null+++ b/.context/explorations/rsc-utilities.md@@ -0,0 +1,366 @@+# RSC Utilities++Generic primitives for lazy loading, intersection observation, and React Server Component streaming.++## Overview++| Component | Fetches | Renders | Use Case |+| ------------------------ | ----------- | ------------------- | --------------------------- |+| `XDSSkeleton` | — | Shimmer placeholder | Loading states |+| `XDSSpinner` | — | Spinning indicator | In-progress states |+| `XDSIntersectionTrigger` | — | Fires callback | Custom intersection logic |+| `XDSLazy` | Data (JSON) | Client-side | Lazy cell/field values |+| `XDSStream` | RSC flight | Server components | Infinite scroll, pagination |++## XDSSkeleton++Loading placeholder with shimmer animation:++```tsx+<XDSSkeleton /> // Full width+<XDSSkeleton width={100} /> // Fixed width+<XDSSkeleton width="50%" /> // Percentage+<XDSSkeleton height={20} /> // Custom height+<XDSSkeleton shape="circle" /> // Avatar placeholder+<XDSSkeleton animate={false} /> // No animation+```++## XDSSpinner++Loading spinner for in-progress states:++```tsx+<XDSSpinner />+<XDSSpinner size="small" />+<XDSSpinner size="large" />+```++## XDSIntersectionTrigger++Fires a callback when element enters viewport. For client-side pagination with callbacks:++```tsx+<XDSIntersectionTrigger+ onIntersect={loadMore}+ rootMargin="200px"+ disabled={!hasMore}>+ {isLoading && <XDSSpinner />}+</XDSIntersectionTrigger>+```++### Props++```tsx+interface XDSIntersectionTriggerProps {+ onIntersect: () => void; // Callback when visible+ rootMargin?: string; // Intersection margin (default: '100px')+ threshold?: number; // Visibility threshold (default: 0)+ disabled?: boolean; // Disable observation+ children?: ReactNode; // Content to render+}+```++### Implementation++```tsx+'use client';++function XDSIntersectionTrigger({+ onIntersect,+ rootMargin = '100px',+ threshold = 0,+ disabled = false,+ children,+}) {+ const ref = useRef<HTMLDivElement>(null);++ useEffect(() => {+ if (disabled || !ref.current) return;++ const observer = new IntersectionObserver(+ ([entry]) => {+ if (entry.isIntersecting) {+ onIntersect();+ }+ },+ {rootMargin, threshold},+ );++ observer.observe(ref.current);+ return () => observer.disconnect();+ }, [disabled, onIntersect, rootMargin, threshold]);++ return <div ref={ref}>{children}</div>;+}+```++## XDSLazy++Lazy load wrapper that fetches data on intersection and renders client-side:++```tsx+<XDSLazy+ fetch={() => fetchScore(user.id)}+ fallback={<XDSSkeleton width={60} />}>+ {score => <span>{score}</span>}+</XDSLazy>+```++### Props++```tsx+interface XDSLazyProps<T> {+ fetch: () => Promise<T>; // Data fetcher+ fallback: ReactNode; // Loading placeholder+ children: (data: T) => ReactNode; // Render function+ rootMargin?: string; // Intersection margin (default: '100px')+}+```++### Implementation++```tsx+'use client';++function XDSLazy<T>({+ fetch,+ fallback,+ children,+ rootMargin = '100px',+}: XDSLazyProps<T>) {+ const ref = useRef<HTMLDivElement>(null);+ const [data, setData] = useState<T | null>(null);+ const [loading, setLoading] = useState(false);+ const [triggered, setTriggered] = useState(false);++ useEffect(() => {+ if (triggered || !ref.current) return;++ const observer = new IntersectionObserver(+ async ([entry]) => {+ if (entry.isIntersecting) {+ setTriggered(true);+ setLoading(true);+ observer.disconnect();++ try {+ const result = await fetch();+ setData(result);+ } finally {+ setLoading(false);+ }+ }+ },+ {rootMargin},+ );++ observer.observe(ref.current);+ return () => observer.disconnect();+ }, [triggered, fetch, rootMargin]);++ if (data !== null) {+ return <>{children(data)}</>;+ }++ return <div ref={ref}>{loading || triggered ? fallback : null}</div>;+}+```++## XDSStream++Fetches RSC flight response on intersection and renders server components. For React Server Component pagination:++```tsx+<XDSStream+ endpoint="/api/users"+ params={{cursor: nextCursor}}+ loading={<XDSSpinner />}+/>+```++### Props++```tsx+interface XDSStreamProps {+ endpoint: string; // RSC endpoint URL+ params?: Record<string, string>; // Query params (cursor, limit, etc.)+ rootMargin?: string; // Intersection margin (default: '200px')+ loading?: ReactNode; // Loading indicator+ disabled?: boolean; // Disable fetching+}+```++### Implementation++```tsx+'use client';++function XDSStream({+ endpoint,+ params,+ rootMargin = '200px',+ loading,+ disabled = false,+}) {+ const ref = useRef<HTMLDivElement>(null);+ const [content, setContent] = useState<ReactNode>(null);+ const [fetching, setFetching] = useState(false);++ useEffect(() => {+ if (disabled || fetching || content) return;++ const observer = new IntersectionObserver(+ async ([entry]) => {+ if (entry.isIntersecting) {+ setFetching(true);+ observer.disconnect();++ const url = params+ ? `${endpoint}?${new URLSearchParams(params)}`+ : endpoint;++ const response = await fetch(url, {+ headers: {RSC: '1'},+ });++ // Framework-specific flight response handling+ const serverContent = await createFromReadableStream(response.body);+ setContent(serverContent);+ setFetching(false);+ }+ },+ {rootMargin},+ );++ if (ref.current) observer.observe(ref.current);+ return () => observer.disconnect();+ }, [disabled, fetching, content, endpoint, params, rootMargin]);++ // Already fetched - render server content+ if (content) return <>{content}</>;++ // Disabled - render nothing+ if (disabled) return null;++ // Sentinel + loading state+ return <div ref={ref}>{fetching && loading}</div>;+}+```++### Recursive Pattern++The server endpoint returns content + next trigger, creating a chain:++```tsx+// /api/users endpoint (server)+async function UsersEndpoint({searchParams}) {+ const cursor = searchParams.cursor;+ const {items, nextCursor, hasMore} = await fetchUsers({+ after: cursor,+ limit: 20,+ });++ return (+ <>+ {items.map(item => (+ <Item key={item.id} data={item} />+ ))}++ {hasMore && (+ <XDSStream endpoint="/api/users" params={{cursor: nextCursor}} />+ )}+ </>+ );+}+```++Each fetch returns:++1. New content+2. Next `XDSStream` sentinel (if more data exists)++This creates infinite scroll without client-side state management.++### Considerations++- **Framework coupling**: Flight response parsing varies (Next.js, Waku, etc.)+- **Error handling**: Consider adding error boundary or error state+- **Retry**: Could add retry logic on fetch failure+- **Deduplication**: Prevent double-fetches on rapid scroll++## Usage Examples++### List with Infinite Scroll++```tsx+async function UserListPage() {+ const {users, nextCursor, hasMore} = await fetchUsers({limit: 20});++ return (+ <XDSList>+ {users.map(user => (+ <XDSListItem key={user.id}>{user.name}</XDSListItem>+ ))}++ {hasMore && (+ <XDSStream+ endpoint="/api/users"+ params={{cursor: nextCursor}}+ loading={<XDSSpinner />}+ />+ )}+ </XDSList>+ );+}+```++### Card Grid with Lazy Images++```tsx+<div className="grid">+ {items.map(item => (+ <Card key={item.id}>+ <XDSLazy+ fetch={() => fetchThumbnail(item.id)}+ fallback={<XDSSkeleton shape="rectangle" height={200} />}>+ {src => <img src={src} alt={item.title} />}+ </XDSLazy>+ <h3>{item.title}</h3>+ </Card>+ ))}+</div>+```++### Client-Side Pagination++```tsx+function ClientPaginatedList() {+ const [items, setItems] = useState(initialItems);+ const [cursor, setCursor] = useState(initialCursor);+ const [loading, setLoading] = useState(false);+ const [hasMore, setHasMore] = useState(true);++ const loadMore = async () => {+ setLoading(true);+ const {items: newItems, nextCursor} = await fetchItems({after: cursor});+ setItems(prev => [...prev, ...newItems]);+ setCursor(nextCursor);+ setHasMore(!!nextCursor);+ setLoading(false);+ };++ return (+ <ul>+ {items.map(item => (+ <li key={item.id}>{item.name}</li>+ ))}++ <XDSIntersectionTrigger+ onIntersect={loadMore}+ disabled={!hasMore || loading}>+ {loading && <XDSSpinner />}+ </XDSIntersectionTrigger>+ </ul>+ );+}+```diff --git a/.context/explorations/table-api-simplification.md b/.context/explorations/table-api-simplification.mdnew file mode 100644index 0000000000..8d542f161f--- /dev/null+++ b/.context/explorations/table-api-simplification.md@@ -0,0 +1,786 @@+# XDSTable API Simplification++Exploring a simplified table API that reduces verbosity while maintaining configurability.++## Design Goals++1. **Minimal required props** - just `label` + `data` for the simplest case+2. **Single canonical form** - one pattern for columns (objects), no multiple syntaxes+3. **Smart defaults** - infer headers, widths, cell rendering from keys+4. **Plugins for features** - all behavior/features stay in `plugins` prop (no prop explosion)+5. **LLM-friendly** - predictable structure, easy to document+6. **RSC-friendly** - streaming mode with minimal config++## API Examples++### Simplest Table (auto-generated columns)++```tsx+<XDSTable+ label="User directory"+ data={[+ {name: 'Alice', email: '[email protected]', status: 'Active'},+ {name: 'Bob', email: '[email protected]', status: 'Pending'},+ ]}+/>+```++- Columns auto-generated from own enumerable properties of `data[0]`+- Headers default to capitalized keys+- Cell rendering by value type:+ - Primitives (string, number, boolean) → render as text+ - null/undefined → render "—" or empty+ - Date → locale formatted string+ - Objects/Arrays → require explicit `cell` renderer (warn in dev)+- Row IDs auto-detect `id` field, fallback to index++### With columns and plugins (features)++All table features are configured via `plugins`:++```tsx+<XDSTable+ label="User directory"+ data={users}+ columns={[+ {+ key: 'name',+ header: 'Full Name',+ width: proportional(2),+ cell: ({item}) => <XDSTableContentCell label={item.name} />,+ },+ {key: 'email', header: 'Email Address'},+ {key: 'status', width: pixel(100)},+ ]}+ plugins={{+ rowHeader: useXDSTableRowHeader({key: 'name'}),+ sortable: useXDSTableSortable({+ defaultSort: {key: 'name', direction: 'asc'},+ }),+ selection: useXDSTableSelection({+ selected: selectedIds,+ onChange: setSelectedIds,+ }),+ emptyState: useXDSTableEmptyState({content: <EmptyMessage />}),+ }}+/>+```++## Column Definition++```tsx+interface XDSTableColumn<T> {+ // Required+ key: string; // Object key to access, also used as column ID++ // Optional with defaults+ header?: string; // Default: capitalize(key)+ width?: ColumnWidth; // Default: proportional(1)+ type?: 'text' | 'number' | 'status' | 'action'; // Default: 'text'+ cell?: (props: {item: T}) => ReactNode; // Default: render item[key] as text++ // Advanced+ align?: 'start' | 'center' | 'end';+}+```++## Core Props++| Prop | Type | Required | Description |+| ------------------ | ----------------------------------------- | -------- | ----------------------------------------------------------------------------------------- |+| `label` | `string` | Yes | Screen reader label for table |+| `data` | `T[]` | No\* | Array of row objects (\*required if no children) |+| `columns` | `Column<T>[]` | No\* | Column definitions (\*required for streaming mode, auto-generated from data[0] otherwise) |+| `children` | `ReactNode` | No\* | Row components (\*mutually exclusive with `data`) |+| `header` | `ReactNode` | No | Additional content in `<thead>` after column headers (e.g., filter row) |+| `footer` | `ReactNode` | No | Content in `<tfoot>` (e.g., load more, totals) |+| `idKey` | `keyof T` | No | Field to use as row ID (default: `'id'`, fallback: index) |+| `density` | `XDSTableDensity` | No | Row height + padding (default: `'balanced'`) |+| `verticalAlign` | `'start' \| 'center'` | No | Cell content alignment (default: based on density) |+| `dividers` | `'none' \| 'rows' \| 'columns' \| 'grid'` | No | Table divider lines (default: `'rows'`) |+| `striped` | `boolean` | No | Alternating row backgrounds (default: `false`) |+| `highlightOnHover` | `boolean` | No | Highlight rows on hover (default: `false`) |+| `plugins` | `XDSTablePlugins` | No | Feature plugins (see below) |+| `xstyle` | `StyleXStyles` | No | Custom styles |++**Important**: Column headers are always rendered from the `columns` prop. The `header` prop is for _additional_ content (like filter rows), not column definitions.++### Header and Footer Slots++The table renders:++1. `<thead>`: Column headers (from `columns`) + optional `header` content+2. `<tbody>`: Row data (from `data` or `children`)+3. `<tfoot>`: Optional `footer` content++**Smart wrapping**: If header/footer content is not an `XDSTableRow`, the table wraps it in `<tr><td colSpan="all">...</td></tr>`.++```tsx+// Simple footer - auto-wrapped in row/cell+<XDSTable+ columns={columns}+ footer={<XDSStream endpoint="/api/users" />}+>+ {users.map(user => ...)}+</XDSTable>++// Custom footer row structure+<XDSTable+ columns={columns}+ footer={+ <XDSTableRow>+ <XDSTableCell>Total</XDSTableCell>+ <XDSTableCell />+ <XDSTableCell>{formatCurrency(sum)}</XDSTableCell>+ </XDSTableRow>+ }+>+ {users.map(user => ...)}+</XDSTable>++// Header with filter row+<XDSTable+ columns={columns}+ header={+ <XDSTableRow>+ {columns.map(col => (+ <XDSTableCell key={col.key}>+ <FilterInput column={col.key} />+ </XDSTableCell>+ ))}+ </XDSTableRow>+ }+>+ {users.map(user => ...)}+</XDSTable>+```++## Appearance Props++Visual styling is controlled via simple top-level props rather than a complex variant system.++### Density++Controls row height and padding. Vertical alignment defaults based on density but can be overridden.++```tsx+type XDSTableDensity =+ | 'compact' // single line, tight padding → default verticalAlign: 'center'+ | 'balanced' // two lines, medium padding → default verticalAlign: 'center'+ | 'spacious' // flexible height, generous padding → default verticalAlign: 'start'+ | SpacingToken // direct spacing token for custom padding+ | {+ rowHeight?: 'single' | 'double' | 'auto' | number;+ padding?: SpacingToken;+ };+```++```tsx+// Preset (most common)+<XDSTable density="balanced" ... />++// Spacing token+<XDSTable density={4} ... />++// Full custom+<XDSTable density={{ rowHeight: 64, padding: 3 }} verticalAlign="center" ... />+```++### Dividers, Striping, and Alignment++| Prop | Type | Default | Description |+| ------------------ | ----------------------------------------- | ---------------- | --------------------------------- |+| `dividers` | `'none' \| 'rows' \| 'columns' \| 'grid'` | `'rows'` | Table divider lines |+| `striped` | `boolean` | `false` | Alternating row background colors |+| `highlightOnHover` | `boolean` | `false` | Highlight rows on mouse hover |+| `verticalAlign` | `'start' \| 'center'` | Based on density | Cell content vertical alignment |++```tsx+<XDSTable+ label="User directory"+ data={users}+ density="compact"+ dividers="grid"+ striped+/>+```++### Competitive Analysis++| Framework | Size/Density | Borders | Striping |+| ------------ | --------------------------------------- | -------------------------------------------------------- | ---------------- |+| Mantine | `horizontalSpacing`, `verticalSpacing` | `withTableBorder`, `withColumnBorders`, `withRowBorders` | `striped` |+| Radix Themes | `size` ("1" \| "2" \| "3") | — | — |+| Ant Design | `size` ("small" \| "middle" \| "large") | `bordered` | — |+| Material UI | `size` ("small" \| "medium") | — | — |+| Carbon | `size` ("xs" - "xl") | — | `useZebraStyles` |++Our approach: semantic `density` presets that bundle row height + padding + alignment, with escape hatches for custom values. Dividers and striping as simple boolean props.++## Plugins++All features are configured via the `plugins` prop. Each plugin is created with a hook:++| Plugin | Hook | Description |+| -------------------- | ------------------------------- | ------------------------------------ |+| `rowHeader` | `useXDSTableRowHeader` | Column to use as row header for a11y |+| `sortable` | `useXDSTableSortable` | Enable column sorting |+| `selection` | `useXDSTableSelection` | Row selection (multi) |+| `selection` | `useXDSTableSingleSelection` | Row selection (single) |+| `activation` | `useXDSTableRowActivation` | Row click/activation |+| `rowStyling` | `useXDSTableRowStyling` | Conditional row styles/props |+| `emptyState` | `useXDSTableEmptyState` | Empty state content |+| `virtualization` | `useXDSTableVirtualization` | Virtual scrolling |+| `expansion` | `useXDSTableRowExpansion` | Expandable rows |+| `expansion` | `useXDSTableTreeRows` | Tree/hierarchical rows |+| `filtering` | `useXDSTableFiltering` | Column filtering |+| `dragAndDropRows` | `useXDSTableDragAndDropRows` | Row reordering |+| `dragAndDropColumns` | `useXDSTableDragAndDropColumns` | Column reordering |+| `columnResize` | `useXDSTableColumnResize` | Resizable columns |+| `stickyColumns` | `useXDSTableStickyColumns` | Sticky columns |++### Row Styling Plugin++For conditional per-row styling based on data:++```tsx+plugins={{+ rowStyling: useXDSTableRowStyling({+ getRowProps: (item) => ({+ xstyle: [+ item.status === 'error' && styles.errorRow,+ item.isArchived && styles.dimmed,+ ],+ 'data-testid': `row-${item.id}`,+ }),+ }),+}}+```++## Migration from Current API++Current:++```tsx+const dataSource = useMemo(+ () =>+ xdsTableStandardDataSource(DATA, {+ getStableUniqueID: item => item.id,+ }),+ [],+);++const rowHeader = useXDSTableRowHeader<Item, ColumnKey>({key: 'name'});++<XDSTable+ columns={columns}+ dataSource={dataSource}+ label="Users"+ plugins={{rowHeader}}+/>;+```++New:++```tsx+<XDSTable+ label="Users"+ data={DATA}+ columns={columns}+ plugins={{+ rowHeader: useXDSTableRowHeader({key: 'name'}),+ }}+/>+```++**Changes:**++- `dataSource` → `data` (raw array)+- `label` → `label` (clearer purpose)+- `getStableUniqueID` → auto-derived from `item.id` (or use `idKey` prop)+- Plugins remain the same pattern++## Open Questions++1. Should `columns` support array-of-arrays data with numeric indices?+2. Should there be a `caption` prop for visible table titles?+3. How does virtualization interact with the `data` prop for lazy loading?++## Recipes++Common table configurations for copy-paste:++### Compact Data-Dense Table++```tsx+<XDSTable+ label="Transaction log"+ data={transactions}+ density="compact"+ highlightOnHover+/>+```++### Spreadsheet-Style++```tsx+<XDSTable+ label="Budget spreadsheet"+ data={cells}+ density="compact"+ dividers="grid"+/>+```++### Card-Like Rows++```tsx+<XDSTable+ label="Project list"+ data={projects}+ density="spacious"+ dividers="none"+ striped+/>+```++### Sortable with Selection++```tsx+<XDSTable+ label="User management"+ data={users}+ columns={[+ {key: 'name', header: 'Name'},+ {key: 'email', header: 'Email'},+ {key: 'role', header: 'Role'},+ ]}+ plugins={{+ rowHeader: useXDSTableRowHeader({key: 'name'}),+ sortable: useXDSTableSortable({+ defaultSort: {key: 'name', direction: 'asc'},+ }),+ selection: useXDSTableSelection({selected, onChange: setSelected}),+ }}+/>+```++## LLM & DevX Considerations++### Plugin Discoverability++All plugins follow the `useXDSTable*` naming convention. The `plugins` prop is typed to show available keys:++```tsx+plugins?: {+ rowHeader?: ReturnType<typeof useXDSTableRowHeader>;+ sortable?: ReturnType<typeof useXDSTableSortable>;+ selection?: ReturnType<typeof useXDSTableSelection | typeof useXDSTableSingleSelection>;+ // ... etc+}+```++IDE autocomplete on the `plugins` object keys reveals all available plugins.++### Defaults Summary++| Prop | Default |+| ------------------ | ------------------------------------------------------- |+| `columns` | Auto-generated from `data[0]` keys |+| `idKey` | `'id'` field, fallback to array index |+| `density` | `'balanced'` |+| `verticalAlign` | `'center'` for compact/balanced, `'start'` for spacious |+| `dividers` | `'rows'` |+| `striped` | `false` |+| `highlightOnHover` | `false` |++## Streaming API (RSC Compatible)++For server streaming and RSC compatibility, use `columns` prop (data-only) with compositional body:++```tsx+const columns = [+ {key: 'name', header: 'Name', width: proportional(2), type: 'content'},+ {key: 'email', header: 'Email'},+ {key: 'status', header: 'Status', width: pixel(100), type: 'status'},+];++<XDSTable+ label="Users"+ columns={columns} // Required upfront for streaming+ density="compact"+ dividers="grid">+ <Suspense fallback={<XDSTableLoadingRow count={10} />}>+ <UserRowsFromServer />+ </Suspense>+</XDSTable>;++// Server Component - streams rows+async function UserRowsFromServer() {+ const users = await fetchUsers();+ return users.map(user => (+ <XDSTableRow key={user.id}>+ <XDSTableCell>{user.name}</XDSTableCell>+ <XDSTableCell>{user.email}</XDSTableCell>+ <XDSTableCell>+ <XDSBadge>{user.status}</XDSBadge>+ </XDSTableCell>+ </XDSTableRow>+ ));+}+```++### Why Columns Upfront?++Column definitions must be provided via props (not children) because:++1. **No upward registration** - Context flows downward; children can't inform parent of column structure+2. **Loading state awareness** - Skeleton rows need column widths/types from context+3. **Single canonical form** - One pattern for columns (design goal #2)+4. **RSC compatible** - No effects or callbacks needed for column registration++**Tradeoff**: Column headers/definitions can't be streamed. This is acceptable because:++- Column definitions are small/fast+- Body cells (the bulk of data) still stream+- Lazy cells can fetch on intersection if needed++### Data vs Streaming Mode++| Aspect | `data` prop | `children` (streaming) |+| -------------------- | ---------------------------------- | --------------------------------- |+| **Use case** | Simple tables, full plugin support | RSC, streaming, custom structure |+| **Server streaming** | ❌ Full array needed | ✅ Row components stream |+| **Auto-columns** | ✅ From object keys | ❌ `columns` prop required |+| **Plugins** | ✅ Full support | ⚠️ Some have split responsibility |++The `data` prop and `children` are mutually exclusive.++### Compositional Components++| Component | Description |+| -------------- | ------------ |+| `XDSTableRow` | Row wrapper |+| `XDSTableCell` | Cell wrapper |++That's it. No `XDSTableHead`, `XDSTableBody`, or `XDSTableFoot` - the table handles structure internally:++- Header renders from `columns` prop+- `children` become body rows+- `footer` prop for footer content++## Loading Patterns++Use generic XDS primitives rather than table-specific loading components. This avoids component proliferation and enables reuse across the design system.++### Skeleton Rows++```tsx+// Use generic XDSSkeleton in table cells+function SkeletonRows({columns, count}) {+ return Array.from({length: count}, (_, i) => (+ <XDSTableRow key={i}>+ {columns.map(col => (+ <XDSTableCell key={col.key}>+ <XDSSkeleton width={col.type === 'status' ? 80 : undefined} />+ </XDSTableCell>+ ))}+ </XDSTableRow>+ ));+}+```++### Infinite Scroll / Load More++Use `footer` prop with generic `XDSIntersectionTrigger`:++```tsx+<XDSTable+ label="Users"+ columns={columns}+ footer={+ hasMore && (+ <XDSIntersectionTrigger onIntersect={loadMore} rootMargin="200px">+ {isLoading && <XDSTableLoadingRow />}+ </XDSIntersectionTrigger>+ )+ }>+ {users.map(user => (+ <XDSTableRow key={user.id}>...</XDSTableRow>+ ))}+</XDSTable>+```++### Lazy Cell Data++For cells that fetch data on visibility:++```tsx+<XDSTableCell>+ <XDSLazy+ fetch={() => fetchScore(user.id)}+ fallback={<XDSSkeleton width={60} />}>+ {score => <span>{score}</span>}+ </XDSLazy>+</XDSTableCell>+```++### XDSTableLoadingRow++A convenience component that renders skeleton cells matching the column structure:++```tsx+// Reads columns from context, renders appropriate skeletons+<XDSTableLoadingRow />++// Multiple rows+<XDSTableLoadingRow count={10} />++// With explicit columns (when context unavailable)+<XDSTableLoadingRow columns={columns} count={5} />+```++Internally uses `XDSSkeleton` with column-aware widths/shapes based on column `type`.++### Generic Primitives++See [RSC Utilities](./rsc-utilities.md) for full documentation on:++| Component | Description |+| ------------------------ | ------------------------------------------------------- |+| `XDSSkeleton` | Loading placeholder (shimmer animation) |+| `XDSIntersectionTrigger` | Fires callback when element enters viewport |+| `XDSLazy` | Lazy load wrapper - fetches data on intersection |+| `XDSStream` | RSC streaming - fetches flight response on intersection |+| `XDSSpinner` | Loading spinner |++## RSC Streaming++For React Server Component infinite scroll, use `XDSStream` after the initial rows:++```tsx+const columns = [+ {key: 'name', header: 'Name', width: proportional(2)},+ {key: 'email', header: 'Email'},+ {key: 'status', header: 'Status', width: pixel(100)},+];++async function UsersPage() {+ const {users, nextCursor, hasMore} = await fetchUsers({limit: 20});++ return (+ <XDSTable label="Users" columns={columns}>+ {users.map(user => (+ <XDSTableRow key={user.id}>+ <XDSTableCell>{user.name}</XDSTableCell>+ <XDSTableCell>{user.email}</XDSTableCell>+ <XDSTableCell>{user.status}</XDSTableCell>+ </XDSTableRow>+ ))}++ {hasMore && (+ <XDSStream+ endpoint="/api/users"+ params={{cursor: nextCursor}}+ loading={<XDSTableLoadingRow />}+ />+ )}+ </XDSTable>+ );+}+```++The server endpoint returns rows + the next `XDSStream` trigger, creating a recursive chain for infinite scroll. See [RSC Utilities](./rsc-utilities.md) for implementation details.++## Plugin Architecture++Plugins work via render transforms. Each plugin can wrap or modify renders at various levels:++```tsx+type XDSTablePlugin<TItem, TColumnKey> = {+ // Table structure+ transformTable?: (render) => render;+ transformLayout?: (render) => render;+ transformColumns?: (columns) => columns;++ // Header+ transformHeaderSegment?: (render) => render;+ transformHeaderRow?: (render) => render;+ transformHeaderCell?: (render) => render;++ // Body+ transformBodyRow?: (render) => render;+ transformBodyCell?: (render) => render;++ // Footer+ transformFooterSegment?: (render) => render;+ transformFooterRow?: (render) => render;+ transformFooterCell?: (render) => render;++ // Loading state+ transformLoadingRow?: (render) => render;+ transformLoadingCell?: (render) => render;+};+```++### How Plugins Compose++Plugin hooks return plugin objects. The table composes all transforms:++```tsx+// Each hook returns a plugin object+const sortable = useXDSTableSortable({ ... });+// → { transformHeaderCell: (render) => renderWithSortIcon, ... }++const selection = useXDSTableSelection({ ... });+// → { transformBodyRow: (render) => renderWithCheckbox, transformColumns: (cols) => [checkboxCol, ...cols] }++// Table composes them+plugins={{ sortable, selection }}+// → All transforms are chained together+```++### Plugins in Streaming Mode++Some plugins work with children, some require `data`:++| Plugin | Data Mode | Streaming Mode | Notes |+| ---------------- | --------- | -------------- | -------------------------------------------------------- |+| `rowHeader` | ✅ | ✅ | Via `<XDSTableRow rowHeader>` |+| `sortable` | ✅ | ⚠️ Split | Table handles UI/indicators, caller handles row ordering |+| `selection` | ✅ | ✅ | Via context + `<XDSTableRow selectable>` |+| `activation` | ✅ | ✅ | Via `<XDSTableRow onActivate>` |+| `emptyState` | ✅ | ✅ | Via conditional children |+| `virtualization` | ✅ | ⚠️ Possible | Needs explicit `rowHeight` + `rowCount` props |+| `expansion` | ✅ | ✅ | Via `<XDSTableRow expandable>` |+| `rowStyling` | ✅ | ✅ | Props on `<XDSTableRow>` |+| `dragAndDrop` | ✅ | ✅ Deferred | Rows register refs on mount |+| `stickyColumns` | ✅ | ✅ | Via column config `{ key: 'name', sticky: true }` |++### Streaming Mode Details++**Sortable (split responsibility):**++```tsx+// Table provides: sort state context, column indicators, onSort callbacks+// Caller provides: correctly ordered rows++const [sort, setSort] = useState({key: 'name', direction: 'asc'});+const sortedUsers = useMemo(+ () => [...users].sort(comparator(sort.key, sort.direction)),+ [users, sort],+);++<XDSTable+ columns={columns}+ plugins={{sortable: useXDSTableSortable({sort, onSort: setSort})}}>+ {sortedUsers.map(user => (+ <XDSTableRow key={user.id}>...</XDSTableRow>+ ))}+</XDSTable>;+```++**Virtualization (with explicit dimensions):**++```tsx+// rowHeight and rowCount enable virtualization without full data knowledge+<XDSTable+ columns={columns}+ rowHeight={48}+ rowCount={1000}+ plugins={{virtualization: useXDSTableVirtualization({maxHeight: 400})}}>+ {/* Only visible rows render */}+</XDSTable>+```++**Drag and Drop (deferred registration):**++```tsx+// Rows register refs with context on mount+// By user interaction time, all refs are available+<XDSTable+ columns={columns}+ plugins={{dragAndDrop: useXDSTableDragAndDropRows({onReorder})}}>+ {items.map(item => (+ <XDSTableRow key={item.id} draggable>+ ...+ </XDSTableRow>+ ))}+</XDSTable>+```++## RSC Plugin Pattern++For React Server Components, plugins can be provided via a wrapper that composes context providers. This avoids upward registration and keeps plugin configuration declarative.++### API++```tsx+<XDSTablePlugins+ sortable={{+ Plugin: XDSTableSortablePlugin,+ defaultSort: {key: 'name', direction: 'asc'},+ }}+ selection={{+ Plugin: XDSTableSelectionPlugin,+ selected: ids,+ onChange: setIds,+ }}>+ <XDSTable label="Users" columns={columns}>+ <UserRows /> {/* Server Component */}+ </XDSTable>+</XDSTablePlugins>+```++### How It Works++**1. XDSTablePlugins composes nested providers:**++```tsx+function XDSTablePlugins({sortable, selection, children}) {+ let result = children;++ if (selection) {+ const {Plugin, ...props} = selection;+ result = <Plugin {...props}>{result}</Plugin>;+ }+ if (sortable) {+ const {Plugin, ...props} = sortable;+ result = <Plugin {...props}>{result}</Plugin>;+ }++ return result;+}+```++**2. Each plugin component is a client boundary:**++```tsx+'use client';++function XDSTableSortablePlugin({defaultSort, onSort, children}) {+ const sortable = useXDSTableSortable({defaultSort, onSort});+ return (+ <SortableContext.Provider value={sortable}>+ {children}+ </SortableContext.Provider>+ );+}+```++**3. Table consumes via context:**++```tsx+function XDSTable({children}) {+ const sortable = useContext(SortableContext);+ const selection = useContext(SelectionContext);+ // Apply plugin transforms...+}+```++### Benefits++- **Server-renderable config**: Plugin props are plain objects, serializable+- **No upward registration**: Plugins known upfront, composed top-down+- **Clean client boundaries**: Each plugin is its own `'use client'` component+- **Composable**: Add/remove plugins declarativelydiff --git a/apps/storybook/stories/Table.stories.tsx b/apps/storybook/stories/Table.stories.tsxnew file mode 100644index 0000000000..0b11da2bab--- /dev/null+++ b/apps/storybook/stories/Table.stories.tsx@@ -0,0 +1,295 @@+import type {Meta, StoryObj} from '@storybook/react';+import {+ XDSTable,+ XDSTableRow,+ XDSTableCell,+ proportional,+ pixel,+} from '@xds/core/Table';+import type {XDSTableColumn, TablePlugin} from '@xds/core/Table';+import {colorRaw, spacingRaw, radiusRaw, textSizeRaw} from '@xds/core/theme';++// =============================================================================+// Sample Data+// =============================================================================++interface User extends Record<string, unknown> {+ id: string;+ name: string;+ email: string;+ role: string;+ age: number;+}++const users: User[] = [+ {+ id: '1',+ name: 'Alice Johnson',+ email: '[email protected]',+ role: 'Engineer',+ age: 30,+ },+ {+ id: '2',+ name: 'Bob Smith',+ email: '[email protected]',+ role: 'Designer',+ age: 25,+ },+ {+ id: '3',+ name: 'Charlie Brown',+ email: '[email protected]',+ role: 'PM',+ age: 35,+ },+ {+ id: '4',+ name: 'Diana Prince',+ email: '[email protected]',+ role: 'Engineer',+ age: 28,+ },+ {+ id: '5',+ name: 'Eve Davis',+ email: '[email protected]',+ role: 'Designer',+ age: 32,+ },+];++const columns: XDSTableColumn<User>[] = [+ {key: 'name', header: 'Name'},+ {key: 'email', header: 'Email', width: proportional(2)},+ {key: 'role', header: 'Role'},+ {key: 'age', header: 'Age', width: pixel(80)},+];++// =============================================================================+// Meta+// =============================================================================++const meta: Meta<typeof XDSTable> = {+ title: 'Core/XDSTable',+ component: XDSTable,+ tags: ['autodocs'],+ argTypes: {+ density: {+ control: 'select',+ options: ['compact', 'balanced', 'spacious'],+ description: 'Row density controlling padding and font size',+ },+ dividers: {+ control: 'select',+ options: ['rows', 'columns', 'grid', 'none'],+ description: 'Divider style between cells',+ },+ striped: {+ control: 'boolean',+ description: 'Alternate row background color',+ },+ hover: {+ control: 'boolean',+ description: 'Highlight rows on hover',+ },+ },+};++export default meta;+type Story = StoryObj<typeof meta>;++// =============================================================================+// Stories+// =============================================================================++export const Default: Story = {+ args: {+ data: users,+ columns,+ idKey: 'id',+ },+};++export const Compact: Story = {+ args: {+ data: users,+ columns,+ idKey: 'id',+ density: 'compact',+ },+};++export const Spacious: Story = {+ args: {+ data: users,+ columns,+ idKey: 'id',+ density: 'spacious',+ },+};++export const StripedWithHover: Story = {+ args: {+ data: users,+ columns,+ idKey: 'id',+ striped: true,+ hover: true,+ },+};++export const GridDividers: Story = {+ args: {+ data: users,+ columns,+ idKey: 'id',+ dividers: 'grid',+ },+};++export const ColumnDividers: Story = {+ args: {+ data: users,+ columns,+ idKey: 'id',+ dividers: 'columns',+ },+};++export const NoDividers: Story = {+ args: {+ data: users,+ columns,+ idKey: 'id',+ dividers: 'none',+ },+};++export const AutoColumns: Story = {+ render: () => (+ <XDSTable+ data={[+ {name: 'Alice', role: 'Engineer', status: 'Active'},+ {name: 'Bob', role: 'Designer', status: 'Away'},+ ]}+ hover+ />+ ),+};++export const CustomCellRenderer: Story = {+ render: () => {+ const cols: XDSTableColumn<User>[] = [+ {key: 'name', header: 'Name'},+ {+ key: 'email',+ header: 'Email',+ width: proportional(2),+ renderCell: item => (+ <a href={`mailto:${item.email}`} style={{color: 'inherit'}}>+ {item.email}+ </a>+ ),+ },+ {+ key: 'role',+ header: 'Role',+ renderCell: item => (+ <span+ style={{+ padding: `${spacingRaw['--spacing-0-5']} ${spacingRaw['--spacing-2']}`,+ borderRadius: radiusRaw['--radius-content'],+ fontSize: textSizeRaw['--text-xsm'],+ backgroundColor:+ item.role === 'Engineer'+ ? colorRaw['--color-blue-background']+ : colorRaw['--color-purple-background'],+ color:+ item.role === 'Engineer'+ ? colorRaw['--color-blue-text']+ : colorRaw['--color-purple-text'],+ }}>+ {item.role}+ </span>+ ),+ },+ {key: 'age', header: 'Age', width: pixel(80)},+ ];++ return <XDSTable data={users} columns={cols} idKey="id" hover />;+ },+};++export const ChildrenMode: Story = {+ render: () => (+ <XDSTable density="balanced" dividers="rows" striped hover>+ <XDSTableRow>+ <XDSTableCell>Alice</XDSTableCell>+ <XDSTableCell>[email protected]</XDSTableCell>+ <XDSTableCell>Engineer</XDSTableCell>+ </XDSTableRow>+ <XDSTableRow>+ <XDSTableCell>Bob</XDSTableCell>+ <XDSTableCell>[email protected]</XDSTableCell>+ <XDSTableCell>Designer</XDSTableCell>+ </XDSTableRow>+ <XDSTableRow>+ <XDSTableCell>Charlie</XDSTableCell>+ <XDSTableCell>[email protected]</XDSTableCell>+ <XDSTableCell>PM</XDSTableCell>+ </XDSTableRow>+ <XDSTableRow>+ <XDSTableCell>Diana</XDSTableCell>+ <XDSTableCell>[email protected]</XDSTableCell>+ <XDSTableCell>Engineer</XDSTableCell>+ </XDSTableRow>+ </XDSTable>+ ),+};++export const AllDensities: Story = {+ render: () => (+ <div style={{display: 'flex', flexDirection: 'column', gap: '32px'}}>+ <div>+ <p style={{margin: '0 0 8px', fontWeight: 600}}>Compact</p>+ <XDSTable+ data={users.slice(0, 3)}+ columns={columns}+ idKey="id"+ density="compact"+ />+ </div>+ <div>+ <p style={{margin: '0 0 8px', fontWeight: 600}}>Balanced (default)</p>+ <XDSTable+ data={users.slice(0, 3)}+ columns={columns}+ idKey="id"+ density="balanced"+ />+ </div>+ <div>+ <p style={{margin: '0 0 8px', fontWeight: 600}}>Spacious</p>+ <XDSTable+ data={users.slice(0, 3)}+ columns={columns}+ idKey="id"+ density="spacious"+ />+ </div>+ </div>+ ),+};++export const KitchenSink: Story = {+ args: {+ data: users,+ columns,+ idKey: 'id',+ density: 'compact',+ dividers: 'grid',+ striped: true,+ hover: true,+ },+};diff --git a/packages/core/src/Table/README.md b/packages/core/src/Table/README.mdnew file mode 100644index 0000000000..41cf7b5888--- /dev/null+++ b/packages/core/src/Table/README.md@@ -0,0 +1,91 @@+# /packages/core/src/Table++Table components for the XDS design system.++<!-- SYNC: When files in this directory change, update this document. -->++## Components++| File | Export | Purpose |+| ------------------ | -------------- | ------------------------------------------------------------ |+| `XDSTable.tsx` | `XDSTable` | Styled, data-driven table with density, dividers, and hover |+| `XDSBaseTable.tsx` | `XDSBaseTable` | Unstyled table with colgroup, plugin pipeline, children mode |+| `XDSTableRow.tsx` | `XDSTableRow` | Thin `<tr>` wrapper for children/streaming mode |+| `XDSTableCell.tsx` | `XDSTableCell` | Thin `<td>` wrapper for children/streaming mode |++## Utilities++| File | Export | Purpose |+| ---------------- | ------------------ | -------------------------------------------- |+| `columnUtils.ts` | `proportional` | Create a proportional (fr-like) column width |+| `columnUtils.ts` | `pixel` | Create a fixed pixel column width |+| `columnUtils.ts` | `generateColumns` | Auto-generate columns from data object keys |+| `columnUtils.ts` | `columnWidthToCSS` | Convert a ColumnWidth to a CSS width string |++## Types++| File | Export | Purpose |+| ---------- | ------------------- | ------------------------------------------------ |+| `types.ts` | `XDSTableColumn` | Column definition (key, header, width, renderer) |+| `types.ts` | `ColumnWidth` | Proportional or pixel width union |+| `types.ts` | `TablePlugin` | Plugin interface for transform-props pipeline |+| `types.ts` | `XDSBaseTableProps` | Props for the unstyled base table |++## Usage Patterns++### Data-driven table++```tsx+<XDSTable+ data={users}+ columns={[+ {key: 'name', header: 'Name'},+ {key: 'email', header: 'Email', width: proportional(2)},+ {key: 'age', header: 'Age', width: pixel(80)},+ ]}+ density="balanced"+ dividers="rows"+ hover+/>+```++### Auto-generated columns++```tsx+// Columns auto-generated from data keys with capitalized headers+<XDSTable data={users} striped />+```++### Children mode++```tsx+<XDSTable>+ <XDSTableRow>+ <XDSTableCell>Alice</XDSTableCell>+ <XDSTableCell>30</XDSTableCell>+ </XDSTableRow>+</XDSTable>+```++### Custom plugin++```tsx+const highlightPlugin: TablePlugin<User> = {+ transformBodyRow(props, item) {+ if (item.isActive) {+ return {...props, styles: [...props.styles, activeRowStyle]};+ }+ return props;+ },+};++<XDSTable data={users} plugins={[highlightPlugin]} />;+```++## Architecture++Two-layer design: **XDSBaseTable** provides unstyled structure and the plugin pipeline. **XDSTable** wraps it and injects a styling plugin built from appearance props (`density`, `dividers`, `striped`, `hover`). This validates the plugin API by dogfooding it.++## Related Files++- `/packages/core/src/theme/tokens.stylex.ts` — Design tokens used by XDSTable stylingdiff --git a/packages/core/src/Table/TableContext.ts b/packages/core/src/Table/TableContext.tsnew file mode 100644index 0000000000..16f6f62e81--- /dev/null+++ b/packages/core/src/Table/TableContext.ts@@ -0,0 +1,23 @@+/**+ * @file TableContext.ts+ * @input React+ * @output Exports TableContext and TableContextValue+ * @position Context layer; connects XDSTable styling to sub-components (XDSTableRow, XDSTableCell)+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Table/XDSTable.tsx (provider)+ * - /packages/core/src/Table/XDSTableRow.tsx (consumer)+ * - /packages/core/src/Table/XDSTableCell.tsx (consumer)+ * - /packages/core/src/Table/index.ts (exports if types change)+ */++import {createContext} from 'react';++export interface TableContextValue {+ density: 'compact' | 'balanced' | 'spacious';+ dividers: 'rows' | 'columns' | 'grid' | 'none';+ striped: boolean;+ hover: boolean;+}++export const TableContext = createContext<TableContextValue | null>(null);diff --git a/packages/core/src/Table/XDSBaseTable.tsx b/packages/core/src/Table/XDSBaseTable.tsxnew file mode 100644index 0000000000..66fc2888f0--- /dev/null+++ b/packages/core/src/Table/XDSBaseTable.tsx@@ -0,0 +1,229 @@+/**+ * @file XDSBaseTable.tsx+ * @input React, types.ts, columnUtils.ts+ * @output Exports XDSBaseTable component+ * @position Core structural component; wrapped by XDSTable.tsx+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Table/README.md (component description, props)+ * - /packages/core/src/Table/XDSTable.test.tsx (tests for new/changed behavior)+ * - /packages/core/src/Table/index.ts (exports if types change)+ */++import {forwardRef, type ReactElement, type Ref} from 'react';+import * as stylex from '@stylexjs/stylex';+import type {+ XDSBaseTableProps,+ XDSTableColumn,+ TableRenderProps,+ HeaderRowRenderProps,+ HeaderCellRenderProps,+ BodyRowRenderProps,+ BodyCellRenderProps,+} from './types';+import {+ generateColumns,+ defaultCellRenderer,+ columnWidthToCSS,+} from './columnUtils';++const styles = stylex.create({+ table: {+ width: '100%',+ borderCollapse: 'collapse',+ borderSpacing: '0',+ tableLayout: 'fixed',+ },+});++/**+ * Run a value through a pipeline of plugin transform functions.+ */+function applyPlugins<TPlugin, TProps, TArgs extends unknown[]>(+ plugins: TPlugin[],+ getter: (+ p: TPlugin,+ ) => ((props: TProps, ...args: TArgs) => TProps) | undefined,+ initial: TProps,+ ...args: TArgs+): TProps {+ return plugins.reduce<TProps>((acc, plugin) => {+ const transform = getter(plugin);+ return transform ? transform(acc, ...args) : acc;+ }, initial);+}++/**+ * Compute total proportional units for percentage calculation.+ */+function getTotalProportional<T extends Record<string, unknown>>(+ columns: XDSTableColumn<T>[],+): number {+ return columns.reduce((sum, col) => {+ const w = col.width ?? {type: 'proportional' as const, value: 1};+ return w.type === 'proportional' ? sum + w.value : sum;+ }, 0);+}++/**+ * Inner XDSBaseTable implementation (generic-preserving).+ */+function XDSBaseTableInner<T extends Record<string, unknown>>(+ {+ data,+ columns: columnsProp,+ idKey,+ plugins = [],+ children,+ tableProps: userTableProps,+ }: XDSBaseTableProps<T>,+ ref: Ref<HTMLTableElement>,+): ReactElement {+ // Resolve columns: explicit > auto-generated from data+ const resolvedColumns: XDSTableColumn<T>[] =+ columnsProp ?? (data ? generateColumns(data) : []);++ const totalProportional = getTotalProportional(resolvedColumns);++ // --- Plugin pipeline: table ---+ const tableRenderProps = applyPlugins(plugins, p => p.transformTable, {+ htmlProps: {...userTableProps},+ styles: [styles.table],+ } as TableRenderProps);++ // --- Plugin pipeline: header row ---+ const headerRowRenderProps = applyPlugins(+ plugins,+ p => p.transformHeaderRow,+ {htmlProps: {}, styles: []} as HeaderRowRenderProps,+ );++ // --- Render ---+ const hasData = data != null && data.length > 0;+ const hasColumns = resolvedColumns.length > 0;++ return (+ <table+ ref={ref}+ {...tableRenderProps.htmlProps}+ {...stylex.props(...tableRenderProps.styles)}>+ {/* colgroup for column widths */}+ {hasColumns && (+ <colgroup>+ {resolvedColumns.map(col => {+ const w = col.width ?? {type: 'proportional' as const, value: 1};+ return (+ <col+ key={col.key}+ style={{width: columnWidthToCSS(w, totalProportional)}}+ />+ );+ })}+ </colgroup>+ )}++ {/* thead */}+ {hasColumns && (+ <thead>+ <tr+ {...headerRowRenderProps.htmlProps}+ {...stylex.props(...headerRowRenderProps.styles)}>+ {resolvedColumns.map(col => {+ const cellRenderProps = applyPlugins(+ plugins,+ p => p.transformHeaderCell,+ {htmlProps: {}, styles: []} as HeaderCellRenderProps,+ col,+ );++ return (+ <th+ key={col.key}+ {...cellRenderProps.htmlProps}+ {...stylex.props(...cellRenderProps.styles)}>+ {col.header ?? col.key}+ </th>+ );+ })}+ </tr>+ </thead>+ )}++ {/* tbody — data-driven or children mode */}+ <tbody>+ {children+ ? children+ : hasData &&+ data.map((item, rowIndex) => {+ const rowKey =+ idKey == null+ ? rowIndex+ : typeof idKey === 'function'+ ? idKey(item)+ : String(item[idKey]);++ const rowRenderProps = applyPlugins(+ plugins,+ p => p.transformBodyRow,+ {htmlProps: {}, styles: []} as BodyRowRenderProps,+ item,+ rowIndex,+ );++ return (+ <tr+ key={rowKey}+ {...rowRenderProps.htmlProps}+ {...stylex.props(...rowRenderProps.styles)}>+ {resolvedColumns.map(col => {+ const cellRenderProps = applyPlugins(+ plugins,+ p => p.transformBodyCell,+ {htmlProps: {}, styles: []} as BodyCellRenderProps,+ col,+ item,+ );++ const content = col.renderCell+ ? col.renderCell(item)+ : defaultCellRenderer(item, col.key);++ return (+ <td+ key={col.key}+ {...cellRenderProps.htmlProps}+ {...stylex.props(...cellRenderProps.styles)}>+ {content}+ </td>+ );+ })}+ </tr>+ );+ })}+ </tbody>+ </table>+ );+}++/**+ * XDSBaseTable — an unstyled, generic `<table>` component.+ *+ * Supports data-driven rendering (via `data` + `columns`) and children mode.+ * Applies plugins as a transform pipeline over render props.+ *+ * @example+ * ```tsx+ * <XDSBaseTable+ * data={[{ name: 'Alice', age: 30 }]}+ * columns={[+ * { key: 'name', header: 'Name' },+ * { key: 'age', header: 'Age', width: pixel(80) },+ * ]}+ * />+ * ```+ */+export const XDSBaseTable = forwardRef(XDSBaseTableInner) as <+ T extends Record<string, unknown>,+>(+ props: XDSBaseTableProps<T> & {ref?: Ref<HTMLTableElement>},+) => ReactElement;diff --git a/packages/core/src/Table/XDSTable.test.tsx b/packages/core/src/Table/XDSTable.test.tsxnew file mode 100644index 0000000000..f4d0152fdf--- /dev/null+++ b/packages/core/src/Table/XDSTable.test.tsx@@ -0,0 +1,732 @@+/**+ * @file XDSTable.test.tsx+ * @input Uses vitest, @testing-library/react, Table components+ * @output Unit tests for XDSBaseTable and XDSTable+ * @position Testing; validates Table implementation+ *+ * SYNC: When XDSBaseTable.tsx or XDSTable.tsx change, update tests to match new behavior+ */++import {describe, it, expect, vi} from 'vitest';+import {render, screen, within} from '@testing-library/react';+import {XDSBaseTable} from './XDSBaseTable';+import {XDSTable} from './XDSTable';+import {XDSTableRow} from './XDSTableRow';+import {XDSTableCell} from './XDSTableCell';+import {+ proportional,+ pixel,+ generateColumns,+ columnWidthToCSS,+ capitalize,+} from './columnUtils';+import type {TablePlugin, XDSTableColumn} from './types';++// =============================================================================+// Test Data+// =============================================================================++interface User extends Record<string, unknown> {+ name: string;+ age: number;+ email: string;+}++const users: User[] = [+ {name: 'Alice', age: 30, email: '[email protected]'},+ {name: 'Bob', age: 25, email: '[email protected]'},+ {name: 'Charlie', age: 35, email: '[email protected]'},+];++const columns: XDSTableColumn<User>[] = [+ {key: 'name', header: 'Name'},+ {key: 'age', header: 'Age', width: pixel(80)},+ {key: 'email', header: 'Email', width: proportional(2)},+];++// =============================================================================+// columnUtils Tests+// =============================================================================++describe('columnUtils', () => {+ describe('proportional', () => {+ it('creates a proportional width with default value 1', () => {+ const w = proportional();+ expect(w).toEqual({type: 'proportional', value: 1});+ });++ it('creates a proportional width with custom value', () => {+ const w = proportional(3);+ expect(w).toEqual({type: 'proportional', value: 3});+ });+ });++ describe('pixel', () => {+ it('creates a pixel width', () => {+ const w = pixel(200);+ expect(w).toEqual({type: 'pixel', value: 200});+ });+ });++ describe('columnWidthToCSS', () => {+ it('converts pixel width to px string', () => {+ expect(columnWidthToCSS(pixel(100), 3)).toBe('100px');+ });++ it('converts proportional width to percentage', () => {+ expect(columnWidthToCSS(proportional(1), 4)).toBe('25%');+ });++ it('handles proportional(2) out of 4', () => {+ expect(columnWidthToCSS(proportional(2), 4)).toBe('50%');+ });+ });++ describe('capitalize', () => {+ it('capitalizes first letter', () => {+ expect(capitalize('name')).toBe('Name');+ });++ it('handles empty string', () => {+ expect(capitalize('')).toBe('');+ });++ it('handles single character', () => {+ expect(capitalize('a')).toBe('A');+ });+ });++ describe('generateColumns', () => {+ it('generates columns from data keys', () => {+ const cols = generateColumns(users);+ expect(cols).toHaveLength(3);+ expect(cols[0].key).toBe('name');+ expect(cols[0].header).toBe('Name');+ expect(cols[1].key).toBe('age');+ expect(cols[1].header).toBe('Age');+ expect(cols[2].key).toBe('email');+ expect(cols[2].header).toBe('Email');+ });++ it('returns empty array for empty data', () => {+ expect(generateColumns([])).toEqual([]);+ });++ it('assigns proportional(1) width to each column', () => {+ const cols = generateColumns(users);+ for (const col of cols) {+ expect(col.width).toEqual({type: 'proportional', value: 1});+ }+ });+ });+});++// =============================================================================+// XDSBaseTable Tests+// =============================================================================++describe('XDSBaseTable', () => {+ it('renders a table element', () => {+ render(<XDSBaseTable data={users} columns={columns} />);+ expect(screen.getByRole('table')).toBeInTheDocument();+ });++ it('renders column headers as th elements', () => {+ render(<XDSBaseTable data={users} columns={columns} />);+ const headers = screen.getAllByRole('columnheader');+ expect(headers).toHaveLength(3);+ expect(headers[0]).toHaveTextContent('Name');+ expect(headers[1]).toHaveTextContent('Age');+ expect(headers[2]).toHaveTextContent('Email');+ });++ it('renders data cells', () => {+ render(<XDSBaseTable data={users} columns={columns} />);+ const cells = screen.getAllByRole('cell');+ // 3 rows * 3 columns = 9 cells+ expect(cells).toHaveLength(9);+ expect(screen.getByText('Alice')).toBeInTheDocument();+ expect(screen.getByText('30')).toBeInTheDocument();+ expect(screen.getByText('[email protected]')).toBeInTheDocument();+ });++ it('renders correct number of rows', () => {+ render(<XDSBaseTable data={users} columns={columns} />);+ // 1 header row + 3 data rows+ expect(screen.getAllByRole('row')).toHaveLength(4);+ });++ it('auto-generates columns from data keys when columns omitted', () => {+ render(<XDSBaseTable data={users} />);+ const headers = screen.getAllByRole('columnheader');+ expect(headers).toHaveLength(3);+ expect(headers[0]).toHaveTextContent('Name');+ expect(headers[1]).toHaveTextContent('Age');+ expect(headers[2]).toHaveTextContent('Email');+ expect(screen.getByText('Alice')).toBeInTheDocument();+ });++ it('uses raw key as header when header prop is not provided', () => {+ const cols: XDSTableColumn<User>[] = [{key: 'name'}];+ render(<XDSBaseTable data={users} columns={cols} />);+ expect(screen.getByRole('columnheader')).toHaveTextContent('name');+ });++ it('renders custom header as ReactNode', () => {+ const cols: XDSTableColumn<User>[] = [+ {key: 'name', header: <span data-testid="custom-header">Full Name</span>},+ ];+ render(<XDSBaseTable data={users} columns={cols} />);+ expect(screen.getByTestId('custom-header')).toHaveTextContent('Full Name');+ });++ it('uses idKey string to key rows', () => {+ render(<XDSBaseTable data={users} columns={columns} idKey="email" />);+ expect(screen.getAllByRole('row')).toHaveLength(4);+ });++ it('uses idKey function to key rows', () => {+ render(+ <XDSBaseTable+ data={users}+ columns={columns}+ idKey={item => item.email}+ />,+ );+ expect(screen.getAllByRole('row')).toHaveLength(4);+ });++ it('renders custom cell renderer', () => {+ const customColumns: XDSTableColumn<User>[] = [+ {+ key: 'name',+ header: 'Name',+ renderCell: (item: User) => (+ <strong data-testid="bold-name">{item.name}</strong>+ ),+ },+ ];+ render(<XDSBaseTable data={users} columns={customColumns} />);+ const boldNames = screen.getAllByTestId('bold-name');+ expect(boldNames).toHaveLength(3);+ expect(boldNames[0]).toHaveTextContent('Alice');+ });++ it('renders null/undefined values as empty string', () => {+ const data = [{name: null as unknown as string, age: 0, email: ''}];+ render(<XDSBaseTable data={data} columns={columns} />);+ const cells = screen.getAllByRole('cell');+ // null renders as empty, 0 renders as '0', empty string renders as empty+ expect(cells[0]).toHaveTextContent('');+ expect(cells[1]).toHaveTextContent('0');+ expect(cells[2]).toHaveTextContent('');+ });++ it('renders children mode instead of data', () => {+ render(+ <XDSBaseTable>+ <tr>+ <td>Manual cell</td>+ </tr>+ </XDSBaseTable>,+ );+ expect(screen.getByText('Manual cell')).toBeInTheDocument();+ });++ it('does not render thead or colgroup in children mode without columns', () => {+ const {container} = render(+ <XDSBaseTable>+ <tr>+ <td>Content</td>+ </tr>+ </XDSBaseTable>,+ );+ expect(container.querySelector('thead')).toBeNull();+ expect(container.querySelector('colgroup')).toBeNull();+ });++ it('renders empty table when data is empty array', () => {+ render(<XDSBaseTable data={[]} columns={columns} />);+ expect(screen.getByRole('table')).toBeInTheDocument();+ // Header row only, no data rows+ expect(screen.getAllByRole('row')).toHaveLength(1);+ });++ it('renders colgroup with correct column widths', () => {+ const {container} = render(<XDSBaseTable data={users} columns={columns} />);+ const cols = container.querySelectorAll('colgroup col');+ expect(cols).toHaveLength(3);+ // Column 0: proportional(1) — default, total proportional = 1+2 = 3, so 33.33%+ // Column 1: pixel(80) — 80px+ // Column 2: proportional(2) — 2/3 = 66.67%+ expect(cols[1]).toHaveStyle({width: '80px'});+ });++ it('forwards ref to the table element', () => {+ const ref = vi.fn();+ render(<XDSBaseTable data={users} columns={columns} ref={ref} />);+ expect(ref).toHaveBeenCalledWith(expect.any(HTMLTableElement));+ });++ it('passes tableProps to the table element', () => {+ render(+ <XDSBaseTable+ data={users}+ columns={columns}+ tableProps={{'aria-label': 'Users table'}}+ />,+ );+ expect(screen.getByRole('table')).toHaveAttribute(+ 'aria-label',+ 'Users table',+ );+ });++ describe('plugin pipeline', () => {+ it('applies transformTable plugin', () => {+ const plugin: TablePlugin<User> = {+ transformTable: props => ({+ ...props,+ htmlProps: {...props.htmlProps, 'data-testid': 'plugin-table'},+ }),+ };+ render(+ <XDSBaseTable data={users} columns={columns} plugins={[plugin]} />,+ );+ expect(screen.getByTestId('plugin-table')).toBeInTheDocument();+ });++ it('applies transformHeaderRow plugin', () => {+ const plugin: TablePlugin<User> = {+ transformHeaderRow: props => ({+ ...props,+ htmlProps: {...props.htmlProps, 'data-testid': 'plugin-header-row'},+ }),+ };+ render(+ <XDSBaseTable data={users} columns={columns} plugins={[plugin]} />,+ );+ expect(screen.getByTestId('plugin-header-row')).toBeInTheDocument();+ });++ it('applies transformHeaderCell plugin with column context', () => {+ const receivedKeys: string[] = [];+ const plugin: TablePlugin<User> = {+ transformHeaderCell: (props, column) => {+ receivedKeys.push(column.key);+ return {+ ...props,+ htmlProps: {...props.htmlProps, 'data-column': column.key},+ };+ },+ };+ render(+ <XDSBaseTable data={users} columns={columns} plugins={[plugin]} />,+ );+ expect(receivedKeys).toEqual(['name', 'age', 'email']);+ const headers = screen.getAllByRole('columnheader');+ expect(headers[0]).toHaveAttribute('data-column', 'name');+ });++ it('applies transformBodyRow plugin with item and index', () => {+ const receivedItems: string[] = [];+ const plugin: TablePlugin<User> = {+ transformBodyRow: (props, item, index) => {+ receivedItems.push(item.name);+ return {+ ...props,+ htmlProps: {...props.htmlProps, 'data-row-index': String(index)},+ };+ },+ };+ render(+ <XDSBaseTable data={users} columns={columns} plugins={[plugin]} />,+ );+ expect(receivedItems).toEqual(['Alice', 'Bob', 'Charlie']);+ });++ it('applies transformBodyCell plugin with column and item context', () => {+ const calls: Array<{col: string; name: string}> = [];+ const plugin: TablePlugin<User> = {+ transformBodyCell: (props, column, item) => {+ calls.push({col: column.key, name: item.name});+ return props;+ },+ };+ render(+ <XDSBaseTable data={users} columns={columns} plugins={[plugin]} />,+ );+ // 3 rows * 3 columns = 9 calls+ expect(calls).toHaveLength(9);+ expect(calls[0]).toEqual({col: 'name', name: 'Alice'});+ });++ it('composes multiple plugins sequentially', () => {+ const plugin1: TablePlugin<User> = {+ transformTable: props => ({+ ...props,+ htmlProps: {...props.htmlProps, 'data-first': 'yes'},+ }),+ };+ const plugin2: TablePlugin<User> = {+ transformTable: props => ({+ ...props,+ htmlProps: {...props.htmlProps, 'data-second': 'yes'},+ }),+ };+ render(+ <XDSBaseTable+ data={users}+ columns={columns}+ plugins={[plugin1, plugin2]}+ />,+ );+ const table = screen.getByRole('table');+ expect(table).toHaveAttribute('data-first', 'yes');+ expect(table).toHaveAttribute('data-second', 'yes');+ });++ it('later plugin can read props set by earlier plugin', () => {+ const plugin1: TablePlugin<User> = {+ transformTable: props => ({+ ...props,+ htmlProps: {...props.htmlProps, 'data-step': '1'},+ }),+ };+ const plugin2: TablePlugin<User> = {+ transformTable: props => {+ const step = (props.htmlProps as Record<string, string>)['data-step'];+ return {+ ...props,+ htmlProps: {...props.htmlProps, 'data-step': step + ',2'},+ };+ },+ };+ render(+ <XDSBaseTable+ data={users}+ columns={columns}+ plugins={[plugin1, plugin2]}+ />,+ );+ expect(screen.getByRole('table')).toHaveAttribute('data-step', '1,2');+ });+ });+});++// =============================================================================+// XDSTable Tests+// =============================================================================++describe('XDSTable', () => {+ it('renders a table with correct structure', () => {+ render(<XDSTable data={users} columns={columns} />);+ expect(screen.getByRole('table')).toBeInTheDocument();+ expect(screen.getAllByRole('columnheader')).toHaveLength(3);+ expect(screen.getAllByRole('cell')).toHaveLength(9);+ expect(screen.getAllByRole('row')).toHaveLength(4);+ });++ it('renders all data values', () => {+ render(<XDSTable data={users} columns={columns} />);+ expect(screen.getByText('Alice')).toBeInTheDocument();+ expect(screen.getByText('Bob')).toBeInTheDocument();+ expect(screen.getByText('Charlie')).toBeInTheDocument();+ expect(screen.getByText('30')).toBeInTheDocument();+ expect(screen.getByText('[email protected]')).toBeInTheDocument();+ });++ it('auto-generates columns from data', () => {+ render(<XDSTable data={users} />);+ const headers = screen.getAllByRole('columnheader');+ expect(headers).toHaveLength(3);+ expect(headers[0]).toHaveTextContent('Name');+ expect(screen.getByText('Alice')).toBeInTheDocument();+ });++ it('forwards ref to the table element', () => {+ const ref = vi.fn();+ render(<XDSTable data={users} columns={columns} ref={ref} />);+ expect(ref).toHaveBeenCalledWith(expect.any(HTMLTableElement));+ });++ describe('density', () => {+ it('renders with compact density', () => {+ render(<XDSTable data={users} columns={columns} density="compact" />);+ expect(screen.getAllByRole('row')).toHaveLength(4);+ });++ it('renders with balanced density (default)', () => {+ render(<XDSTable data={users} columns={columns} />);+ expect(screen.getAllByRole('row')).toHaveLength(4);+ });++ it('renders with spacious density', () => {+ render(<XDSTable data={users} columns={columns} density="spacious" />);+ expect(screen.getAllByRole('row')).toHaveLength(4);+ });+ });++ describe('dividers', () => {+ it('renders with row dividers (default)', () => {+ render(<XDSTable data={users} columns={columns} />);+ expect(screen.getByRole('table')).toBeInTheDocument();+ });++ it('renders with column dividers', () => {+ render(<XDSTable data={users} columns={columns} dividers="columns" />);+ expect(screen.getByRole('table')).toBeInTheDocument();+ });++ it('renders with grid dividers', () => {+ render(<XDSTable data={users} columns={columns} dividers="grid" />);+ expect(screen.getByRole('table')).toBeInTheDocument();+ });++ it('renders with no dividers', () => {+ render(<XDSTable data={users} columns={columns} dividers="none" />);+ expect(screen.getByRole('table')).toBeInTheDocument();+ });+ });++ describe('striped', () => {+ it('renders with striped rows', () => {+ render(<XDSTable data={users} columns={columns} striped />);+ expect(screen.getAllByRole('row')).toHaveLength(4);+ });+ });++ describe('hover', () => {+ it('renders with hover enabled', () => {+ render(<XDSTable data={users} columns={columns} hover />);+ expect(screen.getAllByRole('row')).toHaveLength(4);+ });+ });++ it('renders with all appearance props combined', () => {+ render(+ <XDSTable+ data={users}+ columns={columns}+ density="compact"+ dividers="grid"+ striped+ hover+ />,+ );+ expect(screen.getByRole('table')).toBeInTheDocument();+ expect(screen.getAllByRole('row')).toHaveLength(4);+ expect(screen.getAllByRole('cell')).toHaveLength(9);+ });++ it('accepts user plugins alongside XDS styling', () => {+ const userPlugin: TablePlugin<User> = {+ transformTable: props => ({+ ...props,+ htmlProps: {...props.htmlProps, 'data-testid': 'custom-plugin'},+ }),+ };+ render(<XDSTable data={users} columns={columns} plugins={[userPlugin]} />);+ expect(screen.getByTestId('custom-plugin')).toBeInTheDocument();+ });++ it('runs user plugins after XDS styling plugin', () => {+ const userPlugin: TablePlugin<User> = {+ transformTable: props => {+ // XDS plugin should have already added styles+ expect(props.styles.length).toBeGreaterThan(1);+ return {+ ...props,+ htmlProps: {...props.htmlProps, 'data-testid': 'after-xds'},+ };+ },+ };+ render(<XDSTable data={users} columns={columns} plugins={[userPlugin]} />);+ expect(screen.getByTestId('after-xds')).toBeInTheDocument();+ });++ it('renders children mode with XDSTableRow and XDSTableCell', () => {+ render(+ <XDSTable>+ <XDSTableRow>+ <XDSTableCell>Streamed A</XDSTableCell>+ <XDSTableCell>Streamed B</XDSTableCell>+ </XDSTableRow>+ <XDSTableRow>+ <XDSTableCell>Streamed C</XDSTableCell>+ <XDSTableCell>Streamed D</XDSTableCell>+ </XDSTableRow>+ </XDSTable>,+ );+ expect(screen.getByText('Streamed A')).toBeInTheDocument();+ expect(screen.getByText('Streamed D')).toBeInTheDocument();+ expect(screen.getAllByRole('row')).toHaveLength(2);+ expect(screen.getAllByRole('cell')).toHaveLength(4);+ });++ it('passes through idKey string to base table', () => {+ render(<XDSTable data={users} columns={columns} idKey="email" />);+ expect(screen.getAllByRole('row')).toHaveLength(4);+ });++ it('passes through idKey function to base table', () => {+ const idKey = vi.fn((item: User) => item.email);+ render(<XDSTable data={users} columns={columns} idKey={idKey} />);+ expect(idKey).toHaveBeenCalledTimes(3);+ expect(idKey).toHaveBeenCalledWith(users[0]);+ expect(idKey).toHaveBeenCalledWith(users[1]);+ expect(idKey).toHaveBeenCalledWith(users[2]);+ });+});++// =============================================================================+// XDSTableRow Tests+// =============================================================================++describe('XDSTableRow', () => {+ it('renders a tr element', () => {+ render(+ <table>+ <tbody>+ <XDSTableRow data-testid="test-row">+ <td>Cell</td>+ </XDSTableRow>+ </tbody>+ </table>,+ );+ expect(screen.getByTestId('test-row').tagName).toBe('TR');+ });++ it('renders children inside the tr', () => {+ render(+ <table>+ <tbody>+ <XDSTableRow>+ <td>First</td>+ <td>Second</td>+ </XDSTableRow>+ </tbody>+ </table>,+ );+ expect(screen.getByText('First')).toBeInTheDocument();+ expect(screen.getByText('Second')).toBeInTheDocument();+ });++ it('forwards ref to the tr element', () => {+ const ref = vi.fn();+ render(+ <table>+ <tbody>+ <XDSTableRow ref={ref}>+ <td>Cell</td>+ </XDSTableRow>+ </tbody>+ </table>,+ );+ expect(ref).toHaveBeenCalledWith(expect.any(HTMLTableRowElement));+ });++ it('passes through HTML attributes', () => {+ render(+ <table>+ <tbody>+ <XDSTableRow className="custom" data-testid="row">+ <td>Cell</td>+ </XDSTableRow>+ </tbody>+ </table>,+ );+ expect(screen.getByTestId('row')).toHaveClass('custom');+ });+});++// =============================================================================+// XDSTableCell Tests+// =============================================================================++describe('XDSTableCell', () => {+ it('renders a td element', () => {+ render(+ <table>+ <tbody>+ <tr>+ <XDSTableCell data-testid="test-cell">Content</XDSTableCell>+ </tr>+ </tbody>+ </table>,+ );+ expect(screen.getByTestId('test-cell').tagName).toBe('TD');+ });++ it('renders children inside the td', () => {+ render(+ <table>+ <tbody>+ <tr>+ <XDSTableCell>+ <span>Nested content</span>+ </XDSTableCell>+ </tr>+ </tbody>+ </table>,+ );+ expect(screen.getByText('Nested content')).toBeInTheDocument();+ });++ it('renders empty when no children provided', () => {+ render(+ <table>+ <tbody>+ <tr>+ <XDSTableCell data-testid="empty-cell" />+ </tr>+ </tbody>+ </table>,+ );+ expect(screen.getByTestId('empty-cell')).toHaveTextContent('');+ });++ it('forwards ref to the td element', () => {+ const ref = vi.fn();+ render(+ <table>+ <tbody>+ <tr>+ <XDSTableCell ref={ref}>Cell</XDSTableCell>+ </tr>+ </tbody>+ </table>,+ );+ expect(ref).toHaveBeenCalledWith(expect.any(HTMLTableCellElement));+ });++ it('forwards colSpan attribute', () => {+ render(+ <table>+ <tbody>+ <tr>+ <XDSTableCell colSpan={3} data-testid="span-cell">+ Spanning+ </XDSTableCell>+ </tr>+ </tbody>+ </table>,+ );+ expect(screen.getByTestId('span-cell')).toHaveAttribute('colspan', '3');+ });++ it('forwards rowSpan attribute', () => {+ render(+ <table>+ <tbody>+ <tr>+ <XDSTableCell rowSpan={2} data-testid="rowspan-cell">+ Spanning+ </XDSTableCell>+ </tr>+ </tbody>+ </table>,+ );+ expect(screen.getByTestId('rowspan-cell')).toHaveAttribute('rowspan', '2');+ });+});diff --git a/packages/core/src/Table/XDSTable.tsx b/packages/core/src/Table/XDSTable.tsxnew file mode 100644index 0000000000..c889177225--- /dev/null+++ b/packages/core/src/Table/XDSTable.tsx@@ -0,0 +1,343 @@+/**+ * @file XDSTable.tsx+ * @input React, StyleX, XDSBaseTable, theme tokens, types+ * @output Exports XDSTable component, XDSTableProps, XDSTableDensity, XDSTableDividers types+ * @position Styled wrapper; the primary table API for consumers+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Table/README.md (props table, features, usage examples)+ * - /packages/core/src/Table/XDSTable.test.tsx (tests for new/changed behavior)+ * - /packages/core/src/Table/index.ts (exports if types change)+ * - /apps/storybook/stories/Table.stories.tsx (storybook stories)+ */++import {forwardRef, useMemo, type ReactElement, type Ref} from 'react';+import * as stylex from '@stylexjs/stylex';+import {+ colorVars,+ spacingVars,+ textSizeVars,+ fontWeightVars,+ transitionVars,+} from '../theme/tokens.stylex';+import {XDSBaseTable} from './XDSBaseTable';+import {TableContext} from './TableContext';+import type {+ XDSBaseTableProps,+ TablePlugin,+ TableRenderProps,+ HeaderCellRenderProps,+ BodyRowRenderProps,+ BodyCellRenderProps,+} from './types';++// =============================================================================+// XDSTable Types+// =============================================================================++/** Row density controlling padding and font size */+export type XDSTableDensity = 'compact' | 'balanced' | 'spacious';++/** Divider style between cells */+export type XDSTableDividers = 'rows' | 'columns' | 'grid' | 'none';++/**+ * Props for the styled XDSTable component.+ * Extends XDSBaseTableProps with appearance configuration.+ *+ * @template T - The row data type+ */+export interface XDSTableProps<+ T extends Record<string, unknown>,+> extends XDSBaseTableProps<T> {+ /** Row density. @default 'balanced' */+ density?: XDSTableDensity;+ /** Divider style. @default 'rows' */+ dividers?: XDSTableDividers;+ /** Striped even rows. @default false */+ striped?: boolean;+ /** Hover highlight on rows. @default false */+ hover?: boolean;+}++// =============================================================================+// StyleX Styles+// =============================================================================++const tableStyles = stylex.create({+ base: {+ fontFamily: 'inherit',+ color: colorVars['--color-text-primary'],+ },+});++// Density: padding + font size for cells+const densityStyles = stylex.create({+ compact: {+ paddingBlock: spacingVars['--spacing-1'],+ paddingInline: spacingVars['--spacing-2'],+ fontSize: textSizeVars['--text-xsm'],+ },+ balanced: {+ paddingBlock: spacingVars['--spacing-2'],+ paddingInline: spacingVars['--spacing-3'],+ fontSize: textSizeVars['--text-sm'],+ },+ spacious: {+ paddingBlock: spacingVars['--spacing-3'],+ paddingInline: spacingVars['--spacing-4'],+ fontSize: textSizeVars['--text-base'],+ },+});++// Header cell styles+const headerStyles = stylex.create({+ cell: {+ fontWeight: fontWeightVars['--font-weight-semibold'],+ color: colorVars['--color-text-secondary'],+ textAlign: 'start',+ },+});++// Divider styles — applied to cells+const dividerRowStyles = stylex.create({+ cell: {+ borderBottomWidth: '1px',+ borderBottomStyle: 'solid',+ borderBottomColor: colorVars['--color-divider'],+ },+});++const dividerColumnStyles = stylex.create({+ cell: {+ borderRightWidth: {+ default: '1px',+ ':last-child': '0',+ },+ borderRightStyle: 'solid',+ borderRightColor: colorVars['--color-divider'],+ },+});++const dividerGridStyles = stylex.create({+ cell: {+ borderBottomWidth: '1px',+ borderBottomStyle: 'solid',+ borderBottomColor: colorVars['--color-divider'],+ borderRightWidth: {+ default: '1px',+ ':last-child': '0',+ },+ borderRightStyle: 'solid',+ borderRightColor: colorVars['--color-divider'],+ },+});++// Striped row styles+const stripedStyles = stylex.create({+ evenRow: {+ backgroundColor: colorVars['--color-wash'],+ },+});++// Striped + hover combined (wash default, overlay on hover)+const stripedHoverStyles = stylex.create({+ evenRow: {+ backgroundColor: {+ default: colorVars['--color-wash'],+ ':hover': colorVars['--color-hover-overlay'],+ },+ transitionProperty: 'background-color',+ transitionDuration: transitionVars['--transition-fast'],+ },+});++// Last body row — override bottom border via 'hidden' (wins in border-collapse)+const lastBodyRowStyles = stylex.create({+ row: {+ borderBottomStyle: {+ default: null,+ ':last-child': 'hidden',+ },+ },+});++// Hover row styles+const hoverStyles = stylex.create({+ row: {+ backgroundColor: {+ default: null,+ ':hover': colorVars['--color-hover-overlay'],+ },+ transitionProperty: 'background-color',+ transitionDuration: transitionVars['--transition-fast'],+ },+});++// Header divider (bottom border on header row)+const headerDividerStyles = stylex.create({+ cell: {+ borderBottomWidth: '1px',+ borderBottomStyle: 'solid',+ borderBottomColor: colorVars['--color-divider'],+ },+});++// =============================================================================+// Build XDS Styling Plugin+// =============================================================================++function buildXDSStylePlugin<T extends Record<string, unknown>>(+ density: XDSTableDensity,+ dividers: XDSTableDividers,+ striped: boolean,+ hover: boolean,+): TablePlugin<T> {+ return {+ transformTable(props: TableRenderProps): TableRenderProps {+ return {+ ...props,+ styles: [...props.styles, tableStyles.base],+ };+ },++ transformHeaderCell(+ props: HeaderCellRenderProps,+ column,+ ): HeaderCellRenderProps {+ const cellStyles = [+ ...props.styles,+ headerStyles.cell,+ densityStyles[density],+ headerDividerStyles.cell,+ ];++ // Column dividers on header cells+ if (dividers === 'columns' || dividers === 'grid') {+ cellStyles.push(dividerColumnStyles.cell);+ }++ return {...props, styles: cellStyles};+ },++ transformBodyRow(+ props: BodyRowRenderProps,+ _item: T,+ index: number,+ ): BodyRowRenderProps {+ const rowStyles = [...props.styles];++ // Handle striped + hover combination to avoid backgroundColor conflicts+ if (striped && hover && index % 2 === 1) {+ rowStyles.push(stripedHoverStyles.evenRow);+ } else if (striped && index % 2 === 1) {+ rowStyles.push(stripedStyles.evenRow);+ } else if (hover) {+ rowStyles.push(hoverStyles.row);+ }++ // Hover transition for non-striped rows when both are active+ if (striped && hover && index % 2 === 0) {+ rowStyles.push(hoverStyles.row);+ }++ // Hide bottom border on last body row+ if (dividers === 'rows' || dividers === 'grid') {+ rowStyles.push(lastBodyRowStyles.row);+ }++ return {...props, styles: rowStyles};+ },++ transformBodyCell(+ props: BodyCellRenderProps,+ _column,+ ): BodyCellRenderProps {+ const cellStyles = [...props.styles, densityStyles[density]];++ if (dividers === 'rows' || dividers === 'grid') {+ cellStyles.push(dividerRowStyles.cell);+ }++ if (dividers === 'columns' || dividers === 'grid') {+ cellStyles.push(dividerColumnStyles.cell);+ }++ return {...props, styles: cellStyles};+ },+ };+}++// =============================================================================+// XDSTable Component+// =============================================================================++function XDSTableInner<T extends Record<string, unknown>>(+ {+ density = 'balanced',+ dividers = 'rows',+ striped = false,+ hover = false,+ plugins: userPlugins = [],+ columns,+ data,+ ...rest+ }: XDSTableProps<T>,+ ref: Ref<HTMLTableElement>,+): ReactElement {+ // Build the internal XDS styling plugin+ const xdsPlugin = useMemo(+ () => buildXDSStylePlugin<T>(density, dividers, striped, hover),+ [density, dividers, striped, hover],+ );++ // XDS plugin runs first, user plugins can override/extend+ const mergedPlugins = useMemo(+ () => [xdsPlugin, ...userPlugins],+ [xdsPlugin, userPlugins],+ );++ const contextValue = useMemo(+ () => ({density, dividers, striped, hover}),+ [density, dividers, striped, hover],+ );++ return (+ <TableContext.Provider value={contextValue}>+ <XDSBaseTable<T>+ ref={ref}+ data={data}+ columns={columns}+ plugins={mergedPlugins}+ {...rest}+ />+ </TableContext.Provider>+ );+}++/**+ * XDSTable — a styled, data-driven table component.+ *+ * Wraps XDSBaseTable with an XDS styling plugin that applies density,+ * dividers, striped rows, and hover effects using design tokens.+ *+ * @example+ * ```tsx+ * <XDSTable+ * data={users}+ * columns={[+ * { key: 'name', header: 'Name' },+ * { key: 'email', header: 'Email' },+ * ]}+ * density="compact"+ * dividers="grid"+ * striped+ * hover+ * />+ * ```+ */+export const XDSTable = forwardRef(XDSTableInner) as <+ T extends Record<string, unknown>,+>(+ props: XDSTableProps<T> & {ref?: Ref<HTMLTableElement>},+) => ReactElement;diff --git a/packages/core/src/Table/XDSTableCell.tsx b/packages/core/src/Table/XDSTableCell.tsxnew file mode 100644index 0000000000..52a6a7a366--- /dev/null+++ b/packages/core/src/Table/XDSTableCell.tsx@@ -0,0 +1,109 @@+/**+ * @file XDSTableCell.tsx+ * @input React, StyleX, TableContext, theme tokens+ * @output Exports XDSTableCell component, XDSTableCellProps+ * @position Sub-component; used inside XDSTable children mode+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Table/README.md+ * - /packages/core/src/Table/index.ts+ */++import {+ forwardRef,+ useContext,+ type TdHTMLAttributes,+ type ReactNode,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import {colorVars, spacingVars, textSizeVars} from '../theme/tokens.stylex';+import type {StyleXStyles} from '../theme/types';+import {TableContext} from './TableContext';++/** Props for XDSTableCell — thin `<td>` wrapper */+export interface XDSTableCellProps extends TdHTMLAttributes<HTMLTableCellElement> {+ children?: ReactNode;+}++const densityStyles = stylex.create({+ compact: {+ paddingBlock: spacingVars['--spacing-1'],+ paddingInline: spacingVars['--spacing-2'],+ fontSize: textSizeVars['--text-xsm'],+ },+ balanced: {+ paddingBlock: spacingVars['--spacing-2'],+ paddingInline: spacingVars['--spacing-3'],+ fontSize: textSizeVars['--text-sm'],+ },+ spacious: {+ paddingBlock: spacingVars['--spacing-3'],+ paddingInline: spacingVars['--spacing-4'],+ fontSize: textSizeVars['--text-base'],+ },+});++const dividerRowStyles = stylex.create({+ cell: {+ borderBottomWidth: '1px',+ borderBottomStyle: 'solid',+ borderBottomColor: colorVars['--color-divider'],+ },+});++const dividerColumnStyles = stylex.create({+ cell: {+ borderRightWidth: {+ default: '1px',+ ':last-child': '0',+ },+ borderRightStyle: 'solid',+ borderRightColor: colorVars['--color-divider'],+ },+});++/**+ * XDSTableCell — a `<td>` wrapper for children/streaming mode.+ *+ * When used inside `<XDSTable>`, inherits styling from the table context+ * (density padding, divider borders). When used standalone, renders a plain `<td>`.+ *+ * @example+ * ```tsx+ * <XDSTableRow>+ * <XDSTableCell>Alice</XDSTableCell>+ * <XDSTableCell>30</XDSTableCell>+ * </XDSTableRow>+ * ```+ */+export const XDSTableCell = forwardRef<HTMLTableCellElement, XDSTableCellProps>(+ ({children, ...props}, ref) => {+ const ctx = useContext(TableContext);++ if (!ctx) {+ return (+ <td ref={ref} {...props}>+ {children}+ </td>+ );+ }++ const cellStyles: StyleXStyles[] = [densityStyles[ctx.density]];++ if (ctx.dividers === 'rows' || ctx.dividers === 'grid') {+ cellStyles.push(dividerRowStyles.cell);+ }++ if (ctx.dividers === 'columns' || ctx.dividers === 'grid') {+ cellStyles.push(dividerColumnStyles.cell);+ }++ return (+ <td ref={ref} {...props} {...stylex.props(...cellStyles)}>+ {children}+ </td>+ );+ },+);++XDSTableCell.displayName = 'XDSTableCell';diff --git a/packages/core/src/Table/XDSTableRow.tsx b/packages/core/src/Table/XDSTableRow.tsxnew file mode 100644index 0000000000..6d42c06266--- /dev/null+++ b/packages/core/src/Table/XDSTableRow.tsx@@ -0,0 +1,120 @@+/**+ * @file XDSTableRow.tsx+ * @input React, StyleX, TableContext, theme tokens+ * @output Exports XDSTableRow component, XDSTableRowProps+ * @position Sub-component; used inside XDSTable children mode+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Table/README.md+ * - /packages/core/src/Table/index.ts+ */++import {+ forwardRef,+ useContext,+ type HTMLAttributes,+ type ReactNode,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import {colorVars, transitionVars} from '../theme/tokens.stylex';+import type {StyleXStyles} from '../theme/types';+import {TableContext} from './TableContext';++/** Props for XDSTableRow — thin `<tr>` wrapper */+export interface XDSTableRowProps extends HTMLAttributes<HTMLTableRowElement> {+ children: ReactNode;+}++const stripedRowStyles = stylex.create({+ row: {+ backgroundColor: {+ default: null,+ ':nth-child(even)': colorVars['--color-wash'],+ },+ },+});++const hoverRowStyles = stylex.create({+ row: {+ backgroundColor: {+ default: null,+ ':hover': colorVars['--color-hover-overlay'],+ },+ transitionProperty: 'background-color',+ transitionDuration: transitionVars['--transition-fast'],+ },+});++const stripedHoverRowStyles = stylex.create({+ row: {+ backgroundColor: {+ default: null,+ ':nth-child(even)': colorVars['--color-wash'],+ ':hover': colorVars['--color-hover-overlay'],+ },+ transitionProperty: 'background-color',+ transitionDuration: transitionVars['--transition-fast'],+ },+});++const lastBodyRowStyles = stylex.create({+ row: {+ borderBottomStyle: {+ default: null,+ ':last-child': 'hidden',+ },+ },+});++/**+ * XDSTableRow — a `<tr>` wrapper for children/streaming mode.+ *+ * When used inside `<XDSTable>`, inherits styling from the table context+ * (striped, hover, divider overrides). When used standalone, renders a plain `<tr>`.+ *+ * @example+ * ```tsx+ * <XDSTable>+ * <XDSTableRow>+ * <XDSTableCell>Alice</XDSTableCell>+ * <XDSTableCell>30</XDSTableCell>+ * </XDSTableRow>+ * </XDSTable>+ * ```+ */+export const XDSTableRow = forwardRef<HTMLTableRowElement, XDSTableRowProps>(+ ({children, ...props}, ref) => {+ const ctx = useContext(TableContext);++ if (!ctx) {+ return (+ <tr ref={ref} {...props}>+ {children}+ </tr>+ );+ }++ const rowStyles: StyleXStyles[] = [];++ // Handle striped + hover combination to avoid backgroundColor conflicts+ if (ctx.striped && ctx.hover) {+ rowStyles.push(stripedHoverRowStyles.row);+ } else if (ctx.striped) {+ rowStyles.push(stripedRowStyles.row);+ } else if (ctx.hover) {+ rowStyles.push(hoverRowStyles.row);+ }++ if (ctx.dividers === 'rows' || ctx.dividers === 'grid') {+ rowStyles.push(lastBodyRowStyles.row);+ }++ return (+ <tr ref={ref} {...props} {...stylex.props(...rowStyles)}>+ {children}+ </tr>+ );+ },+);++XDSTableRow.displayName = 'XDSTableRow';diff --git a/packages/core/src/Table/columnUtils.ts b/packages/core/src/Table/columnUtils.tsnew file mode 100644index 0000000000..8e7abbb4c5--- /dev/null+++ b/packages/core/src/Table/columnUtils.ts@@ -0,0 +1,92 @@+/**+ * @file columnUtils.ts+ * @input XDSTableColumn, ColumnWidth types from types.ts+ * @output Pure utility functions for column width and auto-generation+ * @position Utility layer; consumed by XDSBaseTable.tsx+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Table/README.md (utility descriptions)+ * - /packages/core/src/Table/index.ts (exports if functions change)+ */++import type {ReactNode} from 'react';+import type {+ XDSTableColumn,+ ColumnWidth,+ ProportionalWidth,+ PixelWidth,+} from './types';++/**+ * Create a proportional column width (fr-like).+ * Columns share available space proportionally.+ *+ * @example proportional(2) // twice as wide as proportional(1)+ */+export function proportional(value: number = 1): ProportionalWidth {+ return {type: 'proportional', value};+}++/**+ * Create a fixed pixel column width.+ *+ * @example pixel(200) // exactly 200px wide+ */+export function pixel(value: number): PixelWidth {+ return {type: 'pixel', value};+}++/**+ * Convert a ColumnWidth to a CSS width string for `<col>`.+ *+ * Proportional widths are converted to percentages relative to the+ * total proportional units across all columns.+ */+export function columnWidthToCSS(+ width: ColumnWidth,+ totalProportional: number,+): string {+ if (width.type === 'pixel') {+ return `${width.value}px`;+ }+ // Convert proportional to percentage+ const pct = (width.value / totalProportional) * 100;+ return `${pct}%`;+}++/**+ * Capitalize the first letter of a string.+ * Used for auto-generating header text from data keys.+ */+export function capitalize(str: string): string {+ if (str.length === 0) return str;+ return str.charAt(0).toUpperCase() + str.slice(1);+}++/**+ * Default cell renderer — converts the value at `item[key]` to a string.+ */+export function defaultCellRenderer<T extends Record<string, unknown>>(+ item: T,+ key: string,+): ReactNode {+ const value = item[key];+ if (value == null) return '';+ return String(value);+}++/**+ * Auto-generate column definitions from the keys of the first data item.+ * Each column gets `proportional(1)` width and a capitalized header.+ */+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),+ }));+}diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.tsnew file mode 100644index 0000000000..8a92aa6063--- /dev/null+++ b/packages/core/src/Table/index.ts@@ -0,0 +1,41 @@+/**+ * @file index.ts+ * @input Imports from Table component files+ * @output Exports all Table components, types, and utilities+ * @position Component entry point; re-exported by /packages/core/src/index.ts+ *+ * SYNC: When modified, update this header and /packages/core/src/Table/README.md+ */++export {XDSBaseTable} from './XDSBaseTable';+export {XDSTable} from './XDSTable';+export {XDSTableRow} from './XDSTableRow';+export {XDSTableCell} from './XDSTableCell';+export {TableContext} from './TableContext';+export {+ proportional,+ pixel,+ generateColumns,+ columnWidthToCSS,+} from './columnUtils';+export type {+ XDSTableColumn,+ ColumnWidth,+ ProportionalWidth,+ PixelWidth,+ TablePlugin,+ TableRenderProps,+ HeaderRowRenderProps,+ HeaderCellRenderProps,+ BodyRowRenderProps,+ BodyCellRenderProps,+ XDSBaseTableProps,+} from './types';+export type {+ XDSTableProps,+ XDSTableDensity,+ XDSTableDividers,+} from './XDSTable';+export type {XDSTableRowProps} from './XDSTableRow';+export type {XDSTableCellProps} from './XDSTableCell';+export type {TableContextValue} from './TableContext';diff --git a/packages/core/src/Table/types.ts b/packages/core/src/Table/types.tsnew file mode 100644index 0000000000..f32b87844e--- /dev/null+++ b/packages/core/src/Table/types.ts@@ -0,0 +1,163 @@+/**+ * @file types.ts+ * @input None (pure type definitions)+ * @output Exports base Table interfaces: column, render props, plugin, XDSBaseTableProps+ * @position Type foundation; consumed by XDSBaseTable and extended by XDSTable+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Table/README.md (type descriptions)+ * - /packages/core/src/Table/index.ts (exports if types change)+ */++import type {+ HTMLAttributes,+ TdHTMLAttributes,+ ThHTMLAttributes,+ ReactNode,+} from 'react';+import type {StyleXStyles} from '../theme/types';++// =============================================================================+// Column Width+// =============================================================================++/**+ * A proportional (fr-like) column width.+ * Use the `proportional()` helper to create.+ */+export interface ProportionalWidth {+ type: 'proportional';+ value: number;+}++/**+ * A fixed pixel column width.+ * Use the `pixel()` helper to create.+ */+export interface PixelWidth {+ type: 'pixel';+ value: number;+}++/** Column width — either proportional or fixed pixel */+export type ColumnWidth = ProportionalWidth | PixelWidth;++// =============================================================================+// Column Definition+// =============================================================================++/**+ * Column definition for data-driven table rendering.+ *+ * @template T - The row data type+ */+export interface XDSTableColumn<T extends Record<string, unknown>> {+ /** Unique key identifying this column. Used as React key and to access data. */+ key: string;+ /** Header text displayed in `<th>`. Defaults to capitalized `key`. */+ header?: ReactNode;+ /** Column width. Defaults to `proportional(1)`. */+ width?: ColumnWidth;+ /**+ * Custom cell renderer. Receives the row item.+ * Defaults to `String(item[key])`.+ */+ renderCell?: (item: T) => ReactNode;+}++// =============================================================================+// Render Props (Plugin Transform Targets)+// =============================================================================++/** Props passed through the plugin pipeline for the `<table>` element */+export interface TableRenderProps {+ htmlProps: HTMLAttributes<HTMLTableElement>;+ styles: StyleXStyles[];+}++/** Props passed through the plugin pipeline for the header `<tr>` */+export interface HeaderRowRenderProps {+ htmlProps: HTMLAttributes<HTMLTableRowElement>;+ styles: StyleXStyles[];+}++/** Props passed through the plugin pipeline for each `<th>` */+export interface HeaderCellRenderProps {+ htmlProps: ThHTMLAttributes<HTMLTableCellElement>;+ styles: StyleXStyles[];+}++/** Props passed through the plugin pipeline for each body `<tr>` */+export interface BodyRowRenderProps {+ htmlProps: HTMLAttributes<HTMLTableRowElement>;+ styles: StyleXStyles[];+}++/** Props passed through the plugin pipeline for each body `<td>` */+export interface BodyCellRenderProps {+ htmlProps: TdHTMLAttributes<HTMLTableCellElement>;+ styles: StyleXStyles[];+}++// =============================================================================+// Plugin Interface+// =============================================================================++/**+ * Table plugin — transforms render props at each structural level.+ * Plugins compose by sequential application (first plugin's output feeds next).+ */+export interface TablePlugin<+ T extends Record<string, unknown> = Record<string, unknown>,+> {+ /** Transform the root `<table>` element props */+ transformTable?: (props: TableRenderProps) => TableRenderProps;+ /** Transform the header `<tr>` props */+ transformHeaderRow?: (props: HeaderRowRenderProps) => HeaderRowRenderProps;+ /** Transform each `<th>` props */+ transformHeaderCell?: (+ props: HeaderCellRenderProps,+ column: XDSTableColumn<T>,+ ) => HeaderCellRenderProps;+ /** Transform each body `<tr>` props */+ transformBodyRow?: (+ props: BodyRowRenderProps,+ item: T,+ index: number,+ ) => BodyRowRenderProps;+ /** Transform each body `<td>` props */+ transformBodyCell?: (+ props: BodyCellRenderProps,+ column: XDSTableColumn<T>,+ item: T,+ ) => BodyCellRenderProps;+}++// =============================================================================+// XDSBaseTable Props+// =============================================================================++/**+ * Props for the unstyled XDSBaseTable component.+ *+ * @template T - The row data type+ */+export interface XDSBaseTableProps<T extends Record<string, unknown>> {+ /** Array of data items to render as rows */+ data?: T[];+ /** Column definitions. If omitted, auto-generated from data keys. */+ columns?: XDSTableColumn<T>[];+ /**+ * Row key for React reconciliation.+ * - `string` — property name to use as key (e.g. `"id"`), must be a key of `T`+ * - `function` — custom extractor (e.g. `(item) => item.id`)+ * - omitted — falls back to row index+ */+ idKey?: (keyof T & string) | ((item: T) => string | number);+ /** Plugins to transform render props at each level */+ plugins?: TablePlugin<T>[];+ /** Children mode — render `<tr>`/`<td>` directly instead of data-driven */+ children?: ReactNode;+ /** Additional HTML attributes for the `<table>` element */+ tableProps?: HTMLAttributes<HTMLTableElement>;+}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex b4c487049c..039b89cd2e 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -26,6 +26,7 @@ export * from './Text';export * from './TextInput';export * from './TextArea';export * from './TimeInput';+export * from './Table';// Layout utilities and components (includes XDSHStack, XDSVStack)export * from './Layout';