Skip to content

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

TypeScript

feat(Table): window tables that use selection and row index (#10658)

Humberto Virtudes90ebe00a2d6b
diff --git a/.changeset/table-windowing-selection-row-index.md b/.changeset/table-windowing-selection-row-index.md
new file mode 100644
index 0000000000..ff1238e1a1
--- /dev/null
+++ b/.changeset/table-windowing-selection-row-index.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Windowed tables stay windowed with row selection and row numbers. A windowed row-number column widens to fit its last number before that row mounts, at the table's font and density, and pinned columns after it move with it.
+
+@humbertovirtudes
diff --git a/packages/core/src/Table/BaseTable.tsx b/packages/core/src/Table/BaseTable.tsx
index 0c6f453991..f46d451c5d 100644
--- a/packages/core/src/Table/BaseTable.tsx
+++ b/packages/core/src/Table/BaseTable.tsx
@@ -35,7 +35,9 @@ import {TableContext} from './TableContext';
import {use} from 'react';
import {
isFixedHeightColumn,
+ getLogicalPositionExtraVar,
getLogicalPositionRenderer,
+ withLogicalPositionWidths,
} from './tableColumnAdmission';
import {isRenderable} from '../utils/isRenderable';
import * as stylex from '@stylexjs/stylex';
@@ -59,6 +61,7 @@ import type {
import {
generateColumns,
defaultCellRenderer,
+ resolveColumnFloorWidths,
resolveColumnWidths,
resolveTableMinWidth,
} from './columnUtils';
@@ -700,7 +703,27 @@ function BaseTableInner<T extends Record<string, unknown>>({
// Resolve all column widths in a single pass — produces per-column
// inline styles and the aggregate table min-width.
- const resolvedWidths = resolveColumnWidths(resolvedColumns);
+ // A windowed table widens its row-number columns to the width measured for
+ // the last logical row, before that row mounts, so a number never clips.
+ // Fixed layout sizes columns from the header, so rows keep their columns;
+ // pinned offsets read the extra width from a table variable.
+ const sizedColumns = withLogicalPositionWidths(
+ resolvedColumns,
+ windowPlan.logicalPositionWidths,
+ );
+ const resolvedWidths = resolveColumnWidths(sizedColumns);
+ const logicalExtraStyle: Record<string, string> = {};
+ if (sizedColumns !== resolvedColumns) {
+ const floors = resolveColumnFloorWidths(resolvedColumns);
+ const sizedFloors = resolveColumnFloorWidths(sizedColumns);
+ sizedColumns.forEach((column, index) => {
+ const extra =
+ (sizedFloors.get(column.key) ?? 0) - (floors.get(column.key) ?? 0);
+ if (extra > 0) {
+ logicalExtraStyle[getLogicalPositionExtraVar(index)] = `${extra}px`;
+ }
+ });
+ }
// --- Plugin pipeline: table ---
const tableRenderProps = applyPlugins(plugins, p => p.transformTable, {
@@ -842,8 +865,8 @@ function BaseTableInner<T extends Record<string, unknown>>({
...tableRenderProps.htmlProps.style,
...style,
};
- const tableStyle: React.CSSProperties =
- resolvedWidths.tableMinWidth > 0
+ const tableStyle: React.CSSProperties = {
+ ...(resolvedWidths.tableMinWidth > 0
? {
...mergedStyle,
minWidth: resolveTableMinWidth(
@@ -851,7 +874,9 @@ function BaseTableInner<T extends Record<string, unknown>>({
resolvedWidths.tableMinWidth,
),
}
- : mergedStyle;
+ : mergedStyle),
+ ...logicalExtraStyle,
+ };
let tableElement: ReactNode = (
<table
diff --git a/packages/core/src/Table/TableMenuWindowFocus.test.tsx b/packages/core/src/Table/TableMenuWindowFocus.test.tsx
new file mode 100644
index 0000000000..f9c6d14eae
--- /dev/null
+++ b/packages/core/src/Table/TableMenuWindowFocus.test.tsx
@@ -0,0 +1,234 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+import {useMemo} from 'react';
+import {
+ render,
+ screen,
+ fireEvent,
+ waitFor,
+ cleanup,
+} from '@testing-library/react';
+import {afterEach, describe, it, expect, vi} from 'vitest';
+import {warmMenuBottomSheet} from '../DropdownMenu/__tests__/warmMenuBottomSheet';
+import {beforeAll} from 'vitest';
+beforeAll(warmMenuBottomSheet, 20000);
+import {Table} from './Table';
+import type {BodyCellRenderProps, BodyRowRenderProps} from './types';
+import {useTableRowsVirtualization} from './plugins/virtualization/useTableRowsVirtualization';
+const data = Array.from({length: 100}, (_, i) => ({
+ id: String(i),
+ name: `Row ${i}`,
+}));
+const columns = [{key: 'name', header: 'Name'}];
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+function Fixture({items = data}: {items?: typeof data}) {
+ const virtualization = useTableRowsVirtualization({
+ rowHeight: 56,
+ viewportHeight: 240,
+ });
+ const menu = useMemo(
+ () => ({
+ rowModel: 'flat' as const,
+ transformBodyRow(props: BodyRowRenderProps) {
+ return {...props, htmlProps: {...props.htmlProps, tabIndex: 0}};
+ },
+ transformBodyCell(props: BodyCellRenderProps) {
+ return {
+ ...props,
+ contextMenuActions: [
+ {id: 'inspect', label: 'Inspect row', onSelect: () => {}},
+ ],
+ };
+ },
+ }),
+ [],
+ );
+ return (
+ <Table
+ data={items}
+ columns={columns}
+ idKey="id"
+ virtualization={virtualization}
+ plugins={{menu}}
+ />
+ );
+}
+describe('Table recognized menu focus under windowing', () => {
+ it('returns removed owned menu focus even when its row was not focused before opening', async () => {
+ const {container, rerender} = render(<Fixture />);
+ const viewport = container.querySelector(
+ '.astryx-table-scroll-wrapper',
+ ) as HTMLDivElement;
+ const body = container.querySelector('tbody') as HTMLTableSectionElement;
+ let count = data.length;
+ Object.defineProperties(viewport, {
+ clientHeight: {configurable: true, value: 240},
+ clientWidth: {configurable: true, value: 400},
+ scrollHeight: {configurable: true, get: () => count * 56 + 36},
+ scrollWidth: {configurable: true, value: 400},
+ });
+ vi.spyOn(viewport, 'getBoundingClientRect').mockReturnValue(
+ new DOMRect(0, 0, 400, 240),
+ );
+ vi.spyOn(body, 'getBoundingClientRect').mockImplementation(
+ () => new DOMRect(0, 36 - viewport.scrollTop, 400, count * 56),
+ );
+ fireEvent.scroll(viewport);
+ const row = container.querySelector(
+ 'tbody tr[data-table-logical-index="0"]',
+ ) as HTMLTableRowElement;
+ expect(document.activeElement).not.toBe(row);
+ fireEvent.contextMenu(row.cells[0].firstElementChild as HTMLElement, {
+ clientX: 50,
+ clientY: 50,
+ });
+ const item = (
+ await screen.findAllByRole('menuitem', {
+ name: 'Inspect row',
+ hidden: true,
+ })
+ )[0];
+ item.focus();
+ expect(document.activeElement).toBe(item);
+ viewport.scrollTop = 4000;
+ fireEvent.scroll(viewport);
+ await waitFor(() =>
+ expect(
+ container.querySelector('tbody tr[data-table-logical-index="70"]'),
+ ).not.toBeNull(),
+ );
+ expect(row.isConnected).toBe(true);
+ count -= 1;
+ rerender(<Fixture items={data.slice(1)} />);
+ await waitFor(() => expect(viewport).toHaveFocus());
+ expect(row.isConnected).toBe(false);
+ });
+ it.each([false, true])(
+ 'releases a null-target blur only when the document is focused (focused=%s)',
+ async isDocumentFocused => {
+ const {container} = render(<Fixture />);
+ const viewport = container.querySelector(
+ '.astryx-table-scroll-wrapper',
+ ) as HTMLDivElement;
+ const body = container.querySelector('tbody')!;
+ Object.defineProperties(viewport, {
+ clientHeight: {configurable: true, value: 240},
+ clientWidth: {configurable: true, value: 400},
+ scrollHeight: {configurable: true, value: 5636},
+ scrollWidth: {configurable: true, value: 400},
+ });
+ vi.spyOn(viewport, 'getBoundingClientRect').mockReturnValue({
+ x: 0,
+ y: 0,
+ top: 0,
+ left: 0,
+ right: 400,
+ bottom: 240,
+ width: 400,
+ height: 240,
+ toJSON: () => ({}),
+ });
+ vi.spyOn(body, 'getBoundingClientRect').mockImplementation(() => ({
+ x: 0,
+ y: 36 - viewport.scrollTop,
+ top: 36 - viewport.scrollTop,
+ left: 0,
+ right: 400,
+ bottom: 5636 - viewport.scrollTop,
+ width: 400,
+ height: 5600,
+ toJSON: () => ({}),
+ }));
+ fireEvent.scroll(viewport);
+ const row = container.querySelector(
+ 'tbody tr[data-table-logical-index="0"]',
+ ) as HTMLTableRowElement;
+ row.focus();
+ viewport.scrollTop = 4000;
+ fireEvent.scroll(viewport);
+ await waitFor(() =>
+ expect(
+ container.querySelector('tbody tr[data-table-logical-index="70"]'),
+ ).not.toBeNull(),
+ );
+ expect(row.isConnected).toBe(true);
+ vi.spyOn(document, 'hasFocus').mockReturnValue(isDocumentFocused);
+ fireEvent.focusOut(row, {relatedTarget: null});
+ await waitFor(() => expect(row.isConnected).toBe(!isDocumentFocused));
+ if (!isDocumentFocused) {
+ expect(document.activeElement).toBe(row);
+ const outside = document.createElement('button');
+ document.body.append(outside);
+ outside.focus();
+ await waitFor(() => expect(row.isConnected).toBe(false));
+ expect(document.activeElement).toBe(outside);
+ outside.remove();
+ }
+ },
+ );
+ it('retains the same logical row while its menu owns focus and returns to its trigger', async () => {
+ const {container} = render(<Fixture />);
+ const viewport = container.querySelector(
+ '.astryx-table-scroll-wrapper',
+ ) as HTMLDivElement;
+ const body = container.querySelector('tbody')!;
+ Object.defineProperties(viewport, {
+ clientHeight: {configurable: true, value: 240},
+ clientWidth: {configurable: true, value: 400},
+ scrollHeight: {configurable: true, value: 5636},
+ scrollWidth: {configurable: true, value: 400},
+ });
+ vi.spyOn(viewport, 'getBoundingClientRect').mockReturnValue({
+ x: 0,
+ y: 0,
+ top: 0,
+ left: 0,
+ right: 400,
+ bottom: 240,
+ width: 400,
+ height: 240,
+ toJSON: () => ({}),
+ });
+ vi.spyOn(body, 'getBoundingClientRect').mockImplementation(() => ({
+ x: 0,
+ y: 36 - viewport.scrollTop,
+ top: 36 - viewport.scrollTop,
+ left: 0,
+ right: 400,
+ bottom: 5636 - viewport.scrollTop,
+ width: 400,
+ height: 5600,
+ toJSON: () => ({}),
+ }));
+ fireEvent.scroll(viewport);
+ const row = container.querySelector(
+ 'tbody tr[data-table-logical-index="0"]',
+ ) as HTMLTableRowElement;
+ row.focus();
+ fireEvent.contextMenu(row.cells[0].firstElementChild!, {
+ clientX: 50,
+ clientY: 50,
+ });
+ const item = (
+ await screen.findAllByRole('menuitem', {
+ name: 'Inspect row',
+ hidden: true,
+ })
+ )[0];
+ item.focus();
+ viewport.scrollTop = 4000;
+ fireEvent.scroll(viewport);
+ await waitFor(() =>
+ expect(
+ container.querySelector('tbody tr[data-table-logical-index="70"]'),
+ ).not.toBeNull(),
+ );
+ expect(row.isConnected).toBe(true);
+ expect(document.activeElement).toBe(item);
+ fireEvent.keyDown(item, {key: 'Escape'});
+ await waitFor(() => expect(document.activeElement).toBe(row));
+ expect(row.isConnected).toBe(true);
+ });
+});
diff --git a/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.tsx b/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.tsx
index ddd422689c..fad36b531d 100644
--- a/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.tsx
+++ b/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.tsx
@@ -353,6 +353,7 @@ export function useTableGroupedRows<T extends Record<string, unknown>>(
const plugin = useMemo(
(): TablePlugin<T> => ({
+ rowModel: 'grouped',
// A header row is not one of the caller's rows, so running a cell
// renderer against it can only misread it or throw — and the cells are
// discarded by `transformBodyRow` below regardless.
diff --git a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx
index 0bf54c931e..6e99347a02 100644
--- a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx
+++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx
@@ -911,6 +911,7 @@ export function useTableRowExpansion<T extends Record<string, unknown>>(
return useMemo(
(): TablePlugin<T> => ({
+ rowModel: 'detail',
// One colour-mode watch per table for the open panels' dividers.
transformTableContext(children: ReactNode): ReactNode {
return (
diff --git a/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.test.tsx b/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.test.tsx
index d2977421bf..6f5e000e87 100644
--- a/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.test.tsx
+++ b/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.test.tsx
@@ -3,6 +3,8 @@
import {describe, it, expect} from 'vitest';
import {act, render, screen, within} from '@testing-library/react';
import {useState} from 'react';
+import {vi} from 'vitest';
+import {useTableRowsVirtualization} from '../virtualization/useTableRowsVirtualization';
import {Table} from '../../Table';
import type {TableColumn, TablePlugin} from '../../types';
import {useTableRowIndex} from './useTableRowIndex';
@@ -83,6 +85,120 @@ describe('useTableRowIndex', () => {
expect(within(rows[2]).getByText('2')).toBeInTheDocument();
});
+ it('falls back instead of clipping a measured windowed number without changing legacy column widths', () => {
+ const rows = Array.from({length: 20}, (_, index) => ({
+ id: String(index),
+ name: `Product ${index}`,
+ }));
+ vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(320);
+ vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(48);
+ const createRange = document.createRange.bind(document);
+ vi.spyOn(document, 'createRange').mockImplementation(() => {
+ const range = createRange();
+ Object.defineProperty(range, 'getBoundingClientRect', {
+ value: () => ({
+ width: 53,
+ height: 16,
+ top: 0,
+ bottom: 16,
+ left: 0,
+ right: 53,
+ x: 0,
+ y: 0,
+ toJSON() {
+ return {};
+ },
+ }),
+ });
+ return range;
+ });
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(
+ function (this: HTMLElement) {
+ return {
+ height: this.localName === 'tbody' ? rows.length * 56 : 0,
+ top: 0,
+ bottom: 0,
+ left: 0,
+ right: 0,
+ width: 0,
+ x: 0,
+ y: 0,
+ toJSON() {
+ return {};
+ },
+ };
+ },
+ );
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ function Fixture() {
+ const rowIndex = useTableRowIndex({data: rows});
+ const virtualization = useTableRowsVirtualization({
+ rowHeight: 56,
+ viewportHeight: 320,
+ });
+ return (
+ <Table
+ data={rows}
+ columns={columns}
+ idKey="id"
+ plugins={{rowIndex}}
+ virtualization={virtualization}
+ />
+ );
+ }
+ try {
+ const {container} = render(<Fixture />);
+ expect(container.querySelectorAll('tbody > tr')).toHaveLength(
+ rows.length,
+ );
+ expect(container.querySelector('[data-table-logical-index]')).toBeNull();
+ expect(screen.getByRole('columnheader', {name: '#'}).style.width).toBe(
+ '48px',
+ );
+ expect(warning).toHaveBeenCalledWith(
+ expect.stringContaining('row-number content exceeds'),
+ );
+ } finally {
+ vi.restoreAllMocks();
+ }
+ });
+ it('numbers windowed rows from Table positions after same-array append without consulting a second key lookup', () => {
+ const rows: Row[] = data.map(item => ({...item}));
+ const getRowKey = vi.fn((item: Row) => item.id);
+ function Windowed() {
+ const rowIndex = useTableRowIndex({data: rows, getRowKey});
+ const virtualization = useTableRowsVirtualization({
+ rowHeight: 56,
+ viewportHeight: 320,
+ });
+ return (
+ <Table
+ data={rows}
+ columns={columns}
+ idKey="id"
+ virtualization={virtualization}
+ plugins={{rowIndex}}
+ />
+ );
+ }
+ const view = render(<Windowed />);
+ rows.push({id: 'd', name: 'Dora'});
+ view.rerender(<Windowed />);
+ const appended = screen
+ .getByText('Dora')
+ .closest('tr') as HTMLTableRowElement;
+ expect(appended).toHaveAttribute('aria-rowindex', '5');
+ expect(appended.cells[0]).toHaveTextContent('4');
+ expect(getRowKey).not.toHaveBeenCalled();
+ rows.reverse();
+ view.rerender(<Windowed />);
+ const reordered = screen
+ .getByText('Dora')
+ .closest('tr') as HTMLTableRowElement;
+ expect(reordered).toHaveAttribute('aria-rowindex', '2');
+ expect(reordered.cells[0]).toHaveTextContent('1');
+ });
+
it('prepends a header cell with the default label', () => {
render(<Harness />);
const headers = screen.getAllByRole('columnheader');
diff --git a/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.tsx b/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.tsx
index ee527266c0..9dc65a0994 100644
--- a/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.tsx
+++ b/packages/core/src/Table/plugins/rowIndex/useTableRowIndex.tsx
@@ -16,6 +16,7 @@ import {useMemo, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {colorVars, typeScaleVars} from '../../../theme/tokens.stylex';
+import {registerFixedHeightColumn} from '../../tableColumnAdmission';
import type {TableColumn, TablePlugin} from '../../types';
/**
@@ -55,6 +56,19 @@ const styles = stylex.create({
},
});
+function createRowIndexLookup<T>(data: T[], getRowKey?: (item: T) => string) {
+ let map: Map<unknown, number> | undefined;
+ return (item: T): number | undefined => {
+ if (map == null) {
+ map = new Map();
+ for (let index = 0; index < data.length; index++) {
+ map.set(getRowKey ? getRowKey(data[index]) : data[index], index);
+ }
+ }
+ return map.get(getRowKey ? getRowKey(item) : item);
+ };
+}
+
/**
* Returns a {@link TablePlugin} that prepends a right-aligned, monospaced
* row-number column. Numbering follows the rows the table renders, so it
@@ -71,25 +85,12 @@ export function useTableRowIndex<T extends Record<string, unknown>>(
): TablePlugin<T> {
const {data, getRowKey, label = '#', startFrom = 1} = config;
- // The lookup into a caller's `data`. Keyed by getRowKey when provided
- // (stable across new object identities), otherwise by object reference.
- const lookup = useMemo(() => {
- if (data == null) {
- return null;
- }
- const map = new Map<unknown, number>();
- for (let i = 0; i < data.length; i++) {
- const item = data[i];
- map.set(getRowKey ? getRowKey(item) : item, i);
- }
- return (item: T): number | undefined =>
- map.get(getRowKey ? getRowKey(item) : item);
- }, [data, getRowKey]);
+ const lookup = useMemo(
+ () => (data == null ? null : createRowIndexLookup(data, getRowKey)),
+ [data, getRowKey],
+ );
return useMemo((): TablePlugin<T> => {
- // Table runs each cell's transforms just before it renders that cell. So
- // the index cell's renderer reads the position that its own transform
- // stored.
const positions = new WeakMap<T, number>();
// One column object per plugin, so a Table re-render keeps its resolved
// columns and leaves unchanged rows alone.
@@ -107,6 +108,9 @@ export function useTableRowIndex<T extends Record<string, unknown>>(
return <span {...stylex.props(styles.index)}>{idx + startFrom}</span>;
},
};
+ registerFixedHeightColumn(indexColumn, startFrom === 1, logicalIndex => (
+ <span {...stylex.props(styles.index)}>{logicalIndex + 1}</span>
+ ));
return {
rowModel: 'flat',
transformBodyCell(props, column, item, _columnIndex, _columns, context) {
diff --git a/packages/core/src/Table/plugins/selection/useTableSelection.tsx b/packages/core/src/Table/plugins/selection/useTableSelection.tsx
index c09b288c33..b4380ce9d1 100644
--- a/packages/core/src/Table/plugins/selection/useTableSelection.tsx
+++ b/packages/core/src/Table/plugins/selection/useTableSelection.tsx
@@ -60,6 +60,8 @@ import english from '../../../i18n/generated-english/Table/plugins/selection/use
import {createSharedContext} from '../../../utils/sharedContext';
registerEnglishFallback(english);
+import {registerFixedHeightColumn} from '../../tableColumnAdmission';
+import {registerCountIndependentPlugin} from '../../tableRowContextUsage';
// =============================================================================
// Config Type
@@ -397,7 +399,7 @@ export function useTableSelection<T extends Record<string, unknown>>(
[],
);
- return useMemo(
+ const plugin = useMemo(
(): TablePlugin<T> => ({
rowModel: 'flat',
transformTableContext(children: ReactNode) {
@@ -409,6 +411,7 @@ export function useTableSelection<T extends Record<string, unknown>>(
},
transformColumns(columns: TableColumn<T>[]) {
+ registerFixedHeightColumn(selectionColumn);
return [selectionColumn, ...columns];
},
@@ -451,4 +454,5 @@ export function useTableSelection<T extends Record<string, unknown>>(
}),
[store, selectionColumn],
);
+ return registerCountIndependentPlugin(plugin);
}
diff --git a/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.test.tsx b/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.test.tsx
index ad888ddd14..ed275dde77 100644
--- a/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.test.tsx
+++ b/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.test.tsx
@@ -18,6 +18,7 @@ import {render, screen} from '@testing-library/react';
import {Table} from '../../Table';
import {useTableStickyColumns} from './useTableStickyColumns';
import {useTableColumnResize} from '../columnResize/useTableColumnResize';
+import {useTableRowIndex} from '../rowIndex/useTableRowIndex';
import {pixel, proportional} from '../../columnUtils';
import type {TableColumn} from '../../types';
@@ -70,6 +71,30 @@ describe('useTableStickyColumns', () => {
expect(getHeader('Name').style.insetInlineStart).toBe('0px');
});
+ it("adds a row-number column's windowed extra width to the pinned offsets after it", () => {
+ function Harness() {
+ const rowIndex = useTableRowIndex<Row>();
+ const sticky = useTableStickyColumns<Row>({startKeys: ['name']});
+ return (
+ <Table
+ data={data}
+ columns={columns}
+ idKey="id"
+ plugins={{rowIndex, stickyColumns: sticky}}
+ />
+ );
+ }
+ render(<Harness />);
+ // The number column comes first, so Name sits after its 48px floor plus
+ // whatever extra width a windowed table gives it (none here).
+ expect(getHeader('Name').getAttribute('style')).toContain(
+ 'calc(48px + var(--_table-logical-extra-0, 0px))',
+ );
+ expect(screen.getByRole('table').getAttribute('style') ?? '').not.toContain(
+ '--_table-logical-extra',
+ );
+ });
+
it('computes cumulative start offsets for contiguous pinned columns', () => {
function Harness() {
const sticky = useTableStickyColumns<Row>({
diff --git a/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx b/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx
index 3fa24e03b4..38c465cb97 100644
--- a/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx
+++ b/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx
@@ -23,6 +23,8 @@ import {
type RefObject,
} from 'react';
import * as stylex from '@stylexjs/stylex';
+import {registerCountIndependentPlugin} from '../../tableRowContextUsage';
+
import {colorVars, durationVars, easeVars} from '../../../theme/tokens.stylex';
import type {
TableColumn,
@@ -32,6 +34,10 @@ import type {
ScrollWrapperRenderProps,
} from '../../types';
import {resolveColumnFloorWidths} from '../../columnUtils';
+import {
+ getLogicalPositionExtraVar,
+ getLogicalPositionRenderer,
+} from '../../tableColumnAdmission';
import {collapsedBottom} from '../../rowDivider';
import {GLIDING_ATTRIBUTE, PINNED_ATTRIBUTE} from '../../glidingDivider';
import {useTheme, useThemeName} from '../../../theme/useTheme';
@@ -73,14 +79,28 @@ export interface UseTableStickyColumnsConfig {
// pinned block stays contiguous for pixel, proportional, and width-less mixes.
/**
- * Columns pinned to the START edge → cumulative inline offset (px). The pinned
+ * A pinned offset as a CSS length: the floors before the column plus the extra
+ * width a windowed table gives each row-number column among them.
+ */
+function toOffset(pixels: number, extras: number[]): string {
+ if (extras.length === 0) {
+ return `${pixels}px`;
+ }
+ const parts = extras.map(
+ index => `var(${getLogicalPositionExtraVar(index)}, 0px)`,
+ );
+ return `calc(${pixels}px + ${parts.join(' + ')})`;
+}
+
+/**
+ * Columns pinned to the START edge → cumulative inline offset. The pinned
* block is the contiguous run from column 0 through the last key in `startKeys`
* (inclusive of any synthetic columns before it). `null` if none / no context.
*/
function computeStartOffsets(
columns: ReadonlyArray<TableColumn<Record<string, unknown>>> | undefined,
startKeys: string[],
-): Map<string, number> | null {
+): Map<string, string> | null {
if (!columns || columns.length === 0 || startKeys.length === 0) {
return null;
}
@@ -94,11 +114,15 @@ function computeStartOffsets(
return null;
}
const widths = resolveColumnFloorWidths(columns);
- const offsets = new Map<string, number>();
+ const offsets = new Map<string, string>();
+ const extras: number[] = [];
let cumulative = 0;
for (let i = 0; i <= lastStickyIndex; i++) {
- offsets.set(columns[i].key, cumulative);
+ offsets.set(columns[i].key, toOffset(cumulative, extras));
cumulative += widths.get(columns[i].key) ?? 0;
+ if (getLogicalPositionRenderer(columns[i]) != null) {
+ extras.push(i);
+ }
}
return offsets;
}
@@ -111,7 +135,7 @@ function computeStartOffsets(
function computeEndOffsets(
columns: ReadonlyArray<TableColumn<Record<string, unknown>>> | undefined,
endKeys: string[],
-): Map<string, number> | null {
+): Map<string, string> | null {
if (!columns || columns.length === 0 || endKeys.length === 0) {
return null;
}
@@ -126,16 +150,20 @@ function computeEndOffsets(
return null;
}
const widths = resolveColumnFloorWidths(columns);
- const offsets = new Map<string, number>();
+ const offsets = new Map<string, string>();
+ const extras: number[] = [];
let cumulative = 0;
for (let i = columns.length - 1; i >= firstStickyIndex; i--) {
- offsets.set(columns[i].key, cumulative);
+ offsets.set(columns[i].key, toOffset(cumulative, extras));
cumulative += widths.get(columns[i].key) ?? 0;
+ if (getLogicalPositionRenderer(columns[i]) != null) {
+ extras.push(i);
+ }
}
return offsets;
}
-type StickySide = {edge: 'start' | 'end'; offset: number};
+type StickySide = {edge: 'start' | 'end'; offset: string};
/**
* Resolve how a single column should be pinned given the start/end configs and
@@ -150,11 +178,11 @@ function resolveStickySide(
): StickySide | null {
const startOffsets = computeStartOffsets(columns, startKeys);
if (startOffsets?.has(columnKey)) {
- return {edge: 'start', offset: startOffsets.get(columnKey) ?? 0};
+ return {edge: 'start', offset: startOffsets.get(columnKey) ?? '0px'};
}
const endOffsets = computeEndOffsets(columns, endKeys);
if (endOffsets?.has(columnKey)) {
- return {edge: 'end', offset: endOffsets.get(columnKey) ?? 0};
+ return {edge: 'end', offset: endOffsets.get(columnKey) ?? '0px'};
}
return null;
}
@@ -609,7 +637,7 @@ export function useTableStickyColumns<T extends Record<string, unknown>>(
refreshRef.current?.();
});
- return useMemo(
+ const plugin = useMemo(
(): TablePlugin<T> => ({
rowModel: 'flat',
transformTableContext(children: ReactNode): ReactNode {
@@ -643,8 +671,8 @@ export function useTableStickyColumns<T extends Record<string, unknown>>(
// buying a lucky order from the plugin sequence.
const offsetStyle: CSSProperties =
side.edge === 'start'
- ? {position: 'sticky', insetInlineStart: `${side.offset}px`}
- : {position: 'sticky', insetInlineEnd: `${side.offset}px`};
+ ? {position: 'sticky', insetInlineStart: side.offset}
+ : {position: 'sticky', insetInlineEnd: side.offset};
return {
...props,
htmlProps: {
@@ -672,8 +700,8 @@ export function useTableStickyColumns<T extends Record<string, unknown>>(
}
const offsetStyle: CSSProperties =
side.edge === 'start'
- ? {insetInlineStart: `${side.offset}px`}
- : {insetInlineEnd: `${side.offset}px`};
+ ? {insetInlineStart: side.offset}
+ : {insetInlineEnd: side.offset};
return {
...props,
htmlProps: {
@@ -732,4 +760,5 @@ export function useTableStickyColumns<T extends Record<string, unknown>>(
// computed once and reused across renders.
[attachScrollShadow],
);
+ return registerCountIndependentPlugin(plugin);
}
diff --git a/packages/core/src/Table/plugins/tree/useTableTreeData.tsx b/packages/core/src/Table/plugins/tree/useTableTreeData.tsx
index 7e95121c2f..991dafb45f 100644
--- a/packages/core/src/Table/plugins/tree/useTableTreeData.tsx
+++ b/packages/core/src/Table/plugins/tree/useTableTreeData.tsx
@@ -66,6 +66,7 @@ import {createSharedContext} from '../../../utils/sharedContext';
registerEnglishFallback(english);
import {TableContext} from '../../TableContext';
+import {registerCountIndependentPlugin} from '../../tableRowContextUsage';
// =============================================================================
// Types
@@ -566,7 +567,7 @@ export function useTableTreeData<T extends Record<string, unknown>>(
// internally no-ops when hasExpandableRows is false. Swapping between
// an empty and a context-wrapping plugin would change the element tree
// and remount the whole table when flat data turns nested.
- return useMemo((): TablePlugin<T> => {
+ const plugin = useMemo((): TablePlugin<T> => {
const getCachedColumns = (
columns: TableColumn<T>[],
treeKey: string | undefined,
@@ -591,6 +592,7 @@ export function useTableTreeData<T extends Record<string, unknown>>(
};
return {
+ rowModel: 'tree',
transformTableContext(children: ReactNode) {
return <TreeStoreContext value={store}>{children}</TreeStoreContext>;
},
@@ -774,4 +776,5 @@ export function useTableTreeData<T extends Record<string, unknown>>(
},
};
}, [store]);
+ return registerCountIndependentPlugin(plugin);
}
diff --git a/packages/core/src/Table/plugins/virtualization/useTableWindow.test.tsx b/packages/core/src/Table/plugins/virtualization/useTableWindow.test.tsx
index 8eb3d97766..e072ee05b4 100644
--- a/packages/core/src/Table/plugins/virtualization/useTableWindow.test.tsx
+++ b/packages/core/src/Table/plugins/virtualization/useTableWindow.test.tsx
@@ -778,6 +778,156 @@ describe('private Table shared-geometry controller', () => {
unmount();
viewport.remove();
});
+ it('sizes a logical-position column from canvas text metrics without a layout read or DOM write', () => {
+ const measureText = vi.fn((text: string) => ({width: text.length * 7}));
+ vi.stubGlobal(
+ 'OffscreenCanvas',
+ class {
+ getContext() {
+ return {font: '', measureText};
+ }
+ },
+ );
+ const viewport = document.createElement('div');
+ const table = document.createElement('table');
+ const body = document.createElement('tbody');
+ const row = document.createElement('tr');
+ const cell = document.createElement('td');
+ const number = document.createElement('span');
+ number.textContent = '1';
+ number.style.fontSize = '12px';
+ number.style.fontFamily = 'monospace';
+ cell.style.paddingLeft = '12px';
+ cell.style.paddingRight = '12px';
+ cell.append(number);
+ row.append(cell);
+ body.append(row);
+ table.append(body);
+ viewport.append(table);
+ document.body.append(viewport);
+ Object.defineProperty(viewport, 'clientHeight', {value: 100});
+ vi.spyOn(body, 'getBoundingClientRect').mockImplementation(
+ () => ({height: 2000}) as DOMRect,
+ );
+ vi.spyOn(row, 'getBoundingClientRect').mockImplementation(
+ () => ({height: 20}) as DOMRect,
+ );
+ const numberRect = vi.spyOn(number, 'getBoundingClientRect');
+ const cellWrites = vi.spyOn(cell, 'append');
+ const positions = new Set([0]);
+ const measured = {viewportHeight: 100, bodyOffset: 0, isMeasured: true};
+ const geometry = source({
+ ...measured,
+ scrollTop: 0,
+ revision: 1,
+ layoutRevision: 1,
+ });
+ const {result, unmount} = renderHook(() =>
+ useTableWindow({
+ capability: useTableRowsVirtualization({
+ rowHeight: 20,
+ viewportHeight: 100,
+ }),
+ data,
+ keys,
+ isAdmitted: true,
+ logicalPositionColumns: positions,
+ viewport: {current: viewport},
+ body: {current: body},
+ table: {current: table},
+ geometry: geometry.store,
+ }),
+ );
+ // '100' at 7px per digit, 24px of padding and 1px of slack.
+ expect(result.current.logicalPositionWidths.get(0)).toBe(46);
+ expect(measureText).toHaveBeenLastCalledWith('100');
+ expect(numberRect).not.toHaveBeenCalled();
+ expect(cellWrites).not.toHaveBeenCalled();
+ const calls = measureText.mock.calls.length;
+ const publish = (scrollTop: number, revision: number, layout: number) =>
+ act(() =>
+ geometry.publish({
+ ...measured,
+ scrollTop,
+ revision,
+ layoutRevision: layout,
+ }),
+ );
+ // A scroll or a content change does not measure again; a layout change does.
+ publish(4, 1, 1);
+ publish(4, 2, 1);
+ expect(measureText).toHaveBeenCalledTimes(calls);
+ publish(4, 3, 2);
+ expect(measureText.mock.calls.length).toBeGreaterThan(calls);
+ unmount();
+ viewport.remove();
+ vi.unstubAllGlobals();
+ });
+ it('checks the body extent after a row-number width changes at mount', () => {
+ vi.stubGlobal(
+ 'OffscreenCanvas',
+ class {
+ getContext() {
+ return {
+ font: '',
+ measureText: (text: string) => ({width: text.length * 7}),
+ };
+ }
+ },
+ );
+ const viewport = document.createElement('div');
+ const table = document.createElement('table');
+ const body = document.createElement('tbody');
+ const row = document.createElement('tr');
+ const cell = document.createElement('td');
+ const number = document.createElement('span');
+ number.textContent = '1';
+ number.style.fontSize = '12px';
+ number.style.fontFamily = 'monospace';
+ cell.append(number);
+ row.append(cell);
+ body.append(row);
+ table.append(body);
+ viewport.append(table);
+ document.body.append(viewport);
+ Object.defineProperty(viewport, 'clientHeight', {value: 100});
+ // 100 rows of 20px need a 2,000px body; this one cannot hold them.
+ vi.spyOn(body, 'getBoundingClientRect').mockImplementation(
+ () => ({height: 1234}) as DOMRect,
+ );
+ vi.spyOn(row, 'getBoundingClientRect').mockImplementation(
+ () => ({height: 20}) as DOMRect,
+ );
+ const positions = new Set([0]);
+ const geometry = source({
+ viewportHeight: 100,
+ bodyOffset: 0,
+ isMeasured: true,
+ scrollTop: 0,
+ revision: 1,
+ layoutRevision: 1,
+ });
+ const {result, unmount} = renderHook(() =>
+ useTableWindow({
+ capability: useTableRowsVirtualization({
+ rowHeight: 20,
+ viewportHeight: 100,
+ }),
+ data,
+ keys,
+ isAdmitted: true,
+ logicalPositionColumns: positions,
+ viewport: {current: viewport},
+ body: {current: body},
+ table: {current: table},
+ geometry: geometry.store,
+ }),
+ );
+ expect(result.current.isWindowed).toBe(false);
+ unmount();
+ viewport.remove();
+ vi.unstubAllGlobals();
+ });
it('cleans the parent source subscription across StrictMode replay', () => {
const geometry = source();
const refs = {
diff --git a/packages/core/src/Table/plugins/virtualization/useTableWindow.ts b/packages/core/src/Table/plugins/virtualization/useTableWindow.ts
index 8c4895d29a..768212f42b 100644
--- a/packages/core/src/Table/plugins/virtualization/useTableWindow.ts
+++ b/packages/core/src/Table/plugins/virtualization/useTableWindow.ts
@@ -70,6 +70,11 @@ export interface UseTableWindowOptions<T> {
}
export interface TableWindowResult {
segments: ListWindowSegment[];
+ /**
+ * Measured column widths, by column index, that fit the last logical row
+ * position in each logical-position column. Empty when not windowed.
+ */
+ logicalPositionWidths: ReadonlyMap<number, number>;
isWindowed: boolean;
isFixedHeight: boolean;
onRowFocus: (key: string | number, focusTarget?: HTMLElement) => void;
@@ -100,6 +105,7 @@ interface ValidationState {
logicalPositionColumns: ReadonlySet<number>;
checkedRows: WeakSet<HTMLTableRowElement>;
layoutRevision: number | undefined;
+ isPositionWidthMeasured: boolean;
totalHeight: number;
}
interface Violation {
@@ -115,6 +121,103 @@ const EMPTY_GEOMETRY: TableWindowGeometry = Object.freeze({
isMeasured: false,
});
const EMPTY_LOGICAL_POSITION_COLUMNS: ReadonlySet<number> = new Set();
+const EMPTY_POSITION_WIDTHS: ReadonlyMap<number, number> = new Map();
+
+function areWidthsEqual(
+ a: ReadonlyMap<number, number>,
+ b: ReadonlyMap<number, number>,
+): boolean {
+ if (a.size !== b.size) {
+ return false;
+ }
+ for (const [index, width] of a) {
+ const other = b.get(index);
+ if (other === undefined || Math.abs(other - width) > 0.5) {
+ return false;
+ }
+ }
+ return true;
+}
+
+let textContext: OffscreenCanvasRenderingContext2D | null | undefined;
+
+/** Canvas text metrics: no layout read and no DOM write. */
+function measureText(font: string, text: string): number | undefined {
+ if (textContext === undefined) {
+ textContext =
+ typeof OffscreenCanvas === 'undefined'
+ ? null
+ : new OffscreenCanvas(1, 1).getContext('2d');
+ }
+ if (textContext == null) {
+ return undefined;
+ }
+ textContext.font = font;
+ return textContext.measureText(text).width;
+}
+
+function readPixels(value: string): number {
+ return Number.parseFloat(value) || 0;
+}
+
+/**
+ * The column width that fits `text` in a logical-position cell, at the cell's
+ * own font, padding and density. It reads computed styles and canvas text
+ * metrics only, so it adds no layout read and no DOM write. Undefined when it
+ * cannot be measured.
+ */
+function measureLogicalPositionWidth(
+ cell: HTMLTableCellElement,
+ text: string,
+): number | undefined {
+ const view = cell.ownerDocument.defaultView;
+ if (view == null) {
+ return undefined;
+ }
+ const walker = cell.ownerDocument.createTreeWalker(
+ cell,
+ view.NodeFilter.SHOW_TEXT,
+ );
+ let host: HTMLElement | null = null;
+ for (let node = walker.nextNode(); node != null; node = walker.nextNode()) {
+ if (node.textContent?.trim()) {
+ host = node.parentElement;
+ break;
+ }
+ }
+ if (host == null) {
+ return undefined;
+ }
+ const style = view.getComputedStyle(host);
+ if (style.fontSize === '' || style.fontFamily === '') {
+ return undefined;
+ }
+ const font = [style.fontStyle, style.fontWeight, style.fontSize]
+ .filter(part => part !== '')
+ .concat(style.fontFamily)
+ .join(' ');
+ const textWidth = measureText(font, text);
+ if (textWidth === undefined || !(textWidth > 0)) {
+ return undefined;
+ }
+ const spacing =
+ style.letterSpacing === 'normal' ? 0 : readPixels(style.letterSpacing);
+ // Padding and borders between the text and the column edge.
+ let chrome = 0;
+ for (
+ let element: HTMLElement | null = host;
+ element != null && cell.contains(element);
+ element = element.parentElement
+ ) {
+ const box = element === host ? style : view.getComputedStyle(element);
+ chrome +=
+ readPixels(box.paddingLeft) +
+ readPixels(box.paddingRight) +
+ readPixels(box.borderLeftWidth) +
+ readPixels(box.borderRightWidth);
+ }
+ return Math.ceil(textWidth + spacing * text.length + chrome + 1);
+}
const getEmptyGeometry = () => EMPTY_GEOMETRY;
const subscribeToNothing = () => () => {};
@@ -264,6 +367,7 @@ export function useTableWindow<T>({
const [focusedKey, setFocusedKey] = useState<string | number | undefined>();
const [tracking, setTracking] = useState<WindowTracking | undefined>();
const focusNoteRef = useRef<FocusWithin | null>(null);
+ const [positionWidths, setPositionWidths] = useState(EMPTY_POSITION_WIDTHS);
const validationRef = useRef<ValidationState | null>(null);
useDevWarningPerMessage(
'Table',
@@ -478,14 +582,44 @@ export function useTableWindow<T>({
logicalPositionColumns,
checkedRows: new WeakSet(),
layoutRevision: undefined,
+ isPositionWidthMeasured: false,
totalHeight: Number.NaN,
};
validationRef.current = state;
}
+ const isLayoutChanged = state.layoutRevision !== layoutRevision;
+ // Size logical-position columns for the last position before its row
+ // mounts. A new width re-renders the table and returns before this pass
+ // records anything, so the next pass runs every check below.
+ if (
+ (isLayoutChanged || !state.isPositionWidthMeasured) &&
+ logicalPositionColumns.size > 0
+ ) {
+ const row = Array.from(body.current.rows).find(
+ candidate => candidate.getAttribute('aria-hidden') !== 'true',
+ );
+ if (row) {
+ state.isPositionWidthMeasured = true;
+ const next = new Map<number, number>();
+ for (const index of logicalPositionColumns) {
+ const cell = row.cells[index];
+ const width =
+ cell == null
+ ? undefined
+ : measureLogicalPositionWidth(cell, String(data.length));
+ if (width !== undefined) {
+ next.set(index, width);
+ }
+ }
+ if (!areWidthsEqual(positionWidths, next)) {
+ setPositionWidths(next);
+ return;
+ }
+ }
+ }
// A size, font, or outer class or style change can clip rows that passed
// before, so every mounted row is read again. A mounted row is a content
// invalidation only, and reads only the new rows.
- const isLayoutChanged = state.layoutRevision !== layoutRevision;
if (isLayoutChanged) {
state.checkedRows = new WeakSet();
}
@@ -514,19 +648,24 @@ export function useTableWindow<T>({
totalHeight,
revision,
layoutRevision,
+ positionWidths,
body,
viewport,
table,
]);
+ const logicalPositionWidths = isWindowed
+ ? positionWidths
+ : EMPTY_POSITION_WIDTHS;
return useMemo(
() => ({
segments,
+ logicalPositionWidths,
isWindowed,
isFixedHeight: isWindowed,
onRowFocus,
onRowBlur,
}),
- [segments, isWindowed, onRowFocus, onRowBlur],
+ [segments, logicalPositionWidths, isWindowed, onRowFocus, onRowBlur],
);
}
diff --git a/packages/core/src/Table/tableColumnAdmission.test.ts b/packages/core/src/Table/tableColumnAdmission.test.ts
new file mode 100644
index 0000000000..6b518732c1
--- /dev/null
+++ b/packages/core/src/Table/tableColumnAdmission.test.ts
@@ -0,0 +1,50 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+import {describe, expect, it} from 'vitest';
+import {
+ registerFixedHeightColumn,
+ withLogicalPositionWidths,
+} from './tableColumnAdmission';
+import type {TableColumn} from './types';
+
+type Row = {id: string};
+
+function numbered(): TableColumn<Row> {
+ const column: TableColumn<Row> = {
+ key: 'number',
+ header: '#',
+ width: {type: 'pixel', value: 48},
+ renderCell: () => null,
+ };
+ registerFixedHeightColumn(column, true, index => index + 1);
+ return column;
+}
+
+describe('logical-position column widths', () => {
+ it('keeps the columns array when no width is measured or every width fits', () => {
+ const columns = [numbered(), {key: 'name', header: 'Name'}];
+ expect(withLogicalPositionWidths(columns, new Map())).toBe(columns);
+ expect(withLogicalPositionWidths(columns, new Map([[0, 40]]))).toBe(
+ columns,
+ );
+ });
+
+ it('widens a logical-position column to its measured width', () => {
+ const columns = [numbered(), {key: 'name', header: 'Name'}];
+ const sized = withLogicalPositionWidths(columns, new Map([[0, 61]]));
+ expect(sized).not.toBe(columns);
+ expect(sized[1]).toBe(columns[1]);
+ expect(sized[0]).toMatchObject({
+ key: 'number',
+ width: {type: 'pixel', value: 61},
+ });
+ });
+
+ it('leaves columns that render no logical position unchanged', () => {
+ const plain: TableColumn<Row> = {key: 'id', header: 'ID'};
+ registerFixedHeightColumn(plain);
+ const columns = [plain];
+ expect(withLogicalPositionWidths(columns, new Map([[0, 200]]))).toBe(
+ columns,
+ );
+ });
+});
diff --git a/packages/core/src/Table/tableColumnAdmission.ts b/packages/core/src/Table/tableColumnAdmission.ts
index 0ef35a0b80..cf5edf8720 100644
--- a/packages/core/src/Table/tableColumnAdmission.ts
+++ b/packages/core/src/Table/tableColumnAdmission.ts
@@ -24,6 +24,40 @@ export function registerFixedHeightColumn<T extends Record<string, unknown>>(
}
}
+/**
+ * Widens logical-position columns to the measured widths, by column index,
+ * that fit the last position. A column keeps a declared width that already
+ * fits. Returns `columns` itself when no column changes.
+ */
+export function withLogicalPositionWidths<T extends Record<string, unknown>>(
+ columns: TableColumn<T>[],
+ widths: ReadonlyMap<number, number>,
+): TableColumn<T>[] {
+ if (widths.size === 0) {
+ return columns;
+ }
+ let isChanged = false;
+ const next = columns.map((column, index) => {
+ const width = widths.get(index);
+ if (
+ width === undefined ||
+ logicalRenderers.get(column) == null ||
+ (column.width?.type === 'pixel' && width <= column.width.value)
+ ) {
+ return column;
+ }
+ isChanged = true;
+ return {...column, width: {type: 'pixel' as const, value: width}};
+ });
+ return isChanged ? next : columns;
+}
+/**
+ * The table variable that carries the extra width a windowed table gives the
+ * logical-position column at `index`, so pinned offsets can include it.
+ */
+export function getLogicalPositionExtraVar(index: number): string {
+ return `--_table-logical-extra-${index}`;
+}
export function getLogicalPositionRenderer<T extends Record<string, unknown>>(
column: TableColumn<T>,
): ((logicalIndex: number) => ReactNode) | undefined {
diff --git a/packages/core/src/Table/tableRowContextUsage.ts b/packages/core/src/Table/tableRowContextUsage.ts
index 2618b8e54e..048430c56a 100644
--- a/packages/core/src/Table/tableRowContextUsage.ts
+++ b/packages/core/src/Table/tableRowContextUsage.ts
@@ -11,6 +11,7 @@
import type {TablePlugin, TableRowContext} from './types';
import {warnOnce} from '../utils/devWarning';
+const countIndependentPlugins = new WeakSet<object>();
const indexReadingPlugins = new WeakSet<object>();
const countReadingPlugins = new WeakSet<object>();
const trackedContexts = new WeakMap<
@@ -46,6 +47,17 @@ function warnIfLate(plugin: object, field: string): void {
}
}
+/**
+ * Skips row-context tracking for a core plugin that never reads the row index
+ * or count. A later read is not tracked, so its rows can go stale.
+ */
+export function registerCountIndependentPlugin<
+ T extends Record<string, unknown>,
+>(plugin: TablePlugin<T>): TablePlugin<T> {
+ countIndependentPlugins.add(plugin);
+ return plugin;
+}
+
/** Whether a transform of the plugin has read a row's `logicalIndex`. */
export function readsRowIndex<T extends Record<string, unknown>>(
plugin: TablePlugin<T>,
@@ -57,7 +69,9 @@ export function readsRowIndex<T extends Record<string, unknown>>(
export function readsRowCount<T extends Record<string, unknown>>(
plugin: TablePlugin<T>,
): boolean {
- return countReadingPlugins.has(plugin);
+ return (
+ countReadingPlugins.has(plugin) && !countIndependentPlugins.has(plugin)
+ );
}
/**
@@ -69,6 +83,9 @@ export function trackRowContext<T extends Record<string, unknown>>(
plugin: TablePlugin<T>,
context: TableRowContext,
): TableRowContext {
+ if (countIndependentPlugins.has(plugin)) {
+ return context;
+ }
let byPlugin = trackedContexts.get(context);
if (byPlugin == null) {
byPlugin = new WeakMap();
diff --git a/packages/core/src/Table/useTableRowIndex.doc.mjs b/packages/core/src/Table/useTableRowIndex.doc.mjs
index 2d12239edc..967506e330 100644
--- a/packages/core/src/Table/useTableRowIndex.doc.mjs
+++ b/packages/core/src/Table/useTableRowIndex.doc.mjs
@@ -7,7 +7,7 @@ export const docs = {
subComponentOf: 'Table',
displayName: 'useTableRowIndex',
description:
- 'Hook that returns a TablePlugin which prepends a right-aligned, monospaced row-number column. Numbering follows the rows the table renders (reflecting the current sort / filter / pagination view) and starts at 1 by default. Without data, Table gives each row its position; with data, numbers follow that array.',
+ 'Hook that returns a TablePlugin which prepends a right-aligned, monospaced row-number column, starting at 1 by default. Without data, Table supplies row positions; with data, ordinary numbers follow that array. Windowed rows use the parent Table logical position directly; nondefault startFrom values use full rendering.',
props: [
{
name: 'data',
@@ -39,10 +39,11 @@ export const docs = {
/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */
export const docsDense = {
description:
- 'Returns a TablePlugin that prepends a right-aligned monospaced row-number column. Numbering follows the rendered rows (current sort/filter/page view), 1-based by default. Without data, Table supplies each row position; with data, numbers follow it.',
+ 'Returns a TablePlugin with a right-aligned monospaced row-number column, 1-based by default. Without data, Table supplies positions; with data, ordinary numbers follow it. Windowed rows use the parent logical position, and nondefault startFrom falls back to full rendering.',
propDescriptions: {
- data: 'Optional array whose order the numbers follow; omit to use Table row positions.',
- getRowKey: 'Optional key extractor used with data; otherwise items match by reference.',
+ data: 'Optional array whose order ordinary numbers follow; omit to use Table row positions.',
+ getRowKey:
+ 'Optional key extractor used with data; otherwise items match by reference.',
label: "Header label for the index column. Default '#'.",
startFrom: 'First index value. Default 1.',
},