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: restore Altair SVG output as base64-encoded Data URLs (#9104)

Daizu30cf0a595660
diff --git a/marimo/_output/formatters/altair_formatters.py b/marimo/_output/formatters/altair_formatters.py
index bac5dbd23f..85ec30c0cb 100644
--- a/marimo/_output/formatters/altair_formatters.py
+++ b/marimo/_output/formatters/altair_formatters.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import json
+import re
from typing import Any
from urllib.request import urlopen
@@ -80,6 +81,14 @@ class AltairFormatter(FormatterFactory):
data_url = io_to_data_url(mime_response, mime_type)
return (mime_type, data_url or "")
if isinstance(mime_response, str):
+ if (
+ mime_type == "image/svg+xml"
+ and not altair.renderers.options.get("raw_svg")
+ ):
+ _maybe_warn_external_resources(mime_response)
+ svg_bytes = mime_response.encode()
+ data_url = io_to_data_url(svg_bytes, mime_type)
+ return (mime_type, data_url or "")
return mime_type, mime_response
return mime_type, json.dumps(mime_response)
@@ -128,6 +137,25 @@ def _format_png_mimebundle(
return "application/vnd.marimo+mimebundle", json.dumps(mimebundle)
+# Check if the SVG contains external resources that may not render
+# correctly when encoded as a Data URL.
+# https://github.com/marimo-team/marimo/pull/9104
+def _maybe_warn_external_resources(svg: str) -> None:
+ # Strictly detecting external resource usage in SVG is difficult;
+ # as a heuristic, we check for 'href' or 'xlink:href' attributes
+ # that point to external resources (ignoring internal '#' or 'data:' URLs).
+ if re.search(
+ r'<[^>]*\b(?:xlink:)?href\s*=\s*["\'](?!\s*(?:#|data:))[^"\']+', svg
+ ):
+ msg = (
+ "This SVG contains external resources (href/xlink:href) "
+ "that may not render correctly when encoded as a Data URL. "
+ "If images are missing, try enabling raw SVG rendering with: "
+ "altair.renderers.enable('svg', raw_svg=True)."
+ )
+ LOGGER.warning(msg)
+
+
# This is only needed since it seems that altair does not
# handle this internally.
# https://github.com/marimo-team/marimo/issues/2302
diff --git a/marimo/_smoke_tests/altair_examples/altair_svg_rendering.py b/marimo/_smoke_tests/altair_examples/altair_svg_rendering.py
index 4e33a85830..cc2e166a6d 100644
--- a/marimo/_smoke_tests/altair_examples/altair_svg_rendering.py
+++ b/marimo/_smoke_tests/altair_examples/altair_svg_rendering.py
@@ -12,7 +12,7 @@
import marimo
-__generated_with = "0.22.0"
+__generated_with = "0.23.1"
app = marimo.App(width="medium")
with app.setup:
@@ -20,6 +20,9 @@ with app.setup:
import altair as alt
import pandas as pd
+ # Verify vl-convert-python is installed; it's required for the SVG renderer.
+ import vl_convert as vlc
+
@app.cell
def _():
@@ -29,7 +32,6 @@ def _():
@app.cell
def _(data):
- # Issue #9015: SVG charts in layouts render raw base64 string
alt.renderers.enable("svg")
chart = alt.Chart(data).mark_point().encode(x="x", y="y")
@@ -45,8 +47,10 @@ def _(chart):
@app.cell
def _(chart):
- # This renders the raw base64-encoded string (issue #9015)
- mo.vstack([chart])
+ # SVG outputs should be correctly rendered in vstack or hstack
+ # (reported in Issue #9015 and fixed in PR #9043).
+ # For vstack, align="start" is needed to preserve the image size
+ mo.vstack([chart], align="start")
return
@@ -78,7 +82,10 @@ def _(chart_with_images):
@app.cell
def _(chart_with_images):
- # Image marks should not be broken
+ # Image marks are broken.
+ # The root cause is the browser's security restriction.
+ # When marimo detects an SVG with external resources (e.g., image URLs),
+ # it warns the user to enable 'raw_svg=True' for correct rendering.
alt.renderers.enable("svg")
chart_with_images
return
@@ -86,9 +93,9 @@ def _(chart_with_images):
@app.cell
def _(chart_with_images):
- # Image marks should not be broken
- alt.renderers.enable("svg")
- mo.hstack([chart_with_images])
+ # Image marks are correctly rendered when 'raw_svg=True' is enabled.
+ alt.renderers.enable("svg", raw_svg=True)
+ chart_with_images
return
diff --git a/tests/_output/formatters/test_altair_formatters.py b/tests/_output/formatters/test_altair_formatters.py
index 4e686eb5a1..4ae38098a5 100644
--- a/tests/_output/formatters/test_altair_formatters.py
+++ b/tests/_output/formatters/test_altair_formatters.py
@@ -13,6 +13,7 @@ from marimo._output.formatters.altair_formatters import (
FORMAT_LOCALE_URL,
TIME_FORMAT_LOCALE_URL,
AltairFormatter,
+ _maybe_warn_external_resources,
)
from marimo._output.formatters.formatters import register_formatters
from marimo._output.formatting import get_formatter
@@ -157,24 +158,34 @@ def test_altair_formatter_mimebundle():
@pytest.mark.skipif(not HAS_DEPS, reason="altair not installed")
-def test_altair_formatter_svg():
+ ("raw_svg", "expected"),
+ [
+ (True, "<svg></svg>"),
+ (False, "data:image/svg+xml;base64,PHN2Zz48L3N2Zz4="),
+ ],
+)
+def test_altair_formatter_svg(raw_svg: bool, expected: str):
AltairFormatter().register()
import altair as alt
# Create a mock chart with a _repr_mimebundle_ method that returns SVG
mock_chart = alt.Chart(get_data()).mark_point()
- with patch.object(
- alt.Chart,
- "_repr_mimebundle_",
- return_value={"image/svg+xml": "<svg></svg>"},
+ with (
+ patch.dict(alt.renderers.options, {"raw_svg": raw_svg}),
+ patch.object(
+ alt.Chart,
+ "_repr_mimebundle_",
+ return_value={"image/svg+xml": "<svg></svg>"},
+ ),
):
formatter = get_formatter(mock_chart)
assert formatter is not None
mime, content = formatter(mock_chart)
assert mime == "image/svg+xml"
- assert content == "<svg></svg>"
+ assert content == expected
@pytest.mark.skipif(not HAS_DEPS, reason="altair not installed")
@@ -286,3 +297,25 @@ def test_altair_formatter_embed_options():
alt.renderers.set_embed_options()
content = get_formatted_content(get_chart())
assert content["usermeta"]["embedOptions"] == {}
+
+
+ ("content", "expected"),
+ [
+ ('<image xlink:href="https://ffox.png"/>', True),
+ ('<image href="#id"/>', False),
+ ('<image href="data:image/png;base64,xxx"/>', False),
+ ('<image href=" https://ffox.png"/>', True),
+ ('<image href=" #id"/>', False),
+ ],
+)
+def test_maybe_warn_external_resource(content: str, expected: bool) -> None:
+ with patch(
+ "marimo._output.formatters.altair_formatters.LOGGER.warning"
+ ) as mock_warning:
+ _maybe_warn_external_resources(content)
+ if expected:
+ mock_warning.assert_called_once()
+ assert "raw_svg=True" in mock_warning.call_args[0][0]
+ else:
+ mock_warning.assert_not_called()