Skip to content

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

feat: `marimo export html-wasm` with included assets (#3134)

Myles Scolnickc27f0f9ae5ba
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 80d5cdad38..171126eafa 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -138,6 +138,7 @@ Using Hatch:
```bash
hatch run lint
+hatch run format
hatch run typecheck:check
```
diff --git a/docs/guides/exporting.md b/docs/guides/exporting.md
index 73abab15eb..804cc8a8b2 100644
--- a/docs/guides/exporting.md
+++ b/docs/guides/exporting.md
@@ -132,6 +132,80 @@ You can also use other tools that work with Jupyter notebooks:
- [Quarto](https://quarto.org) - Create beautiful documents, websites, presentations
- [nbgrader](https://nbgrader.readthedocs.io/) - Grade notebook assignments
+## Export to WASM-powered HTML
+
+Export your notebook to a self-contained HTML file that runs using WebAssembly:
+
+```bash
+# export as readonly, with code locked
+marimo export html-wasm notebook.py -o output_dir --mode run
+# export as an editable notebook
+marimo export html-wasm notebook.py -o output_dir --mode edit
+```
+
+The exported HTML file will run your notebook using WebAssembly, making it completely self-contained and executable in the browser. This means users can interact with your notebook without needing Python or marimo installed.
+
+Options:
+
+- `--mode`: Choose between `run` (read-only) or `edit` (allows editing)
+- `--output`: Directory to save the HTML and required assets
+
+```{admonition} Note
+:class: note
+
+The exported file must be served over HTTP to function correctly - it cannot be opened directly from the filesystem (file://).
+Your server must also serve the assets in the `assets` directory, next to the HTML file. For this reason, we recommend using the online playground if possible: <https://marimo.app>.
+```
+
+### Testing the export
+
+You can test the export by running the following command in the directory containing your notebook:
+
+```bash
+cd path/to/output_dir
+python -m http.server
+```
+
+## Deploying to GitHub Pages
+
+You can deploy your WebAssembly marimo notebook to GitHub Pages using the following GitHub Actions workflow:
+
+```yaml
+jobs:
+ build:
+ runs-on: ubuntu-latest
+
+ steps:
+ # ... checkout and install dependencies
+
+ - name: 📄 Export notebook
+ run: |
+ marimo export html-wasm notebook.py -o path/to/output --mode run
+
+ - name: 📦 Upload Pages Artifact
+ uses: actions/upload-pages-artifact@v3
+ with:
+ path: path/to/output
+
+ deploy:
+ needs: build
+ runs-on: ubuntu-latest
+ environment:
+ name: github-pages
+ url: ${{ steps.deployment.outputs.page_url }}
+
+ permissions:
+ pages: write
+ id-token: write
+
+ steps:
+ - name: 🌐 Deploy to GitHub Pages
+ id: deployment
+ uses: actions/deploy-pages@v4
+ with:
+ artifact_name: github-pages
+```
+
## 🏝️ Embed marimo outputs in HTML using Islands
```{admonition} Preview
diff --git a/frontend/public/invalid_kernel_id.html b/frontend/public/invalid_kernel_id.html
deleted file mode 100644
index 1b05f0c0df..0000000000
--- a/frontend/public/invalid_kernel_id.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
- <head>
- <meta charset="utf-8" />
- <link rel="icon" href="/favicon.ico" />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <meta name="theme-color" content="#000000" />
- <meta name="description" content="Web site created using create-react-app" />
- <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
- <link rel="manifest" href="/manifest.json" />
- <title>kernel not found</title>
- </head>
- <body>
- <div id="root">
- <p>invalid kernel id</p>
- </div>
- </body>
-</html>
diff --git a/frontend/src/components/editor/controls/shutdown-button.tsx b/frontend/src/components/editor/controls/shutdown-button.tsx
index e8e4985911..99c5c7f5e2 100644
--- a/frontend/src/components/editor/controls/shutdown-button.tsx
+++ b/frontend/src/components/editor/controls/shutdown-button.tsx
@@ -6,6 +6,7 @@ import { Tooltip } from "../../ui/tooltip";
import { useImperativeModal } from "../../modal/ImperativeModal";
import { XIcon } from "lucide-react";
import { sendShutdown } from "@/core/network/requests";
+import { isWasm } from "@/core/wasm/utils";
export const ShutdownButton: React.FC<{ description: string }> = (props) => {
const { openConfirm, closeModal } = useImperativeModal();
@@ -17,6 +18,10 @@ export const ShutdownButton: React.FC<{ description: string }> = (props) => {
}, 200);
};
+ if (isWasm()) {
+ return null;
+ }
+
return (
<Tooltip content="Shutdown">
<Button
diff --git a/marimo/_cli/export/commands.py b/marimo/_cli/export/commands.py
index 8da5d4c4ea..c2881d9b76 100644
--- a/marimo/_cli/export/commands.py
+++ b/marimo/_cli/export/commands.py
@@ -2,7 +2,8 @@
from __future__ import annotations
import asyncio
-from typing import TYPE_CHECKING, Callable, Literal
+import os
+from typing import TYPE_CHECKING, Callable, Literal, Optional
import click
@@ -15,9 +16,11 @@ from marimo._server.export import (
export_as_ipynb,
export_as_md,
export_as_script,
+ export_as_wasm,
run_app_then_export_as_html,
run_app_then_export_as_ipynb,
)
+from marimo._server.export.exporter import Exporter
from marimo._server.utils import asyncio_run
from marimo._utils.file_watcher import FileWatcher
from marimo._utils.marimo_path import MarimoPath
@@ -34,7 +37,7 @@ def export() -> None:
def watch_and_export(
marimo_path: MarimoPath,
- output: str,
+ output: Optional[str],
watch: bool,
export_callback: Callable[[MarimoPath], ExportResult],
) -> None:
@@ -66,7 +69,10 @@ def watch_and_export(
return
async def on_file_changed(file_path: Path) -> None:
- echo(f"File {str(file_path)} changed. Re-exporting to {green(output)}")
+ if output:
+ echo(
+ f"File {str(file_path)} changed. Re-exporting to {green(output)}"
+ )
result = export_callback(MarimoPath(file_path))
write_data(result.contents)
@@ -335,7 +341,69 @@ def ipynb(
return watch_and_export(MarimoPath(name), output, watch, export_callback)
+ help="""Export a notebook as a WASM-powered standalone HTML file.
+
+Example:
+
+ \b
+ * marimo export html-wasm notebook.py -o notebook.wasm.html
+
+The exported HTML file will run the notebook using WebAssembly, making it
+completely self-contained and executable in the browser. This lets you
+share interactive notebooks on the web without setting up
+infrastructure to run Python code.
+
+The exported notebook runs using Pyodide, which supports most
+but not all Python packages. To learn more, see the Pyodide
+documentation.
+
+In order for this file to be able to run, it must be served over HTTP,
+and cannot be opened directly from the file system (e.g. file://).
+"""
+)
+ "-o",
+ "--output",
+ type=str,
+ required=True,
+ help="""Output directory to save the HTML to.""",
+)
+ "--mode",
+ type=click.Choice(["edit", "run"]),
+ help="Whether the notebook code should be editable or readonly",
+ required=True,
+)
[email protected]("name", required=True, callback=validators.is_file_path)
+def html_wasm(
+ name: str,
+ output: str,
+ mode: Literal["edit", "run"],
+) -> None:
+ """Export a notebook as a WASM-powered standalone HTML file."""
+
+ def export_callback(file_path: MarimoPath) -> ExportResult:
+ return export_as_wasm(file_path, mode)
+
+ # Validate output is not a file
+ if os.path.isfile(output):
+ raise click.UsageError(
+ f"Output {output} is a file, but must be a directory."
+ )
+
+ # Export assets first
+ Exporter().export_assets(output)
+ echo(
+ f"Assets copied to {green(output)}. These assets are required for the notebook to run in the browser."
+ )
+
+ outfile = os.path.join(output, "index.html")
+ return watch_and_export(MarimoPath(name), outfile, False, export_callback)
+
+
export.add_command(html)
export.add_command(script)
export.add_command(md)
export.add_command(ipynb)
+export.add_command(html_wasm)
diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.py
index eeb426d467..e15221f586 100644
--- a/marimo/_server/export/__init__.py
+++ b/marimo/_server/export/__init__.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import asyncio
import sys
from dataclasses import dataclass
-from typing import Any, Callable, Literal, cast
+from typing import Any, Callable, Literal, Optional, cast
from marimo._cli.print import echo
from marimo._config.manager import (
@@ -83,6 +83,31 @@ def export_as_ipynb(
)
+def export_as_wasm(
+ path: MarimoPath,
+ mode: Literal["edit", "run"],
+ asset_url: Optional[str] = None,
+) -> ExportResult:
+ file_router = AppFileRouter.from_filename(path)
+ file_key = file_router.get_unique_file_key()
+ assert file_key is not None
+ file_manager = file_router.get_file_manager(file_key)
+ config = get_default_config_manager(current_path=file_manager.path)
+
+ result = Exporter().export_as_wasm(
+ file_manager=file_manager,
+ display_config=config.get_config()["display"],
+ mode=mode,
+ code=file_manager.to_code(),
+ asset_url=asset_url,
+ )
+ return ExportResult(
+ contents=result[0],
+ download_filename=result[1],
+ did_error=False,
+ )
+
+
async def run_app_then_export_as_ipynb(
path: MarimoPath,
sort_mode: Literal["top-down", "topological"],
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index 0b30df5fff..7c4f127483 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -5,15 +5,17 @@ import base64
import io
import mimetypes
import os
+from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, Optional, cast
-from marimo import __version__
+from marimo import __version__, _loggers
from marimo._ast.app import is_default_cell_name
from marimo._ast.cell import Cell, CellConfig, CellImpl
from marimo._config.config import (
DEFAULT_CONFIG,
DisplayConfig,
)
+from marimo._config.settings import GLOBAL_SETTINGS
from marimo._config.utils import deep_copy
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.cell_output import CellChannel, CellOutput
@@ -30,10 +32,15 @@ from marimo._server.export.utils import (
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._server.templates.templates import (
+ static_notebook_template,
+ wasm_notebook_template,
+)
from marimo._server.tokens import SkewProtectionToken
from marimo._utils.paths import import_files
+LOGGER = _loggers.marimo_logger()
+
# Root directory for static assets
root = os.path.realpath(str(import_files("marimo").joinpath("_static")))
@@ -50,14 +57,11 @@ class Exporter:
display_config: DisplayConfig,
request: ExportAsHTMLRequest,
) -> tuple[str, str]:
- index_html_file = os.path.join(root, "index.html")
+ index_html = get_html_contents()
cell_ids = list(file_manager.app.cell_manager.cell_ids())
filename = get_filename(file_manager)
- with open(index_html_file, "r") as f: # noqa: ASYNC101 ASYNC230
- index_html = f.read()
-
files: dict[str, str] = {}
for filename_and_length in request.files:
if filename_and_length.startswith("/@file/"):
@@ -300,6 +304,50 @@ class Exporter:
download_filename = get_download_filename(file_manager, "md")
return "\n".join(document).strip(), download_filename
+ def export_as_wasm(
+ self,
+ *,
+ file_manager: AppFileManager,
+ display_config: DisplayConfig,
+ code: str,
+ mode: Literal["edit", "run"],
+ asset_url: Optional[str] = None,
+ ) -> tuple[str, str]:
+ """Export notebook as a WASM-powered standalone HTML file."""
+ index_html = get_html_contents()
+ filename = get_filename(file_manager)
+
+ # We only want to pass the display config in the static notebook
+ config = deep_copy(DEFAULT_CONFIG)
+ config["display"] = display_config
+
+ html = wasm_notebook_template(
+ html=index_html,
+ version=__version__,
+ filename=filename,
+ mode=mode,
+ user_config=config,
+ config_overrides={},
+ app_config=file_manager.app.config,
+ code=code,
+ asset_url=asset_url,
+ )
+
+ download_filename = get_download_filename(file_manager, "wasm.html")
+
+ return html, download_filename
+
+ def export_assets(self, directory: str) -> None:
+ # Copy assets to the same directory as the notebook
+ dirpath = Path(directory)
+ LOGGER.debug(f"Copying assets to {dirpath}")
+ if not dirpath.exists():
+ dirpath.mkdir(parents=True, exist_ok=True)
+
+ import shutil
+
+ shutil.copytree(root, dirpath, dirs_exist_ok=True)
+
class AutoExporter:
EXPORT_DIR = "__marimo__"
@@ -364,6 +412,22 @@ def _create_notebook_cell(
return node
+def get_html_contents() -> str:
+ if GLOBAL_SETTINGS.DEVELOPMENT_MODE:
+ import urllib.request
+
+ # Fetch from a CDN
+ LOGGER.info(
+ "Fetching index.html from jsdelivr because in development mode"
+ )
+ url = f"https://cdn.jsdelivr.net/npm/@marimo-team/frontend@{__version__}/dist/index.html"
+ with urllib.request.urlopen(url) as response:
+ return cast(str, response.read().decode("utf-8"))
+
+ with open(os.path.join(root, "index.html"), "r") as f:
+ return f.read()
+
+
def _convert_marimo_output_to_ipynb(
output: Optional[CellOutput], console_outputs: list[CellOutput]
) -> list["nbformat.NotebookNode"]:
diff --git a/marimo/_server/export/utils.py b/marimo/_server/export/utils.py
index e9b5006ed6..7c54e53458 100644
--- a/marimo/_server/export/utils.py
+++ b/marimo/_server/export/utils.py
@@ -37,6 +37,8 @@ def get_app_title(file_manager: AppFileManager) -> str:
def get_download_filename(file_manager: AppFileManager, extension: str) -> str:
filename = get_filename(file_manager, f"notebook.{extension}")
basename = os.path.basename(filename)
+ if basename.endswith(f".{extension}"):
+ return basename
return f"{os.path.splitext(basename)[0]}.{extension}"
diff --git a/marimo/_server/templates/templates.py b/marimo/_server/templates/templates.py
index 0c7b646956..3f9ed627d2 100644
--- a/marimo/_server/templates/templates.py
+++ b/marimo/_server/templates/templates.py
@@ -5,7 +5,7 @@ import base64
import json
import os
from textwrap import dedent
-from typing import Any, List, Optional, cast
+from typing import Any, List, Literal, Optional, cast
from marimo import __version__
from marimo._ast.app import _AppConfig
@@ -58,9 +58,11 @@ def notebook_page_template(
html = html.replace(
"{{ title }}",
- parse_title(filename)
- if app_config.app_title is None
- else app_config.app_title,
+ (
+ parse_title(filename)
+ if app_config.app_title is None
+ else app_config.app_title
+ ),
)
html = html.replace(
"{{ app_config }}", json.dumps(_del_none_or_empty(app_config.asdict()))
@@ -125,9 +127,11 @@ def static_notebook_template(
html = html.replace(
"{{ title }}",
- parse_title(filepath)
- if app_config.app_title is None
- else app_config.app_title,
+ (
+ parse_title(filepath)
+ if app_config.app_title is None
+ else app_config.app_title
+ ),
)
html = html.replace(
"{{ app_config }}",
@@ -146,7 +150,8 @@ def static_notebook_template(
if output
}
- static_block = dedent(f"""
+ static_block = dedent(
+ f"""
<script data-marimo="true">
window.__MARIMO_STATIC__ = {{}};
window.__MARIMO_STATIC__.version = "{__version__}";
@@ -164,7 +169,8 @@ def static_notebook_template(
window.__MARIMO_STATIC__.assetUrl = "{asset_url}";
window.__MARIMO_STATIC__.files = {json.dumps(files)};
</script>
- """)
+ """
+ )
# Add HTML head file contents if specified
if app_config.html_head_file:
@@ -172,25 +178,31 @@ def static_notebook_template(
app_config.html_head_file, filename=filepath
)
if head_contents:
- static_block += dedent(f"""
+ static_block += dedent(
+ f"""
{head_contents}
- """)
+ """
+ )
# If has custom css, inline the css and add to the head
if app_config.css_file:
css_contents = read_css_file(app_config.css_file, filename=filepath)
if css_contents:
- static_block += dedent(f"""
+ static_block += dedent(
+ f"""
<style>
{css_contents}
</style>
- """)
+ """
+ )
- code_block = dedent(f"""
+ code_block = dedent(
+ f"""
<marimo-code hidden="">
{uri_encode_component(code)}
</marimo-code>
- """)
+ """
+ )
if not code:
code_block = '<marimo-code hidden=""></marimo-code>'
@@ -215,6 +227,75 @@ def static_notebook_template(
return html
+def wasm_notebook_template(
+ *,
+ html: str,
+ version: str,
+ filename: str,
+ user_config: MarimoConfig,
+ config_overrides: PartialMarimoConfig,
+ app_config: _AppConfig,
+ mode: Literal["edit", "run"],
+ code: str,
+ asset_url: Optional[str] = None,
+) -> str:
+ """Template for WASM notebooks."""
+ import re
+
+ body = html
+
+ if asset_url is not None:
+ body = re.sub(r'="./assets/', f'="{asset_url}/assets/', body)
+
+ body = body.replace("{{ base_url }}", "")
+ body = body.replace("{{ title }}", "marimo")
+ body = body.replace("{{ user_config }}", json.dumps(user_config))
+ body = body.replace(
+ "{{ app_config }}", json.dumps(_del_none_or_empty(app_config.asdict()))
+ )
+ body = body.replace("{{ config_overrides }}", json.dumps(config_overrides))
+ body = body.replace("{{ server_token }}", "123")
+ body = body.replace("{{ version }}", version)
+ body = body.replace("{{ filename }}", filename)
+ body = body.replace("{{ mode }}", "edit" if mode == "edit" else "read")
+ body = body.replace(
+ "</head>", '<marimo-wasm hidden=""></marimo-wasm></head>'
+ )
+
+ warning_script = """
+ <script>
+ if (window.location.protocol === 'file:') {
+ alert('Warning: This file must be served by an HTTP server to function correctly.');
+ }
+ </script>
+ """
+ body = body.replace("</head>", f"{warning_script}</head>")
+
+ # If has custom css, inline the css and add to the head
+ if app_config.css_file:
+ css_contents = read_css_file(app_config.css_file, filename=filename)
+ if css_contents:
+ css_contents = f"<style>{css_contents}</style>"
+ # Append to head
+ body = body.replace("</head>", f"{css_contents}</head>")
+
+ # Add HTML head file contents if specified
+ if app_config.html_head_file:
+ head_contents = read_html_head_file(
+ app_config.html_head_file, filename=filename
+ )
+ if head_contents:
+ # Append to head
+ body = body.replace("</head>", f"{head_contents}</head>")
+
+ body = body.replace(
+ "</head>",
+ f'<marimo-code hidden="">{uri_encode_component(code)}</marimo-code></head>',
+ )
+
+ return body
+
+
def _serialize_to_base64(value: str) -> str:
# Encode the JSON string to URL-encoded format
url_encoded = uri_encode_component(value)
@@ -229,9 +310,11 @@ def _serialize_list_to_base64(value: list[str]) -> list[str]:
def _del_none_or_empty(d: Any) -> Any:
return {
- key: _del_none_or_empty(cast(Any, value))
- if isinstance(value, dict)
- else value
+ key: (
+ _del_none_or_empty(cast(Any, value))
+ if isinstance(value, dict)
+ else value
+ )
for key, value in d.items()
if value is not None and value != []
}
diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.py
index 704f6294da..1c631be1cd 100644
--- a/tests/_cli/test_cli_export.py
+++ b/tests/_cli/test_cli_export.py
@@ -59,6 +59,50 @@ class TestExportHTML:
html = html.replace(dirname, "path")
assert '<marimo-code hidden=""></marimo-code>' in html
+ @staticmethod
+ def test_cli_export_html_wasm(temp_marimo_file: str) -> None:
+ out_dir = Path(temp_marimo_file).parent / "out"
+ p = subprocess.run(
+ [
+ "marimo",
+ "export",
+ "html-wasm",
+ temp_marimo_file,
+ "--mode",
+ "edit",
+ "--output",
+ out_dir,
+ ],
+ capture_output=True,
+ )
+ assert p.returncode == 0, p.stderr.decode()
+ html = Path(out_dir / "index.html").read_text()
+ assert "<marimo-mode data-mode='edit'" in html
+ assert '<marimo-code hidden=""></marimo-code>' not in html
+ assert "<marimo-wasm" in html
+
+ @staticmethod
+ def test_cli_export_html_wasm_read(temp_marimo_file: str) -> None:
+ out_dir = Path(temp_marimo_file).parent / "out"
+ p = subprocess.run(
+ [
+ "marimo",
+ "export",
+ "html-wasm",
+ temp_marimo_file,
+ "--mode",
+ "run",
+ "--output",
+ out_dir,
+ ],
+ capture_output=True,
+ )
+ assert p.returncode == 0, p.stderr.decode()
+ html = Path(out_dir / "index.html").read_text()
+ assert "<marimo-mode data-mode='read'" in html
+ assert '<marimo-code hidden=""></marimo-code>' not in html
+ assert "<marimo-wasm" in html
+
@staticmethod
def test_cli_export_async(temp_async_marimo_file: str) -> None:
p = subprocess.run(
diff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.py
index 0ace132020..3e6ac873be 100644
--- a/tests/_server/export/test_exporter.py
+++ b/tests/_server/export/test_exporter.py
@@ -5,6 +5,7 @@ import json
import pytest
from marimo._ast.app import App, InternalApp
+from marimo._config.config import DEFAULT_CONFIG
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.ops import CellOp
from marimo._output.hypertext import patch_html_for_non_interactive_output
@@ -259,3 +260,49 @@ async def test_run_until_completion_with_stop():
[op.output.data for op in output_data if op.output is not None]
)
snapshot("run_until_completion_with_stop.txt", serialized_out)
+
+
+async def test_export_wasm_edit():
+ app = App()
+
+ @app.cell()
+ def cell_1():
+ print("hello wasm")
+ return
+
+ file_manager = AppFileManager.from_app(InternalApp(app))
+ exporter = Exporter()
+
+ content, filename = exporter.export_as_wasm(
+ file_manager=file_manager,
+ display_config=DEFAULT_CONFIG["display"],
+ mode="edit",
+ code=file_manager.to_code(),
+ )
+
+ assert filename == "notebook.wasm.html"
+ assert "alert(" in content
+ assert "mode='edit'" in content
+
+
+async def test_export_wasm_run():
+ app = App()
+
+ @app.cell()
+ def cell_1():
+ print("hello wasm")
+ return
+
+ file_manager = AppFileManager.from_app(InternalApp(app))
+ exporter = Exporter()
+
+ content, filename = exporter.export_as_wasm(
+ file_manager=file_manager,
+ display_config=DEFAULT_CONFIG["display"],
+ mode="run",
+ code=file_manager.to_code(),
+ )
+
+ assert filename == "notebook.wasm.html"
+ assert "alert(" in content
+ assert "mode='read'" in content
diff --git a/tests/_server/templates/test_templates.py b/tests/_server/templates/test_templates.py
index 28de3d3aef..4587a87495 100644
--- a/tests/_server/templates/test_templates.py
+++ b/tests/_server/templates/test_templates.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import json
import os
import unittest
+from typing import Literal
from marimo._ast.app import _AppConfig
from marimo._ast.cell import CellConfig
@@ -362,3 +363,101 @@ class TestStaticNotebookTemplate(unittest.TestCase):
snapshot("export5.txt", normalize_index_html(result))
finally:
os.remove(head_file)
+
+
+class TestWasmNotebookTemplate(unittest.TestCase):
+ def setUp(self) -> None:
+ 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.version = "1.0.0"
+ self.filename = "notebook.py"
+ self.mode: Literal["edit", "run"] = "run"
+ self.user_config = DEFAULT_CONFIG
+ self.app_config = _AppConfig()
+ self.code = "print('Hello, World!')"
+ self.config_overrides: PartialMarimoConfig = {}
+
+ def test_wasm_notebook_template(self) -> None:
+ result = templates.wasm_notebook_template(
+ html=self.html,
+ version=self.version,
+ filename=self.filename,
+ mode=self.mode,
+ user_config=self.user_config,
+ config_overrides=self.config_overrides,
+ app_config=self.app_config,
+ code=self.code,
+ )
+
+ assert self.filename in result
+ assert self.mode in result
+ assert json.dumps(self.user_config) in result
+ assert '<marimo-wasm hidden="">' in result
+ assert '<marimo-code hidden="">' in result
+
+ def test_wasm_notebook_template_custom_css_and_assets(self) -> None:
+ # Create css file
+ css = "/* custom css */"
+
+ css_file = os.path.join(os.path.dirname(self.filename), "custom.css")
+ with open(css_file, "w") as f:
+ f.write(css)
+
+ try:
+ result = templates.wasm_notebook_template(
+ html=self.html,
+ version=self.version,
+ filename=self.filename,
+ mode=self.mode,
+ user_config=self.user_config,
+ config_overrides=self.config_overrides,
+ app_config=_AppConfig(css_file="custom.css"),
+ code=self.code,
+ asset_url="https://my.cdn.com",
+ )
+
+ assert css in result
+ assert '<marimo-wasm hidden="">' in result
+ assert "https://my.cdn.com/assets/" in result
+ finally:
+ os.remove(css_file)
+
+ def test_wasm_notebook_template_custom_head(self) -> None:
+ # Create html head file
+ head = """
+ <!-- Google tag (gtag.js) -->
+ <script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
+ <script>
+ window.dataLayer = window.dataLayer || [];
+ function gtag(){dataLayer.push(arguments);}
+ gtag('js', new Date());
+ gtag('config', 'G-XXXXXXXXXX');
+ </script>
+ <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
+ """
+
+ head_file = os.path.join(os.path.dirname(self.filename), "head.html")
+ with open(head_file, "w") as f:
+ f.write(head)
+
+ try:
+ result = templates.wasm_notebook_template(
+ html=self.html,
+ version=self.version,
+ filename=self.filename,
+ mode=self.mode,
+ user_config=self.user_config,
+ config_overrides=self.config_overrides,
+ app_config=_AppConfig(html_head_file="head.html"),
+ code=self.code,
+ )
+
+ assert head in result
+ assert '<marimo-wasm hidden="">' in result
+ finally:
+ os.remove(head_file)