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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: add shared table export dialog (#11029)
Kiran Gadhavebfa96392bc41
diff --git a/frontend/plugins.openapi.yaml b/frontend/plugins.openapi.yamlindex b99d1a9067..959a1fcd19 100644--- a/frontend/plugins.openapi.yaml+++ b/frontend/plugins.openapi.yaml@@ -3158,6 +3158,15 @@ components:- json- parquet- tsv+ options:+ type: object+ properties:+ separator:+ type: string+ encoding:+ type: string+ ensure_ascii:+ type: booleanrequired:- formatmarimo-dataframe.download_as.output:@@ -4640,6 +4649,15 @@ components:- json- parquet- tsv+ options:+ type: object+ properties:+ separator:+ type: string+ encoding:+ type: string+ ensure_ascii:+ type: booleanrequired:- formatmarimo-table.download_as.output:diff --git a/frontend/src/components/data-table/TableTopBar.tsx b/frontend/src/components/data-table/TableTopBar.tsxindex fbf3fd5364..3aef5c03fc 100644--- a/frontend/src/components/data-table/TableTopBar.tsx+++ b/frontend/src/components/data-table/TableTopBar.tsx@@ -19,7 +19,7 @@ import {import { Spinner } from "../icons/spinner";import { Button } from "../ui/button";import { ColumnVisibilityDropdown } from "./column-visibility-dropdown";-import { type ExportActionProps, ExportMenu } from "./export-actions";+import { type ExportActionProps, ExportActions } from "./export-actions";const NOOP_ON_SEARCH = () => {/** no-op*/@@ -130,7 +130,7 @@ export const TableTopBar = <TData,>({</Button>)}{downloadAs && (- <ExportMenu+ <ExportActionsdownloadAs={downloadAs}sizeBytes={sizeBytes}sizeBytesIsLoading={sizeBytesIsLoading}diff --git a/frontend/src/components/data-table/__tests__/export-actions.test.tsx b/frontend/src/components/data-table/__tests__/export-actions.test.tsxnew file mode 100644index 0000000000..edf0bf140f--- /dev/null+++ b/frontend/src/components/data-table/__tests__/export-actions.test.tsx@@ -0,0 +1,662 @@+/* Copyright 2026 Marimo. All rights reserved. */++import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from "@testing-library/react";+import { createStore, Provider } from "jotai";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { TooltipProvider } from "@/components/ui/tooltip";+import { toast } from "@/components/ui/use-toast";+import { viewStateAtom, type AppMode } from "@/core/mode";+import { copyToClipboard } from "@/utils/copy";+import { downloadByURL } from "@/utils/download";+import { jsonToMarkdown } from "@/utils/json/json-parser";+import { downloadSizeLimitAtom } from "../download-policy/atoms";+import { ExportActions, type ExportActionProps } from "../export-actions";++const mocks = vi.hoisted(() => ({+ handleInstallPackages: vi.fn(),+}));++vi.mock("@/core/packages/useInstallPackage", () => ({+ useInstallPackages: () => ({+ handleInstallPackages: mocks.handleInstallPackages,+ }),+}));++vi.mock("@/utils/copy", () => ({+ copyToClipboard: vi.fn().mockResolvedValue(undefined),+}));++vi.mock("@/utils/download", () => ({+ downloadByURL: vi.fn(),+ withLoadingToast: vi.fn(+ async (_title: string, callback: () => Promise<unknown>) => callback(),+ ),+}));++vi.mock("@/components/ui/use-toast", () => ({+ toast: vi.fn(() => ({+ dismiss: vi.fn(),+ update: vi.fn(),+ })),+}));++const downloadAs = vi.fn<ExportActionProps["downloadAs"]>();++function renderExportActions(+ props: Partial<ExportActionProps> = {},+ sizeLimit: { limitBytes: number; unavailableMessage: string } | null = null,+ mode: AppMode = "edit",+) {+ const store = createStore();+ store.set(downloadSizeLimitAtom, sizeLimit);+ store.set(viewStateAtom, { mode, cellAnchor: null });++ return render(+ <Provider store={store}>+ <TooltipProvider delayDuration={0}>+ <ExportActions downloadAs={downloadAs} {...props} />+ </TooltipProvider>+ </Provider>,+ );+}++async function openDialog() {+ fireEvent.click(screen.getByTestId("export-button"));+ return screen.findByRole("dialog", { name: "Export table" });+}++describe("ExportActions dialog", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ downloadAs.mockResolvedValue({+ url: "https://example.test/export",+ filename: "table",+ });+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("shows formats in the approved order with an options toggle where supported", async () => {+ renderExportActions();+ const dialog = await openDialog();+ const list = within(dialog).getByRole("list", { name: "Export formats" });+ const rows = within(list).getAllByRole("listitem");++ expect(rows.map((row) => row.dataset.testid)).toEqual([+ "export-row-csv",+ "export-row-tsv",+ "export-row-json",+ "export-row-parquet",+ "export-row-markdown",+ ]);+ for (const label of ["CSV", "TSV", "JSON"]) {+ expect(+ screen.getByRole("button", { name: `${label} options` }),+ ).toHaveAttribute("aria-expanded", "false");+ }+ for (const label of ["Parquet", "Markdown"]) {+ expect(+ screen.queryByRole("button", { name: `${label} options` }),+ ).not.toBeInTheDocument();+ }+ expect(within(dialog).queryByRole("group")).not.toBeInTheDocument();+ });++ it("expands one options panel at a time", async () => {+ renderExportActions();+ const dialog = await openDialog();++ fireEvent.click(screen.getByRole("button", { name: "CSV options" }));+ expect(+ within(dialog).getByRole("group", { name: "CSV options" }),+ ).toBeInTheDocument();+ expect(screen.getByRole("combobox", { name: "Delimiter" })).toHaveValue(+ ",",+ );+ expect(screen.getByRole("combobox", { name: "Encoding" })).toHaveValue(+ "utf-8",+ );++ fireEvent.click(screen.getByRole("button", { name: "JSON options" }));+ expect(+ within(dialog).queryByRole("group", { name: "CSV options" }),+ ).not.toBeInTheDocument();+ expect(+ within(dialog).getByRole("group", { name: "JSON options" }),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("switch", { name: "Escape non-ASCII" }),+ ).toBeChecked();++ fireEvent.click(screen.getByRole("button", { name: "JSON options" }));+ expect(within(dialog).queryByRole("group")).not.toBeInTheDocument();+ });++ it("sends only changed CSV options with a download", async () => {+ renderExportActions();+ await openDialog();+ expect(screen.getByTestId("export-summary-csv")).toHaveTextContent(+ "Comma · UTF-8",+ );+ expect(screen.queryByTestId("export-summary-parquet")).toBeNull();++ fireEvent.click(screen.getByRole("button", { name: "CSV options" }));+ fireEvent.change(screen.getByRole("combobox", { name: "Delimiter" }), {+ target: { value: ";" },+ });+ fireEvent.change(screen.getByRole("combobox", { name: "Encoding" }), {+ target: { value: "utf-8-sig" },+ });+ expect(screen.getByTestId("export-summary-csv")).toHaveTextContent(+ "Semicolon · UTF-8 with BOM",+ );+ fireEvent.click(screen.getByRole("button", { name: "Download CSV" }));++ await waitFor(() => {+ expect(downloadByURL).toHaveBeenCalled();+ });+ expect(downloadAs).toHaveBeenCalledWith({+ format: "csv",+ options: { separator: ";", encoding: "utf-8-sig" },+ });+ });++ it("keeps the delimiter but drops the encoding for a CSV copy", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ text: vi.fn().mockResolvedValue("name;value\n"),+ }),+ );+ renderExportActions();+ await openDialog();++ fireEvent.click(screen.getByRole("button", { name: "CSV options" }));+ fireEvent.change(screen.getByRole("combobox", { name: "Delimiter" }), {+ target: { value: ";" },+ });+ fireEvent.change(screen.getByRole("combobox", { name: "Encoding" }), {+ target: { value: "latin-1" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Copy CSV" }));++ await waitFor(() => {+ expect(copyToClipboard).toHaveBeenCalledWith("name;value\n");+ });+ expect(downloadAs).toHaveBeenCalledWith({+ format: "csv",+ options: { separator: ";" },+ });+ });++ it("sends the JSON escape setting only when turned off", async () => {+ renderExportActions();+ await openDialog();++ fireEvent.click(screen.getByRole("button", { name: "JSON options" }));+ fireEvent.click(screen.getByRole("switch", { name: "Escape non-ASCII" }));+ fireEvent.click(screen.getByRole("button", { name: "Download JSON" }));++ await waitFor(() => {+ expect(downloadByURL).toHaveBeenCalled();+ });+ expect(downloadAs).toHaveBeenCalledWith({+ format: "json",+ options: { ensure_ascii: false },+ });+ });++ it("resets options and panels when the dialog closes", async () => {+ renderExportActions();+ let dialog = await openDialog();++ fireEvent.click(screen.getByRole("button", { name: "CSV options" }));+ fireEvent.change(screen.getByRole("combobox", { name: "Delimiter" }), {+ target: { value: "|" },+ });+ fireEvent.click(within(dialog).getByRole("button", { name: "Close" }));+ await waitFor(() => {+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });++ dialog = await openDialog();+ expect(within(dialog).queryByRole("group")).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Download CSV" }));+ await waitFor(() => {+ expect(downloadAs).toHaveBeenCalledWith({ format: "csv" });+ });+ });++ it("opens without showing an action tooltip", async () => {+ renderExportActions();+ const dialog = await openDialog();+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 10));+ });++ expect(dialog).toHaveFocus();+ expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();+ });++ it("uses named icon buttons and reserves unavailable actions", async () => {+ renderExportActions();+ await openDialog();++ for (const format of ["CSV", "TSV", "JSON"]) {+ expect(+ screen.getByRole("button", { name: `Download ${format}` }),+ ).toBeEnabled();+ expect(+ screen.getByRole("button", { name: `Copy ${format}` }),+ ).toBeEnabled();+ }++ expect(+ screen.getByRole("button", { name: "Download Parquet" }),+ ).toBeEnabled();+ expect(screen.getByRole("button", { name: "Copy Parquet" })).toBeDisabled();+ expect(+ screen.getByRole("button", { name: "Download Markdown" }),+ ).toBeDisabled();+ expect(screen.getByRole("button", { name: "Copy Markdown" })).toBeEnabled();+ });++ it.each([+ ["CSV", "csv"],+ ["TSV", "tsv"],+ ["JSON", "json"],+ ["Parquet", "parquet"],+ ] as const)(+ "downloads %s with its existing URL contract",+ async (label, format) => {+ downloadAs.mockResolvedValue({+ url: "https://example.test/export?token=abc",+ filename: "table.source",+ });+ renderExportActions();+ await openDialog();++ fireEvent.click(+ screen.getByRole("button", { name: `Download ${label}` }),+ );++ await waitFor(() => {+ expect(downloadByURL).toHaveBeenCalledWith(+ `https://example.test/export?token=abc&download=1&filename=table.${format}`,+ `table.${format}`,+ );+ });+ expect(downloadAs).toHaveBeenCalledWith({ format });+ expect(toast).toHaveBeenCalledWith({+ title: `${label} download started`,+ });+ expect(screen.getByRole("dialog")).toBeInTheDocument();+ },+ );++ it("keeps data URLs unchanged", async () => {+ downloadAs.mockResolvedValue({+ url: "data:text/csv;base64,YQ==",+ filename: "table",+ });+ renderExportActions();+ await openDialog();++ fireEvent.click(screen.getByRole("button", { name: "Download CSV" }));++ await waitFor(() => {+ expect(downloadByURL).toHaveBeenCalledWith(+ "data:text/csv;base64,YQ==",+ "table.csv",+ );+ });+ });++ it.each([+ {+ label: "CSV",+ sourceFormat: "csv" as const,+ sourceText: "name,value\nalpha,1\n",+ expectedText: "name,value\nalpha,1\n",+ },+ {+ label: "TSV",+ sourceFormat: "tsv" as const,+ sourceText: "name\tvalue\nalpha\t1\n",+ expectedText: "name\tvalue\nalpha\t1\n",+ },+ {+ label: "JSON",+ sourceFormat: "json" as const,+ sourceText: JSON.stringify([{ name: "alpha", value: 1 }]),+ expectedText: JSON.stringify([{ name: "alpha", value: 1 }], null, 2),+ },+ {+ label: "Markdown",+ sourceFormat: "json" as const,+ sourceText: JSON.stringify([{ name: "alpha", value: 1 }]),+ expectedText: jsonToMarkdown([{ name: "alpha", value: 1 }]),+ },+ ])(+ "copies $label with its existing conversion",+ async ({ label, sourceFormat, sourceText, expectedText }) => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ text: vi.fn().mockResolvedValue(sourceText),+ }),+ );+ renderExportActions();+ await openDialog();++ fireEvent.click(screen.getByRole("button", { name: `Copy ${label}` }));++ await waitFor(() => {+ expect(copyToClipboard).toHaveBeenCalledWith(expectedText);+ });+ expect(downloadAs).toHaveBeenCalledWith({ format: sourceFormat });+ expect(toast).toHaveBeenCalledWith({ title: "Copied to clipboard" });+ await waitFor(() => {+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });+ },+ );++ it("shows the failure inside the affected format row", async () => {+ downloadAs.mockRejectedValueOnce(new Error("Kernel disconnected"));+ renderExportActions();+ await openDialog();++ fireEvent.click(screen.getByRole("button", { name: "Download JSON" }));++ const alert = await screen.findByRole("alert");+ expect(screen.getByTestId("export-row-json")).toContainElement(alert);+ expect(screen.getByTestId("export-row-csv")).not.toContainElement(alert);+ });++ it("shows download request failures inside the dialog", async () => {+ downloadAs.mockRejectedValueOnce(new Error("Kernel disconnected"));+ renderExportActions();+ await openDialog();++ fireEvent.click(screen.getByRole("button", { name: "Download CSV" }));++ const alert = await screen.findByRole("alert");+ expect(alert).toHaveTextContent("Failed to download");+ expect(alert).toHaveTextContent("Kernel disconnected");+ expect(downloadByURL).not.toHaveBeenCalled();+ });++ it("shows file delivery failures inside the dialog", async () => {+ vi.mocked(downloadByURL).mockImplementationOnce(() => {+ throw new Error("Download blocked");+ });+ renderExportActions();+ await openDialog();++ fireEvent.click(screen.getByRole("button", { name: "Download CSV" }));++ const alert = await screen.findByRole("alert");+ expect(alert).toHaveTextContent("Failed to download");+ expect(alert).toHaveTextContent("Download blocked");+ });++ it("shows fetch failures inside the dialog", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: false,+ statusText: "Forbidden",+ }),+ );+ renderExportActions();+ await openDialog();++ fireEvent.click(screen.getByRole("button", { name: "Copy CSV" }));++ const alert = await screen.findByRole("alert");+ expect(alert).toHaveTextContent("Failed to copy to clipboard");+ expect(alert).toHaveTextContent("Forbidden");+ });++ it("shows clipboard failures inside the dialog", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ text: vi.fn().mockResolvedValue("name\nalpha\n"),+ }),+ );+ vi.mocked(copyToClipboard).mockRejectedValueOnce(+ new Error("Clipboard permission denied"),+ );+ renderExportActions();+ await openDialog();++ fireEvent.click(screen.getByRole("button", { name: "Copy CSV" }));++ const alert = await screen.findByRole("alert");+ expect(alert).toHaveTextContent("Failed to copy to clipboard");+ expect(alert).toHaveTextContent("Clipboard permission denied");+ });++ it("shows backend failures before success fields", async () => {+ downloadAs.mockResolvedValueOnce({+ url: "https://example.test/partial",+ filename: "partial",+ error: "Export was rejected",+ });+ renderExportActions();+ await openDialog();++ fireEvent.click(screen.getByRole("button", { name: "Download JSON" }));++ const alert = await screen.findByRole("alert");+ expect(alert).toHaveTextContent("Export was rejected");+ expect(downloadByURL).not.toHaveBeenCalled();+ });++ it("installs missing packages and retries the same action", async () => {+ downloadAs+ .mockResolvedValueOnce({+ url: "",+ filename: "",+ error: "Parquet export requires pyarrow.",+ missing_packages: ["pyarrow"],+ })+ .mockResolvedValueOnce({+ url: "https://example.test/export",+ filename: "table",+ });+ renderExportActions();+ await openDialog();++ fireEvent.click(screen.getByRole("button", { name: "Download Parquet" }));++ const alert = await screen.findByRole("alert");+ expect(alert).toHaveTextContent("Parquet export requires pyarrow.");+ fireEvent.click(+ within(alert).getByRole("button", { name: "Install pyarrow" }),+ );+ expect(mocks.handleInstallPackages).toHaveBeenCalledWith(+ ["pyarrow"],+ expect.any(Function),+ );++ const onInstall = mocks.handleInstallPackages.mock+ .calls[0][1] as () => void;+ onInstall();++ await waitFor(() => {+ expect(downloadAs).toHaveBeenCalledTimes(2);+ expect(downloadByURL).toHaveBeenCalledWith(+ "https://example.test/export?download=1&filename=table.parquet",+ "table.parquet",+ );+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ });+ });++ it("hides package details and installation in read mode", async () => {+ downloadAs.mockResolvedValueOnce({+ url: "",+ filename: "",+ error: "Install pyarrow to export Parquet.",+ missing_packages: ["pyarrow"],+ });+ renderExportActions({}, null, "read");+ await openDialog();++ fireEvent.click(screen.getByRole("button", { name: "Download Parquet" }));++ const alert = await screen.findByRole("alert");+ expect(alert).toHaveTextContent(+ "Parquet export isn't available in this notebook",+ );+ expect(alert).not.toHaveTextContent("pyarrow");+ expect(within(alert).queryByRole("button")).not.toBeInTheDocument();+ });++ it("clears stale failures before a new action and after close", async () => {+ downloadAs.mockRejectedValueOnce(new Error("First failure"));+ renderExportActions();+ let dialog = await openDialog();++ fireEvent.click(screen.getByRole("button", { name: "Download CSV" }));+ expect(await screen.findByRole("alert")).toHaveTextContent("First failure");++ fireEvent.click(screen.getByRole("button", { name: "Download JSON" }));+ await waitFor(() => {+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ expect(downloadByURL).toHaveBeenCalled();+ });++ downloadAs.mockRejectedValueOnce(new Error("Second failure"));+ fireEvent.click(screen.getByRole("button", { name: "Download CSV" }));+ expect(await screen.findByRole("alert")).toHaveTextContent(+ "Second failure",+ );++ fireEvent.click(within(dialog).getByRole("button", { name: "Close" }));+ await waitFor(() => {+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });+ dialog = await openDialog();+ expect(within(dialog).queryByRole("alert")).not.toBeInTheDocument();+ });++ it("ignores a late failure from an earlier action", async () => {+ let rejectFirst: (reason: Error) => void = () => undefined;+ downloadAs+ .mockImplementationOnce(+ () =>+ new Promise((_, reject) => {+ rejectFirst = reject;+ }),+ )+ .mockResolvedValueOnce({+ url: "https://example.test/export",+ filename: "table",+ });+ renderExportActions();+ await openDialog();++ fireEvent.click(screen.getByRole("button", { name: "Download CSV" }));+ fireEvent.click(screen.getByRole("button", { name: "Download JSON" }));+ await waitFor(() => {+ expect(downloadByURL).toHaveBeenCalled();+ });++ await act(async () => {+ rejectFirst(new Error("Late failure"));+ });+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ });++ it("ignores a late failure after the dialog closes", async () => {+ let rejectDownload: (reason: Error) => void = () => undefined;+ downloadAs.mockImplementationOnce(+ () =>+ new Promise((_, reject) => {+ rejectDownload = reject;+ }),+ );+ renderExportActions();+ const dialog = await openDialog();++ fireEvent.click(screen.getByRole("button", { name: "Download CSV" }));+ fireEvent.click(within(dialog).getByRole("button", { name: "Close" }));+ await waitFor(() => {+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });+ await openDialog();++ await act(async () => {+ rejectDownload(new Error("Late failure"));+ });+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ });++ it("closes with the close button and restores trigger focus", async () => {+ renderExportActions();+ const trigger = screen.getByTestId("export-button");+ const dialog = await openDialog();++ fireEvent.click(within(dialog).getByRole("button", { name: "Close" }));++ await waitFor(() => {+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(trigger).toHaveFocus();+ });+ });++ it("closes with Escape and restores trigger focus", async () => {+ renderExportActions();+ const trigger = screen.getByTestId("export-button");+ trigger.focus();+ const dialog = await openDialog();+ const closeButton = within(dialog).getByRole("button", { name: "Close" });+ closeButton.focus();++ fireEvent.keyDown(closeButton, { key: "Escape" });++ await waitFor(() => {+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(trigger).toHaveFocus();+ });+ });++ it.each([+ {+ name: "the size check is pending",+ props: { sizeBytesIsLoading: true },+ },+ {+ name: "the export is over the host limit",+ props: { sizeBytes: 101 },+ },+ ])("keeps the trigger disabled when $name", ({ props }) => {+ renderExportActions(props, {+ limitBytes: 100,+ unavailableMessage: "This export is too large.",+ });+ const trigger = screen.getByTestId("export-button");++ expect(trigger).toBeDisabled();+ expect(trigger).toHaveClass("print:hidden");+ expect(trigger.parentElement).toHaveAttribute("tabindex", "0");+ fireEvent.click(trigger);+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });+});diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsxindex 517d7abce0..be6345c862 100644--- a/frontend/src/components/data-table/data-table.tsx+++ b/frontend/src/components/data-table/data-table.tsx@@ -86,7 +86,7 @@ interface DataTableProps<TData> extends Partial<ExportActionProps> {// PaginationtotalRows: number | TooManyRows;// JSON-serialized size of the currently-rendered data. Forwarded to- // ExportMenu so hosts can size-gate the Export button via downloadSizeLimitAtom.+ // ExportActions so hosts can size-gate the Export button via downloadSizeLimitAtom.sizeBytes?: number | null;sizeBytesIsLoading?: boolean;totalColumns: number;diff --git a/frontend/src/components/data-table/export-actions.tsx b/frontend/src/components/data-table/export-actions.tsxindex b44e90a358..89cdf961d9 100644--- a/frontend/src/components/data-table/export-actions.tsx+++ b/frontend/src/components/data-table/export-actions.tsx@@ -2,14 +2,19 @@import { useAtomValue } from "jotai";import {- BracesIcon,- BrickWallIcon,+ AlertCircleIcon,+ ChevronRightIcon,+ ClipboardCopyIcon,DownloadIcon,- FileTextIcon,- TableIcon,+ InfoIcon,} from "lucide-react";import React from "react";import { downloadSizeLimitAtom } from "./download-policy/atoms";+import type {+ DownloadAsArgs,+ DownloadAsOptions,+ DownloadFormat,+} from "./schemas";import { logNever } from "@/utils/assertNever";import { cn } from "@/utils/cn";import { copyToClipboard } from "@/utils/copy";@@ -21,66 +26,81 @@ import {jsonToMarkdown,} from "@/utils/json/json-parser";import { MissingPackagePrompt } from "../datasources/missing-package-prompt";+import { Alert, AlertDescription, AlertTitle } from "../ui/alert";import { Button } from "../ui/button";import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuLabel,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from "../ui/dropdown-menu";+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "../ui/dialog";+import { Label } from "../ui/label";+import { NativeSelect } from "../ui/native-select";+import { Switch } from "../ui/switch";import { Tooltip } from "../ui/tooltip";import { toast } from "../ui/use-toast";-const FILE_TYPES = {- CSV: {+const EXPORT_OPTIONS = [+ {label: "CSV",format: "csv",description: "Comma-separated values",- icon: TableIcon,+ canDownload: true,+ canCopy: true,},- JSON: {+ {+ label: "TSV",+ format: "tsv",+ description: "Best for Excel and Google Sheets",+ canDownload: true,+ canCopy: true,+ },+ {label: "JSON",format: "json",description: "Raw JSON data",- icon: BracesIcon,+ canDownload: true,+ canCopy: true,},- PARQUET: {+ {label: "Parquet",format: "parquet",description: "Columnar binary format",- icon: BrickWallIcon,+ canDownload: true,+ canCopy: false,},- 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,+ canDownload: false,+ canCopy: true,},-} as const;--const downloadOptions = [- FILE_TYPES.CSV,- FILE_TYPES.TSV,- FILE_TYPES.JSON,- FILE_TYPES.PARQUET,-];-const copyOptions = [- FILE_TYPES.TSV,- FILE_TYPES.JSON,- FILE_TYPES.CSV,- FILE_TYPES.MARKDOWN,-];--type DownloadFormat = (typeof downloadOptions)[number]["format"];-type CopyFormat = (typeof copyOptions)[number]["format"];+] as const;++type ExportFormat = (typeof EXPORT_OPTIONS)[number]["format"];+type CopyFormat = Exclude<ExportFormat, "parquet">;+type ExportAction =+ | { destination: "download"; format: DownloadFormat }+ | { destination: "copy"; format: CopyFormat };++type ExportFailure =+ | {+ kind: "error";+ title: string;+ description: string;+ action: ExportAction;+ }+ | {+ kind: "missing-packages";+ title: string;+ description?: string | null;+ packages: string[];+ featureName: string;+ action: ExportAction;+ };// Each clipboard-copy format fetches from a backend download format, then// transforms the payload client-side as needed.@@ -91,13 +111,117 @@ const COPY_SOURCE_FORMAT: Record<CopyFormat, DownloadFormat> = {markdown: "json",};+const SEPARATORS = [+ { value: ",", label: "Comma" },+ { value: ";", label: "Semicolon" },+ { value: "|", label: "Pipe" },+] as const;++const ENCODINGS = [+ { value: "utf-8", label: "UTF-8" },+ { value: "utf-8-sig", label: "UTF-8 with BOM" },+ { value: "latin-1", label: "Latin-1" },+] as const;++type Separator = (typeof SEPARATORS)[number]["value"];+type Encoding = (typeof ENCODINGS)[number]["value"];++interface ExportSettings {+ csv: { separator: Separator; encoding: Encoding };+ tsv: { encoding: Encoding };+ json: { ensureAscii: boolean };+}++const DEFAULT_SETTINGS: ExportSettings = {+ csv: { separator: ",", encoding: "utf-8" },+ tsv: { encoding: "utf-8" },+ json: { ensureAscii: true },+};++type ConfigurableFormat = keyof ExportSettings;++const isConfigurable = (format: ExportFormat): format is ConfigurableFormat =>+ format in DEFAULT_SETTINGS;++/**+ * Build the request options for one action. Only settings that differ from+ * the defaults are sent, so the backend keeps its own defaults otherwise.+ *+ * Clipboard copies never send an encoding. The browser decodes the fetched+ * payload as UTF-8, so any other encoding would corrupt the copied text.+ */+function requestOptions(+ settings: ExportSettings,+ format: DownloadFormat,+ destination: ExportAction["destination"],+): DownloadAsOptions | undefined {+ const options: DownloadAsOptions = {};+ switch (format) {+ case "csv":+ if (settings.csv.separator !== DEFAULT_SETTINGS.csv.separator) {+ options.separator = settings.csv.separator;+ }+ if (+ destination === "download" &&+ settings.csv.encoding !== DEFAULT_SETTINGS.csv.encoding+ ) {+ options.encoding = settings.csv.encoding;+ }+ break;+ case "tsv":+ if (+ destination === "download" &&+ settings.tsv.encoding !== DEFAULT_SETTINGS.tsv.encoding+ ) {+ options.encoding = settings.tsv.encoding;+ }+ break;+ case "json":+ if (settings.json.ensureAscii !== DEFAULT_SETTINGS.json.ensureAscii) {+ options.ensure_ascii = settings.json.ensureAscii;+ }+ break;+ case "parquet":+ break;+ default:+ logNever(format);+ }+ return Object.keys(options).length > 0 ? options : undefined;+}++const labelForValue = (+ items: ReadonlyArray<{ value: string; label: string }>,+ value: string,+): string => items.find((item) => item.value === value)?.label ?? value;++/** Short summary of the current settings, shown next to the format label. */+function settingsSummary(+ settings: ExportSettings,+ format: ExportFormat,+): string | null {+ switch (format) {+ case "csv":+ return [+ labelForValue(SEPARATORS, settings.csv.separator),+ labelForValue(ENCODINGS, settings.csv.encoding),+ ].join(" · ");+ case "tsv":+ return labelForValue(ENCODINGS, settings.tsv.encoding);+ case "json":+ return settings.json.ensureAscii+ ? "Escapes non-ASCII"+ : "Keeps non-ASCII";+ case "parquet":+ case "markdown":+ return null;+ default:+ logNever(format);+ return null;+ }+}+export interface ExportActionProps {- downloadAs: (req: { format: DownloadFormat }) => Promise<{- url: string;- filename: string;- error?: string | null;- missing_packages?: string[] | null;- }>;+ downloadAs: DownloadAsArgs;// JSON-serialized size of the currently-rendered data. Used together with// downloadSizeLimitAtom to disable the Export button when a host (e.g.,// marimo-lsp inside VS Code) declares a download size cap. Null/undefined@@ -106,13 +230,27 @@ export interface ExportActionProps {sizeBytesIsLoading?: boolean;}-const labelForDownloadFormat = (format: DownloadFormat): string =>- downloadOptions.find((opt) => opt.format === format)?.label ?? format;-const labelForCopyFormat = (format: CopyFormat): string =>- copyOptions.find((opt) => opt.format === format)?.label ?? format;+const labelForFormat = (format: ExportFormat): string =>+ EXPORT_OPTIONS.find((option) => option.format === format)?.label ?? format;++const failureTitleForAction = (action: ExportAction): string =>+ action.destination === "download"+ ? "Failed to download"+ : "Failed to copy to clipboard";++const failureDescription = (error: unknown): string =>+ typeof error === "string" ? error : prettyError(error);-export const ExportMenu: React.FC<ExportActionProps> = (props) => {- const [downloadMenuOpen, setDownloadMenuOpen] = React.useState(false);+export const ExportActions: React.FC<ExportActionProps> = (props) => {+ const [exportDialogOpen, setExportDialogOpen] = React.useState(false);+ const [failure, setFailure] = React.useState<ExportFailure | null>(null);+ const [settings, setSettings] =+ React.useState<ExportSettings>(DEFAULT_SETTINGS);+ const [expandedFormat, setExpandedFormat] =+ React.useState<ConfigurableFormat | null>(null);+ const triggerRef = React.useRef<HTMLButtonElement>(null);+ const dialogRef = React.useRef<HTMLDivElement>(null);+ const latestActionId = React.useRef(0);const policy = useAtomValue(downloadSizeLimitAtom);const overLimit = !!(policy &&@@ -128,13 +266,14 @@ export const ExportMenu: React.FC<ExportActionProps> = (props) => {const button = (<Button+ ref={triggerRef}data-testid="export-button"size="xs"variant="text"disabled={disabled}className={cn("print:hidden text-xs gap-1",- downloadMenuOpen ? "text-primary" : "text-muted-foreground",+ exportDialogOpen ? "text-primary" : "text-muted-foreground",)}><DownloadIcon className="w-3.5 h-3.5" />@@ -142,38 +281,60 @@ export const ExportMenu: React.FC<ExportActionProps> = (props) => {</Button>);+ const handleDialogOpenChange = (open: boolean) => {+ setExportDialogOpen(open);+ if (!open) {+ latestActionId.current += 1;+ setFailure(null);+ setExpandedFormat(null);+ setSettings(DEFAULT_SETTINGS);+ }+ };++ const beginAction = () => {+ const actionId = latestActionId.current + 1;+ latestActionId.current = actionId;+ setFailure(null);+ return actionId;+ };++ const setActionFailure = (actionId: number, nextFailure: ExportFailure) => {+ if (actionId === latestActionId.current) {+ setFailure(nextFailure);+ }+ };+const resolveDownloadUrl = async (format: DownloadFormat,- onRetry: () => void,+ action: ExportAction,+ actionId: number,): Promise<{url: string;filename: string;} | null> => {- let response: Awaited<ReturnType<typeof props.downloadAs>>;- try {- response = await props.downloadAs({ format });- } catch (error) {- toast({- title: "Failed to download",- description:- error != null && typeof error === "object" && "message" in error- ? String(error.message)- : String(error),+ const options = requestOptions(settings, format, action.destination);+ const response = await props.downloadAs(+ options ? { format, options } : { format },+ );++ if (response.missing_packages && response.missing_packages.length > 0) {+ setActionFailure(actionId, {+ kind: "missing-packages",+ title: "Export failed",+ packages: response.missing_packages,+ featureName: `${labelForFormat(action.format)} export`,+ description: response.error,+ action,});return null;}- if (response.missing_packages && response.missing_packages.length > 0) {- toast({- title: "Export failed",- description: (- <MissingPackagePrompt- packages={response.missing_packages}- featureName={`${labelForDownloadFormat(format)} export`}- description={response.error}- onInstall={onRetry}- />- ),+ if (response.error) {+ setActionFailure(actionId, {+ kind: "error",+ title: failureTitleForAction(action),+ description: response.error,+ action,});return null;}@@ -185,49 +346,60 @@ export const ExportMenu: React.FC<ExportActionProps> = (props) => {};const handleDownload = async (format: DownloadFormat) => {- const label = labelForDownloadFormat(format);- const ok = await withLoadingToast(- `Preparing ${label} export...`,- async () => {- const result = await resolveDownloadUrl(format, () => {- void handleDownload(format);- });- if (!result) {- return false;- }- const rawName = (result.filename ?? "").trim();- const baseName = Filenames.withoutExtension(rawName) || "download";- const downloadName = `${baseName}.${format}`;- // Append ?download=1 so the server returns Content-Disposition: attachment.- // This forces a save even when <a download> is ignored — e.g., inside- // sandboxed iframes that lack `allow-downloads`. Skip for data: URLs- // (used in pyodide/wasm) since query params would corrupt the payload.- let downloadUrl = result.url;- if (!downloadUrl.startsWith("data:")) {- const separator = downloadUrl.includes("?") ? "&" : "?";- const params = new URLSearchParams({- download: "1",- filename: downloadName,- });- downloadUrl = `${downloadUrl}${separator}${params.toString()}`;- }- downloadByURL(downloadUrl, downloadName);- return true;- },- );- if (ok) {- toast({ title: `${label} download started` });+ const action: ExportAction = { destination: "download", format };+ const actionId = beginAction();+ const label = labelForFormat(format);+ try {+ const ok = await withLoadingToast(+ `Preparing ${label} export...`,+ async () => {+ const result = await resolveDownloadUrl(format, action, actionId);+ if (!result) {+ return false;+ }+ const rawName = (result.filename ?? "").trim();+ const baseName = Filenames.withoutExtension(rawName) || "download";+ const downloadName = `${baseName}.${format}`;+ // Append ?download=1 so the server returns Content-Disposition: attachment.+ // This forces a save even when <a download> is ignored — e.g., inside+ // sandboxed iframes that lack `allow-downloads`. Skip for data: URLs+ // (used in pyodide/wasm) since query params would corrupt the payload.+ let downloadUrl = result.url;+ if (!downloadUrl.startsWith("data:")) {+ const separator = downloadUrl.includes("?") ? "&" : "?";+ const params = new URLSearchParams({+ download: "1",+ filename: downloadName,+ });+ downloadUrl = `${downloadUrl}${separator}${params.toString()}`;+ }+ downloadByURL(downloadUrl, downloadName);+ return true;+ },+ );+ if (ok) {+ toast({ title: `${label} download started` });+ }+ } catch (error) {+ setActionFailure(actionId, {+ kind: "error",+ title: failureTitleForAction(action),+ description: failureDescription(error),+ action,+ });}};- const handleClipboardCopy = async (format: CopyFormat) => {+ const handleClipboardCopy = async (+ format: CopyFormat,+ action: ExportAction,+ actionId: number,+ ) => {await withLoadingToast(- `Preparing ${labelForCopyFormat(format)} for clipboard...`,+ `Preparing ${labelForFormat(format)} for clipboard...`,async () => {const sourceFormat = COPY_SOURCE_FORMAT[format];- const result = await resolveDownloadUrl(sourceFormat, () => {- void handleClipboardCopy(format);- });+ const result = await resolveDownloadUrl(sourceFormat, action, actionId);if (!result) {return;}@@ -257,79 +429,373 @@ export const ExportMenu: React.FC<ExportActionProps> = (props) => {toast({title: "Copied to clipboard",});+ handleDialogOpenChange(false);},);};+ const handleCopyAction = async (format: CopyFormat) => {+ const action: ExportAction = { destination: "copy", format };+ const actionId = beginAction();+ try {+ await handleClipboardCopy(format, action, actionId);+ } catch (error) {+ setActionFailure(actionId, {+ kind: "error",+ title: failureTitleForAction(action),+ description: failureDescription(error),+ action,+ });+ }+ };++ const retryAction = (action: ExportAction) => {+ if (action.destination === "download") {+ void handleDownload(action.format);+ } else {+ void handleCopyAction(action.format);+ }+ };++ const toggleExpanded = (format: ExportFormat) => {+ if (!isConfigurable(format)) {+ return;+ }+ setExpandedFormat((current) => (current === format ? null : format));+ };+return (- <DropdownMenu- modal={false}- open={downloadMenuOpen}- onOpenChange={setDownloadMenuOpen}- >- <Tooltip- content={tooltipContent}- open={downloadMenuOpen ? false : undefined}- >- <DropdownMenuTrigger asChild={true} disabled={disabled}>- <span tabIndex={disabled ? 0 : -1} className="inline-flex">+ <Dialog open={exportDialogOpen} onOpenChange={handleDialogOpenChange}>+ <Tooltip content={tooltipContent}>+ {disabled ? (+ // Keep the host-limit reason reachable when the nested button is disabled.+ // oxlint-disable-next-line jsx-a11y/no-noninteractive-tabindex+ <span tabIndex={0} className="inline-flex">{button}</span>- </DropdownMenuTrigger>+ ) : (+ <DialogTrigger asChild={true}>{button}</DialogTrigger>+ )}</Tooltip>- <DropdownMenuContent side="bottom" className="print:hidden">- <DropdownMenuLabel className="text-xs text-muted-foreground">- Download- </DropdownMenuLabel>- {downloadOptions.map((option) => (- <DropdownMenuItem- key={option.label}- onSelect={() => {- void handleDownload(option.format);- }}- >- <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>+ <DialogContent+ ref={dialogRef}+ className="print:hidden gap-4 sm:max-w-[540px]"+ onOpenAutoFocus={(event) => {+ event.preventDefault();+ dialogRef.current?.focus();+ }}+ onCloseAutoFocus={(event) => {+ event.preventDefault();+ triggerRef.current?.focus();+ }}+ onKeyDown={(event) => {+ if (event.key === "Escape") {+ handleDialogOpenChange(false);+ }+ }}+ >+ <DialogHeader>+ <DialogTitle>Export table</DialogTitle>+ <DialogDescription>+ Download a file or copy to the clipboard.+ </DialogDescription>+ </DialogHeader>+ <ul+ aria-label="Export formats"+ className="list-none overflow-hidden rounded-md border divide-y"+ >+ {EXPORT_OPTIONS.map((option) => {+ const configurableFormat = isConfigurable(option.format)+ ? option.format+ : null;+ const expanded =+ configurableFormat !== null &&+ expandedFormat === configurableFormat;+ const panelId = `export-options-${option.format}`;+ const rowFailure =+ failure?.action.format === option.format ? failure : null;+ const summary = settingsSummary(settings, option.format);+ return (+ <li+ key={option.format}+ data-testid={`export-row-${option.format}`}+ className={cn(expanded && "bg-muted/40")}+ >+ <div className="grid min-h-[60px] grid-cols-[28px_1fr_auto] items-center gap-x-1 px-2.5 py-2 hover:bg-accent/50">+ {configurableFormat ? (+ <Button+ type="button"+ variant="ghost"+ size="icon"+ aria-label={`${option.label} options`}+ aria-expanded={expanded}+ aria-controls={panelId}+ onClick={() => toggleExpanded(option.format)}+ >+ <ChevronRightIcon+ className={cn(+ "h-4 w-4 text-muted-foreground transition-transform",+ expanded && "rotate-90",+ )}+ />+ </Button>+ ) : (+ <span aria-hidden={true} className="h-6 w-6" />+ )}+ <div className="grid gap-1 pl-1">+ <span className="flex items-baseline gap-x-2">+ <span className="text-sm font-medium leading-tight">+ {option.label}+ </span>+ {summary && (+ <span+ data-testid={`export-summary-${option.format}`}+ className="text-xs text-muted-foreground"+ >+ {summary}+ </span>+ )}+ </span>+ <span className="text-xs text-muted-foreground leading-tight">+ {option.description}+ </span>+ </div>+ <div className="flex items-center gap-0.5">+ <Tooltip+ content={+ option.canDownload+ ? `Download ${option.label}`+ : `${option.label} is available for copy only.`+ }+ >+ <span className="inline-flex">+ <Button+ type="button"+ variant="ghost"+ size="icon"+ aria-label={`Download ${option.label}`}+ disabled={!option.canDownload}+ onClick={+ option.canDownload+ ? () => {+ void handleDownload(option.format);+ }+ : undefined+ }+ >+ <DownloadIcon className="h-4 w-4" />+ </Button>+ </span>+ </Tooltip>+ <Tooltip+ content={+ option.canCopy+ ? `Copy ${option.label}`+ : `${option.label} is available for download only.`+ }+ >+ <span className="inline-flex">+ <Button+ type="button"+ variant="ghost"+ size="icon"+ aria-label={`Copy ${option.label}`}+ disabled={!option.canCopy}+ onClick={+ option.canCopy+ ? () => {+ void handleCopyAction(option.format);+ }+ : undefined+ }+ >+ <ClipboardCopyIcon className="h-4 w-4" />+ </Button>+ </span>+ </Tooltip>+ </div>+ </div>+ {expanded && configurableFormat && (+ <fieldset+ id={panelId}+ className="grid grid-cols-2 gap-3 border-t bg-muted/50 px-3.5 py-3.5 pl-[52px]"+ >+ <legend className="sr-only">{option.label} options</legend>+ <ExportSettingsFields+ format={configurableFormat}+ settings={settings}+ onChange={setSettings}+ />+ </fieldset>+ )}+ {rowFailure && (+ <div className="border-t px-3 py-2 pl-[42px]">+ <Alert+ variant="destructive"+ className="p-3 has-[svg]:pl-9 [&>svg]:left-3 [&>svg]:top-3"+ >+ <AlertCircleIcon className="h-4 w-4" />+ <div>+ <AlertTitle className="text-sm">+ {rowFailure.title}+ </AlertTitle>+ <AlertDescription className="text-xs">+ {rowFailure.kind === "missing-packages" ? (+ <MissingPackagePrompt+ packages={rowFailure.packages}+ featureName={rowFailure.featureName}+ description={rowFailure.description}+ onInstall={() => retryAction(rowFailure.action)}+ className="items-start"+ />+ ) : (+ rowFailure.description+ )}+ </AlertDescription>+ </div>+ </Alert>+ </div>+ )}+ </li>+ );+ })}+ </ul>+ </DialogContent>+ </Dialog>+ );+};++interface ExportSettingsFieldsProps {+ format: ConfigurableFormat;+ settings: ExportSettings;+ onChange: React.Dispatch<React.SetStateAction<ExportSettings>>;+}++const ExportSettingsFields: React.FC<ExportSettingsFieldsProps> = ({+ format,+ settings,+ onChange,+}) => {+ const id = React.useId();++ const encodingField = (encoding: Encoding, key: "csv" | "tsv") => (+ <SettingField+ id={`${id}-encoding`}+ label="Encoding"+ help="Text encoding of the saved file. Pick UTF-8 with BOM when Excel shows garbled accents. Copies always use UTF-8."+ >+ <NativeSelect+ id={`${id}-encoding`}+ className="mb-0 w-full"+ value={encoding}+ onChange={(event) => {+ const next = event.target.value as Encoding;+ onChange((current) => ({+ ...current,+ [key]: { ...current[key], encoding: next },+ }));+ }}+ >+ {ENCODINGS.map((item) => (+ <option key={item.value} value={item.value}>+ {item.label}+ </option>))}- </DropdownMenuContent>- </DropdownMenu>+ </NativeSelect>+ </SettingField>);++ switch (format) {+ case "csv":+ return (+ <>+ <SettingField+ id={`${id}-separator`}+ label="Delimiter"+ help="Character between fields. Semicolon suits spreadsheets in locales that use a comma as the decimal separator."+ >+ <NativeSelect+ id={`${id}-separator`}+ className="mb-0 w-full"+ value={settings.csv.separator}+ onChange={(event) => {+ const next = event.target.value as Separator;+ onChange((current) => ({+ ...current,+ csv: { ...current.csv, separator: next },+ }));+ }}+ >+ {SEPARATORS.map((item) => (+ <option key={item.value} value={item.value}>+ {item.label}+ </option>+ ))}+ </NativeSelect>+ </SettingField>+ {encodingField(settings.csv.encoding, "csv")}+ </>+ );+ case "tsv":+ return encodingField(settings.tsv.encoding, "tsv");+ case "json":+ return (+ <SettingField+ id={`${id}-ensure-ascii`}+ label="Escape non-ASCII"+ help="Write characters outside ASCII as \\u escapes. Turn off to keep accents and symbols readable in the file."+ >+ <Switch+ id={`${id}-ensure-ascii`}+ size="xs"+ checked={settings.json.ensureAscii}+ onCheckedChange={(checked) => {+ onChange((current) => ({+ ...current,+ json: { ensureAscii: checked },+ }));+ }}+ />+ </SettingField>+ );+ default:+ logNever(format);+ return null;+ }};+interface SettingFieldProps {+ id: string;+ label: string;+ help: string;+ children: React.ReactNode;+}++const SettingField: React.FC<SettingFieldProps> = ({+ id,+ label,+ help,+ children,+}) => (+ <div className="grid gap-1.5">+ <span className="flex items-center gap-1">+ <Label htmlFor={id} className="text-xs font-medium">+ {label}+ </Label>+ <Tooltip content={help}>+ <button+ type="button"+ className="inline-flex text-muted-foreground hover:text-foreground"+ aria-label={`${label} help`}+ >+ <InfoIcon className="h-3 w-3" />+ </button>+ </Tooltip>+ </span>+ <span className="flex items-center">{children}</span>+ </div>+);+function fetchJson(url: string): Promise<Record<string, unknown>[]> {return fetchText(url).then(jsonParseWithSpecialChar<Record<string, unknown>[]>,diff --git a/frontend/src/components/data-table/schemas.ts b/frontend/src/components/data-table/schemas.tsindex d56ce10b14..e16b6ed187 100644--- a/frontend/src/components/data-table/schemas.ts+++ b/frontend/src/components/data-table/schemas.ts@@ -3,9 +3,24 @@import z from "zod";import { rpc } from "@/plugins/core/rpc";-export type DownloadAsArgs = (req: {- format: "csv" | "json" | "parquet" | "tsv";-}) => Promise<{+export type DownloadFormat = "csv" | "json" | "parquet" | "tsv";++/**+ * Per-request export options. Each field is optional. A missing field keeps+ * the widget's default for that setting.+ */+export interface DownloadAsOptions {+ separator?: string;+ encoding?: string;+ ensure_ascii?: boolean;+}++export interface DownloadAsRequest {+ format: DownloadFormat;+ options?: DownloadAsOptions;+}++export type DownloadAsArgs = (req: DownloadAsRequest) => Promise<{url: string;filename: string;error?: string | null;@@ -16,6 +31,13 @@ export const DownloadAsSchema = rpc.input(z.object({format: z.enum(["csv", "json", "parquet", "tsv"]),+ options: z+ .object({+ separator: z.string().optional(),+ encoding: z.string().optional(),+ ensure_ascii: z.boolean().optional(),+ })+ .optional(),}),).output(diff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.pyindex 45c3967db5..31b7f7deb8 100644--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py@@ -26,6 +26,7 @@ from marimo._plugins.ui._impl.dataframes.transforms.types import ()from marimo._plugins.ui._impl.table import (DownloadAsArgs,+ DownloadAsOptions,DownloadAsResponse,GetSizeBytesResponse,SearchTableArgs,@@ -367,18 +368,21 @@ class dataframe(UIElement[dict[str, Any], DataFrameType]):bound_filename = get_bound_name(self._id)+ widget_defaults = DownloadOptions(+ delimited=DelimitedOptions(+ encoding=self._download_csv_encoding,+ separator=self._download_csv_separator,+ ),+ json=JsonOptions(ensure_ascii=self._download_json_ensure_ascii),+ )+ options = (args.options or DownloadAsOptions()).resolve(+ widget_defaults+ )+url, filename = download_as(manager,args.format,- options=DownloadOptions(- delimited=DelimitedOptions(- encoding=self._download_csv_encoding,- separator=self._download_csv_separator,- ),- json=JsonOptions(- ensure_ascii=self._download_json_ensure_ascii- ),- ),+ options=options,filename=bound_filename,)return DownloadAsResponse(url=url, filename=filename)diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex 6c207c496e..21f23939f5 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -55,6 +55,9 @@ from marimo._plugins.ui._impl.tables.table_manager import ()from marimo._plugins.ui._impl.tables.utils import get_table_managerfrom marimo._plugins.ui._impl.utils.dataframe import (+ DelimitedOptions,+ DownloadOptions,+ JsonOptions,ListOrTuple,TableData,download_as,@@ -91,9 +94,45 @@ class TableSearchError(Exception):super().__init__(error)+@dataclass+class DownloadAsOptions:+ """Per-request export options chosen in the export dialog.++ Every field is optional. A `None` field keeps the widget's default for+ that setting.++ Args:+ separator (str, optional): Field separator for CSV output.+ encoding (str, optional): Text encoding for CSV and TSV output.+ ensure_ascii (bool, optional): Whether JSON output escapes+ non-ASCII characters.+ """++ separator: str | None = None+ encoding: str | None = None+ ensure_ascii: bool | None = None++ def resolve(self, defaults: DownloadOptions) -> DownloadOptions:+ """Layer the request options over the widget defaults."""+ return DownloadOptions(+ delimited=DelimitedOptions(+ encoding=self.encoding or defaults.delimited.encoding,+ separator=self.separator or defaults.delimited.separator,+ ),+ json=JsonOptions(+ ensure_ascii=(+ defaults.json.ensure_ascii+ if self.ensure_ascii is None+ else self.ensure_ascii+ )+ ),+ )++@dataclassclass DownloadAsArgs:format: Literal["csv", "tsv", "json", "parquet"]+ options: DownloadAsOptions | None = None@dataclass@@ -1036,7 +1075,8 @@ class table(user to install the dependency and retry.Args:- args (DownloadAsArgs): The requested download format. Must be+ args (DownloadAsArgs): The requested download format and+ optional per-request export options. The format must beone of `'csv'`, `'tsv'`, `'json'`, or `'parquet'`.Returns:@@ -1094,10 +1134,14 @@ class table(if isinstance(manager_candidate, TableManager):bound_filename = get_bound_name(self._id)+ options = (args.options or DownloadAsOptions()).resolve(+ DownloadOptions()+ )url, filename = download_as(manager_candidate,args.format,drop_marimo_index=True,+ options=options,filename=bound_filename,)return DownloadAsResponse(url=url, filename=filename)diff --git a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py b/tests/_plugins/ui/_impl/dataframes/test_dataframe.pyindex fc4ffae4c9..15d733cc10 100644--- a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py+++ b/tests/_plugins/ui/_impl/dataframes/test_dataframe.py@@ -16,6 +16,7 @@ from marimo._plugins.ui._impl.dataframes.dataframe import ()from marimo._plugins.ui._impl.table import (DownloadAsArgs,+ DownloadAsOptions,SearchTableArgs,TableSearchError,)@@ -369,6 +370,36 @@ class TestDataframes:assert "A;B" in csv_textassert "1;x" in csv_text+ @staticmethod+ @pytest.mark.skipif(+ not HAS_DEPS, reason="optional dependencies not installed"+ )+ def test_dataframe_download_request_options_layer_over_defaults() -> None:+ df = pd.DataFrame({"A": [1, 2], "B": ["こんにちは", "y"]})+ subject = ui.dataframe(+ df,+ download_csv_separator=";",+ download_csv_encoding="utf-8-sig",+ )++ # A request field replaces the widget default for that setting.+ url = subject._download_as(+ DownloadAsArgs(+ format="csv", options=DownloadAsOptions(separator="|")+ )+ ).url+ csv_bytes = from_data_uri(url)[1]+ assert csv_bytes.startswith(b"\xef\xbb\xbf")+ assert "A|B" in csv_bytes.decode("utf-8-sig")++ # An empty request keeps every widget default.+ url = subject._download_as(+ DownloadAsArgs(format="csv", options=DownloadAsOptions())+ ).url+ csv_bytes = from_data_uri(url)[1]+ assert csv_bytes.startswith(b"\xef\xbb\xbf")+ assert "A;B" in csv_bytes.decode("utf-8-sig")+@staticmethod@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed"diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.pyindex bcbeb04668..2b8a4d8eb7 100644--- a/tests/_plugins/ui/_impl/test_table.py+++ b/tests/_plugins/ui/_impl/test_table.py@@ -24,6 +24,7 @@ from marimo._plugins.ui._impl.table import (CalculateTopKRowsResponse,ColumnSummariesArgs,DownloadAsArgs,+ DownloadAsOptions,SearchTableArgs,SortArgs,TableSearchError,@@ -1700,6 +1701,56 @@ def test_download_as_ignores_cell_selection() -> None:assert int(rows[0]["a"]) == 2+ not DependencyManager.pandas.has() and not DependencyManager.polars.has(),+ reason="Pandas or Polars not installed",+)+def test_download_as_csv_request_options() -> None:+ table = ui.table({"a": [1, 2], "b": ["こんにちは", "y"]})++ default_url = table._download_as(DownloadAsArgs(format="csv")).url+ default_bytes = from_data_uri(default_url)[1]+ assert not default_bytes.startswith(b"\xef\xbb\xbf")+ assert "a,b" in default_bytes.decode("utf-8")++ url = table._download_as(+ DownloadAsArgs(+ format="csv",+ options=DownloadAsOptions(separator=";", encoding="utf-8-sig"),+ )+ ).url+ csv_bytes = from_data_uri(url)[1]+ assert csv_bytes.startswith(b"\xef\xbb\xbf")+ csv_text = csv_bytes.decode("utf-8-sig")+ assert "a;b" in csv_text+ assert "1;こんにちは" in csv_text+++ not DependencyManager.pandas.has(), reason="Pandas not installed"+)+def test_download_as_json_request_options() -> None:+ import pandas as pd++ table = ui.table(pd.DataFrame({"a": ["こんにちは"]}))++ default_text = from_data_uri(+ table._download_as(DownloadAsArgs(format="json")).url+ )[1].decode("utf-8")+ assert "こんにちは" not in default_text+ assert json.loads(default_text)[0]["a"] == "こんにちは"++ text = from_data_uri(+ table._download_as(+ DownloadAsArgs(+ format="json",+ options=DownloadAsOptions(ensure_ascii=False),+ )+ ).url+ )[1].decode("utf-8")+ assert "こんにちは" in text++def test_download_as_parquet_without_libs_reports_missing_packages(monkeypatch: pytest.MonkeyPatch,) -> None: