diff --git a/.changeset/column-fit-to-content.md b/.changeset/column-fit-to-content.md new file mode 100644 index 000000000..4034dbeaf --- /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 8336204cd..b59e56770 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,27 @@ 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 || tableContainerRef == null) return; + const contentWidth = measureColumnContentWidth( + tableRef.current, + columnId, + ); + // The width now, not the last one the resize observer reported + const width = getFittedColumnWidth( + contentWidth, + tableContainerRef.clientWidth, + ); + 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 +1112,7 @@ export const RawLogTable = memo( })} style={{ minWidth: tableMinWidth }} id={tableId} + ref={tableRef} > {displayedColumns.length > 0 && @@ -1101,6 +1127,15 @@ export const RawLogTable = memo( key={header.id} header={header} isLast={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 && (header.column.columnDef.meta as any)?.column @@ -1299,6 +1334,9 @@ 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,10 @@ export default function TableHeader({ minWidth: header.getSize() === UNDEFINED_WIDTH ? 0 : header.getSize(), textAlign: 'left', }} + // measureColumnContentWidth finds the header by this id and measures its + // first child, the whole row, since the remove button and resize handle + // take space the label needs to show in full + data-column-id={header.column.id} > {!header.column.getCanSort() ? ( @@ -100,7 +107,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 000000000..bd98a2424 --- /dev/null +++ b/packages/app/src/components/DBTable/__tests__/columnFit.test.ts @@ -0,0 +1,151 @@ +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('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')}`, + ); + + 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 000000000..5d11d3db4 --- /dev/null +++ b/packages/app/src/components/DBTable/columnFit.ts @@ -0,0 +1,76 @@ +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 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, + ); + return Math.max(0, ...widths); + } finally { + probes.forEach(probe => probe.remove()); + } +} + +/** + * 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 b07296267..297ac0d7c 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,206 @@ 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', () => { + 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('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', + 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('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('160px'); + expect(getHeaderCell(container, 'col2').style.width).toBe('840px'); + }); }); describe('Row click behavior', () => { diff --git a/packages/app/tests/e2e/components/TableComponent.ts b/packages/app/tests/e2e/components/TableComponent.ts index 51b2d5345..e8f77d95b 100644 --- a/packages/app/tests/e2e/components/TableComponent.ts +++ b/packages/app/tests/e2e/components/TableComponent.ts @@ -316,4 +316,78 @@ 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, + ); + } + + /** + * 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 new file mode 100644 index 000000000..17bf48f9a --- /dev/null +++ b/packages/app/tests/e2e/features/search/column-fit.spec.ts @@ -0,0 +1,108 @@ +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( + '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'] }, + 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, + ); + }, + ); +});