Skip to content

feat: add opt-in DOM-based column auto sizing - #187

Open
Estasie wants to merge 10 commits into
mainfrom
feat/dom-column-autosize
Open

Estasie wants to merge 10 commits into
mainfrom
feat/dom-column-autosize

Conversation

@Estasie

@Estasie Estasie commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Add opt-in native column sizing through column.width, replacing the meta.autoSize description API. Callers can use CSS grid tracks such as max-content, auto, and minmax(max-content, 1fr), or a fixed pixel width.

const columns: ColumnDef<Row>[] = [
  {accessorKey: 'name', width: 'max-content', minSize: 80, maxSize: 500},
  {accessorKey: 'value', width: 'minmax(max-content, 1fr)', minSize: 80},
];

Measurement and resizing

  • Table measures a hidden DOM snapshot of the mounted header, body and footer on shared CSS grid tracks, then caches numeric widths. It uses the rendered content and styles without mounting a second React tree or requiring an external DOM ref.
  • The live row layout stays unchanged during measurement. This preserves virtualizer row measurements; only mounted content contributes to column sizing.
  • The first measurement waits for real virtualized cells when data is present. Data updates and scrolling preserve cached widths.
  • Viewport resizing and manual sizing changes recalculate flexible columns. Manual widths remain fixed; double-clicking a resize handle measures that column with max-content and stores the result as a manual width.
  • Applied column definitions are memoized, equivalent controlled sizing objects do not trigger remeasurement, and resize observation targets the viewport rather than the potentially overflowing table.

Compatibility

Tables without column.width retain their existing sizing path. The existing experimentalUseColumnsAutoSize hook remains available. The new API uses the library's ColumnDef type; no ColumnMeta augmentation or duplicated text/control descriptions are required.

The measurement lifecycle follows react-data-grid's CSS track sizing and measured/manual width separation. The implementation is adapted to Gravity Table's existing table/flex markup using an isolated snapshot, rather than converting live virtualized rows to CSS grid.

Local validation

  • TypeScript, CJS/ESM builds and all 38 Jest tests pass.
  • Regression tests cover stable column identities, unchanged live layout during measurement, equivalent controlled sizing, cached widths and double-click resizing.
  • Chromium checks cover manual resize, double-click remeasurement and a virtualized fixture with 10,000 rows and 12 columns. The fixture performs one initial measurement and no additional measurements during five parent updates, scrolling or idle time; widths remain stable.
  • The patched Monitoring package passes TypeScript and its three table tests.
  • Changed TypeScript files have no lint errors; documentation warnings remain.

The previously reported dashboard freeze has not yet been reproduced on the specific affected dashboard, so these fixture checks do not establish that it is resolved there.

@gravity-ui-bot

Copy link
Copy Markdown
Contributor

Preview is ready.

@Estasie
Estasie marked this pull request as ready for review November 2, 2026 10:27
@Estasie Estasie changed the title feat: support declarative column auto sizing feat: add opt-in DOM-based column auto sizing Nov 2, 2026
},
};

export const DOMMeasurementRegressionCase: Story = {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this story shouldn’t be displayed on Storybook

@@ -0,0 +1,48 @@
import type {ColumnDef} from '@tanstack/react-table';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The file is called getColumnId, but it contains several different functions. Let’s create one file with the same name for each function in the utils directory


import type {ColumnDef} from '@tanstack/react-table';
import debounce from 'lodash/debounce.js';
import isEqual from 'lodash/isEqual.js';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. [P1] Restored manual widths leave isMeasuring=true indefinitely.
    useColumnsAutoSize.tsx:559

    With initialState.columnSizing: {value: 200}, the column is excluded from measurement, but hasAllWidths only checks automatic and explicitly defined widths. It does not account for manual sizing.

    Reproduction: getSize() returns 200, the automatic width store remains empty, and isMeasuring stays true. Applications that show a loader until measurement finishes never display the table. The readiness check should recognize an authoritative manual width.

  2. [P2] Adding the first DOM column cancels the newly scheduled React measurement.
    useColumnsAutoSize.tsx:483

    When an existing table switches to mixed measurement mode, the layout effect schedules a fallback through the shared calculateWidths function. The previous legacy effect’s cleanup then calls calculateWidths.cancel(), cancelling the newly scheduled task. Since the input snapshot has already been saved, the next render does not restart measurement.

    Confirmed two consequences: adding a DOM column leaves isMeasuring=true, and a fallback column added at the same time never receives a width. Cancellation needs to belong to a particular measurement run; sharing one debounce across these lifecycles is unsafe.

  3. [P2] DOM mode overwrites defaultColumn.minSize.
    setColumnAutoSizes.ts:45

    With autoMinSize=false, the function adds minSize: undefined, even when the original column has no such property. TanStack merges the column definition over defaultColumn, so the shared minimum is lost.

    Confirmed example: defaultColumn: {minSize: 100} combined with a manual width of 50 produces getSize() === 50, whereas it should be clamped to 100. An absent property should remain absent rather than being explicitly assigned undefined.

  4. [P2] The invalidation key does not represent the values actually being measured.
    useColumnsAutoSize.tsx:379, getColumnId.ts:25

    Measurement reads row.getValue(id), while change detection compares {id, original} and an incomplete snapshot of the columns. Two cases were reproduced with measureOnce: false:

    • Changing accessorKey from a to b while retaining the column ID does not trigger measurement because the accessor is missing from the snapshot.
    • In a collapsed group, changing the second child updates the aggregated value, but row.original still represents the first child. In the diagnostic test, the sum changed from 3 to 201, while the width remained unchanged.

    Change detection should track the values consumed by measurement, or all dependencies that determine those values.

  5. [P2] React fallback loses nested accessor values for DOM columns.
    useColumnsAutoSize.tsx:227

    A column with accessorKey: 'profile.name' and meta.autoSize: {} works correctly through DOM measurement. However, a custom React header without autoSize.header sends it through the fallback. The old getValueFromCell helper then reads row.original['profile.name'] instead of row.getValue('profile_name').

    Consequently, body content is skipped and the width is determined by the header. The helper’s limitation predates this branch; the new issue is using it as a fallback for a path with different accessor semantics. DOM-column fallback should retrieve values through the actual TanStack row model.

  6. [P2] Measurement ignores an explicitly supplied whiteSpace style.
    measureDOMColumns.ts:74

    The nested span receives inline white-space: nowrap. This overrides both the parent cell’s style.whiteSpace and ordinary rules from the supplied className.

    Verified in Chromium using the actual table styles: "Hello world" with whiteSpace: 'pre' measures 81 px, while the corresponding cell occupies approximately 120 px. Text containing a newline produces the opposite error—an overestimated width. Explicit whitespace handling must be preserved.

  7. [P2] The built-in virtualization class breaks the measurement DOM.
    measureDOMColumns.ts:111

    Passing measurementClassName: 'gt-table_with-row-virtualization' causes the rules in BaseTable.scss to make measurement body rows absolutely positioned. They stop contributing to their container’s max-content width.

    In Chromium, a short header with long body content produces only the header width. Without a header, the column is deferred while waiting for layout, despite its container being visible. This is a narrower scenario, but the API permits additional table classes. Measurement should normalize row positioning or explicitly restrict the supported classes.

The main architectural concern is the concentration of responsibilities in useColumnsAutoSize.tsx: two measurement strategies, debouncing, cancellation, fonts, observers, invalidation, and state updates. Issue 2 demonstrates a concrete consequence of combining these responsibilities. I would separate the DOM and React measurement lifecycles while sharing the rules for width precedence and applying results.

Regarding file organization, getColumnId.ts handles IDs, metadata, tree traversal, and dependency snapshots. The snapshot logic particularly deserves a separate function with an explicit contract. No export, packaging, or file-placement defects that break the build were found.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've mostly rewrited inner logic, so probably a new review round?

import type * as React from 'react';

import type {ColumnDef, Row} from '@tanstack/react-table';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I’d keep the lifecycle and browser coverage, but consolidate a few overlapping tests and strengthen assertions that currently don’t establish the behavior described by the test name.

Test Suggested change Reason
Basic fallback and debounced fallback Merge The second test covers the first test’s main scenario. The DOM cleanup assertion could be moved into it.
Exactly one render during resize Rewrite or remove An exact React render count couples the test to scheduling details. Prefer checking that resize ticks do not trigger unnecessary measurements or owner notifications, unless the render count is an intentional performance requirement.
Legacy accessor handling Consider removing the duplicate This tests an unchanged helper and repeats legacy behavior already exercised through the hook in legacyCompatibility.test.tsx. The other ID edge cases and recursive sizing checks remain useful.
The legacy measureOnce assertion Rewrite Mutating row.original while keeping the same row ID leaves the legacy effect’s dependencies unchanged. Measurement would not rerun even with measureOnce disabled. Change the sampled row IDs or composition so the test actually exercises the flag’s behavior.
Accounting for extraWidth Strengthen assertions Width is mocked to a constant 100, and the assertion only checks that a second element exists. Removing the application of extraWidth: 24 would still leave the test passing. Assert the spacer’s width or verify its contribution in a browser test.
Browser coverage of different text inputs Keep, but use separate datasets The long string of W characters determines the column’s maximum width and can mask incorrect measurements of other rows. Test whitespace, newlines, and special characters in datasets where each case determines the expected width.

The stale-result, StrictMode, controlled-update, resize-reset, font-loading, and hidden-state recovery tests cover distinct regression risks and should stay. Unit and browser coverage of hidden state also serve different purposes: state transitions versus actual layout and observer behavior.

I’d prioritize these changes alongside regression tests for the identified bugs: initial columnSizing, the legacy → DOM transition, preservation of defaultColumn.minSize, and invalidation when the values being measured change. The goal should be stronger coverage, rather than a particular test count.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants