Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: add readCode API endpoint, download code in static export (#412)

Myles Scolnickbb4859aa748c
diff --git a/frontend/src/components/data-table/download-actions.tsx b/frontend/src/components/data-table/download-actions.tsx
index 653d96bd34..48254f27a4 100644
--- a/frontend/src/components/data-table/download-actions.tsx
+++ b/frontend/src/components/data-table/download-actions.tsx
@@ -9,6 +9,7 @@ import {
DropdownMenuTrigger,
} from "../ui/dropdown-menu";
import { toast } from "../ui/use-toast";
+import { downloadByURL } from "@/utils/download";
export interface DownloadActionProps {
downloadAs: (req: { format: "csv" | "json" }) => Promise<string>;
@@ -48,12 +49,7 @@ export const DownloadAs: React.FC<DownloadActionProps> = (props) => {
if (!downloadUrl) {
return;
}
- const link = document.createElement("a");
- link.href = downloadUrl;
- link.setAttribute("download", "download");
- document.body.append(link);
- link.click();
- link.remove();
+ downloadByURL(downloadUrl, "download");
}}
>
{option.label}
diff --git a/frontend/src/components/editor/RecoveryButton.tsx b/frontend/src/components/editor/RecoveryButton.tsx
index b8c71a636f..6b0aeff2ee 100644
--- a/frontend/src/components/editor/RecoveryButton.tsx
+++ b/frontend/src/components/editor/RecoveryButton.tsx
@@ -12,6 +12,7 @@ import {
DialogFooter,
DialogTitle,
} from "../ui/dialog";
+import { downloadBlob } from "@/utils/download";
const RecoveryModal = (props: {
proposedName: string;
@@ -19,12 +20,10 @@ const RecoveryModal = (props: {
closeModal: () => void;
}): JSX.Element => {
const downloadRecoveryFile = () => {
- const link = document.createElement("a");
- link.download = `${props.proposedName}.json`;
- link.href = window.URL.createObjectURL(
- new Blob([props.getCellsAsJSON()], { type: "text/plain" })
+ downloadBlob(
+ new Blob([props.getCellsAsJSON()], { type: "text/plain" }),
+ `${props.proposedName}.json`
);
- link.click();
};
// NB: we use markdown class to have sane styling for list, paragraph
diff --git a/frontend/src/components/editor/actions/useNotebookActions.tsx b/frontend/src/components/editor/actions/useNotebookActions.tsx
index a1f994181c..a7d200ec17 100644
--- a/frontend/src/components/editor/actions/useNotebookActions.tsx
+++ b/frontend/src/components/editor/actions/useNotebookActions.tsx
@@ -21,7 +21,7 @@ import { saveCellConfig } from "@/core/network/requests";
import { Objects } from "@/utils/objects";
import { ActionButton } from "./types";
import { downloadAsHTML } from "@/core/static/download-html";
-import { getFeatureFlag } from "@/core/config/feature-flag";
+import { toast } from "@/components/ui/use-toast";
export function useNotebookActions(opts: { filename?: string | null }) {
const { filename } = opts;
@@ -50,10 +50,16 @@ export function useNotebookActions(opts: { filename?: string | null }) {
{
icon: <FolderDownIcon size={14} strokeWidth={1.5} />,
label: "Export as HTML",
- hidden: !getFeatureFlag("static_export"),
handle: async () => {
- await downloadAsHTML({ filename: filename || "notebook.html" });
- return;
+ if (!filename) {
+ toast({
+ variant: "danger",
+ title: "Error",
+ description: "Notebooks must be named to be exported.",
+ });
+ return;
+ }
+ await downloadAsHTML({ filename });
},
},
{
diff --git a/frontend/src/components/static-html/static-banner.tsx b/frontend/src/components/static-html/static-banner.tsx
index 471a70635f..5e2d4c7582 100644
--- a/frontend/src/components/static-html/static-banner.tsx
+++ b/frontend/src/components/static-html/static-banner.tsx
@@ -1,6 +1,12 @@
/* Copyright 2023 Marimo. All rights reserved. */
import { isStaticNotebook } from "@/core/static/static-state";
import React from "react";
+import { Button } from "../ui/button";
+import { toast } from "../ui/use-toast";
+import { getMarimoCode } from "@/core/dom/marimo-tag";
+import { downloadBlob } from "@/utils/download";
+import { getFilenameFromDOM } from "@/core/dom/htmlUtils";
+import { CopyIcon, DownloadIcon } from "lucide-react";
export const StaticBanner: React.FC = () => {
if (!isStaticNotebook()) {
@@ -8,8 +14,41 @@ export const StaticBanner: React.FC = () => {
}
return (
- <div className="px-4 py-2 bg-[var(--sky-2)] border-b border-[var(--sky-7)] text-sm text-[var(--sky-11)] font-semibold">
- This is a static notebook. Any interactive features will not work.
+ <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">
+ <span>
+ This is a static notebook. Some interactive features will not work,
+ however you can download the code and run it locally.
+ </span>
+ <span className="flex flex-wrap justify-end">
+ <Button
+ className="ml-2 flex-shrink-0"
+ variant="secondary"
+ size="xs"
+ onClick={() => {
+ const code = getMarimoCode();
+ window.navigator.clipboard.writeText(code);
+ toast({ title: "Copied to clipboard" });
+ }}
+ >
+ <CopyIcon className="w-4 h-4 mr-1" />
+ Copy code
+ </Button>
+ <Button
+ className="ml-2 flex-shrink-0"
+ variant="secondary"
+ size="xs"
+ onClick={() => {
+ const code = getMarimoCode();
+ downloadBlob(
+ new Blob([code], { type: "text/plain" }),
+ getFilenameFromDOM() || "app.py"
+ );
+ }}
+ >
+ <DownloadIcon className="w-4 h-4 mr-1" />
+ Download code
+ </Button>
+ </span>
</div>
);
};
diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.ts
index d80849c74d..7605443ca5 100644
--- a/frontend/src/core/config/config-schema.ts
+++ b/frontend/src/core/config/config-schema.ts
@@ -38,7 +38,6 @@ export const UserConfigSchema = z
experimental: z
.object({
layouts: z.boolean().optional(),
- static_export: z.boolean().optional(),
})
// Pass through so that we don't remove any extra keys that the user has added.
.passthrough()
diff --git a/frontend/src/core/config/feature-flag.ts b/frontend/src/core/config/feature-flag.ts
index a12bf4821e..f14ac4fd81 100644
--- a/frontend/src/core/config/feature-flag.ts
+++ b/frontend/src/core/config/feature-flag.ts
@@ -7,15 +7,10 @@ export interface ExperimentalFeatures {
* Allows the user to switch between different layouts.
*/
layouts: boolean;
- /**
- * Allows the user to export the notebook as a static HTML file.
- */
- static_export: boolean;
}
const defaultValues: ExperimentalFeatures = {
layouts: false,
- static_export: false,
};
export function getFeatureFlag<T extends keyof ExperimentalFeatures>(
diff --git a/frontend/src/core/dom/marimo-tag.ts b/frontend/src/core/dom/marimo-tag.ts
index 324fade49c..2ac0d35cd8 100644
--- a/frontend/src/core/dom/marimo-tag.ts
+++ b/frontend/src/core/dom/marimo-tag.ts
@@ -18,6 +18,13 @@ export function getRawMarimoUserConfig(): string {
return getMarimoDOMValue("marimo-user-config", "config");
}
+export function getMarimoCode(): string {
+ const tag = document.querySelector("marimo-code");
+ invariant(tag, "internal-error: marimo-code not tag not found");
+ const inner = tag.innerHTML;
+ return decodeURIComponent(inner).trim();
+}
+
function getMarimoDOMValue(tagName: string, key: string) {
const tag = document.querySelector(tagName);
invariant(
diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.ts
index f1c23f8056..0c8a532c23 100644
--- a/frontend/src/core/network/requests.ts
+++ b/frontend/src/core/network/requests.ts
@@ -129,6 +129,9 @@ function createNetworkRequests(): EditRequests & RunRequests {
sendFunctionRequest: (request) => {
return API.post<SendFunctionRequest>("/kernel/function_call/", request);
},
+ readCode: () => {
+ return API.post<{}, { contents: string }>("/kernel/read_code/", {});
+ },
};
}
@@ -148,4 +151,5 @@ export const {
saveAppConfig,
saveCellConfig,
sendFunctionRequest,
+ readCode,
} = isStaticNotebook() ? createStaticRequests() : createNetworkRequests();
diff --git a/frontend/src/core/network/static-requests.ts b/frontend/src/core/network/static-requests.ts
index 63d54abe1b..625f253fbf 100644
--- a/frontend/src/core/network/static-requests.ts
+++ b/frontend/src/core/network/static-requests.ts
@@ -48,5 +48,6 @@ export function createStaticRequests(): EditRequests & RunRequests {
saveUserConfig: throwNotInEditMode,
saveAppConfig: throwNotInEditMode,
saveCellConfig: throwNotInEditMode,
+ readCode: throwNotInEditMode,
};
}
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index 53eae05dd6..892e49857c 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -127,4 +127,5 @@ export interface EditRequests {
saveUserConfig: (request: SaveUserConfigRequest) => Promise<null>;
saveAppConfig: (request: SaveAppConfigRequest) => Promise<null>;
saveCellConfig: (request: SaveCellConfigRequest) => Promise<null>;
+ readCode: () => Promise<{ contents: string }>;
}
diff --git a/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap b/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap
index f372a9fffb..4f19a4d87b 100644
--- a/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap
+++ b/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap
@@ -82,6 +82,10 @@ exports[`download-html > should construct html correctly 1`] = `
};
</script>
+ <marimo-code hidden=\\"\\">
+ import%20marimo%20as%20mo%0A%0Amo.html('%3Ch1%3Ehello%3C%2Fh1%3E')
+ </marimo-code>
+
<script
type=\\"module\\"
crossorigin=\\"anonymous\\"
diff --git a/frontend/src/core/static/__tests__/download-html.test.ts b/frontend/src/core/static/__tests__/download-html.test.ts
index 8195651b81..3b29e18da9 100644
--- a/frontend/src/core/static/__tests__/download-html.test.ts
+++ b/frontend/src/core/static/__tests__/download-html.test.ts
@@ -84,6 +84,7 @@ describe("download-html", () => {
base64: "data:text/plain;base64,bm90ZQo=" as Base64String,
},
},
+ code: "import marimo as mo\n\nmo.html('<h1>hello</h1>')",
assetUrl: `https://cdn.jsdelivr.net/npm/@marimo-team/frontend@${version}/dist`,
filename: "app",
existingDocument: new JSDOM(DOC).window.document,
diff --git a/frontend/src/core/static/download-html.ts b/frontend/src/core/static/download-html.ts
index 902fb67616..1086059ce3 100644
--- a/frontend/src/core/static/download-html.ts
+++ b/frontend/src/core/static/download-html.ts
@@ -5,6 +5,9 @@ import { getMarimoVersion } from "../dom/marimo-tag";
import { downloadVirtualFiles } from "./files";
import { StaticVirtualFiles } from "./types";
import { serializeJsonToBase64 } from "@/utils/json/base64";
+import { readCode } from "../network/requests";
+import { downloadBlob } from "@/utils/download";
+import { toast } from "@/components/ui/use-toast";
// For Testing:
// Flip this to `true` to use local assets instead of CDN
@@ -14,7 +17,7 @@ const ENABLE_LOCAL_ASSETS = false;
/**
* Downloads the current notebook as an HTML file.
*/
-export async function downloadAsHTML(opts: { filename?: string }) {
+export async function downloadAsHTML(opts: { filename: string }) {
const { filename } = opts;
const notebook = getNotebook();
const version = getMarimoVersion();
@@ -26,6 +29,15 @@ export async function downloadAsHTML(opts: { filename?: string }) {
? window.location.origin
: `https://cdn.jsdelivr.net/npm/@marimo-team/frontend@${version}/dist`;
+ const codeResponse = await readCode().catch((error) => {
+ toast({
+ variant: "danger",
+ title: "Error",
+ description: error.message,
+ });
+ throw error;
+ });
+
const html = constructHTML({
notebookState: notebook,
version: version,
@@ -33,13 +45,13 @@ export async function downloadAsHTML(opts: { filename?: string }) {
filename: filename || "notebook",
existingDocument: document,
files: await downloadVirtualFiles(),
+ code: codeResponse.contents,
});
- const url = URL.createObjectURL(new Blob([html], { type: "text/html" }));
- const a = document.createElement("a");
- a.href = url;
- a.download = filename ? `${filename}.html` : "notebook.html";
- a.click();
+ downloadBlob(
+ new Blob([html], { type: "text/html" }),
+ filename ? `${filename}.html` : "notebook.html"
+ );
}
/**
@@ -52,8 +64,10 @@ export function constructHTML(opts: {
filename: string;
files: StaticVirtualFiles;
existingDocument: Document;
+ code: string;
}) {
- const { version, notebookState, assetUrl, existingDocument, files } = opts;
+ const { version, notebookState, assetUrl, existingDocument, files, code } =
+ opts;
const staticHead = existingDocument.head.cloneNode(true) as HTMLHeadElement;
@@ -101,6 +115,10 @@ export function constructHTML(opts: {
window.__MARIMO_STATIC__.assetUrl = "${assetUrl}";
window.__MARIMO_STATIC__.files = ${JSON.stringify(files)};
</script>
+
+ <marimo-code hidden="">
+ ${encodeURIComponent(code)}
+ </marimo-code>
</body>
</html>
`;
diff --git a/frontend/src/utils/download.ts b/frontend/src/utils/download.ts
index 527586f802..ed17d3011a 100644
--- a/frontend/src/utils/download.ts
+++ b/frontend/src/utils/download.ts
@@ -11,13 +11,10 @@ export async function downloadHTMLAsImage(
document.body.classList.add("printing");
// Get screenshot
const dataUrl = await toPng(element);
- // Create an anchor element
- const a = document.createElement("a");
- // Create a PNG image from the canvas
- a.href = dataUrl;
- a.download = filename.endsWith(".png") ? filename : `${filename}.png`;
- // Download the image
- a.click();
+ downloadByURL(
+ dataUrl,
+ filename.endsWith(".png") ? filename : `${filename}.png`
+ );
} catch {
toast({
title: "Error",
@@ -29,3 +26,16 @@ export async function downloadHTMLAsImage(
document.body.classList.remove("printing");
}
}
+
+export function downloadByURL(url: string, filename: string) {
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = filename;
+ a.click();
+ a.remove();
+}
+
+export function downloadBlob(blob: Blob, filename: string) {
+ const url = URL.createObjectURL(blob);
+ downloadByURL(url, filename);
+}
diff --git a/marimo/_server/api/__init__.py b/marimo/_server/api/__init__.py
index 5f062402a8..d9f3daac71 100644
--- a/marimo/_server/api/__init__.py
+++ b/marimo/_server/api/__init__.py
@@ -7,6 +7,7 @@ __all__ = [
"FunctionHandler",
"InstantiateHandler",
"InterruptHandler",
+ "ReadCodeHandler",
"RenameHandler",
"RunHandler",
"SaveAppConfigurationHandler",
@@ -26,6 +27,7 @@ from marimo._server.api.format import FormatHandler
from marimo._server.api.function_call import FunctionHandler
from marimo._server.api.instantiate import InstantiateHandler
from marimo._server.api.interrupt import InterruptHandler
+from marimo._server.api.read_code import ReadCodeHandler
from marimo._server.api.rename import RenameHandler
from marimo._server.api.run import RunHandler
from marimo._server.api.save import SaveHandler
diff --git a/marimo/_server/api/read_code.py b/marimo/_server/api/read_code.py
new file mode 100644
index 0000000000..928ec9aafd
--- /dev/null
+++ b/marimo/_server/api/read_code.py
@@ -0,0 +1,31 @@
+# Copyright 2023 Marimo. All rights reserved.
+from __future__ import annotations
+
+import tornado.web
+
+from marimo._server import sessions
+from marimo._server.api.status import HTTPStatus
+from marimo._server.api.validated_handler import ValidatedHandler
+
+
+class ReadCodeHandler(ValidatedHandler):
+ """Handler for reading code from the server."""
+
+ @sessions.requires_edit
+ def post(self) -> None:
+ mgr = sessions.get_manager()
+ if mgr.filename is None:
+ raise tornado.web.HTTPError(
+ HTTPStatus.METHOD_NOT_ALLOWED,
+ reason="Cannot read code from an unnamed notebook",
+ )
+ try:
+ with open(mgr.filename, "r", encoding="utf-8") as f:
+ contents = f.read().strip()
+ except Exception as e:
+ raise tornado.web.HTTPError(
+ HTTPStatus.SERVER_ERROR,
+ reason="Failed to read file: {0}".format(str(e)),
+ ) from e
+
+ self.write({"contents": contents})
diff --git a/marimo/_server/server.py b/marimo/_server/server.py
index 8cb9fbb49c..3f959350d4 100644
--- a/marimo/_server/server.py
+++ b/marimo/_server/server.py
@@ -212,6 +212,10 @@ def construct_app(
r"/api/kernel/save_app_config/",
api.SaveAppConfigurationHandler,
),
+ (
+ r"/api/kernel/read_code/",
+ api.ReadCodeHandler,
+ ),
(
r"/@file/(.*)",
api.VirtualFileHandler,