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: persistent top toolbar in data table with search, chart-builder, and other actions (#8932)

Kiran Gadhavefd7f11f50485
diff --git a/frontend/src/components/data-table/TableActions.tsx b/frontend/src/components/data-table/TableActions.tsx
deleted file mode 100644
index d2f386abfc..0000000000
--- a/frontend/src/components/data-table/TableActions.tsx
+++ /dev/null
@@ -1,170 +0,0 @@
-/* Copyright 2026 Marimo. All rights reserved. */
-"use no memo";
-
-import type { RowSelectionState, Table } from "@tanstack/react-table";
-import { ChartSplineIcon, PanelRightIcon, SearchIcon } from "lucide-react";
-import React from "react";
-import { useLocale } from "react-aria";
-import type { GetRowIds } from "@/plugins/impl/DataTablePlugin";
-import { cn } from "@/utils/cn";
-import {
- PANEL_TYPES,
- type PanelType,
-} from "../editor/chrome/panels/context-aware-panel/context-aware-panel";
-import { Button } from "../ui/button";
-import { Tooltip } from "../ui/tooltip";
-import { toast } from "../ui/use-toast";
-import { type DownloadActionProps, DownloadAs } from "./download-actions";
-import { DataTablePagination, prettifyRowColumnCount } from "./pagination";
-import type { DataTableSelection } from "./types";
-
-interface TableActionsProps<TData> {
- enableSearch: boolean;
- onSearchQueryChange?: (query: string) => void;
- isSearchEnabled: boolean;
- setIsSearchEnabled: React.Dispatch<React.SetStateAction<boolean>>;
- pagination: boolean;
- totalColumns: number;
- selection?: DataTableSelection;
- onRowSelectionChange?: (value: RowSelectionState) => void;
- table: Table<TData>;
- downloadAs?: DownloadActionProps["downloadAs"];
- getRowIds?: GetRowIds;
- toggleDisplayHeader?: () => void;
- showChartBuilder?: boolean;
- showTableExplorer?: boolean;
- showPageSizeSelector?: boolean;
- togglePanel?: (panelType: PanelType) => void;
- isAnyPanelOpen?: boolean;
- tableLoading?: boolean;
-}
-
-export const TableActions = <TData,>({
- enableSearch,
- onSearchQueryChange,
- isSearchEnabled,
- setIsSearchEnabled,
- pagination,
- totalColumns,
- selection,
- onRowSelectionChange,
- table,
- downloadAs,
- getRowIds,
- toggleDisplayHeader,
- showChartBuilder,
- showTableExplorer,
- showPageSizeSelector,
- togglePanel,
- isAnyPanelOpen,
- tableLoading,
-}: TableActionsProps<TData>) => {
- const { locale } = useLocale();
- const handleSelectAllRows = (value: boolean) => {
- if (!onRowSelectionChange) {
- return;
- }
-
- // Clear all selections
- if (!value) {
- onRowSelectionChange({});
- return;
- }
-
- const selectAllRowsByIndex = () => {
- const allKeys = Array.from(
- { length: table.getRowCount() },
- (_, i) => [i, true] as const,
- );
- onRowSelectionChange(Object.fromEntries(allKeys));
- };
-
- if (!getRowIds) {
- selectAllRowsByIndex();
- return;
- }
-
- getRowIds({}).then((data) => {
- if (data.error) {
- toast({
- title: "Not available",
- description: data.error,
- variant: "danger",
- });
- return;
- }
-
- if (data.all_rows) {
- selectAllRowsByIndex();
- } else {
- onRowSelectionChange(
- Object.fromEntries(data.row_ids.map((id) => [id, true])),
- );
- }
- });
- };
-
- return (
- <div className="flex items-center shrink-0 pt-1">
- {onSearchQueryChange && enableSearch && (
- <Tooltip content="Search">
- <Button
- variant="text"
- size="xs"
- className="mb-0 print:hidden"
- onClick={() => setIsSearchEnabled(!isSearchEnabled)}
- >
- <SearchIcon className="w-4 h-4 text-muted-foreground" />
- </Button>
- </Tooltip>
- )}
- {showChartBuilder && (
- <Tooltip content="Chart builder">
- <Button
- variant="text"
- size="xs"
- className="mb-0 print:hidden"
- onClick={toggleDisplayHeader}
- >
- <ChartSplineIcon className="w-4 h-4 text-muted-foreground" />
- </Button>
- </Tooltip>
- )}
- {showTableExplorer && togglePanel && (
- <Tooltip content="Toggle table explorer">
- <Button
- variant="text"
- size="xs"
- onClick={() => togglePanel(PANEL_TYPES.ROW_VIEWER)}
- className="print:hidden"
- >
- <PanelRightIcon
- className={cn(
- "w-4 h-4 text-muted-foreground",
- isAnyPanelOpen && "text-primary",
- )}
- />
- </Button>
- </Tooltip>
- )}
-
- {pagination ? (
- <DataTablePagination
- totalColumns={totalColumns}
- selection={selection}
- onSelectAllRowsChange={handleSelectAllRows}
- table={table}
- tableLoading={tableLoading}
- showPageSizeSelector={showPageSizeSelector}
- />
- ) : (
- <span className="text-xs text-muted-foreground px-2">
- {prettifyRowColumnCount(table.getRowCount(), totalColumns, locale)}
- </span>
- )}
- <div className="ml-auto">
- {downloadAs && <DownloadAs downloadAs={downloadAs} />}
- </div>
- </div>
- );
-};
diff --git a/frontend/src/components/data-table/TableBottomBar.tsx b/frontend/src/components/data-table/TableBottomBar.tsx
new file mode 100644
index 0000000000..7171c13603
--- /dev/null
+++ b/frontend/src/components/data-table/TableBottomBar.tsx
@@ -0,0 +1,165 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+"use no memo";
+
+import type { RowSelectionState, Table } from "@tanstack/react-table";
+import { useLocale } from "react-aria";
+import type { GetRowIds } from "@/plugins/impl/DataTablePlugin";
+import { Events } from "@/utils/events";
+import { prettyNumber } from "@/utils/numbers";
+import { Button } from "../ui/button";
+import { toast } from "../ui/use-toast";
+import { DataTablePagination, prettifyRowColumnCount } from "./pagination";
+import { CellSelectionStats } from "./range-focus/cell-selection-stats";
+import type { DataTableSelection } from "./types";
+
+interface TableBottomBarProps<TData> {
+ pagination: boolean;
+ totalColumns: number;
+ selection?: DataTableSelection;
+ onRowSelectionChange?: (value: RowSelectionState) => void;
+ table: Table<TData>;
+ getRowIds?: GetRowIds;
+ showPageSizeSelector?: boolean;
+ tableLoading?: boolean;
+}
+
+export const TableBottomBar = <TData,>({
+ pagination,
+ totalColumns,
+ selection,
+ onRowSelectionChange,
+ table,
+ getRowIds,
+ showPageSizeSelector,
+ tableLoading,
+}: TableBottomBarProps<TData>) => {
+ const { locale } = useLocale();
+ const handleSelectAllRows = (value: boolean) => {
+ if (!onRowSelectionChange) {
+ return;
+ }
+
+ // Clear all selections
+ if (!value) {
+ onRowSelectionChange({});
+ return;
+ }
+
+ const selectAllRowsByIndex = () => {
+ const allKeys = Array.from(
+ { length: table.getRowCount() },
+ (_, i) => [i, true] as const,
+ );
+ onRowSelectionChange(Object.fromEntries(allKeys));
+ };
+
+ if (!getRowIds) {
+ selectAllRowsByIndex();
+ return;
+ }
+
+ getRowIds({}).then((data) => {
+ if (data.error) {
+ toast({
+ title: "Not available",
+ description: data.error,
+ variant: "danger",
+ });
+ return;
+ }
+
+ if (data.all_rows) {
+ selectAllRowsByIndex();
+ } else {
+ onRowSelectionChange(
+ Object.fromEntries(data.row_ids.map((id) => [id, true])),
+ );
+ }
+ });
+ };
+
+ const renderTotal = () => {
+ const { rowSelection, cellSelection } = table.getState();
+ let selected = Object.keys(rowSelection).length;
+ let isAllPageSelected = table.getIsAllPageRowsSelected();
+ const numRows = table.getRowCount();
+ let isAllSelected = selected === numRows;
+
+ const isCellSelection =
+ selection === "single-cell" || selection === "multi-cell";
+ if (isCellSelection) {
+ selected = cellSelection.length;
+ isAllPageSelected = false;
+ isAllSelected = false;
+ }
+
+ if (isAllPageSelected && !isAllSelected) {
+ return (
+ <>
+ <span>{prettyNumber(selected, locale)} selected</span>
+ <Button
+ size="xs"
+ data-testid="select-all-button"
+ variant="link"
+ className="h-4 print:hidden"
+ onMouseDown={Events.preventFocus}
+ onClick={() => handleSelectAllRows(true)}
+ >
+ Select all {prettyNumber(numRows, locale)}
+ </Button>
+ </>
+ );
+ }
+
+ if (selected) {
+ return (
+ <>
+ <span>{prettyNumber(selected, locale)} selected</span>
+ <Button
+ size="xs"
+ data-testid="clear-selection-button"
+ variant="link"
+ className="h-4 print:hidden"
+ onMouseDown={Events.preventFocus}
+ onClick={() => {
+ if (!isCellSelection) {
+ handleSelectAllRows(false);
+ } else if (table.resetCellSelection) {
+ table.resetCellSelection();
+ }
+ }}
+ >
+ Clear selection
+ </Button>
+ </>
+ );
+ }
+
+ return (
+ <span>
+ {prettifyRowColumnCount(table.getRowCount(), totalColumns, locale)}
+ </span>
+ );
+ };
+
+ return (
+ <div className="flex lg:grid lg:grid-cols-[1fr_auto_1fr] items-center shrink-0 pt-1">
+ <div className="flex flex-col text-sm text-muted-foreground px-2 shrink-0">
+ <div className="flex items-center gap-1">{renderTotal()}</div>
+ <CellSelectionStats table={table} className="lg:hidden" />
+ </div>
+ <div className="ml-auto lg:ml-0 lg:justify-self-center flex items-center shrink-0">
+ {pagination && (
+ <DataTablePagination
+ table={table}
+ tableLoading={tableLoading}
+ showPageSizeSelector={showPageSizeSelector}
+ />
+ )}
+ </div>
+ <div className="hidden lg:flex justify-end">
+ <CellSelectionStats table={table} className="px-2" />
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/components/data-table/TableTopBar.tsx b/frontend/src/components/data-table/TableTopBar.tsx
new file mode 100644
index 0000000000..941fb95460
--- /dev/null
+++ b/frontend/src/components/data-table/TableTopBar.tsx
@@ -0,0 +1,141 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+"use no memo";
+
+import { useDebounce } from "@uidotdev/usehooks";
+import {
+ ChartSplineIcon,
+ PanelRightIcon,
+ SearchIcon,
+ XIcon,
+} from "lucide-react";
+import React, { useEffect, useState } from "react";
+import useEvent from "react-use-event-hook";
+import { cn } from "@/utils/cn";
+import {
+ PANEL_TYPES,
+ type PanelType,
+} from "../editor/chrome/panels/context-aware-panel/context-aware-panel";
+import { Spinner } from "../icons/spinner";
+import { Button } from "../ui/button";
+import { type ExportActionProps, ExportMenu } from "./export-actions";
+
+const NOOP_ON_SEARCH = () => {
+ /** no-op*/
+};
+
+interface TableTopBarProps extends Partial<ExportActionProps> {
+ enableSearch: boolean;
+ searchQuery?: string;
+ onSearchQueryChange?: (query: string) => void;
+ reloading?: boolean;
+ showChartBuilder?: boolean;
+ isChartBuilderOpen?: boolean;
+ toggleDisplayHeader?: () => void;
+ showTableExplorer?: boolean;
+ togglePanel?: (panelType: PanelType) => void;
+ isAnyPanelOpen?: boolean;
+}
+
+export const TableTopBar: React.FC<TableTopBarProps> = ({
+ enableSearch,
+ searchQuery,
+ onSearchQueryChange,
+ reloading,
+ showChartBuilder,
+ isChartBuilderOpen,
+ toggleDisplayHeader,
+ showTableExplorer,
+ togglePanel,
+ isAnyPanelOpen,
+ downloadAs,
+}) => {
+ const [internalValue, setInternalValue] = useState(searchQuery || "");
+ const debouncedSearch = useDebounce(internalValue, 500);
+ const onSearch = useEvent(onSearchQueryChange ?? NOOP_ON_SEARCH);
+ const inputRef = React.useRef<HTMLInputElement>(null);
+
+ useEffect(() => {
+ 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-3">
+ {/* always-visible search */}
+ {onSearchQueryChange && enableSearch && (
+ <div className="flex items-center">
+ <div className="flex items-center gap-1 rounded-full border px-2 w-56">
+ <SearchIcon className="w-4 h-4 text-muted-foreground shrink-0" />
+ <input
+ ref={inputRef}
+ type="text"
+ className="h-6 border-none bg-transparent focus:outline-hidden text-sm w-full min-w-0"
+ value={internalValue}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ setInternalValue("");
+ inputRef.current?.blur();
+ }
+ }}
+ onChange={(e) => setInternalValue(e.target.value)}
+ placeholder="Search..."
+ />
+ {reloading && <Spinner size="small" />}
+ {internalValue && (
+ <Button
+ variant="text"
+ size="xs"
+ className="h-5 w-5 p-0 shrink-0"
+ onClick={() => setInternalValue("")}
+ >
+ <XIcon className="w-3 h-3 text-muted-foreground" />
+ </Button>
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* actions grouped together */}
+ <div className="flex items-center gap-1 shrink-0">
+ {showChartBuilder && (
+ <Button
+ variant="text"
+ size="xs"
+ className={cn(
+ "print:hidden text-xs gap-1",
+ isChartBuilderOpen ? "text-primary" : "text-muted-foreground",
+ )}
+ onClick={toggleDisplayHeader}
+ >
+ <ChartSplineIcon className="w-3.5 h-3.5" />
+ Chart Builder
+ </Button>
+ )}
+ {showTableExplorer && togglePanel && (
+ <Button
+ variant="text"
+ size="xs"
+ className={cn(
+ "print:hidden text-xs gap-1",
+ isAnyPanelOpen ? "text-primary" : "text-muted-foreground",
+ )}
+ onClick={() => togglePanel(PANEL_TYPES.ROW_VIEWER)}
+ >
+ <PanelRightIcon className="w-3.5 h-3.5" />
+ Table Explorer
+ </Button>
+ )}
+ {downloadAs && <ExportMenu downloadAs={downloadAs} />}
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsx
index 8f9bc52d39..9c8b006ab3 100644
--- a/frontend/src/components/data-table/data-table.tsx
+++ b/frontend/src/components/data-table/data-table.tsx
@@ -37,16 +37,15 @@ import type { CellStyleState } from "./cell-styling/types";
import { ColumnFormattingFeature } from "./column-formatting/feature";
import { ColumnWrappingFeature } from "./column-wrapping/feature";
import { CopyColumnFeature } from "./copy-column/feature";
-import type { DownloadActionProps } from "./download-actions";
+import type { ExportActionProps } from "./export-actions";
import { FilterPills } from "./filter-pills";
import { FocusRowFeature } from "./focus-row/feature";
import { useColumnPinning } from "./hooks/use-column-pinning";
import { useScrollContainerHeight } from "./hooks/use-scroll-container-height";
-import { CellSelectionStats } from "./range-focus/cell-selection-stats";
import { CellSelectionProvider } from "./range-focus/provider";
import { DataTableBody, renderTableHeader } from "./renderers";
-import { SearchBar } from "./SearchBar";
-import { TableActions } from "./TableActions";
+import { TableBottomBar } from "./TableBottomBar";
+import { TableTopBar } from "./TableTopBar";
import {
type DataTableSelection,
MIN_ROWS_TO_VIRTUALIZE,
@@ -54,7 +53,7 @@ import {
} from "./types";
import { getStableRowId } from "./utils";
-interface DataTableProps<TData> extends Partial<DownloadActionProps> {
+interface DataTableProps<TData> extends Partial<ExportActionProps> {
wrapperClassName?: string;
className?: string;
maxHeight?: number;
@@ -99,6 +98,7 @@ interface DataTableProps<TData> extends Partial<DownloadActionProps> {
onViewedRowChange?: OnChangeFn<number>;
// Others
showChartBuilder?: boolean;
+ isChartBuilderOpen?: boolean;
showPageSizeSelector?: boolean;
showTableExplorer?: boolean;
togglePanel?: (panelType: PanelType) => void;
@@ -143,6 +143,7 @@ const DataTableInternal = <TData,>({
freezeColumnsRight,
toggleDisplayHeader,
showChartBuilder,
+ isChartBuilderOpen,
showPageSizeSelector,
showTableExplorer,
togglePanel,
@@ -151,7 +152,6 @@ const DataTableInternal = <TData,>({
viewedRowIdx,
onViewedRowChange,
}: DataTableProps<TData>) => {
- const [isSearchEnabled, setIsSearchEnabled] = React.useState<boolean>(false);
const [showLoadingBar, setShowLoadingBar] = React.useState<boolean>(false);
const { locale } = useLocale();
@@ -284,15 +284,19 @@ const DataTableInternal = <TData,>({
<FilterPills filters={filters} table={table} />
<CellSelectionProvider>
<div className={cn(className || "rounded-md border overflow-hidden")}>
- {onSearchQueryChange && enableSearch && (
- <SearchBar
- value={searchQuery || ""}
- onHide={() => setIsSearchEnabled(false)}
- handleSearch={onSearchQueryChange}
- hidden={!isSearchEnabled}
- reloading={reloading}
- />
- )}
+ <TableTopBar
+ enableSearch={enableSearch}
+ searchQuery={searchQuery}
+ onSearchQueryChange={onSearchQueryChange}
+ reloading={reloading}
+ showChartBuilder={showChartBuilder}
+ isChartBuilderOpen={isChartBuilderOpen}
+ toggleDisplayHeader={toggleDisplayHeader}
+ showTableExplorer={showTableExplorer}
+ togglePanel={togglePanel}
+ isAnyPanelOpen={isAnyPanelOpen}
+ downloadAs={downloadAs}
+ />
<Table className="relative" ref={tableRef}>
{showLoadingBar && (
<thead className="absolute top-0 left-0 h-[3px] w-1/2 bg-primary animate-slide" />
@@ -308,28 +312,17 @@ const DataTableInternal = <TData,>({
/>
</Table>
</div>
- <CellSelectionStats table={table} className="px-2 pt-1 ml-auto" />
+ <TableBottomBar
+ totalColumns={totalColumns}
+ pagination={pagination}
+ selection={selection}
+ onRowSelectionChange={onRowSelectionChange}
+ table={table}
+ getRowIds={getRowIds}
+ showPageSizeSelector={showPageSizeSelector}
+ tableLoading={reloading}
+ />
</CellSelectionProvider>
- <TableActions
- enableSearch={enableSearch}
- totalColumns={totalColumns}
- onSearchQueryChange={onSearchQueryChange}
- isSearchEnabled={isSearchEnabled}
- setIsSearchEnabled={setIsSearchEnabled}
- pagination={pagination}
- selection={selection}
- onRowSelectionChange={onRowSelectionChange}
- table={table}
- downloadAs={downloadAs}
- getRowIds={getRowIds}
- toggleDisplayHeader={toggleDisplayHeader}
- showChartBuilder={showChartBuilder}
- showPageSizeSelector={showPageSizeSelector}
- showTableExplorer={showTableExplorer}
- togglePanel={togglePanel}
- isAnyPanelOpen={isAnyPanelOpen}
- tableLoading={reloading}
- />
</div>
);
};
diff --git a/frontend/src/components/data-table/download-actions.tsx b/frontend/src/components/data-table/download-actions.tsx
deleted file mode 100644
index 91bb3c27a9..0000000000
--- a/frontend/src/components/data-table/download-actions.tsx
+++ /dev/null
@@ -1,224 +0,0 @@
-/* Copyright 2026 Marimo. All rights reserved. */
-
-import {
- BracesIcon,
- BrickWallIcon,
- ChevronDownIcon,
- ClipboardListIcon,
- FileTextIcon,
- TableIcon,
-} from "lucide-react";
-import React from "react";
-import { useLocale } from "react-aria";
-import { logNever } from "@/utils/assertNever";
-import { copyToClipboard } from "@/utils/copy";
-import { downloadByURL } from "@/utils/download";
-import { prettyError } from "@/utils/errors";
-import {
- jsonParseWithSpecialChar,
- jsonToMarkdown,
- jsonToTSV,
-} from "@/utils/json/json-parser";
-import { Button } from "../ui/button";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuSub,
- DropdownMenuSubContent,
- DropdownMenuSubTrigger,
- DropdownMenuTrigger,
-} from "../ui/dropdown-menu";
-import { toast } from "../ui/use-toast";
-
-type DownloadFormat = "csv" | "json" | "parquet";
-
-export interface DownloadActionProps {
- downloadAs: (req: {
- format: DownloadFormat;
- }) => Promise<{ url: string; filename: string }>;
-}
-
-const options = [
- {
- label: "CSV",
- format: "csv",
- icon: TableIcon,
- },
- {
- label: "JSON",
- format: "json",
- icon: BracesIcon,
- },
- {
- label: "Parquet",
- format: "parquet",
- icon: BrickWallIcon,
- },
-] as const;
-
-const clipboardOptions = [
- {
- label: "TSV",
- format: "tsv",
- description: "Best for Excel and Google Sheets",
- icon: TableIcon,
- },
- {
- label: "JSON",
- format: "json",
- description: "Raw JSON data",
- icon: BracesIcon,
- },
- {
- label: "CSV",
- format: "csv",
- description: "Comma-separated values",
- icon: TableIcon,
- },
- {
- label: "Markdown",
- format: "markdown",
- description: "Preserves hyperlinks and formatting",
- icon: FileTextIcon,
- },
-] as const;
-
-export const DownloadAs: React.FC<DownloadActionProps> = (props) => {
- const { locale } = useLocale();
-
- const button = (
- <Button
- data-testid="download-as-button"
- size="xs"
- variant="link"
- className="print:hidden"
- >
- Download <ChevronDownIcon className="w-3 h-3 ml-1" />
- </Button>
- );
-
- const getDownloadResponse = (
- format: DownloadFormat,
- ): Promise<{ url: string; filename: string }> => {
- return props.downloadAs({ format }).catch((error) => {
- toast({
- title: "Failed to download",
- description: "message" in error ? error.message : String(error),
- });
- throw error;
- });
- };
-
- const handleClipboardCopy = async (
- format: (typeof clipboardOptions)[number]["format"],
- ) => {
- let text: string;
-
- switch (format) {
- case "tsv": {
- const { url } = await getDownloadResponse("json");
- const json = await fetchJson(url);
- text = jsonToTSV(json, locale);
- break;
- }
- case "json": {
- const { url } = await getDownloadResponse("json");
- const json = await fetchJson(url);
- text = JSON.stringify(json, null, 2);
- break;
- }
- case "csv": {
- const { url } = await getDownloadResponse("csv");
- const csv = await fetchText(url);
- text = csv;
- break;
- }
- case "markdown": {
- const { url } = await getDownloadResponse("json");
- const json = await fetchJson(url);
- text = jsonToMarkdown(json);
- break;
- }
- default:
- logNever(format);
- return;
- }
-
- await copyToClipboard(text);
- toast({
- title: "Copied to clipboard",
- });
- };
-
- return (
- <DropdownMenu modal={false}>
- <DropdownMenuTrigger asChild={true}>{button}</DropdownMenuTrigger>
- <DropdownMenuContent side="bottom" className="print:hidden">
- {options.map((option) => (
- <DropdownMenuItem
- key={option.label}
- onSelect={async () => {
- const { url, filename } = await getDownloadResponse(
- option.format,
- );
- downloadByURL(url, filename);
- }}
- >
- <option.icon className="mo-dropdown-icon" />
- {option.label}
- </DropdownMenuItem>
- ))}
- <DropdownMenuSeparator />
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <ClipboardListIcon className="mo-dropdown-icon" />
- Copy to clipboard
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent>
- {clipboardOptions.map((option) => (
- <DropdownMenuItem
- key={option.label}
- onSelect={async () => {
- try {
- await handleClipboardCopy(option.format);
- } catch (error) {
- toast({
- title: "Failed to copy to clipboard",
- description: prettyError(error),
- variant: "danger",
- });
- }
- }}
- >
- <option.icon className="mo-dropdown-icon" />
- <div className="flex flex-col">
- <span>{option.label}</span>
- <span className="text-xs text-muted-foreground">
- {option.description}
- </span>
- </div>
- </DropdownMenuItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- </DropdownMenuContent>
- </DropdownMenu>
- );
-};
-
-function fetchJson(url: string): Promise<Record<string, unknown>[]> {
- return fetchText(url).then(
- jsonParseWithSpecialChar<Record<string, unknown>[]>,
- );
-}
-
-function fetchText(url: string): Promise<string> {
- return fetch(url).then((res) => {
- if (!res.ok) {
- throw new Error(res.statusText);
- }
- return res.text();
- });
-}
diff --git a/frontend/src/components/data-table/export-actions.tsx b/frontend/src/components/data-table/export-actions.tsx
new file mode 100644
index 0000000000..5b0b1ff4b7
--- /dev/null
+++ b/frontend/src/components/data-table/export-actions.tsx
@@ -0,0 +1,231 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import {
+ BracesIcon,
+ BrickWallIcon,
+ DownloadIcon,
+ FileTextIcon,
+ TableIcon,
+} from "lucide-react";
+import React from "react";
+import { useLocale } from "react-aria";
+import { logNever } from "@/utils/assertNever";
+import { cn } from "@/utils/cn";
+import { copyToClipboard } from "@/utils/copy";
+import { downloadByURL } from "@/utils/download";
+import { prettyError } from "@/utils/errors";
+import { Filenames } from "@/utils/filenames";
+import {
+ jsonParseWithSpecialChar,
+ jsonToMarkdown,
+ jsonToTSV,
+} from "@/utils/json/json-parser";
+import { Button } from "../ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "../ui/dropdown-menu";
+import { Tooltip } from "../ui/tooltip";
+import { toast } from "../ui/use-toast";
+
+type DownloadFormat = "csv" | "json" | "parquet";
+
+export interface ExportActionProps {
+ downloadAs: (req: { format: DownloadFormat }) => Promise<{
+ url: string;
+ filename: string;
+ }>;
+}
+
+const FILE_TYPES = {
+ CSV: {
+ label: "CSV",
+ format: "csv",
+ description: "Comma-separated values",
+ icon: TableIcon,
+ },
+ JSON: {
+ label: "JSON",
+ format: "json",
+ description: "Raw JSON data",
+ icon: BracesIcon,
+ },
+ PARQUET: {
+ label: "Parquet",
+ format: "parquet",
+ description: "Columnar binary format",
+ icon: BrickWallIcon,
+ },
+ TSV: {
+ label: "TSV",
+ format: "tsv",
+ description: "Best for Excel and Google Sheets",
+ icon: TableIcon,
+ },
+ MARKDOWN: {
+ label: "Markdown",
+ format: "markdown",
+ description: "Preserves hyperlinks and formatting",
+ icon: FileTextIcon,
+ },
+} as const;
+
+const downloadOptions = [FILE_TYPES.CSV, FILE_TYPES.JSON, FILE_TYPES.PARQUET];
+const copyOptions = [
+ FILE_TYPES.TSV,
+ FILE_TYPES.JSON,
+ FILE_TYPES.CSV,
+ FILE_TYPES.MARKDOWN,
+];
+
+export const ExportMenu: React.FC<ExportActionProps> = (props) => {
+ const { locale } = useLocale();
+ const [open, setOpen] = React.useState(false);
+
+ const button = (
+ <Button
+ data-testid="export-button"
+ size="xs"
+ variant="text"
+ className={cn(
+ "print:hidden text-xs gap-1",
+ open ? "text-primary" : "text-muted-foreground",
+ )}
+ >
+ <DownloadIcon className="w-3.5 h-3.5" />
+ Export
+ </Button>
+ );
+
+ const getDownloadResult = (format: DownloadFormat) => {
+ return props.downloadAs({ format }).catch((error) => {
+ toast({
+ title: "Failed to download",
+ description: "message" in error ? error.message : String(error),
+ });
+ throw error;
+ });
+ };
+
+ const handleClipboardCopy = async (
+ format: (typeof copyOptions)[number]["format"],
+ ) => {
+ let text: string;
+
+ switch (format) {
+ case "tsv": {
+ const { url } = await getDownloadResult("json");
+ const json = await fetchJson(url);
+ text = jsonToTSV(json, locale);
+ break;
+ }
+ case "json": {
+ const { url } = await getDownloadResult("json");
+ const json = await fetchJson(url);
+ text = JSON.stringify(json, null, 2);
+ break;
+ }
+ case "csv": {
+ const { url } = await getDownloadResult("csv");
+ const csv = await fetchText(url);
+ text = csv;
+ break;
+ }
+ case "markdown": {
+ const { url } = await getDownloadResult("json");
+ const json = await fetchJson(url);
+ text = jsonToMarkdown(json);
+ break;
+ }
+ default:
+ logNever(format);
+ return;
+ }
+
+ await copyToClipboard(text);
+ toast({
+ title: "Copied to clipboard",
+ });
+ };
+
+ return (
+ <DropdownMenu modal={false} open={open} onOpenChange={setOpen}>
+ <Tooltip content="Export" open={open ? false : undefined}>
+ <DropdownMenuTrigger asChild={true}>{button}</DropdownMenuTrigger>
+ </Tooltip>
+ <DropdownMenuContent side="bottom" className="print:hidden">
+ <DropdownMenuLabel className="text-xs text-muted-foreground">
+ Download
+ </DropdownMenuLabel>
+ {downloadOptions.map((option) => (
+ <DropdownMenuItem
+ key={option.label}
+ onSelect={async () => {
+ const { url, filename } = await getDownloadResult(option.format);
+ const ext = option.format;
+ const rawName = (filename ?? "").trim();
+ const baseName =
+ Filenames.withoutExtension(rawName) || "download";
+ downloadByURL(url, `${baseName}.${ext}`);
+ }}
+ >
+ <option.icon className="mo-dropdown-icon" />
+ <div className="flex flex-col">
+ <span>{option.label}</span>
+ <span className="text-xs text-muted-foreground">
+ {option.description}
+ </span>
+ </div>
+ </DropdownMenuItem>
+ ))}
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel className="text-xs text-muted-foreground">
+ Copy to clipboard
+ </DropdownMenuLabel>
+ {copyOptions.map((option) => (
+ <DropdownMenuItem
+ key={option.label}
+ onSelect={async () => {
+ try {
+ await handleClipboardCopy(option.format);
+ } catch (error) {
+ toast({
+ title: "Failed to copy to clipboard",
+ description: prettyError(error),
+ variant: "danger",
+ });
+ }
+ }}
+ >
+ <option.icon className="mo-dropdown-icon" />
+ <div className="flex flex-col">
+ <span>{option.label}</span>
+ <span className="text-xs text-muted-foreground">
+ {option.description}
+ </span>
+ </div>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+};
+
+function fetchJson(url: string): Promise<Record<string, unknown>[]> {
+ return fetchText(url).then(
+ jsonParseWithSpecialChar<Record<string, unknown>[]>,
+ );
+}
+
+function fetchText(url: string): Promise<string> {
+ return fetch(url).then((res) => {
+ if (!res.ok) {
+ throw new Error(res.statusText);
+ }
+ return res.text();
+ });
+}
diff --git a/frontend/src/components/data-table/pagination.tsx b/frontend/src/components/data-table/pagination.tsx
index dfc587e51c..2b76283b91 100644
--- a/frontend/src/components/data-table/pagination.tsx
+++ b/frontend/src/components/data-table/pagination.tsx
@@ -2,6 +2,7 @@
"use no memo";
import type { Table } from "@tanstack/react-table";
+import { range } from "lodash-es";
import {
ChevronDown,
ChevronLeft,
@@ -12,126 +13,47 @@ import {
import React from "react";
import { useLocale } from "react-aria";
import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "@/components/ui/command";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
- DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
-import { Input } from "@/components/ui/input";
-import { range } from "@/utils/arrays";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { Tooltip } from "@/components/ui/tooltip";
import { cn } from "@/utils/cn";
import { Events } from "@/utils/events";
import { prettyNumber } from "@/utils/numbers";
import { PluralWord } from "@/utils/pluralize";
-import {
- Select,
- SelectContent,
- SelectGroup,
- SelectItem,
- SelectLabel,
- SelectTrigger,
- SelectValue,
-} from "../ui/select";
-import type { DataTableSelection, PageRange } from "./types";
+import type { PageRange } from "./types";
const MAX_PAGES_BEFORE_CLAMPING = 100;
interface DataTablePaginationProps<TData> {
table: Table<TData>;
- selection?: DataTableSelection;
- totalColumns: number;
- onSelectAllRowsChange?: (value: boolean) => void;
tableLoading?: boolean;
showPageSizeSelector?: boolean;
}
export const DataTablePagination = <TData,>({
table,
- selection,
- onSelectAllRowsChange,
- totalColumns,
tableLoading,
showPageSizeSelector,
}: DataTablePaginationProps<TData>) => {
const { locale } = useLocale();
- const renderTotal = () => {
- const { rowSelection, cellSelection } = table.getState();
- let selected = Object.keys(rowSelection).length;
- let isAllPageSelected = table.getIsAllPageRowsSelected();
- const numRows = table.getRowCount();
- let isAllSelected = selected === numRows;
-
- const isCellSelection =
- selection === "single-cell" || selection === "multi-cell";
- if (isCellSelection) {
- selected = cellSelection.length;
- isAllPageSelected = false;
- isAllSelected = false;
- }
-
- if (isAllPageSelected && !isAllSelected) {
- return (
- <>
- <span>{prettyNumber(selected, locale)} selected</span>
- <Button
- size="xs"
- data-testid="select-all-button"
- variant="link"
- className="h-4 print:hidden"
- onMouseDown={Events.preventFocus}
- onClick={() => {
- if (onSelectAllRowsChange) {
- onSelectAllRowsChange(true);
- } else {
- table.toggleAllRowsSelected(true);
- }
- }}
- >
- Select all {prettyNumber(numRows, locale)}
- </Button>
- </>
- );
- }
-
- if (selected) {
- return (
- <>
- <span>{prettyNumber(selected, locale)} selected</span>
- <Button
- size="xs"
- data-testid="clear-selection-button"
- variant="link"
- className="h-4 print:hidden"
- onMouseDown={Events.preventFocus}
- onClick={() => {
- if (!isCellSelection) {
- if (onSelectAllRowsChange) {
- onSelectAllRowsChange(false);
- } else {
- table.toggleAllRowsSelected(false);
- }
- } else if (table.resetCellSelection) {
- table.resetCellSelection();
- }
- }}
- >
- Clear selection
- </Button>
- </>
- );
- }
-
- const rowColumnCount = prettifyRowColumnCount(
- numRows,
- totalColumns,
- locale,
- );
- return <span>{rowColumnCount}</span>;
- };
const currentPage = Math.min(
table.getState().pagination.pageIndex + 1,
table.getPageCount(),
@@ -153,65 +75,72 @@ export const DataTablePagination = <TData,>({
const renderPageSizeSelector = () => {
return (
- <div className="flex items-center gap-1 text-xs whitespace-nowrap mr-1 print:hidden">
- <Select
- value={pageSize.toString()}
- onValueChange={(value) => table.setPageSize(Number(value))}
- >
- <SelectTrigger className="w-11 h-[18px] shadow-none! !hover:shadow-none ring-0! border-border text-xs p-1">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectGroup>
- <SelectLabel>Rows per page</SelectLabel>
- {[...pageSizes].map((size) => {
- const sizeStr = size.toString();
- return (
- <SelectItem key={size} value={sizeStr}>
- {sizeStr}
- </SelectItem>
- );
- })}
- </SelectGroup>
- </SelectContent>
- </Select>
- <span>/ page</span>
+ <div className="flex items-center text-xs whitespace-nowrap mr-1 print:hidden">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild={true}>
+ <button
+ type="button"
+ className="border rounded justify-between pl-1.5 pr-0.5 h-6 text-xs items-center hover:bg-accent inline-flex gap-0.5"
+ >
+ {pageSize} / page
+ <ChevronDown className="h-3 w-3 opacity-50 mb-px" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="center" sideOffset={6}>
+ <DropdownMenuLabel className="text-xs text-muted-foreground">
+ Rows per page
+ </DropdownMenuLabel>
+ {[...pageSizes].map((size) => (
+ <DropdownMenuItem
+ key={size}
+ className={cn(
+ "text-xs cursor-pointer",
+ size === pageSize && "font-semibold bg-accent",
+ )}
+ onSelect={() => table.setPageSize(size)}
+ onMouseDown={Events.preventFocus}
+ >
+ {size}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
</div>
);
};
return (
- <div className="flex flex-1 items-center justify-between px-2">
- <div className="flex items-center gap-2">
- <div className="text-sm text-muted-foreground">{renderTotal()}</div>
+ <div className="flex flex-col lg:flex-row items-center gap-0.5 lg:gap-1 px-2">
+ <div className="order-2 lg:order-first">
{showPageSizeSelector && renderPageSizeSelector()}
</div>
-
- <div className="flex items-end space-x-2 print:hidden">
- <Button
- size="xs"
- variant="outline"
- data-testid="first-page-button"
- className="hidden h-6 w-6 p-0 lg:flex"
- onClick={() => handlePageChange(() => table.setPageIndex(0))}
- onMouseDown={Events.preventFocus}
- disabled={!table.getCanPreviousPage()}
- >
- <span className="sr-only">Go to first page</span>
- <ChevronsLeft className="h-4 w-4" />
- </Button>
- <Button
- size="xs"
- variant="outline"
- data-testid="previous-page-button"
- className="h-6 w-6 p-0"
- onClick={() => handlePageChange(() => table.previousPage())}
- onMouseDown={Events.preventFocus}
- disabled={!table.getCanPreviousPage()}
- >
- <span className="sr-only">Go to previous page</span>
- <ChevronLeft className="h-4 w-4" />
- </Button>
+ <div className="order-1 lg:order-last flex items-center print:hidden">
+ <Tooltip content="First page">
+ <Button
+ size="xs"
+ variant="text"
+ data-testid="first-page-button"
+ className="hidden h-6 w-5 p-0 lg:flex"
+ onClick={() => handlePageChange(() => table.setPageIndex(0))}
+ onMouseDown={Events.preventFocus}
+ disabled={!table.getCanPreviousPage()}
+ >
+ <ChevronsLeft className="h-4 w-4" />
+ </Button>
+ </Tooltip>
+ <Tooltip content="Previous page">
+ <Button
+ size="xs"
+ variant="text"
+ data-testid="previous-page-button"
+ className="h-6 w-5 p-0"
+ onClick={() => handlePageChange(() => table.previousPage())}
+ onMouseDown={Events.preventFocus}
+ disabled={!table.getCanPreviousPage()}
+ >
+ <ChevronLeft className="h-4 w-4" />
+ </Button>
+ </Tooltip>
<div className="flex items-center justify-center text-xs font-medium gap-1">
<span>Page</span>
<PageSelector
@@ -225,32 +154,36 @@ export const DataTablePagination = <TData,>({
of {prettyNumber(totalPages, locale)}
</span>
</div>
- <Button
- size="xs"
- variant="outline"
- data-testid="next-page-button"
- className="h-6 w-6 p-0"
- onClick={() => handlePageChange(() => table.nextPage())}
- onMouseDown={Events.preventFocus}
- disabled={!table.getCanNextPage()}
- >
- <span className="sr-only">Go to next page</span>
- <ChevronRight className="h-4 w-4" />
- </Button>
- <Button
- size="xs"
- variant="outline"
- data-testid="last-page-button"
- className="hidden h-6 w-6 p-0 lg:flex"
- onClick={() =>
- handlePageChange(() => table.setPageIndex(table.getPageCount() - 1))
- }
- onMouseDown={Events.preventFocus}
- disabled={!table.getCanNextPage()}
- >
- <span className="sr-only">Go to last page</span>
- <ChevronsRight className="h-4 w-4" />
- </Button>
+ <Tooltip content="Next page">
+ <Button
+ size="xs"
+ variant="text"
+ data-testid="next-page-button"
+ className="h-6 w-5 p-0"
+ onClick={() => handlePageChange(() => table.nextPage())}
+ onMouseDown={Events.preventFocus}
+ disabled={!table.getCanNextPage()}
+ >
+ <ChevronRight className="h-4 w-4" />
+ </Button>
+ </Tooltip>
+ <Tooltip content="Last page">
+ <Button
+ size="xs"
+ variant="text"
+ data-testid="last-page-button"
+ className="hidden h-6 w-5 p-0 lg:flex"
+ onClick={() =>
+ handlePageChange(() =>
+ table.setPageIndex(table.getPageCount() - 1),
+ )
+ }
+ onMouseDown={Events.preventFocus}
+ disabled={!table.getCanNextPage()}
+ >
+ <ChevronsRight className="h-4 w-4" />
+ </Button>
+ </Tooltip>
</div>
</div>
);
@@ -266,102 +199,89 @@ export const PageSelector = ({
onPageChange: (page: number) => void;
}) => {
const [open, setOpen] = React.useState(false);
- const [jumpValue, setJumpValue] = React.useState("");
- const jumpInputId = React.useId();
const pageRanges = React.useMemo(
() => getPageRanges(currentPage, totalPages),
[currentPage, totalPages],
);
- const handleJump = () => {
- const page = Number.parseInt(jumpValue, 10);
- if (page >= 1 && page <= totalPages) {
- onPageChange(page - 1);
- setJumpValue("");
- setOpen(false);
- }
+ const handleSelect = (page: number) => {
+ onPageChange(page - 1);
+ setOpen(false);
};
return (
- <DropdownMenu open={open} onOpenChange={setOpen}>
- <DropdownMenuTrigger asChild={true}>
+ <Popover open={totalPages > 1 ? open : false} onOpenChange={setOpen}>
+ <PopoverTrigger asChild={true} disabled={totalPages <= 1}>
<button
type="button"
- className="border rounded justify-between pl-1.5 pr-0.5 min-w-9 text-xs items-center hover:bg-accent inline-flex gap-0.5"
+ className={cn(
+ "border rounded justify-between pl-1.5 pr-0.5 h-6 min-w-9 text-xs items-center inline-flex gap-0.5",
+ totalPages > 1
+ ? "hover:bg-accent cursor-pointer"
+ : "opacity-50 cursor-default",
+ )}
data-testid="page-select"
+ disabled={totalPages <= 1}
>
{currentPage}
<ChevronDown className="h-3 w-3 opacity-50 mb-px" />
</button>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- className="w-36 overflow-hidden flex flex-col"
- scrollable={false}
- align="center"
- sideOffset={6}
- style={{ maxHeight: "22rem" }}
- >
- <div className="overflow-y-auto flex-1 min-h-0">
- {pageRanges.map((item) =>
- item.type === "ellipsis" ? (
- <DropdownMenuLabel
- key={item.key}
- className="text-center text-xs text-muted-foreground"
- >
- ...
- </DropdownMenuLabel>
- ) : (
- <DropdownMenuItem
- key={item.page}
- data-testid="page-option"
- className={cn(
- "text-xs cursor-pointer",
- item.page === currentPage && "font-semibold bg-accent",
- )}
- onSelect={() => onPageChange(item.page - 1)}
- onMouseDown={Events.preventFocus}
- >
- {item.page}
- </DropdownMenuItem>
- ),
- )}
- </div>
- {totalPages > MAX_PAGES_BEFORE_CLAMPING && (
- <>
- <DropdownMenuSeparator />
- <div
- className="px-2 pt-0.5 shrink-0"
- onKeyDown={(e) => e.stopPropagation()}
- >
- <label
- htmlFor={jumpInputId}
- className="text-xs text-muted-foreground block mb-1"
- >
- Jump to page
- </label>
- <Input
- id={jumpInputId}
- type="number"
- min={1}
- max={totalPages}
- placeholder={`1-${totalPages}`}
- value={jumpValue}
- onChange={(e) => setJumpValue(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter") {
- handleJump();
- }
- e.stopPropagation();
- }}
- className="h-6 text-xs"
- data-testid="page-jump-input"
- />
- </div>
- </>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
+ </PopoverTrigger>
+ <PopoverContent className="w-36 p-0" align="center" sideOffset={6}>
+ <Command
+ shouldFilter={true}
+ filter={(value, search) => {
+ return value.startsWith(search) ? 1 : 0;
+ }}
+ >
+ <CommandInput
+ placeholder={`Page (1–${totalPages})`}
+ rootClassName="px-2 h-8"
+ className="text-xs h-8"
+ autoFocus={true}
+ icon={null}
+ onKeyDown={(e) => {
+ // Allow navigation/editing keys, block non-numeric input
+ const allowed = [
+ "Backspace",
+ "Delete",
+ "ArrowLeft",
+ "ArrowRight",
+ "Tab",
+ "Enter",
+ "Escape",
+ ];
+ if (!allowed.includes(e.key) && !/^\d$/.test(e.key)) {
+ e.preventDefault();
+ }
+ }}
+ />
+ <CommandList className="max-h-60">
+ {pageRanges.map((item) =>
+ item.type === "ellipsis" ? null : (
+ <CommandItem
+ key={item.page}
+ value={String(item.page)}
+ data-testid="page-option"
+ className={cn(
+ "text-xs cursor-pointer",
+ item.page === currentPage && "font-semibold bg-accent",
+ )}
+ onSelect={() => handleSelect(item.page)}
+ onMouseDown={Events.preventFocus}
+ >
+ {item.page}
+ </CommandItem>
+ ),
+ )}
+ <CommandEmpty className="py-2 text-center text-xs text-muted-foreground">
+ No matching page
+ </CommandEmpty>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
);
};
diff --git a/frontend/src/components/data-table/range-focus/__tests__/cell-selection-stats.test.tsx b/frontend/src/components/data-table/range-focus/__tests__/cell-selection-stats.test.tsx
index 9d3a8c36d3..7b2fadf834 100644
--- a/frontend/src/components/data-table/range-focus/__tests__/cell-selection-stats.test.tsx
+++ b/frontend/src/components/data-table/range-focus/__tests__/cell-selection-stats.test.tsx
@@ -5,6 +5,7 @@ import { render, screen } from "@testing-library/react";
import { useEffect } from "react";
import { I18nProvider } from "react-aria";
import { describe, expect, it } from "vitest";
+import { TooltipProvider } from "@/components/ui/tooltip";
import { SELECT_COLUMN_ID } from "../../types";
import { useCellSelectionReducerActions } from "../atoms";
import { CellSelectionStats } from "../cell-selection-stats";
@@ -23,27 +24,30 @@ const TestHarness = ({
actions.setSelectedCells(selectedCellIds);
}, [actions, selectedCellIds]);
return (
- <I18nProvider locale="en-US">
- <CellSelectionStats table={table} />
- </I18nProvider>
+ <TooltipProvider>
+ <I18nProvider locale="en-US">
+ <CellSelectionStats table={table} />
+ </I18nProvider>
+ </TooltipProvider>
);
};
describe("CellSelectionStats", () => {
- it("should return null when fewer than 2 cells are selected", () => {
+ it("should show hint when fewer than 2 cells are selected", () => {
const row = createMockRow("0", [
createMockCell("0_0", 10),
createMockCell("0_1", 20),
]);
const table = createMockTable([row], []);
- const { container } = render(
+ render(
<CellSelectionProvider>
<TestHarness table={table} selectedCellIds={new Set(["0_0"])} />
</CellSelectionProvider>,
);
- expect(container.firstChild).toBeNull();
+ expect(screen.getByText("No selection")).toBeInTheDocument();
+ expect(screen.queryByText(/Count:/)).not.toBeInTheDocument();
});
it("should display Count stat when 2 or more cells are selected", () => {
@@ -181,20 +185,20 @@ describe("CellSelectionStats", () => {
expect(screen.getByText("Average: 0")).toBeInTheDocument();
});
- it("should not display any stats when exactly one cell is selected", () => {
+ it("should show hint instead of stats when exactly one cell is selected", () => {
const row = createMockRow("0", [
createMockCell("0_0", 10),
createMockCell("0_1", 20),
]);
const table = createMockTable([row], []);
- const { container } = render(
+ render(
<CellSelectionProvider>
<TestHarness table={table} selectedCellIds={new Set(["0_0"])} />
</CellSelectionProvider>,
);
- expect(container.firstChild).toBeNull();
+ expect(screen.getByText("No selection")).toBeInTheDocument();
expect(screen.queryByText(/Count:/)).not.toBeInTheDocument();
});
@@ -301,14 +305,14 @@ describe("CellSelectionStats", () => {
expect(screen.getByText("Average: 25")).toBeInTheDocument();
});
- it("should not display stats when only checkbox column cells are selected", () => {
+ it("should show hint when only checkbox column cells are selected", () => {
const selectCellId1 = `0_${SELECT_COLUMN_ID}`;
const selectCellId2 = `1_${SELECT_COLUMN_ID}`;
const row1 = createMockRow("0", [createMockCell(selectCellId1, true)]);
const row2 = createMockRow("1", [createMockCell(selectCellId2, false)]);
const table = createMockTable([row1, row2], []);
- const { container } = render(
+ render(
<CellSelectionProvider>
<TestHarness
table={table}
@@ -317,7 +321,7 @@ describe("CellSelectionStats", () => {
</CellSelectionProvider>,
);
- expect(container.firstChild).toBeNull();
+ expect(screen.getByText("No selection")).toBeInTheDocument();
expect(screen.queryByText(/Count:/)).not.toBeInTheDocument();
});
diff --git a/frontend/src/components/data-table/range-focus/cell-selection-stats.tsx b/frontend/src/components/data-table/range-focus/cell-selection-stats.tsx
index 0b5c14bcb2..36fd19a41f 100644
--- a/frontend/src/components/data-table/range-focus/cell-selection-stats.tsx
+++ b/frontend/src/components/data-table/range-focus/cell-selection-stats.tsx
@@ -3,6 +3,7 @@
import type { Table } from "@tanstack/react-table";
import { useAtomValue } from "jotai";
import { useLocale } from "react-aria";
+import { Tooltip } from "@/components/ui/tooltip";
import { cn } from "@/utils/cn";
import { selectedCellsAtom } from "./atoms";
import {
@@ -31,7 +32,13 @@ export const CellSelectionStats = <TData,>({
const dataCellCount = countDataCellsInSelection(selectedCells);
if (dataCellCount < 2) {
- return null;
+ return (
+ <Tooltip content="Select multiple cells to see stats">
+ <span className={cn("text-sm text-muted-foreground italic", className)}>
+ No selection
+ </span>
+ </Tooltip>
+ );
}
const numericValues = getNumericValuesFromSelectedCells(table, selectedCells);
@@ -39,7 +46,7 @@ export const CellSelectionStats = <TData,>({
return (
<div
className={cn(
- "flex items-center justify-end gap-3 text-xs text-muted-foreground shrink-0",
+ "flex items-center justify-end gap-3 text-sm text-muted-foreground shrink-0",
className,
)}
>
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index 74f854b77e..7fdda63fcc 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -466,6 +466,7 @@ interface DataTableProps<T> extends Data<T>, DataTableFunctions {
hoverTemplate?: string | null;
cellHoverTexts?: Record<string, Record<string, string | null>> | null;
toggleDisplayHeader?: () => void;
+ isChartBuilderOpen?: boolean;
host: HTMLElement;
cellId?: CellId | null;
}
@@ -749,6 +750,7 @@ export const LoadingDataTableComponent = memo(
> | null
}
toggleDisplayHeader={toggleDisplayHeader}
+ isChartBuilderOpen={displayHeader}
getRow={getRow}
cellId={cellId}
maxHeight={props.maxHeight}
@@ -821,6 +823,7 @@ const DataTableComponent = ({
hoverTemplate,
cellHoverTexts,
toggleDisplayHeader,
+ isChartBuilderOpen,
calculate_top_k_rows,
preview_column,
getRow,
@@ -1088,6 +1091,7 @@ const DataTableComponent = ({
getRowIds={get_row_ids}
toggleDisplayHeader={toggleDisplayHeader}
showChartBuilder={showChartBuilder}
+ isChartBuilderOpen={isChartBuilderOpen}
showPageSizeSelector={showPageSizeSelector}
// Hidden in VSCode (for now) because we don't have a panel to show
// the table explorer.
diff --git a/marimo/_output/formatters/df_formatters.py b/marimo/_output/formatters/df_formatters.py
index 7b986f1f75..52e0451867 100644
--- a/marimo/_output/formatters/df_formatters.py
+++ b/marimo/_output/formatters/df_formatters.py
@@ -96,7 +96,7 @@ class PolarsFormatter(FormatterFactory):
df: pl.DataFrame,
) -> tuple[KnownMimeType, str]:
try:
- return table(df, selection=None, pagination=True)._mime_()
+ return table(df, selection=None, pagination=None)._mime_()
except BaseException as e:
# Catch-all: some libraries like Polars have bugs and raise
# BaseExceptions, which shouldn't crash the kernel
@@ -113,7 +113,7 @@ class PolarsFormatter(FormatterFactory):
df = pl.DataFrame({"value": series})
else:
df = series.to_frame()
- return table(df, selection=None, pagination=True)._mime_()
+ return table(df, selection=None, pagination=None)._mime_()
except BaseException as e:
# Catch-all: some libraries like Polars have bugs and raise
# BaseExceptions, which shouldn't crash the kernel
@@ -157,7 +157,7 @@ class PyArrowFormatter(FormatterFactory):
def _show_marimo_dataframe(
df: pa.Table,
) -> tuple[KnownMimeType, str]:
- return table(df, selection=None, pagination=True)._mime_()
+ return table(df, selection=None, pagination=None)._mime_()
class PySparkFormatter(FormatterFactory):
diff --git a/marimo/_output/formatters/pandas_formatters.py b/marimo/_output/formatters/pandas_formatters.py
index 375c9e3eb7..bde35806a5 100644
--- a/marimo/_output/formatters/pandas_formatters.py
+++ b/marimo/_output/formatters/pandas_formatters.py
@@ -33,7 +33,7 @@ class PandasFormatter(FormatterFactory):
def _show_marimo_dataframe(
df: pd.DataFrame,
) -> tuple[KnownMimeType, str]:
- return table(df, selection=None, pagination=True)._mime_()
+ return table(df, selection=None, pagination=None)._mime_()
@formatting.opinionated_formatter(pd.Series)
def _show_marimo_series(
@@ -44,7 +44,7 @@ class PandasFormatter(FormatterFactory):
if series.name is None:
series = series.rename("value")
return table(
- series.to_frame(), selection=None, pagination=True
+ series.to_frame(), selection=None, pagination=None
)._mime_()
except Exception as e:
LOGGER.warning("Failed to format Series: %s", e)