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
improvement: auto iframe html output with <script/> tags (#3850)
Myles Scolnick1d028ca3005c
diff --git a/marimo/_output/formatters/iframe.py b/marimo/_output/formatters/iframe.pynew file mode 100644index 0000000000..9cbb2aa138--- /dev/null+++ b/marimo/_output/formatters/iframe.py@@ -0,0 +1,42 @@+from __future__ import annotations++from html.parser import HTMLParser+++def maybe_wrap_in_iframe(html_content: str) -> str:+ if _has_script_tag_without_src(html_content):+ from marimo._output.formatting import iframe++ return iframe(html_content).text+ return html_content+++def _has_script_tag_without_src(html_content: str) -> bool:+ # Cheap check+ if "<script" not in html_content:+ return False++ parser = ScriptTagParser()+ try:+ parser.feed(html_content) # type: ignore+ return parser.has_script_without_src+ except StopIteration:+ return parser.has_script_without_src+ except Exception:+ # Don't fail on bad HTML+ return False+++class ScriptTagParser(HTMLParser):+ def __init__(self) -> None:+ super().__init__()+ self.has_script_without_src = False++ def handle_starttag(+ self, tag: str, attrs: list[tuple[str, str | None]]+ ) -> None:+ if tag == "script":+ if not any(attr[0] == "src" for attr in attrs):+ self.has_script_without_src = True+ # Terminate early+ raise StopIterationdiff --git a/marimo/_output/formatters/repr_formatters.py b/marimo/_output/formatters/repr_formatters.pyindex f6a2d86ba0..9e970de46a 100644--- a/marimo/_output/formatters/repr_formatters.py+++ b/marimo/_output/formatters/repr_formatters.py@@ -4,6 +4,7 @@ from __future__ import annotationsfrom typing import Any, Callable, Optional, Tuplefrom marimo._messaging.mimetypes import KnownMimeType+from marimo._output.formatters.iframe import maybe_wrap_in_iframefrom marimo._plugins.core.media import io_to_data_urlfrom marimo._utils.methods import is_callable_method@@ -91,6 +92,10 @@ def maybe_get_repr_formatter(return ("text/html", md(contents or "").text)+ # Handle HTML with <script> tags:+ if mime_type == "text/html":+ contents = maybe_wrap_in_iframe(contents)+return (mime_type, contents)return ("text/html", "")diff --git a/marimo/_smoke_tests/third_party/_treescope.py b/marimo/_smoke_tests/third_party/_treescope.pynew file mode 100644index 0000000000..965ed8b1db--- /dev/null+++ b/marimo/_smoke_tests/third_party/_treescope.py@@ -0,0 +1,35 @@+# /// script+# requires-python = ">=3.12"+# dependencies = [+# "marimo",+# "numpy==2.2.3",+# "treescope==0.1.9",+# ]+# ///++import marimo++__generated_with = "0.11.6"+app = marimo.App(width="medium")+++def _():+ import marimo as mo+ import treescope+ import numpy as np++ my_array = np.cos(np.arange(300).reshape((10,30)) * 0.2)+ figure = treescope.render_array(my_array)+ mo.iframe(figure._repr_html_())+ return figure, mo, my_array, np, treescope+++def _(figure):+ figure+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_output/formatters/test_formatters.py b/tests/_output/formatters/test_formatters.pyindex c1a449c74f..9efec01c7e 100644--- a/tests/_output/formatters/test_formatters.py+++ b/tests/_output/formatters/test_formatters.py@@ -189,6 +189,22 @@ def test_repr_html():assert content == "<h1>Hello, World!</h1>"+def test_repr_html_with_script_tag_without_src():+ class ReprHTMLWithScriptTagWithoutSrc:+ def _repr_html_(self):+ return "<script>alert('Hello, World!')</script>"++ obj = ReprHTMLWithScriptTagWithoutSrc()+ formatter = get_formatter(obj)+ assert formatter is not None+ mime, content = formatter(obj)+ assert mime == "text/html"+ assert (+ content+ == "<iframe srcdoc='<script>alert('Hello, World!')</script>' width='100%' height='400px' onload='__resizeIframe(this)' frameborder='0'></iframe>"+ )++def test_repr_png():png = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABaElEQVR42mNk"diff --git a/tests/_output/formatters/test_iframe.py b/tests/_output/formatters/test_iframe.pynew file mode 100644index 0000000000..efeeb3c5de--- /dev/null+++ b/tests/_output/formatters/test_iframe.py@@ -0,0 +1,53 @@+from __future__ import annotations++from marimo._output.formatters.iframe import (+ _has_script_tag_without_src,+ maybe_wrap_in_iframe,+)+++def test_maybe_wrap_in_iframe_no_script():+ html = "<div>Hello world</div>"+ assert maybe_wrap_in_iframe(html) == html+++def test_maybe_wrap_in_iframe_with_script_src():+ html = '<script src="foo.js"></script>'+ assert maybe_wrap_in_iframe(html) == html+++def test_maybe_wrap_in_iframe_with_inline_script():+ html = '<script>console.log("hello")</script>'+ assert (+ maybe_wrap_in_iframe(html)+ == "<iframe srcdoc='<script>console.log("hello")</script>' width='100%' height='400px' onload='__resizeIframe(this)' frameborder='0'></iframe>"+ )+++def test_has_script_tag_without_src_no_script():+ html = "<div>Hello world</div>"+ assert not _has_script_tag_without_src(html)+++def test_has_script_tag_without_src_with_src():+ html = '<script src="foo.js"></script>'+ assert not _has_script_tag_without_src(html)+++def test_has_script_tag_without_src_inline():+ html = '<script>console.log("hello")</script>'+ assert _has_script_tag_without_src(html)+++def test_has_script_tag_without_src_multiple():+ html = """+ <script src="foo.js"></script>+ <div>Some content</div>+ <script>console.log("hello")</script>+ """+ assert _has_script_tag_without_src(html)+++def test_has_script_tag_without_src_with_attributes():+ html = '<script type="text/javascript" defer>alert("hi")</script>'+ assert _has_script_tag_without_src(html)