diff --git a/.changeset/core-list-window-module.md b/.changeset/core-list-window-module.md deleted file mode 100644 index fa5ddc2d8e913..0000000000000 --- a/.changeset/core-list-window-module.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -'@astryxdesign/core': patch ---- - -[chore] Internal: Core gains a private list-windowing module, the range, spacer and anchor arithmetic that windowed lists share, and Table's virtualization capability hook, which the package does not export yet. Apps import nothing new. - -@humbertovirtudes diff --git a/.changeset/table-fixed-height-windowing.md b/.changeset/table-fixed-height-windowing.md new file mode 100644 index 0000000000000..51e753f55021f --- /dev/null +++ b/.changeset/table-fixed-height-windowing.md @@ -0,0 +1,8 @@ +--- +'@astryxdesign/core': patch +'@astryxdesign/cli': patch +--- + +[feat] Tables can window fixed-height flat data: pass `useTableRowsVirtualization({rowHeight, viewportHeight})` to `Table.virtualization`. Table keeps the complete data and row identity, mounts only the rows in its viewport plus a few overscan rows, keeps native table semantics with full-table row positions, keeps the focused row mounted, and falls back to rendering every row for content or geometry it cannot window. Tables that do not opt in are unchanged. + +@humbertovirtudes diff --git a/.changeset/table-window-controller-internal.md b/.changeset/table-window-controller-internal.md deleted file mode 100644 index 10d5b3b4a4673..0000000000000 --- a/.changeset/table-window-controller-internal.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -'@astryxdesign/core': patch ---- - -[chore] Internal: Table gains a private window controller and a viewport runtime that read the geometry its scroll owner already measures, and `useScrollableArea` reports whether a measurement followed a content or a layout change. Nothing renders through them yet; apps import nothing new. - -@humbertovirtudes diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json index 746ebe3d4e525..e20265f555ded 100644 --- a/apps/sandbox/scripts/next-export-routes.json +++ b/apps/sandbox/scripts/next-export-routes.json @@ -503,6 +503,7 @@ "/templates/RadioListWithValidation/", "/templates/ResizableShowcase/", "/templates/ResizableSidebar/", + "/templates/RowsVirtualizationHookUsage/", "/templates/ScrollableAreaInlineRail/", "/templates/ScrollableAreaOverscrollChaining/", "/templates/ScrollableAreaShowcase/", diff --git a/apps/storybook/stories/TableVirtualization.stories.tsx b/apps/storybook/stories/TableVirtualization.stories.tsx new file mode 100644 index 0000000000000..a50fc6e4e41fb --- /dev/null +++ b/apps/storybook/stories/TableVirtualization.stories.tsx @@ -0,0 +1,35 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +import type {Meta, StoryObj} from '@storybook/react-vite'; +import {Table, useTableRowsVirtualization} from '@astryxdesign/core'; +const rows = Array.from({length: 2000}, (_, index) => ({ + id: String(index), + name: `Product ${index + 1}`, + status: 'Available', +})); +const meta: Meta = { + title: 'Core/Table virtualization', + component: Table, +}; +export default meta; +function Example() { + const virtualization = useTableRowsVirtualization({ + rowHeight: 56, + viewportHeight: 320, + }); + return ( + + ); +} +export const FixedHeightWindowing: StoryObj = { + render: () => , +}; diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json index cc55591b687b8..e43f6eb62e98f 100644 --- a/internal/shadcn-registry/routes.lock.json +++ b/internal/shadcn-registry/routes.lock.json @@ -3941,6 +3941,11 @@ "path": "examples/use-table-row-status/semantic-and-custom-markers", "aliases": [] }, + { + "name": "example-use-table-rows-virtualization-fixed-height-rows", + "path": "examples/use-table-rows-virtualization/fixed-height-rows", + "aliases": [] + }, { "name": "example-use-table-selection-state-table-selection-in-the-leading-mark", "path": "examples/use-table-selection-state/table-selection-in-the-leading-mark", @@ -4336,6 +4341,11 @@ "path": "hooks/use-table-row-status", "aliases": [] }, + { + "name": "hook-use-table-rows-virtualization", + "path": "hooks/use-table-rows-virtualization", + "aliases": [] + }, { "name": "hook-use-table-selection", "path": "hooks/use-table-selection", diff --git a/packages/cli/assets/templates/blocks/components/Table/RowsVirtualizationHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Table/RowsVirtualizationHookUsage.doc.mjs new file mode 100644 index 0000000000000..e00e2ec66e7cc --- /dev/null +++ b/packages/cli/assets/templates/blocks/components/Table/RowsVirtualizationHookUsage.doc.mjs @@ -0,0 +1,14 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */ +export const doc = { + type: 'block', + exampleFor: 'useTableRowsVirtualization', + name: 'useTableRowsVirtualization - Fixed Height Rows', + displayName: 'useTableRowsVirtualization - Fixed Height Rows', + description: + 'A Table with 1,000 product rows in a fixed-height viewport. Scroll vertically to mount the visible rows. The caller keeps all data and columns; this hook does not virtualize columns.', + isReady: true, + aspectRatio: 16 / 9, + componentsUsed: ['Table'], +}; diff --git a/packages/cli/assets/templates/blocks/components/Table/RowsVirtualizationHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Table/RowsVirtualizationHookUsage.tsx new file mode 100644 index 0000000000000..b0cff3697bc7b --- /dev/null +++ b/packages/cli/assets/templates/blocks/components/Table/RowsVirtualizationHookUsage.tsx @@ -0,0 +1,35 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +import { + Table, + useTableRowsVirtualization, + type TableColumn, +} from '@astryxdesign/core/Table'; + +interface Product extends Record { + id: string; + name: string; +} + +const products: Product[] = Array.from({length: 1000}, (_, index) => ({ + id: `product-${index}`, + name: `Product ${index + 1}`, +})); +const columns: TableColumn[] = [{key: 'name', header: 'Product'}]; + +export default function RowsVirtualizationHookUsage() { + const virtualization = useTableRowsVirtualization({ + rowHeight: 56, + viewportHeight: 320, + }); + return ( +
+ ); +} diff --git a/packages/core/api-report.md b/packages/core/api-report.md index 60d9c4a7a7a8f..b313df2702319 100644 --- a/packages/core/api-report.md +++ b/packages/core/api-report.md @@ -2340,6 +2340,7 @@ component Table prop scrollWrapper?: ComponentType<{ children: ReactNode; htmlProps?: HTMLAttributes & { ref?: Ref }; xstyle?: StyleXStyles[]; beforeTable?: ReactNode; afterTable?: ReactNode }> prop textOverflow?: 'wrap' | 'truncate' = 'wrap' prop verticalAlign?: TableVerticalAlign = 'middle' + prop virtualization?: BaseTableProps['virtualization'] prop xstyle?: StyleXStyles inherits AriaAttributes, DOMAttributes, HTMLAttributes component TableBody(props: TableBodyProps) @@ -2972,6 +2973,7 @@ hook useTablePagination: >(config: UseTablePag hook useTableRowExpansion: >(config: UseTableRowExpansionConfig) => TablePlugin hook useTableRowIndex: >(config?: UseTableRowIndexConfig) => TablePlugin hook useTableRowStatus: >(config: UseTableRowStatusConfig) => TablePlugin +hook useTableRowsVirtualization: ({…}: UseTableRowsVirtualizationConfig) => TableVirtualizationCapability hook useTableSelection: >(config: UseTableSelectionConfig) => TablePlugin hook useTableSelectionState: >(config: UseTableSelectionStateConfig) => UseTableSelectionStateResult hook useTableSortable: , TSortKey extends string = string>(config: UseTableSortableConfig) => TablePlugin @@ -3631,6 +3633,7 @@ interface BaseTableProps> extends BaseProps & { ref?: Ref }; xstyle?: StyleXStyles[]; beforeTable?: ReactNode; afterTable?: ReactNode }> textOverflow?: 'wrap' | 'truncate' = 'wrap' + virtualization?: TableVirtualizationCapability xstyle?: StyleXStyles inherits AriaAttributes, DOMAttributes, HTMLAttributes interface BaseTypeaheadProps extends Omit, 'onChange'> (props of BaseTypeahead) @@ -5471,7 +5474,7 @@ interface TablePlugin = Record ScrollWrapperRenderProps transformTable?: (props: TableRenderProps) => TableRenderProps transformTableContext?: (children: ReactNode) => ReactNode -interface TableProps> extends Omit, 'plugins' | 'components'> +interface TableProps> extends TableAppearanceProps children?: ReactNode columns?: TableColumn[] data?: T[] @@ -5488,11 +5491,26 @@ interface TableProps> extends Omit & { ref?: Ref }; xstyle?: StyleXStyles[]; beforeTable?: ReactNode; afterTable?: ReactNode }> textOverflow?: 'wrap' | 'truncate' = 'wrap' verticalAlign?: TableVerticalAlign = 'middle' + virtualization?: BaseTableProps['virtualization'] xstyle?: StyleXStyles inherits AriaAttributes, DOMAttributes, HTMLAttributes +interface TableRenderContext + headerRowCount: number + logicalRowCount: number + mode: 'data' | 'children' + rowModel: 'flat' | 'tree' | 'grouped' | 'detail' | 'custom' + viewport: React.RefObject interface TableRenderProps htmlProps: HTMLAttributes xstyle: StyleXStyles[] +interface TableRowContext + headerRowCount: number + identityStatus: 'valid' | 'missing' | 'invalid' | 'duplicate' + key: string | number | undefined + kind: 'product' | 'synthetic' | 'unknown' + logicalIndex: number + logicalRowCount: number + render: TableRenderContext interface TableRowProps extends BaseProps (props of TableRow) interface TableRowStatus color: TableRowStatusColor | (string & {}) @@ -5503,23 +5521,9 @@ interface TableSelectionState hasSelection: boolean selectedCount: number selectedKeys: ReadonlySet -interface TableRenderContext - headerRowCount: number - logicalRowCount: number - mode: 'data' | 'children' - rowModel: 'flat' | 'tree' | 'grouped' | 'detail' | 'custom' - viewport: React.RefObject interface TableSelectionToolbarProps extends Omit (props of TableSelectionToolbar) interface TableSemanticRowStatus color?: never -interface TableRowContext - headerRowCount: number - identityStatus: 'valid' | 'missing' | 'invalid' | 'duplicate' - key: string | number | undefined - kind: 'product' | 'synthetic' | 'unknown' - logicalIndex: number - logicalRowCount: number - render: TableRenderContext icon?: never label: string status: 'success' | 'warning' | 'error' @@ -5538,6 +5542,8 @@ interface TableTreeRowMeta isExpanded: boolean level: number type TableVerticalAlign = 'middle' | 'top' | 'bottom' +interface TableVirtualizationCapability + [capabilityBrand]: Readonly interface TextAreaProps extends Omit, TextEntryTraitProps (props of TextArea) type TextAreaSize = 'sm' | 'md' | 'lg' interface TextAreaStatus @@ -6248,6 +6254,9 @@ interface UseTableRowIndexConfig> startFrom?: number = 1 interface UseTableRowStatusConfig> getStatus: (item: T) => (TableRowStatus & { status?: never }) | TableSemanticRowStatus | null +interface UseTableRowsVirtualizationConfig + rowHeight: number + viewportHeight: number interface UseTableSelectionConfig> getIsAllSelected: () => boolean getIsIndeterminate?: () => boolean @@ -8727,8 +8736,10 @@ TableHeaderCellProps (.) TableHeaderProps (.) TablePlugin (.) TableProps (.) +TableRenderContext (.) TableRenderProps (.) TableRow (.) +TableRowContext (.) TableRowProps (.) TableRowStatus (.) TableSelectionState (.) @@ -8743,19 +8754,19 @@ TableSortableColumnConfig (.) TableTextOverflow (.) TableTreeRowMeta (.) TableVerticalAlign (.) +TableVirtualizationCapability (.) UseTableColumnResizeConfig (.) UseTableColumnSettingsConfig (.) UseTableColumnSettingsStateConfig (.) -TableRenderContext (.) UseTableColumnSettingsStateReturn (.) UseTableFilteringConfig (.) -TableRowContext (.) UseTableGroupedRowsConfig (.) UseTableGroupedRowsResult (.) UseTablePaginationConfig (.) UseTableRowExpansionConfig (.) UseTableRowIndexConfig (.) UseTableRowStatusConfig (.) +UseTableRowsVirtualizationConfig (.) UseTableSelectionConfig (.) UseTableSelectionStateConfig (.) UseTableSelectionStateResult (.) @@ -8784,6 +8795,7 @@ useTablePagination (.) useTableRowExpansion (.) useTableRowIndex (.) useTableRowStatus (.) +useTableRowsVirtualization (.) useTableSelection (.) useTableSelectionState (.) useTableSortable (.) diff --git a/packages/core/src/Table/BaseTable.tsx b/packages/core/src/Table/BaseTable.tsx index 0ce3f46f15175..0c6f453991675 100644 --- a/packages/core/src/Table/BaseTable.tsx +++ b/packages/core/src/Table/BaseTable.tsx @@ -3,9 +3,8 @@ 'use client'; /** * @file BaseTable.tsx - * @input React, types.ts, columnUtils.ts, tableRowContextUsage.ts - * @output Exports BaseTable component; passes a TableRowContext to body row - * and cell transforms and a TableRenderContext to scroll-wrapper transforms + * @input React, canonical identity/admission, private window planning and tracked row context + * @output Exports BaseTable component and passes immutable transform contexts * @position Core structural component; wrapped by Table.tsx * * SYNC: When modified, update these files to stay in sync: @@ -24,6 +23,20 @@ import { type ReactNode, type Ref, } from 'react'; +import { + createTableRuntime, + TableRuntimeContext, + isTableScrollWrapperOwned, +} from './tableRuntime'; +import {resolveTableIdentity, resolveTableAdmission} from './tableIdentity'; +import {useTableWindow} from './plugins/virtualization/useTableWindow'; +import {getTableVirtualizationConfig} from './plugins/virtualization/useTableRowsVirtualization'; +import {TableContext} from './TableContext'; +import {use} from 'react'; +import { + isFixedHeightColumn, + getLogicalPositionRenderer, +} from './tableColumnAdmission'; import {isRenderable} from '../utils/isRenderable'; import * as stylex from '@stylexjs/stylex'; import {spacingVars} from '../theme/tokens.stylex'; @@ -63,6 +76,7 @@ import { trackRowContext, } from './tableRowContextUsage'; import {devError} from '../utils/devWarning'; +import {useDevWarningPerMessage} from '../hooks/useDevWarning'; import {EmptyState} from '../EmptyState'; import {Text} from '../Text'; import {themeProps} from '../utils/themeProps'; @@ -75,6 +89,13 @@ import english from '../i18n/generated-english/Table/BaseTable.generated'; registerEnglishFallback(english); const styles = stylex.create({ + spacer: (height: number) => ({ + height, + padding: 0, + borderWidth: 0, + lineHeight: 0, + }), + fixedRow: (height: number) => ({height}), table: { width: '100%', borderCollapse: 'collapse', @@ -125,10 +146,6 @@ function applyPlugins( }, initial); } -/** - * Run a row-level pipeline. Each transform gets the row context as its last - * argument, tracked per plugin so row memoization knows what it reads. - */ function applyRowPlugins< T extends Record, TProps, @@ -160,23 +177,6 @@ function applyRowPlugins< ); } -/** - * The row model the plugins admit: the first non-flat declaration, `custom` - * for a body transform that declares no model, otherwise `flat`. - */ -function resolveRowModel>( - plugins: ReadonlyArray>, -): TableRenderContext['rowModel'] { - const modifier = plugins.find( - plugin => - plugin.rowModel !== 'flat' && - (plugin.rowModel != null || - plugin.transformBodyRow != null || - plugin.transformBodyCell != null), - ); - return modifier == null ? 'flat' : (modifier.rowModel ?? 'custom'); -} - // ============================================================================= // Memoized Table Row Component // ============================================================================= @@ -212,13 +212,20 @@ interface TableRowProps> { textOverflow: 'wrap' | 'truncate'; RowComponent: React.ComponentType; CellComponent: React.ComponentType; - renderContext: TableRenderContext; /** * 1-based ARIA row index for this row's position in the full dataset. * `undefined` when the table hasn't opted into ARIA row indexing, in which * case no `aria-rowindex` is emitted (native table semantics). */ ariaRowIndex?: number; + contextIdentity: { + key: string | number | undefined; + identityStatus: TableRowContext['identityStatus']; + }; + renderContext: TableRenderContext; + rowHeight?: number; + onRowFocus?: (key: string | number, focusTarget?: HTMLElement) => void; + onRowBlur?: () => void; } /** @@ -235,21 +242,26 @@ function TableRowInner>({ textOverflow, RowComponent, CellComponent, - renderContext, ariaRowIndex, + contextIdentity, + renderContext, + rowHeight, + onRowFocus, + onRowBlur, }: TableRowProps): ReactElement { + // Only mounted rows build a row context. const context = useMemo( () => Object.freeze({ - key: rowKey, - identityStatus: 'valid', + key: contextIdentity.key, + identityStatus: contextIdentity.identityStatus, kind: renderContext.rowModel === 'flat' ? 'product' : 'unknown', logicalIndex: rowIndex, logicalRowCount: renderContext.logicalRowCount, headerRowCount: renderContext.headerRowCount, render: renderContext, }), - [rowKey, rowIndex, renderContext], + [contextIdentity, rowIndex, renderContext], ); // Build cells first const cells = columns.map((col, columnIndex) => { @@ -279,9 +291,14 @@ function TableRowInner>({ const isDefaultRenderer = !col.renderCell; let rawContent: ReactNode = null; if (!cellRenderProps.isContentSuppressed) { - rawContent = isDefaultRenderer - ? defaultCellRenderer(item, col.key) - : (col.renderCell?.(item) ?? null); + const renderLogicalPosition = + rowHeight == null ? undefined : getLogicalPositionRenderer(col); + rawContent = + renderLogicalPosition != null + ? renderLogicalPosition(context.logicalIndex) + : isDefaultRenderer + ? defaultCellRenderer(item, col.key) + : (col.renderCell?.(item) ?? null); } // In truncate mode, wrap default-rendered string content in @@ -331,53 +348,110 @@ function TableRowInner>({ rowIndex, ); + const rowHtml = rowRenderProps.htmlProps; const row = ( + {...rowHtml} + data-table-logical-index={rowHeight == null ? undefined : rowIndex} + data-table-final-row={ + rowHeight == null + ? undefined + : rowIndex === (context?.logicalRowCount ?? 0) - 1 + ? 'true' + : 'false' + } + onFocus={ + onRowFocus == null + ? rowHtml.onFocus + : event => { + rowHtml.onFocus?.(event); + if (context?.key != null) { + const view = event.currentTarget.ownerDocument.defaultView; + const focusTarget = + view != null && event.target instanceof view.HTMLElement + ? event.target + : event.currentTarget; + onRowFocus(context.key, focusTarget); + } + } + } + onBlur={ + onRowBlur == null + ? rowHtml.onBlur + : event => { + rowHtml.onBlur?.(event); + const leavesDocument = + event.relatedTarget == null && + !event.currentTarget.ownerDocument.hasFocus(); + if ( + !leavesDocument && + !event.currentTarget.contains(event.relatedTarget) + ) { + onRowBlur(); + } + } + } + xstyle={ + rowHeight == null + ? rowRenderProps.xstyle + : [...rowRenderProps.xstyle, styles.fixedRow(rowHeight)] + }> {rowRenderProps.children} ); - // afterRow: plugins (e.g. row expansion) can append a full-width detail - // panel `` after the row. Rendered as a sibling fragment. - if (rowRenderProps.afterRow) { - return ( - <> - {row} - {rowRenderProps.afterRow} - - ); - } - - return row; + // A detail panel must not change the parent of an existing row. + return ( + <> + {row} + {rowRenderProps.afterRow || null} + + ); } /** * Compares TableRowProps to determine if re-render is needed. * Shallow compares the item object and checks if columns/plugins references changed. * - * The row index reaches a row's output only through a plugin's - * `transformBodyRow`, or through a cell transform that reads the context's - * `logicalIndex`, so it is compared only for those plugins: a re-sort that - * moves rows then re-renders none of them unless a plugin can show the index - * (row numbering, conditional formatting). A changed row count re-renders - * rows only when a plugin has read a count. + * A windowed row and a transform that reads logical position need the current + * row index. Otherwise a re-sort moves keyed rows without rebuilding cells. */ function areRowPropsEqual>( prevProps: TableRowProps, nextProps: TableRowProps, ): boolean { + if ( + prevProps.contextIdentity.key !== nextProps.contextIdentity.key || + prevProps.contextIdentity.identityStatus !== + nextProps.contextIdentity.identityStatus || + (prevProps.renderContext !== nextProps.renderContext && + (prevProps.rowHeight != null || + nextProps.rowHeight != null || + prevProps.plugins.some(readsRowCount) || + prevProps.renderContext.mode !== nextProps.renderContext.mode || + prevProps.renderContext.rowModel !== nextProps.renderContext.rowModel || + prevProps.renderContext.headerRowCount !== + nextProps.renderContext.headerRowCount || + prevProps.renderContext.viewport !== + nextProps.renderContext.viewport)) || + prevProps.rowHeight !== nextProps.rowHeight || + prevProps.onRowFocus !== nextProps.onRowFocus || + prevProps.onRowBlur !== nextProps.onRowBlur + ) { + return false; + } if (prevProps.rowKey !== nextProps.rowKey) { return false; } if ( prevProps.rowIndex !== nextProps.rowIndex && - nextProps.plugins.some( - plugin => plugin.transformBodyRow != null || readsRowIndex(plugin), - ) + (prevProps.rowHeight != null || + nextProps.rowHeight != null || + nextProps.plugins.some( + plugin => plugin.transformBodyRow != null || readsRowIndex(plugin), + )) ) { return false; } @@ -460,7 +534,8 @@ function BaseTableInner>({ idKey, plugins: pluginsProp, children, - textOverflow = 'wrap', + textOverflow: textOverflowProp, + virtualization, scrollWrapper: ScrollWrapper, emptyState, rowIndexStart, @@ -475,6 +550,26 @@ function BaseTableInner>({ // Use stable empty array when no plugins provided const plugins = pluginsProp ?? (EMPTY_PLUGINS as TablePlugin[]); + // Admission is resolved before any section renders. + const runtime = useMemo(() => createTableRuntime(), []); + const admission = useMemo(() => resolveTableAdmission(plugins), [plugins]); + const mode = children ? 'children' : 'data'; + const usesCanonicalIdentity = virtualization != null; + const identityLength = data?.length ?? 0; + const cachedIdentity = useMemo( + () => + usesCanonicalIdentity && identityLength > 0 + ? resolveTableIdentity(data ?? [], idKey, true) + : [], + [data, identityLength, idKey, usesCanonicalIdentity], + ); + const identity = usesCanonicalIdentity + ? cachedIdentity + : resolveTableIdentity(data ?? [], idKey, false); + const keys = useMemo( + () => identity.map((row, index) => row.key ?? index), + [identity], + ); // ARIA row indexing. The row ordinal is an accessibility concern that is // independent of any visible index column: when the consumer opts in (by // passing rowIndexStart or rowCount), body rows carry `aria-rowindex` @@ -515,23 +610,93 @@ function BaseTableInner>({ resolvedColumnsRef.current = transformedColumns; } const resolvedColumns = resolvedColumnsRef.current; - - const mode = children ? 'children' : 'data'; - const rowModel = resolveRowModel(plugins); - const logicalRowCount = data?.length ?? 0; const headerRowCount = mode === 'data' && resolvedColumns.length > 0 ? 1 : 0; - const viewportRef = useRef(null); + const config = getTableVirtualizationConfig(virtualization); + const windowFallbackReason = useMemo(() => { + if (mode !== 'data') { + return 'windowing requires data mode'; + } + if (ScrollWrapper == null) { + return 'windowing requires the Table scroll wrapper'; + } + if (!isTableScrollWrapperOwned(ScrollWrapper)) { + return 'windowing requires the Table-owned scroll wrapper'; + } + if (admission.rowModel !== 'flat') { + return "structural body modifiers must declare rowModel: 'flat' to admit windowing"; + } + if (!identity.every(row => row.identityStatus === 'valid')) { + return 'explicit unique valid row identity is required'; + } + if (textOverflowProp === 'wrap') { + return 'explicit wrapped content is not fixed-height'; + } + if (rowIndexStart != null || rowCount != null) { + return 'legacy row offsets or counts conflict with windowed metadata'; + } + if (!resolvedColumns.every(isFixedHeightColumn)) { + return 'a custom cell renderer has no fixed-height admission'; + } + if ( + config == null || + !Number.isFinite(config.rowHeight) || + config.rowHeight <= 0 || + !Number.isFinite(config.viewportHeight) || + config.viewportHeight <= 0 + ) { + return 'row and viewport geometry must be positive finite CSS pixels'; + } + return undefined; + }, [ + mode, + ScrollWrapper, + admission.rowModel, + identity, + textOverflowProp, + rowIndexStart, + rowCount, + resolvedColumns, + config, + ]); + const windowAdmitted = windowFallbackReason === undefined; + useDevWarningPerMessage( + 'Table', + `Windowing disabled: ${windowFallbackReason}. Rendering all rows.`, + virtualization != null && windowFallbackReason != null, + ); + const logicalPositionColumns = useMemo( + () => + new Set( + resolvedColumns.flatMap((column, index) => + getLogicalPositionRenderer(column) == null ? [] : [index], + ), + ), + [resolvedColumns], + ); + const windowPlan = useTableWindow({ + capability: virtualization, + data: data ?? [], + keys, + isAdmitted: windowAdmitted, + logicalPositionColumns, + viewport: runtime.viewport, + body: runtime.body, + table: runtime.table, + geometry: runtime.geometry, + }); const renderContext = useMemo( () => Object.freeze({ mode, - rowModel, - logicalRowCount, + rowModel: admission.rowModel, + logicalRowCount: data?.length ?? 0, headerRowCount, - viewport: viewportRef, + viewport: runtime.viewport, }), - [mode, rowModel, logicalRowCount, headerRowCount], + [mode, admission, data?.length, headerRowCount, runtime], ); + const textOverflow = + textOverflowProp ?? (windowPlan.isWindowed ? 'truncate' : 'wrap'); // Resolve all column widths in a single pass — produces per-column // inline styles and the aggregate table min-width. @@ -690,8 +855,12 @@ function BaseTableInner>({ let tableElement: ReactNode = (
>({ {headerRowRenderProps.children} )} - + {hasData - ? data.map((item, rowIndex) => { - const rowKey = - idKey == null - ? rowIndex - : typeof idKey === 'function' - ? idKey(item) - : String(item[idKey]); - return ( - - key={rowKey} - item={item} - rowIndex={rowIndex} - rowKey={rowKey} - columns={resolvedColumns} - plugins={plugins} - textOverflow={textOverflow} - RowComponent={RowComponent} - CellComponent={CellComponent} - renderContext={renderContext} - ariaRowIndex={ - ariaRowIndexingEnabled - ? firstRowAriaIndex + rowIndex - : undefined - } - /> - ); + ? windowPlan.segments.flatMap(segment => { + if (segment.type === 'gap') { + return [ + + , + ]; + } + const rows: ReactNode[] = []; + for ( + let rowIndex = segment.start; + rowIndex < segment.end; + rowIndex++ + ) { + const item = data[rowIndex]; + const rowIdentity = identity[rowIndex]; + rows.push( + + key={rowIdentity.reactKey} + item={item} + rowIndex={rowIndex} + rowKey={rowIdentity.reactKey} + contextIdentity={rowIdentity} + renderContext={renderContext} + columns={resolvedColumns} + plugins={plugins} + textOverflow={textOverflow} + RowComponent={RowComponent} + CellComponent={CellComponent} + rowHeight={ + windowPlan.isWindowed ? config?.rowHeight : undefined + } + onRowFocus={ + windowPlan.isWindowed + ? windowPlan.onRowFocus + : undefined + } + onRowBlur={ + windowPlan.isWindowed + ? windowPlan.onRowBlur + : undefined + } + ariaRowIndex={ + windowPlan.isWindowed + ? headerRowCount + rowIndex + 1 + : ariaRowIndexingEnabled + ? firstRowAriaIndex + rowIndex + : undefined + } + />, + ); + } + return rows; }) : data != null && emptyState !== false && ( @@ -784,7 +990,7 @@ function BaseTableInner>({ ) : null; const scrollWrapperRef = useMergedRefs( - viewportRef, + runtime.setViewport, scrollWrapperRenderProps?.htmlProps.ref, ); if (ScrollWrapper && scrollWrapperRenderProps) { @@ -817,7 +1023,30 @@ function BaseTableInner>({ } } - return tableElement as ReactElement; + const parentAppearance = use(TableContext); + const effectiveAppearance = useMemo( + () => + parentAppearance == null ? null : {...parentAppearance, textOverflow}, + [parentAppearance, textOverflow], + ); + const runtimeValue = useMemo( + () => ({ + ...runtime, + viewportHeight: windowPlan.isWindowed + ? config?.viewportHeight + : undefined, + }), + [runtime, windowPlan.isWindowed, config?.viewportHeight], + ); + return ( + + {effectiveAppearance == null ? ( + tableElement + ) : ( + {tableElement} + )} + + ); } /** diff --git a/packages/core/src/Table/Table.doc.mjs b/packages/core/src/Table/Table.doc.mjs index 9d527d4fb9307..6ddd840dcaf0a 100644 --- a/packages/core/src/Table/Table.doc.mjs +++ b/packages/core/src/Table/Table.doc.mjs @@ -12,7 +12,7 @@ const anatomy = [ name: 'Scroll region', required: true, description: - 'Outer region that scrolls horizontally, enters the keyboard order, and contains overscroll only while the columns overflow.', + 'Outer region that scrolls horizontally when columns overflow. Fixed-height virtualization also enables block scrolling; the region enters keyboard order while either applicable axis overflows.', }, { name: 'Header section', @@ -197,7 +197,7 @@ export const docs = { name: 'idKey', type: '(keyof T & string) | ((item: T) => string | number)', description: - 'Row key for React reconciliation. Pass a property name string or a function. Falls back to row index if omitted.', + 'Canonical row identity: a property name projects valid strings and finite numbers to strings; a function retains string/number type. Optional legacy tables fall back to index. Virtualization requires explicit unique valid keys.', }, { name: 'density', @@ -238,6 +238,12 @@ export const docs = { "How body cell text behaves when it exceeds the column width. 'wrap' lets text wrap and the row grow taller; 'truncate' clips with an ellipsis (default-rendered cells show a tooltip on hover when truncated). Header cells always truncate.", default: "'wrap'", }, + { + name: 'virtualization', + type: 'TableVirtualizationCapability', + description: + 'Geometry-only capability from useTableRowsVirtualization({rowHeight, viewportHeight}), both positive finite CSS pixels. Pass complete flat data and an explicit idKey. Default text truncates; custom renderers, wrapping, structural plugins, incompatible offsets, invalid identity or unrepresentable geometry use full rendering. Logical row positions include the header.', + }, { name: 'plugins', type: 'Record>', diff --git a/packages/core/src/Table/Table.tsx b/packages/core/src/Table/Table.tsx index 2ddbbea1d8af8..194ce4f3b3ff3 100644 --- a/packages/core/src/Table/Table.tsx +++ b/packages/core/src/Table/Table.tsx @@ -4,7 +4,7 @@ /** * @file Table.tsx - * @input React, StyleX, BaseTable, theme tokens, types, components + * @input React, StyleX, BaseTable, the coordinated Table viewport, theme tokens and types * @output Exports Table component, TableProps, TableDensity, TableDividers types * @position Styled wrapper; the primary table API for consumers * @@ -18,6 +18,8 @@ */ import {use, useMemo, type ReactElement, type Ref} from 'react'; +import {TableRuntimeContext, registerTableScrollWrapper} from './tableRuntime'; +import {mergeRefs} from '../utils/mergeRefs'; import * as stylex from '@stylexjs/stylex'; import {borderVars, colorVars, focusVars} from '../theme/tokens.stylex'; import {focusOutlineStyles} from '../utils/focusOutline.stylex'; @@ -59,16 +61,9 @@ export type TableDividers = 'rows' | 'columns' | 'grid' | 'none'; export type TableTextOverflow = 'wrap' | 'truncate'; -/** - * Props for the styled Table component. - * Supports both data-driven mode and children mode with TableRow/Cell. - * - * @template T - The row data type - */ - -export interface TableProps> extends Omit< +interface TableAppearanceProps> extends Omit< BaseTableProps, - 'plugins' | 'components' + 'plugins' | 'components' | 'virtualization' > { /** Row density. @default 'balanced' */ density?: TableDensity; @@ -111,6 +106,19 @@ export interface TableProps> extends Omit< plugins?: Record>; } +/** + * Props for the styled Table component. + * Supports both data-driven mode and children mode with TableRow/Cell. + * + * @template T - The row data type + */ +export interface TableProps< + T extends Record, +> extends TableAppearanceProps { + /** Fixed-height opt-in. Requires data and explicit idKey; invalid combinations fall back with diagnostics. */ + virtualization?: BaseTableProps['virtualization']; +} + // ============================================================================= // StyleX Styles (table-level only; cell/row/header styles owned by components) // ============================================================================= @@ -123,6 +131,7 @@ const tableStyles = stylex.create({ }); const scrollWrapperStyles = stylex.create({ + viewport: (height: number) => ({height, maxHeight: height}), base: { overflowX: 'auto', WebkitOverflowScrolling: 'touch', @@ -209,23 +218,32 @@ function TableScrollWrapper({ labelledBy != null ? undefined : (tableName?.label ?? t('@astryx.table.label')); + const runtime = use(TableRuntimeContext); + const viewportHeight = runtime?.viewportHeight; + const hasBlockViewport = viewportHeight != null; const {getViewportProps, getContentProps, state} = useScrollableArea({ - axis: 'inline', + axis: hasBlockViewport ? 'both' : 'inline', keyboardAccess: {owner: 'content'}, overscroll: 'contain', }); const {ref, ...restHtmlProps} = htmlProps ?? {}; + const wrapperRef = useMemo( + () => mergeRefs(ref, runtime?.setViewport), + [ref, runtime?.setViewport], + ); const viewportProps = getViewportProps({ role: 'group', 'aria-label': label, // A plugin's explicit name stays authoritative (Table FR1). 'aria-labelledby': restHtmlProps['aria-label'] == null ? labelledBy : undefined, - ...(state.inline.isScrollable ? {tabIndex: 0} : {}), + ...(state.inline.isScrollable || state.block.isScrollable + ? {tabIndex: 0} + : {}), // Reads the corner its container publishes (scrollWrapperStyles). 'data-container-corner': '', ...restHtmlProps, - ref, + ref: wrapperRef, ...mergeProps( themeProps('table-scroll-wrapper'), stylex.props( @@ -235,11 +253,15 @@ function TableScrollWrapper({ // theme restyles through the focus-outline tokens. focusOutlineStyles.focusVisible, scrollWrapperStyles.focusRingInset, + hasBlockViewport && scrollWrapperStyles.viewport(viewportHeight), ...(pluginStyles ?? []), ), ), }); + if (hasBlockViewport) { + viewportProps.style = {...viewportProps.style, overscrollBehaviorY: 'auto'}; + } return (
()}> @@ -275,19 +297,24 @@ function buildTableStylePlugin< // Table Component // ============================================================================= +registerTableScrollWrapper(TableScrollWrapper); + function TableInner>({ density = 'balanced', dividers = 'rows', isStriped = false, hasHover = false, verticalAlign = 'middle', - textOverflow = 'wrap', + textOverflow: textOverflowProp, + virtualization, plugins: userPlugins, columns, data, ref, ...rest }: TableProps & {ref?: Ref}): ReactElement { + const textOverflow = + textOverflowProp ?? (virtualization == null ? 'wrap' : 'truncate'); // Table-level styling plugin (just adds font/color to
) const tablePlugin = useMemo(() => buildTableStylePlugin(), []); const basePlugins = useMemo(() => [tablePlugin], [tablePlugin]); @@ -321,7 +348,8 @@ function TableInner>({ data={data} columns={columns} plugins={mergedPlugins} - textOverflow={textOverflow} + textOverflow={textOverflowProp} + virtualization={virtualization} scrollWrapper={TableScrollWrapper} {...rest} /> diff --git a/packages/core/src/Table/TableCell.tsx b/packages/core/src/Table/TableCell.tsx index 4cd6021877910..fb4f3b8be00b3 100644 --- a/packages/core/src/Table/TableCell.tsx +++ b/packages/core/src/Table/TableCell.tsx @@ -159,7 +159,12 @@ const dividerRowStyles = stylex.create({ // Scoped to tableRowMarker so only the parent is checked — // without the scope, (also a :last-child) would match // and suppress borders on every row. - [stylex.when.ancestor(':last-child', tableRowMarker)]: '0', + [stylex.when.ancestor( + ':last-child:not([data-table-final-row="false"])', + tableRowMarker, + )]: '0', + [stylex.when.ancestor('[data-table-final-row="true"]', tableRowMarker)]: + '0', }, borderBottomStyle: 'solid', borderBottomColor: colorVars['--color-border'], diff --git a/packages/core/src/Table/TableHoverWindow.test.tsx b/packages/core/src/Table/TableHoverWindow.test.tsx new file mode 100644 index 0000000000000..addef4ddf7b1b --- /dev/null +++ b/packages/core/src/Table/TableHoverWindow.test.tsx @@ -0,0 +1,49 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +/** Virtual stripes retain the same hover motion on each logical parity. */ +import {cleanup, render} from '@testing-library/react'; +import {afterEach, describe, expect, it} from 'vitest'; +import {Table} from './Table'; +import {useTableRowsVirtualization} from './plugins/virtualization/useTableRowsVirtualization'; +const data = Array.from({length: 20}, (_, i) => ({ + id: String(i), + name: `Item ${i}`, +})); +const columns = [{key: 'name', header: 'Name'}]; +function Fixture() { + const virtualization = useTableRowsVirtualization({ + rowHeight: 56, + viewportHeight: 240, + }); + return ( + <> +
+
+ + ); +} +afterEach(cleanup); +describe('Table windowed hover parity', () => { + it('preserves each row background transition regardless of logical parity', () => { + const {container} = render(); + const tables = container.querySelectorAll('table'); + const base = getComputedStyle(tables[0].querySelector('tbody tr')!); + expect(base.transitionProperty).toBe('background-color'); + for (const row of tables[1].querySelectorAll( + 'tbody tr:not([aria-hidden])', + )) { + const style = getComputedStyle(row); + expect(style.transitionProperty).toBe(base.transitionProperty); + expect(style.transitionDuration).toBe(base.transitionDuration); + expect(style.transitionTimingFunction).toBe( + base.transitionTimingFunction, + ); + } + }); +}); diff --git a/packages/core/src/Table/TableLegacyIncrementalRender.test.tsx b/packages/core/src/Table/TableLegacyIncrementalRender.test.tsx new file mode 100644 index 0000000000000..1061898ef8ae9 --- /dev/null +++ b/packages/core/src/Table/TableLegacyIncrementalRender.test.tsx @@ -0,0 +1,273 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +/** Regression: legacy data-size changes must not repaint unchanged Table rows. */ +import {render, screen, cleanup} from '@testing-library/react'; +import {afterEach, describe, expect, it, vi} from 'vitest'; +import {Table} from './Table'; +import {useTableSelection} from './plugins/selection/useTableSelection'; +import {useTableStickyColumns} from './plugins/stickyColumns/useTableStickyColumns'; +import {useTableRowExpansion} from './plugins/rowExpansion/useTableRowExpansion'; +import {pixel} from './columnUtils'; +import type { + TableColumn, + BodyRowRenderProps, + BodyCellRenderProps, + TableRowContext, +} from './types'; +interface Item extends Record { + id: string; + name: string; +} +afterEach(cleanup); +describe('legacy Table incremental render cost', () => { + it.each(['expansion', 'custom-row', 'custom-cell'] as const)( + 'preserves append cost for legacy %s plugins that do not read context', + kind => { + const renderCell = vi.fn((item: Item) => item.name); + const columns: TableColumn[] = [ + {key: 'name', header: 'Name', renderCell}, + ]; + const items: Item[] = Array.from({length: 200}, (_, i) => ({ + id: String(i), + name: `Item ${i}`, + })); + const expandedKeys = new Set(); + const onToggle = () => {}; + const getRowKey = (item: Item) => item.id; + const renderExpanded = () => null; + const custom = + kind === 'custom-row' + ? {transformBodyRow: (props: BodyRowRenderProps) => props} + : { + transformBodyCell: (props: BodyCellRenderProps) => props, + }; + function Fixture({data}: {data: Item[]}) { + const expansion = useTableRowExpansion({ + expandedKeys, + onToggle, + getRowKey, + renderExpanded, + }); + return ( +
+ ); + } + const view = render(); + renderCell.mockClear(); + const appended = {id: '200', name: 'Item 200'}; + view.rerender(); + expect(renderCell.mock.calls).toEqual([[appended]]); + renderCell.mockClear(); + view.rerender(); + expect(renderCell).not.toHaveBeenCalled(); + }, + ); + it('tracks cell-level render totals without imposing count reads on other plugins', () => { + const totals: number[] = []; + const plugin = { + transformBodyCell( + props: BodyCellRenderProps, + _col: TableColumn, + _item: Item, + _index: number, + _columns: ReadonlyArray>, + context?: TableRowContext, + ) { + totals.push(context?.render.logicalRowCount ?? -1); + return props; + }, + }; + const columns: TableColumn[] = [{key: 'name', header: 'Name'}]; + const data = [{id: 'a', name: 'A'}]; + const view = render( +
, + ); + totals.length = 0; + view.rerender( +
, + ); + expect(totals).toEqual([2, 2]); + }); + it.each([true, false])( + 'keeps logical totals fresh for a custom transform (flat declared=%s)', + isFlat => { + const counts: number[] = []; + const plugin = { + rowModel: isFlat ? ('flat' as const) : undefined, + transformBodyRow( + props: BodyRowRenderProps, + _item: Item, + _index: number, + context?: TableRowContext, + ) { + counts.push(context?.logicalRowCount ?? -1); + return props; + }, + }; + const data = [{id: 'a', name: 'A'}]; + const columns: TableColumn[] = [{key: 'name', header: 'Name'}]; + const view = render( +
, + ); + counts.length = 0; + view.rerender( +
, + ); + expect(counts).toEqual([2, 2]); + }, + ); + it.each(['selection', 'sticky', 'combined'] as const)( + 'keeps existing %s rows unchanged on append and tail removal', + kind => { + const renderCell = vi.fn((item: Item) => item.name); + const columns: TableColumn[] = [ + {key: 'name', header: 'Name', renderCell, width: pixel(200)}, + ]; + const items: Item[] = Array.from({length: 200}, (_, i) => ({ + id: String(i), + name: `Item ${i}`, + })); + function Fixture({data}: {data: Item[]}) { + const selection = useTableSelection({ + getIsItemSelected: () => false, + onSelectItem: () => {}, + onSelectAll: () => {}, + getIsAllSelected: () => false, + getRowLabel: item => item.name, + }); + const sticky = useTableStickyColumns({startKeys: ['name']}); + return ( +
+ ); + } + const view = render(); + renderCell.mockClear(); + const appended = {id: '200', name: 'Item 200'}; + view.rerender(); + expect(renderCell.mock.calls).toEqual([[appended]]); + renderCell.mockClear(); + view.rerender(); + expect(renderCell).not.toHaveBeenCalled(); + }, + ); + it('renders only the appended item, and no preceding item when the tail is removed', () => { + const renderCell = vi.fn((item: Item) => item.name); + const columns: TableColumn[] = [ + {key: 'name', header: 'Name', renderCell}, + ]; + const items: Item[] = Array.from({length: 200}, (_, i) => ({ + id: String(i), + name: `Item ${i}`, + })); + const view = render(
); + renderCell.mockClear(); + const appended = {id: '200', name: 'Item 200'}; + view.rerender( +
, + ); + expect(renderCell.mock.calls).toEqual([[appended]]); + expect(screen.getByText('Item 200')).toBeInTheDocument(); + renderCell.mockClear(); + view.rerender(
); + expect(renderCell).not.toHaveBeenCalled(); + expect(screen.queryByText('Item 200')).not.toBeInTheDocument(); + }); + it('updates logical indices consumed by cells after a keyed re-sort', () => { + const data: Item[] = [ + {id: 'a', name: 'A'}, + {id: 'b', name: 'B'}, + ]; + const columns: TableColumn[] = [{key: 'name', header: 'Name'}]; + const plugin = { + rowModel: 'flat' as const, + transformBodyCell( + props: BodyCellRenderProps, + _column: TableColumn, + _item: Item, + _index: number, + _columns: ReadonlyArray>, + context?: TableRowContext, + ) { + return { + ...props, + htmlProps: { + ...props.htmlProps, + 'data-logical-index': context?.logicalIndex, + }, + }; + }, + }; + const view = render( +
, + ); + expect(screen.getByText('A').closest('td')).toHaveAttribute( + 'data-logical-index', + '0', + ); + view.rerender( +
, + ); + expect(screen.getByText('A').closest('td')).toHaveAttribute( + 'data-logical-index', + '1', + ); + expect(screen.getByText('B').closest('td')).toHaveAttribute( + 'data-logical-index', + '0', + ); + }); + it('moves keyed rows without repainting when cells do not read logical indices', () => { + const renderCell = vi.fn((item: Item) => item.name); + const columns: TableColumn[] = [ + {key: 'name', header: 'Name', renderCell}, + ]; + const data: Item[] = [ + {id: 'a', name: 'A'}, + {id: 'b', name: 'B'}, + ]; + const view = render(
); + renderCell.mockClear(); + view.rerender( +
, + ); + expect(renderCell).not.toHaveBeenCalled(); + expect(screen.getAllByRole('cell').map(cell => cell.textContent)).toEqual([ + 'B', + 'A', + ]); + }); +}); diff --git a/packages/core/src/Table/TableParentIntegrationRegression.test.tsx b/packages/core/src/Table/TableParentIntegrationRegression.test.tsx new file mode 100644 index 0000000000000..0aa2ee48f612b --- /dev/null +++ b/packages/core/src/Table/TableParentIntegrationRegression.test.tsx @@ -0,0 +1,121 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +import {render, screen, cleanup, fireEvent} from '@testing-library/react'; +import {afterEach, describe, it, expect, vi} from 'vitest'; +import {publishScrollGeometry} from '../hooks/scrollGeometrySubscriptions'; +import {Table} from './Table'; +import {TableBody} from './TableBody'; +import {TableCell} from './TableCell'; +import {TableRow} from './TableRow'; +import type {TablePlugin} from './types'; +import {useTableRowsVirtualization} from './plugins/virtualization/useTableRowsVirtualization'; +const columns = [{key: 'name', header: 'Name'}]; +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); +describe('Table parent compatibility regressions', () => { + it('does not read windowing rectangles when an ordinary Table scrolls', () => { + vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(240); + vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(240); + vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockReturnValue( + 1000, + ); + vi.spyOn(HTMLElement.prototype, 'scrollWidth', 'get').mockReturnValue(240); + const {container} = render( +
, + ); + const viewport = screen.getByRole('group'); + const body = container.querySelector('tbody'); + expect(body).not.toBeNull(); + const viewportRead = vi.spyOn(viewport, 'getBoundingClientRect'); + const bodyRead = vi.spyOn( + body as HTMLTableSectionElement, + 'getBoundingClientRect', + ); + fireEvent.scroll(viewport); + publishScrollGeometry(viewport, true); + expect(viewportRead).not.toHaveBeenCalled(); + expect(bodyRead).not.toHaveBeenCalled(); + }); + it('retains legacy key resolution when a caller appends in place', () => { + const data = [{id: 'a', name: 'A'}]; + const {rerender} = render( +
, + ); + data.push({id: 'b', name: 'B'}); + rerender(
); + expect(screen.getByText('B')).toBeInTheDocument(); + expect(screen.getAllByRole('row')).toHaveLength(3); + }); + it('refreshes identity and stays rendered when windowed data is appended in place', () => { + const data = Array.from({length: 20}, (_, i) => ({ + id: String(i), + name: `Item ${i}`, + })); + function Fixture() { + const virtualization = useTableRowsVirtualization({ + rowHeight: 56, + viewportHeight: 240, + }); + return ( +
+ ); + } + const view = render(); + data.push({id: '20', name: 'Appended item'}); + view.rerender(); + expect(screen.getByRole('table')).toHaveAttribute('aria-rowcount', '22'); + expect( + view.container.querySelectorAll('tbody > tr:not([aria-hidden])').length, + ).toBeLessThan(21); + }); + it('uses actual fallback overflow rather than requested virtualization intent', () => { + function Fixture() { + const virtualization = useTableRowsVirtualization({ + rowHeight: 56, + viewportHeight: 240, + }); + return ( +
item.name}]} + idKey="id" + virtualization={virtualization} + /> + ); + } + const {container} = render(); + expect(container.querySelector('td')?.className).toContain('wrapStyles'); + expect(container.querySelector('td')?.className).not.toContain( + 'overflowStyles', + ); + }); + it('reports no header row to scroll-wrapper plugins in children mode', () => { + const headerRowCounts: number[] = []; + const probe: TablePlugin> = { + transformScrollWrapper(props, context) { + if (context) { + headerRowCounts.push(context.headerRowCount); + } + return props; + }, + }; + render( +
+ + + A + + +
, + ); + expect(screen.queryAllByRole('columnheader')).toHaveLength(0); + expect(headerRowCounts.length).toBeGreaterThan(0); + expect(new Set(headerRowCounts)).toEqual(new Set([0])); + }); +}); diff --git a/packages/core/src/Table/TableProps.compatibility.ts b/packages/core/src/Table/TableProps.compatibility.ts new file mode 100644 index 0000000000000..4b8161b544fdf --- /dev/null +++ b/packages/core/src/Table/TableProps.compatibility.ts @@ -0,0 +1,15 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +/** Compile-only coverage for the released interface-extension surface. */ +import type {TableProps} from './Table'; +interface Item extends Record { + id: string; + name: string; +} +export interface ExtendedTableProps extends TableProps { + testExtension?: string; +} +export const extendedProps: ExtendedTableProps = { + data: [{id: 'a', name: 'A'}], + idKey: 'id', + testExtension: 'kept', +}; diff --git a/packages/core/src/Table/TableRow.tsx b/packages/core/src/Table/TableRow.tsx index cc48f98c42115..019a649bfb0f0 100644 --- a/packages/core/src/Table/TableRow.tsx +++ b/packages/core/src/Table/TableRow.tsx @@ -54,6 +54,30 @@ export interface TableRowProps extends BaseProps { */ const NOT_PANEL_ROW = ':nth-child(even of :not([data-expansion-panel]))'; +const logicalStripedRowStyles = stylex.create({ + row: { + backgroundColor: colorVars['--color-background-muted'], + '--table-row-overlay': colorVars['--color-background-muted'], + }, + hover: { + backgroundColor: { + default: colorVars['--color-background-muted'], + ':hover:where(:not(:disabled,[aria-disabled="true"]))': { + '@media (hover: hover)': colorVars['--color-overlay-hover'], + }, + }, + '--table-row-overlay': { + default: colorVars['--color-background-muted'], + ':hover:where(:not(:disabled,[aria-disabled="true"]))': { + '@media (hover: hover)': colorVars['--color-overlay-hover'], + }, + }, + transitionProperty: 'background-color', + transitionDuration: durationVars['--duration-fast'], + transitionTimingFunction: easeVars['--ease-standard'], + }, +}); + const stripedRowStyles = stylex.create({ row: { backgroundColor: { @@ -171,7 +195,20 @@ export function TableRow({ // pick up the hover highlight (or striping) even when hasHover/isStriped. if (!isHeaderRow) { // Handle striped + hover combination to avoid backgroundColor conflicts - if (ctx.isStriped && ctx.hasHover) { + const logicalIndex = (props as Record)[ + 'data-table-logical-index' + ]; + if (logicalIndex != null) { + if (ctx.isStriped && Number(logicalIndex) % 2 === 1) { + rowStyles.push( + ctx.hasHover + ? logicalStripedRowStyles.hover + : logicalStripedRowStyles.row, + ); + } else if (ctx.hasHover) { + rowStyles.push(hoverRowStyles.row); + } + } else if (ctx.isStriped && ctx.hasHover) { rowStyles.push(stripedHoverRowStyles.row); } else if (ctx.isStriped) { rowStyles.push(stripedRowStyles.row); diff --git a/packages/core/src/Table/TableWindowFallback.test.tsx b/packages/core/src/Table/TableWindowFallback.test.tsx new file mode 100644 index 0000000000000..ff8a0cc532132 --- /dev/null +++ b/packages/core/src/Table/TableWindowFallback.test.tsx @@ -0,0 +1,246 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +/** Development fallback diagnostics through the public Table windowing surface. */ +import {render, cleanup, act, screen} from '@testing-library/react'; +import {useTableSelection} from './plugins/selection/useTableSelection'; +import {useTableRowStatus} from './plugins/rowStatus/useTableRowStatus'; +import {afterEach, describe, expect, it, vi} from 'vitest'; +import {Table} from './Table'; +import {useTableRowsVirtualization} from './plugins/virtualization/useTableRowsVirtualization'; +import type {TableColumn, TablePlugin, BaseTableProps} from './types'; +interface Item extends Record { + id: string; + name: string; +} +const data: Item[] = Array.from({length: 50}, (_, i) => ({ + id: String(i), + name: `Item ${i}`, +})); +const columns: TableColumn[] = [{key: 'name', header: 'Name'}]; +const bodyModifier: TablePlugin = {transformBodyRow: props => props}; +function Fixture({reason}: {reason: string}) { + const virtualization = useTableRowsVirtualization({ + rowHeight: reason === 'geometry' ? 0 : 56, + viewportHeight: 240, + }); + return ( + item.name}] + : columns + } + idKey="id" + virtualization={virtualization} + textOverflow={reason === 'wrap' ? 'wrap' : undefined} + rowIndexStart={reason === 'offset' ? 2 : undefined} + rowCount={reason === 'count' ? 500 : undefined} + plugins={reason === 'model' ? {modifier: bodyModifier} : undefined} + /> + ); +} +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); +describe('Table windowing admission diagnostics', () => { + it('keeps unadmitted row-status composition fully rendered with its accessible markers', () => { + function StatusFixture() { + const virtualization = useTableRowsVirtualization({ + rowHeight: 56, + viewportHeight: 240, + }); + const rowStatus = useTableRowStatus({ + getStatus: () => ({status: 'success', label: 'Ready'}), + }); + return ( +
+ ); + } + const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const view = render(); + expect(view.container.querySelectorAll('tbody > tr')).toHaveLength( + data.length, + ); + expect(screen.getAllByRole('img', {name: 'Ready'})).toHaveLength( + data.length, + ); + expect( + view.container.querySelector('[data-table-logical-index]'), + ).toBeNull(); + expect(warning).toHaveBeenCalledTimes(1); + view.rerender(); + expect(warning).toHaveBeenCalledTimes(1); + }); + it('renders fully with one diagnostic when a caller replaces the owned scroll wrapper', () => { + const CallerWrapper: NonNullable['scrollWrapper']> = ({ + children, + htmlProps, + }) => ( +
+ {children} +
+ ); + function CallerFixture() { + const virtualization = useTableRowsVirtualization({ + rowHeight: 56, + viewportHeight: 240, + }); + return ( +
+ ); + } + const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const view = render(); + expect(view.container.querySelectorAll('tbody > tr')).toHaveLength( + data.length, + ); + expect( + view.container.querySelector('[data-table-logical-index]'), + ).toBeNull(); + expect(view.container.querySelector('[data-caller-wrapper]')).toHaveStyle({ + height: '240px', + overflow: 'auto', + }); + expect(warning).toHaveBeenCalledTimes(1); + expect(warning.mock.calls[0].join(' ')).toContain( + 'Table-owned scroll wrapper', + ); + view.rerender(); + expect(warning).toHaveBeenCalledTimes(1); + }); + + it('keeps a caller scroll wrapper unchanged without virtualization', () => { + const CallerWrapper: NonNullable['scrollWrapper']> = ({ + children, + htmlProps, + }) => ( +
+ {children} +
+ ); + const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const view = render( +
, + ); + expect(view.container.querySelectorAll('tbody > tr')).toHaveLength( + data.length, + ); + expect(view.container.querySelector('[data-caller-wrapper]')).toHaveStyle({ + height: '240px', + overflow: 'auto', + }); + expect(warning).not.toHaveBeenCalled(); + }); + it('preserves the focused selection control when the same keyed row falls back', () => { + function FocusFixture({fallback}: {fallback: boolean}) { + const virtualization = useTableRowsVirtualization({ + rowHeight: 56, + viewportHeight: 240, + }); + const selection = useTableSelection({ + getIsItemSelected: () => false, + onSelectItem() {}, + onSelectAll() {}, + getIsAllSelected: () => false, + getRowLabel: (item: Item) => item.name, + }); + return ( +
+ ); + } + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const view = render(); + const control = screen.getByRole('checkbox', {name: 'Select Item 0'}); + act(() => control.focus()); + expect(document.activeElement).toBe(control); + view.rerender(); + expect(control.isConnected).toBe(true); + expect(screen.getByRole('checkbox', {name: 'Select Item 0'})).toBe(control); + expect(document.activeElement).toBe(control); + }); + it.each(['renderer', 'wrap', 'offset', 'count', 'model', 'geometry'])( + 'explains %s full-render fallback once across rerenders', + reason => { + const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const view = render(); + expect(view.container.querySelectorAll('tbody>tr')).toHaveLength(50); + expect(warning).toHaveBeenCalledTimes(1); + expect(warning.mock.calls[0].join(' ')).toContain('Windowing disabled:'); + view.rerender(); + expect(warning).toHaveBeenCalledTimes(1); + }, + ); + it('reports invalid identity once without a duplicate error for the same fallback', () => { + const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const error = vi.spyOn(console, 'error').mockImplementation(() => {}); + const duplicateData = [ + {id: 'a', name: 'A'}, + {id: 'a', name: 'B'}, + ]; + function DuplicateFixture() { + const virtualization = useTableRowsVirtualization({ + rowHeight: 56, + viewportHeight: 240, + }); + return ( +
+ ); + } + const view = render(); + view.rerender(); + expect(warning).toHaveBeenCalledTimes(1); + expect(warning.mock.calls[0].join(' ')).toContain( + 'explicit unique valid row identity', + ); + expect(error).not.toHaveBeenCalled(); + expect(view.container.querySelectorAll('tbody > tr')).toHaveLength(2); + }); + it('keeps each fallback reason observable once across reason changes', () => { + const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const view = render(); + view.rerender(); + view.rerender(); + expect(warning).toHaveBeenCalledTimes(2); + }); + it('does not warn for valid bounded windowing', () => { + const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}); + render(); + expect(warning).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.ts index 1e89ef45a0094..3a18ebbebe748 100644 --- a/packages/core/src/Table/index.ts +++ b/packages/core/src/Table/index.ts @@ -28,6 +28,11 @@ export interface TableSemanticRowStatus { } export {Table} from './Table'; +export {useTableRowsVirtualization} from './plugins/virtualization'; +export type { + UseTableRowsVirtualizationConfig, + TableVirtualizationCapability, +} from './plugins/virtualization'; export {TableRow} from './TableRow'; export {TableCell} from './TableCell'; export {TableHeaderCell} from './TableHeaderCell'; diff --git a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx index d7d7a7bb08f55..46fcacab530f7 100644 --- a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx +++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx @@ -1,7 +1,7 @@ // Copyright (c) Meta Platforms, Inc. and affiliates. import {describe, it, expect, vi, beforeEach} from 'vitest'; -import {render, screen, fireEvent} from '@testing-library/react'; +import {render, screen, fireEvent, act} from '@testing-library/react'; import {useState} from 'react'; import {Table} from '../../Table'; import type {TableColumn} from '../../types'; @@ -181,6 +181,21 @@ describe('useTableRowExpansion (detail panel)', () => { ).toHaveAttribute('aria-expanded', 'true'); }, ); + it('retains the original focused chevron and row across expansion and collapse', () => { + render(); + const trigger = screen.getAllByRole('button', {name: /expand row/i})[1]; + const row = trigger.closest('tr'); + act(() => trigger.focus()); + fireEvent.click(trigger); + expect(row?.isConnected).toBe(true); + expect(trigger.isConnected).toBe(true); + expect(screen.getByRole('button', {name: /collapse row/i})).toBe(trigger); + expect(document.activeElement).toBe(trigger); + fireEvent.click(trigger); + expect(trigger.closest('tr')).toBe(row); + expect(document.activeElement).toBe(trigger); + expect(screen.queryByTestId('panel')).not.toBeInTheDocument(); + }); it('renders an "Expand row" chevron button for every expandable row', () => { render(); expect(screen.getAllByRole('button', {name: /expand row/i})).toHaveLength( diff --git a/packages/core/src/Table/plugins/virtualization/useTableRowsVirtualization.test.tsx b/packages/core/src/Table/plugins/virtualization/useTableRowsVirtualization.test.tsx index 821b94d48aa67..215a93bbcaa0d 100644 --- a/packages/core/src/Table/plugins/virtualization/useTableRowsVirtualization.test.tsx +++ b/packages/core/src/Table/plugins/virtualization/useTableRowsVirtualization.test.tsx @@ -2,18 +2,62 @@ /** * @file useTableRowsVirtualization.test.tsx - * @input Public capability hook - * @output Capability identity and immutability tests - * @position Colocated Table virtualization capability coverage + * @input Public capability and actual Table + * @output Capability identity, bounded pre-cell rendering, SSR and fallback tests + * @position Colocated Table virtualization runtime coverage */ -import {describe, it, expect} from 'vitest'; -import {renderHook} from '@testing-library/react'; +import {describe, it, expect, vi} from 'vitest'; +import {cleanup, render, renderHook, screen} from '@testing-library/react'; +import {renderToStaticMarkup} from 'react-dom/server'; +import * as TableApi from '@astryxdesign/core/Table'; +import {Table} from '../../Table'; +import type {TableColumn} from '../../types'; import { getTableVirtualizationConfig, useTableRowsVirtualization, } from './useTableRowsVirtualization'; +interface Item extends Record { + id: string; + label: string; +} +const columns: TableColumn[] = [{key: 'label', header: 'Label'}]; +const data: Item[] = Array.from({length: 100}, (_, i) => ({ + id: `row-${i}`, + label: `Item ${i}`, +})); +function Fixture({ + items = data, + rowHeight = 48, + viewportHeight = 240, + tableColumns = columns, +}: { + items?: Item[]; + rowHeight?: number; + viewportHeight?: number; + tableColumns?: TableColumn[]; +}) { + const virtualization = useTableRowsVirtualization({ + rowHeight, + viewportHeight, + }); + return ( +
+ ); +} + describe('Table virtualization capability', () => { + it('exports only the row-specific virtualization hook name', () => { + expect(typeof Reflect.get(TableApi, 'useTableRowsVirtualization')).toBe( + 'function', + ); + expect('useTableVirtualization' in TableApi).toBe(false); + }); it('is immutable geometry intent with stable identity and no public payload or knobs', () => { const {result, rerender} = renderHook( ({rowHeight, viewportHeight}) => @@ -37,3 +81,145 @@ describe('Table virtualization capability', () => { expect(result.current).not.toBe(original); }); }); + +describe('actual Table virtualization', () => { + it('plans before cell construction at 100k and keeps native rows plus truthful metadata', () => { + const readCell = vi.fn(); + const items: Item[] = Array.from({length: 100000}, (_, i) => ({ + id: `id-${i}`, + get label() { + readCell(i); + return `Value ${i}`; + }, + })); + const {container} = render(); + const table = screen.getByRole('table'); + expect(table).toHaveAttribute('aria-rowcount', '100001'); + const bodyRows = Array.from( + container.querySelectorAll('tbody > tr'), + ).filter(row => row.getAttribute('aria-hidden') !== 'true'); + expect(bodyRows).toHaveLength(9); + expect(bodyRows[0]).toHaveAttribute('aria-rowindex', '2'); + expect(bodyRows[8]).toHaveAttribute('aria-rowindex', '10'); + expect(readCell.mock.calls.every(([index]) => index < 9)).toBe(true); + expect(readCell).toHaveBeenCalled(); + const gap = container.querySelector('tbody > tr[aria-hidden="true"]'); + expect(gap).not.toBeNull(); + expect(gap?.firstElementChild?.tagName).toBe('TD'); + expect(gap?.firstElementChild).toHaveAttribute('colspan', '1'); + expect(gap?.querySelector('button,input,a')).toBeNull(); + cleanup(); + }); + it('uses the same bounded server seed and first client output, never a full intermediate body', () => { + const html = renderToStaticMarkup(); + const server = document.createElement('div'); + server.innerHTML = html; + const serverRows = Array.from(server.querySelectorAll('tbody > tr')).filter( + row => row.getAttribute('aria-hidden') !== 'true', + ); + expect(serverRows).toHaveLength(9); + const {container} = render(); + const clientRows = Array.from( + container.querySelectorAll('tbody > tr'), + ).filter(row => row.getAttribute('aria-hidden') !== 'true'); + expect(clientRows.map(row => row.getAttribute('aria-rowindex'))).toEqual( + serverRows.map(row => row.getAttribute('aria-rowindex')), + ); + cleanup(); + }); + it('falls back before rendering unsupported custom content or duplicate identity', () => { + const renderCell = vi.fn((item: Item) => {item.label}); + const {container} = render( + , + ); + expect(renderCell).toHaveBeenCalledTimes(100); + expect( + container.querySelector('tbody > tr[aria-hidden="true"]'), + ).toBeNull(); + cleanup(); + const duplicates = data.map(item => ({...item, id: 'same'})); + const duplicateResult = render(); + expect( + duplicateResult.container.querySelectorAll('tbody > tr'), + ).toHaveLength(100); + expect( + duplicateResult.container.querySelector('table'), + ).not.toHaveAttribute('aria-rowcount'); + cleanup(); + }); + it('keeps typed keys distinct from an idKey function and falls back for projected duplicates or null ids', () => { + interface Loose extends Record { + id: unknown; + label: string; + } + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + function LooseTable({ + items, + idKey, + }: { + items: Loose[]; + idKey: 'id' | ((item: Loose) => string | number); + }) { + const virtualization = useTableRowsVirtualization({ + rowHeight: 48, + viewportHeight: 240, + }); + return ( +
+ ); + } + const rendered = (container: HTMLElement) => + container.querySelectorAll('tbody > tr:not([aria-hidden="true"])').length; + const typed: Loose[] = data.map((item, index) => ({ + label: item.label, + id: index === 1 ? '0' : index, + })); + // A function keeps 0 and '0' as different keys, so the table windows. + const fromFunction = render( + item.id as string | number} />, + ); + expect(rendered(fromFunction.container)).toBeLessThan(100); + expect(fromFunction.container.querySelector('table')).toHaveAttribute( + 'aria-rowcount', + '101', + ); + cleanup(); + // A property name projects both to '0', a duplicate, so the table falls back. + const fromProperty = render(); + expect(rendered(fromProperty.container)).toBe(100); + cleanup(); + const withNull = typed.map((item, index) => + index === 5 ? {...item, id: null} : {...item, id: `row-${index}`}, + ); + const fromNull = render(); + expect(rendered(fromNull.container)).toBe(100); + cleanup(); + expect(warn).toHaveBeenCalledWith( + expect.stringContaining('explicit unique valid row identity'), + ); + warn.mockRestore(); + }); + it('preserves legacy full rendering and empty-state semantics', () => { + const {container} = render( +
, + ); + expect(container.querySelectorAll('tbody > tr')).toHaveLength(100); + expect(container.querySelector('table')).not.toHaveAttribute( + 'aria-rowcount', + ); + cleanup(); + const empty = render(); + expect(empty.container.querySelector('table')).not.toHaveAttribute( + 'aria-rowcount', + ); + expect( + empty.container.querySelector('tbody > tr[aria-hidden="true"]'), + ).toBeNull(); + cleanup(); + }); +}); diff --git a/packages/core/src/Table/tableColumnAdmission.ts b/packages/core/src/Table/tableColumnAdmission.ts new file mode 100644 index 0000000000000..0ef35a0b805f1 --- /dev/null +++ b/packages/core/src/Table/tableColumnAdmission.ts @@ -0,0 +1,36 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +/** + * @file Private fixed-height column admission. + * @input First-party columns whose structural renderer is owned and bounded. + * @output Identity-based admission without a new caller assertion prop. + * @position Shared Table protocol, with actual pitch validated after mount. + */ +import type {ReactNode} from 'react'; +import type {TableColumn} from './types'; +const heightSafe = new WeakMap(); +const logicalRenderers = new WeakMap< + object, + (logicalIndex: number) => ReactNode +>(); +/** Admits a first-party column to fixed-height windowing. */ +export function registerFixedHeightColumn>( + column: TableColumn, + isCompatible = true, + renderLogicalPosition?: (logicalIndex: number) => ReactNode, +): void { + heightSafe.set(column, isCompatible); + if (renderLogicalPosition != null) { + logicalRenderers.set(column, renderLogicalPosition); + } +} + +export function getLogicalPositionRenderer>( + column: TableColumn, +): ((logicalIndex: number) => ReactNode) | undefined { + return logicalRenderers.get(column); +} +export function isFixedHeightColumn>( + column: TableColumn, +): boolean { + return column.renderCell == null || heightSafe.get(column) === true; +} diff --git a/packages/core/src/Table/tableIdentity.ts b/packages/core/src/Table/tableIdentity.ts new file mode 100644 index 0000000000000..1214a7c7f5000 --- /dev/null +++ b/packages/core/src/Table/tableIdentity.ts @@ -0,0 +1,89 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +/** + * @file Table canonical identity and opt-in admission. + * @input Complete logical data, idKey and declared plugin capabilities. + * @output Type-preserving row identities and order-independent admission. + * @position Private parent protocol; never a plugin-specific extractor. + */ +import type {TablePlugin, TableRowContext} from './types'; + +export interface RowIdentity { + key: string | number | undefined; + reactKey: string | number; + identityStatus: TableRowContext['identityStatus']; +} + +export function resolveTableIdentity>( + data: ReadonlyArray, + idKey: (keyof T & string) | ((item: T) => string | number) | undefined, + usesCanonicalIdentity: boolean, +): RowIdentity[] { + const counts = new Map(); + const rows = data.map((item, index): RowIdentity => { + if (!usesCanonicalIdentity) { + const key = + idKey == null + ? index + : typeof idKey === 'function' + ? idKey(item) + : String(item[idKey]); + return {key, reactKey: key, identityStatus: 'valid'}; + } + if (idKey == null) { + return { + key: undefined, + reactKey: `invalid:${index}`, + identityStatus: 'missing', + }; + } + let raw: unknown; + try { + raw = typeof idKey === 'function' ? idKey(item) : item[idKey]; + } catch { + return { + key: undefined, + reactKey: `invalid:${index}`, + identityStatus: 'invalid', + }; + } + if ( + typeof raw !== 'string' && + (typeof raw !== 'number' || !Number.isFinite(raw)) + ) { + return { + key: undefined, + reactKey: `invalid:${index}`, + identityStatus: 'invalid', + }; + } + const key = typeof idKey === 'function' ? raw : String(raw); + counts.set(key, (counts.get(key) ?? 0) + 1); + return { + key, + reactKey: `${typeof key === 'number' ? 'n' : 's'}:${key}`, + identityStatus: 'valid', + }; + }); + if (!usesCanonicalIdentity) { + return rows; + } + return rows.map((row, index) => + row.key != null && (counts.get(row.key) ?? 0) > 1 + ? {...row, identityStatus: 'duplicate', reactKey: `duplicate:${index}`} + : row, + ); +} + +export function resolveTableAdmission>( + plugins: ReadonlyArray>, +) { + const modifier = plugins.find( + plugin => + plugin.rowModel !== 'flat' && + (plugin.rowModel != null || + plugin.transformBodyRow != null || + plugin.transformBodyCell != null), + ); + const rowModel = modifier?.rowModel ?? (modifier ? 'custom' : 'flat'); + return {rowModel}; +} diff --git a/packages/core/src/Table/types.ts b/packages/core/src/Table/types.ts index cfc5a0cb45e50..a85f1da6c568c 100644 --- a/packages/core/src/Table/types.ts +++ b/packages/core/src/Table/types.ts @@ -22,6 +22,7 @@ import type { } from 'react'; import type {StyleXStyles} from '../theme/types'; import type {BaseProps} from '../BaseProps'; +import type {TableVirtualizationCapability} from './plugins/virtualization/useTableRowsVirtualization'; import type {TableFilterFieldRef} from './plugins/filtering/useTableFiltering'; // ============================================================================= @@ -616,6 +617,8 @@ export interface BaseTableProps< T extends Record, > extends BaseProps { ref?: React.Ref; + /** Geometry-only, fixed-height capability; Styled Table owns its coordinated viewport. */ + virtualization?: TableVirtualizationCapability; /** Array of data items to render as rows */ data?: T[]; /** Column definitions. If omitted, auto-generated from data keys. */ diff --git a/packages/core/src/Table/useTableRowsVirtualization.doc.mjs b/packages/core/src/Table/useTableRowsVirtualization.doc.mjs new file mode 100644 index 0000000000000..1fc7ef60ac2d5 --- /dev/null +++ b/packages/core/src/Table/useTableRowsVirtualization.doc.mjs @@ -0,0 +1,38 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */ +export const docs = { + name: 'useTableRowsVirtualization', + subComponentOf: 'Table', + displayName: 'useTableRowsVirtualization', + description: + 'Returns an opaque capability for fixed-height flat-row Table windowing. Pass the capability to Table.virtualization and keep the complete data, columns, explicit stable idKey and plugins on Table. Sizes are positive finite CSS pixels. Supported rows use single-line content; explicit wrapping, arbitrary custom renderers, non-flat rows or invalid identity use ordinary full rendering. Windowing uses the Table-owned scroll wrapper; a caller-provided scrollWrapper takes diagnostic full-render fallback. Mounted rows retain native table semantics and full-table positions; unmounted rows are not promised screen-reader discovery.', + props: [ + { + name: 'rowHeight', + type: 'number', + required: true, + description: + 'Total body-row pitch in CSS pixels, including existing density padding and collapsed borders. Must fit text and supported controls without reducing their size.', + }, + { + name: 'viewportHeight', + type: 'number', + required: true, + description: + 'Bounded Table-owned viewport height in CSS pixels. Table accounts for its headers and chrome.', + }, + ], +}; + +/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */ +export const docsDense = { + description: + 'Geometry-only fixed-height flat-row opt-in for Table.virtualization. Keep full data and stable idKey on Table. Positive finite CSS-pixel sizes; unsupported content, geometry, identity or a caller scrollWrapper falls back to full rendering. Native mounted-row semantics, not discovery of unmounted rows.', + propDescriptions: { + rowHeight: + 'Total body-row pitch including density padding and borders; text and supported controls must fit.', + viewportHeight: + 'Bounded Table-owned viewport height; headers and chrome are accounted for by Table.', + }, +};