Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/column-fit-table-tiles.md
Original file line number Diff line number Diff line change
@@ -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.
17 changes: 16 additions & 1 deletion packages/app/src/HDXMultiSeriesTableChart.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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';
Expand Down Expand Up @@ -118,6 +119,7 @@ export const Table = ({
const [tableContainer, setTableContainer] = useState<HTMLDivElement | null>(
null,
);
const tableRef = useRef<HTMLTableElement>(null);

const truncatedData = useMemo(() => {
if (data.length > MAX_TABLE_ROWS) {
Expand Down Expand Up @@ -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({
Expand Down Expand Up @@ -444,6 +454,7 @@ export const Table = ({
ref={setTableContainer}
>
<table
ref={tableRef}
className="w-100"
style={{
tableLayout: 'fixed',
Expand Down Expand Up @@ -476,6 +487,7 @@ export const Table = ({
key={header.id}
header={header}
isLast={headerIndex === headerGroup.headers.length - 1}
onFitToContent={() => fitColumnToContent(header.column.id)}
lastItemButtons={
<>
{headerIndex === headerGroup.headers.length - 1 && (
Expand Down Expand Up @@ -550,6 +562,9 @@ export const Table = ({
return (
<td
key={cell.id}
// measureColumnContentWidth finds the cell by this id
// and measures its first child
data-column-id={cell.column.id}
title={`${cell.getValue()}`}
className={cx({
[styles.lastCell]: isLastCell,
Expand Down
99 changes: 98 additions & 1 deletion packages/app/src/__tests__/HDXMultiSeriesTableChart.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';
import type { ChartPaletteToken } from '@hyperdx/common-utils/dist/types';
import { screen, waitFor } from '@testing-library/react';
import { screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

import { Table } from '@/HDXMultiSeriesTableChart';
Expand Down Expand Up @@ -645,4 +645,101 @@ describe('HDXMultiSeriesTableChart <Table>', () => {
).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(
<Table
data={[
{ ServiceName: 'checkout-service', Count: 10 },
{ ServiceName: 'api', Count: 3 },
]}
columns={baseColumns}
sorting={[]}
onSortingChange={() => {}}
/>,
);

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(
<Table
data={baseData}
columns={baseColumns}
sorting={[]}
onSortingChange={() => {}}
/>,
);

expect(
within(getHeaderCell(container, 'count')).queryByTestId(
'column-resize-handle',
),
).toBeNull();
});
});
});
16 changes: 5 additions & 11 deletions packages/app/src/components/DBRowTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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.
Expand Down
85 changes: 85 additions & 0 deletions packages/app/src/components/DBTable/__tests__/columnFit.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import {
ColumnSizingState,
functionalUpdate,
Updater,
} from '@tanstack/react-table';

import {
fitColumn,
getFittedColumnWidth,
measureColumnContentWidth,
} from '@/components/DBTable/columnFit';
Expand Down Expand Up @@ -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(
`<tbody><tr>${bodyCell('service', 'api')}</tr></tbody>`,
);
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(
`<tbody><tr>${bodyCell('service', 'api')}</tr></tbody>`,
Expand Down Expand Up @@ -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(
`<tbody><tr>${bodyCell('service', 'checkout-service')}</tr></tbody>`,
);
let sizes: Record<string, number> = { body: 300 };
const tanstackTable = {
setColumnSizing: (updater: Updater<ColumnSizingState>) => {
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(
`<tbody><tr>${bodyCell('service', 'x'.repeat(100))}</tr></tbody>`,
);
let sizes: Record<string, number> = {};
const tanstackTable = {
setColumnSizing: (updater: Updater<ColumnSizingState>) => {
sizes = functionalUpdate(updater, sizes);
},
};

fitColumn(tanstackTable, table, 500, 'service');

expect(sizes).toEqual({ service: 250 });
});
});
29 changes: 25 additions & 4 deletions packages/app/src/components/DBTable/columnFit.ts
Original file line number Diff line number Diff line change
@@ -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. */
Expand Down Expand Up @@ -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 }];
Expand Down Expand Up @@ -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<ColumnSizingState>) => void },
tableElement: HTMLTableElement,
visibleTableWidth: number,
columnId: string,
): void {
const width = getFittedColumnWidth(
measureColumnContentWidth(tableElement, columnId),
visibleTableWidth,
);
table.setColumnSizing(sizes => ({ ...sizes, [columnId]: width }));
}
Loading
Loading