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: handle more output mime types from islands (#2339)

Myles Scolnick3f905dd8ab64
diff --git a/marimo/_islands/island_generator.py b/marimo/_islands/island_generator.py
index fbe4f724b4..7cb8e5f699 100644
--- a/marimo/_islands/island_generator.py
+++ b/marimo/_islands/island_generator.py
@@ -10,9 +10,8 @@ from marimo._ast.app import App, InternalApp, _AppConfig
from marimo._ast.cell import Cell, CellConfig
from marimo._ast.compiler import compile_cell
from marimo._messaging.cell_output import CellOutput
-from marimo._output.formatting import as_html
+from marimo._output.formatting import as_html, mime_to_html
from marimo._output.utils import uri_encode_component
-from marimo._plugins.stateless.json_output import json_output
from marimo._plugins.ui import code_editor
from marimo._server.export import run_app_until_completion
from marimo._server.file_manager import AppFileManager
@@ -97,7 +96,11 @@ class MarimoIslandStub:
if not (display_code or display_output or is_reactive):
raise ValueError("You must include either code or output")
- output = handle_mimetypes(self.output) if self.output else None
+ output = (
+ mime_to_html(self.output.mimetype, self.output.data)
+ if self.output is not None
+ else None
+ )
# Specifying display_code=False will hide the code block, but still
# make it present for reactivity, unless reactivity is disabled.
@@ -513,19 +516,3 @@ class MarimoIslandGenerator:
def remove_empty_lines(text: str) -> str:
return "\n".join([line for line in text.split("\n") if line.strip() != ""])
-
-
-def handle_mimetypes(output: CellOutput) -> str:
- data = output.data
- if not isinstance(data, str):
- return f"{data}"
- mimetype = output.mimetype
- # Since raw data, without wrapping in an image tag, this is just a huge
- # blob.
- if mimetype.startswith("image/"):
- data = f"<img src='{data}'/>"
- elif mimetype == "application/json":
- data = f"{json_output(json.loads(data))}"
- # TODO: Errors are displayed as just json strings until reactivity kicks
- # in. Ideally, handle application/vnd.marimo+error
- return data
diff --git a/marimo/_output/formatting.py b/marimo/_output/formatting.py
index 6ace9de695..748a930a3f 100644
--- a/marimo/_output/formatting.py
+++ b/marimo/_output/formatting.py
@@ -326,6 +326,10 @@ def as_html(value: object) -> Html:
return Html(f"<span>{escape(str(value))}</span>")
mimetype, data = formatter(value)
+ return mime_to_html(mimetype, data)
+
+
+def mime_to_html(mimetype: KnownMimeType, data: Any) -> Html:
if mimetype == "text/html":
# Using `as_html` to embed multiline HTML content
# into a multiline markdown string can break Python markdown's
diff --git a/tests/_islands/snapshots/island-mimetypes.txt b/tests/_islands/snapshots/island-mimetypes.txt
new file mode 100644
index 0000000000..6658ef58cb
--- /dev/null
+++ b/tests/_islands/snapshots/island-mimetypes.txt
@@ -0,0 +1,40 @@
+<marimo-island
+ data-app-id="main"
+ data-cell-id="MJUe"
+ data-reactive="true"
+>
+ <marimo-cell-output>
+ <span class="markdown prose dark:prose-invert"><span class="paragraph">Hello, islands!</span></span>
+ </marimo-cell-output>
+ <marimo-cell-code hidden>mo.md('Hello%2C%20islands!')</marimo-cell-code>
+</marimo-island>
+<marimo-island
+ data-app-id="main"
+ data-cell-id="vblA"
+ data-reactive="true"
+>
+ <marimo-cell-output>
+ <img src='https://example.com/image.png' />
+ </marimo-cell-output>
+ <marimo-cell-code hidden>mo.image('https%3A%2F%2Fexample.com%2Fimage.png')</marimo-cell-code>
+</marimo-island>
+<marimo-island
+ data-app-id="main"
+ data-cell-id="bkHC"
+ data-reactive="true"
+>
+ <marimo-cell-output>
+ <marimo-json-output data-json-data='{&quot;key&quot;: &quot;text/plain:&#92;&quot;value&#92;&quot;&quot;}'></marimo-json-output>
+ </marimo-cell-output>
+ <marimo-cell-code hidden>%7B'key'%3A%20'value'%7D</marimo-cell-code>
+</marimo-island>
+<marimo-island
+ data-app-id="main"
+ data-cell-id="lEQa"
+ data-reactive="true"
+>
+ <marimo-cell-output>
+ <marimo-json-output data-json-data='[&quot;text/plain:1&quot;, &quot;text/html:&lt;span class=&#92;&quot;markdown prose dark:prose-invert&#92;&quot;&gt;&lt;span class=&#92;&quot;paragraph&#92;&quot;&gt;Hello&lt;/span&gt;&lt;/span&gt;&quot;]'></marimo-json-output>
+ </marimo-cell-output>
+ <marimo-cell-code hidden>%5B1%2C%20mo.md('Hello')%5D</marimo-cell-code>
+</marimo-island>
\ No newline at end of file
diff --git a/tests/_islands/test_island_generator.py b/tests/_islands/test_island_generator.py
index a781f5ded8..8da94ca350 100644
--- a/tests/_islands/test_island_generator.py
+++ b/tests/_islands/test_island_generator.py
@@ -5,9 +5,7 @@ import pytest
from marimo import __version__
from marimo._islands.island_generator import (
MarimoIslandGenerator,
- handle_mimetypes,
)
-from marimo._messaging.cell_output import CellChannel, CellOutput
from tests.mocks import snapshotter
snapshot = snapshotter(__file__)
@@ -39,6 +37,11 @@ async def test_render():
generator = MarimoIslandGenerator()
block1 = generator.add_code("import marimo as mo")
block2 = generator.add_code("mo.md('Hello, islands!')")
+ imageBlock = generator.add_code(
+ "mo.image('https://example.com/image.png')"
+ )
+ jsonBlock = generator.add_code("{'key': 'value'}")
+ arrayBlock = generator.add_code("[1, mo.md('Hello')]")
await generator.build()
@@ -55,6 +58,18 @@ async def test_render():
snapshot("island-no-output.txt", block2.render(display_output=False))
+ snapshot(
+ "island-mimetypes.txt",
+ "\n".join(
+ [
+ block2.render(display_code=False),
+ imageBlock.render(display_code=False),
+ jsonBlock.render(display_code=False),
+ arrayBlock.render(display_code=False),
+ ]
+ ),
+ )
+
async def test_render_head():
generator = MarimoIslandGenerator()
@@ -65,21 +80,3 @@ async def test_render_head():
snapshot(
"header.txt", generator.render_head().replace(__version__, "0.0.0")
)
-
-
-async def test_handle_image_mimetype():
- small_image = CellOutput(
- data="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",
- mimetype="image/gif",
- channel=CellChannel.OUTPUT,
- )
- assert handle_mimetypes(small_image).startswith("<img")
-
-
-async def test_handle_json_mimetype():
- small_image = CellOutput(
- data="[1, 2, 3]",
- mimetype="application/json",
- channel=CellChannel.OUTPUT,
- )
- assert handle_mimetypes(small_image).startswith("<marimo-json")