Skip to content

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

improvement: inline layouts when exported to wasm (#3661)

Myles Scolnicke77840e4f66d
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 78bf11dec8..baaeec6b51 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -2,8 +2,10 @@
from __future__ import annotations
import ast
+import base64
import inspect
from dataclasses import asdict, dataclass, field
+from pathlib import Path
from textwrap import dedent
from typing import (
TYPE_CHECKING,
@@ -472,6 +474,19 @@ class InternalApp:
def update_config(self, updates: dict[str, Any]) -> _AppConfig:
return self.config.update(updates)
+ def inline_layout_file(self) -> InternalApp:
+ if self.config.layout_file:
+ layout_path = Path(self.config.layout_file)
+ if self._app._filename:
+ # Resolve relative to the current working directory
+ layout_path = Path(self._app._filename).parent / layout_path
+ layout_file = layout_path.read_bytes()
+ data_uri = base64.b64encode(layout_file).decode()
+ self.update_config(
+ {"layout_file": f"data:application/json;base64,{data_uri}"}
+ )
+ return self
+
def with_data(
self,
*,
diff --git a/marimo/_output/data/data.py b/marimo/_output/data/data.py
index cd1887450d..4d358f979d 100644
--- a/marimo/_output/data/data.py
+++ b/marimo/_output/data/data.py
@@ -159,13 +159,3 @@ def any_data(data: Union[str, bytes, io.BytesIO], ext: str) -> VirtualFile:
return item.virtual_file
raise ValueError(f"Unsupported data type: {type(data)}")
-
-
-# Format: data:mime_type;base64,data
-def from_data_uri(data: str) -> tuple[str, bytes]:
- assert isinstance(data, str)
- assert data.startswith("data:")
- mime_type, data = data.split(",", 1)
- # strip data: and ;base64
- mime_type = mime_type.split(";")[0][5:]
- return mime_type, base64.b64decode(data)
diff --git a/marimo/_output/formatters/matplotlib_formatters.py b/marimo/_output/formatters/matplotlib_formatters.py
index f18d89f56c..095fb95d66 100644
--- a/marimo/_output/formatters/matplotlib_formatters.py
+++ b/marimo/_output/formatters/matplotlib_formatters.py
@@ -32,7 +32,7 @@ class MatplotlibFormatter(FormatterFactory):
from matplotlib.container import BarContainer # type: ignore
from marimo._output import formatting
- from marimo._output.utils import build_data_url
+ from marimo._utils.data_uri import build_data_url
def mime_data_artist(artist: Artist) -> tuple[KnownMimeType, str]:
buf = io.BytesIO()
diff --git a/marimo/_output/mpl.py b/marimo/_output/mpl.py
index c0824f8d39..3d20b02b67 100644
--- a/marimo/_output/mpl.py
+++ b/marimo/_output/mpl.py
@@ -27,7 +27,7 @@ from matplotlib.backends.backend_agg import FigureCanvasAgg
from marimo._messaging.cell_output import CellChannel
from marimo._messaging.mimetypes import KnownMimeType
from marimo._messaging.ops import CellOp
-from marimo._output.utils import build_data_url
+from marimo._utils.data_uri import build_data_url
FigureCanvas = FigureCanvasAgg
diff --git a/marimo/_output/utils.py b/marimo/_output/utils.py
index e546c38529..16710a1d09 100644
--- a/marimo/_output/utils.py
+++ b/marimo/_output/utils.py
@@ -4,15 +4,6 @@ from __future__ import annotations
import urllib.parse
from typing import Optional, Union
-from marimo._messaging.mimetypes import KnownMimeType
-
-
-def build_data_url(mimetype: KnownMimeType, data: bytes) -> str:
- assert mimetype is not None
- # `data` must be base64 encoded
- str_repr = data.decode("utf-8").replace("\n", "")
- return f"data:{mimetype};base64,{str_repr}"
-
def flatten_string(text: str) -> str:
return "".join([line.strip() for line in text.split("\n")])
diff --git a/marimo/_plugins/ui/_impl/charts/altair_transformer.py b/marimo/_plugins/ui/_impl/charts/altair_transformer.py
index 59183d8c57..87899eedf1 100644
--- a/marimo/_plugins/ui/_impl/charts/altair_transformer.py
+++ b/marimo/_plugins/ui/_impl/charts/altair_transformer.py
@@ -9,11 +9,11 @@ from narwhals.typing import IntoDataFrame
import marimo._output.data.data as mo_data
from marimo._dependencies.dependencies import DependencyManager
-from marimo._output.utils import build_data_url
from marimo._plugins.ui._impl.tables.utils import (
get_table_manager,
get_table_manager_or_none,
)
+from marimo._utils.data_uri import build_data_url
Data = Union[Dict[Any, Any], IntoDataFrame, nw.DataFrame[Any]]
_DataType = Union[Dict[Any, Any], IntoDataFrame, nw.DataFrame[Any]]
diff --git a/marimo/_runtime/layout/layout.py b/marimo/_runtime/layout/layout.py
index ca95c48c94..274c563b36 100644
--- a/marimo/_runtime/layout/layout.py
+++ b/marimo/_runtime/layout/layout.py
@@ -7,6 +7,7 @@ from dataclasses import dataclass
from typing import Any, Optional
from marimo import _loggers
+from marimo._utils.data_uri import from_data_uri
LOGGER = _loggers.marimo_logger()
@@ -57,6 +58,18 @@ def read_layout_config(
Returns: the layout configuration
"""
+ # Handle data URI
+ if filename.startswith("data:"):
+ try:
+ # Decode base64
+ _mime, data = from_data_uri(filename)
+ # Parse as JSON
+ data_json = json.loads(data)
+ return LayoutConfig(type=data_json["type"], data=data_json["data"])
+ except Exception as e:
+ LOGGER.warning("Failed to decode data URI: %s", e)
+ return None
+
filepath = os.path.join(directory, filename)
if not os.path.exists(filepath):
LOGGER.warning("Layout file %s does not exist", filepath)
@@ -66,4 +79,4 @@ def read_layout_config(
return None
with open(filepath) as f:
data = json.load(f)
- return LayoutConfig(type=data["type"], data=data["data"])
+ return LayoutConfig(type=data["type"], data=data["data"]) # type: ignore[call-overload]
diff --git a/marimo/_runtime/virtual_file.py b/marimo/_runtime/virtual_file.py
index cae8420414..1e896dae33 100644
--- a/marimo/_runtime/virtual_file.py
+++ b/marimo/_runtime/virtual_file.py
@@ -12,10 +12,10 @@ from typing import TYPE_CHECKING, Optional, cast
from marimo import _loggers
from marimo._messaging.mimetypes import KnownMimeType
-from marimo._output.utils import build_data_url
from marimo._runtime.cell_lifecycle_item import CellLifecycleItem
from marimo._runtime.context import ContextNotInitializedError
from marimo._server.api.status import HTTPException, HTTPStatus
+from marimo._utils.data_uri import build_data_url
from marimo._utils.platform import is_pyodide
if TYPE_CHECKING:
diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.py
index fc2cf56734..2957d96d7f 100644
--- a/marimo/_server/export/__init__.py
+++ b/marimo/_server/export/__init__.py
@@ -93,6 +93,8 @@ def export_as_wasm(
file_key = file_router.get_unique_file_key()
assert file_key is not None
file_manager = file_router.get_file_manager(file_key)
+ # Inline the layout file, if it exists
+ file_manager.app.inline_layout_file()
config = get_default_config_manager(current_path=file_manager.path)
result = Exporter().export_as_wasm(
@@ -150,6 +152,9 @@ async def run_app_then_export_as_html(
assert file_key is not None
file_manager = file_router.get_file_manager(file_key)
+ # Inline the layout file, if it exists
+ file_manager.app.inline_layout_file()
+
config = get_default_config_manager(current_path=file_manager.path)
session_view, did_error = await run_app_until_completion(
file_manager,
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index 66bcd5be28..8779afaa99 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -27,7 +27,6 @@ from marimo._config.utils import deep_copy
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.mimetypes import KnownMimeType
-from marimo._output.utils import build_data_url
from marimo._runtime import dataflow
from marimo._runtime.virtual_file import read_virtual_file
from marimo._server.export.utils import (
@@ -44,6 +43,7 @@ from marimo._server.templates.templates import (
wasm_notebook_template,
)
from marimo._server.tokens import SkewProtectionToken
+from marimo._utils.data_uri import build_data_url
from marimo._utils.marimo_path import MarimoPath
from marimo._utils.paths import import_files
@@ -414,7 +414,8 @@ class Exporter:
def export_public_folder(
self, directory: str, marimo_file: MarimoPath
) -> bool:
- public_dir = marimo_file.path.parent / "public"
+ FOLDER_NAME = "public"
+ public_dir = marimo_file.path.parent / FOLDER_NAME
if public_dir.exists():
import shutil
@@ -424,10 +425,15 @@ class Exporter:
if not dirpath.exists():
dirpath.mkdir(parents=True, exist_ok=True)
+ target_dir = dirpath / FOLDER_NAME
+ if target_dir == public_dir:
+ # Skip if source and target are the same
+ return True
+
LOGGER.debug(f"Copying public folder to {dirpath}")
shutil.copytree(
public_dir,
- dirpath / "public",
+ target_dir,
dirs_exist_ok=True,
)
return True
diff --git a/marimo/_utils/data_uri.py b/marimo/_utils/data_uri.py
new file mode 100644
index 0000000000..6428c752fc
--- /dev/null
+++ b/marimo/_utils/data_uri.py
@@ -0,0 +1,20 @@
+from __future__ import annotations
+
+import base64
+
+
+def build_data_url(mimetype: str, data: bytes) -> str:
+ assert mimetype is not None
+ # `data` must be base64 encoded
+ str_repr = data.decode("utf-8").replace("\n", "")
+ return f"data:{mimetype};base64,{str_repr}"
+
+
+# Format: data:mime_type;base64,data
+def from_data_uri(data: str) -> tuple[str, bytes]:
+ assert isinstance(data, str)
+ assert data.startswith("data:")
+ mime_type, data = data.split(",", 1)
+ # strip data: and ;base64
+ mime_type = mime_type.split(";")[0][5:]
+ return mime_type, base64.b64decode(data)
diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.py
index 4298c9ba69..703c33c4f7 100644
--- a/tests/_cli/test_cli_export.py
+++ b/tests/_cli/test_cli_export.py
@@ -112,6 +112,20 @@ class TestExportHTML:
assert (out_dir / "public" / "test.txt").exists()
assert (out_dir / "public" / "test.txt").read_text() == "test content"
+ # Try exporting to the same directory that contains the public folder
+ p = subprocess.run(
+ [
+ "marimo",
+ "export",
+ "html-wasm",
+ temp_marimo_file,
+ "--output",
+ public_dir.parent,
+ ],
+ capture_output=True,
+ )
+ assert p.returncode == 0, p.stderr.decode()
+
# Clean up
shutil.rmtree(public_dir)
diff --git a/tests/_output/test_output_utils.py b/tests/_output/test_output_utils.py
index d886ecf335..af93f49147 100644
--- a/tests/_output/test_output_utils.py
+++ b/tests/_output/test_output_utils.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-import base64
from typing import cast
import pytest
@@ -8,12 +7,6 @@ import pytest
from marimo._output import utils
-def test_build_data_url() -> None:
- data = base64.b64encode(b"test")
- url = utils.build_data_url("text/plain", data)
- assert url == "data:text/plain;base64,dGVzdA=="
-
-
def test_flatten_string() -> None:
text = """
hello
diff --git a/tests/_plugins/ui/_impl/test_data_explorer.py b/tests/_plugins/ui/_impl/test_data_explorer.py
index 464244540b..a2a1fb8470 100644
--- a/tests/_plugins/ui/_impl/test_data_explorer.py
+++ b/tests/_plugins/ui/_impl/test_data_explorer.py
@@ -6,8 +6,8 @@ from typing import Any
import pytest
from marimo._dependencies.dependencies import DependencyManager
-from marimo._output.data.data import from_data_uri
from marimo._plugins.ui._impl import data_explorer
+from marimo._utils.data_uri import from_data_uri
from marimo._utils.platform import is_windows
from tests._data.mocks import create_dataframes
diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.py
index a446bcf95f..a19763644e 100644
--- a/tests/_plugins/ui/_impl/test_table.py
+++ b/tests/_plugins/ui/_impl/test_table.py
@@ -7,7 +7,6 @@ from typing import Any
import pytest
from marimo._dependencies.dependencies import DependencyManager
-from marimo._output.data.data import from_data_uri
from marimo._plugins import ui
from marimo._plugins.ui._impl.dataframes.transforms.types import Condition
from marimo._plugins.ui._impl.table import SearchTableArgs, SortArgs
@@ -15,6 +14,7 @@ from marimo._plugins.ui._impl.tables.default_table import DefaultTableManager
from marimo._plugins.ui._impl.utils.dataframe import TableData
from marimo._runtime.functions import EmptyArgs
from marimo._runtime.runtime import Kernel
+from marimo._utils.data_uri import from_data_uri
from tests._data.mocks import create_dataframes
diff --git a/tests/_runtime/layout/test_layout.py b/tests/_runtime/layout/test_layout.py
new file mode 100644
index 0000000000..e55ad41a89
--- /dev/null
+++ b/tests/_runtime/layout/test_layout.py
@@ -0,0 +1,89 @@
+from __future__ import annotations
+
+import json
+import os
+import tempfile
+from pathlib import Path
+
+import pytest
+
+from marimo._runtime.layout.layout import (
+ LayoutConfig,
+ read_layout_config,
+ save_layout_config,
+)
+
+
+def temp_dir():
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ yield tmp_dir
+
+
+def test_save_layout_config(temp_dir: str):
+ config = LayoutConfig(type="grid", data={"cols": 2})
+ filepath = save_layout_config(temp_dir, "test.py", config)
+
+ assert filepath == "layouts/test.grid.json"
+ full_path = os.path.join(temp_dir, filepath)
+ assert os.path.exists(full_path)
+
+ with open(full_path) as f:
+ saved_data = json.load(f)
+ assert saved_data == {"type": "grid", "data": {"cols": 2}}
+
+
+def test_read_layout_config(temp_dir: str):
+ # Create a test layout file
+ config = LayoutConfig(type="grid", data={"cols": 2})
+ filepath = save_layout_config(temp_dir, "test.py", config)
+
+ # Read it back
+ read_config = read_layout_config(temp_dir, filepath)
+ assert read_config is not None
+ assert read_config.type == "grid"
+ assert read_config.data == {"cols": 2}
+
+
+def test_read_layout_config_data_uri():
+ # Create a data URI
+ config_data = {"type": "grid", "data": {"cols": 2}}
+ json_str = json.dumps(config_data)
+ import base64
+
+ data_uri = f"data:application/json;base64,{base64.b64encode(json_str.encode()).decode()}"
+
+ # Read it
+ config = read_layout_config("", data_uri)
+ assert config is not None
+ assert config.type == "grid"
+ assert config.data == {"cols": 2}
+
+
+def test_read_layout_config_nonexistent_file(temp_dir: str):
+ config = read_layout_config(temp_dir, "nonexistent.json")
+ assert config is None
+
+
+def test_read_layout_config_invalid_extension(temp_dir: str):
+ # Create a non-JSON file
+ path = Path(temp_dir) / "invalid.txt"
+ path.write_text('{"type": "grid", "data": {}}')
+
+ config = read_layout_config(temp_dir, "invalid.txt")
+ assert config is None
+
+
+def test_read_layout_config_invalid_data_uri():
+ config = read_layout_config("", "data:invalid")
+ assert config is None
+
+
+def test_read_layout_config_invalid_json(temp_dir: str):
+ # Create an invalid JSON file
+ path = Path(temp_dir) / "layouts" / "invalid.grid.json"
+ path.parent.mkdir(exist_ok=True)
+ path.write_text("invalid json")
+
+ with pytest.raises(json.JSONDecodeError):
+ read_layout_config(temp_dir, "layouts/invalid.grid.json")
diff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.py
index 6f9e43d8ba..c8d6dc2cdf 100644
--- a/tests/_server/export/test_exporter.py
+++ b/tests/_server/export/test_exporter.py
@@ -1,7 +1,7 @@
from __future__ import annotations
import json
-from typing import Any
+from typing import TYPE_CHECKING, Any
import pytest
@@ -10,13 +10,18 @@ from marimo._config.config import DEFAULT_CONFIG
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.ops import CellOp
from marimo._server.export import (
+ export_as_wasm,
run_app_then_export_as_ipynb,
run_app_until_completion,
)
from marimo._server.export.exporter import Exporter
from marimo._server.file_manager import AppFileManager
+from marimo._utils.marimo_path import MarimoPath
from tests.mocks import snapshotter
+if TYPE_CHECKING:
+ from pathlib import Path
+
snapshot = snapshotter(__file__)
HAS_NBFORMAT = DependencyManager.nbformat.has()
@@ -342,6 +347,37 @@ async def test_export_wasm_run():
assert "mode='read'" in content
+async def test_export_html_with_layout(tmp_path: Path):
+ test_file = tmp_path / "test.py"
+ test_file.write_text(
+ """
+import marimo
+
+app = marimo.App(layout_file="layouts/layout.json")
+
+def __():
+ x = 1
+ return
+"""
+ )
+
+ # Create the layout file
+ layout_file = tmp_path / "layouts" / "layout.json"
+ layout_file.parent.mkdir(parents=True, exist_ok=True)
+ layout_file.write_text('{"type": "slides", "data": {}}')
+
+ # Export the app
+ result = export_as_wasm(
+ path=MarimoPath(test_file),
+ mode="edit",
+ show_code=True,
+ )
+ assert result.did_error is False
+ assert "layout.json" not in result.contents
+ assert "data:application/json" in result.contents
+
+
def _print_messages(messages: list[CellOp]) -> str:
result: list[dict[str, Any]] = []
for message in messages:
diff --git a/tests/_utils/test_data_uri.py b/tests/_utils/test_data_uri.py
new file mode 100644
index 0000000000..e8201663d0
--- /dev/null
+++ b/tests/_utils/test_data_uri.py
@@ -0,0 +1,82 @@
+from __future__ import annotations
+
+import base64
+
+import pytest
+
+from marimo._utils.data_uri import build_data_url, from_data_uri
+
+
+def test_build_data_url():
+ test_data = b"Hello, World!"
+ encoded = base64.b64encode(test_data)
+ url = build_data_url("text/plain", encoded)
+ assert url == f"data:text/plain;base64,{encoded.decode('utf-8')}"
+
+ # Test with binary data
+ binary_data = b"\x00\x01\x02\x03"
+ encoded = base64.b64encode(binary_data)
+ url = build_data_url("application/octet-stream", encoded)
+ assert (
+ url
+ == f"data:application/octet-stream;base64,{encoded.decode('utf-8')}"
+ )
+
+ # Test with JSON data
+ json_data = b'{"key": "value"}'
+ encoded = base64.b64encode(json_data)
+ url = build_data_url("application/json", encoded)
+ assert url == f"data:application/json;base64,{encoded.decode('utf-8')}"
+
+
+def test_build_data_url_newline_handling():
+ test_data = b"Hello\nWorld"
+ encoded = base64.b64encode(test_data)
+ url = build_data_url("text/plain", encoded)
+ assert "\n" not in url
+ assert url == "data:text/plain;base64," + encoded.decode("utf-8").replace(
+ "\n", ""
+ )
+
+
+def test_from_data_uri():
+ # Test text data
+ test_data = b"Hello, World!"
+ encoded = base64.b64encode(test_data).decode()
+ uri = f"data:text/plain;base64,{encoded}"
+ mime_type, data = from_data_uri(uri)
+ assert mime_type == "text/plain"
+ assert data == test_data
+
+ # Test JSON data
+ json_data = b'{"key": "value"}'
+ encoded = base64.b64encode(json_data).decode()
+ uri = f"data:application/json;base64,{encoded}"
+ mime_type, data = from_data_uri(uri)
+ assert mime_type == "application/json"
+ assert data == json_data
+
+ # Test binary data
+ binary_data = b"\x00\x01\x02\x03"
+ encoded = base64.b64encode(binary_data).decode()
+ uri = f"data:application/octet-stream;base64,{encoded}"
+ mime_type, data = from_data_uri(uri)
+ assert mime_type == "application/octet-stream"
+ assert data == binary_data
+
+
+def test_from_data_uri_invalid_input():
+ with pytest.raises(AssertionError):
+ from_data_uri("not-a-data-uri")
+
+ with pytest.raises(AssertionError):
+ from_data_uri(123) # type: ignore
+
+ # Valid prefix but invalid base64
+ with pytest.raises(ValueError):
+ from_data_uri("data:text/plain;base64,not-base64!")
+
+
+def test_build_data_url_invalid_input():
+ with pytest.raises(AssertionError):
+ build_data_url(None, b"data") # type: ignore