diff --git a/.changeset/column-fit-table-tiles.md b/.changeset/column-fit-table-tiles.md new file mode 100644 index 000000000..5f090be5c --- /dev/null +++ b/.changeset/column-fit-table-tiles.md @@ -0,0 +1,6 @@ +--- +'@hyperdx/app': patch +--- + +feat: double-click a column's resize handle on a dashboard table tile to fit the +column to its content, like in search results. diff --git a/packages/app/src/HDXMultiSeriesTableChart.tsx b/packages/app/src/HDXMultiSeriesTableChart.tsx index 5df9362e6..117c5ba25 100644 --- a/packages/app/src/HDXMultiSeriesTableChart.tsx +++ b/packages/app/src/HDXMultiSeriesTableChart.tsx @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useMemo, useRef, useState } from 'react'; import Link from 'next/link'; import cx from 'classnames'; import { MAX_TABLE_ROWS } from '@hyperdx/common-utils/dist/core/utils'; @@ -29,6 +29,7 @@ import { ColumnDef } from '@tanstack/react-table'; import { useVirtualizer } from '@tanstack/react-virtual'; import { CsvExportButton } from './components/CsvExportButton'; +import { fitColumn } from './components/DBTable/columnFit'; import DBRowTableFieldWithPopover, { type CellFilterHandler, } from './components/DBTable/DBRowTableFieldWithPopover'; @@ -118,6 +119,7 @@ export const Table = ({ const [tableContainer, setTableContainer] = useState( null, ); + const tableRef = useRef(null); const truncatedData = useMemo(() => { if (data.length > MAX_TABLE_ROWS) { @@ -404,6 +406,14 @@ export const Table = ({ ...sortingParams, }); + // Fits a column on a double-click of its resize handle. Like a dragged + // width, the fitted one lives in the table's own state. The last data + // column fills the tile and can't be resized, so it never gets here. + const fitColumnToContent = (columnId: string) => { + if (tableRef.current == null || tableContainer == null) return; + fitColumn(table, tableRef.current, tableContainer.clientWidth, columnId); + }; + const { rows } = table.getRowModel(); const rowVirtualizer = useVirtualizer({ @@ -444,6 +454,7 @@ export const Table = ({ ref={setTableContainer} > fitColumnToContent(header.column.id)} lastItemButtons={ <> {headerIndex === headerGroup.headers.length - 1 && ( @@ -550,6 +562,9 @@ export const Table = ({ return (
', () => { ).rejects.toThrow(); }); }); + + describe('Fit column to content', () => { + const CHAR_WIDTH = 8; + const TABLE_WIDTH = 1000; + + // jsdom does no layout. Give the tile a 1000px width and report the hidden + // copies the fit measures as 8px per character of text. + let rectSpy: 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; + return { + width, + height: 0, + top: 0, + left: 0, + right: width, + bottom: 0, + x: 0, + y: 0, + toJSON: () => ({}), + }; + }); + clientWidthSpy = jest + .spyOn(HTMLElement.prototype, 'clientWidth', 'get') + .mockReturnValue(TABLE_WIDTH); + }); + + afterAll(() => { + rectSpy.mockRestore(); + clientWidthSpy.mockRestore(); + }); + + 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; + }; + + it('fits a column to its widest value when its resize handle is double-clicked', async () => { + const { container } = renderWithMantine( + {}} + />, + ); + + await userEvent.dblClick( + within(getHeaderCell(container, 'service')).getByTestId( + 'column-resize-handle', + ), + ); + + expect(getHeaderCell(container, 'service').style.width).toBe( + `${'checkout-service'.length * CHAR_WIDTH}px`, + ); + // Like a dragged width, the fitted one isn't saved anywhere. + expect( + Object.keys(window.localStorage).filter(key => + key.endsWith('-column-sizes'), + ), + ).toEqual([]); + }); + + it('gives the last data column, which fills the tile, nothing to fit', () => { + const { container } = renderWithMantine( +
{}} + />, + ); + + expect( + within(getHeaderCell(container, 'count')).queryByTestId( + 'column-resize-handle', + ), + ).toBeNull(); + }); + }); }); diff --git a/packages/app/src/components/DBRowTable.tsx b/packages/app/src/components/DBRowTable.tsx index b59e56770..13b0259e4 100644 --- a/packages/app/src/components/DBRowTable.tsx +++ b/packages/app/src/components/DBRowTable.tsx @@ -124,10 +124,7 @@ import ChartErrorState, { ChartErrorStateVariant, } from './charts/ChartErrorState'; import { getAdhocCellCondition } from './DBTable/adhocCellCondition'; -import { - getFittedColumnWidth, - measureColumnContentWidth, -} from './DBTable/columnFit'; +import { fitColumn } from './DBTable/columnFit'; import DBRowTableFieldWithPopover from './DBTable/DBRowTableFieldWithPopover'; import DBRowTableRowButtons from './DBTable/DBRowTableRowButtons'; import { @@ -869,16 +866,13 @@ export const RawLogTable = memo( return; } if (tableRef.current == null || tableContainerRef == null) return; - const contentWidth = measureColumnContentWidth( - tableRef.current, - columnId, - ); // The width now, not the last one the resize observer reported - const width = getFittedColumnWidth( - contentWidth, + fitColumn( + table, + tableRef.current, tableContainerRef.clientWidth, + columnId, ); - table.setColumnSizing(sizes => ({ ...sizes, [columnId]: width })); }; // Sum actual column widths to derive a pixel min-width for the table. diff --git a/packages/app/src/components/DBTable/__tests__/columnFit.test.ts b/packages/app/src/components/DBTable/__tests__/columnFit.test.ts index bd98a2424..ff5a75ca3 100644 --- a/packages/app/src/components/DBTable/__tests__/columnFit.test.ts +++ b/packages/app/src/components/DBTable/__tests__/columnFit.test.ts @@ -1,4 +1,11 @@ import { + ColumnSizingState, + functionalUpdate, + Updater, +} from '@tanstack/react-table'; + +import { + fitColumn, getFittedColumnWidth, measureColumnContentWidth, } from '@/components/DBTable/columnFit'; @@ -119,6 +126,36 @@ describe('measureColumnContentWidth', () => { expect(table.innerHTML).toBe(html); }); + it('sets the copy styles as important, so a class like w-100 cannot override the width', () => { + const table = renderTable( + `${bodyCell('service', 'api')}`, + ); + const measured: HTMLElement[] = []; + rectSpy.mockImplementation(function (this: HTMLElement) { + measured.push(this); + return { + width: 0, + height: 0, + top: 0, + left: 0, + right: 0, + bottom: 0, + x: 0, + y: 0, + toJSON: () => ({}), + }; + }); + + measureColumnContentWidth(table, 'service'); + + const copy = measured.find(el => el.style.visibility === 'hidden'); + expect( + ['position', 'visibility', 'width'].map(property => + copy?.style.getPropertyPriority(property), + ), + ).toEqual(['important', 'important', 'important']); + }); + it('returns 0 when the column has no cells', () => { const table = renderTable( `${bodyCell('service', 'api')}`, @@ -149,3 +186,51 @@ describe('getFittedColumnWidth', () => { expect(getFittedColumnWidth(2000, 60)).toBe(50); }); }); + +describe('fitColumn', () => { + let rectSpy: jest.SpyInstance; + + beforeEach(() => { + rectSpy = mockLayout(); + }); + + afterEach(() => { + rectSpy.mockRestore(); + document.body.innerHTML = ''; + }); + + it('sets the fitted width the way a drag does, keeping the other widths', () => { + const table = renderTable( + `${bodyCell('service', 'checkout-service')}`, + ); + let sizes: Record = { body: 300 }; + const tanstackTable = { + setColumnSizing: (updater: Updater) => { + sizes = functionalUpdate(updater, sizes); + }, + }; + + fitColumn(tanstackTable, table, 1400, 'service'); + + expect(sizes).toEqual({ + body: 300, + service: 'checkout-service'.length * CHAR_WIDTH, + }); + }); + + it('caps the width by the visible table width it is given', () => { + const table = renderTable( + `${bodyCell('service', 'x'.repeat(100))}`, + ); + let sizes: Record = {}; + const tanstackTable = { + setColumnSizing: (updater: Updater) => { + sizes = functionalUpdate(updater, sizes); + }, + }; + + fitColumn(tanstackTable, table, 500, 'service'); + + expect(sizes).toEqual({ service: 250 }); + }); +}); diff --git a/packages/app/src/components/DBTable/columnFit.ts b/packages/app/src/components/DBTable/columnFit.ts index 5d11d3db4..d370d9ba8 100644 --- a/packages/app/src/components/DBTable/columnFit.ts +++ b/packages/app/src/components/DBTable/columnFit.ts @@ -1,3 +1,5 @@ +import { ColumnSizingState, Updater } from '@tanstack/react-table'; + import { MIN_COLUMN_WIDTH } from '@/tableUtils'; /** The widest a column gets when it is fitted to its content. */ @@ -29,12 +31,13 @@ export function measureColumnContentWidth( return []; } // A hidden copy at max-content width reports the width the content - // needs, whatever width the column has now. + // needs, whatever width the column has now. The styles are important + // so a class like `w-100`, which is `!important` itself, can't win. const probe = content.cloneNode(true); if (!(probe instanceof HTMLElement)) return []; - probe.style.position = 'absolute'; - probe.style.visibility = 'hidden'; - probe.style.width = 'max-content'; + probe.style.setProperty('position', 'absolute', 'important'); + probe.style.setProperty('visibility', 'hidden', 'important'); + probe.style.setProperty('width', 'max-content', 'important'); cell.append(probe); probes.push(probe); return [{ cell, content, probe }]; @@ -74,3 +77,21 @@ export function getFittedColumnWidth( Math.max(MIN_COLUMN_WIDTH, Math.ceil(contentWidth)), ); } + +/** + * Fits a column of a rendered TanStack table to its content, setting the width + * the same way dragging its resize handle does. `visibleTableWidth` is the + * width of the area the table scrolls in, read when the fit happens. + */ +export function fitColumn( + table: { setColumnSizing: (updater: Updater) => void }, + tableElement: HTMLTableElement, + visibleTableWidth: number, + columnId: string, +): void { + const width = getFittedColumnWidth( + measureColumnContentWidth(tableElement, columnId), + visibleTableWidth, + ); + table.setColumnSizing(sizes => ({ ...sizes, [columnId]: width })); +} diff --git a/packages/app/tests/e2e/features/chart-explorer.spec.ts b/packages/app/tests/e2e/features/chart-explorer.spec.ts index b2bf6747d..3e7ad4cdf 100644 --- a/packages/app/tests/e2e/features/chart-explorer.spec.ts +++ b/packages/app/tests/e2e/features/chart-explorer.spec.ts @@ -1,5 +1,6 @@ import { DisplayType } from '@hyperdx/common-utils/dist/types'; +import { TableComponent } from '../components/TableComponent'; import { ChartExplorerPage } from '../page-objects/ChartExplorerPage'; import { expect, test } from '../utils/base-test'; import { @@ -476,6 +477,59 @@ test.describe('Chart Explorer Functionality', { tag: ['@charts'] }, () => { }); }, ); + + test('should fit a table column to its content when its resize handle is double-clicked', async ({ + page, + }) => { + const { chartEditor } = chartExplorerPage; + + await test.step('Query a table grouped by ServiceName', async () => { + await expect(chartExplorerPage.form).toBeVisible(); + await chartExplorerPage.page.waitForLoadState('networkidle'); + await chartEditor.setChartType(DisplayType.Table); + await chartEditor.setGroupBy('ServiceName'); + await chartEditor.runQuery(false); + await expect( + chartExplorerPage.getTableSortButton('ServiceName'), + ).toBeVisible({ timeout: 15000 }); + }); + + // The last column fills the table and has no handle, so fit the other. + const resultsTable = new TableComponent( + page, + 'table:has([data-testid="column-resize-handle"])', + ); + const resizableHeader = page + .locator('thead th:has([data-testid="column-resize-handle"])') + .first(); + await expect(resizableHeader).toHaveAttribute('data-column-id', /.+/); + const columnId = String( + await resizableHeader.getAttribute('data-column-id'), + ); + let fittedWidth = 0; + + await test.step('Narrow a column wider than its values', async () => { + const defaultWidth = await resultsTable.getColumnWidth(columnId); + await resultsTable.fitColumnToContent(columnId); + await expect + .poll(() => resultsTable.getColumnWidth(columnId)) + .toBeLessThan(defaultWidth); + fittedWidth = await resultsTable.getColumnWidth(columnId); + }); + + await test.step('Widen it back after squeezing it', async () => { + await resultsTable.dragColumnResizeHandle(columnId, 30 - fittedWidth); + await expect + .poll(() => resultsTable.getColumnWidth(columnId)) + .toBeLessThan(fittedWidth); + + await resultsTable.fitColumnToContent(columnId); + + await expect + .poll(() => resultsTable.getColumnWidth(columnId)) + .toBeCloseTo(fittedWidth, 0); + }); + }); }); const DAY_MS = 24 * 60 * 60 * 1000;