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: allow non-pixels for mo.image, mo.video (#2956)
Myles Scolnicka8bfb7450724
diff --git a/marimo/_output/utils.py b/marimo/_output/utils.pyindex 65f7976ab5..e546c38529 100644--- a/marimo/_output/utils.py+++ b/marimo/_output/utils.py@@ -30,3 +30,25 @@ def create_style(def uri_encode_component(code: str) -> str:"""Equivalent to `encodeURIComponent` in JavaScript."""return urllib.parse.quote(code, safe="~()*!.'")+++def normalize_dimension(value: Union[int, float, str, None]) -> Optional[str]:+ """Normalize dimension value to CSS string.++ Handles:+ - Integers (converted to px)+ - Strings (passed through if they have units, converted to px if just number)+ - None (returns None)+ """+ if value is None:+ return None+ if isinstance(value, int):+ return f"{value}px"+ if isinstance(value, float):+ return f"{value}px"+ if isinstance(value, str):+ # If string is just a number, treat as percentage+ if value.isdigit():+ return f"{value}px"+ return value+ raise ValueError(f"Invalid dimension value: {value}")diff --git a/marimo/_plugins/stateless/image.py b/marimo/_plugins/stateless/image.pyindex d0f98384a0..ceaf689dec 100644--- a/marimo/_plugins/stateless/image.py+++ b/marimo/_plugins/stateless/image.py@@ -10,7 +10,7 @@ from marimo._dependencies.dependencies import DependencyManagerfrom marimo._output.builder import hfrom marimo._output.hypertext import Htmlfrom marimo._output.rich_help import mddoc-from marimo._output.utils import create_style+from marimo._output.utils import create_style, normalize_dimensionfrom marimo._plugins.core.media import io_to_data_urlImage = Union[str, bytes, io.BytesIO, io.BufferedReader]@@ -89,8 +89,8 @@ def _normalize_image(src: ImageLike) -> Image:def image(src: ImageLike,alt: Optional[str] = None,- width: Optional[int] = None,- height: Optional[int] = None,+ width: Optional[Union[int, str]] = None,+ height: Optional[Union[int, str]] = None,rounded: bool = False,style: Optional[dict[str, Any]] = None,caption: Optional[str] = None,@@ -121,8 +121,8 @@ def image(- `src`: a path or URL to an image, a file-like object(opened in binary mode), or array-like object.- `alt`: the alt text of the image- - `width`: the width of the image in pixels- - `height`: the height of the image in pixels+ - `width`: the width of the image in pixels or a string with units+ - `height`: the height of the image in pixels or a string with units- `rounded`: whether to round the corners of the image- `style`: a dictionary of CSS styles to apply to the image- `caption`: the caption of the image@@ -154,8 +154,8 @@ def image(styles = create_style({- "width": f"{width}px" if width is not None else None,- "height": f"{height}px" if height is not None else None,+ "width": normalize_dimension(width),+ "height": normalize_dimension(height),"border-radius": "4px" if rounded else None,**(style or {}),}diff --git a/marimo/_plugins/stateless/video.py b/marimo/_plugins/stateless/video.pyindex e08a6f59da..b6b1395165 100644--- a/marimo/_plugins/stateless/video.py+++ b/marimo/_plugins/stateless/video.py@@ -7,7 +7,7 @@ from typing import Optional, Unionfrom marimo._output.builder import hfrom marimo._output.hypertext import Htmlfrom marimo._output.rich_help import mddoc-from marimo._output.utils import create_style+from marimo._output.utils import create_style, normalize_dimensionfrom marimo._plugins.core.media import io_to_data_url@@ -18,8 +18,8 @@ def video(muted: bool = False,autoplay: bool = False,loop: bool = False,- width: Optional[int] = None,- height: Optional[int] = None,+ width: Optional[Union[int, str]] = None,+ height: Optional[Union[int, str]] = None,rounded: bool = False,) -> Html:"""Render an video as HTML.@@ -41,8 +41,8 @@ def video(- `autoplay`: whether to autoplay the video.the video will only autoplay if `muted` is `True`- `loop`: whether to loop the video- - `width`: the width of the video- - `height`: the height of the video+ - `width`: the width of the video in pixels or a string with units+ - `height`: the height of the video in pixels or a string with units- `rounded`: whether to round the corners of the video**Returns.**@@ -57,8 +57,8 @@ def video(resolved_src = io_to_data_url(src, fallback_mime_type="video/mp4")styles = create_style({- "width": f"{width}px" if width is not None else None,- "height": f"{height}px" if height is not None else None,+ "width": normalize_dimension(width),+ "height": normalize_dimension(height),"border-radius": "4px" if rounded else None,})diff --git a/tests/_output/test_output_utils.py b/tests/_output/test_output_utils.pynew file mode 100644index 0000000000..d886ecf335--- /dev/null+++ b/tests/_output/test_output_utils.py@@ -0,0 +1,72 @@+from __future__ import annotations++import base64+from typing import cast++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+ world+ """+ assert utils.flatten_string(text) == "helloworld"+++def test_create_style() -> None:+ # Empty dict returns None+ assert utils.create_style({}) is None++ # Basic key-value pairs+ style = utils.create_style({"color": "red", "width": "100px"})+ assert style == "color: red;width: 100px"++ # None values are filtered out+ style = utils.create_style({"color": "red", "width": None})+ assert style == "color: red"++ # Numeric values+ style = utils.create_style({"width": 100, "height": 50.5})+ assert style == "width: 100;height: 50.5"+++def test_uri_encode_component() -> None:+ # Test basic string+ assert utils.uri_encode_component("hello world") == "hello%20world"++ # Test special characters+ assert utils.uri_encode_component("!@#$%^&*()") == "!%40%23%24%25%5E%26*()"++ # Test safe characters+ assert utils.uri_encode_component("~.!'()") == "~.!'()"+++def test_normalize_dimension() -> None:+ # Test None+ assert utils.normalize_dimension(None) is None++ # Test integers+ assert utils.normalize_dimension(100) == "100px"++ # Test floats+ assert utils.normalize_dimension(50.5) == "50.5px"++ # Test strings with units+ assert utils.normalize_dimension("100%") == "100%"+ assert utils.normalize_dimension("50vh") == "50vh"++ # Test numeric strings+ assert utils.normalize_dimension("100") == "100px"++ # Test invalid input+ with pytest.raises(ValueError):+ utils.normalize_dimension(cast(str, ["invalid"]))