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
7 changes: 7 additions & 0 deletions .changeset/column-fit-to-content.md
Original file line number Diff line number Diff line change
@@ -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.
52 changes: 45 additions & 7 deletions packages/app/src/components/DBRowTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import cx from 'classnames';
Expand Down Expand Up @@ -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';
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -516,6 +524,7 @@ export const RawLogTable = memo(
},
[],
);
const tableRef = useRef<HTMLTableElement>(null);

const [containerWidth, setContainerWidth] = useState(0);
useEffect(() => {
Expand Down Expand Up @@ -798,13 +807,8 @@ export const RawLogTable = memo(
}, [fetchMoreOnBottomReached, tableContainerRef]);

const reactTableProps = useMemo((): TableOptions<any> => {
//TODO: fix any
const onColumnSizingChange = (updaterOrValue: any) => {
const state =
updaterOrValue instanceof Function
? updaterOrValue()
: updaterOrValue;
setColumnSizeStorage({ ...columnSizeStorage, ...state });
const onColumnSizingChange = (updater: Updater<ColumnSizingState>) => {
setColumnSizeStorage(sizes => functionalUpdate(updater, sizes));
};

const initReactTableProps = {
Expand Down Expand Up @@ -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 }));
Comment thread
alex-fedotyev marked this conversation as resolved.
Resolved
};

// 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.
Expand Down Expand Up @@ -1087,6 +1112,7 @@ export const RawLogTable = memo(
})}
style={{ minWidth: tableMinWidth }}
id={tableId}
ref={tableRef}
>
<thead className={styles.tableHead}>
{displayedColumns.length > 0 &&
Expand All @@ -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
Expand Down Expand Up @@ -1299,6 +1334,9 @@ export const RawLogTable = memo(
return (
<div
key={cell.id}
// measureColumnContentWidth finds the cell by
// this id and measures its first child
data-column-id={cell.column.id}
className={cx(
'flex-shrink-0 overflow-hidden position-relative',
columnCustomClassName,
Expand Down
14 changes: 14 additions & 0 deletions packages/app/src/components/DBTable/TableHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,14 @@ export default function TableHeader({
header,
lastItemButtons,
onRemoveColumn,
onFitToContent,
}: {
isLast: boolean;
header: Header<any, any>;
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 (
Expand All @@ -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}
>
<Group wrap="nowrap" gap={0} align="center">
{!header.column.getCanSort() ? (
Expand Down Expand Up @@ -100,7 +107,14 @@ export default function TableHeader({
<div
onMouseDown={header.getResizeHandler()}
onTouchStart={header.getResizeHandler()}
onDoubleClick={onFitToContent}
title={
onFitToContent
? 'Drag to resize, double-click to fit'
: undefined
}
className={headerStyles.resizer}
data-testid="column-resize-handle"
/>
)}
</Group>
Expand Down
151 changes: 151 additions & 0 deletions packages/app/src/components/DBTable/__tests__/columnFit.test.ts
Original file line number Diff line number Diff line change
@@ -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) =>
`<th data-column-id="${columnId}" style="width: 160px"><div style="width: ${160 - padding}px">${label}</div></th>`;

const bodyCell = (columnId: string, value: string) =>
`<td><div data-column-id="${columnId}" style="width: 160px"><div style="width: 160px">${value}</div></div></td>`;

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(`
<thead><tr>${headerCell('service', 'Service')}${headerCell('body', 'Body')}</tr></thead>
<tbody>
<tr>${bodyCell('service', 'api')}${bodyCell('body', 'a much longer value in another column')}</tr>
<tr>${bodyCell('service', 'checkout-service')}${bodyCell('body', 'short')}</tr>
</tbody>
`);

expect(measureColumnContentWidth(table, 'service')).toBe(
'checkout-service'.length * CHAR_WIDTH,
);
});

it('adds the padding the cell keeps around its content', () => {
const table = renderTable(`
<thead><tr>${headerCell('level', 'Level', 8)}</tr></thead>
<tbody><tr>${bodyCell('level', 'warn')}</tr></tbody>
`);

expect(measureColumnContentWidth(table, 'level')).toBe(
'Level'.length * CHAR_WIDTH + 8,
);
});

it('skips cells of a table nested in an expanded row', () => {
const table = renderTable(`
<tbody>
<tr>${bodyCell('service', 'api')}</tr>
<tr><td><table><tbody><tr>${bodyCell('service', 'nested-table-service')}</tr></tbody></table></td></tr>
</tbody>
`);

expect(measureColumnContentWidth(table, 'service')).toBe(
'api'.length * CHAR_WIDTH,
);
});

it('leaves the table as it found it', () => {
const table = renderTable(
`<tbody><tr>${bodyCell('service', 'api')}</tr></tbody>`,
);
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(
`<tbody><tr>${bodyCell('service', 'api')}</tr></tbody>`,
);
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(
`<tbody><tr>${bodyCell('service', 'api')}</tr></tbody>`,
);

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);
});
});
76 changes: 76 additions & 0 deletions packages/app/src/components/DBTable/columnFit.ts
Original file line number Diff line number Diff line change
@@ -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)),
);
}
Loading
Loading