A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: add download as html or png in Run mode (#1469)
Myles Scolnick1ab075ac1097
diff --git a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsxindex 8a3f172b65..c5e3193c01 100644--- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx+++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx@@ -9,12 +9,27 @@ import { z } from "zod";import { useDelayVisibility } from "./useDelayVisibility";import { AppMode } from "@/core/mode";import { ReadonlyPythonCode } from "@/components/editor/code/readonly-python-code";-import { Code2Icon } from "lucide-react";+import {+ ChevronDown,+ Code2Icon,+ Download,+ FolderDownIcon,+ ImageIcon,+} from "lucide-react";import { cn } from "@/utils/cn";import { Button } from "@/components/ui/button";import { outputIsStale } from "@/core/cells/cell";import { isStaticNotebook } from "@/core/static/static-state";import { ConsoleOutput } from "@/components/editor/output/ConsoleOutput";+import {+ DropdownMenuItem,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { downloadHTMLAsImage } from "@/utils/download";+import { useFilename } from "@/core/saving/filename";+import { downloadAsHTML } from "@/core/static/download-html";type VerticalLayout = null;type VerticalLayoutProps = ICellRendererProps<VerticalLayout>;@@ -29,6 +44,7 @@ const VerticalLayoutRenderer: React.FC<VerticalLayoutProps> = ({// Default to showing code if the notebook is staticreturn isStaticNotebook();});+const evaluateCanShowCode = () => {const cellsHaveCode = cells.some((cell) => Boolean(cell.code));@@ -65,28 +81,78 @@ const VerticalLayoutRenderer: React.FC<VerticalLayoutProps> = ({name={cell.name}/>))}+ <ActionButtons+ canShowCode={canShowCode}+ showCode={showCode}+ onToggleShowCode={() => setShowCode((v) => !v)}+ />+ </VerticalLayoutWrapper>+ );+};++const ActionButtons: React.FC<{+ canShowCode: boolean;+ showCode: boolean;+ onToggleShowCode: () => void;+}> = ({ canShowCode, showCode, onToggleShowCode }) => {+ const [filename] = useFilename();+ const handleDownloadAsPNG = async () => {+ const app = document.getElementById("App");+ if (!app) {+ return;+ }+ await downloadHTMLAsImage(app, filename || "screenshot.png");+ };++ const handleDownloadAsHTML = async () => {+ const app = document.getElementById("App");+ if (!app) {+ return;+ }+ await downloadAsHTML({ filename: filename || "app" });+ };++ return (+ <div+ className={cn(+ "right-0 top-0 z-50 m-4 no-print flex gap-2",+ // If the notebook is static, we have a banner at the top, so+ // we can't use fixed positioning. Ideally this is sticky, but the+ // current dom structure makes that difficult.+ isStaticNotebook() ? "absolute" : "fixed",+ )}+ >{canShowCode && (- <div- className={cn(- "right-0 top-0 z-50 m-4",- // If the notebook is static, we have a banner at the top, so- // we can't use fixed positioning. Ideally this is sticky, but the- // current dom structure makes that difficult.- isStaticNotebook() ? "absolute" : "fixed",- )}+ <Button+ variant="secondary"+ onClick={onToggleShowCode}+ size="xs"+ data-testid="show-code">- <Button- variant="secondary"- onClick={() => setShowCode((prev) => !prev)}- size="sm"- data-testid="show-code"- >- <Code2Icon className="w-4 h-4 mr-2" />- {showCode ? "Hide code" : "Show code"}- </Button>- </div>+ <Code2Icon className="w-4 h-4 mr-2" />+ {showCode ? "Hide code" : "Show code"}+ </Button>)}- </VerticalLayoutWrapper>+ <DropdownMenu modal={false}>+ <DropdownMenuTrigger asChild={true}>+ <Button variant="secondary" size="xs" data-testid="download-as">+ <Download className="w-4 h-4 mr-2" />+ Download as+ <ChevronDown className="w-4 h-4 ml-2" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="no-print w-[220px]">+ <DropdownMenuItem onSelect={handleDownloadAsHTML}>+ <FolderDownIcon className="mr-2" size={14} strokeWidth={1.5} />+ Download as HTML+ </DropdownMenuItem>+ <DropdownMenuItem onSelect={handleDownloadAsPNG}>+ <ImageIcon className="mr-2" size={14} strokeWidth={1.5} />+ Download as PNG+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>);};diff --git a/frontend/src/components/static-html/static-banner.tsx b/frontend/src/components/static-html/static-banner.tsxindex 13d942fcfc..4d7352766d 100644--- a/frontend/src/components/static-html/static-banner.tsx+++ b/frontend/src/components/static-html/static-banner.tsx@@ -31,7 +31,7 @@ export const StaticBanner: React.FC = () => {}return (- <div className="px-4 py-2 bg-[var(--sky-2)] border-b border-[var(--sky-7)] text-md text-[var(--sky-11)] font-semibold flex justify-between items-center gap-4">+ <div className="px-4 py-2 bg-[var(--sky-2)] border-b border-[var(--sky-7)] text-md text-[var(--sky-11)] font-semibold flex justify-between items-center gap-4 no-print"><span>This is a static Python notebook built using{" "}<adiff --git a/marimo/_server/api/endpoints/export.py b/marimo/_server/api/endpoints/export.pyindex 190b867f73..e0235aac13 100644--- a/marimo/_server/api/endpoints/export.py+++ b/marimo/_server/api/endpoints/export.py@@ -12,6 +12,7 @@ from marimo._server.api.deps import AppStatefrom marimo._server.api.status import HTTPStatusfrom marimo._server.api.utils import parse_requestfrom marimo._server.export.exporter import Exporter+from marimo._server.model import SessionModefrom marimo._server.models.export import (ExportAsHTMLRequest,ExportAsMarkdownRequest,@@ -29,7 +30,7 @@ router = APIRouter()@router.post("/html")-@requires("edit")+@requires("read")async def export_as_html(*,request: Request,@@ -41,6 +42,10 @@ async def export_as_html(body = await parse_request(request, cls=ExportAsHTMLRequest)session = app_state.require_current_session()+ # Only include the code and console if we are in edit mode+ if app_state.mode != SessionMode.EDIT:+ body.include_code = False+html, filename = Exporter().export_as_html(file_manager=session.app_file_manager,session_view=session.session_view,diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.pyindex fe6d9f738d..a92c71fbf3 100644--- a/marimo/_server/export/exporter.py+++ b/marimo/_server/export/exporter.py@@ -8,7 +8,7 @@ import osfrom typing import castfrom marimo import __version__-from marimo._ast.cell import Cell, CellImpl+from marimo._ast.cell import Cell, CellConfig, CellImplfrom marimo._config.config import (DEFAULT_CONFIG,DisplayConfig,@@ -38,6 +38,7 @@ root = os.path.realpath(str(import_files("marimo").joinpath("_static")))class Exporter:def export_as_html(self,+ *,file_manager: AppFileManager,session_view: SessionView,display_config: DisplayConfig,@@ -69,12 +70,18 @@ class Exporter:config = _deep_copy(DEFAULT_CONFIG)config["display"] = display_config- code = file_manager.to_code() if request.include_code else ""- codes = (- file_manager.app.cell_manager.codes()- if request.include_code- else ["" for _ in cell_ids]- )+ # code and console outputs are grouped together, but+ # we can split them up in the future if desired.+ if request.include_code:+ code = file_manager.to_code()+ codes = file_manager.app.cell_manager.codes()+ configs = file_manager.app.cell_manager.configs()+ console_outputs = session_view.get_cell_console_outputs(cell_ids)+ else:+ code = ""+ codes = ["" for _ in cell_ids]+ configs = [CellConfig() for _ in cell_ids]+ console_outputs = {}html = static_notebook_template(html=index_html,@@ -86,11 +93,9 @@ class Exporter:cell_ids=cell_ids,cell_names=list(file_manager.app.cell_manager.names()),cell_codes=list(codes),- cell_configs=list(file_manager.app.cell_manager.configs()),+ cell_configs=list(configs),cell_outputs=session_view.get_cell_outputs(cell_ids),- cell_console_outputs=session_view.get_cell_console_outputs(- cell_ids- ),+ cell_console_outputs=console_outputs,files=files,asset_url=request.asset_url,)diff --git a/tests/_server/api/endpoints/test_export.py b/tests/_server/api/endpoints/test_export.pyindex 154968bf3a..3b11576255 100644--- a/tests/_server/api/endpoints/test_export.py+++ b/tests/_server/api/endpoints/test_export.py@@ -4,8 +4,9 @@ from __future__ import annotationsfrom typing import TYPE_CHECKINGfrom marimo import __version__+from marimo._output.utils import uri_encode_componentfrom tests._server.conftest import get_session_manager-from tests._server.mocks import token_header, with_session+from tests._server.mocks import token_header, with_read_session, with_sessionfrom tests.mocks import snapshotterif TYPE_CHECKING:@@ -19,6 +20,8 @@ HEADERS = {**token_header("fake-token"),}+CODE = uri_encode_component("import marimo as mo")+@with_session(SESSION_ID)def test_export_html(client: TestClient) -> None:@@ -36,6 +39,7 @@ def test_export_html(client: TestClient) -> None:)body = response.textassert '<marimo-code hidden=""></marimo-code>' not in body+ assert CODE in body@with_session(SESSION_ID)@@ -75,6 +79,43 @@ def test_export_html_no_code(client: TestClient) -> None:)body = response.textassert '<marimo-code hidden=""></marimo-code>' in body+ assert CODE not in body+++# Read session forces empty code+@with_read_session(SESSION_ID)+def test_export_html_no_code_in_read(client: TestClient) -> None:+ session = get_session_manager(client).get_session(SESSION_ID)+ assert session+ session.app_file_manager.filename = "test.py"+ response = client.post(+ "/api/export/html",+ headers=HEADERS,+ json={+ "download": False,+ "files": [],+ "include_code": True,+ },+ )+ body = response.text+ assert '<marimo-code hidden=""></marimo-code>' in body+ assert CODE not in body++ session = get_session_manager(client).get_session(SESSION_ID)+ assert session+ session.app_file_manager.filename = "test.py"+ response = client.post(+ "/api/export/html",+ headers=HEADERS,+ json={+ "download": False,+ "files": [],+ "include_code": False,+ },+ )+ body = response.text+ assert '<marimo-code hidden=""></marimo-code>' in body+ assert CODE not in body@with_session(SESSION_ID)@@ -102,3 +143,23 @@ def test_export_markdown(client: TestClient) -> None:assert response.status_code == 200assert f"marimo-version: {__version__}" in response.textassert "```{.python.marimo}" in response.text+++@with_read_session(SESSION_ID)+def test_other_exports_dont_work_in_read(client: TestClient) -> None:+ response = client.post(+ "/api/export/markdown",+ headers=HEADERS,+ json={+ "download": False,+ },+ )+ assert response.status_code == 401+ response = client.post(+ "/api/export/script",+ headers=HEADERS,+ json={+ "download": False,+ },+ )+ assert response.status_code == 401