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.

experimental: export as html improvements and bug fixes (#408)

Myles Scolnicke24121f9a05d
diff --git a/.github/workflows/playwright.yml b/.github/workflows/playwright.yml
index 03bc2072f8..18791b9280 100644
--- a/.github/workflows/playwright.yml
+++ b/.github/workflows/playwright.yml
@@ -27,6 +27,7 @@ jobs:
run: |
echo "[experimental]" > .marimo.toml
echo "layouts=true" >> .marimo.toml
+ echo "static_export=true" >> .marimo.toml
- uses: pnpm/action-setup@v2
with:
diff --git a/frontend/.gitignore b/frontend/.gitignore
index 87ae13c4c4..56ee3aef6e 100644
--- a/frontend/.gitignore
+++ b/frontend/.gitignore
@@ -19,6 +19,7 @@
/playwright-report/
/playwright/.cache/
e2e-tests/screenshots
+e2e-tests/exports
# storybook
/storybook-static
diff --git a/frontend/e2e-tests/cells.spec.ts b/frontend/e2e-tests/cells.spec.ts
index 9866bcbe78..073e7add3b 100644
--- a/frontend/e2e-tests/cells.spec.ts
+++ b/frontend/e2e-tests/cells.spec.ts
@@ -1,7 +1,7 @@
/* Copyright 2023 Marimo. All rights reserved. */
import { test, expect } from "@playwright/test";
import { getAppUrl, resetFile } from "../playwright.config";
-import { pressShortcut } from "./helper";
+import { exportAsHTMLAndTakeScreenshot, pressShortcut } from "./helper";
const appUrl = getAppUrl("cells.py");
test.beforeEach(async ({ page }, info) => {
@@ -134,3 +134,7 @@ test("page renders 2 cells", async ({ page }) => {
// Verify the rendered cells
await expect(page.locator("h1")).toHaveText(["Cell 1", "Cell 2"]);
});
+
+test("export as HTML", async ({ page }) => {
+ await exportAsHTMLAndTakeScreenshot(page);
+});
diff --git a/frontend/e2e-tests/helper.ts b/frontend/e2e-tests/helper.ts
index c5769c92cf..2b8ef21d70 100644
--- a/frontend/e2e-tests/helper.ts
+++ b/frontend/e2e-tests/helper.ts
@@ -84,3 +84,27 @@ export async function pressShortcut(page: Page, action: HotkeyAction) {
await page.keyboard.press(keymap);
}
+
+/**
+ * Export as HTML
+ *
+ * Download HTML of the current notebook and take a screenshot
+ */
+export async function exportAsHTMLAndTakeScreenshot(page: Page) {
+ // Start waiting for download before clicking. Note no await.
+ const downloadPromise = page.waitForEvent("download");
+ await page.getByTestId("notebook-menu-dropdown").click();
+ await page.getByText("Export as HTML").click();
+ const download = await downloadPromise;
+
+ // Wait for the download process to complete and save the downloaded file somewhere.
+ const path = `e2e-tests/exports/${download.suggestedFilename()}`;
+ await download.saveAs(path);
+
+ // Open a new page and take a screenshot
+ const exportPage = await page.context().newPage();
+ // @ts-expect-error process not defined
+ const fullPath = `${process.cwd()}/${path}`;
+ await exportPage.goto(`file://${fullPath}`);
+ await takeScreenshot(exportPage, path);
+}
diff --git a/frontend/e2e-tests/kitchen-sink.spec.ts b/frontend/e2e-tests/kitchen-sink.spec.ts
new file mode 100644
index 0000000000..1eb0d50d0b
--- /dev/null
+++ b/frontend/e2e-tests/kitchen-sink.spec.ts
@@ -0,0 +1,12 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { test } from "@playwright/test";
+import { getAppUrl } from "../playwright.config";
+import { exportAsHTMLAndTakeScreenshot, takeScreenshot } from "./helper";
+
+test("can screenshot and export as html", async ({ page }) => {
+ const appUrl = getAppUrl("kitchen_sink.py//edit");
+ await page.goto(appUrl);
+
+ await takeScreenshot(page, __filename);
+ await exportAsHTMLAndTakeScreenshot(page);
+});
diff --git a/frontend/e2e-tests/py/kitchen_sink.py b/frontend/e2e-tests/py/kitchen_sink.py
new file mode 100644
index 0000000000..063c7efcbd
--- /dev/null
+++ b/frontend/e2e-tests/py/kitchen_sink.py
@@ -0,0 +1,561 @@
+import marimo
+
+__generated_with = "0.1.60"
+app = marimo.App()
+
+
+def __(mo):
+ # markdown
+ markdown = mo.md(
+ f"""
+ # Hello world!
+
+ `marimo` _supports_ **markdown**
+ """
+ )
+ return markdown,
+
+
+def __(np, plt):
+ # Generate some random data
+ categories = ["A", "B", "C", "D", "E"]
+ values = np.random.rand(5)
+
+ bar = plt.bar(categories, values)
+ plt.title("Random Bar Chart")
+ plt.xlabel("Categories")
+ plt.ylabel("Values")
+ None
+ return bar, categories, values
+
+
+def __(mo):
+ # options
+ callout_kind = mo.ui.dropdown(
+ label="Color",
+ options=["neutral", "danger", "warn", "success", "info"],
+ value="info",
+ )
+
+ justify = mo.ui.dropdown(
+ ["start", "center", "end", "space-between", "space-around"],
+ value="space-between",
+ label="justify",
+ )
+ align = mo.ui.dropdown(
+ ["start", "center", "end", "stretch"], value="center", label="align"
+ )
+ gap = mo.ui.number(start=0, step=0.25, stop=2, value=0.25, label="gap")
+ wrap = mo.ui.checkbox(label="wrap")
+ return align, callout_kind, gap, justify, wrap
+
+
+def __(alt, callout_kind, mo, office_characters, vega_datasets):
+ options = ["Apples", "Oranges", "Pears"]
+
+ # inputs
+ button = mo.ui.button(label="Click me")
+ checkbox = mo.ui.checkbox(label="check me")
+ date = mo.ui.date(label="Start Date")
+ dropdown = mo.ui.dropdown(options=options, value=options[0])
+ file = mo.vstack([mo.ui.file(kind="button"), mo.ui.file(kind="area")])
+ multiselect = mo.ui.multiselect(options=options)
+ number = mo.ui.number(start=1, stop=20, label="Number")
+ radio = mo.ui.radio(options=options)
+ slider = mo.ui.slider(start=1, stop=20, label="Slider", value=3)
+ switch = mo.ui.switch(label="do not disturb")
+ table = mo.ui.table(data=office_characters, pagination=True)
+ text_area = mo.ui.text_area(placeholder="Search...", label="Description")
+ text = mo.ui.text(placeholder="Search...", label="Filter")
+ refresh = mo.ui.refresh(label="Refresh", options=["1s", "5s", "10s", "30s"])
+ microphone = mo.ui.microphone(label="Drop a beat!")
+ chart = mo.ui.altair_chart(
+ alt.Chart(vega_datasets.data.cars())
+ .mark_point()
+ .encode(
+ x="Horsepower",
+ y="Miles_per_Gallon",
+ color="Origin",
+ )
+ )
+
+ # form
+ form = mo.ui.text_area(placeholder="...").form()
+
+ # callout
+ callout = mo.callout("This is a callout", kind=callout_kind.value)
+
+ # batch
+ batch = mo.md("{start} → {end}").batch(
+ start=mo.ui.date(label="Start Date"), end=mo.ui.date(label="End Date")
+ )
+
+ # status
+ # TODO(akshayka): this is using an internal API since we don't expose the progress bar
+ progress_bar = mo._plugins.stateless.status._progress.ProgressBar(
+ title=None, subtitle=None, total=10
+ )
+
+ with mo.status.spinner(title="Hang tight!") as spinner:
+ pass
+
+ # stat
+ stat = mo.stat(
+ value="$100.54",
+ label="Open price",
+ caption="+2.4%",
+ direction="increase",
+ bordered=True,
+ )
+ return (
+ batch,
+ button,
+ callout,
+ chart,
+ checkbox,
+ date,
+ dropdown,
+ file,
+ form,
+ microphone,
+ multiselect,
+ number,
+ options,
+ progress_bar,
+ radio,
+ refresh,
+ slider,
+ spinner,
+ stat,
+ switch,
+ table,
+ text,
+ text_area,
+ )
+
+
+def __(create_wrapper, mo):
+ # array
+ wish = mo.ui.text(placeholder="Wish")
+
+ create_wrapper(
+ mo.ui.array([wish] * 3, label="Three wishes"),
+ "array",
+ )
+ return wish,
+
+
+def __(batch, create_wrapper, mo):
+ # batch
+ create_wrapper(
+ mo.hstack([batch, batch.value]),
+ "batch",
+ )
+ return
+
+
+def __(create_wrapper, mo, refresh):
+ # refresh
+ create_wrapper(mo.hstack([refresh, refresh.value]), "refresh")
+ return
+
+
+def __(button, create_wrapper, mo):
+ # button
+ create_wrapper(
+ mo.hstack([button]),
+ "button",
+ )
+ return
+
+
+def __(checkbox, create_wrapper, mo):
+ # checkbox
+ create_wrapper(
+ mo.hstack([checkbox, mo.md(f"Has value: {checkbox.value}")]),
+ "checkbox",
+ )
+ return
+
+
+def __(create_wrapper, mo):
+ # dictionary
+ first_name = mo.ui.text(placeholder="First name")
+ last_name = mo.ui.text(placeholder="Last name")
+ email = mo.ui.text(placeholder="Email", kind="email")
+
+ create_wrapper(
+ mo.ui.dictionary(
+ {
+ "First name": first_name,
+ "Last name": last_name,
+ "Email": email,
+ }
+ ),
+ "dictionary",
+ )
+ return email, first_name, last_name
+
+
+def __(callout, callout_kind, create_wrapper, mo):
+ create_wrapper(
+ mo.vstack([callout_kind, callout], align="stretch", gap=0),
+ "callout",
+ )
+ return
+
+
+def __(create_wrapper, markdown):
+ create_wrapper(
+ markdown,
+ "markdown",
+ )
+ return
+
+
+def __(create_wrapper, file):
+ create_wrapper(
+ file,
+ "file",
+ )
+ return
+
+
+def __(create_wrapper, mo, multiselect):
+ create_wrapper(
+ mo.hstack([multiselect, mo.md(f"Has value: {multiselect.value}")]),
+ "multiselect",
+ )
+ return
+
+
+def __(create_wrapper, dropdown, mo):
+ create_wrapper(
+ mo.hstack([dropdown, mo.md(f"Has value: {dropdown.value}")]),
+ "dropdown",
+ )
+ return
+
+
+def __(create_wrapper, date, mo):
+ create_wrapper(
+ mo.hstack([date, mo.md(f"Has value: {date.value}")]),
+ "date",
+ )
+ return
+
+
+def __(create_wrapper, mo, switch):
+ create_wrapper(
+ mo.hstack([switch, mo.md(f"Has value: {switch.value}")]),
+ "switch",
+ )
+ return
+
+
+def __(create_wrapper, microphone, mo):
+ # microphone
+ create_wrapper(
+ mo.hstack([microphone, mo.audio(microphone.value)]),
+ "microphone",
+ )
+ return
+
+
+def __(create_wrapper, mo, slider):
+ create_wrapper(
+ mo.hstack([slider, mo.md(f"Has value: {slider.value}")]),
+ "slider",
+ )
+ return
+
+
+def __(create_wrapper, mo):
+ _src = "https://upload.wikimedia.org/wikipedia/commons/8/8c/Ivan_Ili%C4%87-Chopin_-_Prelude_no._1_in_C_major.ogg"
+ create_wrapper(
+ mo.audio(_src),
+ "audio",
+ )
+ return
+
+
+def __(create_wrapper, mo):
+ create_wrapper(
+ mo.pdf(
+ src="https://arxiv.org/pdf/2104.00282.pdf",
+ width="100%",
+ height="200px",
+ ),
+ "pdf",
+ )
+ return
+
+
+def __(create_wrapper, mo):
+ _src = (
+ "https://images.pexels.com/photos/86596/owl-bird-eyes-eagle-owl-86596.jpeg"
+ )
+ create_wrapper(
+ mo.image(src=_src, width=280, rounded=True),
+ "image",
+ )
+ return
+
+
+def __(create_wrapper, mo, number):
+ create_wrapper(
+ mo.hstack([number, mo.md(f"Has value: {number.value}")]),
+ "number",
+ )
+ return
+
+
+def __(mo):
+ def create_wrapper(element, key, code=""):
+ return mo.vstack(
+ [mo.md(f"## **{key.upper()}**"), element], align="stretch", gap=2
+ )
+ return create_wrapper,
+
+
+def __(create_wrapper, mo, text):
+ create_wrapper(
+ mo.hstack([text, mo.md(f"Has value: {text.value}")]),
+ "text",
+ )
+ return
+
+
+def __(create_wrapper, mo, text_area):
+ create_wrapper(
+ mo.hstack([text_area, mo.md(f"Has value: {text_area.value}")]),
+ "text_area",
+ )
+ return
+
+
+def __(create_wrapper, mo, radio):
+ create_wrapper(
+ mo.hstack([radio, mo.md(f"Has value: {radio.value}")]),
+ "radio",
+ )
+ return
+
+
+def __(create_wrapper, form, mo):
+ create_wrapper(
+ mo.hstack([form, mo.md(f"Has value: {form.value}")]),
+ "form",
+ )
+ return
+
+
+def __(create_wrapper, mo):
+ create_wrapper(
+ mo.accordion(
+ {
+ "Door 1": mo.md("Nothing!"),
+ "Door 2": mo.md("Nothing!"),
+ "Door 3": mo.image(
+ "https://images.unsplash.com/photo-1524024973431-2ad916746881",
+ height=150,
+ ),
+ }
+ ),
+ "accordion",
+ )
+ return
+
+
+def __(bar, create_wrapper, mo):
+ create_wrapper(
+ mo.tabs(
+ {
+ "📈 Sales": bar,
+ "💻 Settings": mo.ui.text(placeholder="Key"),
+ }
+ ),
+ "tabs",
+ )
+ return
+
+
+def __(create_wrapper, mo):
+ tree = mo.tree(
+ [
+ "entry",
+ "another entry",
+ {"key": [0, mo.ui.slider(1, 10, value=5), 2]},
+ ],
+ label="A tree of elements.",
+ )
+
+ create_wrapper(
+ tree,
+ "tree",
+ )
+ return tree,
+
+
+def __(align, boxes, create_wrapper, gap, justify, mo, wrap):
+ horizontal = mo.hstack(
+ boxes,
+ align=align.value,
+ justify=justify.value,
+ gap=gap.value,
+ wrap=wrap.value,
+ )
+ vertical = mo.vstack(
+ boxes,
+ align=align.value,
+ gap=gap.value,
+ )
+
+ stacks = mo.vstack(
+ [
+ mo.hstack([justify, align, gap], justify="center"),
+ horizontal,
+ mo.md("-----------------------------"),
+ vertical,
+ ],
+ align="stretch",
+ gap=1,
+ )
+
+ create_wrapper(
+ stacks,
+ "stacks",
+ )
+ return horizontal, stacks, vertical
+
+
+def __(create_wrapper, table):
+ create_wrapper(
+ table, "table", "mo.ui.table(data=office_characters, pagination=True)"
+ )
+ return
+
+
+def __(create_wrapper, spinner):
+ # spinner
+ create_wrapper(
+ spinner,
+ "spinner",
+ )
+ return
+
+
+def __(create_wrapper, progress_bar):
+ # progress bar
+ create_wrapper(
+ progress_bar,
+ "progress-bar",
+ )
+ return
+
+
+def __(create_wrapper, stat):
+ create_wrapper(
+ stat,
+ "stat",
+ )
+ return
+
+
+def __(chart, create_wrapper, mo):
+ create_wrapper(
+ mo.vstack([chart, mo.ui.table(chart.value)]),
+ "altair-chart",
+ )
+ return
+
+
+def __(mo):
+ def create_box(num=1):
+ box_size = 30 + num * 10
+ return mo.Html(
+ f"<div style='min-width: {box_size}px; min-height: {box_size}px; background-color: orange; text-align: center; line-height: {box_size}px'>{str(num)}</div>"
+ )
+
+
+ boxes = [create_box(i) for i in range(1, 5)]
+ return boxes, create_box
+
+
+def __():
+ office_characters = [
+ {"first_name": "Michael", "last_name": "Scott"},
+ {"first_name": "Jim", "last_name": "Halpert"},
+ {"first_name": "Pam", "last_name": "Beesly"},
+ {"first_name": "Dwight", "last_name": "Schrute"},
+ {"first_name": "Angela", "last_name": "Martin"},
+ {"first_name": "Kevin", "last_name": "Malone"},
+ {"first_name": "Oscar", "last_name": "Martinez"},
+ {"first_name": "Stanley", "last_name": "Hudson"},
+ {"first_name": "Phyllis", "last_name": "Vance"},
+ {"first_name": "Meredith", "last_name": "Palmer"},
+ {"first_name": "Creed", "last_name": "Bratton"},
+ {"first_name": "Ryan", "last_name": "Howard"},
+ {"first_name": "Kelly", "last_name": "Kapoor"},
+ {"first_name": "Toby", "last_name": "Flenderson"},
+ {"first_name": "Darryl", "last_name": "Philbin"},
+ {"first_name": "Erin", "last_name": "Hannon"},
+ {"first_name": "Andy", "last_name": "Bernard"},
+ {"first_name": "Jan", "last_name": "Levinson"},
+ {"first_name": "David", "last_name": "Wallace"},
+ {"first_name": "Holly", "last_name": "Flax"},
+ ]
+ return office_characters,
+
+
+def __():
+ import altair as alt
+ import vega_datasets
+ import marimo as mo
+ import matplotlib.pyplot as plt
+ import numpy as np
+ return alt, mo, np, plt, vega_datasets
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/frontend/index.html b/frontend/index.html
index faf994874e..0b702b08c5 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -13,7 +13,7 @@
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<link rel="manifest" href="/manifest.json" />
- <script>
+ <script data-marimo="true">
function __resizeIframe(obj) {
// Resize the iframe to the height of the content
obj.style.height =
diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts
index 608cfb2bd4..bd87990131 100644
--- a/frontend/playwright.config.ts
+++ b/frontend/playwright.config.ts
@@ -35,6 +35,7 @@ const appToOptions = {
"layout_grid.py//run": { port: port(), command: "run" },
"layout_grid_max_width.py//run": { port: port(), command: "run" },
"output.py//run": { port: port(), command: "run" },
+ "kitchen_sink.py//edit": { port: port(), command: "edit" },
} satisfies Record<string, ServerOptions>;
export type ApplicationNames = keyof typeof appToOptions;
diff --git a/frontend/src/components/editor/notebook-menu-dropdown.tsx b/frontend/src/components/editor/notebook-menu-dropdown.tsx
index 5adf6b4df4..0ae417bc45 100644
--- a/frontend/src/components/editor/notebook-menu-dropdown.tsx
+++ b/frontend/src/components/editor/notebook-menu-dropdown.tsx
@@ -24,6 +24,7 @@ export const NotebookMenuDropdown: React.FC<Props> = ({ filename }) => {
shape="circle"
size="small"
className="h-[27px] w-[27px]"
+ data-testid="notebook-menu-dropdown"
color="hint-green"
>
<MenuIcon strokeWidth={1.8} />
@@ -35,7 +36,11 @@ export const NotebookMenuDropdown: React.FC<Props> = ({ filename }) => {
<DropdownMenuTrigger asChild={true}>{button}</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="no-print w-[220px]">
{actions.map((action) => (
- <DropdownMenuItem key={action.label} onSelect={() => action.handle()}>
+ <DropdownMenuItem
+ key={action.label}
+ onSelect={() => action.handle()}
+ data-testid={`notebook-menu-dropdown-${action.label}`}
+ >
{action.icon && <span className="flex-0 mr-2">{action.icon}</span>}
<span className="flex-1">{action.label}</span>
{action.hotkey && renderMinimalShortcut(action.hotkey)}
diff --git a/frontend/src/components/editor/renderers/grid-layout/styles.css b/frontend/src/components/editor/renderers/grid-layout/styles.css
index 76ea74930d..a0620751ee 100644
--- a/frontend/src/components/editor/renderers/grid-layout/styles.css
+++ b/frontend/src/components/editor/renderers/grid-layout/styles.css
@@ -21,7 +21,7 @@
}
/* for images we expand the image to fill the grid item */
-.output img {
+.react-grid-item .output img {
height: 100%;
object-fit: contain;
}
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index 4c50b204f3..fc5e2f8dd5 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -29,6 +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";
/**
* The state of the notebook.
@@ -77,8 +78,14 @@ function initialNotebookState(): NotebookState {
const notebookState = parseStaticState();
return {
cellIds: notebookState.cellIds,
- cellData: notebookState.cellData,
- cellRuntime: notebookState.cellRuntime,
+ cellData: Objects.mapValues(
+ notebookState.cellData,
+ deserializeBase64ToJson<CellData>
+ ),
+ cellRuntime: Objects.mapValues(
+ notebookState.cellRuntime,
+ deserializeBase64ToJson<CellRuntimeState>
+ ),
cellHandles: {},
history: [],
scrollKey: null,
diff --git a/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap b/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap
index 69d2f73611..f372a9fffb 100644
--- a/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap
+++ b/frontend/src/core/static/__tests__/__snapshots__/download-html.test.ts.snap
@@ -34,6 +34,20 @@ exports[`download-html > should construct html correctly 1`] = `
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>
</head>
<body>
@@ -55,28 +69,10 @@ exports[`download-html > should construct html correctly 1`] = `
window.__MARIMO_STATIC__.notebookState = {
cellIds: [\\"1\\"],
cellData: {
- 1: {
- id: \\"1\\",
- config: {},
- name: \\"cell\\",
- code: \\"code\\",
- edited: false,
- lastCodeRun: null,
- serializedEditorState: null,
- },
+ 1: \\"JTdCJTIyaWQlMjIlM0ElMjIxJTIyJTJDJTIyY29uZmlnJTIyJTNBJTdCJTdEJTJDJTIybmFtZSUyMiUzQSUyMmNlbGwlMjIlMkMlMjJjb2RlJTIyJTNBJTIyY29kZSUyMiUyQyUyMmVkaXRlZCUyMiUzQWZhbHNlJTJDJTIybGFzdENvZGVSdW4lMjIlM0FudWxsJTJDJTIyc2VyaWFsaXplZEVkaXRvclN0YXRlJTIyJTNBbnVsbCU3RA==\\",
},
cellRuntime: {
- 1: {
- outline: null,
- output: null,
- consoleOutputs: [],
- status: \\"idle\\",
- interrupted: false,
- errored: false,
- stopped: false,
- runElapsedTimeMs: null,
- runStartTimestamp: null,
- },
+ 1: \\"JTdCJTIyb3V0bGluZSUyMiUzQW51bGwlMkMlMjJvdXRwdXQlMjIlM0FudWxsJTJDJTIyY29uc29sZU91dHB1dHMlMjIlM0ElNUIlNUQlMkMlMjJzdGF0dXMlMjIlM0ElMjJpZGxlJTIyJTJDJTIyaW50ZXJydXB0ZWQlMjIlM0FmYWxzZSUyQyUyMmVycm9yZWQlMjIlM0FmYWxzZSUyQyUyMnN0b3BwZWQlMjIlM0FmYWxzZSUyQyUyMnJ1bkVsYXBzZWRUaW1lTXMlMjIlM0FudWxsJTJDJTIycnVuU3RhcnRUaW1lc3RhbXAlMjIlM0FudWxsJTdE\\",
},
};
window.__MARIMO_STATIC__.assetUrl =
diff --git a/frontend/src/core/static/__tests__/download-html.test.ts b/frontend/src/core/static/__tests__/download-html.test.ts
index 25554524d4..8195651b81 100644
--- a/frontend/src/core/static/__tests__/download-html.test.ts
+++ b/frontend/src/core/static/__tests__/download-html.test.ts
@@ -6,6 +6,7 @@ import { createCell, createCellRuntimeState } from "@/core/cells/types";
import { JSDOM } from "jsdom";
// @ts-expect-error - no types
import prettier from "prettier";
+import { Base64String } from "@/utils/json/base64";
const DOC = `
<html lang="en">
@@ -24,9 +25,18 @@ const DOC = `
<meta name="description" content="a marimo app" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<link rel="manifest" href="/manifest.json" />
- <script>
+ <script data-marimo="true">
function __resizeIframe(obj) {
- obj.style.height = obj.contentWindow.document.documentElement.scrollHeight + 'px';
+ // 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>
@@ -71,7 +81,7 @@ describe("download-html", () => {
},
files: {
"/@file/note.txt": {
- base64: "data:text/plain;base64,bm90ZQo=",
+ base64: "data:text/plain;base64,bm90ZQo=" as Base64String,
},
},
assetUrl: `https://cdn.jsdelivr.net/npm/@marimo-team/frontend@${version}/dist`,
diff --git a/frontend/src/core/static/__tests__/files.test.ts b/frontend/src/core/static/__tests__/files.test.ts
index eb2fa6abc7..42d05c5a04 100644
--- a/frontend/src/core/static/__tests__/files.test.ts
+++ b/frontend/src/core/static/__tests__/files.test.ts
@@ -1,6 +1,7 @@
/* Copyright 2023 Marimo. All rights reserved. */
import { describe, afterEach, expect, it, vi } from "vitest";
import { patchFetch, patchVegaLoader } from "../files";
+import { Base64String } from "@/utils/json/base64";
describe("patchFetch", () => {
const originalFetch = window.fetch;
@@ -12,7 +13,7 @@ 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", // Base64 for "Test content"
+ base64: "data:text/plain;base64,VGVzdCBjb250ZW50" as Base64String,
},
};
@@ -48,7 +49,8 @@ describe("patchVegaLoader", () => {
it("should return file content for virtual files", async () => {
const virtualFiles = {
"virtual-file.json": {
- base64: "data:application/json;base64,eyJrZXkiOiAidmFsdWUifQ==", // Base64 for '{"key": "value"}'
+ base64:
+ "data:application/json;base64,eyJrZXkiOiAidmFsdWUifQ==" as Base64String,
},
};
diff --git a/frontend/src/core/static/download-html.ts b/frontend/src/core/static/download-html.ts
index c87240c8b0..902fb67616 100644
--- a/frontend/src/core/static/download-html.ts
+++ b/frontend/src/core/static/download-html.ts
@@ -1,12 +1,14 @@
/* Copyright 2023 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";
// For Testing:
-// Flip this to true to use local assets instead of CDN
-// This should be false for production
+// Flip this to `true` to use local assets instead of CDN
+// This should be `false` for production
const ENABLE_LOCAL_ASSETS = false;
/**
@@ -18,7 +20,9 @@ export async function downloadAsHTML(opts: { filename?: string }) {
const version = getMarimoVersion();
const assetUrl =
- ENABLE_LOCAL_ASSETS || process.env.NODE_ENV === "development"
+ 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`;
@@ -85,8 +89,14 @@ export function constructHTML(opts: {
window.__MARIMO_STATIC__.version = "${version}";
window.__MARIMO_STATIC__.notebookState = ${JSON.stringify({
cellIds: notebookState.cellIds,
- cellData: notebookState.cellData,
- cellRuntime: notebookState.cellRuntime,
+ cellData: Objects.mapValues(
+ notebookState.cellData,
+ serializeJsonToBase64
+ ),
+ cellRuntime: Objects.mapValues(
+ notebookState.cellRuntime,
+ serializeJsonToBase64
+ ),
})};
window.__MARIMO_STATIC__.assetUrl = "${assetUrl}";
window.__MARIMO_STATIC__.files = ${JSON.stringify(files)};
diff --git a/frontend/src/core/static/types.ts b/frontend/src/core/static/types.ts
index 563c35ac80..3e9092fbca 100644
--- a/frontend/src/core/static/types.ts
+++ b/frontend/src/core/static/types.ts
@@ -1,13 +1,16 @@
/* Copyright 2023 Marimo. All rights reserved. */
+import { Base64String } from "@/utils/json/base64";
import { NotebookState } from "../cells/cells";
+import { CellId } from "../cells/ids";
-export interface StaticNotebookState
- extends Pick<NotebookState, "cellIds" | "cellData" | "cellRuntime"> {
+export interface StaticNotebookState extends Pick<NotebookState, "cellIds"> {
version: string;
assetUrl: string;
+ cellRuntime: Record<CellId, Base64String>;
+ cellData: Record<CellId, Base64String>;
}
-export type StaticVirtualFiles = Record<string, { base64: string }>;
+export type StaticVirtualFiles = Record<string, { base64: Base64String }>;
export interface MarimoStaticState {
version: string;
diff --git a/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx b/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx
index 7ace6c54b3..1337154d37 100644
--- a/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx
+++ b/frontend/src/plugins/impl/plotly/PlotlyPlugin.tsx
@@ -91,7 +91,7 @@ export const PlotlyComponent = memo(
range: evt.range,
});
})}
- className="w-full h-full"
+ className="w-full"
useResizeHandler={true}
frames={figure.frames ?? undefined}
onError={useEvent((err) => {
diff --git a/frontend/src/utils/blob.ts b/frontend/src/utils/blob.ts
index eab6ee8064..f542e9cc95 100644
--- a/frontend/src/utils/blob.ts
+++ b/frontend/src/utils/blob.ts
@@ -1,9 +1,11 @@
/* Copyright 2023 Marimo. All rights reserved. */
-export function serializeBlob(blob: Blob): Promise<string> {
- return new Promise<string>((resolve, reject) => {
+import { Base64String } from "./json/base64";
+
+export function serializeBlob(blob: Blob): Promise<Base64String> {
+ return new Promise<Base64String>((resolve, reject) => {
const reader = new FileReader();
reader.onload = (event) => {
- resolve(event.target?.result as string);
+ resolve(event.target?.result as Base64String);
};
reader.onerror = (error) => {
reject(error);
@@ -12,7 +14,7 @@ export function serializeBlob(blob: Blob): Promise<string> {
});
}
-export function deserializeBlob(serializedBlob: string): Promise<Blob> {
+export function deserializeBlob(serializedBlob: Base64String): 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
new file mode 100644
index 0000000000..2c988547ac
--- /dev/null
+++ b/frontend/src/utils/json/__tests__/base64.test.ts
@@ -0,0 +1,40 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { expect, describe, test } from "vitest";
+import {
+ serializeJsonToBase64,
+ deserializeBase64ToJson,
+ Base64String,
+} from "../base64";
+
+describe("base64Utils", () => {
+ const testData = {
+ name: "marimo inc",
+ type: "company",
+ };
+
+ const expectedBase64 =
+ "JTdCJTIybmFtZSUyMiUzQSUyMm1hcmltbyUyMGluYyUyMiUyQyUyMnR5cGUlMjIlM0ElMjJjb21wYW55JTIyJTdE" as Base64String;
+
+ test("serializeJsonToBase64 should correctly encode JSON to Base64", () => {
+ const base64Encoded = serializeJsonToBase64(testData);
+ expect(base64Encoded).toBe(expectedBase64);
+ });
+
+ test("deserializeBase64ToJson should correctly decode Base64 to JSON", () => {
+ const jsonDecoded = deserializeBase64ToJson(expectedBase64);
+ expect(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);
+ });
+});
diff --git a/frontend/src/utils/json/base64.ts b/frontend/src/utils/json/base64.ts
new file mode 100644
index 0000000000..6a3bb96666
--- /dev/null
+++ b/frontend/src/utils/json/base64.ts
@@ -0,0 +1,16 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { TypedString } from "../typed";
+
+export type Base64String = TypedString<"Base64">;
+
+// Serialization: JSON to Base64
+export function serializeJsonToBase64(jsonObject: object) {
+ const jsonString = JSON.stringify(jsonObject);
+ return btoa(encodeURIComponent(jsonString)) as Base64String;
+}
+
+// Deserialization: Base64 to JSON
+export function deserializeBase64ToJson<T>(base64: Base64String): T {
+ const decodedString = decodeURIComponent(atob(base64));
+ return JSON.parse(decodedString) as T;
+}