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: unified export dialog UI (#10429)
Péter Gyarmati3abe8de7b5a2
diff --git a/frontend/e2e-tests/helper.ts b/frontend/e2e-tests/helper.tsindex c7c996b785..4c0d00e53b 100644--- a/frontend/e2e-tests/helper.ts+++ b/frontend/e2e-tests/helper.ts@@ -105,15 +105,11 @@ export async function exportAsHTMLAndTakeScreenshot(page: Page) {// Wait for networkidle so that the notebook is fully loadedawait page.waitForLoadState("networkidle");- // Start waiting for download before clicking.+ await openCommandPalette({ page, command: "Download as HTML" });+const [download] = await Promise.all([page.waitForEvent("download"),- page- .getByTestId("notebook-menu-dropdown")- .click()- .then(() => {- return openCommandPalette({ page, command: "Download as HTML" });- }),+ page.getByRole("button", { name: "Export HTML" }).click(),]);// Wait for the download process to complete and save the downloaded file somewhere.diff --git a/frontend/src/components/editor/actions/__tests__/pair-with-agent-commands.test.ts b/frontend/src/components/editor/actions/__tests__/pair-with-agent-commands.test.tsindex 403d426260..c705e13add 100644--- a/frontend/src/components/editor/actions/__tests__/pair-with-agent-commands.test.ts+++ b/frontend/src/components/editor/actions/__tests__/pair-with-agent-commands.test.ts@@ -8,8 +8,8 @@ import {getRawPrompt,getTerminalCommand,maskToken,- shellQuote,} from "../pair-with-agent-commands";+import { shellQuote } from "@/utils/shell";const CONNECTION: ConnectionInfo = {url: "http://localhost:8000",diff --git a/frontend/src/components/editor/actions/export-dialog/__tests__/export-command.test.ts b/frontend/src/components/editor/actions/export-dialog/__tests__/export-command.test.tsnew file mode 100644index 0000000000..609bb40980--- /dev/null+++ b/frontend/src/components/editor/actions/export-dialog/__tests__/export-command.test.ts@@ -0,0 +1,115 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { describe, expect, it } from "vitest";+import { getExportCommand } from "../export-command";+import {+ DEFAULT_EXPORT_OPTIONS,+ type ExportFormat,+ type ExportOptions,+} from "../state";++function options(overrides: Partial<ExportOptions> = {}): ExportOptions {+ return {+ ...DEFAULT_EXPORT_OPTIONS,+ ...overrides,+ };+}++function command(+ format: ExportFormat,+ filename: string | null,+ overrides: Partial<ExportOptions> = {},+) {+ return getExportCommand({ format, filename, options: options(overrides) });+}++describe("getExportCommand", () => {+ it("includes the selected HTML code setting and derived output path", () => {+ expect(+ command("html", "/tmp/my notebook.py", {+ html: { includeCode: false },+ }),+ ).toBe(+ "marimo export html '/tmp/my notebook.py' --no-include-code -o '/tmp/my notebook.html'",+ );+ });++ it("uses the selected Markdown flavor and its extension", () => {+ expect(+ command("markdown", "report.py", {+ markdown: { flavor: "mystmd" },+ }),+ ).toBe("marimo export md report.py --flavor=mystmd -o report.myst.md");+ });++ it.each([+ ["report.md", "report.export.md"],+ ["report.markdown", "report.md"],+ ["report.qmd", "report.export.qmd"],+ ["report.myst.md", "report.export.myst.md"],+ ["report.mdx", "report.export.mdx"],+ ])(+ "keeps the automatic Markdown output distinct from %s",+ (filename, output) => {+ expect(command("markdown", filename)).toBe(+ `marimo export md ${filename} -o ${output}`,+ );+ },+ );++ it("includes every configurable document PDF setting", () => {+ expect(+ command("pdf", "report.py", {+ pdf: {+ preset: "document",+ includeInputs: false,+ includeOutputs: false,+ webpdf: false,+ },+ }),+ ).toBe(+ "marimo export pdf report.py --as=document --no-include-inputs --no-include-outputs --no-webpdf -o report.pdf",+ );+ });++ it("includes IPYNB cell order and output selection", () => {+ expect(+ command("ipynb", "report.py", {+ ipynb: { sortMode: "top-down", includeOutputs: true },+ }),+ ).toBe(+ "marimo export ipynb report.py --sort=top-down --include-outputs -o report.ipynb",+ );+ });++ it("omits the fixed WebPDF engine flag for slide PDFs", () => {+ expect(+ command("pdf", "slides.py", {+ pdf: {+ preset: "slides",+ includeInputs: false,+ includeOutputs: false,+ webpdf: false,+ },+ }),+ ).toBe(+ "marimo export pdf slides.py --as=slides --no-include-inputs --no-include-outputs -o slides.pdf",+ );+ });++ it("uses the script export filename contract", () => {+ expect(+ command("script", "analysis.py", {+ script: { type: "flat" },+ }),+ ).toBe("marimo export script analysis.py -o analysis.script.py");+ });++ it.each([+ ["editable notebook source", "script", "analysis.py"],+ ["unnamed notebook", "html", null],+ ["PNG capture", "png", "analysis.py"],+ ] as const)("has no command for %s", (_case, format, filename) => {+ expect(command(format, filename)).toBeNull();+ });+});diff --git a/frontend/src/components/editor/actions/export-dialog/__tests__/export-dialog.test.tsx b/frontend/src/components/editor/actions/export-dialog/__tests__/export-dialog.test.tsxnew file mode 100644index 0000000000..dfea3cb05d--- /dev/null+++ b/frontend/src/components/editor/actions/export-dialog/__tests__/export-dialog.test.tsx@@ -0,0 +1,423 @@+/* Copyright 2026 Marimo. All rights reserved. */++import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { Provider } from "jotai";+import type React from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { MockRequestClient } from "@/__mocks__/requests";+import { Dialog } from "@/components/ui/dialog";+import { TooltipProvider } from "@/components/ui/tooltip";+import { viewStateAtom } from "@/core/mode";+import { requestClientAtom } from "@/core/network/requests";+import { filenameAtom } from "@/core/saving/file-state";+import { store } from "@/core/state/jotai";+import { isWasm } from "@/core/wasm/utils";+import * as copyModule from "@/utils/copy";+import { ExportDialog } from "../export-dialog";+import {+ DEFAULT_EXPORT_OPTIONS,+ type ExportFormat,+ exportOptionsAtom,+ lastExportFormatAtom,+} from "../state";++const { exportNotebookMock } = vi.hoisted(() => ({+ exportNotebookMock: vi.fn().mockResolvedValue(undefined),+}));++vi.mock("@/utils/copy", () => ({+ copyToClipboard: vi.fn().mockResolvedValue(undefined),+}));++vi.mock("@/core/wasm/utils", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@/core/wasm/utils")>();+ return { ...actual, isWasm: vi.fn(() => false) };+});++vi.mock("../export-notebook", () => ({+ exportNotebook: exportNotebookMock,+}));++function wrapper({ children }: { children: React.ReactNode }) {+ return (+ <Provider store={store}>+ <TooltipProvider>+ <Dialog open={true}>{children}</Dialog>+ </TooltipProvider>+ </Provider>+ );+}++function renderDialog(initialFormat?: ExportFormat, onClose = vi.fn()) {+ return render(+ <ExportDialog initialFormat={initialFormat} onClose={onClose} />,+ { wrapper },+ );+}++async function waitForExportEnabled() {+ await waitFor(() =>+ expect(screen.getByTestId("export-submit")).toBeEnabled(),+ );+}++describe("ExportDialog", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ localStorage.clear();+ store.set(requestClientAtom, MockRequestClient.create());+ store.set(filenameAtom, "/project/notebook.py");+ store.set(viewStateAtom, { mode: "edit", cellAnchor: null });+ store.set(exportOptionsAtom, DEFAULT_EXPORT_OPTIONS);+ store.set(lastExportFormatAtom, "html");+ vi.mocked(isWasm).mockReturnValue(false);+ vi.stubGlobal("matchMedia", () => ({+ matches: false,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ }));+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("locks format and option controls while exporting", async () => {+ let finishExport: (() => void) | undefined;+ exportNotebookMock.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finishExport = resolve;+ }),+ );+ const onClose = vi.fn();+ renderDialog("pdf", onClose);+ await waitForExportEnabled();++ fireEvent.click(screen.getByTestId("export-submit"));+ await waitFor(() => expect(exportNotebookMock).toHaveBeenCalledOnce());++ expect(screen.getByTestId("export-submit")).toHaveAttribute(+ "aria-busy",+ "true",+ );+ expect(screen.getByTestId("export-format-html")).toBeDisabled();+ expect(screen.getByRole("radio", { name: "Document" })).toBeDisabled();+ expect(screen.getByRole("switch", { name: "Include code" })).toBeDisabled();++ finishExport?.();+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());+ });++ it("describes the selected PDF options", async () => {+ renderDialog("pdf");+ await waitForExportEnabled();++ expect(+ screen.getByRole("radiogroup", { name: "Layout" }),+ ).toHaveAccessibleDescription("Creates pages for reading or printing.");+ expect(+ screen.getByRole("switch", { name: "Include code" }),+ ).toHaveAccessibleDescription("Includes code cells in the PDF.");+ const method = screen.getByRole("radiogroup", { name: "Method" });+ expect(method).toHaveAccessibleDescription(+ "Uses browser rendering to preserve the notebook's visual output.",+ );+ expect(screen.getByRole("radio", { name: "Browser" })).toBeChecked();++ fireEvent.click(screen.getByRole("radio", { name: "LaTeX first" }));+ expect(method).toHaveAccessibleDescription(+ "Uses Pandoc and TeX when available, then falls back to browser rendering.",+ );+ expect(screen.getByRole("radio", { name: "LaTeX first" })).toBeChecked();++ fireEvent.click(screen.getByRole("switch", { name: "Include code" }));+ expect(+ screen.getByRole("switch", { name: "Include code" }),+ ).toHaveAccessibleDescription("Leaves code cells out of the PDF.");++ fireEvent.click(screen.getByRole("radio", { name: "Slides" }));+ expect(+ screen.getByRole("radiogroup", { name: "Layout" }),+ ).toHaveAccessibleDescription(+ "Creates presentation slides from the notebook.",+ );+ });++ it("describes the selected Markdown format", () => {+ renderDialog("markdown");++ expect(+ screen.getByRole("combobox", { name: "Format" }),+ ).toHaveAccessibleDescription(+ "Chooses a format from the notebook filename. Defaults to Markdown (.md).",+ );++ act(() => {+ store.set(exportOptionsAtom, {+ ...store.get(exportOptionsAtom),+ markdown: { flavor: "qmd" },+ });+ });++ expect(+ screen.getByRole("combobox", { name: "Format" }),+ ).toHaveAccessibleDescription("Creates a .qmd file for Quarto.");+ });++ it("describes the selected Jupyter cell order", () => {+ renderDialog("ipynb");++ expect(+ screen.getByRole("radiogroup", { name: "Cell order" }),+ ).toHaveAccessibleDescription(+ "Reorders cells so each cell appears after the cells it depends on.",+ );++ fireEvent.click(screen.getByRole("radio", { name: "Top to bottom" }));++ expect(+ screen.getByRole("radiogroup", { name: "Cell order" }),+ ).toHaveAccessibleDescription(+ "Keeps cells in the same order as this notebook.",+ );+ });++ it("shows every format and updates the equivalent command with options", async () => {+ renderDialog();++ for (const format of [+ "html",+ "markdown",+ "ipynb",+ "pdf",+ "script",+ "png",+ ]) {+ expect(screen.getByTestId(`export-format-${format}`)).toBeVisible();+ }++ await waitForExportEnabled();+ expect(screen.getByTestId("export-cli-command")).toHaveTextContent(+ "marimo export html /project/notebook.py --include-code",+ );+ expect(+ screen.getByText(+ "Uses the current session state. The copied command exports the saved notebook.",+ ),+ ).toBeVisible();++ fireEvent.click(screen.getByRole("switch", { name: "Include code" }));+ expect(screen.getByTestId("export-cli-command")).toHaveTextContent(+ "--no-include-code",+ );+ });++ it("matches tab keyboard orientation to the responsive layout", () => {+ const listeners = new Set<() => void>();+ const media = {+ matches: false,+ addEventListener: vi.fn((_event: "change", listener: () => void) =>+ listeners.add(listener),+ ),+ removeEventListener: vi.fn((_event: "change", listener: () => void) =>+ listeners.delete(listener),+ ),+ };+ vi.stubGlobal(+ "matchMedia",+ vi.fn(() => media),+ );++ renderDialog();+ const tablist = screen.getByRole("tablist", { name: "Export format" });+ expect(tablist).toHaveAttribute("aria-orientation", "horizontal");++ act(() => {+ media.matches = true;+ for (const listener of listeners) {+ listener();+ }+ });+ expect(tablist).toHaveAttribute("aria-orientation", "vertical");+ });++ it("keeps unavailable formats visible and names missing packages", async () => {+ store.set(+ requestClientAtom,+ MockRequestClient.create({+ getExportAvailability: vi.fn().mockResolvedValue({+ source: "server",+ formats: [+ {+ format: "pdf",+ dependenciesAvailable: false,+ missingPackages: ["nbconvert[webpdf]"],+ },+ ],+ }),+ }),+ );++ renderDialog("pdf");++ expect(await screen.findByText("nbconvert[webpdf]")).toBeVisible();+ expect(+ screen.getByText(/where marimo is running to use this export/),+ ).toBeVisible();+ expect(screen.getByTestId("export-submit")).toBeDisabled();+ expect(screen.getByTestId("export-format-pdf")).toBeVisible();+ });++ it("announces requirement checks as status updates", () => {+ store.set(+ requestClientAtom,+ MockRequestClient.create({+ getExportAvailability: vi.fn(() => new Promise(() => undefined)),+ }),+ );++ renderDialog("pdf");++ expect(screen.getByRole("status")).toHaveTextContent(+ "Checking PDF requirements…",+ );+ });++ it("hides the document renderer when exporting slides", async () => {+ renderDialog("pdf");+ await waitForExportEnabled();++ fireEvent.click(screen.getByRole("radio", { name: "Slides" }));++ expect(+ screen.queryByRole("radiogroup", { name: "Method" }),+ ).not.toBeInTheDocument();+ });++ it("requires a saved file for notebook source but not flat script", () => {+ store.set(filenameAtom, null);++ renderDialog("script");++ expect(+ screen.getByText("Name and save this notebook before exporting."),+ ).toBeVisible();+ expect(screen.getByTestId("export-submit")).toBeDisabled();++ fireEvent.click(screen.getByRole("radio", { name: "Flat script" }));++ expect(+ screen.queryByText("Name and save this notebook before exporting."),+ ).not.toBeInTheDocument();+ expect(screen.getByTestId("export-submit")).toBeEnabled();+ });++ it("allows an export attempt when requirements cannot be checked", async () => {+ store.set(+ requestClientAtom,+ MockRequestClient.create({+ getExportAvailability: vi+ .fn()+ .mockRejectedValue(new Error("unavailable")),+ }),+ );++ renderDialog("pdf");++ expect(+ await screen.findByText(+ "Couldn't check whether this export is available. You can still try it.",+ ),+ ).toBeVisible();+ expect(screen.getByTestId("export-submit")).toBeEnabled();+ });++ it("shows browser printing for PDF export in WebAssembly", () => {+ vi.mocked(isWasm).mockReturnValue(true);++ renderDialog("pdf");++ expect(+ screen.getByText(+ "Use your browser's print dialog to save the current app view as a PDF.",+ ),+ ).toBeVisible();+ expect(screen.queryByRole("radio", { name: "Document" })).toBeNull();+ expect(screen.queryByTestId("export-cli-command")).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Print to PDF" })).toBeEnabled();+ });++ it("copies the displayed CLI command", async () => {+ store.set(exportOptionsAtom, {+ ...DEFAULT_EXPORT_OPTIONS,+ script: { type: "flat" },+ });+ renderDialog("script");+ await waitForExportEnabled();++ fireEvent.click(+ screen.getByRole("button", { name: "Copy POSIX shell command" }),+ );++ await waitFor(() =>+ expect(copyModule.copyToClipboard).toHaveBeenCalledWith(+ "marimo export script /project/notebook.py -o /project/notebook.script.py",+ ),+ );+ });++ it("describes and selects each Python format", () => {+ renderDialog("script");++ expect(+ screen.getByRole("radio", { name: "Notebook source" }),+ ).toBeChecked();+ expect(+ screen.getByRole("radiogroup", { name: "Format" }),+ ).toHaveAccessibleDescription(+ "Downloads the saved notebook source for continued editing in marimo.",+ );+ expect(+ screen.getByRole("button", { name: "Export notebook source" }),+ ).toBeVisible();+ expect(screen.queryByTestId("export-cli-command")).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole("radio", { name: "Flat script" }));++ expect(+ screen.getByRole("radiogroup", { name: "Format" }),+ ).toHaveAccessibleDescription(+ "Reorders cells so the Python script runs from top to bottom.",+ );+ expect(+ screen.getByRole("button", { name: "Export flat script" }),+ ).toBeVisible();+ expect(screen.getByTestId("export-cli-command")).toHaveTextContent(+ "marimo export script /project/notebook.py",+ );+ });++ it("hides the shell command until the notebook is saved", () => {+ store.set(filenameAtom, null);+ store.set(exportOptionsAtom, {+ ...DEFAULT_EXPORT_OPTIONS,+ script: { type: "flat" },+ });++ renderDialog("script");++ expect(screen.queryByTestId("export-cli-command")).not.toBeInTheDocument();+ expect(+ screen.getByText(+ "Save the notebook to copy an equivalent shell command.",+ ),+ ).toBeVisible();+ });+});diff --git a/frontend/src/components/editor/actions/export-dialog/__tests__/export-notebook.test.ts b/frontend/src/components/editor/actions/export-dialog/__tests__/export-notebook.test.tsnew file mode 100644index 0000000000..feaf81593e--- /dev/null+++ b/frontend/src/components/editor/actions/export-dialog/__tests__/export-notebook.test.ts@@ -0,0 +1,178 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { beforeEach, describe, expect, it, vi } from "vitest";+import type { ExportedFile } from "@/core/network/types";+import { exportNotebook } from "../export-notebook";+import { DEFAULT_EXPORT_OPTIONS, type ExportOptions } from "../state";++type Requests = Parameters<typeof exportNotebook>[0]["requests"];++const FILE: ExportedFile<string> = {+ contents: "exported",+ filename: "notebook.txt",+ mediaType: "text/plain",+};++function makeOptions(overrides: Partial<ExportOptions> = {}): ExportOptions {+ return {+ ...DEFAULT_EXPORT_OPTIONS,+ ...overrides,+ };+}++function makeRequests(): Requests {+ return {+ exportAsHTML: vi.fn().mockResolvedValue(FILE),+ exportAsMarkdown: vi.fn().mockResolvedValue(FILE),+ exportAsIPYNB: vi.fn().mockResolvedValue(FILE),+ exportAsPDF: vi.fn().mockResolvedValue({+ ...FILE,+ contents: new Blob(),+ filename: "notebook.pdf",+ mediaType: "application/pdf",+ }),+ exportAsScript: vi.fn().mockResolvedValue(FILE),+ readCode: vi.fn().mockResolvedValue({+ contents: "import marimo",+ }),+ };+}++describe("exportNotebook", () => {+ let requests: Requests;+ let captureOutputs: ReturnType<typeof vi.fn>;+ let capturePNG: ReturnType<typeof vi.fn>;+ let downloadFile: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ requests = makeRequests();+ captureOutputs = vi.fn().mockResolvedValue(undefined);+ capturePNG = vi.fn().mockResolvedValue(undefined);+ downloadFile = vi.fn();+ });++ const run = (+ format: Parameters<typeof exportNotebook>[0]["format"],+ options = makeOptions(),+ ) =>+ exportNotebook({+ format,+ options,+ requests,+ sourceFilename: "notebook.py",+ htmlFiles: ["data.csv"],+ captureOutputs,+ capturePNG,+ downloadFile,+ });++ it("passes HTML settings and virtual files through the session API", async () => {+ await run("html", makeOptions({ html: { includeCode: false } }));++ expect(requests.exportAsHTML).toHaveBeenCalledWith({+ download: false,+ files: ["data.csv"],+ includeCode: false,+ });+ expect(downloadFile).toHaveBeenCalledWith(FILE);+ });++ it("passes the selected Markdown flavor through the session API", async () => {+ await run("markdown", makeOptions({ markdown: { flavor: "qmd" } }));++ expect(requests.exportAsMarkdown).toHaveBeenCalledWith({+ download: false,+ flavor: "qmd",+ });+ expect(downloadFile).toHaveBeenCalledWith(FILE);+ });++ it("captures outputs before an IPYNB export when requested", async () => {+ const calls: string[] = [];+ captureOutputs.mockImplementation(async () => {+ calls.push("capture");+ });+ vi.mocked(requests.exportAsIPYNB).mockImplementation(async () => {+ calls.push("export");+ return FILE;+ });++ await run(+ "ipynb",+ makeOptions({+ ipynb: { sortMode: "top-down", includeOutputs: true },+ }),+ );++ expect(calls).toEqual(["capture", "export"]);+ expect(requests.exportAsIPYNB).toHaveBeenCalledWith({+ download: false,+ sortMode: "top-down",+ includeOutputs: true,+ });+ expect(downloadFile).toHaveBeenCalledWith(FILE);+ });++ it("skips browser capture when IPYNB outputs are excluded", async () => {+ await run("ipynb");++ expect(captureOutputs).not.toHaveBeenCalled();+ expect(requests.exportAsIPYNB).toHaveBeenCalledWith({+ download: false,+ sortMode: "topological",+ includeOutputs: false,+ });+ expect(downloadFile).toHaveBeenCalledWith(FILE);+ });++ it("captures current outputs before PDF export and sends every option", async () => {+ const pdf = makeOptions({+ pdf: {+ preset: "slides",+ includeInputs: false,+ includeOutputs: true,+ webpdf: false,+ },+ });++ await run("pdf", pdf);++ expect(captureOutputs).toHaveBeenCalledOnce();+ expect(requests.exportAsPDF).toHaveBeenCalledWith(pdf.pdf);+ expect(downloadFile).toHaveBeenCalledWith(+ expect.objectContaining({ filename: "notebook.pdf" }),+ );+ });++ it("downloads the editable notebook source", async () => {+ await run("script");++ expect(requests.readCode).toHaveBeenCalledOnce();+ expect(requests.exportAsScript).not.toHaveBeenCalled();+ expect(downloadFile).toHaveBeenCalledWith({+ contents: "import marimo",+ filename: "notebook.py",+ mediaType: "text/plain",+ });+ });++ it("downloads a flat script through the export API", async () => {+ await run(+ "script",+ makeOptions({+ script: { type: "flat" },+ }),+ );++ expect(requests.exportAsScript).toHaveBeenCalledWith({ download: false });+ expect(requests.readCode).not.toHaveBeenCalled();+ expect(downloadFile).toHaveBeenCalledWith(FILE);+ });++ it("uses client-side capture for PNG", async () => {+ await run("png");++ expect(capturePNG).toHaveBeenCalledOnce();+ expect(downloadFile).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/components/editor/actions/export-dialog/__tests__/state.test.ts b/frontend/src/components/editor/actions/export-dialog/__tests__/state.test.tsnew file mode 100644index 0000000000..42293cafbb--- /dev/null+++ b/frontend/src/components/editor/actions/export-dialog/__tests__/state.test.ts@@ -0,0 +1,234 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { describe, expect, it } from "vitest";+import type { ExportAvailabilityResponse } from "@/core/network/types";+import {+ applyExportOptionOverrides,+ DEFAULT_EXPORT_OPTIONS,+ type ExportFormat,+ type ExportOptions,+ getExportFormatStatus,+ isExportFormat,+ mergeExportOptions,+} from "../state";++const AVAILABLE: ExportAvailabilityResponse = {+ source: "server",+ formats: [+ {+ format: "ipynb",+ dependenciesAvailable: true,+ missingPackages: [],+ },+ {+ format: "pdf",+ dependenciesAvailable: true,+ missingPackages: [],+ },+ ],+};++const EXPECTED_DEFAULT_OPTIONS: ExportOptions = {+ html: { includeCode: true },+ markdown: { flavor: null },+ ipynb: { sortMode: "topological", includeOutputs: false },+ pdf: {+ preset: "document",+ includeInputs: true,+ includeOutputs: true,+ webpdf: true,+ },+ script: { type: "source" },+};++type StatusOptions = Parameters<typeof getExportFormatStatus>[0];++function status(+ format: ExportFormat,+ overrides: Partial<Omit<StatusOptions, "format">> = {},+) {+ return getExportFormatStatus({+ format,+ options: DEFAULT_EXPORT_OPTIONS,+ runtime: "server",+ filename: "notebook.py",+ availability: { status: "success", data: AVAILABLE },+ ...overrides,+ });+}++describe("export option state", () => {+ it("adds current defaults to a stored partial option shape", () => {+ expect(+ mergeExportOptions({+ html: { includeCode: false },+ pdf: { preset: "slides" },+ }),+ ).toEqual({+ ...EXPECTED_DEFAULT_OPTIONS,+ html: { includeCode: false },+ pdf: {+ ...EXPECTED_DEFAULT_OPTIONS.pdf,+ preset: "slides",+ },+ });+ });++ it("keeps valid stored fields and resets invalid fields", () => {+ expect(+ mergeExportOptions({+ html: { includeCode: "false" },+ markdown: { flavor: "unknown" },+ ipynb: { sortMode: "unknown", includeOutputs: true },+ pdf: {+ preset: "unknown",+ includeInputs: false,+ includeOutputs: "false",+ webpdf: false,+ },+ script: { type: "unknown" },+ }),+ ).toEqual({+ ...EXPECTED_DEFAULT_OPTIONS,+ ipynb: {+ ...EXPECTED_DEFAULT_OPTIONS.ipynb,+ includeOutputs: true,+ },+ pdf: {+ ...EXPECTED_DEFAULT_OPTIONS.pdf,+ includeInputs: false,+ webpdf: false,+ },+ });+ });++ it.each([null, { pdf: "invalid" }])(+ "resets malformed stored options",+ (stored) => {+ expect(mergeExportOptions(stored)).toEqual(EXPECTED_DEFAULT_OPTIONS);+ },+ );++ it("applies a shortcut preset without resetting sibling options", () => {+ const options = {+ ...DEFAULT_EXPORT_OPTIONS,+ pdf: {+ preset: "document" as const,+ includeInputs: false,+ includeOutputs: false,+ webpdf: false,+ },+ };++ expect(+ applyExportOptionOverrides(options, {+ pdf: { preset: "slides" },+ }).pdf,+ ).toEqual({+ ...options.pdf,+ preset: "slides",+ });+ expect(+ applyExportOptionOverrides(options, {+ script: { type: "flat" },+ }).script,+ ).toEqual({ type: "flat" });+ });++ it("accepts current formats and rejects unknown values", () => {+ expect(isExportFormat("markdown")).toBe(true);+ expect(isExportFormat("wasm")).toBe(false);+ expect(isExportFormat(null)).toBe(false);+ });+});++describe("getExportFormatStatus", () => {+ it("waits only for formats with server dependencies", () => {+ expect(status("ipynb", { availability: { status: "pending" } })).toEqual({+ available: false,+ reason: { type: "checking-requirements" },+ });+ expect(status("html", { availability: { status: "pending" } })).toEqual({+ available: true,+ });+ });++ it("requires a notebook name for file-backed server formats", () => {+ expect(status("markdown", { filename: null })).toEqual({+ available: false,+ reason: { type: "notebook-must-be-named" },+ });+ });++ it("requires a saved file for notebook source but not flat script", () => {+ expect(status("script", { filename: null })).toEqual({+ available: false,+ reason: { type: "notebook-must-be-named" },+ });+ expect(+ status("script", {+ filename: null,+ options: {+ ...DEFAULT_EXPORT_OPTIONS,+ script: { type: "flat" },+ },+ }),+ ).toEqual({ available: true });+ });++ it("reports missing server packages", () => {+ expect(+ status("pdf", {+ availability: {+ status: "success",+ data: {+ source: "server",+ formats: [+ {+ format: "pdf",+ dependenciesAvailable: false,+ missingPackages: ["nbconvert[webpdf]"],+ },+ ],+ },+ },+ }),+ ).toEqual({+ available: false,+ reason: {+ type: "missing-packages",+ packages: ["nbconvert[webpdf]"],+ },+ });+ });++ it.each([+ ["html", true, undefined],+ ["markdown", true, undefined],+ ["ipynb", false, "wasm-runtime"],+ ["pdf", true, "wasm-runtime"],+ ["script", true, undefined],+ ["png", true, undefined],+ ] as const)(+ "describes %s availability in WebAssembly",+ (format, available, reason) => {+ expect(+ status(format, {+ runtime: "wasm",+ filename: null,+ availability: { status: "success", data: null },+ }),+ ).toEqual({+ available,+ ...(reason ? { reason: { type: reason } } : {}),+ });+ },+ );++ it("allows an export attempt when the availability check fails", () => {+ expect(status("pdf", { availability: { status: "error" } })).toEqual({+ available: true,+ availabilityCheckFailed: true,+ });+ });+});diff --git a/frontend/src/components/editor/actions/export-dialog/__tests__/use-export-dialog.test.tsx b/frontend/src/components/editor/actions/export-dialog/__tests__/use-export-dialog.test.tsxnew file mode 100644index 0000000000..5375ac77c8--- /dev/null+++ b/frontend/src/components/editor/actions/export-dialog/__tests__/use-export-dialog.test.tsx@@ -0,0 +1,287 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { act, render, renderHook, waitFor } from "@testing-library/react";+import { Provider } from "jotai";+import type React from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { MockRequestClient } from "@/__mocks__/requests";+import { viewStateAtom } from "@/core/mode";+import { requestClientAtom } from "@/core/network/requests";+import { filenameAtom } from "@/core/saving/file-state";+import { store } from "@/core/state/jotai";+import { isWasm } from "@/core/wasm/utils";+import {+ DEFAULT_EXPORT_OPTIONS,+ type ExportFormat,+ exportOptionsAtom,+ lastExportFormatAtom,+} from "../state";+import { useExportDialog } from "../use-export-dialog";++const { downloadHTMLAsImageMock, exportNotebookMock, toastMock } = vi.hoisted(+ () => ({+ downloadHTMLAsImageMock: vi.fn().mockResolvedValue(true),+ exportNotebookMock: vi.fn().mockResolvedValue(undefined),+ toastMock: vi.fn(() => ({+ dismiss: vi.fn(),+ update: vi.fn(),+ })),+ }),+);++vi.mock("@/components/ui/use-toast", () => ({+ toast: toastMock,+}));++vi.mock("@/core/wasm/utils", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@/core/wasm/utils")>();+ return { ...actual, isWasm: vi.fn(() => false) };+});++vi.mock("@/utils/download", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@/utils/download")>();+ return { ...actual, downloadHTMLAsImage: downloadHTMLAsImageMock };+});++vi.mock("../export-notebook", () => ({+ exportNotebook: exportNotebookMock,+}));++function wrapper({ children }: { children: React.ReactNode }) {+ return <Provider store={store}>{children}</Provider>;+}++function renderController(initialFormat?: ExportFormat, onClose = vi.fn()) {+ return renderHook(() => useExportDialog({ initialFormat, onClose }), {+ wrapper,+ });+}++async function waitForAvailable(+ getController: () => ReturnType<typeof useExportDialog>,+) {+ await waitFor(() =>+ expect(getController().selected.status.available).toBe(true),+ );+}++describe("useExportDialog", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ localStorage.clear();+ store.set(requestClientAtom, MockRequestClient.create());+ store.set(filenameAtom, "/project/notebook.py");+ store.set(viewStateAtom, { mode: "edit", cellAnchor: null });+ store.set(exportOptionsAtom, DEFAULT_EXPORT_OPTIONS);+ store.set(lastExportFormatAtom, "html");+ vi.mocked(isWasm).mockReturnValue(false);+ document.title = "Notebook";+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ document.getElementById("App")?.remove();+ });++ it("keeps PNG export open when the app view is missing", async () => {+ exportNotebookMock.mockImplementationOnce(+ async ({ capturePNG }: { capturePNG: () => Promise<void> }) =>+ capturePNG(),+ );+ const onClose = vi.fn();+ const { result } = renderController("png", onClose);+ await waitForAvailable(() => result.current);++ await act(async () => {+ await result.current.submit();+ });++ expect(toastMock).toHaveBeenCalledWith({+ title: "Failed to download as PNG",+ description: "The current app view could not be captured.",+ variant: "danger",+ });+ expect(result.current.isExporting).toBe(false);+ expect(store.get(viewStateAtom).mode).toBe("edit");+ expect(onClose).not.toHaveBeenCalled();+ });++ it("captures the app view and restores the dialog", async () => {+ const app = document.createElement("div");+ app.id = "App";+ document.body.append(app);+ const { container: dialogContainer } = render(<div />);+ const dialog = dialogContainer.firstElementChild as HTMLDivElement;+ exportNotebookMock.mockImplementationOnce(+ async ({ capturePNG }: { capturePNG: () => Promise<void> }) =>+ capturePNG(),+ );+ downloadHTMLAsImageMock.mockImplementationOnce(+ async ({ prepare }: Parameters<typeof downloadHTMLAsImageMock>[0]) => {+ const cleanup = prepare?.(app);+ expect(dialogContainer).not.toBeVisible();+ cleanup?.();+ return true;+ },+ );+ const onClose = vi.fn();+ const { result } = renderController("png", onClose);+ await waitForAvailable(() => result.current);+ act(() => {+ result.current.dialogRef.current = dialog;+ });++ await act(async () => {+ await result.current.submit();+ });++ expect(onClose).toHaveBeenCalledOnce();+ expect(store.get(viewStateAtom).mode).toBe("edit");+ expect(dialogContainer).toBeVisible();+ });++ it("restores the dialog and edit mode when PNG capture fails", async () => {+ const app = document.createElement("div");+ app.id = "App";+ document.body.append(app);+ const { container: dialogContainer } = render(<div />);+ const dialog = dialogContainer.firstElementChild as HTMLDivElement;+ exportNotebookMock.mockImplementationOnce(+ async ({ capturePNG }: { capturePNG: () => Promise<void> }) =>+ capturePNG(),+ );+ downloadHTMLAsImageMock.mockImplementationOnce(+ async ({ prepare }: Parameters<typeof downloadHTMLAsImageMock>[0]) => {+ const cleanup = prepare?.(app);+ cleanup?.();+ return false;+ },+ );+ const onClose = vi.fn();+ const { result } = renderController("png", onClose);+ await waitForAvailable(() => result.current);+ act(() => {+ result.current.dialogRef.current = dialog;+ });++ await act(async () => {+ await result.current.submit();+ });++ expect(result.current.isExporting).toBe(false);+ expect(store.get(viewStateAtom).mode).toBe("edit");+ expect(dialogContainer).toBeVisible();+ expect(onClose).not.toHaveBeenCalled();+ });++ it("does not close a newer modal after unmounting", async () => {+ let finishExport: (() => void) | undefined;+ exportNotebookMock.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finishExport = resolve;+ }),+ );+ const onClose = vi.fn();+ const { result, unmount } = renderController(undefined, onClose);+ await waitForAvailable(() => result.current);++ let submit: Promise<void> | undefined;+ act(() => {+ submit = result.current.submit();+ });+ await waitFor(() => expect(exportNotebookMock).toHaveBeenCalledOnce());++ unmount();+ finishExport?.();+ await submit;++ expect(onClose).not.toHaveBeenCalled();+ });++ it("keeps the dialog open when a server export fails", async () => {+ exportNotebookMock.mockRejectedValueOnce(new Error("export failed"));+ const onClose = vi.fn();+ const { result } = renderController(undefined, onClose);+ await waitForAvailable(() => result.current);++ await act(async () => {+ await result.current.submit();+ });++ expect(result.current.isExporting).toBe(false);+ expect(onClose).not.toHaveBeenCalled();+ });++ it("preserves the saved notebook filename for source export", async () => {+ store.set(filenameAtom, "/project/report.qmd");+ document.title = "Custom app title";+ const { result } = renderController("script");+ await waitForAvailable(() => result.current);++ await act(async () => {+ await result.current.submit();+ });++ expect(exportNotebookMock).toHaveBeenCalledWith(+ expect.objectContaining({ sourceFilename: "report.qmd" }),+ );+ });++ it("uses the page title for WebAssembly source export", async () => {+ vi.mocked(isWasm).mockReturnValue(true);+ store.set(filenameAtom, "notebook.py");+ document.title = "Shared analysis";+ const { result } = renderController("script");+ await waitForAvailable(() => result.current);++ await act(async () => {+ await result.current.submit();+ });++ expect(exportNotebookMock).toHaveBeenCalledWith(+ expect.objectContaining({ sourceFilename: "Shared analysis.py" }),+ );+ });++ it("keeps equivalent CLI commands for WebAssembly exports", () => {+ vi.mocked(isWasm).mockReturnValue(true);+ const { result } = renderController("html");++ expect(result.current.selected.command).toBe(+ "marimo export html /project/notebook.py --include-code -o /project/notebook.html",+ );+ });++ it("persists the selected format and its options", () => {+ const first = renderController();++ act(() => {+ first.result.current.selectFormat("pdf");+ first.result.current.updateOptions("pdf", { preset: "slides" });+ });+ first.unmount();++ const second = renderController();+ expect(second.result.current.selected.format).toBe("pdf");+ expect(second.result.current.options.pdf.preset).toBe("slides");+ });++ it("prints the current view for PDF export in WebAssembly", async () => {+ vi.mocked(isWasm).mockReturnValue(true);+ const print = vi.fn();+ vi.stubGlobal("print", print);+ const onClose = vi.fn();+ const { result } = renderController("pdf", onClose);++ expect(result.current.selected.usesBrowserPrint).toBe(true);++ await act(async () => {+ await result.current.submit();+ });++ expect(onClose).toHaveBeenCalledOnce();+ await waitFor(() => expect(print).toHaveBeenCalledOnce());+ expect(exportNotebookMock).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/components/editor/actions/export-dialog/export-command.ts b/frontend/src/components/editor/actions/export-dialog/export-command.tsnew file mode 100644index 0000000000..94ca0def80--- /dev/null+++ b/frontend/src/components/editor/actions/export-dialog/export-command.ts@@ -0,0 +1,149 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { Filenames } from "@/utils/filenames";+import { shellQuote } from "@/utils/shell";+import type { ExportFormat, ExportOptions, MarkdownFlavor } from "./state";++const MARKDOWN_EXTENSIONS: Record<MarkdownFlavor, string> = {+ pymdown: "md",+ qmd: "qmd",+ mystmd: "myst.md",+ mdx: "mdx",+};++const MARKDOWN_SUFFIXES = [".myst.md", ".markdown", ".qmd", ".mdx", ".md"];++function inferMarkdownFlavor(filename: string): MarkdownFlavor {+ if (filename.endsWith(".myst.md")) {+ return "mystmd";+ }+ if (filename.endsWith(".qmd")) {+ return "qmd";+ }+ if (filename.endsWith(".mdx")) {+ return "mdx";+ }+ return "pymdown";+}++function markdownOutputFilename(+ filename: string,+ selectedFlavor: MarkdownFlavor | null,+): string {+ const flavor = selectedFlavor ?? inferMarkdownFlavor(filename);+ const extension = MARKDOWN_EXTENSIONS[flavor];+ const suffix = MARKDOWN_SUFFIXES.find((candidate) =>+ filename.endsWith(candidate),+ );+ let stem = Filenames.withoutExtension(filename);+ if (suffix) {+ stem = filename.slice(0, -suffix.length);+ }+ const output = `${stem}.${extension}`;+ if (output !== filename) {+ return output;+ }+ return `${filename.slice(0, -(extension.length + 1))}.export.${extension}`;+}++type FlagValue = boolean | string | null;++function translateFlags(values: Record<string, FlagValue>): string[] {+ return Object.entries(values).flatMap(([name, value]) => {+ if (value === null) {+ return [];+ }+ if (value === true) {+ return [`--${name}`];+ }+ if (value === false) {+ return [`--no-${name}`];+ }+ return [`--${name}=${value}`];+ });+}++function webPDFFlagValue(pdf: ExportOptions["pdf"]): boolean | null {+ if (pdf.preset === "document") {+ return pdf.webpdf;+ }+ return null;+}++type CommandFormat = Exclude<ExportFormat, "png">;++interface ExportCommandDefinition {+ subcommand: string;+ flags: (options: ExportOptions) => Record<string, FlagValue>;+ outputFilename: (source: string, options: ExportOptions) => string;+}++const EXPORT_COMMAND_DEFINITIONS: Record<+ CommandFormat,+ ExportCommandDefinition+> = {+ html: {+ subcommand: "html",+ flags: ({ html }) => ({ "include-code": html.includeCode }),+ outputFilename: (source) => Filenames.toHTML(source),+ },+ markdown: {+ subcommand: "md",+ flags: ({ markdown }) => ({ flavor: markdown.flavor }),+ outputFilename: (source, { markdown }) =>+ markdownOutputFilename(source, markdown.flavor),+ },+ ipynb: {+ subcommand: "ipynb",+ flags: ({ ipynb }) => ({+ sort: ipynb.sortMode,+ "include-outputs": ipynb.includeOutputs,+ }),+ outputFilename: (source) => Filenames.toIPYNB(source),+ },+ pdf: {+ subcommand: "pdf",+ flags: ({ pdf }) => ({+ as: pdf.preset,+ "include-inputs": pdf.includeInputs,+ "include-outputs": pdf.includeOutputs,+ webpdf: webPDFFlagValue(pdf),+ }),+ outputFilename: (source) => Filenames.toPDF(source),+ },+ script: {+ subcommand: "script",+ flags: () => ({}),+ outputFilename: (source) =>+ `${Filenames.withoutExtension(source)}.script.py`,+ },+};++export function getExportCommand({+ format,+ filename,+ options,+}: {+ format: ExportFormat;+ filename: string | null;+ options: ExportOptions;+}): string | null {+ if (+ format === "png" ||+ (format === "script" && options.script.type === "source") ||+ !filename+ ) {+ return null;+ }++ const definition = EXPORT_COMMAND_DEFINITIONS[format];+ return [+ "marimo",+ "export",+ definition.subcommand,+ shellQuote(filename),+ ...translateFlags(definition.flags(options)),+ "-o",+ shellQuote(definition.outputFilename(filename, options)),+ ].join(" ");+}diff --git a/frontend/src/components/editor/actions/export-dialog/export-dialog.tsx b/frontend/src/components/editor/actions/export-dialog/export-dialog.tsxnew file mode 100644index 0000000000..ababd1f89b--- /dev/null+++ b/frontend/src/components/editor/actions/export-dialog/export-dialog.tsx@@ -0,0 +1,190 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { useMediaQuery } from "@uidotdev/usehooks";+import type React from "react";+import { CopyClipboardIcon } from "@/components/icons/copy-icon";+import { Spinner } from "@/components/icons/spinner";+import { Button, buttonVariants } from "@/components/ui/button";+import {+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";+import { cn } from "@/utils/cn";+import { FORMAT_DEFINITIONS } from "./format-options";+import { FormatNotice, FormatStatusIcon } from "./format-notice";+import type { ExportFormat } from "./state";+import { useExportDialog } from "./use-export-dialog";++const DESKTOP_LAYOUT_QUERY = "(min-width: 640px)";++export const ExportDialog: React.FC<{+ initialFormat?: ExportFormat;+ onClose: () => void;+ returnFocusRef?: React.RefObject<HTMLElement | null>;+}> = ({ initialFormat, onClose, returnFocusRef }) => {+ const {+ dialogRef,+ isExporting,+ formats,+ options,+ selected,+ selectFormat,+ updateOptions,+ submit,+ } = useExportDialog({ initialFormat, onClose });+ const desktopLayout = useMediaQuery(DESKTOP_LAYOUT_QUERY);+ const {+ format,+ status,+ usesBrowserPrint,+ actionLabel,+ command,+ footerDescription,+ } = selected;+ const definition = FORMAT_DEFINITIONS[format];+ const FormatOptions = definition.Options;++ const returnFocusProps = returnFocusRef+ ? {+ onCloseAutoFocus: (event: Event) => {+ event.preventDefault();+ returnFocusRef.current?.focus();+ },+ }+ : {};++ return (+ <DialogContent+ ref={dialogRef}+ className="grid h-dvh max-h-[760px] min-w-0 w-[calc(100vw-2rem)] grid-rows-[auto_minmax(0,1fr)_auto] gap-0 overflow-hidden p-0 sm:top-[5vh] sm:h-[90vh] sm:max-h-[640px] sm:max-w-3xl"+ data-testid="export-dialog"+ {...returnFocusProps}+ >+ <DialogHeader className="border-b px-5 py-4 pr-12">+ <DialogTitle>Export notebook</DialogTitle>+ <DialogDescription>+ Choose a format and adjust its options.+ </DialogDescription>+ </DialogHeader>++ <Tabs+ value={format}+ onValueChange={selectFormat}+ orientation={desktopLayout ? "vertical" : "horizontal"}+ className="flex min-h-0 min-w-0 flex-col overflow-hidden sm:grid sm:grid-cols-[168px_minmax(0,1fr)]"+ >+ <TabsList+ aria-label="Export format"+ className="grid max-h-none shrink-0 grid-cols-2 items-stretch justify-start gap-1 overflow-auto rounded-none border-b bg-muted/20 p-2 min-[360px]:grid-cols-3 sm:flex sm:h-full sm:flex-col sm:border-b-0 sm:border-r"+ >+ {formats.map(({ format: candidate, status: candidateStatus }) => {+ const candidateDefinition = FORMAT_DEFINITIONS[candidate];+ return (+ <TabsTrigger+ key={candidate}+ value={candidate}+ disabled={isExporting}+ className="min-w-0 justify-start gap-2 px-2.5 py-2 text-xs data-[state=active]:shadow-xs sm:w-full sm:text-sm"+ data-testid={`export-format-${candidate}`}+ >+ <candidateDefinition.Icon+ className="size-3.5 shrink-0"+ strokeWidth={1.5}+ />+ <span className="truncate">{candidateDefinition.label}</span>+ <FormatStatusIcon status={candidateStatus} />+ </TabsTrigger>+ );+ })}+ </TabsList>++ <TabsContent+ value={format}+ className="mt-0 min-h-0 min-w-0 overflow-y-auto px-4 py-3"+ >+ <div className="mb-3">+ <h3 className="text-base font-semibold">{definition.label}</h3>+ <p className="mt-0.5 text-sm text-muted-foreground">+ {definition.description}+ </p>+ </div>++ <FormatNotice+ format={format}+ formatLabel={definition.label}+ status={status}+ />++ {usesBrowserPrint ? null : (+ <FormatOptions+ options={options}+ updateOptions={updateOptions}+ disabled={isExporting}+ />+ )}+ </TabsContent>+ </Tabs>++ <footer className="min-w-0 border-t bg-muted/20 px-4 py-3">+ {command ? (+ <div className="flex min-w-0 items-center gap-2 rounded-md border bg-background px-2.5 py-2 font-mono text-xs">+ <span+ className="select-none text-muted-foreground"+ aria-hidden={true}+ >+ $+ </span>+ <code+ className="min-w-0 flex-1 overflow-x-auto whitespace-nowrap"+ data-testid="export-cli-command"+ aria-label="Equivalent POSIX shell command"+ >+ {command}+ </code>+ <CopyClipboardIcon+ value={command}+ className="size-3.5"+ buttonClassName={cn(+ buttonVariants({ variant: "ghost", size: "icon" }),+ "shrink-0",+ )}+ tooltip="Copy POSIX shell command"+ ariaLabel="Copy POSIX shell command"+ toastTitle="Command copied"+ />+ </div>+ ) : null}++ <div+ className={cn(+ "flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",+ command && "mt-3",+ )}+ >+ {footerDescription ? (+ <p className="text-xs text-muted-foreground">{footerDescription}</p>+ ) : null}+ <Button+ type="button"+ disabled={!status.available || isExporting}+ aria-busy={isExporting}+ onClick={submit}+ className={cn(+ "border-(--blue-11) bg-(--blue-11) hover:border-(--blue-12) hover:bg-(--blue-12) sm:min-w-36 dark:border-(--blue-7) dark:bg-(--blue-5) dark:text-(--blue-12) dark:hover:border-(--blue-8) dark:hover:bg-(--blue-6)",+ !footerDescription && "sm:ml-auto",+ )}+ data-testid="export-submit"+ >+ {isExporting && (+ <Spinner size="small" className="mr-2" aria-hidden={true} />+ )}+ {usesBrowserPrint ? "Print to PDF" : actionLabel}+ </Button>+ </div>+ </footer>+ </DialogContent>+ );+};diff --git a/frontend/src/components/editor/actions/export-dialog/export-notebook.ts b/frontend/src/components/editor/actions/export-dialog/export-notebook.tsnew file mode 100644index 0000000000..08c2a701db--- /dev/null+++ b/frontend/src/components/editor/actions/export-dialog/export-notebook.ts@@ -0,0 +1,98 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type { EditRequests, ExportedFile } from "@/core/network/types";+import { assertNever } from "@/utils/assertNever";+import { runServerSidePDFDownload } from "../pdf-export";+import type { ExportFormat, ExportOptions } from "./state";++type ExportRequests = Pick<+ EditRequests,+ | "exportAsHTML"+ | "exportAsMarkdown"+ | "exportAsIPYNB"+ | "exportAsPDF"+ | "exportAsScript"+ | "readCode"+>;++export async function exportNotebook({+ format,+ options,+ requests,+ sourceFilename,+ htmlFiles,+ captureOutputs,+ capturePNG,+ downloadFile,+}: {+ format: ExportFormat;+ options: ExportOptions;+ requests: ExportRequests;+ sourceFilename: string;+ htmlFiles: string[];+ captureOutputs: () => Promise<void>;+ capturePNG: () => Promise<void>;+ downloadFile: (file: ExportedFile) => void;+}): Promise<void> {+ switch (format) {+ case "html": {+ const file = await requests.exportAsHTML({+ download: false,+ files: htmlFiles,+ includeCode: options.html.includeCode,+ });+ downloadFile(file);+ return;+ }+ case "markdown": {+ const file = await requests.exportAsMarkdown({+ download: false,+ flavor: options.markdown.flavor,+ });+ downloadFile(file);+ return;+ }+ case "ipynb": {+ if (options.ipynb.includeOutputs) {+ await captureOutputs();+ }+ const file = await requests.exportAsIPYNB({+ download: false,+ sortMode: options.ipynb.sortMode,+ includeOutputs: options.ipynb.includeOutputs,+ });+ downloadFile(file);+ return;+ }+ case "pdf":+ await runServerSidePDFDownload({+ exportOptions: options.pdf,+ captureOutputs,+ downloadPDF: async (exportOptions) => {+ const file = await requests.exportAsPDF(exportOptions);+ downloadFile(file);+ },+ });+ return;++ case "script": {+ if (options.script.type === "source") {+ const source = await requests.readCode();+ downloadFile({+ contents: source.contents,+ filename: sourceFilename,+ mediaType: "text/plain",+ });+ return;+ }+ const file = await requests.exportAsScript({ download: false });+ downloadFile(file);+ return;+ }+ case "png":+ await capturePNG();+ return;+ default:+ assertNever(format);+ }+}diff --git a/frontend/src/components/editor/actions/export-dialog/format-notice.tsx b/frontend/src/components/editor/actions/export-dialog/format-notice.tsxnew file mode 100644index 0000000000..668ffbe34b--- /dev/null+++ b/frontend/src/components/editor/actions/export-dialog/format-notice.tsx@@ -0,0 +1,138 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { AlertCircleIcon } from "lucide-react";+import type { PropsWithChildren } from "react";+import { Spinner } from "@/components/icons/spinner";+import { Alert, AlertDescription } from "@/components/ui/alert";+import { assertNever } from "@/utils/assertNever";+import { cn } from "@/utils/cn";+import type {+ ExportBlockReason,+ ExportFormat,+ ExportFormatStatus,+} from "./state";++export function FormatStatusIcon({ status }: { status: ExportFormatStatus }) {+ if (status.available && !status.availabilityCheckFailed) {+ return null;+ }+ if (status.reason?.type === "checking-requirements") {+ return (+ <span className="ml-auto flex shrink-0">+ <Spinner size="small" className="size-3" />+ <span className="sr-only">Checking requirements</span>+ </span>+ );+ }+ const statusLabel = status.availabilityCheckFailed+ ? "Requirements unknown"+ : "Unavailable";+ return (+ <span className="ml-auto flex shrink-0">+ <AlertCircleIcon+ className={cn(+ "size-3",+ status.availabilityCheckFailed+ ? "text-muted-foreground"+ : "text-(--yellow-11)",+ )}+ />+ <span className="sr-only">{statusLabel}</span>+ </span>+ );+}++export function FormatNotice({+ format,+ formatLabel,+ status,+}: {+ format: ExportFormat;+ formatLabel: string;+ status: ExportFormatStatus;+}) {+ if (status.availabilityCheckFailed) {+ return (+ <div className="mb-2.5">+ <Notice>+ Couldn't check whether this export is available. You can still try it.+ </Notice>+ </div>+ );+ }+ if (!status.reason) {+ return null;+ }++ return (+ <div className="mb-2.5">+ <ReasonNotice+ format={format}+ formatLabel={formatLabel}+ reason={status.reason}+ />+ </div>+ );+}++function Notice({ children }: PropsWithChildren) {+ return (+ <Alert+ variant="warning"+ className="flex items-start gap-2.5 p-3 text-(--yellow-12) has-[svg]:pl-3 sm:items-center [&>svg]:static [&>svg+div]:translate-y-0"+ >+ <AlertCircleIcon className="mt-0.5 size-4 shrink-0 sm:mt-0" />+ <AlertDescription className="min-w-0 flex-1 text-sm leading-5">+ {children}+ </AlertDescription>+ </Alert>+ );+}++function ReasonNotice({+ format,+ formatLabel,+ reason,+}: {+ format: ExportFormat;+ formatLabel: string;+ reason: ExportBlockReason;+}) {+ switch (reason.type) {+ case "checking-requirements":+ return (+ <Alert+ role="status"+ variant="info"+ className="flex items-center gap-2.5 p-3 has-[svg]:pl-3 [&>svg]:static [&>svg+div]:translate-y-0"+ >+ <Spinner className="size-4 shrink-0" size="small" />+ <AlertDescription className="min-w-0 flex-1 text-sm leading-5">+ Checking {formatLabel} requirements…+ </AlertDescription>+ </Alert>+ );+ case "notebook-must-be-named":+ return <Notice>Name and save this notebook before exporting.</Notice>;+ case "missing-packages":+ return (+ <Notice>+ Install{" "}+ <code className="break-words font-mono">+ {reason.packages.join(", ")}+ </code>{" "}+ where marimo is running to use this export.+ </Notice>+ );+ case "wasm-runtime":+ return (+ <Notice>+ {format === "pdf"+ ? "Use your browser's print dialog to save the current app view as a PDF."+ : "Open this notebook in a local marimo session to use this export."}+ </Notice>+ );+ default:+ assertNever(reason);+ }+}diff --git a/frontend/src/components/editor/actions/export-dialog/format-options.tsx b/frontend/src/components/editor/actions/export-dialog/format-options.tsxnew file mode 100644index 0000000000..93bead5422--- /dev/null+++ b/frontend/src/components/editor/actions/export-dialog/format-options.tsx@@ -0,0 +1,531 @@+/* Copyright 2026 Marimo. All rights reserved. */++import {+ CodeIcon,+ FileIcon,+ FileTextIcon,+ GlobeIcon,+ ImageIcon,+ type LucideIcon,+ NotebookIcon,+} from "lucide-react";+import { type ComponentType, type PropsWithChildren, useId } from "react";+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Switch } from "@/components/ui/switch";+import {+ IPYNB_SORT_MODES,+ MARKDOWN_FLAVORS,+ PDF_PRESETS,+ SCRIPT_TYPES,+ type ExportFormat,+ type ExportOptions,+ type MarkdownFlavor,+} from "./state";++export interface FormatOptionsProps {+ options: ExportOptions;+ updateOptions: UpdateExportOptions;+ disabled: boolean;+}++export type UpdateExportOptions = <Format extends keyof ExportOptions>(+ format: Format,+ options: Partial<ExportOptions[Format]>,+) => void;++interface Choice<Value extends string> {+ value: Value;+ label: string;+ description: string;+}++type ChoiceDetails = Omit<Choice<string>, "value">;++function defineChoices<Value extends string>(+ values: readonly Value[],+ details: Record<Value, ChoiceDetails>,+): readonly Choice<Value>[] {+ return values.map((value) => ({ value, ...details[value] }));+}++type MarkdownFormat = MarkdownFlavor | "automatic";+const MARKDOWN_FORMATS: readonly MarkdownFormat[] = [+ "automatic",+ ...MARKDOWN_FLAVORS,+];+const MARKDOWN_FLAVOR_OPTIONS = defineChoices(MARKDOWN_FORMATS, {+ automatic: {+ label: "Automatic",+ description:+ "Chooses a format from the notebook filename. Defaults to Markdown (.md).",+ },+ pymdown: {+ label: "Markdown (.md)",+ description: "Creates a .md file with Python code blocks.",+ },+ qmd: {+ label: "Quarto (.qmd)",+ description: "Creates a .qmd file for Quarto.",+ },+ mystmd: {+ label: "MyST (.myst.md)",+ description: "Creates a .myst.md file for MyST.",+ },+ mdx: {+ label: "MDX (.mdx)",+ description: "Creates a .mdx file for MDX.",+ },+});++const IPYNB_SORT_OPTIONS = defineChoices(IPYNB_SORT_MODES, {+ "top-down": {+ label: "Top to bottom",+ description: "Keeps cells in the same order as this notebook.",+ },+ topological: {+ label: "Dependency order",+ description:+ "Reorders cells so each cell appears after the cells it depends on.",+ },+});++const PDF_PRESET_OPTIONS = defineChoices(PDF_PRESETS, {+ document: {+ label: "Document",+ description: "Creates pages for reading or printing.",+ },+ slides: {+ label: "Slides",+ description: "Creates presentation slides from the notebook.",+ },+});++const PDF_RENDERERS = ["browser", "latex"] as const;+const PDF_RENDERER_OPTIONS = defineChoices(PDF_RENDERERS, {+ browser: {+ label: "Browser",+ description:+ "Uses browser rendering to preserve the notebook's visual output.",+ },+ latex: {+ label: "LaTeX first",+ description:+ "Uses Pandoc and TeX when available, then falls back to browser rendering.",+ },+});++const SCRIPT_TYPE_OPTIONS = defineChoices(SCRIPT_TYPES, {+ source: {+ label: "Notebook source",+ description:+ "Downloads the saved notebook source for continued editing in marimo.",+ },+ flat: {+ label: "Flat script",+ description: "Reorders cells so the Python script runs from top to bottom.",+ },+});++interface FormatDefinition {+ label: string;+ actionLabel: string;+ description: string;+ Icon: LucideIcon;+ Options: ComponentType<FormatOptionsProps>;+}++export const FORMAT_DEFINITIONS: Record<ExportFormat, FormatDefinition> = {+ html: {+ label: "HTML",+ actionLabel: "Export HTML",+ description: "Save the current notebook as an HTML page.",+ Icon: GlobeIcon,+ Options: HTMLFormatOptions,+ },+ markdown: {+ label: "Markdown",+ actionLabel: "Export Markdown",+ description:+ "Save code and text in a Markdown-based file. Cell outputs are not included.",+ Icon: FileTextIcon,+ Options: MarkdownFormatOptions,+ },+ ipynb: {+ label: "Jupyter",+ actionLabel: "Export Jupyter notebook",+ description: "Open the notebook in Jupyter and other compatible tools.",+ Icon: NotebookIcon,+ Options: IPYNBFormatOptions,+ },+ pdf: {+ label: "PDF",+ actionLabel: "Export PDF",+ description: "Save the notebook as a PDF for printing or sharing.",+ Icon: FileIcon,+ Options: PDFFormatOptions,+ },+ script: {+ label: "Python",+ actionLabel: "Export flat script",+ description: "Save the notebook as a Python file.",+ Icon: CodeIcon,+ Options: ScriptFormatOptions,+ },+ png: {+ label: "PNG",+ actionLabel: "Export PNG",+ description: "Capture the current app view as an image.",+ Icon: ImageIcon,+ Options: NoFormatOptions,+ },+};++function HTMLFormatOptions({+ options,+ updateOptions,+ disabled,+}: FormatOptionsProps) {+ return (+ <OptionsGroup>+ <SwitchOption+ label="Include code"+ descriptions={{+ checked: "Includes code cells in the webpage.",+ unchecked: "Leaves code cells out of the webpage.",+ }}+ checked={options.html.includeCode}+ disabled={disabled}+ onCheckedChange={(includeCode) =>+ updateOptions("html", { includeCode })+ }+ />+ </OptionsGroup>+ );+}++function MarkdownFormatOptions({+ options,+ updateOptions,+ disabled,+}: FormatOptionsProps) {+ return (+ <OptionsGroup>+ <SelectOption+ label="Format"+ value={options.markdown.flavor ?? "automatic"}+ disabled={disabled}+ onValueChange={(value) =>+ updateOptions("markdown", {+ flavor: value === "automatic" ? null : value,+ })+ }+ options={MARKDOWN_FLAVOR_OPTIONS}+ />+ </OptionsGroup>+ );+}++function IPYNBFormatOptions({+ options,+ updateOptions,+ disabled,+}: FormatOptionsProps) {+ return (+ <OptionsGroup>+ <RadioOption+ label="Cell order"+ value={options.ipynb.sortMode}+ disabled={disabled}+ onValueChange={(sortMode) => updateOptions("ipynb", { sortMode })}+ options={IPYNB_SORT_OPTIONS}+ />+ <SwitchOption+ label="Include outputs"+ descriptions={{+ checked: "Keeps the outputs currently shown in the notebook.",+ unchecked: "Leaves cell outputs out of the Jupyter notebook.",+ }}+ checked={options.ipynb.includeOutputs}+ disabled={disabled}+ onCheckedChange={(includeOutputs) =>+ updateOptions("ipynb", { includeOutputs })+ }+ />+ </OptionsGroup>+ );+}++function PDFFormatOptions({+ options,+ updateOptions,+ disabled,+}: FormatOptionsProps) {+ return (+ <OptionsGroup>+ <RadioOption+ label="Layout"+ value={options.pdf.preset}+ disabled={disabled}+ onValueChange={(preset) => updateOptions("pdf", { preset })}+ options={PDF_PRESET_OPTIONS}+ />+ <SwitchOption+ label="Include code"+ descriptions={{+ checked: "Includes code cells in the PDF.",+ unchecked: "Leaves code cells out of the PDF.",+ }}+ checked={options.pdf.includeInputs}+ disabled={disabled}+ onCheckedChange={(includeInputs) =>+ updateOptions("pdf", { includeInputs })+ }+ />+ <SwitchOption+ label="Include outputs"+ descriptions={{+ checked: "Keeps the outputs currently shown in the notebook.",+ unchecked: "Leaves cell outputs out of the PDF.",+ }}+ checked={options.pdf.includeOutputs}+ disabled={disabled}+ onCheckedChange={(includeOutputs) =>+ updateOptions("pdf", { includeOutputs })+ }+ />+ {options.pdf.preset === "document" ? (+ <RadioOption+ label="Method"+ value={options.pdf.webpdf ? "browser" : "latex"}+ disabled={disabled}+ onValueChange={(renderer) =>+ updateOptions("pdf", { webpdf: renderer === "browser" })+ }+ options={PDF_RENDERER_OPTIONS}+ />+ ) : null}+ </OptionsGroup>+ );+}++function ScriptFormatOptions({+ options,+ updateOptions,+ disabled,+}: FormatOptionsProps) {+ return (+ <OptionsGroup>+ <RadioOption+ label="Format"+ value={options.script.type}+ disabled={disabled}+ onValueChange={(type) => updateOptions("script", { type })}+ options={SCRIPT_TYPE_OPTIONS}+ />+ </OptionsGroup>+ );+}++function NoFormatOptions() {+ return null;+}++function OptionsGroup({ children }: PropsWithChildren) {+ return <div className="divide-y rounded-md border">{children}</div>;+}++function SwitchOption({+ label,+ descriptions,+ descriptionOverride,+ checked,+ disabled,+ onCheckedChange,+}: {+ label: string;+ descriptions: {+ checked: string;+ unchecked: string;+ };+ descriptionOverride?: string;+ checked: boolean;+ disabled?: boolean;+ onCheckedChange: (checked: boolean) => void;+}) {+ const id = useId();+ const descriptionId = `${id}-description`;+ const description =+ descriptionOverride ??+ (checked ? descriptions.checked : descriptions.unchecked);+ const possibleDescriptions = [+ descriptions.checked,+ descriptions.unchecked,+ ...(descriptionOverride ? [descriptionOverride] : []),+ ];+ return (+ <div className="flex min-h-14 items-center justify-between gap-4 px-3 py-2">+ <div className="min-w-0">+ <label htmlFor={id} className="text-sm font-medium leading-5">+ {label}+ </label>+ <OptionDescription+ id={descriptionId}+ description={description}+ possibleDescriptions={possibleDescriptions}+ />+ </div>+ <Switch+ id={id}+ size="sm"+ checked={checked}+ disabled={disabled}+ onCheckedChange={onCheckedChange}+ aria-label={label}+ aria-describedby={descriptionId}+ />+ </div>+ );+}++function RadioOption<Value extends string>({+ label,+ value,+ disabled,+ onValueChange,+ options,+}: {+ label: string;+ value: Value;+ disabled?: boolean;+ onValueChange: (value: Value) => void;+ options: readonly Choice<Value>[];+}) {+ const id = useId();+ const descriptionId = `${id}-description`;+ const selectedDescription = options.find(+ (option) => option.value === value,+ )?.description;+ return (+ <div className="flex min-h-14 flex-col items-stretch gap-2 px-3 py-2 sm:flex-row sm:items-center sm:justify-between sm:gap-4">+ <div className="min-w-0">+ <div className="text-sm font-medium leading-5">{label}</div>+ <OptionDescription+ id={descriptionId}+ description={selectedDescription ?? ""}+ possibleDescriptions={options.map((option) => option.description)}+ />+ </div>+ <RadioGroup+ value={value}+ onValueChange={(nextValue) => onValueChange(nextValue as Value)}+ className="flex shrink-0 flex-wrap gap-x-5 gap-y-2 sm:justify-end"+ aria-label={label}+ aria-describedby={descriptionId}+ disabled={disabled}+ >+ {options.map((option, index) => {+ const optionId = `${id}-${index}`;+ return (+ <div key={option.value} className="flex items-center gap-2">+ <RadioGroupItem id={optionId} value={option.value} />+ <label htmlFor={optionId} className="text-sm">+ {option.label}+ </label>+ </div>+ );+ })}+ </RadioGroup>+ </div>+ );+}++function SelectOption<Value extends string>({+ label,+ value,+ disabled,+ onValueChange,+ options,+}: {+ label: string;+ value: Value;+ disabled?: boolean;+ onValueChange: (value: Value) => void;+ options: readonly Choice<Value>[];+}) {+ const id = useId();+ const descriptionId = `${id}-description`;+ const selectedDescription = options.find(+ (option) => option.value === value,+ )?.description;+ return (+ <div className="flex min-h-14 flex-col items-stretch gap-2 px-3 py-2 sm:flex-row sm:items-center sm:justify-between sm:gap-4">+ <div className="min-w-0">+ <label htmlFor={id} className="text-sm font-medium leading-5">+ {label}+ </label>+ <OptionDescription+ id={descriptionId}+ description={selectedDescription ?? ""}+ possibleDescriptions={options.map((option) => option.description)}+ />+ </div>+ <Select+ value={value}+ disabled={disabled}+ onValueChange={(nextValue) => onValueChange(nextValue as Value)}+ >+ <SelectTrigger+ id={id}+ aria-describedby={descriptionId}+ className="h-8 w-full shrink-0 sm:w-44"+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {options.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ );+}++function OptionDescription({+ id,+ description,+ possibleDescriptions,+}: {+ id: string;+ description: string;+ possibleDescriptions: readonly string[];+}) {+ const sizingDescriptions = [...new Set(possibleDescriptions)].filter(+ (candidate) => candidate !== description,+ );+ return (+ <div className="mt-0.5 grid text-xs leading-4 text-muted-foreground">+ <p id={id} aria-live="polite" className="col-start-1 row-start-1">+ {description}+ </p>+ {sizingDescriptions.map((candidate) => (+ <p+ key={candidate}+ aria-hidden={true}+ className="invisible col-start-1 row-start-1"+ >+ {candidate}+ </p>+ ))}+ </div>+ );+}diff --git a/frontend/src/components/editor/actions/export-dialog/state.ts b/frontend/src/components/editor/actions/export-dialog/state.tsnew file mode 100644index 0000000000..0caf7a169b--- /dev/null+++ b/frontend/src/components/editor/actions/export-dialog/state.ts@@ -0,0 +1,321 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { atomWithStorage } from "jotai/utils";+import { z } from "zod";+import type { ExportAvailabilityResponse } from "@/core/network/types";+import { adaptForLocalStorage } from "@/utils/storage/jotai";++export const EXPORT_FORMATS = [+ "html",+ "markdown",+ "ipynb",+ "pdf",+ "script",+ "png",+] as const;++export type ExportFormat = (typeof EXPORT_FORMATS)[number];++export const MARKDOWN_FLAVORS = ["pymdown", "qmd", "mystmd", "mdx"] as const;+export const IPYNB_SORT_MODES = ["topological", "top-down"] as const;+export const PDF_PRESETS = ["document", "slides"] as const;+export const SCRIPT_TYPES = ["source", "flat"] as const;++export type MarkdownFlavor = (typeof MARKDOWN_FLAVORS)[number];+export type ScriptType = (typeof SCRIPT_TYPES)[number];++export function isExportFormat(value: unknown): value is ExportFormat {+ return (+ typeof value === "string" &&+ EXPORT_FORMATS.some((format) => format === value)+ );+}++export interface ExportOptions {+ html: {+ includeCode: boolean;+ };+ markdown: {+ flavor: MarkdownFlavor | null;+ };+ ipynb: {+ sortMode: (typeof IPYNB_SORT_MODES)[number];+ includeOutputs: boolean;+ };+ pdf: {+ preset: (typeof PDF_PRESETS)[number];+ includeInputs: boolean;+ includeOutputs: boolean;+ webpdf: boolean;+ };+ script: {+ type: ScriptType;+ };+}++export const DEFAULT_EXPORT_OPTIONS: ExportOptions = {+ html: {+ includeCode: true,+ },+ markdown: {+ flavor: null,+ },+ ipynb: {+ sortMode: "topological",+ includeOutputs: false,+ },+ pdf: {+ preset: "document",+ includeInputs: true,+ includeOutputs: true,+ webpdf: true,+ },+ script: {+ type: "source",+ },+};++function storedValue<Schema extends z.ZodType>(+ schema: Schema,+ fallback: Exclude<z.output<Schema>, undefined>,+) {+ return schema.default(fallback).catch(fallback);+}++function storedGroup<Shape extends z.ZodRawShape>(shape: Shape) {+ return z.object(shape).optional().catch(undefined);+}++const storedExportOptionsSchema = z+ .object({+ html: storedGroup({+ includeCode: storedValue(+ z.boolean(),+ DEFAULT_EXPORT_OPTIONS.html.includeCode,+ ),+ }),+ markdown: storedGroup({+ flavor: storedValue(+ z.enum(MARKDOWN_FLAVORS).nullable(),+ DEFAULT_EXPORT_OPTIONS.markdown.flavor,+ ),+ }),+ ipynb: storedGroup({+ sortMode: storedValue(+ z.enum(IPYNB_SORT_MODES),+ DEFAULT_EXPORT_OPTIONS.ipynb.sortMode,+ ),+ includeOutputs: storedValue(+ z.boolean(),+ DEFAULT_EXPORT_OPTIONS.ipynb.includeOutputs,+ ),+ }),+ pdf: storedGroup({+ preset: storedValue(+ z.enum(PDF_PRESETS),+ DEFAULT_EXPORT_OPTIONS.pdf.preset,+ ),+ includeInputs: storedValue(+ z.boolean(),+ DEFAULT_EXPORT_OPTIONS.pdf.includeInputs,+ ),+ includeOutputs: storedValue(+ z.boolean(),+ DEFAULT_EXPORT_OPTIONS.pdf.includeOutputs,+ ),+ webpdf: storedValue(z.boolean(), DEFAULT_EXPORT_OPTIONS.pdf.webpdf),+ }),+ script: storedGroup({+ type: storedValue(+ z.enum(SCRIPT_TYPES),+ DEFAULT_EXPORT_OPTIONS.script.type,+ ),+ }),+ })+ .catch({});++export type ExportOptionOverrides = {+ [Format in keyof ExportOptions]?: Partial<ExportOptions[Format]>;+};++export function applyExportOptionOverrides(+ options: ExportOptions,+ overrides: ExportOptionOverrides,+): ExportOptions {+ const next = { ...options };+ const mergeFormat = <Format extends keyof ExportOptions>(format: Format) => {+ next[format] = { ...options[format], ...overrides[format] };+ };+ for (const format of Object.keys(overrides) as (keyof ExportOptions)[]) {+ mergeFormat(format);+ }+ return next;+}++export function mergeExportOptions(saved: unknown): ExportOptions {+ return applyExportOptionOverrides(+ DEFAULT_EXPORT_OPTIONS,+ storedExportOptionsSchema.parse(saved),+ );+}++const exportOptionsStorage = adaptForLocalStorage<ExportOptions, unknown>({+ toSerializable: (value) => value,+ fromSerializable: mergeExportOptions,+});++export const exportOptionsAtom = atomWithStorage<ExportOptions>(+ "marimo:export:options:v1",+ DEFAULT_EXPORT_OPTIONS,+ exportOptionsStorage,+ { getOnInit: true },+);++export const lastExportFormatAtom = atomWithStorage<ExportFormat>(+ "marimo:export:last-format:v1",+ "html",+ adaptForLocalStorage<ExportFormat, unknown>({+ toSerializable: (value) => value,+ fromSerializable: (value) => (isExportFormat(value) ? value : "html"),+ }),+ { getOnInit: true },+);++export type ExportBlockReason =+ | { type: "checking-requirements" }+ | { type: "notebook-must-be-named" }+ | { type: "missing-packages"; packages: string[] }+ | { type: "wasm-runtime" };++export interface ExportFormatStatus {+ available: boolean;+ reason?: ExportBlockReason;+ availabilityCheckFailed?: boolean;+}++interface GetExportFormatStatusOptions {+ format: ExportFormat;+ options: ExportOptions;+ runtime: "server" | "wasm";+ filename: string | null;+ availability:+ | { status: "pending" }+ | { status: "error" }+ | { status: "success"; data: ExportAvailabilityResponse | null };+}++interface ExportFormatRequirements {+ requiresNamedNotebookOnServer: boolean;+ requiresServerRuntime: boolean;+ checksServerAvailability: boolean;+}++const FORMAT_REQUIREMENTS: Record<ExportFormat, ExportFormatRequirements> = {+ html: {+ requiresNamedNotebookOnServer: true,+ requiresServerRuntime: false,+ checksServerAvailability: false,+ },+ markdown: {+ requiresNamedNotebookOnServer: true,+ requiresServerRuntime: false,+ checksServerAvailability: false,+ },+ ipynb: {+ requiresNamedNotebookOnServer: true,+ requiresServerRuntime: true,+ checksServerAvailability: true,+ },+ pdf: {+ requiresNamedNotebookOnServer: true,+ requiresServerRuntime: true,+ checksServerAvailability: true,+ },+ script: {+ requiresNamedNotebookOnServer: false,+ requiresServerRuntime: false,+ checksServerAvailability: false,+ },+ png: {+ requiresNamedNotebookOnServer: false,+ requiresServerRuntime: false,+ checksServerAvailability: false,+ },+};++export function isBrowserPrintExport(+ runtime: "server" | "wasm",+ format: ExportFormat,+): boolean {+ return runtime === "wasm" && format === "pdf";+}++export function getExportFormatStatus({+ format,+ options,+ runtime,+ filename,+ availability,+}: GetExportFormatStatusOptions): ExportFormatStatus {+ const isNotebookSource =+ format === "script" && options.script.type === "source";+ const requirements = isNotebookSource+ ? {+ ...FORMAT_REQUIREMENTS.script,+ requiresNamedNotebookOnServer: true,+ }+ : FORMAT_REQUIREMENTS[format];++ const usesBrowserPrint = isBrowserPrintExport(runtime, format);++ if (runtime === "wasm" && requirements.requiresServerRuntime) {+ return {+ available: usesBrowserPrint,+ reason: { type: "wasm-runtime" },+ };+ }++ if (+ runtime === "server" &&+ requirements.requiresNamedNotebookOnServer &&+ !filename+ ) {+ return {+ available: false,+ reason: { type: "notebook-must-be-named" },+ };+ }++ if (runtime === "wasm" || !requirements.checksServerAvailability) {+ return { available: true };+ }++ if (availability.status === "pending") {+ return {+ available: false,+ reason: { type: "checking-requirements" },+ };+ }++ if (availability.status === "error" || !availability.data) {+ return { available: true, availabilityCheckFailed: true };+ }++ const serverStatus = availability.data.formats.find(+ (candidate) => candidate.format === format,+ );+ if (!serverStatus) {+ return { available: true, availabilityCheckFailed: true };+ }+ if (!serverStatus.dependenciesAvailable) {+ return {+ available: false,+ reason: {+ type: "missing-packages",+ packages: serverStatus.missingPackages,+ },+ };+ }++ return { available: true };+}diff --git a/frontend/src/components/editor/actions/export-dialog/use-export-dialog.ts b/frontend/src/components/editor/actions/export-dialog/use-export-dialog.tsnew file mode 100644index 0000000000..d2fdcc86a4--- /dev/null+++ b/frontend/src/components/editor/actions/export-dialog/use-export-dialog.ts@@ -0,0 +1,380 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { useAtom, useAtomValue, useSetAtom } from "jotai";+import { useEffect, useRef, useState } from "react";+import { toast } from "@/components/ui/use-toast";+import {+ updateCellOutputsWithScreenshots,+ useEnrichCellOutputs,+} from "@/core/export/hooks";+import { runDuringPresentMode, viewStateAtom } from "@/core/mode";+import { useRequestClient } from "@/core/network/requests";+import type { ExportAvailabilityResponse } from "@/core/network/types";+import { useFilename } from "@/core/saving/filename";+import { VirtualFileTracker } from "@/core/static/virtual-file-tracker";+import { isWasm } from "@/core/wasm/utils";+import { type AsyncDataResult, useAsyncData } from "@/hooks/useAsyncData";+import {+ ADD_PRINTING_CLASS,+ downloadExportedFile,+ downloadHTMLAsImage,+ withLoadingToast,+} from "@/utils/download";+import { Filenames } from "@/utils/filenames";+import { Paths } from "@/utils/paths";+import { getExportCommand } from "./export-command";+import { exportNotebook } from "./export-notebook";+import { FORMAT_DEFINITIONS, type UpdateExportOptions } from "./format-options";+import {+ EXPORT_FORMATS,+ type ExportFormat,+ type ExportOptions,+ exportOptionsAtom,+ getExportFormatStatus,+ isBrowserPrintExport,+ isExportFormat,+ lastExportFormatAtom,+} from "./state";++type ExportAvailability = Parameters<+ typeof getExportFormatStatus+>[0]["availability"];++const SCRIPT_EXPORT_COPY: Record<+ ExportOptions["script"]["type"],+ { actionLabel: string; progressLabel: string }+> = {+ source: {+ actionLabel: "Export notebook source",+ progressLabel: "notebook source",+ },+ flat: {+ actionLabel: "Export flat script",+ progressLabel: "flat script",+ },+};++function getExportAvailability(+ runtime: "server" | "wasm",+ request: AsyncDataResult<ExportAvailabilityResponse | null>,+): ExportAvailability {+ if (runtime === "wasm") {+ return { status: "success", data: null };+ }++ switch (request.status) {+ case "pending":+ case "loading":+ return { status: "pending" };+ case "error":+ return { status: "error" };+ case "success":+ return { status: "success", data: request.data };+ }+}++function getSourceFilename(+ runtime: "server" | "wasm",+ filename: string | null,+): string {+ if (runtime === "server" && filename) {+ return Paths.basename(filename);+ }+ return Filenames.toPY(document.title);+}++function getFooterDescription({+ usesBrowserPrint,+ hasCommand,+ format,+ isNotebookSource,+}: {+ usesBrowserPrint: boolean;+ hasCommand: boolean;+ format: ExportFormat;+ isNotebookSource: boolean;+}): string | null {+ if (usesBrowserPrint) {+ return "Uses the browser's print settings for page size and filename.";+ }+ if (hasCommand) {+ return "Uses the current session state. The copied command exports the saved notebook.";+ }+ if (format !== "png" && !isNotebookSource) {+ return "Save the notebook to copy an equivalent shell command.";+ }+ return null;+}++function useExportDialogState(initialFormat?: ExportFormat) {+ const filename = useFilename();+ const [options, setOptions] = useAtom(exportOptionsAtom);+ const [lastFormat, setLastFormat] = useAtom(lastExportFormatAtom);+ const [format, setFormat] = useState<ExportFormat>(+ initialFormat ?? lastFormat,+ );+ const runtime = isWasm() ? "wasm" : "server";+ const requests = useRequestClient();++ const availabilityRequest =+ useAsyncData<ExportAvailabilityResponse | null>(async () => {+ if (runtime === "wasm") {+ return null;+ }+ return requests.getExportAvailability();+ }, [runtime, requests]);+ const availability = getExportAvailability(runtime, availabilityRequest);++ const statusFor = (candidate: ExportFormat) =>+ getExportFormatStatus({+ format: candidate,+ options,+ runtime,+ filename,+ availability,+ });+ const status = statusFor(format);+ const formats = EXPORT_FORMATS.map((candidate) => ({+ format: candidate,+ status: statusFor(candidate),+ }));+ const usesBrowserPrint = isBrowserPrintExport(runtime, format);+ const definition = FORMAT_DEFINITIONS[format];+ const isNotebookSource =+ format === "script" && options.script.type === "source";+ const { actionLabel, progressLabel } =+ format === "script"+ ? SCRIPT_EXPORT_COPY[options.script.type]+ : {+ actionLabel: definition.actionLabel,+ progressLabel: definition.label,+ };+ const command = usesBrowserPrint+ ? null+ : getExportCommand({ format, filename, options });+ const footerDescription = getFooterDescription({+ usesBrowserPrint,+ hasCommand: Boolean(command),+ format,+ isNotebookSource,+ });++ useEffect(() => {+ if (initialFormat) {+ setLastFormat(initialFormat);+ }+ }, [initialFormat, setLastFormat]);++ const selectFormat = (value: string) => {+ if (isExportFormat(value)) {+ setFormat(value);+ setLastFormat(value);+ }+ };++ const updateOptions: UpdateExportOptions = (optionFormat, nextOptions) => {+ setOptions((current) => {+ const next = { ...current };+ next[optionFormat] = {+ ...current[optionFormat],+ ...nextOptions,+ };+ return next;+ });+ };++ return {+ formats,+ options,+ selected: {+ format,+ status,+ usesBrowserPrint,+ actionLabel,+ command,+ footerDescription,+ },+ exportRequest: {+ format,+ options,+ sourceFilename: getSourceFilename(runtime, filename),+ available: status.available,+ usesBrowserPrint,+ progressLabel,+ },+ selectFormat,+ updateOptions,+ };+}++async function captureCurrentAppView(+ dialogContainer: HTMLElement | null,+): Promise<void> {+ const app = document.getElementById("App");+ if (!app) {+ const message = "The current app view could not be captured.";+ toast({+ title: "Failed to download as PNG",+ description: message,+ variant: "danger",+ });+ throw new Error(message);+ }++ const previousVisibility = dialogContainer?.style.visibility;+ const wasCaptureExcluded =+ dialogContainer?.classList.contains("print:hidden");+ const downloaded = await downloadHTMLAsImage({+ element: app,+ filename: document.title,+ prepare: () => {+ const cleanupPrinting = ADD_PRINTING_CLASS();+ if (dialogContainer) {+ dialogContainer.classList.add("print:hidden");+ dialogContainer.style.visibility = "hidden";+ }+ return () => {+ cleanupPrinting();+ if (dialogContainer) {+ if (!wasCaptureExcluded) {+ dialogContainer.classList.remove("print:hidden");+ }+ dialogContainer.style.visibility = previousVisibility ?? "";+ }+ };+ },+ });+ if (!downloaded) {+ throw new Error("Failed to capture the current app view.");+ }+}++function printCurrentView(onClose: () => void): void {+ onClose();+ requestAnimationFrame(() => {+ setTimeout(() => {+ window.print();+ }, 0);+ });+}++function useExportDialogAction({+ format,+ options,+ sourceFilename,+ available,+ usesBrowserPrint,+ progressLabel,+ onClose,+}: {+ format: ExportFormat;+ options: ExportOptions;+ sourceFilename: string;+ available: boolean;+ usesBrowserPrint: boolean;+ progressLabel: string;+ onClose: () => void;+}) {+ const requests = useRequestClient();+ const takeScreenshots = useEnrichCellOutputs();+ const viewState = useAtomValue(viewStateAtom);+ const setViewState = useSetAtom(viewStateAtom);+ const [isExporting, setIsExporting] = useState(false);+ const dialogRef = useRef<HTMLDivElement>(null);+ const mountedRef = useRef(true);++ useEffect(() => {+ mountedRef.current = true;+ return () => {+ mountedRef.current = false;+ };+ }, []);++ const captureOutputs = async (+ progress: Parameters<typeof takeScreenshots>[0]["progress"],+ ) => {+ await updateCellOutputsWithScreenshots({+ takeScreenshots: () => takeScreenshots({ progress }),+ updateCellOutputs: requests.updateCellOutputs,+ });+ };++ const capturePNG = async () => {+ const capture = () =>+ captureCurrentAppView(dialogRef.current?.parentElement ?? null);+ if (viewState.mode !== "edit") {+ await capture();+ return;+ }+ try {+ await runDuringPresentMode(capture);+ } finally {+ setViewState(viewState);+ }+ };++ const submit = async () => {+ if (!available || isExporting) {+ return;+ }+ if (usesBrowserPrint) {+ printCurrentView(onClose);+ return;+ }++ setIsExporting(true);+ try {+ await withLoadingToast(+ `Exporting ${progressLabel}…`,+ async (progress) => {+ await exportNotebook({+ format,+ options,+ requests,+ sourceFilename,+ htmlFiles: VirtualFileTracker.INSTANCE.filenames(),+ captureOutputs: () => captureOutputs(progress),+ capturePNG,+ downloadFile: downloadExportedFile,+ });+ },+ );+ if (mountedRef.current) {+ onClose();+ }+ } catch {+ // Request and capture helpers report actionable errors to the user.+ } finally {+ if (mountedRef.current) {+ setIsExporting(false);+ }+ }+ };++ return { dialogRef, isExporting, submit };+}++export function useExportDialog({+ initialFormat,+ onClose,+}: {+ initialFormat?: ExportFormat;+ onClose: () => void;+}) {+ const { exportRequest, selectFormat, ...state } =+ useExportDialogState(initialFormat);+ const action = useExportDialogAction({+ ...exportRequest,+ onClose,+ });++ return {+ ...state,+ ...action,+ selectFormat: (value: string) => {+ if (!action.isExporting) {+ selectFormat(value);+ }+ },+ };+}diff --git a/frontend/src/components/editor/actions/pair-with-agent-commands.ts b/frontend/src/components/editor/actions/pair-with-agent-commands.tsindex c6d6697c1d..2949c3fc39 100644--- a/frontend/src/components/editor/actions/pair-with-agent-commands.ts+++ b/frontend/src/components/editor/actions/pair-with-agent-commands.ts@@ -2,6 +2,7 @@import { assertNever } from "@/utils/assertNever";import { KnownQueryParams } from "@/core/constants";+import { shellQuote } from "@/utils/shell";export type AgentTab = "claude" | "codex" | "opencode" | "prompt";@@ -23,27 +24,6 @@ export function getMarimoCommand(): string {return import.meta.env.DEV ? "uv run marimo" : "uvx marimo@latest";}-/**- * POSIX-quote a value for safe embedding in a shell command. These commands are- * meant to be copied into a terminal, so a url/token containing shell- * metacharacters (`'`, `&`, `$(...)`, ...) must not break out of its argument.- *- * Mirrors Python's `shlex.quote` (used on the CLI side in- * `marimo/_cli/pair/commands.py`) so both sides produce identical commands:- * values that are already shell-safe are left as-is for readability, and- * anything else is single-quoted with embedded quotes escaped as `'"'"'`.- */-export function shellQuote(value: string): string {- if (value === "") {- return "''";- }- // Same "safe" character set as CPython's shlex.quote (ASCII \w plus a few).- if (/^[\w@%+=:,./-]+$/.test(value)) {- return value;- }- return `'${value.replaceAll("'", `'"'"'`)}'`;-}-/** Return the server file key from a page URL, preserving its decoded value. */export function getFileFromURL(href: string): string | undefined {const file = new URL(href).searchParams.get(KnownQueryParams.filePath);diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsxindex ed1bf3adee..2820b59793 100644--- a/frontend/src/components/editor/actions/useNotebookActions.tsx+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx@@ -1,6 +1,7 @@/* Copyright 2026 Marimo. All rights reserved. */import { useAtom, useAtomValue, useSetAtom } from "jotai";+import type { RefObject } from "react";import {BookMarkedIcon,CheckIcon,@@ -51,7 +52,6 @@ import { GitHubIcon } from "@/components/icons/github";import { MarimoPlusIcon } from "@/components/icons/marimo-icons";import { YouTubeIcon } from "@/components/icons/youtube";import { useImperativeModal } from "@/components/modal/ImperativeModal";-import { renderShortcut } from "@/components/shortcuts/renderShortcut";import { PairWithAgentModal } from "@/components/editor/actions/pair-with-agent-modal";import { ShareStaticNotebookModal } from "@/components/static-html/share-modal";import { toast } from "@/components/ui/use-toast";@@ -66,30 +66,15 @@ import { disabledCellIds } from "@/core/cells/utils";import { capabilitiesAtom } from "@/core/config/capabilities";import { aiEnabledAtom, useResolvedMarimoConfig } from "@/core/config/config";import { Constants } from "@/core/constants";-import {- updateCellOutputsWithScreenshots,- useEnrichCellOutputs,-} from "@/core/export/hooks";import { useLayoutActions, useLayoutState } from "@/core/layout/layout";import { useTogglePresenting } from "@/core/layout/useTogglePresenting";import { kioskModeAtom, viewStateAtom } from "@/core/mode";import { useRequestClient } from "@/core/network/requests";import { useFilename } from "@/core/saving/filename";-import { downloadAsHTML } from "@/core/static/download-html";import { createShareableLink } from "@/core/wasm/share";import { isWasm } from "@/core/wasm/utils";import { copyToClipboard } from "@/utils/copy";-import {- ADD_PRINTING_CLASS,- downloadAsPDF,- downloadBlob,- downloadExportedFile,- downloadHTMLAsImage,- withLoadingToast,-} from "@/utils/download";-import { Filenames } from "@/utils/filenames";import { Objects } from "@/utils/objects";-import type { ProgressState } from "@/utils/progress";import { Strings } from "@/utils/strings";import { newNotebookURL } from "@/utils/urls";import { useRunAllCells } from "../cell/useRunCells";@@ -100,7 +85,13 @@ import { keyboardShortcutsAtom } from "../controls/keyboard-shortcuts";import { commandPaletteAtom } from "../controls/state";import { displayLayoutName, getLayoutIcon } from "../renderers/layout-select";import { LAYOUT_TYPES } from "../renderers/types";-import { runServerSidePDFDownload } from "./pdf-export";+import { ExportDialog } from "./export-dialog/export-dialog";+import {+ applyExportOptionOverrides,+ exportOptionsAtom,+ type ExportFormat,+ type ExportOptionOverrides,+} from "./export-dialog/state";import type { ActionButton } from "./types";import { useCopyNotebook } from "./useCopyNotebook";import { useRestartKernel } from "./useRestartKernel";@@ -111,7 +102,11 @@ const NOOP_HANDLER = (event?: Event) => {event?.stopPropagation();};-export function useNotebookActions() {+export function useNotebookActions({+ exportDialogReturnFocusRef,+}: {+ exportDialogReturnFocusRef?: RefObject<HTMLElement | null>;+} = {}) {const filename = useFilename();const { openModal, closeModal } = useImperativeModal();const { toggleApplication } = useChromeActions();@@ -138,15 +133,8 @@ export function useNotebookActions() {const setSettingsDialogOpen = useSetAtom(settingDialogAtom);const { handleClick: openSettings } = useOpenSettingsToTab();const setKeyboardShortcutsOpen = useSetAtom(keyboardShortcutsAtom);- const {- exportAsIPYNB,- exportAsMarkdown,- exportAsScript,- readCode,- saveCellConfig,- updateCellOutputs,- } = useRequestClient();- const takeScreenshots = useEnrichCellOutputs();+ const setExportOptions = useSetAtom(exportOptionsAtom);+ const { readCode, saveCellConfig } = useRequestClient();const hasDisabledCells = useAtomValue(hasDisabledCellsAtom);const canUndoDeletes = useAtomValue(canUndoDeletesAtom);@@ -158,10 +146,6 @@ export function useNotebookActions() {const sharingHtmlEnabled = resolvedConfig.sharing?.html ?? true;const sharingWasmEnabled = resolvedConfig.sharing?.wasm ?? true;const sharingMolabEnabled = resolvedConfig.sharing?.molab ?? true;-- // Server-side PDF export is always available outside WASM.- // Browser print fallback is used in WASM.- const serverSidePdfEnabled = !isWasm();const isSlidesLayout = selectedLayout === "slides";const renderCheckboxElement = (checked: boolean) => (@@ -170,82 +154,39 @@ export function useNotebookActions() {</div>);- const renderRecommendedElement = (recommended: boolean) => {- if (!recommended) {- return null;+ const openExportDialog = (+ initialFormat?: ExportFormat,+ optionOverrides?: ExportOptionOverrides,+ ) => {+ if (optionOverrides) {+ setExportOptions((current) =>+ applyExportOptionOverrides(current, optionOverrides),+ );}- return (- <span className="ml-3 shrink-0 rounded-full border border-emerald-200 bg-emerald-50 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-emerald-700">- Recommended- </span>+ openModal(+ <ExportDialog+ initialFormat={initialFormat}+ onClose={closeModal}+ returnFocusRef={exportDialogReturnFocusRef}+ />,);};- const downloadServerSidePDF = async ({- preset,- title,- }: {- preset: "document" | "slides";- title: string;- }) => {- if (!filename) {- toastNotebookMustBeNamed();- return;- }-- const runDownload = async (progress: ProgressState) => {- await runServerSidePDFDownload({- exportOptions: {- webpdf: false,- preset,- includeInputs: true,- includeOutputs: true,- },- captureOutputs: () =>- updateCellOutputsWithScreenshots({- takeScreenshots: () => takeScreenshots({ progress }),- updateCellOutputs,- }),- downloadPDF: downloadAsPDF,- });- };- await withLoadingToast(title, runDownload);- };-- const handleDocumentPDF = async () => {- if (serverSidePdfEnabled) {- await downloadServerSidePDF({- preset: "document",- title: "Downloading Document PDF...",- });- return;- }- const beforeprint = new Event("export-beforeprint");- const afterprint = new Event("export-afterprint");- window.dispatchEvent(beforeprint);- setTimeout(() => window.print(), 0);- setTimeout(() => window.dispatchEvent(afterprint), 0);- };-- const handleDownloadAsIPYNB = async () => {- if (!filename) {- toastNotebookMustBeNamed();- return;- }-- const runDownload = async (progress: ProgressState) => {- await updateCellOutputsWithScreenshots({- takeScreenshots: () => takeScreenshots({ progress }),- updateCellOutputs,- });- const exportedFile = await exportAsIPYNB({ download: false });- downloadExportedFile(exportedFile);- };-- await withLoadingToast("Downloading IPYNB...", runDownload);- };-const actions: ActionButton[] = [+ {+ icon: <DownloadIcon size={14} strokeWidth={1.5} />,+ label: "Export…",+ additionalKeywords: [+ "download",+ "html",+ "markdown",+ "ipynb",+ "pdf",+ "script",+ "png",+ ],+ handle: () => openExportDialog(),+ },{icon: <DownloadIcon size={14} strokeWidth={1.5} />,label: "Download",@@ -254,83 +195,44 @@ export function useNotebookActions() {{icon: <FolderDownIcon size={14} strokeWidth={1.5} />,label: "Download as HTML",- handle: async () => {- if (!filename) {- toastNotebookMustBeNamed();- return;- }- await downloadAsHTML({ includeCode: true });- },+ handle: () =>+ openExportDialog("html", { html: { includeCode: true } }),},{icon: <FolderDownIcon size={14} strokeWidth={1.5} />,label: "Download as HTML (exclude code)",- handle: async () => {- if (!filename) {- toastNotebookMustBeNamed();- return;- }- await downloadAsHTML({ includeCode: false });- },+ handle: () =>+ openExportDialog("html", { html: { includeCode: false } }),},{icon: (<MarkdownIcon strokeWidth={1.5} style={{ width: 14, height: 14 }} />),label: "Download as Markdown",- handle: async () => {- const exportedFile = await exportAsMarkdown({ download: false });- downloadExportedFile(exportedFile);- },+ handle: () => openExportDialog("markdown"),},{icon: <NotebookIcon size={14} strokeWidth={1.5} />,label: "Download as ipynb",- handle: handleDownloadAsIPYNB,+ handle: () => openExportDialog("ipynb"),},{icon: <CodeIcon size={14} strokeWidth={1.5} />,label: "Download notebook source",- handle: async () => {- const code = await readCode();- downloadBlob(- new Blob([code.contents], { type: "text/plain" }),- Filenames.toPY(document.title),- );- },+ handle: () =>+ openExportDialog("script", { script: { type: "source" } }),},{icon: <CodeIcon size={14} strokeWidth={1.5} />,label: "Download flat script",- handle: async () => {- const exportedFile = await exportAsScript({ download: false });- downloadExportedFile(exportedFile);- },+ handle: () =>+ openExportDialog("script", { script: { type: "flat" } }),},{divider: true,icon: <ImageIcon size={14} strokeWidth={1.5} />,label: "Download as PNG",- disabled: viewState.mode !== "present",- tooltip:- viewState.mode === "present" ? undefined : (- <span>- Only available in app view. <br />- Toggle with: {renderShortcut("global.hideCode", false)}- </span>- ),- handle: async () => {- const app = document.getElementById("App");- if (!app) {- return;- }- await downloadHTMLAsImage({- element: app,- filename: document.title,- // Add body.printing ONLY when converting the whole notebook to a screenshot- prepare: ADD_PRINTING_CLASS,- });- },+ handle: () => openExportDialog("png"),},isSlidesLayout? {@@ -342,19 +244,24 @@ export function useNotebookActions() {{icon: <FileIcon size={14} strokeWidth={1.5} />,label: "Document Layout",- handle: handleDocumentPDF,+ handle: () =>+ openExportDialog("pdf", {+ pdf: { preset: "document" },+ }),},{icon: <FileIcon size={14} strokeWidth={1.5} />,label: "Slides Layout",- rightElement: renderRecommendedElement(true),- hidden: !serverSidePdfEnabled,- handle: async () => {- await downloadServerSidePDF({- preset: "slides",- title: "Downloading Slides PDF...",- });- },+ hidden: isWasm(),+ rightElement: (+ <span className="ml-3 shrink-0 rounded-full border border-emerald-200 bg-emerald-50 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-emerald-700">+ Recommended+ </span>+ ),+ handle: () =>+ openExportDialog("pdf", {+ pdf: { preset: "slides" },+ }),},],}@@ -362,7 +269,10 @@ export function useNotebookActions() {divider: true,icon: <FileIcon size={14} strokeWidth={1.5} />,label: "Download as PDF",- handle: handleDocumentPDF,+ handle: () =>+ openExportDialog("pdf", {+ pdf: { preset: "document" },+ }),},],},@@ -740,11 +650,3 @@ export function useNotebookActions() {return action;});}--function toastNotebookMustBeNamed() {- toast({- title: "Error",- description: "Notebooks must be named to be exported.",- variant: "danger",- });-}diff --git a/frontend/src/components/editor/controls/__tests__/notebook-menu-dropdown.test.tsx b/frontend/src/components/editor/controls/__tests__/notebook-menu-dropdown.test.tsxnew file mode 100644index 0000000000..c6ba27540a--- /dev/null+++ b/frontend/src/components/editor/controls/__tests__/notebook-menu-dropdown.test.tsx@@ -0,0 +1,187 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { Provider } from "jotai";+import type React from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { MockRequestClient } from "@/__mocks__/requests";+import { ModalProvider } from "@/components/modal/ImperativeModal";+import { TooltipProvider } from "@/components/ui/tooltip";+import { layoutStateAtom } from "@/core/layout/layout";+import { kioskModeAtom, viewStateAtom } from "@/core/mode";+import { requestClientAtom } from "@/core/network/requests";+import { filenameAtom } from "@/core/saving/file-state";+import { store } from "@/core/state/jotai";+import { isWasm } from "@/core/wasm/utils";+import {+ DEFAULT_EXPORT_OPTIONS,+ exportOptionsAtom,+ lastExportFormatAtom,+} from "../../actions/export-dialog/state";+import { NotebookMenuDropdown } from "../notebook-menu-dropdown";++vi.mock("@/core/wasm/utils", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@/core/wasm/utils")>();+ return { ...actual, isWasm: vi.fn(() => false) };+});++function wrapper({ children }: { children: React.ReactNode }) {+ return (+ <Provider store={store}>+ <TooltipProvider>+ <ModalProvider>{children}</ModalProvider>+ </TooltipProvider>+ </Provider>+ );+}++function openNotebookMenu() {+ fireEvent.pointerDown(screen.getByTestId("notebook-menu-dropdown"), {+ button: 0,+ ctrlKey: false,+ });+}++async function openDownloadMenu() {+ openNotebookMenu();+ fireEvent.click(await screen.findByRole("menuitem", { name: "Download" }));+}++async function selectDownload(name: string | RegExp) {+ await openDownloadMenu();+ fireEvent.click(await screen.findByRole("menuitem", { name }));+}++describe("NotebookMenuDropdown", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ localStorage.clear();+ store.set(requestClientAtom, MockRequestClient.create());+ store.set(filenameAtom, "/project/notebook.py");+ store.set(viewStateAtom, { mode: "edit", cellAnchor: null });+ store.set(kioskModeAtom, false);+ store.set(layoutStateAtom, {+ selectedLayout: "vertical",+ layoutData: {},+ });+ store.set(exportOptionsAtom, DEFAULT_EXPORT_OPTIONS);+ store.set(lastExportFormatAtom, "html");+ vi.mocked(isWasm).mockReturnValue(false);+ vi.stubGlobal("PointerEvent", MouseEvent);+ vi.stubGlobal("matchMedia", () => ({+ matches: false,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ }));+ });++ afterEach(() => {+ document.title = "";+ vi.unstubAllGlobals();+ });++ it("returns focus to the notebook menu when the dialog closes", async () => {+ render(<NotebookMenuDropdown />, { wrapper });+ const menuButton = screen.getByTestId("notebook-menu-dropdown");++ openNotebookMenu();+ fireEvent.click(+ await screen.findByRole("menuitem", {+ name: "Export…",+ }),+ );+ fireEvent.click(await screen.findByRole("button", { name: "Close" }));++ await waitFor(() => expect(menuButton).toHaveFocus());+ });++ it("opens the HTML shortcut with code excluded", async () => {+ render(<NotebookMenuDropdown />, { wrapper });++ await selectDownload("Download as HTML (exclude code)");++ expect(await screen.findByTestId("export-dialog")).toBeVisible();+ expect(screen.getByTestId("export-format-html")).toHaveAttribute(+ "aria-selected",+ "true",+ );+ expect(+ screen.getByRole("switch", { name: "Include code" }),+ ).not.toBeChecked();+ });++ it("opens the slides PDF shortcut with the slides layout", async () => {+ store.set(layoutStateAtom, {+ selectedLayout: "slides",+ layoutData: {},+ });+ render(<NotebookMenuDropdown />, { wrapper });++ await openDownloadMenu();+ fireEvent.click(+ await screen.findByRole("menuitem", {+ name: "Download as PDF",+ }),+ );+ fireEvent.click(+ await screen.findByRole("menuitem", {+ name: /Slides Layout/,+ }),+ );++ expect(await screen.findByTestId("export-dialog")).toBeVisible();+ expect(screen.getByTestId("export-format-pdf")).toHaveAttribute(+ "aria-selected",+ "true",+ );+ expect(screen.getByRole("radio", { name: "Slides" })).toBeChecked();+ });++ it("hides the slides PDF shortcut in WebAssembly", async () => {+ vi.mocked(isWasm).mockReturnValue(true);+ store.set(layoutStateAtom, {+ selectedLayout: "slides",+ layoutData: {},+ });+ render(<NotebookMenuDropdown />, { wrapper });++ await openDownloadMenu();+ fireEvent.click(+ await screen.findByRole("menuitem", {+ name: "Download as PDF",+ }),+ );++ expect(+ screen.getByRole("menuitem", { name: "Document Layout" }),+ ).toBeVisible();+ expect(+ screen.queryByRole("menuitem", { name: /Slides Layout/ }),+ ).not.toBeInTheDocument();+ });++ it("preselects each Python format from its download shortcut", async () => {+ render(<NotebookMenuDropdown />, { wrapper });++ await selectDownload("Download notebook source");++ expect(await screen.findByTestId("export-dialog")).toBeVisible();+ expect(screen.getByTestId("export-format-script")).toHaveAttribute(+ "aria-selected",+ "true",+ );+ expect(+ screen.getByRole("radio", { name: "Notebook source" }),+ ).toBeChecked();++ fireEvent.click(screen.getByRole("button", { name: "Close" }));+ await waitFor(() =>+ expect(screen.queryByTestId("export-dialog")).not.toBeInTheDocument(),+ );++ await selectDownload("Download flat script");++ expect(await screen.findByTestId("export-dialog")).toBeVisible();+ expect(screen.getByRole("radio", { name: "Flat script" })).toBeChecked();+ });+});diff --git a/frontend/src/components/editor/controls/notebook-menu-dropdown.tsx b/frontend/src/components/editor/controls/notebook-menu-dropdown.tsxindex d713512a46..9f9f03ada9 100644--- a/frontend/src/components/editor/controls/notebook-menu-dropdown.tsx+++ b/frontend/src/components/editor/controls/notebook-menu-dropdown.tsx@@ -1,7 +1,7 @@/* Copyright 2026 Marimo. All rights reserved. */import { MenuIcon } from "lucide-react";-import React from "react";+import React, { useRef } from "react";import { useLocale } from "react-aria";import { Button } from "@/components/editor/inputs/Inputs";import {@@ -33,7 +33,8 @@ export const NotebookMenuDropdown: React.FC<Props> = ({disabled = false,tooltip = "Actions",}) => {- const actions = useNotebookActions();+ const exportDialogReturnFocusRef = useRef<HTMLButtonElement>(null);+ const actions = useNotebookActions({ exportDialogReturnFocusRef });const { locale } = useLocale();// Create tooltip content with keyboard shortcut decorationconst tooltipContent = (@@ -50,6 +51,7 @@ export const NotebookMenuDropdown: React.FC<Props> = ({const button = (<Button+ ref={exportDialogReturnFocusRef}aria-label="Config"shape="circle"size="small"diff --git a/frontend/src/utils/__tests__/download.test.tsx b/frontend/src/utils/__tests__/download.test.tsxindex 121929bb9e..6d9fde4008 100644--- a/frontend/src/utils/__tests__/download.test.tsx+++ b/frontend/src/utils/__tests__/download.test.tsx@@ -390,8 +390,9 @@ describe("downloadHTMLAsImage", () => {it("should download image without prepare function", async () => {vi.mocked(toPng).mockResolvedValue(mockDataUrl);- await downloadHTMLAsImage({ element: mockElement, filename: "test" });-+ expect(+ await downloadHTMLAsImage({ element: mockElement, filename: "test" }),+ ).toBe(true);expect(toPng).toHaveBeenCalledWith(mockElement,expect.objectContaining({@@ -452,8 +453,9 @@ describe("downloadHTMLAsImage", () => {it("should show error toast on failure", async () => {vi.mocked(toPng).mockRejectedValue(new Error("Failed"));- await downloadHTMLAsImage({ element: mockElement, filename: "test" });-+ expect(+ await downloadHTMLAsImage({ element: mockElement, filename: "test" }),+ ).toBe(false);expect(toast).toHaveBeenCalledWith({title: "Failed to download as PNG",description: "Failed",diff --git a/frontend/src/utils/download.ts b/frontend/src/utils/download.tsindex 546e1781b2..d3d170e8b8 100644--- a/frontend/src/utils/download.ts+++ b/frontend/src/utils/download.ts@@ -140,7 +140,7 @@ export async function downloadHTMLAsImage(opts: {element: HTMLElement;filename: string;prepare?: (element: HTMLElement) => () => void;-}) {+}): Promise<boolean> {const { element, filename, prepare } = opts;// Capture current scroll position@@ -156,6 +156,7 @@ export async function downloadHTMLAsImage(opts: {// Get screenshotconst dataUrl = await toPng(element);downloadByURL(dataUrl, Filenames.toPNG(filename));+ return true;} catch (error) {Logger.error("Error downloading as PNG", error);toast({@@ -163,6 +164,7 @@ export async function downloadHTMLAsImage(opts: {description: prettyError(error),variant: "danger",});+ return false;} finally {cleanup?.();if (document.body.classList.contains("printing")) {diff --git a/frontend/src/utils/shell.ts b/frontend/src/utils/shell.tsnew file mode 100644index 0000000000..38fed6f4ff--- /dev/null+++ b/frontend/src/utils/shell.ts@@ -0,0 +1,17 @@+/* Copyright 2026 Marimo. All rights reserved. */++/**+ * Quote one argument for a POSIX shell command.+ *+ * Mirrors Python's `shlex.quote` so copied commands cannot interpret argument+ * contents as shell syntax.+ */+export function shellQuote(value: string): string {+ if (value === "") {+ return "''";+ }+ if (/^[\w@%+=:,./-]+$/.test(value)) {+ return value;+ }+ return `'${value.replaceAll("'", `'"'"'`)}'`;+}