From da6217bd9fd95913435baf7a7030855338f51a69 Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:39:40 +0000 Subject: [PATCH 1/3] feat(app): double-click a column's resize handle to fit it to its content Double-clicking the resize handle on a search results column sets the column to the width of its widest rendered cell, header included, so it gets narrower or wider to match what it shows. A fitted column stops at 600px or half the visible table width, whichever is smaller. The last column already fills the space the others leave, so double-clicking it clears a dragged width and it fills the table again. The fitted width is saved and reset like a dragged one. Clearing the last column's width needs the column sizing handler to apply TanStack's updater to the stored sizes. It called the updater with no previous state and merged the result in, so a stored size could never be removed. The handler is now typed without `any`. Co-Authored-By: Claude Opus 5.5 --- .changeset/column-fit-to-content.md | 7 + packages/app/src/components/DBRowTable.tsx | 42 ++++- .../src/components/DBTable/TableHeader.tsx | 11 ++ .../DBTable/__tests__/columnFit.test.ts | 136 +++++++++++++++ .../app/src/components/DBTable/columnFit.ts | 72 ++++++++ .../components/__tests__/DBRowTable.test.tsx | 155 ++++++++++++++++++ .../tests/e2e/components/TableComponent.ts | 64 ++++++++ .../e2e/features/search/column-fit.spec.ts | 90 ++++++++++ 8 files changed, 570 insertions(+), 7 deletions(-) create mode 100644 .changeset/column-fit-to-content.md create mode 100644 packages/app/src/components/DBTable/__tests__/columnFit.test.ts create mode 100644 packages/app/src/components/DBTable/columnFit.ts create mode 100644 packages/app/tests/e2e/features/search/column-fit.spec.ts diff --git a/.changeset/column-fit-to-content.md b/.changeset/column-fit-to-content.md new file mode 100644 index 0000000000..4034dbeaf9 --- /dev/null +++ b/.changeset/column-fit-to-content.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/app': patch +--- + +feat: double-click a column's resize handle in search results to fit the column +to its content. A fitted column stops at 600px or half the visible table width, +and the last column goes back to filling the table. diff --git a/packages/app/src/components/DBRowTable.tsx b/packages/app/src/components/DBRowTable.tsx index 8336204cd0..a4cbfc068f 100644 --- a/packages/app/src/components/DBRowTable.tsx +++ b/packages/app/src/components/DBRowTable.tsx @@ -4,6 +4,7 @@ import React, { useCallback, useEffect, useMemo, + useRef, useState, } from 'react'; import cx from 'classnames'; @@ -61,11 +62,14 @@ import { FetchNextPageOptions } from '@tanstack/react-query'; import { ColumnDef, ColumnResizeMode, + ColumnSizingState, flexRender, + functionalUpdate, getCoreRowModel, Row as TableRow, SortingState, TableOptions, + Updater, useReactTable, } from '@tanstack/react-table'; import { useVirtualizer } from '@tanstack/react-virtual'; @@ -120,6 +124,10 @@ import ChartErrorState, { ChartErrorStateVariant, } from './charts/ChartErrorState'; import { getAdhocCellCondition } from './DBTable/adhocCellCondition'; +import { + getFittedColumnWidth, + measureColumnContentWidth, +} from './DBTable/columnFit'; import DBRowTableFieldWithPopover from './DBTable/DBRowTableFieldWithPopover'; import DBRowTableRowButtons from './DBTable/DBRowTableRowButtons'; import { @@ -516,6 +524,7 @@ export const RawLogTable = memo( }, [], ); + const tableRef = useRef(null); const [containerWidth, setContainerWidth] = useState(0); useEffect(() => { @@ -798,13 +807,8 @@ export const RawLogTable = memo( }, [fetchMoreOnBottomReached, tableContainerRef]); const reactTableProps = useMemo((): TableOptions => { - //TODO: fix any - const onColumnSizingChange = (updaterOrValue: any) => { - const state = - updaterOrValue instanceof Function - ? updaterOrValue() - : updaterOrValue; - setColumnSizeStorage({ ...columnSizeStorage, ...state }); + const onColumnSizingChange = (updater: Updater) => { + setColumnSizeStorage(sizes => functionalUpdate(updater, sizes)); }; const initReactTableProps = { @@ -856,6 +860,25 @@ export const RawLogTable = memo( const table = useReactTable(reactTableProps); + // Fits a column to its widest rendered cell. The last column fills the + // space the others leave, so it goes back to filling it instead: any + // narrower leaves a gap, and any wider scrolls the table sideways. + const fitColumnToContent = (columnId: string, isLast: boolean) => { + if (isLast) { + table.getColumn(columnId)?.resetSize(); + return; + } + if (tableRef.current == null) return; + const contentWidth = measureColumnContentWidth( + tableRef.current, + columnId, + ); + if (contentWidth === 0) return; + + const width = getFittedColumnWidth(contentWidth, containerWidth); + table.setColumnSizing(sizes => ({ ...sizes, [columnId]: width })); + }; + // Sum actual column widths to derive a pixel min-width for the table. // This enables horizontal scrolling when the viewport is narrower than // the total column widths. @@ -1087,6 +1110,7 @@ export const RawLogTable = memo( })} style={{ minWidth: tableMinWidth }} id={tableId} + ref={tableRef} > {displayedColumns.length > 0 && @@ -1101,6 +1125,9 @@ export const RawLogTable = memo( key={header.id} header={header} isLast={isLast} + onFitToContent={() => + fitColumnToContent(header.column.id, isLast) + } onRemoveColumn={ onRemoveColumn && (header.column.columnDef.meta as any)?.column @@ -1299,6 +1326,7 @@ export const RawLogTable = memo( return (
; lastItemButtons?: React.ReactNode; onRemoveColumn?: () => void; + /** Fits the column to its content when the resize handle is double-clicked. */ + onFitToContent?: () => void; }) { 'use no memo'; // todo: table headers arent being resized properly with the react compiler return ( @@ -33,6 +36,7 @@ export default function TableHeader({ minWidth: header.getSize() === UNDEFINED_WIDTH ? 0 : header.getSize(), textAlign: 'left', }} + data-column-id={header.column.id} > {!header.column.getCanSort() ? ( @@ -100,7 +104,14 @@ export default function TableHeader({
)} diff --git a/packages/app/src/components/DBTable/__tests__/columnFit.test.ts b/packages/app/src/components/DBTable/__tests__/columnFit.test.ts new file mode 100644 index 0000000000..d5000e2a71 --- /dev/null +++ b/packages/app/src/components/DBTable/__tests__/columnFit.test.ts @@ -0,0 +1,136 @@ +import { + getFittedColumnWidth, + measureColumnContentWidth, +} from '@/components/DBTable/columnFit'; + +const CHAR_WIDTH = 8; + +// jsdom does no layout. The hidden copies the helper measures report 8px per +// character of text; every other element reports the width in its inline +// style. +function mockLayout() { + return jest + .spyOn(HTMLElement.prototype, 'getBoundingClientRect') + .mockImplementation(function (this: HTMLElement) { + const width = + this.style.visibility === 'hidden' + ? (this.textContent ?? '').length * CHAR_WIDTH + : parseFloat(this.style.width) || 0; + return { + width, + height: 0, + top: 0, + left: 0, + right: width, + bottom: 0, + x: 0, + y: 0, + toJSON: () => ({}), + }; + }); +} + +function renderTable(html: string) { + const table = document.createElement('table'); + table.innerHTML = html; + document.body.append(table); + return table; +} + +const headerCell = (columnId: string, label: string, padding = 0) => + `
${label}
`; + +const bodyCell = (columnId: string, value: string) => + `
${value}
`; + +describe('measureColumnContentWidth', () => { + let rectSpy: jest.SpyInstance; + + beforeEach(() => { + rectSpy = mockLayout(); + }); + + afterEach(() => { + rectSpy.mockRestore(); + document.body.innerHTML = ''; + }); + + it('returns the widest of the header and the rendered cells of the column', () => { + const table = renderTable(` + ${headerCell('service', 'Service')}${headerCell('body', 'Body')} + + ${bodyCell('service', 'api')}${bodyCell('body', 'a much longer value in another column')} + ${bodyCell('service', 'checkout-service')}${bodyCell('body', 'short')} + + `); + + expect(measureColumnContentWidth(table, 'service')).toBe( + 'checkout-service'.length * CHAR_WIDTH, + ); + }); + + it('adds the padding the cell keeps around its content', () => { + const table = renderTable(` + ${headerCell('level', 'Level', 8)} + ${bodyCell('level', 'warn')} + `); + + expect(measureColumnContentWidth(table, 'level')).toBe( + 'Level'.length * CHAR_WIDTH + 8, + ); + }); + + it('skips cells of a table nested in an expanded row', () => { + const table = renderTable(` + + ${bodyCell('service', 'api')} + ${bodyCell('service', 'nested-table-service')}
+ + `); + + expect(measureColumnContentWidth(table, 'service')).toBe( + 'api'.length * CHAR_WIDTH, + ); + }); + + it('leaves the table as it found it', () => { + const table = renderTable( + `${bodyCell('service', 'api')}`, + ); + const html = table.innerHTML; + + measureColumnContentWidth(table, 'service'); + + expect(table.innerHTML).toBe(html); + }); + + it('returns 0 when the column has no cells', () => { + const table = renderTable( + `${bodyCell('service', 'api')}`, + ); + + expect(measureColumnContentWidth(table, 'body')).toBe(0); + }); +}); + +describe('getFittedColumnWidth', () => { + it('rounds the content width up so the content is not cut off', () => { + expect(getFittedColumnWidth(101.2, 1400)).toBe(102); + }); + + it('keeps at least the minimum column width', () => { + expect(getFittedColumnWidth(12, 1400)).toBe(50); + }); + + it('caps the width at 600px', () => { + expect(getFittedColumnWidth(2000, 1600)).toBe(600); + }); + + it('caps the width at half the visible table width when that is smaller', () => { + expect(getFittedColumnWidth(2000, 800)).toBe(400); + }); + + it('never caps below the minimum column width', () => { + expect(getFittedColumnWidth(2000, 60)).toBe(50); + }); +}); diff --git a/packages/app/src/components/DBTable/columnFit.ts b/packages/app/src/components/DBTable/columnFit.ts new file mode 100644 index 0000000000..8ef5f5543a --- /dev/null +++ b/packages/app/src/components/DBTable/columnFit.ts @@ -0,0 +1,72 @@ +import { MIN_COLUMN_WIDTH } from '@/tableUtils'; + +/** The widest a column gets when it is fitted to its content. */ +const MAX_FITTED_COLUMN_WIDTH = 600; + +/** + * Width, in px, that a column's widest cell needs to show its content without + * truncating or wrapping it. Only cells rendered in `table` count: the header + * and whichever body rows are mounted. Cells name their column in + * `data-column-id`; cells of tables nested in an expanded row are skipped. + * Returns 0 when the column has no cells. + */ +export function measureColumnContentWidth( + table: HTMLTableElement, + columnId: string, +): number { + const measured = Array.from( + table.querySelectorAll('[data-column-id]'), + ).flatMap(cell => { + const content = cell.firstElementChild; + if ( + !(cell instanceof HTMLElement) || + cell.dataset.columnId !== columnId || + cell.closest('table') !== table || + !(content instanceof HTMLElement) + ) { + return []; + } + // A hidden copy at max-content width reports the width the content + // needs, whatever width the column has now. + const probe = content.cloneNode(true); + if (!(probe instanceof HTMLElement)) return []; + probe.style.position = 'absolute'; + probe.style.visibility = 'hidden'; + probe.style.width = 'max-content'; + cell.append(probe); + return [{ cell, content, probe }]; + }); + + // Every copy is in place before the first read, so the browser lays the + // table out once rather than once per cell. + const widths = measured.map( + ({ cell, content, probe }) => + probe.getBoundingClientRect().width + + // The padding and border the cell keeps around its content + cell.getBoundingClientRect().width - + content.getBoundingClientRect().width, + ); + measured.forEach(({ probe }) => probe.remove()); + + return Math.max(0, ...widths); +} + +/** + * The width to give a column whose content is `contentWidth` px wide: no less + * than the minimum column width, and no more than 600px or half of + * `visibleTableWidth`, whichever is smaller, so one long value can't push the + * other columns out of view. + */ +export function getFittedColumnWidth( + contentWidth: number, + visibleTableWidth: number, +): number { + const maxWidth = Math.max( + MIN_COLUMN_WIDTH, + Math.min(MAX_FITTED_COLUMN_WIDTH, visibleTableWidth / 2), + ); + return Math.min( + maxWidth, + Math.max(MIN_COLUMN_WIDTH, Math.ceil(contentWidth)), + ); +} diff --git a/packages/app/src/components/__tests__/DBRowTable.test.tsx b/packages/app/src/components/__tests__/DBRowTable.test.tsx index b072962674..057870b33f 100644 --- a/packages/app/src/components/__tests__/DBRowTable.test.tsx +++ b/packages/app/src/components/__tests__/DBRowTable.test.tsx @@ -283,6 +283,161 @@ describe('RawLogTable', () => { }); }); + describe('Fit column to content', () => { + const CHAR_WIDTH = 8; + const VIEWPORT_HEIGHT = 900; + const TABLE_WIDTH = 1000; + + // jsdom does no layout. Give the scroll container a screenful of height so + // the virtualizer mounts the rows and a 1000px width, and report the + // hidden copies the fit measures as 8px per character of text. + let rectSpy: jest.SpyInstance; + let clientHeightSpy: jest.SpyInstance; + let clientWidthSpy: jest.SpyInstance; + + beforeAll(() => { + rectSpy = jest + .spyOn(HTMLElement.prototype, 'getBoundingClientRect') + .mockImplementation(function (this: HTMLElement) { + const width = + this.style.visibility === 'hidden' + ? (this.textContent ?? '').length * CHAR_WIDTH + : 0; + const height = + this.dataset.testid === 'search-results-table' + ? VIEWPORT_HEIGHT + : 23; + return { + width, + height, + top: 0, + left: 0, + right: width, + bottom: height, + x: 0, + y: 0, + toJSON: () => ({}), + }; + }); + clientHeightSpy = jest + .spyOn(HTMLElement.prototype, 'clientHeight', 'get') + .mockReturnValue(VIEWPORT_HEIGHT); + clientWidthSpy = jest + .spyOn(HTMLElement.prototype, 'clientWidth', 'get') + .mockReturnValue(TABLE_WIDTH); + }); + + afterAll(() => { + rectSpy.mockRestore(); + clientHeightSpy.mockRestore(); + clientWidthSpy.mockRestore(); + }); + + beforeEach(() => { + window.localStorage.clear(); + }); + + const baseProps = { + displayedColumns: ['col1', 'col2'], + isLoading: false, + dedupRows: false, + hasNextPage: false, + onRowDetailsClick: () => {}, + generateRowId: () => mockRowWhereResult, + columnTypeMap: new Map(), + showExpandButton: false, + }; + + const getHeaderCell = (container: HTMLElement, columnId: string) => { + const header = container.querySelector( + `th[data-column-id="${columnId}"]`, + ); + if (!(header instanceof HTMLElement)) { + throw new Error(`No header cell for ${columnId}`); + } + return header; + }; + + const fitColumn = (container: HTMLElement, columnId: string) => + userEvent.dblClick( + within(getHeaderCell(container, columnId)).getByTestId( + 'column-resize-handle', + ), + ); + + const storedSizes = (): unknown => + JSON.parse(window.localStorage.getItem('t1-column-sizes') ?? '{}'); + + it('narrows a column to its widest value when its resize handle is double-clicked', async () => { + const { container } = renderWithMantine( + , + ); + expect(getHeaderCell(container, 'col1').style.width).toBe('160px'); + + await fitColumn(container, 'col1'); + + expect(getHeaderCell(container, 'col1').style.width).toBe( + `${'abcdefghij'.length * CHAR_WIDTH}px`, + ); + expect(storedSizes()).toEqual({ col1: 80 }); + }); + + it('caps a fitted column at half the visible table width', async () => { + const { container } = renderWithMantine( + , + ); + + await fitColumn(container, 'col1'); + + expect(storedSizes()).toEqual({ col1: TABLE_WIDTH / 2 }); + }); + + it('returns the last column to filling the table', async () => { + window.localStorage.setItem( + 't1-column-sizes', + JSON.stringify({ col1: 200, col2: 300 }), + ); + const { container } = renderWithMantine( + , + ); + expect(getHeaderCell(container, 'col2').style.width).toBe('300px'); + + await fitColumn(container, 'col2'); + + expect(storedSizes()).toEqual({ col1: 200 }); + // What col1's 200px leaves of the 1000px table + expect(getHeaderCell(container, 'col2').style.width).toBe('800px'); + }); + + it('fits a column of a table that does not save its widths', async () => { + const { container } = renderWithMantine( + , + ); + + await fitColumn(container, 'col1'); + + expect(getHeaderCell(container, 'col1').style.width).toBe('80px'); + }); + }); + describe('Row click behavior', () => { const ROW_ID = 'Timestamp = 1'; const VIEWPORT_HEIGHT = 900; diff --git a/packages/app/tests/e2e/components/TableComponent.ts b/packages/app/tests/e2e/components/TableComponent.ts index 51b2d53451..b802762e24 100644 --- a/packages/app/tests/e2e/components/TableComponent.ts +++ b/packages/app/tests/e2e/components/TableComponent.ts @@ -316,4 +316,68 @@ export class TableComponent { 'raw-log-table-sort-indicator', ); } + + /** + * Get the header cell of a column in the row table, by the column's id + */ + getColumnHeaderCell(columnId: string) { + return this.tableContainer.locator(`th[data-column-id="${columnId}"]`); + } + + /** + * Get the handle that resizes a column on drag and fits it on double-click + */ + getColumnResizeHandle(columnId: string) { + return this.getColumnHeaderCell(columnId).getByTestId( + 'column-resize-handle', + ); + } + + async getColumnWidth(columnId: string) { + const box = await this.getColumnHeaderCell(columnId).boundingBox(); + if (box == null) { + throw new Error(`The ${columnId} column header is not visible`); + } + return box.width; + } + + /** + * Drag a column's resize handle by `deltaX` pixels (negative narrows it) + */ + async dragColumnResizeHandle(columnId: string, deltaX: number) { + const box = await this.getColumnResizeHandle(columnId).boundingBox(); + if (box == null) { + throw new Error(`The ${columnId} resize handle is not visible`); + } + const x = box.x + box.width / 2; + const y = box.y + box.height / 2; + await this.page.mouse.move(x, y); + await this.page.mouse.down(); + await this.page.mouse.move(x + deltaX, y, { steps: 8 }); + await this.page.mouse.up(); + } + + async fitColumnToContent(columnId: string) { + // A font that loads late changes how wide the text is. + await this.page.evaluate(async () => { + await document.fonts.ready; + }); + await this.getColumnResizeHandle(columnId).dblclick(); + } + + /** + * Count the rendered cells of a column whose value is cut off + */ + countTruncatedCells(columnId: string) { + return this.tableContainer + .locator(`tbody [data-column-id="${columnId}"]`) + .evaluateAll( + cells => + cells.filter(cell => { + // The element that clips the value: cell > field > value text + const text = cell.firstElementChild?.firstElementChild; + return text != null && text.scrollWidth > text.clientWidth; + }).length, + ); + } } diff --git a/packages/app/tests/e2e/features/search/column-fit.spec.ts b/packages/app/tests/e2e/features/search/column-fit.spec.ts new file mode 100644 index 0000000000..5367c06d33 --- /dev/null +++ b/packages/app/tests/e2e/features/search/column-fit.spec.ts @@ -0,0 +1,90 @@ +import { SearchPage } from '../../page-objects/SearchPage'; +import { expect, test } from '../../utils/base-test'; + +test.describe('Search results column fit', { tag: '@search' }, () => { + let searchPage: SearchPage; + + test.beforeEach(async ({ page }) => { + searchPage = new SearchPage(page); + await searchPage.goto(); + }); + + test( + 'widens a column that cuts its values off when its resize handle is double-clicked', + { tag: ['@local-mode'] }, + async () => { + const { table } = searchPage; + await table.dragColumnResizeHandle('ServiceName', -100); + await expect + .poll(() => table.countTruncatedCells('ServiceName')) + .toBeGreaterThan(0); + const squeezedWidth = await table.getColumnWidth('ServiceName'); + + await table.fitColumnToContent('ServiceName'); + + await expect.poll(() => table.countTruncatedCells('ServiceName')).toBe(0); + expect(await table.getColumnWidth('ServiceName')).toBeGreaterThan( + squeezedWidth, + ); + }, + ); + + test( + 'narrows a column wider than its values when its resize handle is double-clicked', + { tag: ['@local-mode'] }, + async () => { + const { table } = searchPage; + await table.dragColumnResizeHandle('ServiceName', 200); + const widenedWidth = await table.getColumnWidth('ServiceName'); + + await table.fitColumnToContent('ServiceName'); + + await expect + .poll(() => table.getColumnWidth('ServiceName')) + .toBeLessThan(widenedWidth); + expect(await table.countTruncatedCells('ServiceName')).toBe(0); + }, + ); + + test( + 'returns the last column to filling the table', + { tag: ['@local-mode'] }, + async () => { + const { table } = searchPage; + const fillWidth = await table.getColumnWidth('Body'); + await table.dragColumnResizeHandle('Body', -150); + await expect + .poll(() => table.getColumnWidth('Body')) + .toBeLessThan(fillWidth); + + await table.fitColumnToContent('Body'); + + await expect + .poll(() => table.getColumnWidth('Body')) + .toBeCloseTo(fillWidth, 0); + }, + ); + + test( + 'keeps a fitted width after a reload', + { tag: ['@local-mode'] }, + async ({ page }) => { + const { table } = searchPage; + await table.dragColumnResizeHandle('ServiceName', 200); + const widenedWidth = await table.getColumnWidth('ServiceName'); + await table.fitColumnToContent('ServiceName'); + await expect + .poll(() => table.getColumnWidth('ServiceName')) + .toBeLessThan(widenedWidth); + const fittedWidth = await table.getColumnWidth('ServiceName'); + + await page.reload(); + await table.waitForRowsToPopulate(); + + expect(await table.getColumnWidth('ServiceName')).toBeCloseTo( + fittedWidth, + 0, + ); + }, + ); +}); From 110a997f52e42c8029a2b4c5a1d9921ff0f550b4 Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:00:28 +0000 Subject: [PATCH 2/3] fix(app): review feedback on column fit - Read the visible table width when the handle is double-clicked, instead of the last width the resize observer reported. - Drop the empty-measurement guard. The header always has width, so the measurement is never 0 for the column being fitted. - Remove the measuring copies in a finally block, so a failed read cannot leave them in the table. - Note at both render sites what the measurement relies on, and why it measures the whole header row: the remove button and resize handle take room the label needs to show in full. - Test that a column whose header is wider than its values shows the whole label after a fit, the read-time width cap, and cleanup when a read throws. Co-Authored-By: Claude Opus 5.5 --- packages/app/src/components/DBRowTable.tsx | 12 ++-- .../src/components/DBTable/TableHeader.tsx | 3 + .../DBTable/__tests__/columnFit.test.ts | 15 ++++ .../app/src/components/DBTable/columnFit.ts | 72 ++++++++++--------- .../components/__tests__/DBRowTable.test.tsx | 20 ++++++ .../tests/e2e/components/TableComponent.ts | 10 +++ .../e2e/features/search/column-fit.spec.ts | 18 +++++ 7 files changed, 112 insertions(+), 38 deletions(-) diff --git a/packages/app/src/components/DBRowTable.tsx b/packages/app/src/components/DBRowTable.tsx index a4cbfc068f..3f5e56621a 100644 --- a/packages/app/src/components/DBRowTable.tsx +++ b/packages/app/src/components/DBRowTable.tsx @@ -868,14 +868,16 @@ export const RawLogTable = memo( table.getColumn(columnId)?.resetSize(); return; } - if (tableRef.current == null) return; + if (tableRef.current == null || tableContainerRef == null) return; const contentWidth = measureColumnContentWidth( tableRef.current, columnId, ); - if (contentWidth === 0) return; - - const width = getFittedColumnWidth(contentWidth, containerWidth); + // The width now, not the last one the resize observer reported + const width = getFittedColumnWidth( + contentWidth, + tableContainerRef.clientWidth, + ); table.setColumnSizing(sizes => ({ ...sizes, [columnId]: width })); }; @@ -1326,6 +1328,8 @@ export const RawLogTable = memo( return (
diff --git a/packages/app/src/components/DBTable/__tests__/columnFit.test.ts b/packages/app/src/components/DBTable/__tests__/columnFit.test.ts index d5000e2a71..bd98a24245 100644 --- a/packages/app/src/components/DBTable/__tests__/columnFit.test.ts +++ b/packages/app/src/components/DBTable/__tests__/columnFit.test.ts @@ -104,6 +104,21 @@ describe('measureColumnContentWidth', () => { expect(table.innerHTML).toBe(html); }); + it('removes its copies even when reading a width throws', () => { + const table = renderTable( + `${bodyCell('service', 'api')}`, + ); + const html = table.innerHTML; + rectSpy.mockImplementation(() => { + throw new Error('layout failed'); + }); + + expect(() => measureColumnContentWidth(table, 'service')).toThrow( + 'layout failed', + ); + expect(table.innerHTML).toBe(html); + }); + it('returns 0 when the column has no cells', () => { const table = renderTable( `${bodyCell('service', 'api')}`, diff --git a/packages/app/src/components/DBTable/columnFit.ts b/packages/app/src/components/DBTable/columnFit.ts index 8ef5f5543a..5d11d3db45 100644 --- a/packages/app/src/components/DBTable/columnFit.ts +++ b/packages/app/src/components/DBTable/columnFit.ts @@ -14,41 +14,45 @@ export function measureColumnContentWidth( table: HTMLTableElement, columnId: string, ): number { - const measured = Array.from( - table.querySelectorAll('[data-column-id]'), - ).flatMap(cell => { - const content = cell.firstElementChild; - if ( - !(cell instanceof HTMLElement) || - cell.dataset.columnId !== columnId || - cell.closest('table') !== table || - !(content instanceof HTMLElement) - ) { - return []; - } - // A hidden copy at max-content width reports the width the content - // needs, whatever width the column has now. - const probe = content.cloneNode(true); - if (!(probe instanceof HTMLElement)) return []; - probe.style.position = 'absolute'; - probe.style.visibility = 'hidden'; - probe.style.width = 'max-content'; - cell.append(probe); - return [{ cell, content, probe }]; - }); + const probes: HTMLElement[] = []; + try { + const measured = Array.from( + table.querySelectorAll('[data-column-id]'), + ).flatMap(cell => { + const content = cell.firstElementChild; + if ( + !(cell instanceof HTMLElement) || + cell.dataset.columnId !== columnId || + cell.closest('table') !== table || + !(content instanceof HTMLElement) + ) { + return []; + } + // A hidden copy at max-content width reports the width the content + // needs, whatever width the column has now. + const probe = content.cloneNode(true); + if (!(probe instanceof HTMLElement)) return []; + probe.style.position = 'absolute'; + probe.style.visibility = 'hidden'; + probe.style.width = 'max-content'; + cell.append(probe); + probes.push(probe); + return [{ cell, content, probe }]; + }); - // Every copy is in place before the first read, so the browser lays the - // table out once rather than once per cell. - const widths = measured.map( - ({ cell, content, probe }) => - probe.getBoundingClientRect().width + - // The padding and border the cell keeps around its content - cell.getBoundingClientRect().width - - content.getBoundingClientRect().width, - ); - measured.forEach(({ probe }) => probe.remove()); - - return Math.max(0, ...widths); + // Every copy is in place before the first read, so the browser lays the + // table out once rather than once per cell. + const widths = measured.map( + ({ cell, content, probe }) => + probe.getBoundingClientRect().width + + // The padding and border the cell keeps around its content + cell.getBoundingClientRect().width - + content.getBoundingClientRect().width, + ); + return Math.max(0, ...widths); + } finally { + probes.forEach(probe => probe.remove()); + } } /** diff --git a/packages/app/src/components/__tests__/DBRowTable.test.tsx b/packages/app/src/components/__tests__/DBRowTable.test.tsx index 057870b33f..09a35d8f0f 100644 --- a/packages/app/src/components/__tests__/DBRowTable.test.tsx +++ b/packages/app/src/components/__tests__/DBRowTable.test.tsx @@ -403,6 +403,26 @@ describe('RawLogTable', () => { expect(storedSizes()).toEqual({ col1: TABLE_WIDTH / 2 }); }); + it('caps a fitted column by the table width at the time of the double-click', async () => { + const { container } = renderWithMantine( + , + ); + + // The table narrowed after the width the component last recorded. + clientWidthSpy.mockReturnValue(600); + try { + await fitColumn(container, 'col1'); + } finally { + clientWidthSpy.mockReturnValue(TABLE_WIDTH); + } + + expect(storedSizes()).toEqual({ col1: 300 }); + }); + it('returns the last column to filling the table', async () => { window.localStorage.setItem( 't1-column-sizes', diff --git a/packages/app/tests/e2e/components/TableComponent.ts b/packages/app/tests/e2e/components/TableComponent.ts index b802762e24..e8f77d95b9 100644 --- a/packages/app/tests/e2e/components/TableComponent.ts +++ b/packages/app/tests/e2e/components/TableComponent.ts @@ -380,4 +380,14 @@ export class TableComponent { }).length, ); } + + /** + * Whether a column's header label is cut off + */ + isColumnHeaderLabelTruncated(columnId: string) { + return this.getColumnHeaderCell(columnId) + .locator('.mantine-Text-root') + .first() + .evaluate(label => label.scrollWidth > label.clientWidth); + } } diff --git a/packages/app/tests/e2e/features/search/column-fit.spec.ts b/packages/app/tests/e2e/features/search/column-fit.spec.ts index 5367c06d33..17bf48f9ad 100644 --- a/packages/app/tests/e2e/features/search/column-fit.spec.ts +++ b/packages/app/tests/e2e/features/search/column-fit.spec.ts @@ -46,6 +46,24 @@ test.describe('Search results column fit', { tag: '@search' }, () => { }, ); + test( + 'shows the whole header label of a column whose header is wider than its values', + { tag: ['@local-mode'] }, + async () => { + const { table } = searchPage; + await table.dragColumnResizeHandle('SeverityText', -40); + await expect + .poll(() => table.isColumnHeaderLabelTruncated('SeverityText')) + .toBe(true); + + await table.fitColumnToContent('SeverityText'); + + await expect + .poll(() => table.isColumnHeaderLabelTruncated('SeverityText')) + .toBe(false); + }, + ); + test( 'returns the last column to filling the table', { tag: ['@local-mode'] }, From fbf843d64d27c82a8abedb2d606685dd9a18d614 Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:14:10 +0000 Subject: [PATCH 3/3] fix(app): offer column fit only in tables that save their widths Tables without a tableId keep column widths in TanStack's own state, which the last column's fill width and the table's min width don't read. A fit there narrowed a column without the last column growing to match, so the rows fell out of line with the header. Dragging in those tables already drifts the same way; this keeps the new gesture out of it. Also tests that a dragged width is still saved under the retyped column sizing handler. Co-Authored-By: Claude Opus 5.5 --- packages/app/src/components/DBRowTable.tsx | 10 ++++- .../components/__tests__/DBRowTable.test.tsx | 37 +++++++++++++++++-- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/packages/app/src/components/DBRowTable.tsx b/packages/app/src/components/DBRowTable.tsx index 3f5e56621a..b59e56770f 100644 --- a/packages/app/src/components/DBRowTable.tsx +++ b/packages/app/src/components/DBRowTable.tsx @@ -1127,8 +1127,14 @@ export const RawLogTable = memo( key={header.id} header={header} isLast={isLast} - onFitToContent={() => - fitColumnToContent(header.column.id, isLast) + // Only saved widths feed the last column's fill + // width, so elsewhere a fit would leave the rows + // out of line with the header. + onFitToContent={ + tableId + ? () => + fitColumnToContent(header.column.id, isLast) + : undefined } onRemoveColumn={ onRemoveColumn && diff --git a/packages/app/src/components/__tests__/DBRowTable.test.tsx b/packages/app/src/components/__tests__/DBRowTable.test.tsx index 09a35d8f0f..297ac0d7c5 100644 --- a/packages/app/src/components/__tests__/DBRowTable.test.tsx +++ b/packages/app/src/components/__tests__/DBRowTable.test.tsx @@ -1,7 +1,13 @@ import { Provider } from 'jotai'; import type { ReactElement } from 'react'; import type { BuilderChartConfigWithDateRange } from '@hyperdx/common-utils/dist/types'; -import { renderHook, screen, waitFor, within } from '@testing-library/react'; +import { + fireEvent, + renderHook, + screen, + waitFor, + within, +} from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { fromPartial } from '@total-typescript/shoehorn'; @@ -281,6 +287,26 @@ describe('RawLogTable', () => { expect(headers).toHaveLength(2); expect((headers[0] as HTMLElement).style.width).not.toBe('250px'); }); + + it('saves the width a column is dragged to', () => { + const { container } = renderWithMantine( + , + ); + const header = container.querySelector('th[data-column-id="col1"]'); + if (!(header instanceof HTMLElement)) throw new Error('No col1 header'); + + // From the default 160px, 40px to the right + fireEvent.mouseDown(within(header).getByTestId('column-resize-handle'), { + clientX: 100, + }); + fireEvent.mouseMove(document, { clientX: 140 }); + fireEvent.mouseUp(document, { clientX: 140 }); + + expect( + JSON.parse(window.localStorage.getItem('t1-column-sizes') ?? '{}'), + ).toEqual({ col1: 200 }); + expect(header.style.width).toBe('200px'); + }); }); describe('Fit column to content', () => { @@ -444,17 +470,22 @@ describe('RawLogTable', () => { expect(getHeaderCell(container, 'col2').style.width).toBe('800px'); }); - it('fits a column of a table that does not save its widths', async () => { + it('does not fit columns of a table that does not save its widths', async () => { const { container } = renderWithMantine( , ); + const handle = within(getHeaderCell(container, 'col1')).getByTestId( + 'column-resize-handle', + ); + expect(handle.getAttribute('title')).toBeNull(); await fitColumn(container, 'col1'); - expect(getHeaderCell(container, 'col1').style.width).toBe('80px'); + expect(getHeaderCell(container, 'col1').style.width).toBe('160px'); + expect(getHeaderCell(container, 'col2').style.width).toBe('840px'); }); });