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(table): column visibility dropdown in table top bar (#9865)

Kiran Gadhave9bd649c9a0f5
diff --git a/frontend/src/components/data-table/TableBottomBar.tsx b/frontend/src/components/data-table/TableBottomBar.tsx
index 9cd2f1b640..088f339265 100644
--- a/frontend/src/components/data-table/TableBottomBar.tsx
+++ b/frontend/src/components/data-table/TableBottomBar.tsx
@@ -7,10 +7,6 @@ import type { GetRowIds } from "@/plugins/impl/DataTablePlugin";
import { cn } from "@/utils/cn";
import { Events } from "@/utils/events";
import { prettyNumber } from "@/utils/numbers";
-import {
- PANEL_TYPES,
- type PanelType,
-} from "../editor/chrome/panels/context-aware-panel/context-aware-panel";
import { Button } from "../ui/button";
import { toast } from "../ui/use-toast";
import { getColumnCountForDisplay } from "./hooks/use-column-visibility";
@@ -27,7 +23,6 @@ interface TableBottomBarProps<TData> {
getRowIds?: GetRowIds;
showPageSizeSelector?: boolean;
tableLoading?: boolean;
- togglePanel?: (panelType: PanelType) => void;
part?: string;
className?: string;
}
@@ -41,7 +36,6 @@ export const TableBottomBar = <TData,>({
getRowIds,
showPageSizeSelector,
tableLoading,
- togglePanel,
part,
className,
}: TableBottomBarProps<TData>) => {
@@ -159,15 +153,7 @@ export const TableBottomBar = <TData,>({
return (
<span className="flex items-center gap-1">
<span>{rowsAndColumns}</span>
- {hiddenSuffix && (
- <button
- type="button"
- className="text-xs underline-offset-2 hover:underline cursor-pointer"
- onClick={() => togglePanel?.(PANEL_TYPES.COLUMN_EXPLORER)}
- >
- {hiddenSuffix}
- </button>
- )}
+ {hiddenSuffix && <span className="text-xs">{hiddenSuffix}</span>}
</span>
);
};
diff --git a/frontend/src/components/data-table/TableTopBar.tsx b/frontend/src/components/data-table/TableTopBar.tsx
index 83706cb23f..052be468b2 100644
--- a/frontend/src/components/data-table/TableTopBar.tsx
+++ b/frontend/src/components/data-table/TableTopBar.tsx
@@ -1,6 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
"use no memo";
+import type { Table } from "@tanstack/react-table";
import { useDebounce } from "@uidotdev/usehooks";
import {
ChartSplineIcon,
@@ -17,13 +18,15 @@ import {
} from "../editor/chrome/panels/context-aware-panel/context-aware-panel";
import { Spinner } from "../icons/spinner";
import { Button } from "../ui/button";
+import { ColumnVisibilityDropdown } from "./column-visibility-dropdown";
import { type ExportActionProps, ExportMenu } from "./export-actions";
const NOOP_ON_SEARCH = () => {
/** no-op*/
};
-interface TableTopBarProps extends Partial<ExportActionProps> {
+interface TableTopBarProps<TData> extends Partial<ExportActionProps> {
+ table: Table<TData>;
enableSearch: boolean;
searchQuery?: string;
onSearchQueryChange?: (query: string) => void;
@@ -38,7 +41,8 @@ interface TableTopBarProps extends Partial<ExportActionProps> {
sizeBytesIsLoading?: boolean;
}
-export const TableTopBar: React.FC<TableTopBarProps> = ({
+export const TableTopBar = <TData,>({
+ table,
enableSearch,
searchQuery,
onSearchQueryChange,
@@ -52,7 +56,7 @@ export const TableTopBar: React.FC<TableTopBarProps> = ({
downloadAs,
sizeBytes,
sizeBytesIsLoading,
-}) => {
+}: TableTopBarProps<TData>) => {
const [internalValue, setInternalValue] = useState(searchQuery || "");
const debouncedSearch = useDebounce(internalValue, 500);
const onSearch = useEvent(onSearchQueryChange ?? NOOP_ON_SEARCH);
@@ -62,16 +66,6 @@ export const TableTopBar: React.FC<TableTopBarProps> = ({
onSearch(debouncedSearch);
}, [debouncedSearch, onSearch]);
- const hasAnyAction =
- (enableSearch && onSearchQueryChange) ||
- showChartBuilder ||
- showTableExplorer ||
- downloadAs;
-
- if (!hasAnyAction) {
- return null;
- }
-
return (
<div className="flex items-center h-10 px-2 border-b gap-2">
{onSearchQueryChange && enableSearch && (
@@ -106,6 +100,7 @@ export const TableTopBar: React.FC<TableTopBarProps> = ({
)}
<div className="flex items-center shrink-0">
+ <ColumnVisibilityDropdown table={table} />
{showChartBuilder && (
<Button
variant="text"
diff --git a/frontend/src/components/data-table/__tests__/TableBottomBar.test.tsx b/frontend/src/components/data-table/__tests__/TableBottomBar.test.tsx
index 8f5e3235cc..ddada2cbf9 100644
--- a/frontend/src/components/data-table/__tests__/TableBottomBar.test.tsx
+++ b/frontend/src/components/data-table/__tests__/TableBottomBar.test.tsx
@@ -3,7 +3,7 @@
import { getCoreRowModel, useReactTable } from "@tanstack/react-table";
import { render, screen } from "@testing-library/react";
-import { describe, expect, it, vi } from "vitest";
+import { describe, expect, it } from "vitest";
import { TooltipProvider } from "@/components/ui/tooltip";
import { CellSelectionProvider } from "../range-focus/provider";
import { TableBottomBar } from "../TableBottomBar";
@@ -11,7 +11,6 @@ import { TableBottomBar } from "../TableBottomBar";
function renderWithTable(opts: {
totalColumns: number;
hiddenColumns?: string[];
- togglePanel?: (panelType: string) => void;
}) {
const Wrapper = () => {
const table = useReactTable({
@@ -34,7 +33,6 @@ function renderWithTable(opts: {
pagination={false}
totalColumns={opts.totalColumns}
table={table}
- togglePanel={opts.togglePanel}
/>
);
};
@@ -60,14 +58,10 @@ describe("TableBottomBar — hidden column count", () => {
expect(screen.getByText(/\(1 hidden\)/)).toBeInTheDocument();
});
- it("invokes togglePanel('column-explorer') when '(n hidden)' is clicked", () => {
- const togglePanel = vi.fn();
- renderWithTable({
- totalColumns: 3,
- hiddenColumns: ["col1"],
- togglePanel,
- });
- screen.getByText(/\(1 hidden\)/).click();
- expect(togglePanel).toHaveBeenCalledWith("column-explorer");
+ it("renders '(n hidden)' as inert text, not a button", () => {
+ renderWithTable({ totalColumns: 3, hiddenColumns: ["col1"] });
+ const suffix = screen.getByText(/\(1 hidden\)/);
+ expect(suffix.tagName).toBe("SPAN");
+ expect(suffix.closest("button")).toBeNull();
});
});
diff --git a/frontend/src/components/data-table/__tests__/column-visibility-dropdown.test.tsx b/frontend/src/components/data-table/__tests__/column-visibility-dropdown.test.tsx
new file mode 100644
index 0000000000..4a73c6daa5
--- /dev/null
+++ b/frontend/src/components/data-table/__tests__/column-visibility-dropdown.test.tsx
@@ -0,0 +1,227 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import {
+ type ColumnDef,
+ getCoreRowModel,
+ useReactTable,
+} from "@tanstack/react-table";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { beforeAll, describe, expect, it } from "vitest";
+import { ColumnVisibilityDropdown } from "../column-visibility-dropdown";
+import { INDEX_COLUMN_NAME, SELECT_COLUMN_ID } from "../types";
+
+beforeAll(() => {
+ global.HTMLElement.prototype.scrollIntoView = () => {
+ // jsdom does not implement scrollIntoView; cmdk calls it on selection.
+ };
+ if (!global.HTMLElement.prototype.hasPointerCapture) {
+ global.HTMLElement.prototype.hasPointerCapture = () => false;
+ }
+});
+
+type Row = Record<string, unknown>;
+
+const TEST_COLUMNS: ColumnDef<Row>[] = [
+ { id: SELECT_COLUMN_ID, accessorKey: SELECT_COLUMN_ID },
+ { id: INDEX_COLUMN_NAME, accessorKey: INDEX_COLUMN_NAME },
+ { id: "__m_column__0", accessorKey: "__m_column__0" },
+ {
+ id: "customer_name",
+ accessorKey: "customer_name",
+ meta: { dataType: "string" },
+ },
+ { id: "cust_age", accessorKey: "cust_age", meta: { dataType: "integer" } },
+ {
+ id: "order_total",
+ accessorKey: "order_total",
+ meta: { dataType: "number" },
+ },
+];
+
+interface HarnessProps {
+ initiallyHidden?: string[];
+ nonHideable?: string[];
+}
+
+function Harness({ initiallyHidden = [], nonHideable = [] }: HarnessProps) {
+ const table = useReactTable<Row>({
+ data: [],
+ columns: TEST_COLUMNS.map((column) =>
+ nonHideable.includes(column.id as string)
+ ? { ...column, enableHiding: false }
+ : column,
+ ),
+ getCoreRowModel: getCoreRowModel(),
+ locale: "en-US",
+ initialState: {
+ columnVisibility: Object.fromEntries(
+ initiallyHidden.map((id) => [id, false]),
+ ),
+ },
+ });
+ return <ColumnVisibilityDropdown table={table} />;
+}
+
+function renderAndOpen(props?: HarnessProps) {
+ const result = render(<Harness {...(props ?? {})} />);
+ fireEvent.click(screen.getByTestId("column-visibility-trigger"));
+ return result;
+}
+
+function getOptionTexts(): string[] {
+ return screen.getAllByRole("option").map((el) => el.textContent ?? "");
+}
+
+function getColumnOption(name: string): HTMLElement {
+ const option = screen
+ .getAllByRole("option")
+ .find((el) => el.textContent === name);
+ if (!option) {
+ throw new Error(`No option for column ${name}`);
+ }
+ return option;
+}
+
+function getSearchInput() {
+ return screen.getByPlaceholderText("Search columns...");
+}
+
+describe("ColumnVisibilityDropdown", () => {
+ it("renders user columns and excludes select/index/nameless columns", () => {
+ renderAndOpen();
+ expect(screen.getByText("customer_name")).toBeInTheDocument();
+ expect(screen.getByText("cust_age")).toBeInTheDocument();
+ expect(screen.getByText("order_total")).toBeInTheDocument();
+ expect(screen.queryByText(SELECT_COLUMN_ID)).not.toBeInTheDocument();
+ expect(screen.queryByText(INDEX_COLUMN_NAME)).not.toBeInTheDocument();
+ expect(screen.queryByText("__m_column__0")).not.toBeInTheDocument();
+ });
+
+ it("lists hidden columns before shown columns", () => {
+ renderAndOpen({ initiallyHidden: ["cust_age"] });
+ expect(getOptionTexts()).toEqual([
+ "Show all",
+ "cust_age",
+ "customer_name",
+ "order_total",
+ ]);
+ });
+
+ it("toggling a hidden column flips the icon without moving the row", () => {
+ renderAndOpen({ initiallyHidden: ["cust_age"] });
+ expect(
+ getColumnOption("cust_age").querySelector(".lucide-eye-off"),
+ ).not.toBeNull();
+
+ fireEvent.click(getColumnOption("cust_age"));
+
+ expect(getOptionTexts()).toEqual([
+ "Show all",
+ "cust_age",
+ "customer_name",
+ "order_total",
+ ]);
+ expect(
+ getColumnOption("cust_age").querySelector(".lucide-eye-off"),
+ ).toBeNull();
+ });
+
+ it("re-sorts on reopen after a toggle", () => {
+ renderAndOpen({ initiallyHidden: ["cust_age"] });
+ // Hide customer_name: it stays in the shown section until reopen.
+ fireEvent.click(getColumnOption("customer_name"));
+ expect(getOptionTexts()).toEqual([
+ "Show all",
+ "cust_age",
+ "customer_name",
+ "order_total",
+ ]);
+
+ const trigger = screen.getByTestId("column-visibility-trigger");
+ fireEvent.click(trigger);
+ fireEvent.click(trigger);
+
+ // Reopen sorts both hidden columns first, preserving table order.
+ expect(getOptionTexts()).toEqual([
+ "Show all",
+ "customer_name",
+ "cust_age",
+ "order_total",
+ ]);
+ });
+
+ it("filters columns with smartMatch", () => {
+ renderAndOpen();
+ fireEvent.change(getSearchInput(), { target: { value: "cust" } });
+ expect(screen.getByText("customer_name")).toBeInTheDocument();
+ expect(screen.getByText("cust_age")).toBeInTheDocument();
+ expect(screen.queryByText("order_total")).not.toBeInTheDocument();
+ });
+
+ it("shows 'No results.' when nothing matches", () => {
+ renderAndOpen();
+ fireEvent.change(getSearchInput(), { target: { value: "xyz" } });
+ expect(screen.getByText("No results.")).toBeInTheDocument();
+ expect(screen.queryByText("customer_name")).not.toBeInTheDocument();
+ });
+
+ it("disables 'Show all' when no columns are hidden", () => {
+ renderAndOpen();
+ expect(getColumnOption("Show all")).toHaveAttribute(
+ "aria-disabled",
+ "true",
+ );
+ });
+
+ it("'Show all' restores hidden columns", () => {
+ renderAndOpen({ initiallyHidden: ["cust_age", "order_total"] });
+ fireEvent.click(getColumnOption("Show all"));
+
+ expect(
+ getColumnOption("cust_age").querySelector(".lucide-eye-off"),
+ ).toBeNull();
+ expect(
+ getColumnOption("order_total").querySelector(".lucide-eye-off"),
+ ).toBeNull();
+ expect(getColumnOption("Show all")).toHaveAttribute(
+ "aria-disabled",
+ "true",
+ );
+ });
+
+ it("hides and shows matching columns via bulk actions while searching", () => {
+ renderAndOpen();
+ fireEvent.change(getSearchInput(), { target: { value: "cust" } });
+ expect(screen.queryByText(/Show all/)).not.toBeInTheDocument();
+
+ fireEvent.click(getColumnOption("Hide 2 matching"));
+ expect(
+ getColumnOption("customer_name").querySelector(".lucide-eye-off"),
+ ).not.toBeNull();
+ expect(
+ getColumnOption("cust_age").querySelector(".lucide-eye-off"),
+ ).not.toBeNull();
+ expect(screen.queryByText(/Hide \d+ matching/)).not.toBeInTheDocument();
+
+ fireEvent.click(getColumnOption("Show 2 matching"));
+ expect(
+ getColumnOption("customer_name").querySelector(".lucide-eye-off"),
+ ).toBeNull();
+ expect(screen.queryByText(/Show \d+ matching/)).not.toBeInTheDocument();
+ });
+
+ it("offers both bulk actions when matches are mixed", () => {
+ renderAndOpen({ initiallyHidden: ["cust_age"] });
+ fireEvent.change(getSearchInput(), { target: { value: "cust" } });
+ expect(screen.getByText(/Hide 1 matching/)).toBeInTheDocument();
+ expect(screen.getByText(/Show 1 matching/)).toBeInTheDocument();
+ });
+
+ it("renders non-hideable columns disabled and without an eye toggle", () => {
+ renderAndOpen({ nonHideable: ["customer_name"] });
+ const option = getColumnOption("customer_name");
+ expect(option).toHaveAttribute("aria-disabled", "true");
+ expect(option.querySelector(".lucide-eye")).toBeNull();
+ expect(option.querySelector(".lucide-eye-off")).toBeNull();
+ });
+});
diff --git a/frontend/src/components/data-table/column-visibility-dropdown.tsx b/frontend/src/components/data-table/column-visibility-dropdown.tsx
new file mode 100644
index 0000000000..09f92b57be
--- /dev/null
+++ b/frontend/src/components/data-table/column-visibility-dropdown.tsx
@@ -0,0 +1,204 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+"use no memo";
+
+// tanstack/table is not compatible with React compiler
+// https://github.com/TanStack/table/issues/5567
+
+import type { Table } from "@tanstack/react-table";
+import { Columns3Icon, EyeIcon, EyeOffIcon } from "lucide-react";
+import React from "react";
+import { ColumnName } from "@/components/datasources/components";
+import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandInput,
+ CommandItem,
+ CommandList,
+ CommandSeparator,
+} from "@/components/ui/command";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { type BulkAction, useSelectList } from "@/components/ui/select-core";
+import type { DataType } from "@/core/kernel/messages";
+import { cn } from "@/utils/cn";
+import { Events } from "@/utils/events";
+import { smartMatchFilter } from "@/utils/smartMatch";
+import { NAMELESS_COLUMN_PREFIX } from "./columns";
+import { INDEX_COLUMN_NAME, SELECT_COLUMN_ID } from "./types";
+
+function getUserColumns<TData>(table: Table<TData>) {
+ return table
+ .getAllLeafColumns()
+ .filter(
+ (column) =>
+ column.id !== SELECT_COLUMN_ID &&
+ column.id !== INDEX_COLUMN_NAME &&
+ !column.id.startsWith(NAMELESS_COLUMN_PREFIX),
+ );
+}
+
+export const ColumnVisibilityDropdown = <TData,>({
+ table,
+}: {
+ table: Table<TData>;
+}) => {
+ const userColumns = getUserColumns(table);
+ const options = userColumns.map((column) => ({
+ value: column.id,
+ label: column.id,
+ disabled: !column.getCanHide(),
+ data: { dataType: column.columnDef.meta?.dataType },
+ }));
+ // Modeled as a select list over hidden columns: "selected" means hidden, so
+ // the hook's pinning floats hidden columns to the top and freezes that order
+ // while the menu is open.
+ const hiddenIds = userColumns
+ .filter((column) => !column.getIsVisible())
+ .map((column) => column.id);
+
+ const applyHidden = (next: string[] | string | null) => {
+ const hidden = new Set(Array.isArray(next) ? next : []);
+ table.setColumnVisibility((previous) => ({
+ ...previous,
+ ...Object.fromEntries(
+ userColumns.map((column) => [column.id, !hidden.has(column.id)]),
+ ),
+ }));
+ };
+
+ const list = useSelectList<string>({
+ options,
+ value: hiddenIds,
+ onChange: applyHidden,
+ multiple: true,
+ filterFn: smartMatchFilter,
+ pinSelected: true,
+ });
+ // With selection modeling hidden columns, select-matching hides the visible
+ // matches and deselect-matching shows the hidden ones.
+ const matchingActions = list.bulkActions.filter(
+ (
+ action,
+ ): action is Extract<
+ BulkAction<string>,
+ { kind: "select-matching" | "deselect-matching" }
+ > =>
+ action.kind === "select-matching" || action.kind === "deselect-matching",
+ );
+
+ return (
+ <Popover open={list.open} onOpenChange={list.setOpen}>
+ <PopoverTrigger asChild={true}>
+ <Button
+ variant="text"
+ size="xs"
+ data-testid="column-visibility-trigger"
+ onMouseDown={Events.preventFocus}
+ className={cn(
+ "print:hidden text-xs gap-1",
+ list.open ? "text-primary" : "text-muted-foreground",
+ )}
+ >
+ <Columns3Icon className="w-3.5 h-3.5" />
+ Columns
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-64 p-0" align="end">
+ <Command shouldFilter={false}>
+ <CommandInput
+ placeholder="Search columns..."
+ value={list.searchQuery}
+ onValueChange={list.setSearchQuery}
+ />
+ <CommandList>
+ <CommandEmpty>No results.</CommandEmpty>
+ {list.searchQuery === "" ? (
+ <>
+ <CommandItem
+ value="__show_all__"
+ disabled={hiddenIds.length === 0}
+ onSelect={() => applyHidden([])}
+ className="cursor-pointer"
+ >
+ <EyeIcon className="w-3 h-3 mr-1.5" />
+ Show all
+ </CommandItem>
+ <CommandSeparator />
+ </>
+ ) : (
+ matchingActions.length > 0 && (
+ <>
+ {matchingActions.map((action) => (
+ <CommandItem
+ key={action.kind}
+ value={`__bulk_${action.kind}`}
+ onSelect={action.run}
+ className="cursor-pointer"
+ >
+ {action.kind === "select-matching" ? (
+ <EyeOffIcon className="w-3 h-3 mr-1.5" />
+ ) : (
+ <EyeIcon className="w-3 h-3 mr-1.5" />
+ )}
+ {action.kind === "select-matching" ? "Hide" : "Show"}{" "}
+ {action.items.length} matching
+ </CommandItem>
+ ))}
+ <CommandSeparator />
+ </>
+ )
+ )}
+ {list.visibleOptions.map((option, index) => {
+ const hidden = list.isChecked(option.value);
+ const { dataType } = option.data as {
+ dataType: DataType | undefined;
+ };
+ const isSectionBoundary =
+ index === list.pinnedCount &&
+ list.pinnedCount > 0 &&
+ list.pinnedCount < list.visibleOptions.length;
+ return (
+ <React.Fragment key={option.value}>
+ {isSectionBoundary && <CommandSeparator />}
+ <CommandItem
+ value={option.value}
+ disabled={option.disabled}
+ onSelect={() => list.toggle(option.value)}
+ className="flex items-center gap-1.5 cursor-pointer"
+ >
+ {dataType === undefined ? (
+ <span>{option.label}</span>
+ ) : (
+ <ColumnName
+ columnName={option.label}
+ dataType={dataType}
+ />
+ )}
+ {!option.disabled && (
+ <span
+ className={cn(
+ "ml-auto",
+ hidden ? "text-primary" : "text-muted-foreground",
+ )}
+ >
+ {hidden ? (
+ <EyeOffIcon className="w-3 h-3" />
+ ) : (
+ <EyeIcon className="w-3 h-3" />
+ )}
+ </span>
+ )}
+ </CommandItem>
+ </React.Fragment>
+ );
+ })}
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ );
+};
diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsx
index 7c0bfdf8f7..44f3752405 100644
--- a/frontend/src/components/data-table/data-table.tsx
+++ b/frontend/src/components/data-table/data-table.tsx
@@ -356,6 +356,7 @@ const DataTableInternal = <TData,>({
className={cn(className || "rounded-md border overflow-hidden")}
>
<TableTopBar
+ table={table}
enableSearch={enableSearch}
searchQuery={searchQuery}
onSearchQueryChange={onSearchQueryChange}
@@ -413,7 +414,6 @@ const DataTableInternal = <TData,>({
getRowIds={getRowIds}
showPageSizeSelector={showPageSizeSelector}
tableLoading={reloading}
- togglePanel={togglePanel}
/>
</div>
</CellSelectionProvider>