Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

📏 fix: Make DataTable Row Estimates Breakpoint- and Leaf-Column-Aware (#16817)

Marco Beretta8acc19f98f2c
diff --git a/e2e/specs/mock/scenarios/data-table-row-estimate.spec.ts b/e2e/specs/mock/scenarios/data-table-row-estimate.spec.ts
new file mode 100644
index 0000000000..af02389196
--- /dev/null
+++ b/e2e/specs/mock/scenarios/data-table-row-estimate.spec.ts
@@ -0,0 +1,55 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import { NEW_CHAT_PATH } from '../helpers';
+
+/**
+ * The virtualized DataTable guesses a compact row's height before it renders: 36px from `sm` up
+ * and 24px below it. The probe is a row of the compact cell the table renders, resolved through the
+ * stylesheet the app shipped, so the guess is checked against what the cell actually measures on
+ * either side of the breakpoint.
+ */
+const COMPACT_CELL_CLASSES =
+ 'px-4 align-middle py-theme-table-cell-dense sm:py-theme-table-cell-compact text-xs sm:text-sm';
+
+async function compactRowHeight(page: Page): Promise<number> {
+ return page.evaluate((classes) => {
+ const table = document.createElement('table');
+ const row = table.insertRow();
+ const cell = row.insertCell();
+ cell.className = classes;
+ cell.textContent = 'Row';
+ table.style.cssText = 'position:fixed;top:0;left:0;border-collapse:separate;border-spacing:0';
+ document.body.append(table);
+ const height = row.getBoundingClientRect().height;
+ table.remove();
+ return height;
+ }, COMPACT_CELL_CLASSES);
+}
+
+/** Each tag is written out whole: the runner finds a scenario by its literal tag. */
+const CASES = [
+ {
+ title: 'a compact row measures the estimate below sm @scenario:data-table-row-estimate-375',
+ width: 375,
+ expected: 24,
+ },
+ {
+ title: 'a compact row measures the estimate from sm up @scenario:data-table-row-estimate-1024',
+ width: 1024,
+ expected: 36,
+ },
+] as const;
+
+test.describe('DataTable compact row estimate', () => {
+ for (const { title, width, expected } of CASES) {
+ test(title, async ({ page }) => {
+ await page.setViewportSize({ width, height: 800 });
+ await page.goto(NEW_CHAT_PATH, { timeout: 15000 });
+ await expect(page.getByRole('textbox', { name: 'Message input' })).toBeVisible({
+ timeout: 30000,
+ });
+
+ expect(await compactRowHeight(page)).toBe(expected);
+ });
+ }
+});
diff --git a/packages/client/src/components/DataTable.spec.tsx b/packages/client/src/components/DataTable.spec.tsx
new file mode 100644
index 0000000000..68a4ea975d
--- /dev/null
+++ b/packages/client/src/components/DataTable.spec.tsx
@@ -0,0 +1,70 @@
+import React from 'react';
+import { render } from '@testing-library/react';
+import * as ReactVirtual from '@tanstack/react-virtual';
+import type { ColumnDef } from '@tanstack/react-table';
+import DataTable from './DataTable';
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => key,
+ useMediaQuery: jest.fn(() => false),
+}));
+
+jest.mock('@tanstack/react-virtual', () => {
+ const actual = jest.requireActual('@tanstack/react-virtual');
+ return { ...actual, useVirtualizer: jest.fn(actual.useVirtualizer) };
+});
+
+interface Row {
+ title: string;
+ owner: string;
+}
+
+const data: Row[] = [{ title: 'First', owner: 'Ada' }];
+
+/** The first guess the table gave the virtualizer for a row it has not rendered. */
+const estimate = (columns: ColumnDef<Row>[]): number => {
+ const useVirtualizer = jest.mocked(ReactVirtual.useVirtualizer);
+ useVirtualizer.mockClear();
+ render(<DataTable columns={columns} data={data} showCheckboxes={false} />);
+ const options = useVirtualizer.mock.calls[0][0];
+ return options.estimateSize(0);
+};
+
+describe('DataTable row estimate', () => {
+ const originalMatchMedia = window.matchMedia;
+
+ beforeEach(() => {
+ window.matchMedia = jest.fn().mockImplementation(() => ({
+ matches: true,
+ addEventListener: jest.fn(),
+ removeEventListener: jest.fn(),
+ }));
+ });
+
+ afterEach(() => {
+ window.matchMedia = originalMatchMedia;
+ });
+
+ it('uses the compact estimate when no column is the title', () => {
+ expect(estimate([{ accessorKey: 'owner', header: 'Owner' }])).toBe(36);
+ });
+
+ it('uses the titled estimate for a title column', () => {
+ expect(estimate([{ accessorKey: 'title', header: 'Title' }])).toBe(48);
+ });
+
+ it('estimates a compact row at 24px below sm, where the cells carry a quarter of the space', () => {
+ window.matchMedia = jest.fn().mockImplementation(() => ({
+ matches: false,
+ addEventListener: jest.fn(),
+ removeEventListener: jest.fn(),
+ }));
+ expect(estimate([{ accessorKey: 'owner', header: 'Owner' }])).toBe(24);
+ });
+
+ it('finds a title leaf inside a grouped column definition', () => {
+ expect(
+ estimate([{ header: 'Group', columns: [{ accessorKey: 'title', header: 'Title' }] }]),
+ ).toBe(48);
+ });
+});
diff --git a/packages/client/src/components/DataTable.tsx b/packages/client/src/components/DataTable.tsx
index 23c9190102..d92f1914c6 100644
--- a/packages/client/src/components/DataTable.tsx
+++ b/packages/client/src/components/DataTable.tsx
@@ -297,16 +297,9 @@ export default function DataTable<TData, TValue>({
const { rows } = table.getRowModel();
/** The first guess for a row that has not rendered yet, from the columns it will carry: a
- * title cell's height when there is one, a compact row otherwise. Both follow the theme's cell
- * space and row rule, and rendered rows are measured. */
- const hasTitleColumn = useMemo(
- () =>
- columns.some(
- (column) =>
- column.id === 'title' || ('accessorKey' in column && column.accessorKey === 'title'),
- ),
- [columns],
- );
+ * title cell's height when a visible leaf column is the title, a compact row otherwise. Both
+ * follow the theme's cell space and row rule, and rendered rows are measured. */
+ const hasTitleColumn = table.getVisibleLeafColumns().some((column) => column.id === 'title');
const rowHeight = useTableRowHeight(hasTitleColumn ? 'titled' : 'compact');
const rowVirtualizer = useVirtualizer({
count: rows.length,
diff --git a/packages/client/src/components/DataTable/DataTable.hooks.spec.ts b/packages/client/src/components/DataTable/DataTable.hooks.spec.ts
index 67ed2682c0..166ffddea7 100644
--- a/packages/client/src/components/DataTable/DataTable.hooks.spec.ts
+++ b/packages/client/src/components/DataTable/DataTable.hooks.spec.ts
@@ -471,7 +471,26 @@ describe('DataTable Hooks', () => {
});
describe('useTableRowHeight', () => {
+ const originalMatchMedia = window.matchMedia;
+ let listeners: Array<() => void>;
+ let wide: boolean;
+
+ beforeEach(() => {
+ listeners = [];
+ wide = true;
+ window.matchMedia = jest.fn().mockImplementation(() => ({
+ get matches() {
+ return wide;
+ },
+ addEventListener: (_: string, listener: () => void) => listeners.push(listener),
+ removeEventListener: (_: string, listener: () => void) => {
+ listeners = listeners.filter((l) => l !== listener);
+ },
+ }));
+ });
+
afterEach(() => {
+ window.matchMedia = originalMatchMedia;
document.documentElement.style.removeProperty('--theme-table-cell-space-y');
document.documentElement.style.removeProperty('--theme-table-row-stroke');
});
@@ -495,4 +514,29 @@ describe('useTableRowHeight', () => {
/** The title cell's fixed height is a border box, so the rule sits inside it. */
expect(titled.result.current).toBe(32);
});
+
+ describe('below the sm breakpoint', () => {
+ beforeEach(() => {
+ wide = false;
+ });
+
+ it('is 24px compact on a narrow screen, where the cells carry a quarter of the space', () => {
+ expect(renderHook(() => useTableRowHeight('compact')).result.current).toBe(24);
+ expect(renderHook(() => useTableRowHeight('titled')).result.current).toBe(48);
+ });
+
+ it('re-reads when the viewport crosses sm', () => {
+ const { result, unmount } = renderHook(() => useTableRowHeight('compact'));
+ expect(result.current).toBe(24);
+
+ act(() => {
+ wide = true;
+ listeners.forEach((listener) => listener());
+ });
+ expect(result.current).toBe(36);
+
+ unmount();
+ expect(listeners).toHaveLength(0);
+ });
+ });
});
diff --git a/packages/client/src/components/DataTable/DataTable.hooks.ts b/packages/client/src/components/DataTable/DataTable.hooks.ts
index 88e7547e11..a2fa411e33 100644
--- a/packages/client/src/components/DataTable/DataTable.hooks.ts
+++ b/packages/client/src/components/DataTable/DataTable.hooks.ts
@@ -173,10 +173,18 @@ function readRootLength(property: string, fallbackRem: number): number {
type TableRowKind = 'dense' | 'compact' | 'titled';
+const SM_BREAKPOINT_QUERY = '(min-width: 640px)';
+
+function isBelowSm(): boolean {
+ return typeof window !== 'undefined' && typeof window.matchMedia === 'function'
+ ? !window.matchMedia(SM_BREAKPOINT_QUERY).matches
+ : false;
+}
+
/**
* A row's height in px. A dense row holds 2rem of controls between a quarter of the cell space
- * above and below; a compact row a 1.25rem text line between half the space above and below (its
- * size from `sm` up); a titled row is as tall as its title cell, a header-sized cell of twice the
+ * above and below; a compact row a 1.25rem text line between half the space above and below from
+ * `sm` up, and a 1rem line between a quarter of it below; a titled row is as tall as its title cell, a header-sized cell of twice the
* space around a 1rem line. The dense and compact cells grow by the row rule under them; the title
* cell's fixed height is a border box that already holds it.
*/
@@ -189,14 +197,14 @@ function readTableRowHeight(kind: TableRowKind): number {
const stroke = readRootLength('--theme-table-row-stroke', 0);
const heights: Record<TableRowKind, number> = {
dense: 2 * rootSize + space / 2 + stroke,
- compact: 1.25 * rootSize + space + stroke,
+ compact: isBelowSm() ? rootSize + space / 2 + stroke : 1.25 * rootSize + space + stroke,
titled: rootSize + 2 * space,
};
return heights[kind];
}
-/** The theme paints its appearance onto the root's inline style and class, so those are the
- * changes worth re-reading on. */
+/** The theme paints its appearance onto the root's inline style and class, and the cell sizes
+ * change at `sm`, so those are the changes worth re-reading on. */
function subscribeToGeometry(onChange: () => void): () => void {
if (typeof MutationObserver === 'undefined' || typeof document === 'undefined') {
return () => undefined;
@@ -206,11 +214,17 @@ function subscribeToGeometry(onChange: () => void): () => void {
attributes: true,
attributeFilter: ['style', 'class'],
});
- return () => observer.disconnect();
+ const breakpoint =
+ typeof window.matchMedia === 'function' ? window.matchMedia(SM_BREAKPOINT_QUERY) : null;
+ breakpoint?.addEventListener('change', onChange);
+ return () => {
+ observer.disconnect();
+ breakpoint?.removeEventListener('change', onChange);
+ };
}
/**
- * A table row's height in px (dense 40px, compact 36px, titled 48px by default), for geometry JavaScript has
+ * A table row's height in px (dense 40px, compact 36px or 24px below `sm`, titled 48px by default), for geometry JavaScript has
* to know, such as a virtualized row. Follows a theme switch.
*/
export function useTableRowHeight(kind: TableRowKind): number {