diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2f172443..e62a3b63 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -63,8 +63,12 @@ jobs: - name: Install Chromium run: npx playwright install --with-deps chromium - name: Build Storybook + env: + STORYBOOK_BROWSER_TESTS: 1 run: npm run build-storybook - name: Run Browser Regressions + env: + STORYBOOK_BROWSER_TESTS: 1 shell: bash run: | set -euo pipefail diff --git a/.storybook/browser-tests/nativeWidths/NativeWidths.stories.tsx b/.storybook/browser-tests/nativeWidths/NativeWidths.stories.tsx new file mode 100644 index 00000000..45daa3ba --- /dev/null +++ b/.storybook/browser-tests/nativeWidths/NativeWidths.stories.tsx @@ -0,0 +1,82 @@ +import * as React from 'react'; + +import {Table} from '../../../src/components'; +import {useRowVirtualizer} from '../../../src/hooks/useRowVirtualizer'; +import {useTable} from '../../../src/hooks/useTable'; +import type {ColumnDef} from '../../../src/types/base'; + +const cases = [ + 'Hello world', + 'Long first line of text\nLong second line of text', + 'Кириллица и длинное значение', + '🛠️ 😀 🛠️ 😀 🛠️ 😀 🛠️ 😀', + '0', +]; +const columns: ColumnDef<{value: string}>[] = [ + { + accessorKey: 'value', + width: 'max-content', + cell: ({getValue}) => ( + + {getValue()} + + ), + }, +]; +function Fixture({ + value, + virtual = false, + initiallyHidden = false, +}: { + value: string; + virtual?: boolean; + initiallyHidden?: boolean; +}) { + const container = React.useRef(null); + const data = React.useMemo( + () => Array.from({length: virtual ? 100 : 1}, () => ({value})), + [value, virtual], + ); + const table = useTable({ + columns, + data, + defaultColumn: {minSize: 100}, + enableColumnResizing: true, + }); + const virtualizer = useRowVirtualizer({ + count: data.length, + estimateSize: () => 32, + getScrollElement: () => container.current, + overscan: 2, + }); + return ( +
+ + + ); +} +function Regression() { + return ( +
+ {cases.map((value) => ( + + ))} + + +
+ ); +} +export default {title: 'Browser tests/Native widths', tags: ['browser-regression', '!autodocs']}; +export const Layout = {render: () => }; diff --git a/.storybook/browser-tests/nativeWidths/testNativeWidths.ts b/.storybook/browser-tests/nativeWidths/testNativeWidths.ts new file mode 100644 index 00000000..7b4bea56 --- /dev/null +++ b/.storybook/browser-tests/nativeWidths/testNativeWidths.ts @@ -0,0 +1,58 @@ +import type {TestRunnerConfig} from '@storybook/test-runner'; +type Page = Parameters>[0]; +export async function testNativeWidths(page: Page) { + await page.waitForFunction( + () => document.querySelectorAll('[data-qa="native-fixture"] td').length >= 6, + ); + await page.waitForTimeout(50); + await page + .locator('[data-qa="native-fixture"] table[hidden]') + .evaluateAll((tables) => tables.forEach((table) => table.removeAttribute('hidden'))); + const verify = async () => { + await page.waitForFunction(() => + Array.from(document.querySelectorAll('[data-qa="native-fixture"]')).every((fixture) => { + const cell = fixture.querySelector('td'); + const text = cell?.querySelector('[data-qa="native-text"]'); + if (!cell || !text) return false; + const style = getComputedStyle(cell); + const expected = Math.max( + 100, + text.getBoundingClientRect().width + + parseFloat(style.paddingLeft) + + parseFloat(style.paddingRight), + ); + const actual = parseFloat(style.width); + return Math.abs(expected - actual) < 2; + }), + ); + }; + await verify(); + const initial = await page + .locator('[data-qa="native-fixture"] td') + .evaluateAll((cells) => cells.map((cell) => getComputedStyle(cell).width)); + // Hide only tables: parent viewport dimensions stay unchanged. + await page.locator('[data-qa="native-fixture"] table').evaluateAll((tables) => + tables.forEach((table) => { + (table as HTMLElement).style.display = 'none'; + }), + ); + await page.waitForTimeout(50); + await page.locator('[data-qa="native-fixture"] table').evaluateAll((tables) => + tables.forEach((table) => { + (table as HTMLElement).style.display = ''; + }), + ); + await verify(); + await page.locator('[data-qa="native-fixture"]').evaluateAll((fixtures) => + fixtures.forEach((fixture) => { + (fixture as HTMLElement).style.transform = 'scale(.5)'; + (fixture as HTMLElement).style.width = '620px'; + }), + ); + await page.waitForTimeout(100); + const scaled = await page + .locator('[data-qa="native-fixture"] td') + .evaluateAll((cells) => cells.map((cell) => getComputedStyle(cell).width)); + if (JSON.stringify(initial) !== JSON.stringify(scaled)) + throw new Error('Scale changed native column widths'); +} diff --git a/.storybook/main.ts b/.storybook/main.ts index f09a0a6d..af0a6cd3 100644 --- a/.storybook/main.ts +++ b/.storybook/main.ts @@ -23,7 +23,13 @@ const config: StorybookConfig = { '@storybook/addon-webpack5-compiler-babel', ], framework: '@storybook/react-webpack5', - stories: ['../src/**/*.mdx', '../src/**/*.stories.@(ts|tsx)'], + stories: [ + '../src/**/*.mdx', + '../src/**/*.stories.@(ts|tsx)', + ...(process.env.STORYBOOK_BROWSER_TESTS === '1' + ? ['./browser-tests/**/*.stories.tsx'] + : []), + ], typescript: { reactDocgen: 'react-docgen-typescript', }, diff --git a/.storybook/test-runner.ts b/.storybook/test-runner.ts index caa4f496..b718d1df 100644 --- a/.storybook/test-runner.ts +++ b/.storybook/test-runner.ts @@ -1,6 +1,7 @@ import type {TestRunnerConfig} from '@storybook/test-runner'; import {toMatchImageSnapshot} from 'jest-image-snapshot'; +import {testNativeWidths} from './browser-tests/nativeWidths/testNativeWidths'; import {testAdaptiveVirtualization} from './browser-tests/testAdaptiveVirtualization/testAdaptiveVirtualization'; import {testVirtualizedTreeReordering} from './browser-tests/testVirtualizedTreeReordering/testVirtualizedTreeReordering'; @@ -13,6 +14,10 @@ const config: TestRunnerConfig = { expect.extend({toMatchImageSnapshot}); }, async postVisit(page, context) { + if (context.id === 'browser-tests-native-widths--layout') { + await testNativeWidths(page); + return; + } if (context.id === ADAPTIVE_VIRTUALIZATION_STORY) { await testAdaptiveVirtualization(page); return; diff --git a/src/components/BaseCell/BaseCell.tsx b/src/components/BaseCell/BaseCell.tsx index 9921d608..e520c67a 100644 --- a/src/components/BaseCell/BaseCell.tsx +++ b/src/components/BaseCell/BaseCell.tsx @@ -8,8 +8,10 @@ import {b} from '../BaseTable/BaseTable.classname'; import {areMemoizedCellPropsEqual} from './utils/areMemoizedCellPropsEqual'; -export interface BaseCellProps - extends Omit, 'className'> { +export interface BaseCellProps extends Omit< + React.TdHTMLAttributes, + 'className' +> { cell?: Cell; className?: string | ((cell?: Cell) => string); attributes?: @@ -48,6 +50,7 @@ const BaseCellComponent = ({ className={b('cell', getCellClassModes(cell), className)} {...restProps} {...attributes} + data-column-id={cell?.column.id} data-virtualization-cell-content={deferContent ? 'deferred' : undefined} style={getCellStyles(cell, {...style, ...attributes?.style})} > diff --git a/src/components/BaseFooterCell/BaseFooterCell.tsx b/src/components/BaseFooterCell/BaseFooterCell.tsx index 1d3d6ccf..6fe13588 100644 --- a/src/components/BaseFooterCell/BaseFooterCell.tsx +++ b/src/components/BaseFooterCell/BaseFooterCell.tsx @@ -32,6 +32,9 @@ export const BaseFooterCell = ({ colSpan={header.colSpan > 1 ? header.colSpan : undefined} rowSpan={rowSpan > 1 ? rowSpan : undefined} {...attributes} + data-column-id={ + header.colSpan === 1 && !header.isPlaceholder ? header.column.id : undefined + } style={getCellStyles(header, attributes?.style)} > {flexRender(header.column.columnDef.footer, header.getContext())} diff --git a/src/components/BaseHeaderCell/BaseHeaderCell.tsx b/src/components/BaseHeaderCell/BaseHeaderCell.tsx index 1b087f9b..635d72da 100644 --- a/src/components/BaseHeaderCell/BaseHeaderCell.tsx +++ b/src/components/BaseHeaderCell/BaseHeaderCell.tsx @@ -18,8 +18,7 @@ import {b} from '../BaseTable/BaseTable.classname'; export interface BaseHeaderCellProps { className?: - | string - | ((header: Header, parentHeader?: Header) => string); + string | ((header: Header, parentHeader?: Header) => string); header: Header; parentHeader?: Header; renderHeaderCellContent?: (props: {header: Header}) => React.ReactNode; @@ -114,6 +113,9 @@ export const BaseHeaderCell = React.forwardRef( aria-sort={getAriaSort(header.column.getIsSorted())} aria-colindex={getHeaderCellAriaColIndex(header)} {...attributes} + data-column-id={ + header.colSpan === 1 && !header.isPlaceholder ? header.column.id : undefined + } style={getCellStyles(header, attributes?.style)} > {renderContent()} diff --git a/src/components/BaseResizeHandle/BaseResizeHandle.tsx b/src/components/BaseResizeHandle/BaseResizeHandle.tsx index 58188f06..bf40404f 100644 --- a/src/components/BaseResizeHandle/BaseResizeHandle.tsx +++ b/src/components/BaseResizeHandle/BaseResizeHandle.tsx @@ -1,4 +1,5 @@ import type {Header} from '../../types/base'; +import {autoSizeColumn} from '../BaseTable/hooks/useColumnWidths'; import {b} from './BaseResizeHandle.classname'; @@ -28,7 +29,9 @@ export const BaseResizeHandle = ({ }, className, )} - onDoubleClick={() => header.column.resetSize()} + onDoubleClick={() => { + if (!autoSizeColumn(table, header.column.id)) header.column.resetSize(); + }} onMouseDown={header.getResizeHandler()} onTouchStart={header.getResizeHandler()} style={{ diff --git a/src/components/BaseTable/BaseTable.tsx b/src/components/BaseTable/BaseTable.tsx index 12562702..46a7682e 100644 --- a/src/components/BaseTable/BaseTable.tsx +++ b/src/components/BaseTable/BaseTable.tsx @@ -1,5 +1,6 @@ import * as React from 'react'; +import {useForkRef} from '@gravity-ui/uikit'; import type {QAProps} from '@gravity-ui/uikit'; import type {Row, Table} from '@tanstack/react-table'; import type {VirtualItem, Virtualizer} from '@tanstack/react-virtual'; @@ -18,13 +19,16 @@ import {LastSelectedRowContextProvider} from '../LastSelectedRowContext'; import {SortableListContext} from '../SortableListContext'; import {b} from './BaseTable.classname'; +import {useColumnWidths} from './hooks/useColumnWidths'; import {useTableVirtualization} from './hooks/useTableVirtualization'; import type {CanDeferOffscreenCellContent} from './types'; import './BaseTable.scss'; -export interface BaseTableProps - extends QAProps { +export interface BaseTableProps< + TData, + TScrollElement extends Element | Window = HTMLDivElement, +> extends QAProps { /** The table instance returned from the `useTable` hook */ table: Table; /** HTML attributes for the `
` element */ @@ -175,6 +179,8 @@ export const BaseTable = React.forwardRef( }: BaseTableProps, ref: React.Ref, ) => { + const {tableRef} = useColumnWidths(table); + const resolvedTableRef = useForkRef(tableRef, ref); const draggableContext = React.useContext(SortableListContext); const columnReorderingContext = React.useContext(ColumnReorderingContext); const draggingRowIndex = draggableContext?.activeItemIndex ?? -1; @@ -302,7 +308,7 @@ export const BaseTable = React.forwardRef( return (
-1 ? draggingRowIndex : undefined} data-column-drag-active={isColumnDragActive || undefined} diff --git a/src/components/BaseTable/hooks/useColumnWidths.test.tsx b/src/components/BaseTable/hooks/useColumnWidths.test.tsx new file mode 100644 index 00000000..4237c8cf --- /dev/null +++ b/src/components/BaseTable/hooks/useColumnWidths.test.tsx @@ -0,0 +1,126 @@ +/* eslint-disable testing-library/no-node-access -- Verify native track measurements and style restoration. */ +import * as React from 'react'; + +import {act, fireEvent, render, screen} from '@testing-library/react'; + +import {useTable} from '../../../hooks/useTable'; +import type {ColumnDef} from '../../../types/base'; +import {BaseTable} from '../BaseTable'; + +const columns: ColumnDef<{value: string}>[] = [ + {accessorKey: 'value', header: 'Value', width: 'max-content', minSize: 50}, +]; +let intrinsicWidth = 100; +const readWidth = jest.fn(); +let table: ReturnType>; +function Example({ + value = 'short', + controlled = false, + empty = false, +}: { + value?: string; + controlled?: boolean; + empty?: boolean; +}) { + const data = React.useMemo(() => (empty ? [] : [{value}]), [value, empty]); + table = useTable({ + columns, + data, + enableColumnResizing: true, + ...(controlled ? {state: {columnSizing: {}}} : {}), + }); + return ; +} +beforeEach(() => { + intrinsicWidth = 100; + readWidth.mockClear(); + jest.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockImplementation(function ( + this: HTMLElement, + ) { + return this.getBoundingClientRect().width; + }); + jest.spyOn(HTMLElement.prototype, 'getClientRects').mockImplementation(function ( + this: HTMLElement, + ) { + return (this.isConnected ? [{}] : []) as unknown as DOMRectList; + }); + jest.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function ( + this: HTMLElement, + ) { + if (this.dataset.measuringCellKey) { + readWidth(); + const liveTable = this.ownerDocument.querySelector( + 'table:not([aria-hidden])', + ) as HTMLElement; + expect(liveTable.style.display).not.toBe('grid'); + expect(this.closest('table')?.getAttribute('aria-hidden')).toBe('true'); + } + return {width: this.dataset.measuringCellKey ? intrinsicWidth : 600} as DOMRect; + }); +}); +afterEach(() => jest.restoreAllMocks()); + +test('caches measured tracks across data updates and restores live table styles', () => { + const {rerender} = render(); + const cell = screen.getByRole('cell'); + const previousColumns = table.getAllLeafColumns(); + expect(cell.style.width).toBe('100px'); + intrinsicWidth = 250; + rerender(); + expect(table.getAllLeafColumns()).toBe(previousColumns); + expect(cell.style.width).toBe('100px'); + expect(cell.style.gridColumn).toBe(''); + expect(screen.getByRole('table').style.display).toBe(''); + const probes = screen.getByRole('table').querySelectorAll('[data-measuring-cell-key]'); + expect(probes).toHaveLength(0); +}); +test('keeps manually resized widths and double click stores a new max-content width', () => { + render(); + act(() => table.setColumnSizing({value: 180})); + expect(screen.getByRole('cell').style.width).toBe('180px'); + intrinsicWidth = 220; + const handle = screen.getByRole('columnheader').querySelector('[class*="resize-handle"]'); + expect(handle).not.toBeNull(); + fireEvent.doubleClick(handle as Element); + expect(screen.getByRole('cell').style.width).toBe('220px'); + expect(table.getState().columnSizing.value).toBe(220); +}); + +test('does not remeasure when a controlled owner recreates equivalent sizing state', () => { + const {rerender} = render(); + const before = readWidth.mock.calls.length; + rerender(); + expect(readWidth).toHaveBeenCalledTimes(before); +}); + +test('replaces header-only widths when the first rows arrive', () => { + const {rerender} = render(); + expect(table.getColumn('value')?.getSize()).toBe(100); + intrinsicWidth = 250; + rerender(); + expect(table.getColumn('value')?.getSize()).toBe(250); +}); + +test('resetting a manual width measures current content', () => { + render(); + act(() => table.setColumnSizing({value: 180})); + intrinsicWidth = 250; + act(() => table.setColumnSizing({})); + expect(table.getColumn('value')?.getSize()).toBe(250); +}); + +test('font loading refreshes native widths', () => { + const descriptor = Object.getOwnPropertyDescriptor(document, 'fonts'); + const fonts = Object.assign(new EventTarget(), {status: 'loaded', ready: Promise.resolve()}); + Object.defineProperty(document, 'fonts', {configurable: true, value: fonts}); + try { + const {unmount} = render(); + intrinsicWidth = 250; + act(() => fonts.dispatchEvent(new Event('loadingdone'))); + expect(table.getColumn('value')?.getSize()).toBe(250); + unmount(); + } finally { + if (descriptor) Object.defineProperty(document, 'fonts', descriptor); + else Reflect.deleteProperty(document, 'fonts'); + } +}); diff --git a/src/components/BaseTable/hooks/useColumnWidths.ts b/src/components/BaseTable/hooks/useColumnWidths.ts new file mode 100644 index 00000000..520f410d --- /dev/null +++ b/src/components/BaseTable/hooks/useColumnWidths.ts @@ -0,0 +1,181 @@ +import * as React from 'react'; + +import type {Table} from '@tanstack/react-table'; +import {flushSync} from 'react-dom'; + +import {useIsomorphicLayoutEffect} from '../../../hooks/useIsomorphicLayoutEffect'; +import type {ColumnDef} from '../../../types/base'; +import {getLeafColumnDefinitions} from '../utils/getLeafColumnDefinitions'; +import {getNativeColumnId} from '../utils/getNativeColumnId'; +import {measureGridColumns} from '../utils/measureGridColumns'; + +const autoSizeHandlers = new WeakMap void>(); + +/** @internal */ +export function autoSizeColumn(table: object, id: string): boolean { + const handler = autoSizeHandlers.get(table); + if (!handler) return false; + handler(id); + return true; +} + +/** Native track measurement follows react-data-grid's measured/resized width lifecycle. */ +export function useColumnWidths(table: Table) { + const tableRef = React.useRef(null); + const [measured, setMeasured] = React.useState>({}); + const [autoResize, setAutoResize] = React.useState(null); + const [, retryLayout] = React.useReducer((n: number) => n + 1, 0); + const [gridWidth, setGridWidth] = React.useState(0); + const source = React.useRef({columns: table.options.columns, applied: table.options.columns}); + if (table.options.columns !== source.current.applied) + source.current.columns = table.options.columns; + const columns = source.current.columns as ColumnDef[]; + const leaves = getLeafColumnDefinitions(columns); + const enabled = leaves.some((column) => column.width !== undefined); + const sizing = table.getState().columnSizing; + const [fontRevision, refreshFonts] = React.useReducer((n: number) => n + 1, 0); + const headerOnly = React.useRef(new Set()); + const previous = React.useRef({gridWidth, sizing, fontRevision, tracksKey: ''}); + const applied = React.useMemo(() => { + if (!enabled) return columns; + const apply = (defs: ColumnDef[]): ColumnDef[] => + defs.map((column) => { + if ('columns' in column && column.columns) + return {...column, columns: apply(column.columns)}; + const id = getNativeColumnId(column); + const size = typeof column.width === 'number' ? column.width : measured[id]; + return size === undefined ? column : {...column, size}; + }); + return apply(columns); + }, [columns, enabled, measured]); + if (enabled) { + source.current.applied = applied; + if (table.options.columns !== applied) + table.setOptions((current) => ({...current, columns: applied})); + } + + useIsomorphicLayoutEffect(() => { + if (!enabled) return undefined; + const element = tableRef.current; + if (!element) return undefined; + let wasVisible = element.getClientRects().length > 0; + const observer = + typeof ResizeObserver === 'function' + ? new ResizeObserver(() => { + const width = (element.parentElement ?? element).clientWidth; + const visible = element.getClientRects().length > 0; + if (visible && !wasVisible) retryLayout(); + wasVisible = visible; + setGridWidth((current) => + Math.abs(current - width) < 0.5 ? current : width, + ); + }) + : undefined; + // A table can overflow its viewport. Its intrinsic width must not become + // an input to its next measurement (a resize feedback loop). + observer?.observe(element.parentElement ?? element); + // The table may be hidden while its parent keeps the same dimensions. + observer?.observe(element); + const fonts = element.ownerDocument.fonts; + let active = true; + let pendingFonts = fonts?.status === 'loading'; + const onFonts = () => { + if (!active || fonts?.status === 'loading') return; + pendingFonts = false; + refreshFonts(); + }; + fonts?.addEventListener('loadingdone', onFonts); + fonts?.ready.then(() => { + if (pendingFonts) onFonts(); + }); + autoSizeHandlers.set(table, (id) => flushSync(() => setAutoResize(id))); + return () => { + active = false; + fonts?.removeEventListener('loadingdone', onFonts); + observer?.disconnect(); + autoSizeHandlers.delete(table); + }; + }, [enabled, table]); + + useIsomorphicLayoutEffect(() => { + if (!enabled || !tableRef.current) return; + // The virtualizer realizes its first rows after it learns the viewport. + // Do not permanently cache header-only widths while actual data is pending. + if ( + table.getRowModel().rows.length && + !tableRef.current.tBodies[0]?.querySelector( + '[data-column-id]:not([data-virtualization-cell-content="deferred"])', + ) + ) + return; + const visible = table.getVisibleLeafColumns(); + const last = previous.current; + const hasRows = table.getRowModel().rows.length > 0; + const tracksKey = JSON.stringify( + visible.map((column) => { + const definition = leaves.find((leaf) => getNativeColumnId(leaf) === column.id); + return [ + column.id, + definition?.width, + definition?.size, + column.columnDef.minSize, + column.columnDef.maxSize, + ]; + }), + ); + const changed = tracksKey !== last.tracksKey || fontRevision !== last.fontRevision; + const resized = + Object.keys(sizing).length !== Object.keys(last.sizing).length || + Object.keys(sizing).some((id) => sizing[id] !== last.sizing[id]); + const viewportWidth = gridWidth || tableRef.current.parentElement?.clientWidth || 0; + const widthChanged = Math.abs(viewportWidth - last.gridWidth) >= 0.5; + const pending = new Set(); + const tracks = visible.map((column) => { + const definition = leaves.find((leaf) => getNativeColumnId(leaf) === column.id); + const width = + definition?.width ?? (definition?.size === undefined ? 'auto' : definition.size); + if (column.id === autoResize) { + pending.add(column.id); + return 'max-content'; + } + if (sizing[column.id] !== undefined) return `${column.getSize()}px`; + if (typeof width === 'number') return `${width}px`; + if ( + changed || + widthChanged || + (resized && width !== 'max-content' && width !== 'min-content') || + (last.sizing[column.id] !== undefined && sizing[column.id] === undefined) || + (hasRows && headerOnly.current.has(column.id)) || + measured[column.id] === undefined + ) { + pending.add(column.id); + return width; + } + return `${measured[column.id]}px`; + }); + if (!pending.size) { + previous.current = {gridWidth: viewportWidth, sizing, fontRevision, tracksKey}; + return; + } + const widths = measureGridColumns(tableRef.current, visible, tracks, viewportWidth); + if (!widths) return; + previous.current = {gridWidth: viewportWidth, sizing, fontRevision, tracksKey}; + for (const id of pending) { + if (widths[id] === undefined) continue; + if (hasRows) headerOnly.current.delete(id); + else headerOnly.current.add(id); + } + setMeasured((current) => { + const next = {...current}; + for (const id of pending) if (widths[id] !== undefined) next[id] = widths[id]; + return Object.keys(next).every((id) => next[id] === current[id]) ? current : next; + }); + if (autoResize !== null) { + const width = widths[autoResize]; + if (width !== undefined) + table.setColumnSizing((current) => ({...current, [autoResize]: width})); + setAutoResize(null); + } + }); + return {tableRef}; +} diff --git a/src/components/BaseTable/utils/getLeafColumnDefinitions.ts b/src/components/BaseTable/utils/getLeafColumnDefinitions.ts new file mode 100644 index 00000000..a955c147 --- /dev/null +++ b/src/components/BaseTable/utils/getLeafColumnDefinitions.ts @@ -0,0 +1,7 @@ +import type {ColumnDef} from '../../../types/base'; + +export function getLeafColumnDefinitions(columns: ColumnDef[]): ColumnDef[] { + return columns.flatMap((column) => + 'columns' in column && column.columns ? getLeafColumnDefinitions(column.columns) : [column], + ); +} diff --git a/src/components/BaseTable/utils/getNativeColumnId.ts b/src/components/BaseTable/utils/getNativeColumnId.ts new file mode 100644 index 00000000..2fdde629 --- /dev/null +++ b/src/components/BaseTable/utils/getNativeColumnId.ts @@ -0,0 +1,12 @@ +import type {ColumnDef} from '../../../types/base'; + +export function getNativeColumnId(column: ColumnDef): string { + return ( + column.id ?? + ('accessorKey' in column + ? String(column.accessorKey).replace(/\./g, '_') + : typeof column.header === 'string' + ? column.header + : '') + ); +} diff --git a/src/components/BaseTable/utils/measureGridColumns.ts b/src/components/BaseTable/utils/measureGridColumns.ts new file mode 100644 index 00000000..8772c643 --- /dev/null +++ b/src/components/BaseTable/utils/measureGridColumns.ts @@ -0,0 +1,99 @@ +import type {Column} from '@tanstack/react-table'; + +/** Lay out a detached DOM snapshot on shared CSS grid tracks before paint. + * Empty measuring cells read track widths, exactly as in react-data-grid. + * @returns Measured widths, or undefined for a hidden/detached table. + */ +export function measureGridColumns( + table: HTMLTableElement, + columns: Column[], + tracks: string[], + viewportWidth?: number, +): Record | undefined { + if (!table.isConnected || !table.getClientRects().length) return undefined; + // Never switch the live virtualized rows between flex and grid layouts: + // doing so invalidates row measurements and can trigger resize feedback. + const snapshot = table.cloneNode(true) as HTMLTableElement; + snapshot.setAttribute('aria-hidden', 'true'); + snapshot.inert = true; + snapshot.removeAttribute('id'); + for (const element of Array.from(snapshot.querySelectorAll('[id]'))) + element.removeAttribute('id'); + const write = (element: HTMLElement, style: Partial) => { + Object.assign(element.style, style); + }; + const probes: HTMLElement[] = []; + try { + write(snapshot, { + position: 'fixed', + left: '0', + top: '0', + visibility: 'hidden', + pointerEvents: 'none', + contain: 'layout style', + width: `${viewportWidth || table.parentElement?.clientWidth || table.clientWidth}px`, + boxSizing: 'border-box', + display: 'grid', + gridTemplateColumns: tracks.join(' '), + alignContent: 'start', + }); + for (const section of [snapshot.tHead, ...Array.from(snapshot.tBodies), snapshot.tFoot]) { + if (section) write(section, {display: 'contents'}); + } + for (const [index, row] of Array.from(snapshot.rows).entries()) { + write(row, {display: 'contents', position: 'static', transform: 'none'}); + let start = 1; + for (const cell of Array.from(row.cells)) { + const id = cell.dataset.columnId; + const columnIndex = columns.findIndex((column) => column.id === id); + if (columnIndex >= 0) start = columnIndex + 1; + const column = columns[columnIndex]; + write(cell, { + display: 'block', + position: 'relative', + width: 'auto', + inlineSize: 'auto', + minWidth: `${column?.columnDef.minSize ?? 50}px`, + maxWidth: + column?.columnDef.maxSize === undefined + ? 'none' + : `${column.columnDef.maxSize}px`, + gridColumn: `${start} / span ${cell.colSpan}`, + gridRow: String(index + 2), + contain: 'none', + }); + start += cell.colSpan; + } + } + for (const [index, column] of columns.entries()) { + const probe = table.ownerDocument.createElement('div'); + Object.assign(probe.style, { + gridColumn: String(index + 1), + gridRow: '1', + visibility: 'hidden', + contain: 'strict', + minWidth: `${column.columnDef.minSize ?? 50}px`, + maxWidth: + column.columnDef.maxSize === undefined + ? 'none' + : `${column.columnDef.maxSize}px`, + }); + probe.dataset.measuringCellKey = column.id; + probes.push(probe); + snapshot.append(probe); + } + table.parentElement?.append(snapshot); + const widths: Record = {}; + for (const [index, probe] of probes.entries()) { + // CSS layout widths do not include transforms on ancestor elements. + const width = + Number.parseFloat( + table.ownerDocument.defaultView?.getComputedStyle(probe).width ?? '', + ) || probe.offsetWidth; + if (width > 0) widths[columns[index].id] = width; + } + return widths; + } finally { + snapshot.remove(); + } +} diff --git a/src/hooks/useColumnsAutoSize/README.md b/src/hooks/useColumnsAutoSize/README.md index 90d09316..48775420 100644 --- a/src/hooks/useColumnsAutoSize/README.md +++ b/src/hooks/useColumnsAutoSize/README.md @@ -241,3 +241,29 @@ TanStack `columnSizing` and predefined widths retain priority over auto widths. Callbacks are emitted for changes, not simply because the table mounts or a callback prop changes. The callback requests an update in controlled mode: only new `columnWidths` props change the rendered widths. + +## Native CSS column sizing + +For react-data-grid style sizing, specify `width` on the column definitions +(import `ColumnDef` from `@gravity-ui/table`, rather than TanStack): + +```tsx +const columns: ColumnDef[] = [ + {accessorKey: 'name', header: 'Name', width: 'max-content', minSize: 80, maxSize: 500}, + {accessorKey: 'value', header: 'Value', width: 'minmax(max-content, 1fr)', minSize: 80}, +]; +const table = useTable({columns, data, enableColumnResizing: true}); +return
; +``` + +No autosize hook or external DOM ref is required. The table lays out a hidden DOM snapshot of its mounted +header, body and footer cells on shared CSS grid tracks before paint, reads the +track widths through empty measuring cells, then caches numeric sizes. +The live row layout is preserved during measurement. Only mounted content contributes. Changing data or scrolling preserves cached +widths. The first rows after an empty result, font loading, changes to visible +track definitions, and resetting a manual width trigger a fresh measurement. +Resizing the table or another column recalculates flexible tracks; intrinsic +`max-content` / `min-content` tracks retain their widths when a neighboring +column is resized; +manual sizes remain fixed. Double-click a resize handle to measure that column +with `max-content` again and store the result as a manual size. diff --git a/src/hooks/useColumnsAutoSize/__stories__/NativeColumnWidths.tsx b/src/hooks/useColumnsAutoSize/__stories__/NativeColumnWidths.tsx new file mode 100644 index 00000000..8a276e40 --- /dev/null +++ b/src/hooks/useColumnsAutoSize/__stories__/NativeColumnWidths.tsx @@ -0,0 +1,86 @@ +import * as React from 'react'; + +import {Table} from '../../../components'; +import type {ColumnDef} from '../../../types/base'; +import {useRowVirtualizer} from '../../useRowVirtualizer'; +import {useTable} from '../../useTable'; + +const columns: ColumnDef<{name: string; value: number}>[] = [ + {accessorKey: 'name', header: 'Name', width: 'max-content', minSize: 50, maxSize: 500}, + {accessorKey: 'value', header: 'Value', width: 'minmax(max-content, 1fr)', minSize: 50}, +]; +export function NativeColumnWidths() { + const [long, setLong] = React.useState(false); + const data = React.useMemo( + () => [ + {name: long ? 'A much longer name for the autosize regression' : 'Name', value: 123}, + ], + [long], + ); + const table = useTable({ + columns, + data, + enableColumnResizing: true, + columnResizeMode: 'onChange', + }); + return ( +
+ +
+ + ); +} + +const virtualColumns: ColumnDef>[] = Array.from( + {length: 12}, + (_, index) => ({ + id: String(index), + accessorFn: (row) => row[String(index)], + header: `Column ${index}`, + width: index === 11 ? 'minmax(max-content, 1fr)' : 'max-content', + minSize: 80, + maxSize: index === 11 ? undefined : 500, + }), +); +const virtualData = Array.from({length: 10000}, (_, index) => + Object.fromEntries( + virtualColumns.map(({id}) => [id ?? '', `${index}: value for column ${id}`]), + ), +); +export function VirtualizedNativeColumnWidths() { + const [tick, setTick] = React.useState(0); + const containerRef = React.useRef(null); + // Fresh, equivalent column definitions model a dashboard widget's parent updates. + const table = useTable({ + data: virtualData, + columns: virtualColumns.map((column) => ({...column})), + enableColumnResizing: true, + columnResizeMode: 'onChange', + }); + const virtualizer = useRowVirtualizer({ + count: virtualData.length, + estimateSize: () => 32, + getScrollElement: () => containerRef.current, + overscan: 5, + }); + return ( +
+ +
+
+ + + ); +} diff --git a/src/hooks/useColumnsAutoSize/__stories__/useColumnsAutoSize.stories.tsx b/src/hooks/useColumnsAutoSize/__stories__/useColumnsAutoSize.stories.tsx index 50dacdf1..a09db8ec 100644 --- a/src/hooks/useColumnsAutoSize/__stories__/useColumnsAutoSize.stories.tsx +++ b/src/hooks/useColumnsAutoSize/__stories__/useColumnsAutoSize.stories.tsx @@ -2,6 +2,10 @@ import type {Meta, StoryObj} from '@storybook/react'; import {AutoSizedTable} from './AutoSizedTable'; import {MeasureOnceColumnsChangeTable} from './MeasureOnceColumnsChangeTable'; +import { + NativeColumnWidths as NativeColumnWidthsExample, + VirtualizedNativeColumnWidths, +} from './NativeColumnWidths'; import {TableWithDynamicData} from './TableWithDynamicData'; import {columns} from './constants/columns'; import {columnsWithComplexComponents} from './constants/columnsWithComplexComponents'; @@ -180,3 +184,9 @@ export const MeasureOnceColumnsChange: Story = { }, }, }; + +export const NativeColumnWidths: Story = {render: () => }; + +export const VirtualizedNativeColumnSizing: Story = { + render: () => , +}; diff --git a/src/types/base.ts b/src/types/base.ts index dca86986..137a7ed2 100644 --- a/src/types/base.ts +++ b/src/types/base.ts @@ -9,6 +9,10 @@ import type { } from '@tanstack/react-table'; export type ColumnDef = BaseColumnDef & { + /** CSS grid track width, e.g. 'max-content', 'auto' or 'minmax(max-content, 1fr)'. + * Numeric widths are fixed pixels. CSS widths enable native column measurement. + */ + width?: number | string; /* Show indents depending on row depth */ withNestingStyles?: boolean; /* Show vertical lines indicating depth in tree */ @@ -25,19 +29,25 @@ export type DefinedColumnDef = Omit< id: string; }; -export interface Column - extends Omit, 'columnDef' | 'columns'> { +export interface Column extends Omit< + BaseColumn, + 'columnDef' | 'columns' +> { columnDef: ColumnDef; columns: Column[]; } -export interface Cell - extends Omit, 'column'> { +export interface Cell extends Omit< + BaseCell, + 'column' +> { column: Column; } -export interface Header - extends Omit, 'column'> { +export interface Header extends Omit< + BaseHeader, + 'column' +> { column: Column; } @@ -45,8 +55,10 @@ export type HeaderGroup = Omit, 'h headers: Header[]; }; -interface PassedTableOptions - extends Omit, 'getCoreRowModel' | 'columns'> { +interface PassedTableOptions extends Omit< + TableOptions, + 'getCoreRowModel' | 'columns' +> { getCoreRowModel?: TableOptions['getCoreRowModel']; columns: ColumnDef[]; }