Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: made table responsive to no. of columns and improved table header (#9006)

Kiran Gadhaveb4c09da9db9e
diff --git a/frontend/src/components/data-table/__tests__/columns.test.tsx b/frontend/src/components/data-table/__tests__/columns.test.tsx
index 8b9ee4a9e2..185a2af6af 100644
--- a/frontend/src/components/data-table/__tests__/columns.test.tsx
+++ b/frontend/src/components/data-table/__tests__/columns.test.tsx
@@ -1,9 +1,9 @@
/* Copyright 2026 Marimo. All rights reserved. */
import type { Column } from "@tanstack/react-table";
-import { render } from "@testing-library/react";
+import { fireEvent, render } from "@testing-library/react";
import { I18nProvider } from "react-aria";
-import { describe, expect, it, test } from "vitest";
+import { describe, expect, it, test, vi } from "vitest";
import { TooltipProvider } from "@/components/ui/tooltip";
import { parseContent } from "@/utils/url-parser";
import {
@@ -312,7 +312,7 @@ describe("generateColumns", () => {
expect(cell?.props.className).toContain("center");
});
- it("should apply text justification to column header parents", () => {
+ it("should always left-align column headers regardless of text justification", () => {
const columns = generateColumns({
rowHeaders: [],
selection: null,
@@ -330,33 +330,112 @@ describe("generateColumns", () => {
columnDef: { meta: col.meta },
});
- // Right-justified: parent wrapper should have items-end, sort/filter icons should flip to the left
+ // Even with right justification, header is left-aligned with sort + menu buttons
const { container: rightContainer } = render(
<TooltipProvider>
{/* oxlint-disable-next-line typescript/no-explicit-any */}
{(columns[0].header as any)({ column: mockColumn(columns[0]) })}
</TooltipProvider>,
);
+ expect(
+ rightContainer.querySelector("[data-testid='data-table-sort-button']"),
+ ).toBeTruthy();
+ expect(
+ rightContainer.querySelector(
+ "[data-testid='data-table-column-menu-button']",
+ ),
+ ).toBeTruthy();
+ // No flex-row-reverse or items-end on header
const rightWrapper = rightContainer.firstElementChild;
- expect(rightWrapper?.className).toContain("items-end");
- const rightHeader = rightContainer.querySelector(
- "[data-testid='data-table-sort-button']",
- );
- expect(rightHeader?.className).toContain("flex-row-reverse");
+ expect(rightWrapper?.className).not.toContain("items-end");
+ expect(rightWrapper?.className).not.toContain("flex-row-reverse");
- // Center-justified: parent wrapper should have items-center, no flex-row-reverse
+ // Same for center-justified column
const { container: centerContainer } = render(
<TooltipProvider>
{/* oxlint-disable-next-line typescript/no-explicit-any */}
{(columns[1].header as any)({ column: mockColumn(columns[1]) })}
</TooltipProvider>,
);
+ expect(
+ centerContainer.querySelector("[data-testid='data-table-sort-button']"),
+ ).toBeTruthy();
+ expect(
+ centerContainer.querySelector(
+ "[data-testid='data-table-column-menu-button']",
+ ),
+ ).toBeTruthy();
const centerWrapper = centerContainer.firstElementChild;
- expect(centerWrapper?.className).toContain("items-center");
- const centerHeader = centerContainer.querySelector(
+ expect(centerWrapper?.className).not.toContain("items-center");
+ expect(centerWrapper?.className).not.toContain("flex-row-reverse");
+ });
+
+ it("should cycle sort button through asc, desc, and clear on clicks", () => {
+ const columns = generateColumns({
+ rowHeaders: [],
+ selection: null,
+ fieldTypes,
+ });
+
+ const toggleSorting = vi.fn();
+ const clearSorting = vi.fn();
+ let sortDirection: false | "asc" | "desc" = false;
+
+ const mockColumn = (col: (typeof columns)[number]) => ({
+ id: col.id,
+ getCanSort: () => true,
+ getCanFilter: () => false,
+ getIsSorted: () => sortDirection,
+ getSortIndex: () => -1,
+ getFilterValue: () => undefined,
+ toggleSorting,
+ clearSorting,
+ columnDef: { meta: col.meta },
+ });
+
+ const mock = mockColumn(columns[0]);
+
+ const { container, rerender } = render(
+ <TooltipProvider>
+ {/* oxlint-disable-next-line typescript/no-explicit-any */}
+ {(columns[0].header as any)({ column: mock })}
+ </TooltipProvider>,
+ );
+
+ const sortButton = container.querySelector(
"[data-testid='data-table-sort-button']",
);
- expect(centerHeader?.className).not.toContain("flex-row-reverse");
+ expect(sortButton).toBeTruthy();
+
+ // first click unsorted > asc
+ fireEvent.click(sortButton!);
+ expect(toggleSorting).toHaveBeenCalledWith(false, true);
+
+ // Simulate asc state and re-render
+ sortDirection = "asc";
+ rerender(
+ <TooltipProvider>
+ {/* oxlint-disable-next-line typescript/no-explicit-any */}
+ {(columns[0].header as any)({ column: mock })}
+ </TooltipProvider>,
+ );
+
+ // second click asc >dsc
+ fireEvent.click(sortButton!);
+ expect(toggleSorting).toHaveBeenCalledWith(true, true);
+
+ // Simulate desc state and re-render
+ sortDirection = "desc";
+ rerender(
+ <TooltipProvider>
+ {/* oxlint-disable-next-line typescript/no-explicit-any */}
+ {(columns[0].header as any)({ column: mock })}
+ </TooltipProvider>,
+ );
+
+ // third click back to unsorted
+ fireEvent.click(sortButton!);
+ expect(clearSorting).toHaveBeenCalled();
});
it("should not include index column if it exists", () => {
diff --git a/frontend/src/components/data-table/column-header.tsx b/frontend/src/components/data-table/column-header.tsx
index 09246caf9d..5e35c4d75a 100644
--- a/frontend/src/components/data-table/column-header.tsx
+++ b/frontend/src/components/data-table/column-header.tsx
@@ -2,7 +2,13 @@
"use no memo";
import type { Column, Table } from "@tanstack/react-table";
-import { FilterIcon, MinusIcon, TextIcon, XIcon } from "lucide-react";
+import {
+ EllipsisIcon,
+ FilterIcon,
+ MinusIcon,
+ TextIcon,
+ XIcon,
+} from "lucide-react";
import { useMemo, useRef, useState } from "react";
import { useLocale } from "react-aria";
import {
@@ -69,7 +75,7 @@ interface DataTableColumnHeaderProps<
> extends React.HTMLAttributes<HTMLDivElement> {
column: Column<TData, TValue>;
header: React.ReactNode;
- justify?: "left" | "center" | "right";
+ subheader?: React.ReactNode;
calculateTopKRows?: CalculateTopKRows;
table?: Table<TData>;
}
@@ -77,7 +83,7 @@ interface DataTableColumnHeaderProps<
export const DataTableColumnHeader = <TData, TValue>({
column,
header,
- justify,
+ subheader,
className,
calculateTopKRows,
table,
@@ -92,49 +98,51 @@ export const DataTableColumnHeader = <TData, TValue>({
// No sorting or filtering
if (!column.getCanSort() && !column.getCanFilter()) {
- return <div className={cn(className)}>{header}</div>;
+ return (
+ <div className={cn(className)}>
+ {header}
+ {subheader}
+ </div>
+ );
}
const hasFilter = column.getFilterValue() !== undefined;
- const hideIcon = !column.getIsSorted() && !hasFilter;
return (
<>
- <DropdownMenu modal={false}>
- <DropdownMenuTrigger asChild={true}>
- <div
- className={cn(
- "group flex items-center my-1 space-between w-full select-none gap-2 border hover:border-border border-transparent hover:bg-(--slate-3) data-[state=open]:bg-(--slate-3) data-[state=open]:border-border rounded px-1 -mx-1",
- justify === "right" && "flex-row-reverse",
- className,
- )}
- data-testid="data-table-sort-button"
- >
- <span className="flex-1">{header}</span>
- <span
- className={cn(
- "h-5 py-1 px-1",
- hideIcon &&
- "invisible group-hover:visible data-[state=open]:visible",
- )}
- >
- {renderSortFilterIcon(column)}
- </span>
- </div>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start">
- {renderDataType(column)}
- {renderSorts(column, table)}
- {renderCopyColumn(column)}
- {renderColumnPinning(column)}
- {renderColumnWrapping(column)}
- {renderFormatOptions(column, locale)}
- <DropdownMenuSeparator />
- {renderMenuItemFilter(column)}
- {renderFilterByValues(column, setIsFilterValueOpen)}
- {hasFilter && <ClearFilterMenuItem column={column} />}
- </DropdownMenuContent>
- </DropdownMenu>
+ <div
+ className={cn("group flex flex-col my-1 w-full select-none", className)}
+ >
+ <div className="flex items-center gap-1">
+ <span>{header}</span>
+ {column.getCanSort() && <SortButton column={column} />}
+ <DropdownMenu modal={false}>
+ <DropdownMenuTrigger asChild={true}>
+ <button
+ type="button"
+ className="inline-flex items-center justify-center h-5 w-5 rounded hover:bg-(--slate-4) text-muted-foreground opacity-0 group-hover:opacity-100 focus:opacity-100 group-focus-within:opacity-100 data-[state=open]:opacity-100 data-[state=open]:text-accent-foreground"
+ aria-label="Column options"
+ data-testid="data-table-column-menu-button"
+ >
+ <EllipsisIcon className="h-3.5 w-3.5" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start">
+ {renderDataType(column)}
+ {renderSorts(column, table)}
+ {renderCopyColumn(column)}
+ {renderColumnPinning(column)}
+ {renderColumnWrapping(column)}
+ {renderFormatOptions(column, locale)}
+ <DropdownMenuSeparator />
+ {renderMenuItemFilter(column)}
+ {renderFilterByValues(column, setIsFilterValueOpen)}
+ {hasFilter && <ClearFilterMenuItem column={column} />}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ {subheader}
+ </div>
{isFilterValueOpen && (
<PopoverFilterByValues
setIsFilterValueOpen={setIsFilterValueOpen}
@@ -146,28 +154,45 @@ export const DataTableColumnHeader = <TData, TValue>({
);
};
-export const DataTableColumnHeaderWithSummary = <TData, TValue>({
+const SortButton = <TData, TValue>({
column,
- header,
- summary,
- className,
-}: DataTableColumnHeaderProps<TData, TValue> & {
- summary: React.ReactNode;
+}: {
+ column: Column<TData, TValue>;
}) => {
+ const sortDirection = column.getIsSorted();
+
+ const handleClick = (e: React.MouseEvent) => {
+ e.stopPropagation();
+ if (!sortDirection) {
+ column.toggleSorting(false, true); // asc
+ } else if (sortDirection === "asc") {
+ column.toggleSorting(true, true); // desc
+ } else {
+ column.clearSorting();
+ }
+ };
+
return (
- <div
+ <button
+ type="button"
+ onClick={handleClick}
className={cn(
- "flex flex-col h-full pt-0.5 pb-3 justify-between items-start",
- className,
+ "inline-flex items-center justify-center h-5 w-5 rounded hover:bg-(--slate-4)",
+ sortDirection
+ ? "text-accent-foreground"
+ : "text-muted-foreground opacity-0 group-hover:opacity-100 focus:opacity-100 group-focus-within:opacity-100",
)}
+ aria-label={
+ sortDirection === "asc"
+ ? "Sorted ascending, click to sort descending"
+ : sortDirection === "desc"
+ ? "Sorted descending, click to clear sort"
+ : "Sort column ascending"
+ }
+ data-testid="data-table-sort-button"
>
- <DataTableColumnHeader
- column={column}
- header={header}
- className={className}
- />
- {summary}
- </div>
+ {renderSortFilterIcon(column)}
+ </button>
);
};
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsx
index ae09106e4a..274df781d9 100644
--- a/frontend/src/components/data-table/columns.tsx
+++ b/frontend/src/components/data-table/columns.tsx
@@ -206,41 +206,30 @@ export function generateColumns<T>({
</div>
) : null;
- const justify = getJustify(key);
-
- const headerWithType = (
- <div
+ const headerName = (
+ <span
className={cn(
- "flex flex-col",
- justify === "center" && "items-center",
- justify === "right" && "items-end",
+ "font-bold",
+ headerTitle && "underline decoration-dotted",
)}
>
- <span
- className={cn(
- "font-bold",
- headerTitle && "underline decoration-dotted",
- )}
- >
- {key === "" ? " " : key}
- </span>
- {dtypeHeader}
- </div>
+ {key === "" ? " " : key}
+ </span>
);
const headerWithTooltip = headerTitle ? (
<Tooltip content={headerTitle} delayDuration={300}>
- {headerWithType}
+ {headerName}
</Tooltip>
) : (
- headerWithType
+ headerName
);
const dataTableColumnHeader = (
<DataTableColumnHeader
header={headerWithTooltip}
+ subheader={dtypeHeader}
column={column}
- justify={justify}
calculateTopKRows={calculateTopKRows}
table={table}
/>
@@ -255,8 +244,6 @@ export function generateColumns<T>({
<div
className={cn(
"flex flex-col h-full pt-0.5 pb-3 justify-between items-start",
- justify === "center" && "items-center",
- justify === "right" && "items-end",
)}
>
{dataTableColumnHeader}
@@ -283,13 +270,13 @@ export function generateColumns<T>({
const dataType = column.columnDef.meta?.dataType;
const isNumeric = dataType === "number" || dataType === "integer";
- const cellStyles = getCellStyleClass(
+ const cellStyles = getCellStyleClass({
justify,
wrapped,
canSelectCell,
- isCellSelected,
+ isSelected: isCellSelected,
isNumeric,
- );
+ });
const renderedCell = renderCellValue({
column,
@@ -448,13 +435,19 @@ function getFilterTypeForFieldType(
}
}
-function getCellStyleClass(
- justify: "left" | "center" | "right" | undefined,
- wrapped: boolean | undefined,
- canSelectCell: boolean,
- isSelected: boolean,
- isNumeric?: boolean,
-): string {
+function getCellStyleClass({
+ justify = "left",
+ wrapped,
+ canSelectCell,
+ isSelected,
+ isNumeric = false,
+}: {
+ justify: "left" | "center" | "right" | undefined;
+ wrapped: boolean | undefined;
+ canSelectCell: boolean;
+ isSelected: boolean;
+ isNumeric?: boolean;
+}): string {
return cn(
canSelectCell && "cursor-pointer",
isSelected &&
diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsx
index d306205f28..3436c85476 100644
--- a/frontend/src/components/data-table/data-table.tsx
+++ b/frontend/src/components/data-table/data-table.tsx
@@ -47,6 +47,7 @@ import { DataTableBody, renderTableHeader } from "./renderers";
import { TableBottomBar } from "./TableBottomBar";
import { TableTopBar } from "./TableTopBar";
import {
+ AUTO_WIDTH_MAX_COLUMNS,
type DataTableSelection,
MIN_ROWS_TO_VIRTUALIZE,
type TooManyRows,
@@ -300,7 +301,13 @@ const DataTableInternal = <TData,>({
isAnyPanelOpen={isAnyPanelOpen}
downloadAs={downloadAs}
/>
- <Table className="relative" ref={tableRef}>
+ <Table
+ className={cn(
+ "relative",
+ columns.length <= AUTO_WIDTH_MAX_COLUMNS ? "w-auto" : "w-full",
+ )}
+ ref={tableRef}
+ >
{showLoadingBar && (
<thead className="absolute top-0 left-0 h-[3px] w-1/2 bg-primary animate-slide" />
)}
diff --git a/frontend/src/components/data-table/renderers.tsx b/frontend/src/components/data-table/renderers.tsx
index 94b3c3efe4..0d435d6682 100644
--- a/frontend/src/components/data-table/renderers.tsx
+++ b/frontend/src/components/data-table/renderers.tsx
@@ -27,7 +27,7 @@ import { DataTableContextMenu } from "./context-menu";
import { CellRangeSelectionIndicator } from "./range-focus/cell-selection-indicator";
import { useCellRangeSelection } from "./range-focus/use-cell-range-selection";
import { useScrollIntoViewOnFocus } from "./range-focus/use-scroll-into-view";
-import { TABLE_ROW_HEIGHT_PX } from "./types";
+import { AUTO_WIDTH_MAX_COLUMNS, TABLE_ROW_HEIGHT_PX } from "./types";
import { stringifyUnknownValue } from "./utils";
export function renderTableHeader<TData>(
@@ -46,7 +46,7 @@ export function renderTableHeader<TData>(
<TableHead
key={header.id}
className={cn(
- "h-auto min-h-10 whitespace-pre align-top",
+ "h-auto min-h-10 whitespace-pre align-top border-r border-r-border/75",
className,
)}
style={style}
@@ -69,6 +69,13 @@ export function renderTableHeader<TData>(
{renderHeaderGroup(table.getLeftHeaderGroups())}
{renderHeaderGroup(table.getCenterHeaderGroups())}
{renderHeaderGroup(table.getRightHeaderGroups())}
+ {table.getAllColumns().length <= AUTO_WIDTH_MAX_COLUMNS && (
+ <th
+ className="w-full border-0"
+ aria-hidden="true"
+ role="presentation"
+ />
+ )}
</TableRow>
</TableHeader>
);
@@ -163,7 +170,7 @@ export const DataTableBody = <TData,>({
{...getCellDomProps(cell.id)}
key={cell.id}
className={cn(
- "whitespace-pre truncate max-w-[300px] outline-hidden",
+ "whitespace-pre truncate max-w-[300px] outline-hidden border-r border-r-border/75",
cell.column.getColumnWrapping &&
cell.column.getColumnWrapping?.() === "wrap" &&
COLUMN_WRAPPING_STYLES,
@@ -230,15 +237,21 @@ export const DataTableBody = <TData,>({
{renderCells(row.getLeftVisibleCells())}
{renderCells(row.getCenterVisibleCells())}
{renderCells(row.getRightVisibleCells())}
+ {columns.length <= AUTO_WIDTH_MAX_COLUMNS && (
+ <td className="border-0" aria-hidden="true" role="presentation" />
+ )}
</TableRow>
);
};
+ const hasFillerColumn = columns.length <= AUTO_WIDTH_MAX_COLUMNS;
+ const totalColSpan = columns.length + (hasFillerColumn ? 1 : 0);
+
const renderRows = () => {
if (rows.length === 0) {
return (
<TableRow>
- <TableCell colSpan={columns.length} className="h-24 text-center">
+ <TableCell colSpan={totalColSpan} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
@@ -255,7 +268,7 @@ export const DataTableBody = <TData,>({
data-virtual-spacer=""
style={{ height: virtualItems[0].start }}
>
- <td colSpan={columns.length} />
+ <td colSpan={totalColSpan} />
</tr>
)}
{virtualItems.map((vItem) => renderRow(rows[vItem.index]))}
@@ -266,7 +279,7 @@ export const DataTableBody = <TData,>({
height: totalSize - (virtualItems.at(-1)?.end ?? totalSize),
}}
>
- <td colSpan={columns.length} />
+ <td colSpan={totalColSpan} />
</tr>
)}
</>
diff --git a/frontend/src/components/data-table/types.ts b/frontend/src/components/data-table/types.ts
index 6280e3a98c..43be0f851f 100644
--- a/frontend/src/components/data-table/types.ts
+++ b/frontend/src/components/data-table/types.ts
@@ -16,6 +16,10 @@ declare module "@tanstack/react-table" {
export const TABLE_ROW_HEIGHT_PX = 24;
export const TABLE_HEADER_HEIGHT_PX = 40;
+// Below this column count, the table uses w-auto with a filler column
+// to prevent columns from stretching unnecessarily
+export const AUTO_WIDTH_MAX_COLUMNS = 4;
+
// Default number of visible rows when virtualizing without an explicit maxHeight.
export const DEFAULT_VIRTUAL_ROWS = 15;