A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
experimental: start of static html (#303)
Myles Scolnick6cfafe2b1992
diff --git a/frontend/.storybook/preview-head.html b/frontend/.storybook/preview-head.htmlindex c9c1f13c54..046d5be921 100644--- a/frontend/.storybook/preview-head.html+++ b/frontend/.storybook/preview-head.html@@ -2,7 +2,7 @@<marimo-mode data-mode="edit" hidden></marimo-mode><marimo-version data-mode="0.1.0" hidden></marimo-version><marimo-user-config- data-config='{"completion":{"activate_on_typing":false, "copilot": true},"save":{"autosave":"off","autosave_delay":0},"keymap":{"preset":"default"},"experimental":{"theming":true}}'+ data-config='{"completion":{"activate_on_typing":false, "copilot": true},"save":{"autosave":"off","autosave_delay":0},"keymap":{"preset":"default"},"experimental":{}}'hidden></marimo-user-config><marimo-app-config data-config="{}" hidden></marimo-app-config>diff --git a/frontend/package.json b/frontend/package.jsonindex dfc3f2fdfa..197e224c13 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -59,6 +59,7 @@"@tanstack/react-table": "^8.10.7","@textea/json-viewer": "^3.2.3","@types/js-cookie": "^3.0.5",+ "@types/jsdom": "^21.1.5","@types/react-grid-layout": "^1.3.4","@uiw/react-codemirror": "^4.21.20","class-variance-authority": "^0.7.0",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex aae768a802..5bceb43c38 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -146,6 +146,9 @@ dependencies:'@types/js-cookie':specifier: ^3.0.5version: 3.0.5+ '@types/jsdom':+ specifier: ^21.1.5+ version: 21.1.5'@types/react-grid-layout':specifier: ^1.3.4version: 1.3.4@@ -6197,6 +6200,14 @@ packages:resolution: {integrity: sha512-qC4bCqYGy1y/NP7dDVr7KJarn+PbX1nSpwA7JXdu0HxT3QYjO8MJ+cntENtHFVy2dRAyBV23OZ6MxsW1AM1L8g==}dev: true+ /@types/[email protected]:+ resolution: {integrity: sha512-sBK/3YjS3uuPj+HzZyhB4GGTnFmk0mdyQfhzZ/sqs9ciyG41QJdZZdwcPa6OfW97OTNTwl5tBAsfEOm/dui9pQ==}+ dependencies:+ '@types/node': 20.8.10+ '@types/tough-cookie': 4.0.4+ parse5: 7.1.2+ dev: false+/@types/[email protected]:resolution: {integrity: sha512-qcUXuemtEu+E5wZSJHNxUXeCZhAfXKQ41D+duX+VYPde7xyEVZci+/oXKJL13tnRs9lR2pr4fod59GT6/X1/yQ==}@@ -6361,6 +6372,10 @@ packages:resolution: {integrity: sha512-dH4FlIn2s6EJw8PsAzanFGYZKu/4VcqIb7gMglB9bLDfgb5rkHulXzJLhxpxQXmu2IC+V8qV+Ut7Ejmw9JtVgw==}dev: true+ /@types/[email protected]:+ resolution: {integrity: sha512-95Sfz4nvMAb0Nl9DTxN3j64adfwfbBPEYq14VN7zT5J5O2M9V6iZMIIQU1U+pJyl9agHYHNCqhCXgyEtIRRa5A==}+ dev: false+/@types/[email protected]:resolution: {integrity: sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ==}dev: true@@ -12212,7 +12227,6 @@ packages:resolution: {integrity: sha512-Czj1WaSVpaoj0wbhMzLmWD69anp2WH7FXMB9n1Sy8/ZFF9jolSQVMu1Ij5WIyGmcBmhk7EOndpO4mIpihVqAXw==}dependencies:entities: 4.5.0- dev: trueresolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==}diff --git a/frontend/src/MarimoApp.tsx b/frontend/src/MarimoApp.tsxindex e670f2540d..6c428fe8d8 100644--- a/frontend/src/MarimoApp.tsx+++ b/frontend/src/MarimoApp.tsx@@ -12,6 +12,7 @@ import { CommandPallette } from "./editor/CommandPallette";import { useAppConfig, useUserConfig } from "@/core/state/config";import { initialMode } from "./core/mode";import { AppChrome } from "./editor/chrome/wrapper/app-chrome";+import { StaticBanner } from "./components/static-html/static-banner";/*** The root component of the Marimo app.@@ -27,6 +28,7 @@ export const MarimoApp: React.FC = () => {const body =initialMode === "read" ? (<>+ <StaticBanner /><App userConfig={userConfig} appConfig={appConfig} /><Toaster /></>diff --git a/frontend/src/components/static-html/static-banner.tsx b/frontend/src/components/static-html/static-banner.tsxnew file mode 100644index 0000000000..471a70635f--- /dev/null+++ b/frontend/src/components/static-html/static-banner.tsx@@ -0,0 +1,15 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { isStaticNotebook } from "@/core/static/static-state";+import React from "react";++export const StaticBanner: React.FC = () => {+ if (!isStaticNotebook()) {+ return null;+ }++ return (+ <div className="px-4 py-2 bg-[var(--sky-2)] border-b border-[var(--sky-7)] text-sm text-[var(--sky-11)] font-semibold">+ This is a static notebook. Any interactive features will not work.+ </div>+ );+};diff --git a/frontend/src/core/RuntimeState.ts b/frontend/src/core/RuntimeState.tsindex 8ad324f867..254b35eb7d 100644--- a/frontend/src/core/RuntimeState.ts+++ b/frontend/src/core/RuntimeState.ts@@ -2,6 +2,7 @@import { sendComponentValues } from "@/core/network/requests";import { marimoValueReadyEvent, MarimoValueReadyEventType } from "./dom/events";import { UI_ELEMENT_REGISTRY, UIElementRegistry } from "./dom/uiregistry";+import { isStaticNotebook } from "./static/static-state";/*** Manager to track running cells.@@ -55,7 +56,7 @@ export class RuntimeState {}running(): boolean {- return this.runningCount > 0;+ return this.runningCount > 0 && !isStaticNotebook();}flushUpdates() {diff --git a/frontend/src/core/config/config.ts b/frontend/src/core/config/config.tsindex e103b20e04..9e2d4b9b44 100644--- a/frontend/src/core/config/config.ts+++ b/frontend/src/core/config/config.ts@@ -35,6 +35,7 @@ export const UserConfigSchema = zexperimental: z.object({layouts: z.boolean().optional(),+ static_export: z.boolean().optional(),})// Pass through so that we don't remove any extra keys that the user has added..passthrough()diff --git a/frontend/src/core/config/feature-flag.ts b/frontend/src/core/config/feature-flag.tsindex ab0662dfcc..ed1841c972 100644--- a/frontend/src/core/config/feature-flag.ts+++ b/frontend/src/core/config/feature-flag.ts@@ -7,10 +7,15 @@ export interface ExperimentalFeatures {* Allows the user to switch between different layouts.*/layouts: boolean;+ /**+ * Allows the user to export the notebook as a static HTML file.+ */+ static_export: boolean;}const defaultValues: ExperimentalFeatures = {layouts: false,+ static_export: false,};export function getFeatureFlag<T extends keyof ExperimentalFeatures>(diff --git a/frontend/src/core/dom/version.ts b/frontend/src/core/dom/version.tsnew file mode 100644index 0000000000..c177b7cf1a--- /dev/null+++ b/frontend/src/core/dom/version.ts@@ -0,0 +1,19 @@+/* Copyright 2023 Marimo. All rights reserved. */++import { invariant } from "@/utils/invariant";++export function getMarimoVersion() {+ const tag = document.querySelector("marimo-version");+ invariant(+ tag !== null && tag instanceof HTMLElement,+ "internal-error: marimo-version tag not found"+ );++ const version = tag.dataset.version;+ invariant(+ version !== undefined,+ "internal-error: marimo-version tag does not have version"+ );++ return version;+}diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.tsindex 0823a6cd04..47731d9b0c 100644--- a/frontend/src/core/network/requests.ts+++ b/frontend/src/core/network/requests.ts@@ -1,6 +1,8 @@/* Copyright 2023 Marimo. All rights reserved. */import { CellId } from "../model/ids";+import { isStaticNotebook } from "../static/static-state";import { API } from "./api";+import { createStaticRequests } from "./static-requests";import {CodeCompletionRequest,DeleteRequest,@@ -17,119 +19,133 @@ import {SaveAppConfigRequest,SaveCellConfigRequest,SendFunctionRequest,+ RunRequests,+ EditRequests,} from "./types";import { invariant } from "@/utils/invariant";-interface ValueUpdate {- objectId: string;- value: unknown;-}--export function sendComponentValues(valueUpdates: ValueUpdate[]) {- const objectIds = [];- const values = [];- for (const update of valueUpdates) {- objectIds.push(update.objectId);- values.push(update.value);- }-- return API.post<SetComponentValuesRequest>("/kernel/set_ui_element_value/", {- objectIds: objectIds,- values: values,- });-}--export function sendRename(filename: string | null) {- return API.post<RenameRequest>("/kernel/rename/", {- filename: filename,- });-}--export function sendSave(request: SaveKernelRequest) {- // Validate same length- invariant(- request.codes.length === request.names.length,- "cell codes and names must be the same length"- );- invariant(- request.codes.length === request.configs.length,- "cell codes and configs must be the same length"- );-- return API.post<SaveKernelRequest>("/kernel/save/", request);-}--export function sendFormat(codes: Record<CellId, string>) {- return API.post<FormatRequest, FormatResponse>("/kernel/format/", {- codes: codes,- }).then((res) => res.codes);-}--export function sendInterrupt() {- return API.post("/kernel/interrupt/", {});-}--export function sendShutdown() {- return API.post("/kernel/shutdown/", {});-}--export function sendRun(cellId: CellId, code: string) {- return sendRunMultiple([cellId], [code]);-}--export function sendInstantiate(request: InstantiateRequest) {- // Validate same length- invariant(- request.objectIds.length === request.values.length,- "must be the same length"- );-- return API.post<InstantiateRequest>("/kernel/instantiate/", request);-}--export function sendRunMultiple(cellIds: CellId[], codes: string[]) {- // Validate same length- invariant(cellIds.length === codes.length, "must be the same length");-- return API.post<RunRequest>("/kernel/run/", {- cellIds: cellIds,- codes: codes,- });-}--export function sendDeleteCell(cellId: CellId) {- return API.post<DeleteRequest>("/kernel/delete/", {- cellId: cellId,- });-}--export async function sendDirectoryAutocompleteRequest(prefix: string) {- return API.post<- SendDirectoryAutocompleteRequest,- SendDirectoryAutocompleteResponse- >("/kernel/directory_autocomplete/", {- prefix: prefix,- });-}--export async function sendCodeCompletionRequest(- request: CodeCompletionRequest-) {- return API.post<CodeCompletionRequest>("/kernel/code_autocomplete/", request);-}--export function saveUserConfig(request: SaveUserConfigRequest) {- return API.post<SaveUserConfigRequest>("/kernel/save_user_config/", request);-}--export function saveAppConfig(request: SaveAppConfigRequest) {- return API.post<SaveAppConfigRequest>("/kernel/save_app_config/", request);-}--export function saveCellConfig(request: SaveCellConfigRequest) {- return API.post<SaveCellConfigRequest>("/kernel/set_cell_config/", request);-}--export function sendFunctionRequest(request: SendFunctionRequest) {- return API.post<SendFunctionRequest>("/kernel/function_call/", request);-}+function createNetworkRequests(): EditRequests & RunRequests {+ return {+ sendComponentValues: (valueUpdates) => {+ const objectIds: string[] = [];+ const values: unknown[] = [];+ for (const update of valueUpdates) {+ objectIds.push(update.objectId);+ values.push(update.value);+ }++ return API.post<SetComponentValuesRequest>(+ "/kernel/set_ui_element_value/",+ {+ objectIds: objectIds,+ values: values,+ }+ );+ },+ sendRename: (filename: string | null) => {+ return API.post<RenameRequest>("/kernel/rename/", {+ filename: filename,+ });+ },+ sendSave: (request: SaveKernelRequest) => {+ // Validate same length+ invariant(+ request.codes.length === request.names.length,+ "cell codes and names must be the same length"+ );+ invariant(+ request.codes.length === request.configs.length,+ "cell codes and configs must be the same length"+ );++ return API.post<SaveKernelRequest>("/kernel/save/", request);+ },+ sendFormat: (codes: Record<CellId, string>) => {+ return API.post<FormatRequest, FormatResponse>("/kernel/format/", {+ codes: codes,+ }).then((res) => res.codes);+ },+ sendInterrupt: () => {+ return API.post("/kernel/interrupt/", {});+ },+ sendShutdown: () => {+ return API.post("/kernel/shutdown/", {});+ },+ sendRun: (cellIds: CellId[], codes: string[]) => {+ // Validate same length+ invariant(cellIds.length === codes.length, "must be the same length");++ return API.post<RunRequest>("/kernel/run/", {+ cellIds: cellIds,+ codes: codes,+ });+ },+ sendInstantiate: (request: InstantiateRequest) => {+ // Validate same length+ invariant(+ request.objectIds.length === request.values.length,+ "must be the same length"+ );++ return API.post<InstantiateRequest>("/kernel/instantiate/", request);+ },+ sendDeleteCell: (cellId) => {+ return API.post<DeleteRequest>("/kernel/delete/", {+ cellId: cellId,+ });+ },+ sendDirectoryAutocompleteRequest: (prefix) => {+ return API.post<+ SendDirectoryAutocompleteRequest,+ SendDirectoryAutocompleteResponse+ >("/kernel/directory_autocomplete/", {+ prefix: prefix,+ });+ },+ sendCodeCompletionRequest: (request) => {+ return API.post<CodeCompletionRequest>(+ "/kernel/code_autocomplete/",+ request+ );+ },+ saveUserConfig: (request) => {+ return API.post<SaveUserConfigRequest>(+ "/kernel/save_user_config/",+ request+ );+ },+ saveAppConfig: (request) => {+ return API.post<SaveAppConfigRequest>(+ "/kernel/save_app_config/",+ request+ );+ },+ saveCellConfig: (request) => {+ return API.post<SaveCellConfigRequest>(+ "/kernel/set_cell_config/",+ request+ );+ },+ sendFunctionRequest: (request) => {+ return API.post<SendFunctionRequest>("/kernel/function_call/", request);+ },+ };+}++export const {+ sendComponentValues,+ sendRename,+ sendSave,+ sendFormat,+ sendInterrupt,+ sendShutdown,+ sendRun,+ sendInstantiate,+ sendDeleteCell,+ sendDirectoryAutocompleteRequest,+ sendCodeCompletionRequest,+ saveUserConfig,+ saveAppConfig,+ saveCellConfig,+ sendFunctionRequest,+} = isStaticNotebook() ? createStaticRequests() : createNetworkRequests();diff --git a/frontend/src/core/network/static-requests.ts b/frontend/src/core/network/static-requests.tsnew file mode 100644index 0000000000..63d54abe1b--- /dev/null+++ b/frontend/src/core/network/static-requests.ts@@ -0,0 +1,52 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { toast } from "@/components/ui/use-toast";+import {+ EditRequests,+ InstantiateRequest,+ RunRequests,+ SendFunctionRequest,+} from "./types";+import { Logger } from "@/utils/Logger";++export function createStaticRequests(): EditRequests & RunRequests {+ const throwNotInEditMode = () => {+ throw new Error("Unreachable. Expected to be in run mode");+ };++ return {+ sendComponentValues: async (valueUpdates) => {+ toast({+ title: "Static notebook",+ description:+ "This notebook is not connected to a kernel. Any interactive elements will not work.",+ });+ Logger.log("Updating UI elements is not supported in static mode");+ return null;+ },+ sendInstantiate: async (request: InstantiateRequest) => {+ Logger.log("Viewing as static notebook");+ return null;+ },+ sendFunctionRequest: async (request: SendFunctionRequest) => {+ toast({+ title: "Static notebook",+ description:+ "This notebook is not connected to a kernel. Any interactive elements will not work.",+ });+ Logger.log("Function requests are not supported in static mode");+ return null;+ },+ sendRun: throwNotInEditMode,+ sendRename: throwNotInEditMode,+ sendSave: throwNotInEditMode,+ sendInterrupt: throwNotInEditMode,+ sendShutdown: throwNotInEditMode,+ sendFormat: throwNotInEditMode,+ sendDeleteCell: throwNotInEditMode,+ sendDirectoryAutocompleteRequest: throwNotInEditMode,+ sendCodeCompletionRequest: throwNotInEditMode,+ saveUserConfig: throwNotInEditMode,+ saveAppConfig: throwNotInEditMode,+ saveCellConfig: throwNotInEditMode,+ };+}diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.tsindex 9dbedd570e..8a76f85f99 100644--- a/frontend/src/core/network/types.ts+++ b/frontend/src/core/network/types.ts@@ -5,6 +5,9 @@ import { CellId } from "../../core/model/ids";import { CellConfig } from "../model/cells";import { RequestId } from "./DeferredRequestRegistry";+// Ideally this would be generated from server.py, but for now we just+// manually keep them in sync.+export interface DeleteRequest {cellId: CellId;}@@ -89,3 +92,39 @@ export interface SendFunctionRequest {namespace: string;functionName: string;}++interface ValueUpdate {+ objectId: string;+ value: unknown;+}++/**+ * Requests sent to the BE during run/edit mode.+ */+export interface RunRequests {+ sendComponentValues: (valueUpdates: ValueUpdate[]) => Promise<null>;+ sendInstantiate: (request: InstantiateRequest) => Promise<null>;+ sendFunctionRequest: (request: SendFunctionRequest) => Promise<null>;+}++/**+ * Requests sent to the BE during edit mode.+ */+export interface EditRequests {+ sendRename: (filename: string | null) => Promise<null>;+ sendSave: (request: SaveKernelRequest) => Promise<null>;+ sendRun: (cellIds: CellId[], codes: string[]) => Promise<null>;+ sendInterrupt: () => Promise<null>;+ sendShutdown: () => Promise<null>;+ sendFormat: (+ codes: Record<CellId, string>+ ) => Promise<Record<CellId, string>>;+ sendDeleteCell: (cellId: CellId) => Promise<null>;+ sendDirectoryAutocompleteRequest: (+ prefix: string+ ) => Promise<SendDirectoryAutocompleteResponse>;+ sendCodeCompletionRequest: (request: CodeCompletionRequest) => Promise<null>;+ saveUserConfig: (request: SaveUserConfigRequest) => Promise<null>;+ saveAppConfig: (request: SaveAppConfigRequest) => Promise<null>;+ saveCellConfig: (request: SaveCellConfigRequest) => Promise<null>;+}diff --git a/frontend/src/core/state/cells.ts b/frontend/src/core/state/cells.tsindex ea2c09a418..157308debb 100644--- a/frontend/src/core/state/cells.ts+++ b/frontend/src/core/state/cells.ts@@ -26,6 +26,7 @@ import { CellHandle } from "@/editor/Cell";import { Logger } from "@/utils/Logger";import { Objects } from "@/utils/objects";import { EditorView } from "@codemirror/view";+import { isStaticNotebook, parseStaticState } from "../static/static-state";/*** The state of the notebook.@@ -66,6 +67,18 @@ export interface NotebookState {* Initial state of the notebook.*/function initialNotebookState(): NotebookState {+ if (isStaticNotebook()) {+ const notebookState = parseStaticState();+ return {+ cellIds: notebookState.cellIds,+ cellData: notebookState.cellData,+ cellRuntime: notebookState.cellRuntime,+ cellHandles: {},+ history: [],+ scrollKey: null,+ };+ }+return {cellIds: [],cellData: {},diff --git a/frontend/src/core/state/config.ts b/frontend/src/core/state/config.tsindex d419289e29..931caf47dc 100644--- a/frontend/src/core/state/config.ts+++ b/frontend/src/core/state/config.ts@@ -35,3 +35,7 @@ const appConfigAtom = atom<AppConfig>(parseAppConfig());export function useAppConfig() {return useAtom(appConfigAtom);}++export function getAppConfig() {+ return store.get(appConfigAtom);+}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.snapnew file mode 100644index 0000000000..1e4543c9be--- /dev/null+++ b/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap@@ -0,0 +1,99 @@+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html++exports[`download-html > should construct html correctly 1`] = `+"<html>+ <head>+ <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\\"+ />+ </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: {+ id: \\"1\\",+ config: {},+ name: \\"cell\\",+ code: \\"code\\",+ edited: false,+ lastCodeRun: null,+ serializedEditorState: null,+ },+ },+ cellRuntime: {+ 1: {+ outline: null,+ output: null,+ consoleOutputs: [],+ status: \\"idle\\",+ interrupted: false,+ errored: false,+ stopped: false,+ runElapsedTimeMs: null,+ runStartTimestamp: null,+ },+ },+ };+ window.__MARIMO_STATIC__.assetUrl =+ \\"https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist\\";+ </script>++ <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.tsnew file mode 100644index 0000000000..8959f5b2cb--- /dev/null+++ b/frontend/src/core/static/__tests__/download-html.test.ts@@ -0,0 +1,81 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { describe, expect, it } from "vitest";+import { constructHTML } from "../download-html";+import { CellId } from "@/core/model/ids";+import { createCell, createCellRuntimeState } from "@/core/model/cells";+import { JSDOM } from "jsdom";+// @ts-expect-error - no types+import prettier from "prettier";++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" />+ <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>+ function __resizeIframe(obj) {+ obj.style.height = obj.contentWindow.document.documentElement.scrollHeight + 'px';+ }+ </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-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",+ }),+ },+ cellRuntime: { [cellId]: createCellRuntimeState() },+ },+ assetUrl: `https://cdn.jsdelivr.net/npm/@marimo-team/frontend@${version}/dist`,+ filename: "app",+ existingDocument: new JSDOM(DOC).window.document,+ });++ const formattedResult = prettier.format(result, {+ parser: "html",+ });+ expect(formattedResult).toMatchSnapshot();+ });+});diff --git a/frontend/src/core/static/download-html.ts b/frontend/src/core/static/download-html.tsnew file mode 100644index 0000000000..cbca8d843f--- /dev/null+++ b/frontend/src/core/static/download-html.ts@@ -0,0 +1,164 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { NotebookState, getNotebook } from "../state/cells";+import { getMarimoVersion } from "../dom/version";++// 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 function downloadAsHTML(opts: { filename?: string }) {+ const { filename } = opts;+ const notebook = getNotebook();+ const version = getMarimoVersion();++ const assetUrl =+ ENABLE_LOCAL_ASSETS || process.env.NODE_ENV === "development"+ ? window.location.origin+ : `https://cdn.jsdelivr.net/npm/@marimo-team/frontend@${version}/dist`;++ const html = constructHTML({+ notebookState: notebook,+ version: version,+ assetUrl: assetUrl,+ filename: filename || "notebook",+ existingDocument: document,+ });++ const url = URL.createObjectURL(new Blob([html], { type: "text/html" }));+ const a = document.createElement("a");+ a.href = url;+ a.download = filename ? `${filename}.html` : "notebook.html";+ a.click();+}++/**+ * Constructs HTML for the a static rendering of the page.+ */+export function constructHTML(opts: {+ version: string;+ notebookState: Pick<NotebookState, "cellIds" | "cellData" | "cellRuntime">;+ assetUrl: string;+ filename: string;+ existingDocument: Document;+}) {+ const { version, notebookState, assetUrl, existingDocument } = opts;++ const staticHead = existingDocument.head.cloneNode(true) as HTMLHeadElement;++ const elementsFromBody = [+ "marimo-filename",+ "marimo-version",+ "marimo-user-config",+ "marimo-app-config",+ ];++ // Create initial elements+ const html = `+ <!DOCTYPE html>+ <html>+ <head>+ ${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: notebookState.cellData,+ cellRuntime: notebookState.cellRuntime,+ })};+ window.__MARIMO_STATIC__.assetUrl = "${assetUrl}";+ </script>+ </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);+ }++ return doc.documentElement.outerHTML;+}++function updateAssetUrl(existingUrl: string, assetBaseUrl: string) {+ // Will convert: https://localhost:8080/assets/index-c78b8d10.js+ // into: https://cdn.jsdelivr.net/npm/@marimo-team/[email protected]/dist/assets/index-c78b8d10.js++ // relative path+ if (existingUrl.startsWith("/")) {+ return `${assetBaseUrl}${existingUrl}`;+ }++ // absolute path+ const url = new URL(existingUrl);+ if (url.origin !== window.location.origin) {+ return `${assetBaseUrl}${url.pathname}`;+ }++ // otherwise, leave as is+ return existingUrl;+}diff --git a/frontend/src/core/static/static-state.ts b/frontend/src/core/static/static-state.tsnew file mode 100644index 0000000000..33e3ee5fd6--- /dev/null+++ b/frontend/src/core/static/static-state.ts@@ -0,0 +1,37 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { invariant } from "@/utils/invariant";+import { NotebookState } from "../state/cells";++export interface StaticNotebookState+ extends Pick<NotebookState, "cellIds" | "cellData" | "cellRuntime"> {+ version: string;+ assetUrl: string;+}++declare global {+ interface Window {+ __MARIMO_STATIC__?: {+ version: string;+ notebookState: StaticNotebookState;+ assetUrl: string;+ };+ }+}++export function parseStaticState(): StaticNotebookState {+ invariant(window.__MARIMO_STATIC__ !== undefined, "Not a static notebook");++ return window.__MARIMO_STATIC__.notebookState;+}++export function isStaticNotebook(): boolean {+ return (+ typeof window !== "undefined" && window.__MARIMO_STATIC__ !== undefined+ );+}++export function getStaticNotebookAssetUrl(): string {+ invariant(window.__MARIMO_STATIC__ !== undefined, "Not a static notebook");++ return window.__MARIMO_STATIC__.assetUrl;+}diff --git a/frontend/src/core/websocket/StaticWebsocket.ts b/frontend/src/core/websocket/StaticWebsocket.tsnew file mode 100644index 0000000000..a3951f2128--- /dev/null+++ b/frontend/src/core/websocket/StaticWebsocket.ts@@ -0,0 +1,48 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { IReconnectingWebSocket } from "./types";++export class StaticWebsocket implements IReconnectingWebSocket {+ CONNECTING = WebSocket.CONNECTING;+ OPEN = WebSocket.OPEN;+ CLOSING = WebSocket.CLOSING;+ CLOSED = WebSocket.CLOSED;+ binaryType = "blob" as BinaryType;+ bufferedAmount = 0;+ extensions = "";+ protocol = "";+ url = "";++ onclose = null;+ onerror = null;+ onmessage = null;+ onopen = null;++ addEventListener(type: unknown, callback: unknown, options?: unknown): void {+ // Noop+ }+ removeEventListener(+ type: unknown,+ callback: unknown,+ options?: unknown+ ): void {+ // Noop+ }+ dispatchEvent(event: Event): boolean {+ // Noop+ return false;+ }++ readyState = WebSocket.OPEN;+ retryCount = 0;+ shouldReconnect = false;++ reconnect(code?: number | undefined, reason?: string | undefined): void {+ // Noop+ }+ send(data: string | ArrayBufferLike | Blob | ArrayBufferView) {+ // Noop+ }+ close() {+ // Noop+ }+}diff --git a/frontend/src/core/websocket/types.ts b/frontend/src/core/websocket/types.tsindex 301e2c90ca..bde26dd552 100644--- a/frontend/src/core/websocket/types.ts+++ b/frontend/src/core/websocket/types.ts@@ -1,5 +1,7 @@/* Copyright 2023 Marimo. All rights reserved. */+import ReconnectingWebSocket from "partysocket/ws";+export enum WebSocketState {CONNECTING = 0,OPEN = 1,@@ -28,3 +30,9 @@ export type ConnectionStatus =| WebSocketState.OPEN| WebSocketState.CLOSING;};++type PublicInterface<T> = {+ [P in keyof T]: T[P];+};++export type IReconnectingWebSocket = PublicInterface<ReconnectingWebSocket>;diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsxindex b86d57bb27..1617b43e60 100644--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx@@ -23,6 +23,7 @@ import { renderHTML } from "@/plugins/core/RenderHTML";import { FUNCTIONS_REGISTRY } from "../functions/FunctionRegistry";import { jsonParseWithSpecialChar } from "@/utils/json-parser";import { prettyError } from "@/utils/errors";+import { isStaticNotebook } from "../static/static-state";import { useRef } from "react";/**@@ -190,6 +191,7 @@ export function useMarimoWebSocket(opts: {};const ws = useWebSocket({+ static: isStaticNotebook(),/*** Unique URL for this session.*/diff --git a/frontend/src/core/websocket/useWebSocket.tsx b/frontend/src/core/websocket/useWebSocket.tsxindex 14d8fcdbf4..53b4da7bcb 100644--- a/frontend/src/core/websocket/useWebSocket.tsx+++ b/frontend/src/core/websocket/useWebSocket.tsx@@ -1,9 +1,12 @@/* Copyright 2023 Marimo. All rights reserved. */import { useEffect, useRef } from "react";import ReconnectingWebSocket from "partysocket/ws";+import { IReconnectingWebSocket } from "./types";+import { StaticWebsocket } from "./StaticWebsocket";interface UseWebSocketOptions {url: string;+ static: boolean;onOpen?: (event: WebSocketEventMap["open"]) => void;onMessage?: (event: WebSocketEventMap["message"]) => void;onClose?: (event: WebSocketEventMap["close"]) => void;@@ -18,14 +21,16 @@ interface UseWebSocketOptions {export function useWebSocket(options: UseWebSocketOptions) {const { onOpen, onMessage, onClose, onError, ...rest } = options;- const wsRef = useRef<ReconnectingWebSocket>();+ const wsRef = useRef<IReconnectingWebSocket>();useEffect(() => {- wsRef.current = new ReconnectingWebSocket(rest.url, undefined, {- // We don't want Infinity retries- maxRetries: 10,- debug: false,- });+ wsRef.current = options.static+ ? new StaticWebsocket()+ : new ReconnectingWebSocket(rest.url, undefined, {+ // We don't want Infinity retries+ maxRetries: 10,+ debug: false,+ });const socket = wsRef.current;onOpen && socket.addEventListener("open", onOpen);diff --git a/frontend/src/editor/Cell.tsx b/frontend/src/editor/Cell.tsxindex eb88ed735a..8244b23775 100644--- a/frontend/src/editor/Cell.tsx+++ b/frontend/src/editor/Cell.tsx@@ -195,7 +195,7 @@ const CellComponent = (const code = prepareToRunEffects();registerRunStart();- sendRun(cellId, code);+ sendRun([cellId], [code]);});const handleDelete = useEvent(() => {diff --git a/frontend/src/editor/actions/useNotebookActions.tsx b/frontend/src/editor/actions/useNotebookActions.tsxindex 96fddf14e7..1936051da0 100644--- a/frontend/src/editor/actions/useNotebookActions.tsx+++ b/frontend/src/editor/actions/useNotebookActions.tsx@@ -8,6 +8,7 @@ import {ZapIcon,ZapOffIcon,BookMarkedIcon,+ FolderDownIcon,} from "lucide-react";import { commandPalletteAtom } from "../CommandPallette";import {@@ -19,6 +20,8 @@ import {import { saveCellConfig } from "@/core/network/requests";import { Objects } from "@/utils/objects";import { ActionButton } from "./types";+import { downloadAsHTML } from "@/core/static/download-html";+import { getFeatureFlag } from "@/core/config/feature-flag";export function useNotebookActions(opts: { filename?: string | null }) {const { filename } = opts;@@ -44,6 +47,14 @@ export function useNotebookActions(opts: { filename?: string | null }) {});},},+ {+ icon: <FolderDownIcon size={14} strokeWidth={1.5} />,+ label: "Export as HTML",+ hidden: !getFeatureFlag("static_export"),+ handle: () => {+ return downloadAsHTML({ filename: filename || "notebook.html" });+ },+ },{icon: <ZapIcon size={14} strokeWidth={1.5} />,label: "Enable all cells",diff --git a/frontend/src/editor/cell/useRunCells.ts b/frontend/src/editor/cell/useRunCells.tsindex 56a7ae2da0..66efadb850 100644--- a/frontend/src/editor/cell/useRunCells.ts+++ b/frontend/src/editor/cell/useRunCells.ts@@ -1,7 +1,7 @@/* Copyright 2023 Marimo. All rights reserved. */import { RuntimeState } from "@/core/RuntimeState";import { CellId } from "@/core/model/ids";-import { sendRunMultiple } from "@/core/network/requests";+import { sendRun } from "@/core/network/requests";import { staleCellIds, useNotebook } from "@/core/state/cells";import { derefNotNull } from "@/utils/dereference";import useEvent from "react-use-event-hook";@@ -46,7 +46,7 @@ function useRunCells() {}RuntimeState.INSTANCE.registerRunStart();- await sendRunMultiple(cellIds, codes);+ await sendRun(cellIds, codes);});return runCells;diff --git a/frontend/src/plugins/core/registerReactComponent.tsx b/frontend/src/plugins/core/registerReactComponent.tsxindex e9a12cfbf4..68825fb5f6 100644--- a/frontend/src/plugins/core/registerReactComponent.tsx+++ b/frontend/src/plugins/core/registerReactComponent.tsx@@ -42,6 +42,10 @@ 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 {/**@@ -323,8 +327,7 @@ export function registerReactComponent<T>(plugin: IPlugin<T, unknown>): void {) {return true;}- // Only copy stylesheets that point to our domain- return sheet.href && sheet.href.startsWith(window.location.origin);+ return shouldCopyStyleSheet(sheet);});// Create new stylesheets if not already cachedfor (const sheet of sheets) {@@ -368,8 +371,7 @@ export function registerReactComponent<T>(plugin: IPlugin<T, unknown>): void {);const styleSheets = Array.from(document.styleSheets).flatMap((sheet) => {- // Only copy stylesheets that point to our domain- if (!sheet.href || !sheet.href.startsWith(window.location.origin)) {+ if (!shouldCopyStyleSheet(sheet)) {return [];}@@ -393,3 +395,17 @@ export function registerReactComponent<T>(plugin: IPlugin<T, unknown>): void {defineCustomElement(plugin.tagName, WebComponent);}++// Copy the stylesheet to the shadow root if it is local+// or from our assetUrl (in the case of a static notebook)+function shouldCopyStyleSheet(sheet: CSSStyleSheet): boolean {+ if (!sheet.href) {+ return false;+ }++ if (isStaticNotebook()) {+ return sheet.href.startsWith(getStaticNotebookAssetUrl());+ }++ return sheet.href.startsWith(window.location.origin);+}diff --git a/frontend/vite.config.ts b/frontend/vite.config.tsindex 8886833d14..08a1482f12 100644--- a/frontend/vite.config.ts+++ b/frontend/vite.config.ts@@ -19,15 +19,15 @@ const htmlDevPlugin = (): Plugin => {const serverDoc = new JSDOM(serverHtml).window.document;const devDoc = new JSDOM(html).window.document;- const devHead = devDoc.head;// copies these elements from server to devconst copyElements = [+ "title","marimo-filename",+ "marimo-version","marimo-mode","marimo-user-config","marimo-app-config",- "title",];// remove from dev@@ -45,7 +45,7 @@ const htmlDevPlugin = (): Plugin => {if (!element) {throw new Error(`Element ${id} not found.`);}- devHead.append(element);+ devDoc.head.append(element);});return devDoc.documentElement.outerHTML;diff --git a/marimo/_server/server.py b/marimo/_server/server.pyindex fda5a538d4..44d4f7e245 100644--- a/marimo/_server/server.py+++ b/marimo/_server/server.py@@ -136,6 +136,13 @@ class ShutdownHandler(tornado.web.RequestHandler):shutdown()+class CorsStaticFileHandler(tornado.web.StaticFileHandler):+ def set_default_headers(self) -> None:+ self.set_header("Access-Control-Allow-Origin", "*")+ self.set_header("Access-Control-Allow-Headers", "x-requested-with")+ self.set_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")++def construct_app(root: str, development_mode: bool) -> tornado.web.Application:@@ -210,22 +217,22 @@ def construct_app(),(r"/(favicon\.ico)",- tornado.web.StaticFileHandler,+ CorsStaticFileHandler,{"path": root},),(r"/(manifest\.json)",- tornado.web.StaticFileHandler,+ CorsStaticFileHandler,{"path": root},),(r"/(android-chrome-(192x192|512x512)\.png)",- tornado.web.StaticFileHandler,+ CorsStaticFileHandler,{"path": root},),(r"/assets/(.*)",- tornado.web.StaticFileHandler,+ CorsStaticFileHandler,{"path": static_dir},),],