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.

improvement: move html export logic to python code (#1135)

Myles Scolnickff54828f672f
diff --git a/frontend/src/components/static-html/share-modal.tsx b/frontend/src/components/static-html/share-modal.tsx
index 2018f007ef..1d520df155 100644
--- a/frontend/src/components/static-html/share-modal.tsx
+++ b/frontend/src/components/static-html/share-modal.tsx
@@ -13,8 +13,9 @@ import { Input } from "../ui/input";
import { CopyIcon } from "lucide-react";
import { Events } from "@/utils/events";
import { Tooltip } from "../ui/tooltip";
-import { createStaticHTMLNotebook } from "@/core/static/download-html";
import { Constants } from "@/core/constants";
+import { exportHTML } from "@/core/network/requests";
+import { VirtualFileTracker } from "@/core/static/virtual-file-tracker";
const BASE_URL = "https://static.marimo.app";
@@ -36,7 +37,11 @@ export const ShareStaticNotebookModal: React.FC<{
e.preventDefault();
onClose();
- const html = await createStaticHTMLNotebook();
+ const html = await exportHTML({
+ download: false,
+ includeCode: true,
+ files: VirtualFileTracker.INSTANCE.filenames(),
+ });
const prevToast = toast({
title: "Uploading static notebook...",
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index f83c7ab7cd..c03fec6d66 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -29,7 +29,7 @@ import { EditorView } from "@codemirror/view";
import { splitAtom, selectAtom } from "jotai/utils";
import { isStaticNotebook, parseStaticState } from "../static/static-state";
import { CellLog, getCellLogsForMessage } from "./logs";
-import { deserializeBase64ToJson } from "@/utils/json/base64";
+import { deserializeBase64, deserializeJson } from "@/utils/json/base64";
import { historyField } from "@codemirror/commands";
import { clamp } from "@/utils/math";
import { LayoutState } from "../layout/layout";
@@ -86,17 +86,44 @@ export interface LastSavedNotebook {
*/
function initialNotebookState(): NotebookState {
if (isStaticNotebook()) {
- const notebookState = parseStaticState();
+ const {
+ cellCodes,
+ cellConfigs,
+ cellConsoleOutputs,
+ cellIds,
+ cellNames,
+ cellOutputs,
+ } = parseStaticState();
+ const cellData: Record<CellId, CellData> = {};
+ const cellRuntime: Record<CellId, CellRuntimeState> = {};
+ for (const [i, cellId] of cellIds.entries()) {
+ const name = cellNames[i];
+ const code = cellCodes[i];
+ const config = cellConfigs[i];
+ const outputs = cellConsoleOutputs[cellId] || [];
+ const output = cellOutputs[cellId];
+ cellData[cellId] = {
+ id: cellId,
+ name: deserializeBase64(name),
+ code: deserializeBase64(code),
+ edited: false,
+ lastCodeRun: null,
+ config: deserializeJson(deserializeBase64(config)),
+ serializedEditorState: null,
+ };
+ cellRuntime[cellId] = {
+ ...createCellRuntimeState(),
+ output: output ? deserializeJson(deserializeBase64(output)) : null,
+ consoleOutputs: outputs.map((output) =>
+ deserializeJson(deserializeBase64(output)),
+ ),
+ };
+ }
+
return {
- cellIds: notebookState.cellIds,
- cellData: Objects.mapValues(
- notebookState.cellData,
- deserializeBase64ToJson<CellData>,
- ),
- cellRuntime: Objects.mapValues(
- notebookState.cellRuntime,
- deserializeBase64ToJson<CellRuntimeState>,
- ),
+ cellIds: cellIds,
+ cellData: cellData,
+ cellRuntime: cellRuntime,
cellHandles: {},
history: [],
scrollKey: null,
diff --git a/frontend/src/core/network/api.ts b/frontend/src/core/network/api.ts
index 80193c6ad2..22c8103aeb 100644
--- a/frontend/src/core/network/api.ts
+++ b/frontend/src/core/network/api.ts
@@ -40,7 +40,7 @@ export const API = {
) {
return response.json() as RESP;
} else {
- return null as RESP;
+ return response.text() as unknown as RESP;
}
})
.catch((error) => {
diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.ts
index cdb1a33750..96191a6685 100644
--- a/frontend/src/core/network/requests-network.ts
+++ b/frontend/src/core/network/requests-network.ts
@@ -32,6 +32,7 @@ import {
WorkspaceFilesResponse,
RunningNotebooksResponse,
ShutdownSessionRequest,
+ ExportHTMLRequest,
} from "./types";
import { invariant } from "@/utils/invariant";
@@ -209,5 +210,14 @@ export function createNetworkRequests(): EditRequests & RunRequests {
shutdownSession: (request: ShutdownSessionRequest) => {
return API.post("/home/shutdown_session", request);
},
+ exportHTML: async (request: ExportHTMLRequest) => {
+ if (
+ process.env.NODE_ENV === "development" ||
+ process.env.NODE_ENV === "test"
+ ) {
+ request.assetUrl = window.location.origin;
+ }
+ return API.post("/export/html", request);
+ },
};
}
diff --git a/frontend/src/core/network/requests-static.ts b/frontend/src/core/network/requests-static.ts
index fa0ea7f2d5..710ca691a4 100644
--- a/frontend/src/core/network/requests-static.ts
+++ b/frontend/src/core/network/requests-static.ts
@@ -63,5 +63,6 @@ export function createStaticRequests(): EditRequests & RunRequests {
getWorkspaceFiles: throwNotInEditMode,
getRunningNotebooks: throwNotInEditMode,
shutdownSession: throwNotInEditMode,
+ exportHTML: throwNotInEditMode,
};
}
diff --git a/frontend/src/core/network/requests-toasting.ts b/frontend/src/core/network/requests-toasting.ts
index 914bfb515c..a5bd7c7fd3 100644
--- a/frontend/src/core/network/requests-toasting.ts
+++ b/frontend/src/core/network/requests-toasting.ts
@@ -39,6 +39,7 @@ export function createErrorToastingRequests(
getWorkspaceFiles: "Failed to get workspace files",
getRunningNotebooks: "Failed to get running notebooks",
shutdownSession: "Failed to shutdown session",
+ exportHTML: "Failed to export HTML",
};
const handlers = {} as EditRequests & RunRequests;
diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.ts
index b0c8c2048d..503ffd7004 100644
--- a/frontend/src/core/network/requests.ts
+++ b/frontend/src/core/network/requests.ts
@@ -47,4 +47,5 @@ export const {
getWorkspaceFiles,
getRunningNotebooks,
shutdownSession,
+ exportHTML,
} = getRequest();
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index 80f7c2bf8f..aeb755fe9b 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -196,6 +196,13 @@ export interface ShutdownSessionRequest {
sessionId: SessionId;
}
+export interface ExportHTMLRequest {
+ assetUrl?: string;
+ includeCode: boolean;
+ files: string[];
+ download: boolean;
+}
+
/**
* Requests sent to the BE during run/edit mode.
*/
@@ -250,6 +257,7 @@ export interface EditRequests {
shutdownSession: (
request: ShutdownSessionRequest,
) => Promise<RunningNotebooksResponse>;
+ exportHTML: (request: ExportHTMLRequest) => Promise<string>;
}
export type RequestKey = keyof (EditRequests & RunRequests);
diff --git a/frontend/src/core/pyodide/bridge.ts b/frontend/src/core/pyodide/bridge.ts
index e4a0bf6dc5..bc6a8aa3d9 100644
--- a/frontend/src/core/pyodide/bridge.ts
+++ b/frontend/src/core/pyodide/bridge.ts
@@ -5,6 +5,7 @@ import { CellId } from "../cells/ids";
import {
CodeCompletionRequest,
EditRequests,
+ ExportHTMLRequest,
FileCreateRequest,
FileDeleteRequest,
FileDetailsResponse,
@@ -362,6 +363,20 @@ export class PyodideBridge implements RunRequests, EditRequests {
return response as FileDetailsResponse;
};
+ exportHTML = async (request: ExportHTMLRequest): Promise<string> => {
+ if (
+ process.env.NODE_ENV === "development" ||
+ process.env.NODE_ENV === "test"
+ ) {
+ request.assetUrl = window.location.origin;
+ }
+ const response = await this.rpc.proxy.request.bridge({
+ functionName: "export_html",
+ payload: request,
+ });
+ return response as string;
+ };
+
getRecentFiles = throwNotImplemented;
getWorkspaceFiles = throwNotImplemented;
getRunningNotebooks = throwNotImplemented;
diff --git a/frontend/src/core/pyodide/worker/types.ts b/frontend/src/core/pyodide/worker/types.ts
index 9f842d224d..1fd010ed4c 100644
--- a/frontend/src/core/pyodide/worker/types.ts
+++ b/frontend/src/core/pyodide/worker/types.ts
@@ -2,6 +2,7 @@
import type { PyodideInterface } from "pyodide";
import type {
CodeCompletionRequest,
+ ExportHTMLRequest,
FileCreateRequest,
FileDeleteRequest,
FileDetailsResponse,
@@ -65,6 +66,7 @@ export interface RawBridge {
load_packages(request: string): Promise<string>;
read_file(request: string): Promise<string>;
set_interrupt_buffer(request: Uint8Array): Promise<string>;
+ export_html(request: ExportHTMLRequest): Promise<string>;
}
export type SerializedBridge = {
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
deleted file mode 100644
index 6c95d736e4..0000000000
--- a/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap
+++ /dev/null
@@ -1,113 +0,0 @@
-// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
-
-exports[`download-html > should construct html correctly 1`] = `
-"<!doctype html>
-<html>
- <head>
- <base href="/" />
-
- <meta charset="utf-8" />
- <link
- rel="icon"
- href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/favicon.ico"
- crossorigin="anonymous"
- />
- <link
- rel="preload"
- href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/gradient-6c6e9bb3.png"
- as="image"
- crossorigin="anonymous"
- />
- <link
- rel="preload"
- href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/noise-b5c8172e.png"
- as="image"
- crossorigin="anonymous"
- />
-
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <meta name="theme-color" content="#000000" />
- <meta name="description" content="a marimo app" />
- <link
- rel="apple-touch-icon"
- href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/apple-touch-icon.png"
- crossorigin="anonymous"
- />
- <link
- rel="manifest"
- href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/manifest.json"
- crossorigin="anonymous"
- />
- <script data-marimo="true">
- function __resizeIframe(obj) {
- // Resize the iframe to the height of the content
- obj.style.height =
- obj.contentWindow.document.documentElement.scrollHeight + "px";
-
- // Resize the iframe when the content changes
- const resizeObserver = new ResizeObserver((entries) => {
- obj.style.height =
- obj.contentWindow.document.documentElement.scrollHeight + "px";
- });
- resizeObserver.observe(obj.contentWindow.document.body);
- }
- </script>
-
- <link rel="preconnect" href="https://fonts.googleapis.com" />
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="" />
- <link
- href="https://fonts.googleapis.com/css2?family=Fira+Mono:wght@400;500;700&amp;family=Lora&amp;family=PT+Sans:wght@400;700&amp;display=swap"
- rel="stylesheet"
- />
- </head>
-
- <body>
- <div id="root"></div>
- <marimo-mode data-mode="read" hidden=""></marimo-mode>
- <marimo-filename hidden="">app.py</marimo-filename>
- <marimo-version data-version="0.1.44" hidden=""></marimo-version>
- <marimo-user-config
- data-config='{"display": {"theme": "light"}, "keymap": {"preset": "default"}, "save": {"autosave": "after_delay", "format_on_save": true, "autosave_delay": 1000}, "server": {"browser": "default"}, "experimental": {"layouts": true, "theming": true}, "runtime": {"auto_instantiate": true}, "completion": {"activate_on_typing": true, "copilot": true}}'
- hidden=""
- ></marimo-user-config>
- <marimo-app-config
- data-config='{"width": "full", "layout_file": null}'
- hidden=""
- ></marimo-app-config>
- <script data-marimo="true">
- window.__MARIMO_STATIC__ = {};
- window.__MARIMO_STATIC__.version = "0.1.44";
- window.__MARIMO_STATIC__.notebookState = {
- cellIds: ["1"],
- cellData: {
- 1: "JTdCJTIyaWQlMjIlM0ElMjIxJTIyJTJDJTIyY29uZmlnJTIyJTNBJTdCJTIyaGlkZV9jb2RlJTIyJTNBdHJ1ZSU3RCUyQyUyMm5hbWUlMjIlM0ElMjJjZWxsJTIyJTJDJTIyY29kZSUyMiUzQSUyMmNvZGUlMjIlMkMlMjJlZGl0ZWQlMjIlM0FmYWxzZSUyQyUyMmxhc3RDb2RlUnVuJTIyJTNBbnVsbCUyQyUyMnNlcmlhbGl6ZWRFZGl0b3JTdGF0ZSUyMiUzQW51bGwlN0Q=",
- },
- cellRuntime: {
- 1: "JTdCJTIyb3V0bGluZSUyMiUzQW51bGwlMkMlMjJvdXRwdXQlMjIlM0FudWxsJTJDJTIyY29uc29sZU91dHB1dHMlMjIlM0ElNUIlNUQlMkMlMjJzdGF0dXMlMjIlM0ElMjJpZGxlJTIyJTJDJTIyaW50ZXJydXB0ZWQlMjIlM0FmYWxzZSUyQyUyMmVycm9yZWQlMjIlM0FmYWxzZSUyQyUyMnN0b3BwZWQlMjIlM0FmYWxzZSUyQyUyMnJ1bkVsYXBzZWRUaW1lTXMlMjIlM0FudWxsJTJDJTIycnVuU3RhcnRUaW1lc3RhbXAlMjIlM0FudWxsJTJDJTIyZGVidWdnZXJBY3RpdmUlMjIlM0FmYWxzZSU3RA==",
- },
- };
- window.__MARIMO_STATIC__.assetUrl =
- "https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist";
- window.__MARIMO_STATIC__.files = {
- "/@file/note.txt": { base64: "data:text/plain;base64,bm90ZQo=" },
- };
- </script>
-
- <marimo-code hidden="">
- import%20marimo%20as%20mo%0A%0Amo.html('%3Ch1%3Ehello%3C%2Fh1%3E')
- </marimo-code>
-
- <script
- type="module"
- crossorigin="anonymous"
- src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index-2e140915.js"
- ></script>
- <link
- rel="stylesheet"
- href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index-116d8088.css"
- crossorigin="anonymous"
- />
- </body>
-</html>
-"
-`;
diff --git a/frontend/src/core/static/__tests__/download-html.test.ts b/frontend/src/core/static/__tests__/download-html.test.ts
index 1b63cc3655..ee3ee9916d 100644
--- a/frontend/src/core/static/__tests__/download-html.test.ts
+++ b/frontend/src/core/static/__tests__/download-html.test.ts
@@ -1,117 +1,9 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { describe, expect, it } from "vitest";
-import { constructHTML, visibleForTesting } from "../download-html";
-import { CellId } from "@/core/cells/ids";
-import { createCell, createCellRuntimeState } from "@/core/cells/types";
-import { JSDOM } from "jsdom";
-import prettier from "prettier";
-import { Base64String } from "@/utils/json/base64";
+import { visibleForTesting } from "../download-html";
const { updateAssetUrl } = visibleForTesting;
-const DOC = `
-<html lang="en">
- <head>
- <style id="random-style">
- #thing {
- visibility: hidden;
- }
- </style>
- <meta charset="utf-8" />
- <link rel="icon" href="/favicon.ico" />
- <link rel="preload" href="/assets/gradient-6c6e9bb3.png" as="image" />
- <link rel="preload" href="/assets/noise-b5c8172e.png" as="image" />
- <link
- rel="preload"
- href="/assets/Lora-VariableFont_wght-dqKLWsPt.ttf"
- as="font"
- crossorigin="anonymous"
- />
- <link
- rel="preload"
- href="/assets/PTSans-Regular-sS9EvFu5.ttf"
- as="font"
- crossorigin="anonymous"
- />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <meta name="theme-color" content="#000000" />
- <meta name="description" content="a marimo app" />
- <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
- <link rel="manifest" href="/manifest.json" />
- <script data-marimo="true">
- function __resizeIframe(obj) {
- // Resize the iframe to the height of the content
- obj.style.height =
- obj.contentWindow.document.documentElement.scrollHeight + "px";
-
- // Resize the iframe when the content changes
- const resizeObserver = new ResizeObserver((entries) => {
- obj.style.height =
- obj.contentWindow.document.documentElement.scrollHeight + "px";
- });
- resizeObserver.observe(obj.contentWindow.document.body);
- }
- </script>
- </head>
- <body class="light light-theme">
- <marimo-filename hidden="">app.py</marimo-filename>
- <marimo-mode data-mode="edit" hidden=""></marimo-mode>
- <marimo-version data-version="0.1.44" hidden=""></marimo-version>
- <marimo-server-token data-token="123" hidden=""></marimo-server-token>
- <marimo-user-config
- data-config='{"display": {"theme": "light"}, "keymap": {"preset": "default"}, "save": {"autosave": "after_delay", "format_on_save": true, "autosave_delay": 1000}, "server": {"browser": "default"}, "experimental": {"layouts": true, "theming": true}, "runtime": {"auto_instantiate": true}, "completion": {"activate_on_typing": true, "copilot": true}}'
- hidden=""
- ></marimo-user-config>
- <marimo-app-config data-config='{"width": "full", "layout_file": null}' hidden=""></marimo-app-config>
-
- <title>app</title>
- <script type="module" crossorigin="" src="/assets/index-2e140915.js"></script>
- <link rel="stylesheet" href="/assets/index-116d8088.css" />
-
- <div id="root">
- <main>App HTML should not render</main>
- </div>
- </body>
-</html>
-`;
-
-describe("download-html", () => {
- it("should construct html correctly", async () => {
- const cellId = "1" as CellId;
- const version = "0.1.44";
- const result = constructHTML({
- version: version,
- notebookState: {
- cellIds: [cellId],
- cellData: {
- [cellId]: createCell({
- id: cellId,
- name: "cell",
- code: "code",
- config: {
- hide_code: true,
- },
- }),
- },
- cellRuntime: { [cellId]: createCellRuntimeState() },
- },
- files: {
- "/@file/note.txt": {
- 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`,
- existingDocument: new JSDOM(DOC).window.document,
- });
-
- const formattedResult = await prettier.format(result, {
- parser: "html",
- });
- expect(formattedResult).toMatchSnapshot();
- });
-});
-
describe("updateAssetUrl", () => {
const assetBaseUrl =
"https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist";
diff --git a/frontend/src/core/static/__tests__/files.test.ts b/frontend/src/core/static/__tests__/files.test.ts
index ba9d0e7f6d..a32f81f55b 100644
--- a/frontend/src/core/static/__tests__/files.test.ts
+++ b/frontend/src/core/static/__tests__/files.test.ts
@@ -1,7 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { describe, afterEach, expect, it, vi } from "vitest";
import { patchFetch, patchVegaLoader } from "../files";
-import { Base64String } from "@/utils/json/base64";
+import { DataURLString } from "@/utils/json/base64";
describe("patchFetch", () => {
const originalFetch = window.fetch;
@@ -12,9 +12,8 @@ describe("patchFetch", () => {
it("should return a blob response when a virtual file is fetched", async () => {
const virtualFiles = {
- "/@file/virtual-file.txt": {
- base64: "data:text/plain;base64,VGVzdCBjb250ZW50" as Base64String,
- },
+ "/@file/virtual-file.txt":
+ "data:text/plain;base64,VGVzdCBjb250ZW50" as DataURLString,
};
patchFetch(virtualFiles);
@@ -48,10 +47,8 @@ describe("patchFetch", () => {
describe("patchVegaLoader", () => {
it("should return file content for virtual files", async () => {
const virtualFiles = {
- "virtual-file.json": {
- base64:
- "data:application/json;base64,eyJrZXkiOiAidmFsdWUifQ==" as Base64String,
- },
+ "virtual-file.json":
+ "data:application/json;base64,eyJrZXkiOiAidmFsdWUifQ==" as DataURLString,
};
const loader = {
diff --git a/frontend/src/core/static/download-html.ts b/frontend/src/core/static/download-html.ts
index 167634f658..4a19454fd7 100644
--- a/frontend/src/core/static/download-html.ts
+++ b/frontend/src/core/static/download-html.ts
@@ -1,54 +1,19 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { Objects } from "@/utils/objects";
-import { NotebookState, getNotebook } from "../cells/cells";
-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 { exportHTML } from "../network/requests";
import { downloadBlob } from "@/utils/download";
import { Paths } from "@/utils/paths";
-
-// For Testing:
-// Flip this to `true` to use local assets instead of CDN
-// This should be `false` for production
-const ENABLE_LOCAL_ASSETS = false;
-
-/**
- * Downloads the current notebook as an HTML file.
- */
-export async function createStaticHTMLNotebook() {
- const notebook = getNotebook();
- const version = getMarimoVersion();
-
- const assetUrl =
- ENABLE_LOCAL_ASSETS ||
- process.env.NODE_ENV === "development" ||
- process.env.NODE_ENV === "test"
- ? window.location.origin
- : `https://cdn.jsdelivr.net/npm/@marimo-team/frontend@${version}/dist`;
-
- const codeResponse = await readCode();
-
- const html = constructHTML({
- notebookState: notebook,
- version: version,
- assetUrl: assetUrl,
- existingDocument: document,
- files: await downloadVirtualFiles(),
- code: codeResponse.contents,
- });
-
- return html;
-}
+import { VirtualFileTracker } from "./virtual-file-tracker";
/**
* Downloads the current notebook as an HTML file.
*/
export async function downloadAsHTML(opts: { filename: string }) {
const { filename } = opts;
- const html = await createStaticHTMLNotebook();
-
+ const html = await exportHTML({
+ download: true,
+ includeCode: true,
+ files: VirtualFileTracker.INSTANCE.filenames(),
+ });
const filenameWithoutPath = Paths.basename(filename) ?? "notebook.py";
const filenameWithoutExtension =
filenameWithoutPath.split(".").shift() ?? "app";
@@ -59,139 +24,6 @@ export async function downloadAsHTML(opts: { filename: string }) {
);
}
-/**
- * Constructs HTML for the a static rendering of the page.
- */
-export function constructHTML(opts: {
- version: string;
- notebookState: Pick<NotebookState, "cellIds" | "cellData" | "cellRuntime">;
- assetUrl: string;
- files: StaticVirtualFiles;
- existingDocument: Document;
- code: string;
-}) {
- const { version, notebookState, assetUrl, existingDocument, files, code } =
- opts;
-
- const staticHead = existingDocument.head.cloneNode(true) as HTMLHeadElement;
- // Remove fonts, that contain as="font"
- staticHead.querySelectorAll("link[as=font]").forEach((el) => el.remove());
-
- const elementsFromBody = [
- "marimo-filename",
- "marimo-version",
- "marimo-user-config",
- "marimo-app-config",
- ];
-
- // Create initial elements
- const html = `
- <!DOCTYPE html>
- <html>
- <head>
- <base href="/">
- ${staticHead.innerHTML}
- </head>
-
- <body>
- <div id="root"></div>
- <marimo-mode data-mode="read" hidden=""></marimo-mode>
- ${elementsFromBody
- .map((id) => {
- const element = existingDocument.querySelector(id);
- if (!element) {
- throw new Error(`Element ${id} not found.`);
- }
- return element.outerHTML;
- })
- .join("\n")}
- <script data-marimo="true">
- window.__MARIMO_STATIC__ = {};
- window.__MARIMO_STATIC__.version = "${version}";
- window.__MARIMO_STATIC__.notebookState = ${JSON.stringify({
- cellIds: notebookState.cellIds,
- cellData: Objects.mapValues(
- notebookState.cellData,
- serializeJsonToBase64,
- ),
- cellRuntime: Objects.mapValues(
- notebookState.cellRuntime,
- serializeJsonToBase64,
- ),
- })};
- window.__MARIMO_STATIC__.assetUrl = "${assetUrl}";
- window.__MARIMO_STATIC__.files = ${JSON.stringify(files)};
- </script>
-
- <marimo-code hidden="">
- ${encodeURIComponent(code)}
- </marimo-code>
- </body>
- </html>
- `;
-
- const doc = new DOMParser().parseFromString(html, "text/html");
-
- // Copy over any stylesheets or scripts from the body that are URL based
- const body = existingDocument.body;
- const appendToBody = (element: Element) => {
- const el = element.cloneNode(true);
- if (el instanceof HTMLElement) {
- el.setAttribute("crossorigin", "anonymous");
- }
- doc.body.append(element.cloneNode(true));
- };
- body.querySelectorAll("style[href]").forEach(appendToBody);
- body.querySelectorAll("script[src]").forEach(appendToBody);
- body.querySelectorAll("link[href]").forEach(appendToBody);
-
- // Update scripts to point to CDN
- const scripts = doc.querySelectorAll("script");
- scripts.forEach((script) => {
- const src = script.getAttribute("src");
- if (src) {
- script.setAttribute("src", updateAssetUrl(src, assetUrl));
- script.setAttribute("crossorigin", "anonymous");
- } else if (!Object.hasOwn(script.dataset, "marimo")) {
- script.remove();
- }
- });
-
- // Update links to point to CDN
- const links = doc.querySelectorAll("link");
- links.forEach((link) => {
- const href = link.getAttribute("href");
- if (href) {
- link.setAttribute("href", updateAssetUrl(href, assetUrl));
- link.setAttribute("crossorigin", "anonymous");
- } else {
- link.remove();
- }
- });
-
- // Remove style tags
- const styles = doc.querySelectorAll("style");
- styles.forEach((style) => style.remove());
-
- // Handle testing with Vite
- if (process.env.NODE_ENV === "development") {
- const devScript = doc.createElement("script");
- devScript.setAttribute("type", "module");
- devScript.setAttribute("src", `${window.location.origin}/src/main.tsx`);
- doc.body.append(devScript);
- }
-
- doc.head.innerHTML = `
- ${doc.head.innerHTML}
- <link rel="preconnect" href="https://fonts.googleapis.com">
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
- <link href="https://fonts.googleapis.com/css2?family=Fira+Mono:wght@400;500;700&family=Lora&family=PT+Sans:wght@400;700&display=swap" rel="stylesheet">
- `.trim();
-
- // add DOCTYPE back in
- return `<!DOCTYPE html>\n${doc.documentElement.outerHTML}`;
-}
-
function updateAssetUrl(existingUrl: string, assetBaseUrl: string) {
// Will convert: https://localhost:8080/assets/index-c78b8d10.js
// Or will convert ./assets/index-c78b8d10.js
diff --git a/frontend/src/core/static/files.ts b/frontend/src/core/static/files.ts
index 68f85ca0ac..811f73a340 100644
--- a/frontend/src/core/static/files.ts
+++ b/frontend/src/core/static/files.ts
@@ -1,39 +1,8 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { Logger } from "@/utils/Logger";
-import { VirtualFileTracker } from "./virtual-file-tracker";
import { StaticVirtualFiles } from "./types";
-import { deserializeBlob, serializeBlob } from "@/utils/blob";
+import { deserializeBlob } from "@/utils/blob";
import { getStaticVirtualFiles } from "./static-state";
-import { Sets } from "@/utils/sets";
-
-/**
- * Download virtual files used in the notebook
- */
-export async function downloadVirtualFiles(): Promise<StaticVirtualFiles> {
- const files: StaticVirtualFiles = {};
-
- const virtualFiles = Sets.merge(
- ...VirtualFileTracker.INSTANCE.virtualFiles.values(),
- );
-
- for (const url of virtualFiles) {
- try {
- const response = await fetch(url);
- const contentType = response.headers.get("Content-Type") ?? "";
- if (!contentType) {
- Logger.warn(`Content-Type header missing for virtual file ${url}`);
- }
- const data = await response.blob();
- const base64 = await serializeBlob(data);
- files[url] = { base64 };
- } catch (error) {
- Logger.warn(`Error downloading virtual file ${url}`, error);
- }
- }
-
- return files;
-}
/**
* Patch fetch to resolve virtual files
@@ -55,7 +24,7 @@ export function patchFetch(
: new URL(urlString);
if (files[url.pathname]) {
- const { base64 } = files[url.pathname];
+ const base64 = files[url.pathname];
const blob = await deserializeBlob(base64);
return new Response(blob);
}
@@ -80,7 +49,7 @@ export function patchVegaLoader(
loader.http = async (url: string) => {
if (files[url]) {
- const { base64 } = files[url];
+ const base64 = files[url];
const blob = await deserializeBlob(base64);
return blob.text();
}
diff --git a/frontend/src/core/static/static-state.ts b/frontend/src/core/static/static-state.ts
index 7b20fcb397..55c524c8d4 100644
--- a/frontend/src/core/static/static-state.ts
+++ b/frontend/src/core/static/static-state.ts
@@ -22,12 +22,6 @@ export function isStaticNotebook(): boolean {
return window?.__MARIMO_STATIC__ !== undefined;
}
-export function getStaticNotebookAssetUrl(): string {
- invariant(window.__MARIMO_STATIC__ !== undefined, "Not a static notebook");
-
- return window.__MARIMO_STATIC__.assetUrl;
-}
-
export function getStaticVirtualFiles(): StaticVirtualFiles {
invariant(window.__MARIMO_STATIC__ !== undefined, "Not a static notebook");
diff --git a/frontend/src/core/static/types.ts b/frontend/src/core/static/types.ts
index e2dc597ab1..5cd79af59d 100644
--- a/frontend/src/core/static/types.ts
+++ b/frontend/src/core/static/types.ts
@@ -1,16 +1,35 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { Base64String } from "@/utils/json/base64";
-import { NotebookState } from "../cells/cells";
+import { Base64String, DataURLString, JsonString } from "@/utils/json/base64";
import { CellId } from "../cells/ids";
+import { OutputMessage } from "../kernel/messages";
+import { CellConfig } from "../cells/types";
-export interface StaticNotebookState extends Pick<NotebookState, "cellIds"> {
- version: string;
- assetUrl: string;
- cellRuntime: Record<CellId, Base64String>;
- cellData: Record<CellId, Base64String>;
+export interface StaticNotebookState {
+ cellIds: CellId[];
+ cellNames: Array<Base64String<string>>;
+ cellCodes: Array<Base64String<string>>;
+ cellConfigs: Array<Base64String<JsonString<CellConfig>>>;
+ /**
+ * The runtime output of each cell.
+ * {
+ * "cell-1": "base64 json string",
+ * }
+ */
+ cellOutputs: Record<
+ CellId,
+ Base64String<JsonString<OutputMessage>> | undefined
+ >;
+ /**
+ * The data of each cell.
+ *
+ */
+ cellConsoleOutputs: Record<
+ CellId,
+ Array<Base64String<JsonString<OutputMessage>>> | undefined
+ >;
}
-export type StaticVirtualFiles = Record<string, { base64: Base64String }>;
+export type StaticVirtualFiles = Record<string, DataURLString>;
export interface MarimoStaticState {
version: string;
diff --git a/frontend/src/core/static/virtual-file-tracker.ts b/frontend/src/core/static/virtual-file-tracker.ts
index 4476875fb0..e3f950281e 100644
--- a/frontend/src/core/static/virtual-file-tracker.ts
+++ b/frontend/src/core/static/virtual-file-tracker.ts
@@ -41,6 +41,15 @@ export class VirtualFileTracker {
}
}
+ filenames(): string[] {
+ const set = new Set<string>();
+ for (const files of this.virtualFiles.values()) {
+ files.forEach((file) => set.add(file));
+ }
+
+ return [...set];
+ }
+
removeForCellId(cellId: CellId): void {
this.virtualFiles.delete(cellId);
}
diff --git a/frontend/src/plugins/core/registerReactComponent.tsx b/frontend/src/plugins/core/registerReactComponent.tsx
index dd3566fa3c..a317977271 100644
--- a/frontend/src/plugins/core/registerReactComponent.tsx
+++ b/frontend/src/plugins/core/registerReactComponent.tsx
@@ -43,10 +43,6 @@ import { PluginFunctions } from "./rpc";
import { ZodSchema } from "zod";
import useEvent from "react-use-event-hook";
import { Functions } from "@/utils/functions";
-import {
- getStaticNotebookAssetUrl,
- isStaticNotebook,
-} from "@/core/static/static-state";
export interface PluginSlotHandle {
/**
@@ -441,8 +437,11 @@ function shouldCopyStyleSheet(sheet: CSSStyleSheet): boolean {
return false;
}
- if (isStaticNotebook()) {
- return sheet.href.startsWith(getStaticNotebookAssetUrl());
+ if (
+ sheet.href.includes("127.0.0.1") &&
+ (process.env.NODE_ENV === "test" || process.env.NODE_ENV === "development")
+ ) {
+ return true;
}
if (sheet.href.includes("@marimo-team/frontend")) {
diff --git a/frontend/src/utils/blob.ts b/frontend/src/utils/blob.ts
index 1272b97a90..06349ec940 100644
--- a/frontend/src/utils/blob.ts
+++ b/frontend/src/utils/blob.ts
@@ -1,11 +1,11 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { Base64String } from "./json/base64";
+import { DataURLString } from "./json/base64";
-export function serializeBlob(blob: Blob): Promise<Base64String> {
- return new Promise<Base64String>((resolve, reject) => {
+export function serializeBlob<T>(blob: Blob): Promise<DataURLString> {
+ return new Promise<DataURLString>((resolve, reject) => {
const reader = new FileReader();
reader.onload = (event) => {
- resolve(event.target?.result as Base64String);
+ resolve(event.target?.result as DataURLString);
};
reader.onerror = (evt) => {
reject(new Error(`Failed to read blob: ${evt.type}`));
@@ -14,7 +14,7 @@ export function serializeBlob(blob: Blob): Promise<Base64String> {
});
}
-export function deserializeBlob(serializedBlob: Base64String): Promise<Blob> {
+export function deserializeBlob(serializedBlob: DataURLString): Promise<Blob> {
return new Promise((resolve, reject) => {
try {
// Extract the base64 data from the data URL
diff --git a/frontend/src/utils/json/__tests__/base64.test.ts b/frontend/src/utils/json/__tests__/base64.test.ts
index 9b187475bc..8a20c7e826 100644
--- a/frontend/src/utils/json/__tests__/base64.test.ts
+++ b/frontend/src/utils/json/__tests__/base64.test.ts
@@ -1,10 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { expect, describe, test } from "vitest";
-import {
- serializeJsonToBase64,
- deserializeBase64ToJson,
- Base64String,
-} from "../base64";
+import { deserializeBase64, Base64String, JsonString } from "../base64";
describe("base64Utils", () => {
const testData = {
@@ -13,7 +9,9 @@ describe("base64Utils", () => {
};
const expectedBase64 =
- "JTdCJTIybmFtZSUyMiUzQSUyMm1hcmltbyUyMGluYyUyMiUyQyUyMnR5cGUlMjIlM0ElMjJjb21wYW55JTIyJTdE" as Base64String;
+ "JTdCJTIybmFtZSUyMiUzQSUyMm1hcmltbyUyMGluYyUyMiUyQyUyMnR5cGUlMjIlM0ElMjJjb21wYW55JTIyJTdE" as Base64String<
+ JsonString<typeof testData>
+ >;
test("serializeJsonToBase64 should correctly encode JSON to Base64", () => {
const base64Encoded = serializeJsonToBase64(testData);
@@ -21,20 +19,19 @@ describe("base64Utils", () => {
});
test("deserializeBase64ToJson should correctly decode Base64 to JSON", () => {
- const jsonDecoded = deserializeBase64ToJson(expectedBase64);
- expect(jsonDecoded).toEqual(testData);
+ const jsonDecoded = deserializeBase64(expectedBase64);
+ expect(JSON.parse(jsonDecoded)).toEqual(testData);
});
test("serializeJsonToBase64 and deserializeBase64ToJson should be reversible", () => {
const base64Encoded = serializeJsonToBase64(testData);
- const jsonDecoded = deserializeBase64ToJson(base64Encoded);
- expect(jsonDecoded).toEqual(testData);
- });
-
- test("deserializeBase64ToJson should throw an error for invalid Base64 strings", () => {
- const invalidBase64 = "InvalidBase64String" as Base64String;
- expect(() => {
- deserializeBase64ToJson(invalidBase64);
- }).toThrow(SyntaxError);
+ const jsonDecoded = deserializeBase64(base64Encoded);
+ expect(JSON.parse(jsonDecoded)).toEqual(testData);
});
});
+
+// Serialization: JSON to Base64
+function serializeJsonToBase64<T>(jsonObject: T) {
+ const jsonString = JSON.stringify(jsonObject);
+ return btoa(encodeURIComponent(jsonString)) as Base64String<JsonString<T>>;
+}
diff --git a/frontend/src/utils/json/base64.ts b/frontend/src/utils/json/base64.ts
index 6ec23e4f78..1ed0a7ebf0 100644
--- a/frontend/src/utils/json/base64.ts
+++ b/frontend/src/utils/json/base64.ts
@@ -1,20 +1,27 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { TypedString } from "../typed";
-export type Base64String = TypedString<"Base64">;
+export type JsonString<T> = TypedString<"Json"> & {
+ _of_: T;
+};
-// Serialization: JSON to Base64
-export function serializeJsonToBase64(jsonObject: object) {
- const jsonString = JSON.stringify(jsonObject);
- return btoa(encodeURIComponent(jsonString)) as Base64String;
-}
+export type Base64String<T = unknown> = TypedString<"Base64"> & {
+ _of_: T;
+};
+
+export type DataURLString = `data:${string};base64,${Base64String<string>}`;
-// Deserialization: Base64 to JSON
-export function deserializeBase64ToJson<T>(base64: Base64String): T {
+// Deserialization: Base64 to String
+export function deserializeBase64<T>(base64: Base64String<T>): T {
const decodedString = decodeURIComponent(atob(base64));
- return JSON.parse(decodedString) as T;
+ return decodedString as T;
+}
+
+// Deserialization: String to JSON
+export function deserializeJson<T>(jsonString: JsonString<T>): T {
+ return JSON.parse(jsonString) as T;
}
-export function base64ToDataURL(base64: Base64String, mimeType: string) {
+export function base64ToDataURL<T>(base64: Base64String<T>, mimeType: string) {
return `data:${mimeType};base64,${base64}`;
}
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.py
index 1695dc010b..6a0dfa0636 100644
--- a/marimo/_ast/cell.py
+++ b/marimo/_ast/cell.py
@@ -32,6 +32,9 @@ class CellConfig:
def from_dict(cls, kwargs: dict[str, Any]) -> CellConfig:
return cls(**{k: v for k, v in kwargs.items() if k in CellConfigKeys})
+ def asdict(self) -> dict[str, Any]:
+ return dataclasses.asdict(self)
+
def configure(self, update: dict[str, Any] | CellConfig) -> None:
"""Update the config in-place.
diff --git a/marimo/_messaging/cell_output.py b/marimo/_messaging/cell_output.py
index d690d41e55..71cce7adc6 100644
--- a/marimo/_messaging/cell_output.py
+++ b/marimo/_messaging/cell_output.py
@@ -4,9 +4,9 @@
from __future__ import annotations
import time
-from dataclasses import dataclass, field
+from dataclasses import asdict, dataclass, field
from enum import Enum
-from typing import Sequence, Union
+from typing import Any, Sequence, Union
from marimo._messaging.errors import Error
from marimo._messaging.mimetypes import KnownMimeType
@@ -34,6 +34,9 @@ class CellOutput:
data: Union[str, Sequence[Error]]
timestamp: float = field(default_factory=lambda: time.time())
+ def asdict(self) -> dict[str, Any]:
+ return asdict(self)
+
@staticmethod
def stdout(data: str) -> CellOutput:
return CellOutput(
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index 9b85840f12..8d33525c09 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -33,10 +33,12 @@ from marimo._runtime.requests import (
SetUIElementValueRequest,
)
from marimo._runtime.runtime import Kernel
+from marimo._server.export.exporter import Exporter
from marimo._server.file_manager import AppFileManager
from marimo._server.files.os_file_system import OSFileSystem
from marimo._server.model import SessionMode
from marimo._server.models.base import deep_to_camel_case
+from marimo._server.models.export import ExportAsHTMLRequest
from marimo._server.models.files import (
FileCreateRequest,
FileCreateResponse,
@@ -57,6 +59,7 @@ from marimo._server.models.models import (
SaveAppConfigurationRequest,
SaveRequest,
)
+from marimo._server.session.session_view import SessionView
from marimo._snippets.snippets import read_snippets
from marimo._utils.formatter import DefaultFormatter
from marimo._utils.parse_dataclass import parse_raw
@@ -162,10 +165,12 @@ class PyodideSession:
self.app_metadata = app_metadata
self._queue_manager = AsyncQueueManager()
self.session_consumer = on_write
+ self.session_view = SessionView()
self._initial_user_config = user_config
self.consumers: list[Callable[[KernelMessage], None]] = [
lambda msg: self.session_consumer(msg),
+ lambda msg: self.session_view.add_raw_operation(msg[1]),
]
def _on_message(self, msg: KernelMessage) -> None:
@@ -327,6 +332,16 @@ class PyodideBridge:
response = FileUpdateResponse(success=False, message=str(e))
return json.dumps(deep_to_camel_case(dataclasses.asdict(response)))
+ def export_html(self, request: str) -> str:
+ parsed = parse_raw(json.loads(request), ExportAsHTMLRequest)
+ html, _filename = Exporter().export_as_html(
+ file_manager=self.session.app_manager,
+ session_view=self.session.session_view,
+ display_config=self.session._initial_user_config["display"],
+ request=parsed,
+ )
+ return json.dumps(html)
+
def launch_pyodide_kernel(
control_queue: asyncio.Queue[ControlRequest],
diff --git a/marimo/_runtime/virtual_file.py b/marimo/_runtime/virtual_file.py
index 717774e429..afa7e28c47 100644
--- a/marimo/_runtime/virtual_file.py
+++ b/marimo/_runtime/virtual_file.py
@@ -14,6 +14,7 @@ from marimo import _loggers
from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.utils import build_data_url
from marimo._runtime.cell_lifecycle_item import CellLifecycleItem
+from marimo._server.api.status import HTTPException, HTTPStatus
from marimo._utils.platform import is_pyodide
if TYPE_CHECKING:
@@ -267,3 +268,30 @@ class VirtualFileRegistry:
def _without_leading_dot(ext: str) -> str:
return ext[1:] if ext.startswith(".") else ext
+
+
+def read_virtual_file(filename: str, byte_length: int) -> bytes:
+ if not shared_memory:
+ raise RuntimeError("Shared memory is not supported on this platform")
+
+ key = filename
+ shm = None
+ try:
+ # NB: this can't be collapsed into a one-liner!
+ # doing it in one line yields a 'released memoryview ...'
+ # because shared_memory has built in ref-tracking + GC
+ shm = shared_memory.SharedMemory(name=key)
+ buffer_contents = bytes(shm.buf)[: int(byte_length)]
+ except FileNotFoundError as err:
+ LOGGER.debug(
+ "Error retrieving shared memory for virtual file: %s", err
+ )
+ raise HTTPException(
+ HTTPStatus.NOT_FOUND,
+ detail="File not found",
+ ) from err
+ finally:
+ if shm is not None:
+ shm.close()
+
+ return buffer_contents
diff --git a/marimo/_server/api/endpoints/assets.py b/marimo/_server/api/endpoints/assets.py
index 66b040e78f..ec1657988f 100644
--- a/marimo/_server/api/endpoints/assets.py
+++ b/marimo/_server/api/endpoints/assets.py
@@ -1,24 +1,28 @@
# Copyright 2024 Marimo. All rights reserved.
-import json
+from __future__ import annotations
+
import mimetypes
import os
import re
-from http import HTTPStatus
-from multiprocessing import shared_memory
+from typing import TYPE_CHECKING
from starlette.exceptions import HTTPException
-from starlette.requests import Request
from starlette.responses import FileResponse, HTMLResponse, Response
from starlette.staticfiles import StaticFiles
-from marimo import __version__, _loggers
-from marimo._runtime.virtual_file import EMPTY_VIRTUAL_FILE
+from marimo import _loggers
+from marimo._runtime.virtual_file import EMPTY_VIRTUAL_FILE, read_virtual_file
from marimo._server.api.deps import AppState
-from marimo._server.api.utils import parse_title
-from marimo._server.model import SessionMode
from marimo._server.router import APIRouter
+from marimo._server.templates.templates import (
+ home_page_template,
+ notebook_page_template,
+)
from marimo._utils.paths import import_files
+if TYPE_CHECKING:
+ from starlette.requests import Request
+
LOGGER = _loggers.marimo_logger()
# Router for serving static assets
@@ -50,31 +54,29 @@ async def index(request: Request) -> HTMLResponse:
with open(index_html, "r") as f: # noqa: ASYNC101
html = f.read()
- # Shared configuration
- html = html.replace("{{ base_url }}", app_state.base_url)
- html = html.replace("{{ user_config }}", json.dumps(user_config))
- html = html.replace("{{ server_token }}", app_state.server_token)
- html = html.replace("{{ version }}", __version__)
-
if not file_key:
- LOGGER.debug("No file key provided, serving homepage")
# We don't know which file to use, so we need to render a homepage
- html = html.replace("{{ title }}", "marimo")
- html = html.replace("{{ app_config }}", json.dumps({}))
- html = html.replace("{{ filename }}", "")
- html = html.replace("{{ mode }}", "home")
+ LOGGER.debug("No file key provided, serving homepage")
+ html = home_page_template(
+ html=html,
+ base_url=app_state.base_url,
+ user_config=user_config,
+ server_token=app_state.server_token,
+ )
else:
- LOGGER.debug(f"File key provided: {file_key}")
# We have a file key, so we can render the app with the file
+ LOGGER.debug(f"File key provided: {file_key}")
app_manager = app_state.session_manager.app_manager(file_key)
- app_config = app_manager.app.config.asdict()
-
- html = html.replace("{{ title }}", parse_title(app_manager.filename))
- html = html.replace("{{ app_config }}", json.dumps(app_config))
- html = html.replace("{{ filename }}", app_manager.filename or "")
- html = html.replace(
- "{{ mode }}",
- "read" if app_state.mode == SessionMode.RUN else "edit",
+ app_config = app_manager.app.config
+
+ html = notebook_page_template(
+ html=html,
+ base_url=app_state.base_url,
+ user_config=user_config,
+ server_token=app_state.server_token,
+ app_config=app_config,
+ filename=app_manager.filename,
+ mode=app_state.mode,
)
return HTMLResponse(html)
@@ -101,25 +103,7 @@ def virtual_file(
return Response(content=b"", media_type="application/octet-stream")
byte_length, filename = filename_and_length.split("-", 1)
- key = filename
- shm = None
- try:
- # NB: this can't be collapsed into a one-liner!
- # doing it in one line yields a 'released memoryview ...'
- # because shared_memory has built in ref-tracking + GC
- shm = shared_memory.SharedMemory(name=key)
- buffer_contents = bytes(shm.buf)[: int(byte_length)]
- except FileNotFoundError as err:
- LOGGER.debug(
- "Error retrieving shared memory for virtual file: %s", err
- )
- raise HTTPException(
- HTTPStatus.NOT_FOUND,
- detail="File not found",
- ) from err
- finally:
- if shm is not None:
- shm.close()
+ buffer_contents = read_virtual_file(filename, int(byte_length))
mimetype, _ = mimetypes.guess_type(filename)
return Response(
content=buffer_contents,
diff --git a/marimo/_server/api/endpoints/export.py b/marimo/_server/api/endpoints/export.py
new file mode 100644
index 0000000000..d348481a3d
--- /dev/null
+++ b/marimo/_server/api/endpoints/export.py
@@ -0,0 +1,56 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from starlette.authentication import requires
+from starlette.responses import HTMLResponse
+
+from marimo import _loggers
+from marimo._server.api.deps import AppState
+from marimo._server.api.utils import parse_request
+from marimo._server.export.exporter import Exporter
+from marimo._server.models.export import ExportAsHTMLRequest
+from marimo._server.router import APIRouter
+
+if TYPE_CHECKING:
+ from starlette.requests import Request
+
+LOGGER = _loggers.marimo_logger()
+
+# Router for export endpoints
+router = APIRouter()
+
+
+@requires("edit")
+async def export_as_html(
+ *,
+ request: Request,
+) -> HTMLResponse:
+ """
+ Export the notebook as HTML.
+ """
+ app_state = AppState(request)
+ body = await parse_request(request, cls=ExportAsHTMLRequest)
+ session = app_state.require_current_session()
+
+ html, filename = Exporter().export_as_html(
+ file_manager=session.app_file_manager,
+ session_view=session.session_view,
+ display_config=app_state.session_manager.user_config_manager.get_config()[
+ "display"
+ ],
+ request=body,
+ )
+
+ if body.download:
+ headers = {"Content-Disposition": f"attachment; filename={filename}"}
+ else:
+ headers = {}
+
+ # Download the HTML
+ return HTMLResponse(
+ content=html,
+ headers=headers,
+ )
diff --git a/marimo/_server/api/router.py b/marimo/_server/api/router.py
index 0701ac646b..5465c786d8 100644
--- a/marimo/_server/api/router.py
+++ b/marimo/_server/api/router.py
@@ -1,9 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
-
-from typing import List
-
-from starlette.routing import BaseRoute
+from typing import TYPE_CHECKING, List
from marimo._server.api.endpoints.ai import router as ai_router
from marimo._server.api.endpoints.assets import router as assets_router
@@ -13,6 +11,7 @@ from marimo._server.api.endpoints.documentation import (
)
from marimo._server.api.endpoints.editing import router as editing_router
from marimo._server.api.endpoints.execution import router as execution_router
+from marimo._server.api.endpoints.export import router as export_router
from marimo._server.api.endpoints.file_explorer import (
router as file_explorer_router,
)
@@ -22,6 +21,9 @@ from marimo._server.api.endpoints.home import router as home_router
from marimo._server.api.endpoints.ws import router as ws_router
from marimo._server.router import APIRouter
+if TYPE_CHECKING:
+ from starlette.routing import BaseRoute
+
# Define the app routes
def build_routes(base_url: str = "") -> List[BaseRoute]:
@@ -44,6 +46,9 @@ def build_routes(base_url: str = "") -> List[BaseRoute]:
)
app_router.include_router(ai_router, prefix="/api/ai", name="ai")
app_router.include_router(home_router, prefix="/api/home", name="home")
+ app_router.include_router(
+ export_router, prefix="/api/export", name="export"
+ )
app_router.include_router(health_router, name="health")
app_router.include_router(ws_router, name="ws")
app_router.include_router(assets_router, name="assets")
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
new file mode 100644
index 0000000000..aeb29a8079
--- /dev/null
+++ b/marimo/_server/export/exporter.py
@@ -0,0 +1,89 @@
+from __future__ import annotations
+
+import mimetypes
+import os
+from typing import cast
+
+from marimo._config.config import (
+ DEFAULT_CONFIG,
+ DisplayConfig,
+ _deep_copy,
+)
+from marimo._messaging.mimetypes import KnownMimeType
+from marimo._output.utils import build_data_url
+from marimo._runtime.virtual_file import read_virtual_file
+from marimo._server.file_manager import AppFileManager
+from marimo._server.models.export import ExportAsHTMLRequest
+from marimo._server.session.session_view import SessionView
+from marimo._server.templates.templates import static_notebook_template
+from marimo._utils.paths import import_files
+
+# Root directory for static assets
+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,
+ request: ExportAsHTMLRequest,
+ ) -> tuple[str, str]:
+ index_html_file = os.path.join(root, "index.html")
+
+ cell_ids = list(file_manager.app.cell_manager.cell_ids())
+ filename = file_manager.filename
+ if not filename:
+ filename = "notebook.py"
+
+ with open(index_html_file, "r") as f: # noqa: ASYNC101
+ index_html = f.read()
+
+ files: dict[str, str] = {}
+ for filename_and_length in request.files:
+ if filename_and_length.startswith("/@file/"):
+ filename = filename_and_length[7:]
+ byte_length, basename = filename.split("-", 1)
+ buffer_contents = read_virtual_file(basename, int(byte_length))
+ mime_type, _ = mimetypes.guess_type(basename) or (
+ "text/plain",
+ None,
+ )
+ files[filename_and_length] = build_data_url(
+ cast(KnownMimeType, mime_type), buffer_contents
+ )
+
+ 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]
+ )
+
+ html = static_notebook_template(
+ html=index_html,
+ user_config=config,
+ server_token="static",
+ app_config=file_manager.app.config,
+ filename=file_manager.filename,
+ code=code,
+ 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_outputs=session_view.get_cell_outputs(cell_ids),
+ cell_console_outputs=session_view.get_cell_console_outputs(
+ cell_ids
+ ),
+ files=files,
+ asset_url=request.asset_url,
+ )
+
+ basename = os.path.basename(filename)
+ download_filename = f"{os.path.splitext(basename)[0]}.html"
+
+ return html, download_filename
diff --git a/marimo/_server/file_manager.py b/marimo/_server/file_manager.py
index 47459e73cd..5e7fee8ef4 100644
--- a/marimo/_server/file_manager.py
+++ b/marimo/_server/file_manager.py
@@ -148,7 +148,8 @@ class AppFileManager:
cell_configs=list(self.app.cell_manager.configs()),
config=new_config,
)
- self._create_file(self.filename, contents)
+ header_comments = codegen.get_header_comments(self.filename)
+ self._create_file(self.filename, contents, header_comments)
def save(self, request: SaveRequest) -> None:
"""Save the current app."""
@@ -201,6 +202,16 @@ class AppFileManager:
if self.filename is None:
self.rename(filename)
+ def to_code(self) -> str:
+ """Read the contents of the unsaved file."""
+ contents = codegen.generate_filecontents(
+ codes=list(self.app.cell_manager.codes()),
+ names=list(self.app.cell_manager.names()),
+ cell_configs=list(self.app.cell_manager.configs()),
+ config=self.app.config,
+ )
+ return contents
+
def read_file(self) -> str:
"""Read the contents of the file."""
if self.filename is None:
diff --git a/marimo/_server/models/export.py b/marimo/_server/models/export.py
new file mode 100644
index 0000000000..a6dd360342
--- /dev/null
+++ b/marimo/_server/models/export.py
@@ -0,0 +1,13 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import List, Optional
+
+
+@dataclass
+class ExportAsHTMLRequest:
+ download: bool
+ files: List[str]
+ include_code: bool
+ asset_url: Optional[str] = None
diff --git a/marimo/_server/router.py b/marimo/_server/router.py
index 76a640ebcb..caf753ec8e 100644
--- a/marimo/_server/router.py
+++ b/marimo/_server/router.py
@@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar
from starlette.responses import (
FileResponse,
+ HTMLResponse,
JSONResponse,
Response,
StreamingResponse,
@@ -53,6 +54,8 @@ class APIRouter(Router):
return response
if isinstance(response, StreamingResponse):
return response
+ if isinstance(response, HTMLResponse):
+ return response
if dataclasses.is_dataclass(response):
return JSONResponse(
diff --git a/marimo/_server/session/session_view.py b/marimo/_server/session/session_view.py
index 62887c2c6b..16fdae538e 100644
--- a/marimo/_server/session/session_view.py
+++ b/marimo/_server/session/session_view.py
@@ -115,6 +115,28 @@ class SessionView:
# Resolve stdin
self.add_stdin("")
+ def get_cell_outputs(
+ self, ids: list[CellId_t]
+ ) -> dict[CellId_t, CellOutput]:
+ """Get the outputs for the given cell ids."""
+ outputs: dict[CellId_t, CellOutput] = {}
+ for cell_id in ids:
+ cell_op = self.cell_operations.get(cell_id)
+ if cell_op is not None and cell_op.output is not None:
+ outputs[cell_id] = cell_op.output
+ return outputs
+
+ def get_cell_console_outputs(
+ self, ids: list[CellId_t]
+ ) -> dict[CellId_t, list[CellOutput]]:
+ """Get the console outputs for the given cell ids."""
+ outputs: dict[CellId_t, list[CellOutput]] = {}
+ for cell_id in ids:
+ cell_op = self.cell_operations.get(cell_id)
+ if cell_op is not None and cell_op.console:
+ outputs[cell_id] = as_list(cell_op.console)
+ return outputs
+
@property
def operations(self) -> list[MessageOperation]:
all_ops: list[MessageOperation] = [
diff --git a/marimo/_server/templates/templates.py b/marimo/_server/templates/templates.py
new file mode 100644
index 0000000000..1978d3c3e8
--- /dev/null
+++ b/marimo/_server/templates/templates.py
@@ -0,0 +1,158 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import base64
+import json
+import urllib.parse
+from typing import List, Optional
+
+from marimo import __version__
+from marimo._ast.app import _AppConfig
+from marimo._ast.cell import CellConfig, CellId_t
+from marimo._config.config import MarimoConfig
+from marimo._messaging.cell_output import CellOutput
+from marimo._server.api.utils import parse_title
+from marimo._server.model import SessionMode
+
+
+def home_page_template(
+ html: str,
+ base_url: str,
+ user_config: MarimoConfig,
+ server_token: str,
+) -> str:
+ html = html.replace("{{ base_url }}", base_url)
+ html = html.replace("{{ user_config }}", json.dumps(user_config))
+ html = html.replace("{{ server_token }}", server_token)
+ html = html.replace("{{ version }}", __version__)
+
+ html = html.replace("{{ title }}", "marimo")
+ html = html.replace("{{ app_config }}", json.dumps({}))
+ html = html.replace("{{ filename }}", "")
+ html = html.replace("{{ mode }}", "home")
+
+ return html
+
+
+def notebook_page_template(
+ html: str,
+ base_url: str,
+ user_config: MarimoConfig,
+ server_token: str,
+ app_config: _AppConfig,
+ filename: Optional[str],
+ mode: SessionMode,
+) -> str:
+ html = html.replace("{{ base_url }}", base_url)
+ html = html.replace("{{ user_config }}", json.dumps(user_config))
+ html = html.replace("{{ server_token }}", server_token)
+ html = html.replace("{{ version }}", __version__)
+
+ html = html.replace("{{ title }}", parse_title(filename))
+ html = html.replace("{{ app_config }}", json.dumps(app_config.asdict()))
+ html = html.replace("{{ filename }}", filename or "")
+ html = html.replace(
+ "{{ mode }}",
+ "read" if mode == SessionMode.RUN else "edit",
+ )
+
+ return html
+
+
+def static_notebook_template(
+ html: str,
+ user_config: MarimoConfig,
+ server_token: str,
+ app_config: _AppConfig,
+ filename: Optional[str],
+ code: str,
+ cell_ids: list[str],
+ cell_names: list[str],
+ cell_codes: list[str],
+ cell_configs: list[CellConfig],
+ cell_outputs: dict[CellId_t, CellOutput],
+ cell_console_outputs: dict[CellId_t, List[CellOutput]],
+ files: dict[str, str],
+ asset_url: Optional[str] = None,
+) -> str:
+ if asset_url is None:
+ asset_url = f"https://cdn.jsdelivr.net/npm/@marimo-team/frontend@{__version__}/dist"
+
+ html = html.replace("{{ base_url }}", "")
+ html = html.replace(
+ "{{ user_config }}", json.dumps(user_config, sort_keys=True)
+ )
+ html = html.replace("{{ server_token }}", server_token)
+ html = html.replace("{{ version }}", __version__)
+
+ html = html.replace("{{ title }}", parse_title(filename))
+ html = html.replace(
+ "{{ app_config }}", json.dumps(app_config.asdict(), sort_keys=True)
+ )
+ html = html.replace("{{ filename }}", filename or "")
+ html = html.replace("{{ mode }}", "read")
+
+ serialized_cell_outputs = {
+ cell_id: _serialize_to_base64(json.dumps(output.asdict()))
+ for cell_id, output in cell_outputs.items()
+ }
+ serialized_cell_console_outputs = {
+ cell_id: [_serialize_to_base64(json.dumps(o.asdict())) for o in output]
+ for cell_id, output in cell_console_outputs.items()
+ if output
+ }
+
+ static_block = f"""
+ <script data-marimo="true">
+ window.__MARIMO_STATIC__ = {{}};
+ window.__MARIMO_STATIC__.version = "{__version__}";
+ window.__MARIMO_STATIC__.notebookState = {json.dumps({
+ "cellIds": cell_ids,
+ "cellNames": _serialize_list_to_base64(cell_names),
+ "cellCodes": _serialize_list_to_base64(cell_codes),
+ "cellConfigs": _serialize_list_to_base64([
+ json.dumps(config.asdict())
+ for config in cell_configs
+ ]),
+ "cellOutputs": serialized_cell_outputs,
+ "cellConsoleOutputs": serialized_cell_console_outputs,
+ })};
+ window.__MARIMO_STATIC__.assetUrl = "{asset_url}";
+ window.__MARIMO_STATIC__.files = {json.dumps(files)};
+ </script>
+ """
+
+ code_block = f"""
+ <marimo-code hidden="">
+ {urllib.parse.quote(code)}
+ </marimo-code>
+ """
+ if not code:
+ code_block = '<marimo-code hidden=""></marimo-code>'
+
+ # Replace all relative href and src with absolute URL
+ html = (
+ html.replace("href='./", f"crossorigin='anonymous' href='{asset_url}/")
+ .replace("src='./", f"crossorigin='anonymous' src='{asset_url}/")
+ .replace('href="./', f'crossorigin="anonymous" href="{asset_url}/')
+ .replace('src="./', f'crossorigin="anonymous" src="{asset_url}/')
+ )
+
+ # Append to body
+ html = html.replace("</head>", f"{static_block}</head>")
+ # Append to body
+ html = html.replace("</body>", f"{code_block}</body>")
+
+ return html
+
+
+def _serialize_to_base64(value: str) -> str:
+ # Encode the JSON string to URL-encoded format
+ url_encoded = urllib.parse.quote(value)
+ # Encode the URL-encoded string to Base64
+ base64_encoded = base64.b64encode(url_encoded.encode()).decode()
+ return base64_encoded
+
+
+def _serialize_list_to_base64(value: list[str]) -> list[str]:
+ return [_serialize_to_base64(v) for v in value]
diff --git a/tests/.gitignore b/tests/.gitignore
new file mode 100644
index 0000000000..3b4a1161f0
--- /dev/null
+++ b/tests/.gitignore
@@ -0,0 +1 @@
+!**/snapshots/*
diff --git a/tests/_runtime/test_autoreload.py b/tests/_runtime/test_autoreload.py
index 3e019a2b97..2b92520648 100644
--- a/tests/_runtime/test_autoreload.py
+++ b/tests/_runtime/test_autoreload.py
@@ -7,7 +7,7 @@ import sys
import textwrap
import time
-from marimo._config.config import DEFAULT_CONFIG
+from marimo._config.config import DEFAULT_CONFIG, _deep_copy
from marimo._runtime.autoreload import ModuleReloader
from marimo._runtime.requests import SetUserConfigRequest
from marimo._runtime.runtime import Kernel
@@ -79,7 +79,7 @@ async def test_reload_function_kernel(
)
)
- config = DEFAULT_CONFIG.copy()
+ config = _deep_copy(DEFAULT_CONFIG)
config["runtime"]["auto_reload"] = True
k.set_user_config(SetUserConfigRequest(config=config))
await k.run([exec_req.get(f"import {py_modname}; x={py_modname}.foo()")])
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index 8671b59737..0d7ab43aa7 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -2,7 +2,6 @@
from __future__ import annotations
import sys
-from types import ModuleType
from typing import TYPE_CHECKING, Sequence
import pytest
@@ -30,6 +29,7 @@ from tests.conftest import ExecReqProvider
if TYPE_CHECKING:
import pathlib
+ from types import ModuleType
def _check_edges(error: Error, expected_edges: Sequence[Edge]) -> None:
diff --git a/tests/_runtime/test_virtual_file.py b/tests/_runtime/test_virtual_file.py
index 7498340574..32afbc42d1 100644
--- a/tests/_runtime/test_virtual_file.py
+++ b/tests/_runtime/test_virtual_file.py
@@ -242,3 +242,26 @@ async def test_cached_vfile_disposal(
await k.run([append_vfile])
assert len(ctx.virtual_file_registry.registry) == 1
assert vfile not in ctx.virtual_file_registry.filenames()
+
+
+async def test_virtual_files_not_supported(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ get_context().virtual_files_supported = False
+
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import io
+ import marimo as mo
+ bytestream = io.BytesIO(b"hello world")
+ pdf_plugin = mo.pdf(bytestream)
+ """
+ ),
+ ],
+ )
+
+ ctx = get_context()
+ assert len(ctx.virtual_file_registry.registry) == 0
+ ctx.virtual_files_supported = True
diff --git a/tests/_server/api/endpoints/test_export.py b/tests/_server/api/endpoints/test_export.py
new file mode 100644
index 0000000000..da687ff84f
--- /dev/null
+++ b/tests/_server/api/endpoints/test_export.py
@@ -0,0 +1,55 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from tests._server.conftest import get_session_manager
+from tests._server.mocks import with_session
+from tests.mocks import snapshotter
+
+if TYPE_CHECKING:
+ from starlette.testclient import TestClient
+
+snapshot = snapshotter(__file__)
+
+SESSION_ID = "session-123"
+HEADERS = {
+ "Marimo-Session-Id": SESSION_ID,
+ "Marimo-Server-Token": "fake-token",
+}
+
+
+@with_session(SESSION_ID)
+def test_export_html(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>' not in body
+
+
+@with_session(SESSION_ID)
+def test_export_html_no_code(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": False,
+ },
+ )
+ body = response.text
+ assert '<marimo-code hidden=""></marimo-code>' in body
diff --git a/tests/_server/session/test_session_view.py b/tests/_server/session/test_session_view.py
index 579a384d56..04c7c13a25 100644
--- a/tests/_server/session/test_session_view.py
+++ b/tests/_server/session/test_session_view.py
@@ -1,4 +1,5 @@
# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
from typing import Any
from unittest.mock import patch
@@ -326,3 +327,99 @@ def test_stdin(time_mock: Any) -> None:
CellOutput.stdout("Hello"),
CellOutput.stdout("What is your name? marimo\n"),
]
+
+
+@patch("time.time", return_value=123)
+def test_get_cell_outputs(time_mock: Any) -> None:
+ del time_mock
+ cell_2_id = "cell_2"
+ session_view = SessionView()
+ session_view.add_operation(
+ CellOp(
+ cell_id=cell_id,
+ output=initial_output,
+ status=initial_status,
+ ),
+ )
+ session_view.add_operation(
+ CellOp(
+ cell_id=cell_2_id,
+ output=None,
+ status=updated_status,
+ ),
+ )
+
+ assert session_view.get_cell_outputs([cell_id]) == {
+ cell_id: initial_output
+ }
+ assert session_view.get_cell_outputs([cell_id, cell_2_id]) == {
+ cell_id: initial_output
+ }
+
+ session_view.add_operation(
+ CellOp(
+ cell_id=cell_id,
+ output=updated_output,
+ status=updated_status,
+ )
+ )
+ session_view.add_operation(
+ CellOp(
+ cell_id=cell_2_id,
+ output=updated_output,
+ status=updated_status,
+ )
+ )
+
+ assert session_view.get_cell_outputs([cell_id, cell_2_id]) == {
+ cell_id: updated_output,
+ cell_2_id: updated_output,
+ }
+
+
+@patch("time.time", return_value=123)
+def test_get_cell_console_outputs(time_mock: Any) -> None:
+ del time_mock
+ cell_2_id = "cell_2"
+ session_view = SessionView()
+ session_view.add_operation(
+ CellOp(
+ cell_id=cell_id,
+ console=[CellOutput.stdout("one")],
+ status=initial_status,
+ )
+ )
+ session_view.add_operation(
+ CellOp(
+ cell_id=cell_2_id,
+ console=None,
+ status=updated_status,
+ )
+ )
+
+ assert session_view.get_cell_console_outputs([cell_id]) == {
+ cell_id: [CellOutput.stdout("one")]
+ }
+ assert session_view.get_cell_console_outputs([cell_id, cell_2_id]) == {
+ cell_id: [CellOutput.stdout("one")],
+ }
+
+ session_view.add_operation(
+ CellOp(
+ cell_id=cell_id,
+ console=[CellOutput.stdout("two")],
+ status=updated_status,
+ )
+ )
+ session_view.add_operation(
+ CellOp(
+ cell_id=cell_2_id,
+ console=[CellOutput.stdout("two")],
+ status=updated_status,
+ )
+ )
+
+ assert session_view.get_cell_console_outputs([cell_id, cell_2_id]) == {
+ cell_id: [CellOutput.stdout("one"), CellOutput.stdout("two")],
+ cell_2_id: [CellOutput.stdout("two")],
+ }
diff --git a/tests/_server/templates/data/index.html b/tests/_server/templates/data/index.html
new file mode 100644
index 0000000000..fd94e42184
--- /dev/null
+++ b/tests/_server/templates/data/index.html
@@ -0,0 +1,69 @@
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <base href='{{ base_url }}/' />
+ <meta charset="utf-8" />
+ <link rel="icon" href="./favicon.ico" />
+ <!-- Preload is necessary because we show these images when we disconnect from the server,
+ but at that point we cannot load these images from the server -->
+ <link rel="preload" href="./assets/gradient-yHQUC_QB.png" as="image" />
+ <link rel="preload" href="./assets/noise-60BoTA8O.png" as="image" />
+ <!-- Preload the fonts -->
+ <link rel="preload" href="./assets/Lora-VariableFont_wght-B2ootaw-.ttf" as="font" crossorigin="anonymous" />
+ <link rel="preload" href="./assets/PTSans-Regular-CxL0S8W7.ttf" as="font" crossorigin="anonymous" />
+ <link rel="preload" href="./assets/PTSans-Bold-D9fedIX3.ttf" as="font" crossorigin="anonymous" />
+ <link rel="preload" href="./assets/FiraMono-Regular-BTCkDNvf.ttf" as="font" crossorigin="anonymous" />
+ <link rel="preload" href="./assets/FiraMono-Medium-DU3aDxX5.ttf" as="font" crossorigin="anonymous" />
+ <link rel="preload" href="./assets/FiraMono-Bold-CLVRCuM9.ttf" as="font" crossorigin="anonymous" />
+
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <meta name="theme-color" content="#000000" />
+ <meta name="description" content="a marimo app" />
+ <link rel="apple-touch-icon" href="./apple-touch-icon.png" />
+ <link rel="manifest" href="./manifest.json" />
+
+ <script data-marimo="true">
+ function __resizeIframe(obj) {
+ var scrollbarHeight = 20; // Max between windows, mac, and linux
+
+ function setHeight() {
+ var element = obj.contentWindow.document.documentElement;
+ // If there is no vertical scrollbar, we don't need to resize the iframe
+ if (element.scrollHeight === element.clientHeight) {
+ return;
+ }
+
+ // Create a new height that includes the scrollbar height if it's visible
+ var hasHorizontalScrollbar = element.scrollWidth > element.clientWidth;
+ var newHeight = element.scrollHeight + (hasHorizontalScrollbar ? scrollbarHeight : 0);
+
+ // Only update the height if it's different from the current height
+ if (obj.style.height !== `${newHeight}px`) {
+ obj.style.height = `${newHeight}px`;
+ }
+ }
+
+ // Resize the iframe to the height of the content and bottom scrollbar height
+ setHeight();
+
+ // Resize the iframe when the content changes
+ const resizeObserver = new ResizeObserver((entries) => {
+ setHeight();
+ });
+ resizeObserver.observe(obj.contentWindow.document.body);
+ }
+ </script>
+ <marimo-filename hidden>{{ filename }}</marimo-filename>
+ <marimo-mode data-mode='{{ mode }}' hidden></marimo-mode>
+ <marimo-version data-version='{{ version }}' hidden></marimo-version>
+ <marimo-user-config data-config='{{ user_config }}' hidden></marimo-user-config>
+ <marimo-app-config data-config='{{ app_config }}' hidden></marimo-app-config>
+ <marimo-server-token data-token='{{ server_token }}' hidden></marimo-server-token>
+ <title>{{ title }}</title>
+ <script type="module" crossorigin src="./assets/index-h93-9ptT.js"></script>
+ <link rel="stylesheet" crossorigin href="./assets/index-Bkoicf0g.css">
+ </head>
+ <body>
+ <div id="root"></div>
+ </body>
+</html>
diff --git a/tests/_server/templates/snapshots/export1.txt b/tests/_server/templates/snapshots/export1.txt
new file mode 100644
index 0000000000..86a478115b
--- /dev/null
+++ b/tests/_server/templates/snapshots/export1.txt
@@ -0,0 +1,81 @@
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <base href='/' />
+ <meta charset="utf-8" />
+ <link rel="icon" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/favicon.ico" />
+ <!-- Preload is necessary because we show these images when we disconnect from the server,
+ but at that point we cannot load these images from the server -->
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/gradient.png"" as="image" />
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/noise.png"" as="image" />
+ <!-- Preload the fonts -->
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/Lora-VariableFont_wght.ttf"" as="font" crossorigin="anonymous" />
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/PTSans-Regular.ttf"" as="font" crossorigin="anonymous" />
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/PTSans-Bold.ttf"" as="font" crossorigin="anonymous" />
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/FiraMono-Regular.ttf"" as="font" crossorigin="anonymous" />
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/FiraMono-Medium.ttf"" as="font" crossorigin="anonymous" />
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/FiraMono-Bold.ttf"" as="font" crossorigin="anonymous" />
+
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <meta name="theme-color" content="#000000" />
+ <meta name="description" content="a marimo app" />
+ <link rel="apple-touch-icon" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/apple-touch-icon.png" />
+ <link rel="manifest" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/manifest.json" />
+
+ <script data-marimo="true">
+ function __resizeIframe(obj) {
+ var scrollbarHeight = 20; // Max between windows, mac, and linux
+
+ function setHeight() {
+ var element = obj.contentWindow.document.documentElement;
+ // If there is no vertical scrollbar, we don't need to resize the iframe
+ if (element.scrollHeight === element.clientHeight) {
+ return;
+ }
+
+ // Create a new height that includes the scrollbar height if it's visible
+ var hasHorizontalScrollbar = element.scrollWidth > element.clientWidth;
+ var newHeight = element.scrollHeight + (hasHorizontalScrollbar ? scrollbarHeight : 0);
+
+ // Only update the height if it's different from the current height
+ if (obj.style.height !== `${newHeight}px`) {
+ obj.style.height = `${newHeight}px`;
+ }
+ }
+
+ // Resize the iframe to the height of the content and bottom scrollbar height
+ setHeight();
+
+ // Resize the iframe when the content changes
+ const resizeObserver = new ResizeObserver((entries) => {
+ setHeight();
+ });
+ resizeObserver.observe(obj.contentWindow.document.body);
+ }
+ </script>
+ <marimo-filename hidden>notebook.py</marimo-filename>
+ <marimo-mode data-mode='read' hidden></marimo-mode>
+ <marimo-version data-version='0.0.0' hidden></marimo-version>
+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": false}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default"}}' hidden></marimo-user-config>
+ <marimo-app-config data-config='{"layout_file": null, "width": "normal"}' hidden></marimo-app-config>
+ <marimo-server-token data-token='token' hidden></marimo-server-token>
+ <title>notebook</title>
+ <script type="module" crossorigin crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.js""></script>
+ <link rel="stylesheet" crossorigin crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.css"">
+
+ <script data-marimo="true">
+ window.__MARIMO_STATIC__ = {};
+ window.__MARIMO_STATIC__.version = "0.0.0";
+ window.__MARIMO_STATIC__.notebookState = {"cellIds": ["cell1", "cell2"], "cellNames": ["Q2VsbCUyMDE=", "Q2VsbCUyMDI="], "cellCodes": ["cHJpbnQlMjglMjdIZWxsbyUyQyUyMENlbGwlMjAxJTI3JTI5", "cHJpbnQlMjglMjdIZWxsbyUyQyUyMENlbGwlMjAyJTI3JTI5"], "cellConfigs": ["JTdCJTIyZGlzYWJsZWQlMjIlM0ElMjBmYWxzZSUyQyUyMCUyMmhpZGVfY29kZSUyMiUzQSUyMGZhbHNlJTdE", "JTdCJTIyZGlzYWJsZWQlMjIlM0ElMjBmYWxzZSUyQyUyMCUyMmhpZGVfY29kZSUyMiUzQSUyMGZhbHNlJTdE"], "cellOutputs": {"cell1": "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMm91dHB1dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dC9wbGFpbiUyMiUyQyUyMCUyMmRhdGElMjIlM0ElMjAlMjJIZWxsbyUyQyUyMENlbGwlMjAxJTIyJTJDJTIwJTIydGltZXN0YW1wJTIyJTNBJTIwMCU3RA=="}, "cellConsoleOutputs": {"cell1": ["JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZG91dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dC9wbGFpbiUyMiUyQyUyMCUyMmRhdGElMjIlM0ElMjAlMjJIZWxsbyUyQyUyMENlbGwlMjAxJTIyJTJDJTIwJTIydGltZXN0YW1wJTIyJTNBJTIwMCU3RA==", "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZGVyciUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dC9wbGFpbiUyMiUyQyUyMCUyMmRhdGElMjIlM0ElMjAlMjJFcnJvciUyMGluJTIwQ2VsbCUyMDElMjIlMkMlMjAlMjJ0aW1lc3RhbXAlMjIlM0ElMjAwJTdE"]}};
+ window.__MARIMO_STATIC__.assetUrl = "https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist";
+ window.__MARIMO_STATIC__.files = {"file1": "File 1 content", "file2": "File 2 content"};
+ </script>
+ </head>
+ <body>
+ <div id="root"></div>
+
+ <marimo-code hidden="">
+ print%28%27Hello%2C%20World%21%27%29
+ </marimo-code>
+ </body>
+</html>
diff --git a/tests/_server/templates/snapshots/export2.txt b/tests/_server/templates/snapshots/export2.txt
new file mode 100644
index 0000000000..e4a3b3956e
--- /dev/null
+++ b/tests/_server/templates/snapshots/export2.txt
@@ -0,0 +1,81 @@
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <base href='/' />
+ <meta charset="utf-8" />
+ <link rel="icon" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/favicon.ico" />
+ <!-- Preload is necessary because we show these images when we disconnect from the server,
+ but at that point we cannot load these images from the server -->
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/gradient.png"" as="image" />
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/noise.png"" as="image" />
+ <!-- Preload the fonts -->
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/Lora-VariableFont_wght.ttf"" as="font" crossorigin="anonymous" />
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/PTSans-Regular.ttf"" as="font" crossorigin="anonymous" />
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/PTSans-Bold.ttf"" as="font" crossorigin="anonymous" />
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/FiraMono-Regular.ttf"" as="font" crossorigin="anonymous" />
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/FiraMono-Medium.ttf"" as="font" crossorigin="anonymous" />
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/FiraMono-Bold.ttf"" as="font" crossorigin="anonymous" />
+
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <meta name="theme-color" content="#000000" />
+ <meta name="description" content="a marimo app" />
+ <link rel="apple-touch-icon" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/apple-touch-icon.png" />
+ <link rel="manifest" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/manifest.json" />
+
+ <script data-marimo="true">
+ function __resizeIframe(obj) {
+ var scrollbarHeight = 20; // Max between windows, mac, and linux
+
+ function setHeight() {
+ var element = obj.contentWindow.document.documentElement;
+ // If there is no vertical scrollbar, we don't need to resize the iframe
+ if (element.scrollHeight === element.clientHeight) {
+ return;
+ }
+
+ // Create a new height that includes the scrollbar height if it's visible
+ var hasHorizontalScrollbar = element.scrollWidth > element.clientWidth;
+ var newHeight = element.scrollHeight + (hasHorizontalScrollbar ? scrollbarHeight : 0);
+
+ // Only update the height if it's different from the current height
+ if (obj.style.height !== `${newHeight}px`) {
+ obj.style.height = `${newHeight}px`;
+ }
+ }
+
+ // Resize the iframe to the height of the content and bottom scrollbar height
+ setHeight();
+
+ // Resize the iframe when the content changes
+ const resizeObserver = new ResizeObserver((entries) => {
+ setHeight();
+ });
+ resizeObserver.observe(obj.contentWindow.document.body);
+ }
+ </script>
+ <marimo-filename hidden></marimo-filename>
+ <marimo-mode data-mode='read' hidden></marimo-mode>
+ <marimo-version data-version='0.0.0' hidden></marimo-version>
+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": false}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default"}}' hidden></marimo-user-config>
+ <marimo-app-config data-config='{"layout_file": null, "width": "normal"}' hidden></marimo-app-config>
+ <marimo-server-token data-token='token' hidden></marimo-server-token>
+ <title>marimo</title>
+ <script type="module" crossorigin crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.js""></script>
+ <link rel="stylesheet" crossorigin crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.css"">
+
+ <script data-marimo="true">
+ window.__MARIMO_STATIC__ = {};
+ window.__MARIMO_STATIC__.version = "0.0.0";
+ window.__MARIMO_STATIC__.notebookState = {"cellIds": ["cell1", "cell2"], "cellNames": ["Q2VsbCUyMDE=", "Q2VsbCUyMDI="], "cellCodes": ["cHJpbnQlMjglMjdIZWxsbyUyQyUyMENlbGwlMjAxJTI3JTI5", "cHJpbnQlMjglMjdIZWxsbyUyQyUyMENlbGwlMjAyJTI3JTI5"], "cellConfigs": ["JTdCJTIyZGlzYWJsZWQlMjIlM0ElMjBmYWxzZSUyQyUyMCUyMmhpZGVfY29kZSUyMiUzQSUyMGZhbHNlJTdE", "JTdCJTIyZGlzYWJsZWQlMjIlM0ElMjBmYWxzZSUyQyUyMCUyMmhpZGVfY29kZSUyMiUzQSUyMGZhbHNlJTdE"], "cellOutputs": {"cell1": "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMm91dHB1dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dC9wbGFpbiUyMiUyQyUyMCUyMmRhdGElMjIlM0ElMjAlMjJIZWxsbyUyQyUyMENlbGwlMjAxJTIyJTJDJTIwJTIydGltZXN0YW1wJTIyJTNBJTIwMCU3RA=="}, "cellConsoleOutputs": {"cell1": ["JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZG91dCUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dC9wbGFpbiUyMiUyQyUyMCUyMmRhdGElMjIlM0ElMjAlMjJIZWxsbyUyQyUyMENlbGwlMjAxJTIyJTJDJTIwJTIydGltZXN0YW1wJTIyJTNBJTIwMCU3RA==", "JTdCJTIyY2hhbm5lbCUyMiUzQSUyMCUyMnN0ZGVyciUyMiUyQyUyMCUyMm1pbWV0eXBlJTIyJTNBJTIwJTIydGV4dC9wbGFpbiUyMiUyQyUyMCUyMmRhdGElMjIlM0ElMjAlMjJFcnJvciUyMGluJTIwQ2VsbCUyMDElMjIlMkMlMjAlMjJ0aW1lc3RhbXAlMjIlM0ElMjAwJTdE"]}};
+ window.__MARIMO_STATIC__.assetUrl = "https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist";
+ window.__MARIMO_STATIC__.files = {"file1": "File 1 content", "file2": "File 2 content"};
+ </script>
+ </head>
+ <body>
+ <div id="root"></div>
+
+ <marimo-code hidden="">
+ print%28%27Hello%2C%20World%21%27%29
+ </marimo-code>
+ </body>
+</html>
diff --git a/tests/_server/templates/snapshots/export3.txt b/tests/_server/templates/snapshots/export3.txt
new file mode 100644
index 0000000000..7ef0244a7d
--- /dev/null
+++ b/tests/_server/templates/snapshots/export3.txt
@@ -0,0 +1,77 @@
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <base href='/' />
+ <meta charset="utf-8" />
+ <link rel="icon" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/favicon.ico" />
+ <!-- Preload is necessary because we show these images when we disconnect from the server,
+ but at that point we cannot load these images from the server -->
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/gradient.png"" as="image" />
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/noise.png"" as="image" />
+ <!-- Preload the fonts -->
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/Lora-VariableFont_wght.ttf"" as="font" crossorigin="anonymous" />
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/PTSans-Regular.ttf"" as="font" crossorigin="anonymous" />
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/PTSans-Bold.ttf"" as="font" crossorigin="anonymous" />
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/FiraMono-Regular.ttf"" as="font" crossorigin="anonymous" />
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/FiraMono-Medium.ttf"" as="font" crossorigin="anonymous" />
+ <link rel="preload" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/FiraMono-Bold.ttf"" as="font" crossorigin="anonymous" />
+
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <meta name="theme-color" content="#000000" />
+ <meta name="description" content="a marimo app" />
+ <link rel="apple-touch-icon" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/apple-touch-icon.png" />
+ <link rel="manifest" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/manifest.json" />
+
+ <script data-marimo="true">
+ function __resizeIframe(obj) {
+ var scrollbarHeight = 20; // Max between windows, mac, and linux
+
+ function setHeight() {
+ var element = obj.contentWindow.document.documentElement;
+ // If there is no vertical scrollbar, we don't need to resize the iframe
+ if (element.scrollHeight === element.clientHeight) {
+ return;
+ }
+
+ // Create a new height that includes the scrollbar height if it's visible
+ var hasHorizontalScrollbar = element.scrollWidth > element.clientWidth;
+ var newHeight = element.scrollHeight + (hasHorizontalScrollbar ? scrollbarHeight : 0);
+
+ // Only update the height if it's different from the current height
+ if (obj.style.height !== `${newHeight}px`) {
+ obj.style.height = `${newHeight}px`;
+ }
+ }
+
+ // Resize the iframe to the height of the content and bottom scrollbar height
+ setHeight();
+
+ // Resize the iframe when the content changes
+ const resizeObserver = new ResizeObserver((entries) => {
+ setHeight();
+ });
+ resizeObserver.observe(obj.contentWindow.document.body);
+ }
+ </script>
+ <marimo-filename hidden>notebook.py</marimo-filename>
+ <marimo-mode data-mode='read' hidden></marimo-mode>
+ <marimo-version data-version='0.0.0' hidden></marimo-version>
+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": false}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default"}}' hidden></marimo-user-config>
+ <marimo-app-config data-config='{"layout_file": null, "width": "normal"}' hidden></marimo-app-config>
+ <marimo-server-token data-token='token' hidden></marimo-server-token>
+ <title>notebook</title>
+ <script type="module" crossorigin crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.js""></script>
+ <link rel="stylesheet" crossorigin crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index.css"">
+
+ <script data-marimo="true">
+ window.__MARIMO_STATIC__ = {};
+ window.__MARIMO_STATIC__.version = "0.0.0";
+ window.__MARIMO_STATIC__.notebookState = {"cellIds": [], "cellNames": [], "cellCodes": [], "cellConfigs": [], "cellOutputs": {}, "cellConsoleOutputs": {}};
+ window.__MARIMO_STATIC__.assetUrl = "https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist";
+ window.__MARIMO_STATIC__.files = {};
+ </script>
+ </head>
+ <body>
+ <div id="root"></div>
+ <marimo-code hidden=""></marimo-code></body>
+</html>
diff --git a/tests/_server/templates/test_templates.py b/tests/_server/templates/test_templates.py
new file mode 100644
index 0000000000..7cd34e5346
--- /dev/null
+++ b/tests/_server/templates/test_templates.py
@@ -0,0 +1,214 @@
+from __future__ import annotations
+
+import json
+import os
+import unittest
+
+from marimo._ast.app import _AppConfig
+from marimo._ast.cell import CellConfig
+from marimo._config.config import DEFAULT_CONFIG
+from marimo._messaging.cell_output import CellChannel, CellOutput
+from marimo._server.model import SessionMode
+from marimo._server.templates import templates
+from tests._server.templates.utils import normalize_index_html
+from tests.mocks import snapshotter
+
+snapshot = snapshotter(__file__)
+
+
+class TestNotebookPageTemplate(unittest.TestCase):
+ def setUp(self):
+ root = os.path.realpath(
+ os.path.join(os.path.dirname(__file__), "data")
+ )
+ index_html = os.path.join(root, "index.html")
+ with open(index_html, "r") as f:
+ self.html = f.read()
+
+ self.base_url = "/subpath"
+ self.user_config = DEFAULT_CONFIG
+ self.server_token = "token"
+ self.app_config = _AppConfig()
+ self.filename = "notebook.py"
+ self.mode = SessionMode.RUN
+
+ def test_notebook_page_template(self):
+ result = templates.notebook_page_template(
+ self.html,
+ self.base_url,
+ self.user_config,
+ self.server_token,
+ self.app_config,
+ self.filename,
+ self.mode,
+ )
+
+ assert self.base_url in result
+ assert self.server_token in result
+ assert self.filename in result
+ assert "read" in result
+
+ def test_notebook_page_template_no_filename(self):
+ result = templates.notebook_page_template(
+ self.html,
+ self.base_url,
+ self.user_config,
+ self.server_token,
+ self.app_config,
+ None,
+ self.mode,
+ )
+
+ assert self.base_url in result
+ assert self.server_token in result
+ assert "<title>marimo</title>" in result
+ assert "read" in result
+
+ def test_notebook_page_template_edit_mode(self):
+ result = templates.notebook_page_template(
+ self.html,
+ self.base_url,
+ self.user_config,
+ self.server_token,
+ self.app_config,
+ self.filename,
+ SessionMode.EDIT,
+ )
+
+ assert self.base_url in result
+ assert self.server_token in result
+ assert self.filename in result
+ assert "edit" in result
+
+
+class TestHomePageTemplate(unittest.TestCase):
+ def setUp(self):
+ root = os.path.realpath(
+ os.path.join(os.path.dirname(__file__), "data")
+ )
+ index_html = os.path.join(root, "index.html")
+ with open(index_html, "r") as f:
+ self.html = f.read()
+
+ self.base_url = "/subpath"
+ self.user_config = DEFAULT_CONFIG
+ self.server_token = "token"
+
+ def test_home_page_template(self):
+ result = templates.home_page_template(
+ self.html,
+ self.base_url,
+ self.user_config,
+ self.server_token,
+ )
+
+ assert self.base_url in result
+ assert self.server_token in result
+ assert json.dumps(self.user_config) in result
+ assert "marimo" in result
+ assert json.dumps({}) in result
+ assert "" in result
+ assert "home" in result
+
+
+class TestStaticNotebookTemplate(unittest.TestCase):
+ def setUp(self):
+ root = os.path.realpath(
+ os.path.join(os.path.dirname(__file__), "data")
+ )
+ index_html = os.path.join(root, "index.html")
+ with open(index_html, "r") as f:
+ self.html = f.read()
+
+ self.user_config = DEFAULT_CONFIG
+ self.server_token = "token"
+ self.app_config = _AppConfig()
+ self.filename = "notebook.py"
+ self.code = "print('Hello, World!')"
+ self.cell_ids = ["cell1", "cell2"]
+ self.cell_names = ["Cell 1", "Cell 2"]
+ self.cell_codes = ["print('Hello, Cell 1')", "print('Hello, Cell 2')"]
+ self.cell_configs = [CellConfig(), CellConfig()]
+ self.cell_outputs = {
+ "cell1": CellOutput(
+ channel=CellChannel.OUTPUT,
+ data="Hello, Cell 1",
+ mimetype="text/plain",
+ timestamp=0,
+ )
+ }
+ self.cell_console_outputs = {
+ "cell1": [
+ CellOutput(
+ channel=CellChannel.STDOUT,
+ data="Hello, Cell 1",
+ mimetype="text/plain",
+ timestamp=0,
+ ),
+ CellOutput(
+ channel=CellChannel.STDERR,
+ data="Error in Cell 1",
+ mimetype="text/plain",
+ timestamp=0,
+ ),
+ ],
+ "cell2": [],
+ }
+ self.files = {"file1": "File 1 content", "file2": "File 2 content"}
+
+ def test_static_notebook_template(self):
+ result = templates.static_notebook_template(
+ self.html,
+ self.user_config,
+ self.server_token,
+ self.app_config,
+ self.filename,
+ self.code,
+ self.cell_ids,
+ self.cell_names,
+ self.cell_codes,
+ self.cell_configs,
+ self.cell_outputs,
+ self.cell_console_outputs,
+ self.files,
+ )
+
+ snapshot("export1.txt", normalize_index_html(result))
+
+ def test_static_notebook_template_no_filename(self):
+ result = templates.static_notebook_template(
+ self.html,
+ self.user_config,
+ self.server_token,
+ self.app_config,
+ None,
+ self.code,
+ self.cell_ids,
+ self.cell_names,
+ self.cell_codes,
+ self.cell_configs,
+ self.cell_outputs,
+ self.cell_console_outputs,
+ files=self.files,
+ )
+
+ snapshot("export2.txt", normalize_index_html(result))
+
+ def test_static_notebook_template_no_code(self):
+ result = templates.static_notebook_template(
+ self.html,
+ self.user_config,
+ self.server_token,
+ self.app_config,
+ self.filename,
+ "",
+ [],
+ [],
+ [],
+ [],
+ {},
+ {},
+ {},
+ )
+
+ snapshot("export3.txt", normalize_index_html(result))
diff --git a/tests/_server/templates/utils.py b/tests/_server/templates/utils.py
new file mode 100644
index 0000000000..a8187d4ac2
--- /dev/null
+++ b/tests/_server/templates/utils.py
@@ -0,0 +1,43 @@
+from __future__ import annotations
+
+import os
+import re
+
+from marimo import __version__
+
+
+def remove_hash_from_href(url: str) -> str:
+ base, ext = os.path.splitext(url)
+ if len(base) < 10:
+ return url
+ if base[-9] == "-": # Hash is 9 characters long
+ return f'{base[:-9]}{ext}"'
+ return url
+
+
+def normalize_index_html(index_html: str) -> str:
+ # Remove the hash from the URLs in the index.html
+ # And remove the version
+ # This is so the snapshots can stay stable across versions
+ index_html = re.sub(
+ r'href="[^"]+"',
+ lambda x: remove_hash_from_href(x.group(0)),
+ index_html,
+ )
+ index_html = re.sub(
+ r"href='[^']+'",
+ lambda x: remove_hash_from_href(x.group(0)),
+ index_html,
+ )
+ index_html = re.sub(
+ r'src="[^"]+"',
+ lambda x: remove_hash_from_href(x.group(0)),
+ index_html,
+ )
+ index_html = re.sub(
+ r"src='[^']+'",
+ lambda x: remove_hash_from_href(x.group(0)),
+ index_html,
+ )
+ index_html = index_html.replace(__version__, "0.0.0")
+ return index_html
diff --git a/tests/_server/test_file_manager.py b/tests/_server/test_file_manager.py
index 10d8181ef4..d77c0d962a 100644
--- a/tests/_server/test_file_manager.py
+++ b/tests/_server/test_file_manager.py
@@ -1,9 +1,12 @@
+from __future__ import annotations
+
import os
import tempfile
from typing import Generator
import pytest
+from marimo import __version__
from marimo._ast.cell import CellConfig
from marimo._server.api.status import HTTPException, HTTPStatus
from marimo._server.file_manager import AppFileManager
@@ -182,3 +185,26 @@ def test_read_unnamed_notebook(app_file_manager: AppFileManager) -> None:
def test_read_layout(app_file_manager: AppFileManager) -> None:
layout = app_file_manager.read_layout_config()
assert layout is None
+
+
+def test_to_code(app_file_manager: AppFileManager) -> None:
+ code = app_file_manager.to_code()
+ assert code == "\n".join(
+ [
+ "import marimo",
+ "",
+ f'__generated_with = "{__version__}"',
+ "app = marimo.App()",
+ "",
+ "",
+ "@app.cell",
+ "def __():",
+ " import marimo as mo",
+ " return mo,",
+ "",
+ "",
+ 'if __name__ == "__main__":',
+ " app.run()",
+ "",
+ ]
+ )
diff --git a/tests/mocks.py b/tests/mocks.py
new file mode 100644
index 0000000000..7e4a5e3308
--- /dev/null
+++ b/tests/mocks.py
@@ -0,0 +1,56 @@
+from __future__ import annotations
+
+import difflib
+import os
+from typing import Callable
+
+
+def snapshotter(current_file: str) -> Callable[[str, str], None]:
+ """
+ Utility function to create and compare snapshots.
+
+ If the snapshot doesn't exist, it will be created.
+
+ If the snapshot exists, it will be compared with the new result.
+ If the result is different, the test will fail,
+ but the snapshot will be updated with the new result.
+ """
+
+ def snapshot(filename: str, result: str) -> None:
+ filepath = os.path.join(
+ os.path.dirname(current_file), "snapshots", filename
+ )
+
+ # If snapshot directory doesn't exist, create it
+ if not os.path.exists(os.path.dirname(filepath)):
+ os.makedirs(os.path.dirname(filepath))
+
+ # If doesn't exist, create snapshot
+ if not os.path.exists(filepath):
+ with open(filepath, "w") as f:
+ f.write(result)
+ print("Snapshot updated")
+
+ # Read snapshot
+ with open(filepath, "r") as f:
+ expected = f.read()
+
+ with open(filepath, "w") as f:
+ f.write(result)
+
+ assert result, "Result is empty"
+ assert expected, "Expected is empty"
+ text_diff = "\n".join(
+ list(
+ difflib.unified_diff(
+ expected.splitlines(),
+ result.splitlines(),
+ lineterm="",
+ )
+ )
+ )
+ if expected != result:
+ print(f"Snapshot differs:\n{text_diff}")
+ assert result == expected
+
+ return snapshot