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.

fix: properly handle iframes in marimo export (#1258)

Myles Scolnick5b3e615ee9a0
diff --git a/docs/guides/coming_from_jupyter.md b/docs/guides/coming_from_jupyter.md
index e9a26c1851..7493196152 100644
--- a/docs/guides/coming_from_jupyter.md
+++ b/docs/guides/coming_from_jupyter.md
@@ -3,6 +3,5 @@
If you're coming from Jupyter, this guide will help you get started
with marimo. Fun fact: the guide is itself a marimo notebook!
-
-<iframe src="https://marimo.app/l/z0aerp?embed=true" width=800 height=1200>
+<iframe src="https://marimo.app/l/z0aerp?embed=true" width="100%" height=1200 class="demo" frameBorder="0">
</iframe>
diff --git a/docs/guides/wasm.md b/docs/guides/wasm.md
index 08e0f7544c..65ff4f4ba8 100644
--- a/docs/guides/wasm.md
+++ b/docs/guides/wasm.md
@@ -108,7 +108,7 @@ import plotly
**Try it!** A WASM notebook is embedded below. Try installing a package.
-<iframe src="https://marimo.app/l/wvz76s?embed=true" width=800 height=300>
+<iframe src="https://marimo.app/l/wvz76s?embed=true" width="100%" height=300 class="demo" frameBorder="0">
</iframe>
## Configuration
@@ -161,12 +161,13 @@ providing your users with an interactive code playground.
```html
<iframe
src="https://marimo.app/l/aojjhb?embed=true"
- width="800"
+ width="100%"
height="300"
+ frameborder="0"
></iframe>
```
-<iframe src="https://marimo.app/l/aojjhb?embed=true" width="800" height="300"></iframe>
+<iframe src="https://marimo.app/l/aojjhb?embed=true" width="100%" height="300" class="demo" frameBorder="0"></iframe>
### Embedding an existing notebook
@@ -176,12 +177,13 @@ URL to your notebook](#creating-and-sharing-wasm-notebooks), then put it in an i
```html
<iframe
src="https://marimo.app/l/c7h6pz?embed=true"
- width="800"
+ width="100%"
height="300"
+ frameborder="0"
></iframe>
```
-<iframe src="https://marimo.app/l/c7h6pz?embed=true" width="800" height="600"></iframe>
+<iframe src="https://marimo.app/l/c7h6pz?embed=true" width="100%" height="600" class="demo" frameBorder="0"></iframe>
After obtaining a URL to your
notebook,
@@ -194,12 +196,13 @@ You can optionally render embedded notebooks in read-only mode by appending
```html
<iframe
src="https://marimo.app/l/c7h6pz?mode=read&embed=true"
- width="800"
+ width="100%"
height="300"
+ frameborder="0"
></iframe>
```
-<iframe src="https://marimo.app/l/c7h6pz?mode=read&embed=true" width="800" height="600"></iframe>
+<iframe src="https://marimo.app/l/c7h6pz?mode=read&embed=true" width="100%" height="600" class="demo" frameBorder="0"></iframe>
## Limitations
diff --git a/marimo/_output/builder.py b/marimo/_output/builder.py
index 786f635be9..70d1d78887 100644
--- a/marimo/_output/builder.py
+++ b/marimo/_output/builder.py
@@ -1,11 +1,13 @@
# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
from typing import List, Optional, Tuple, Union
class _HTMLBuilder:
@staticmethod
def div(
- children: Union[str, List[str]], style: Optional[str] = None
+ children: Union[str, List[str]], *, style: Optional[str] = None
) -> str:
resolved_children = (
[children] if isinstance(children, str) else children
@@ -24,6 +26,7 @@ class _HTMLBuilder:
@staticmethod
def img(
+ *,
src: Optional[str] = None,
alt: Optional[str] = None,
style: Optional[str] = None,
@@ -43,6 +46,7 @@ class _HTMLBuilder:
@staticmethod
def video(
+ *,
src: Optional[str] = None,
controls: bool = True,
muted: bool = False,
@@ -71,6 +75,7 @@ class _HTMLBuilder:
@staticmethod
def audio(
+ *,
src: Optional[str] = None,
controls: bool = True,
) -> str:
@@ -87,12 +92,15 @@ class _HTMLBuilder:
@staticmethod
def iframe(
+ *,
src: Optional[str] = None,
srcdoc: Optional[str] = None,
width: Optional[str] = None,
height: Optional[str] = None,
style: Optional[str] = None,
onload: Optional[str] = None,
+ # Opinionated defaults
+ frameborder: Optional[str] = "0",
**kwargs: str,
) -> str:
params: List[Tuple[str, Union[str, None]]] = []
@@ -108,6 +116,8 @@ class _HTMLBuilder:
params.append(("style", style))
if onload:
params.append(("onload", onload))
+ if frameborder:
+ params.append(("frameborder", frameborder))
for key, value in kwargs.items():
params.append((key, value))
diff --git a/marimo/_output/formatters/altair_formatters.py b/marimo/_output/formatters/altair_formatters.py
index b837903064..8145108817 100644
--- a/marimo/_output/formatters/altair_formatters.py
+++ b/marimo/_output/formatters/altair_formatters.py
@@ -2,7 +2,9 @@
from __future__ import annotations
from marimo._messaging.mimetypes import KnownMimeType
+from marimo._output.builder import h
from marimo._output.formatters.formatter_factory import FormatterFactory
+from marimo._output.formatters.utils import src_or_src_doc
from marimo._output.utils import flatten_string
@@ -12,8 +14,6 @@ class AltairFormatter(FormatterFactory):
return "altair"
def register(self) -> None:
- import html
-
import altair # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
from marimo._output import formatting
@@ -26,10 +26,6 @@ class AltairFormatter(FormatterFactory):
@formatting.formatter(altair.TopLevelMixin)
def _show_chart(chart: altair.Chart) -> tuple[KnownMimeType, str]:
- # TODO(akshayka): remove the `onload` hack and handle iframe
- # resizing entirely in the frontend
- # `__resizeIframe` is a script defined in the frontend that sets
- # the height of the iframe to the height of the contained document
import altair as alt
# If the user has not set the max_rows option, we set it to 20_000
@@ -40,10 +36,11 @@ class AltairFormatter(FormatterFactory):
"text/html",
(
flatten_string(
- f"<iframe srcdoc='{html.escape(chart.to_html())}'"
- "frameborder='0' scrolling='auto'"
- "style='width: 100%'"
- "onload='__resizeIframe(this)'></iframe>"
+ h.iframe(
+ **src_or_src_doc(chart.to_html()),
+ onload="__resizeIframe(this)",
+ style="width: 100%",
+ )
)
),
)
diff --git a/marimo/_output/formatters/bokeh_formatters.py b/marimo/_output/formatters/bokeh_formatters.py
index e034922821..15ce5d8660 100644
--- a/marimo/_output/formatters/bokeh_formatters.py
+++ b/marimo/_output/formatters/bokeh_formatters.py
@@ -1,9 +1,10 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-import marimo._output.data.data as mo_data
from marimo._messaging.mimetypes import KnownMimeType
+from marimo._output.builder import h
from marimo._output.formatters.formatter_factory import FormatterFactory
+from marimo._output.formatters.utils import src_or_src_doc
from marimo._output.utils import flatten_string
@@ -24,16 +25,14 @@ class BokehFormatter(FormatterFactory):
import bokeh.embed # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
import bokeh.resources # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
- html = bokeh.embed.file_html(plot, bokeh.resources.CDN)
- html_file = mo_data.html(html)
+ html_content = bokeh.embed.file_html(plot, bokeh.resources.CDN)
return (
"text/html",
- (
- flatten_string(
- f"<iframe src='{html_file.url}'"
- "frameborder='0' scrolling='auto'"
- "style='width: 100%'"
- "onload='__resizeIframe(this)'></iframe>"
+ flatten_string(
+ h.iframe(
+ **src_or_src_doc(html_content),
+ onload="__resizeIframe(this)",
+ style="width: 100%",
)
),
)
diff --git a/marimo/_output/formatters/ipython_formatters.py b/marimo/_output/formatters/ipython_formatters.py
index 98c66c744a..7bd1e41cf0 100644
--- a/marimo/_output/formatters/ipython_formatters.py
+++ b/marimo/_output/formatters/ipython_formatters.py
@@ -5,7 +5,7 @@ import functools
from typing import Any, Callable
from marimo._messaging.mimetypes import KnownMimeType
-from marimo._output import builder
+from marimo._output.builder import h
from marimo._output.formatters.formatter_factory import FormatterFactory
@@ -47,12 +47,10 @@ class IPythonFormatter(FormatterFactory):
) -> tuple[KnownMimeType, str]:
if html.url is not None:
# TODO(akshayka): resize iframe not working
- data = builder.h.iframe(
+ data = h.iframe(
src=html.url,
- width="100%",
onload="__resizeIframe(this)",
- scrolling="auto",
- frameborder="0",
+ width="100%",
)
else:
data = str(html._repr_html_()) # type: ignore
diff --git a/marimo/_output/formatters/leafmap_formatters.py b/marimo/_output/formatters/leafmap_formatters.py
index 84e3ba8f42..aa31f3e3d3 100644
--- a/marimo/_output/formatters/leafmap_formatters.py
+++ b/marimo/_output/formatters/leafmap_formatters.py
@@ -3,10 +3,10 @@ from __future__ import annotations
from typing import Any, cast
-import marimo._output.data.data as mo_data
from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.builder import h
from marimo._output.formatters.formatter_factory import FormatterFactory
+from marimo._output.formatters.utils import src_or_src_doc
from marimo._output.utils import flatten_string
@@ -27,17 +27,15 @@ class LeafmapFormatter(FormatterFactory):
# leafmap.folium.Map has a _repr_html_, which we have
# another custom formatter for, but this wraps the map in an
# additional iframe which can cause weird layout issues
- html = mo_data.html(cast(Any, fmap).to_html())
+ html_content = cast(Any, fmap).to_html()
return (
"text/html",
flatten_string(
h.iframe(
- src=html.url,
- scrolling="auto",
- frameborder="0",
- width="100%",
- style="min-height: 540px",
+ **src_or_src_doc(html_content),
onload="__resizeIframe(this)",
+ style="min-height: 540px",
+ width="100%",
)
),
)
@@ -50,17 +48,15 @@ class LeafmapFormatter(FormatterFactory):
# notebook without scrolling
height = lmap.layout.height or "540px"
width = lmap.layout.width or "100%"
- html = mo_data.html(lmap.to_html(width=width, height=height))
+ html_content = lmap.to_html(width=width, height=height)
return (
"text/html",
(
flatten_string(
h.iframe(
- src=html.url,
- scrolling="auto",
- frameborder="0",
- width="100%",
+ **src_or_src_doc(html_content),
onload="__resizeIframe(this)",
+ width="100%",
)
)
),
diff --git a/marimo/_output/formatters/utils.py b/marimo/_output/formatters/utils.py
new file mode 100644
index 0000000000..f36121ec0a
--- /dev/null
+++ b/marimo/_output/formatters/utils.py
@@ -0,0 +1,35 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import html
+from typing import Dict
+
+import marimo._output.data.data as mo_data
+from marimo._runtime.context.types import (
+ ContextNotInitializedError,
+ get_context,
+)
+
+
+def src_or_src_doc(html_content: str) -> Dict[str, str]:
+ """
+ Depending if virtual files are supported,
+ return the appropriate src or srcdoc attribute for an iframe.
+
+ While `src:text/html;base64` is supported in most modern browsers,
+ it does not allow us to resize the iframe to fit the content.
+
+ So, we use `srcdoc` when not running a server (e.g. an html export).
+ """
+
+ try:
+ ctx = get_context()
+ except ContextNotInitializedError:
+ # If no context, return srcdoc
+ return {"srcdoc": html.escape(html_content)}
+
+ if ctx.virtual_files_supported:
+ html_file = mo_data.html(html_content)
+ return {"src": html_file.url}
+ else:
+ return {"srcdoc": html.escape(html_content)}
diff --git a/marimo/_runtime/virtual_file.py b/marimo/_runtime/virtual_file.py
index 86e59adfe1..d27eefd01a 100644
--- a/marimo/_runtime/virtual_file.py
+++ b/marimo/_runtime/virtual_file.py
@@ -128,7 +128,7 @@ class VirtualFileLifecycleItem(CellLifecycleItem):
filename = random_filename(self.ext)
if context is None or not context.virtual_files_supported:
self._virtual_file = VirtualFile(
- filename="", buffer=self.buffer, as_data_url=True
+ filename=filename, buffer=self.buffer, as_data_url=True
)
return
diff --git a/tests/_output/formatters/test_altair.py b/tests/_output/formatters/test_altair.py
new file mode 100644
index 0000000000..ae46330522
--- /dev/null
+++ b/tests/_output/formatters/test_altair.py
@@ -0,0 +1,40 @@
+from __future__ import annotations
+
+import pytest
+
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._runtime.runtime import Kernel
+from tests.conftest import ExecReqProvider
+
+HAS_DEPS = DependencyManager.has_altair()
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+async def test_altair(
+ executing_kernel: Kernel, exec_req: ExecReqProvider
+) -> None:
+ from marimo._output.formatters.formatters import register_formatters
+
+ register_formatters()
+
+ await executing_kernel.run(
+ [
+ exec_req.get(
+ """
+ import altair as alt
+ import pandas as pd
+ from marimo._output.formatting import get_formatter
+
+ data = pd.DataFrame({"a": ["A", "B"], "b": [28, 55]})
+ chart = alt.Chart(data).mark_bar().encode(x="a", y="b")
+ formatter = get_formatter(chart)
+ result = formatter(chart)
+ """
+ )
+ ]
+ )
+
+ result = executing_kernel.globals["result"]
+ assert result is not None
+ assert result[0] == "text/html"
+ assert result[1].startswith("<iframe src=")
diff --git a/tests/_output/formatters/test_formatter_utils.py b/tests/_output/formatters/test_formatter_utils.py
new file mode 100644
index 0000000000..4da987b2a5
--- /dev/null
+++ b/tests/_output/formatters/test_formatter_utils.py
@@ -0,0 +1,32 @@
+from __future__ import annotations
+
+import html
+from typing import Any
+from unittest.mock import Mock, patch
+
+from marimo._output.formatters.utils import src_or_src_doc
+from marimo._runtime.runtime import Kernel
+from tests.conftest import ExecReqProvider
+
+
+def test_srcdoc_in_notebook() -> None:
+ html_content = "<html><body>Hello, World!</body></html>"
+ escaped_html_content = html.escape(html_content)
+
+ result = src_or_src_doc(html_content)
+ assert result == {"srcdoc": escaped_html_content}
+
+
+@patch(
+ "marimo._output.formatters.utils.mo_data.html",
+ return_value=Mock(url="file_url"),
+)
+def test_src_in_notebook(
+ mock_html: Any, executing_kernel: Kernel, exec_req: ExecReqProvider
+) -> None:
+ del executing_kernel
+ del exec_req
+ html_content = "<html><body>Hello, World!</body></html>"
+ result = src_or_src_doc(html_content)
+ assert result == {"src": "file_url"}
+ mock_html.assert_called_once_with(html_content)
diff --git a/tests/_output/test_builder.py b/tests/_output/test_builder.py
index cb76d79cb3..ec93422531 100644
--- a/tests/_output/test_builder.py
+++ b/tests/_output/test_builder.py
@@ -1,11 +1,16 @@
# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
from marimo._output.builder import _join_params, h
def test_div() -> None:
assert h.div("Hello") == "<div>Hello</div>"
assert h.div(["Hello", "World"]) == "<div>HelloWorld</div>"
- assert h.div("Hello", "color:red") == "<div style='color:red'>Hello</div>"
+ assert (
+ h.div("Hello", style="color:red")
+ == "<div style='color:red'>Hello</div>"
+ )
def test_img() -> None:
@@ -31,10 +36,10 @@ def test_audio() -> None:
def test_iframe() -> None:
- assert h.iframe() == "<iframe />"
+ assert h.iframe() == "<iframe frameborder='0' />"
assert (
h.iframe(src="https://marimo.io")
- == "<iframe src='https://marimo.io' />"
+ == "<iframe src='https://marimo.io' frameborder='0' />"
)
diff --git a/tests/_output/test_data.py b/tests/_output/test_data.py
new file mode 100644
index 0000000000..2a2e8afbbf
--- /dev/null
+++ b/tests/_output/test_data.py
@@ -0,0 +1,36 @@
+from __future__ import annotations
+
+import json
+
+import marimo._output.data.data as mo_data
+
+
+def test_html() -> None:
+ html_content = "<html><body><h1>Hello, HTML!</h1></body></html>"
+ vfile = mo_data.html(html_content)
+ assert vfile.filename.endswith(".html")
+ assert (
+ vfile.url
+ == "data:text/html;base64,PGh0bWw+PGJvZHk+PGgxPkhlbGxvLCBIVE1MITwvaDE+PC9ib2R5PjwvaHRtbD4=" # noqa: E501
+ )
+
+
+def test_text() -> None:
+ text_content = "Hello, Text!"
+ vfile = mo_data.any_data(text_content, ext="txt")
+ assert vfile.filename.endswith(".txt")
+ assert vfile.url == "data:text/plain;base64,SGVsbG8sIFRleHQh"
+
+
+def test_json() -> None:
+ json_content = {"key": "value"}
+ vfile = mo_data.json(json.dumps(json_content))
+ assert vfile.filename.endswith(".json")
+ assert vfile.url == "data:application/json;base64,eyJrZXkiOiAidmFsdWUifQ=="
+
+
+def test_csv() -> None:
+ csv_content = "a,b,c\n1,2,3\n4,5,6"
+ vfile = mo_data.csv(csv_content)
+ assert vfile.filename.endswith(".csv")
+ assert vfile.url == "data:text/csv;base64,YSxiLGMKMSwyLDMKNCw1LDY="