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: allow .style() to take kwargs, add tests (#2380)

Myles Scolnicke33707989c2c
diff --git a/marimo/_output/formatting.py b/marimo/_output/formatting.py
index 748a930a3f..347f0f6fea 100644
--- a/marimo/_output/formatting.py
+++ b/marimo/_output/formatting.py
@@ -329,6 +329,17 @@ def as_html(value: object) -> Html:
return mime_to_html(mimetype, data)
+def as_dom_node(value: object) -> Html:
+ """
+ Similar to as_html, but allows for string, int, float, and bool values
+ to be passed through without being wrapped in an Html object.
+ """
+ if isinstance(value, (str, int, float, bool)):
+ return Html(escape(str(value)))
+
+ return as_html(value)
+
+
def mime_to_html(mimetype: KnownMimeType, data: Any) -> Html:
if mimetype == "text/html":
# Using `as_html` to embed multiline HTML content
diff --git a/marimo/_output/hypertext.py b/marimo/_output/hypertext.py
index bc9054bbec..d961c7cd0a 100644
--- a/marimo/_output/hypertext.py
+++ b/marimo/_output/hypertext.py
@@ -2,7 +2,7 @@
from __future__ import annotations
import weakref
-from typing import TYPE_CHECKING, Any, Literal, final
+from typing import TYPE_CHECKING, Any, Literal, Optional, final
from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.mime import MIME
@@ -236,22 +236,26 @@ class Html(MIME):
return _callout(self, kind=kind)
@mddoc
- def style(self, style: dict[str, Any]) -> Html:
+ def style(
+ self, style: Optional[dict[str, Any]] = None, **kwargs: Any
+ ) -> Html:
"""Wrap an object in a styled container.
**Example.**
```python
mo.md("...").style({"max-height": "300px", "overflow": "auto"})
+ mo.md("...").style(max_height="300px", overflow="auto")
```
**Args.**
- - `styles`: a dict of CSS styles, keyed by property name
+ - `style`: an optional dict of CSS styles, keyed by property name
+ - `**kwargs`: CSS styles as keyword arguments
"""
from marimo._plugins.stateless import style as _style
- return _style.style(self, style)
+ return _style.style(self, style=style, **kwargs)
def _js(text: str) -> Html:
diff --git a/marimo/_plugins/stateless/style.py b/marimo/_plugins/stateless/style.py
index 7629bcb58a..663df9b9d9 100644
--- a/marimo/_plugins/stateless/style.py
+++ b/marimo/_plugins/stateless/style.py
@@ -1,28 +1,43 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Any
+from typing import Any, Optional
from marimo._output.builder import h
-from marimo._output.formatting import as_html
+from marimo._output.formatting import as_dom_node
from marimo._output.hypertext import Html
from marimo._output.rich_help import mddoc
@mddoc
-def style(item: object, styles: dict[str, Any]) -> Html:
+def style(
+ item: object, style: Optional[dict[str, Any]] = None, **kwargs: Any
+) -> Html:
"""Wrap an object in a styled container.
**Example.**
```python
mo.style(item, styles={"max-height": "300px", "overflow": "auto"})
+ mo.style(item, max_height="300px", overflow="auto")
```
**Args.**
- `item`: an object to render as HTML
- - `styles`: a dict of CSS styles, keyed by property name
+ - `styles`: a optional dict of CSS styles, keyed by property name
+ - `**kwargs`: additional CSS styles
"""
- style_str = ";".join([f"{key}:{value}" for key, value in styles.items()])
- return Html(h.div(children=as_html(item).text, style=style_str))
+ # Initialize combined_style with style dict if provided,
+ # otherwise empty dict
+ combined_style = style or {}
+
+ # Add kwargs to combined_style, converting snake_case to kebab-case
+ for key, value in kwargs.items():
+ kebab_key = key.replace("_", "-")
+ combined_style[kebab_key] = value
+
+ style_str = ";".join(
+ [f"{key}:{value}" for key, value in combined_style.items()]
+ )
+ return Html(h.div(children=as_dom_node(item).text, style=style_str))
diff --git a/tests/_output/formatters/test_formatters.py b/tests/_output/formatters/test_formatters.py
index 0606c40945..d738cb65f2 100644
--- a/tests/_output/formatters/test_formatters.py
+++ b/tests/_output/formatters/test_formatters.py
@@ -13,6 +13,7 @@ from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.formatters.formatters import register_formatters
from marimo._output.formatting import (
Plain,
+ as_dom_node,
as_html,
formatter,
get_formatter,
@@ -329,3 +330,13 @@ def test_repr_empty_string():
mime, content = formatter(obj)
assert mime == "application/json"
assert content == ""
+
+
+def test_as_dom_node():
+ assert as_dom_node("test").text == "test"
+ assert as_dom_node(123).text == "123"
+ assert as_dom_node(123.456).text == "123.456"
+ assert as_dom_node(None).text == "<span>None</span>"
+ assert as_dom_node(True).text == "True"
+ assert as_dom_node(False).text == "False"
+ assert as_dom_node({"key": "value"}).text.startswith("<marimo-json")
diff --git a/tests/_output/test_hypertext.py b/tests/_output/test_hypertext.py
new file mode 100644
index 0000000000..af858a84c4
--- /dev/null
+++ b/tests/_output/test_hypertext.py
@@ -0,0 +1,123 @@
+from __future__ import annotations
+
+from marimo._output.hypertext import Html, _js
+from marimo._plugins.ui._impl.batch import batch as batch_plugin
+from marimo._plugins.ui._impl.input import button
+
+
+def test_html_initialization():
+ html = Html("<p>Hello, World!</p>")
+ assert html.text == "<p>Hello, World!</p>"
+
+
+def test_html_mime():
+ html = Html("<p>Test</p>")
+ mime_type, content = html._mime_()
+ assert mime_type == "text/html"
+ assert content == "<p>Test</p>"
+
+
+def test_html_format():
+ html = Html("<p>\n Hello\n</p>")
+ assert f"{html}" == "<p>Hello</p>"
+
+
+def test_html_batch():
+ html = Html("Name: {name}")
+ batched = html.batch(name=button())
+ assert isinstance(batched, batch_plugin)
+
+
+def test_html_center():
+ html = Html("<p>Centered</p>")
+ centered = html.center()
+ assert "justify-content: center" in centered.text
+
+
+def test_html_right():
+ html = Html("<p>Right</p>")
+ right_aligned = html.right()
+ assert "justify-content: flex-end" in right_aligned.text
+
+
+def test_html_left():
+ html = Html("<p>Left</p>")
+ left_aligned = html.left()
+ assert "justify-content: flex-start" in left_aligned.text
+
+
+def test_html_callout():
+ html = Html("<p>Important</p>")
+ callout = html.callout(kind="warn")
+ assert "marimo-callout" in callout.text
+ assert "warn" in callout.text
+
+
+def test_html_style():
+ html = Html("<p>Styled</p>")
+ styled = html.style({"color": "red", "font-size": "16px"})
+ assert "style=" in styled.text
+ assert "color:red" in styled.text
+ assert "font-size:16px" in styled.text
+
+
+def test_js():
+ js_html = _js("console.log('Hello');")
+ assert js_html.text == "<script>console.log('Hello');</script>"
+
+
+# Add more tests as needed for edge cases and other functionalities
+
+
+def test_html_empty():
+ html = Html("")
+ assert html.text == ""
+
+
+def test_html_with_special_characters():
+ html = Html("<p>Hello & World</p>")
+ assert html.text == "<p>Hello & World</p>"
+
+
+def test_html_nested_elements():
+ html = Html("<div><p>Nested</p></div>")
+ assert html.text == "<div><p>Nested</p></div>"
+
+
+def test_html_multiple_elements():
+ html = Html("<p>First</p><p>Second</p>")
+ assert html.text == "<p>First</p><p>Second</p>"
+
+
+def test_html_with_attributes():
+ html = Html('<a href="https://example.com">Link</a>')
+ assert html.text == '<a href="https://example.com">Link</a>'
+
+
+def test_html_batch_multiple_inputs():
+ html = Html("Name: {name}, Age: {age}")
+ batched = html.batch(name=button(), age=button())
+ assert isinstance(batched, batch_plugin)
+
+
+def test_html_style_empty_dict():
+ html = Html("<p>No Style</p>")
+ styled = html.style({})
+ assert styled.text == "<div><p>No Style</p></div>"
+
+
+def test_js_empty():
+ js_html = _js("")
+ assert js_html.text == "<script></script>"
+
+
+def test_js_multiple_lines():
+ js_code = """
+ console.log('Line 1');
+ console.log('Line 2');
+ """
+ js_html = _js(js_code)
+ assert "<script>" in js_html.text
+ assert "console.log('Line 1');" in js_html.text
+ assert "console.log('Line 2');" in js_html.text
+ assert "</script>" in js_html.text
diff --git a/tests/_plugins/stateless/test_style.py b/tests/_plugins/stateless/test_style.py
new file mode 100644
index 0000000000..6f43270b32
--- /dev/null
+++ b/tests/_plugins/stateless/test_style.py
@@ -0,0 +1,59 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from marimo._output.hypertext import Html
+from marimo._plugins.stateless.style import style
+
+
+def test_style_with_dict():
+ result = style("Test content", style={"color": "red", "font-size": "16px"})
+ assert isinstance(result, Html)
+ assert (
+ result.text
+ == "<div style='color:red;font-size:16px'>Test content</div>"
+ )
+
+
+def test_style_with_kwargs():
+ result = style("Test content", color="blue", font_weight="bold")
+ assert isinstance(result, Html)
+ assert (
+ result.text
+ == "<div style='color:blue;font-weight:bold'>Test content</div>"
+ )
+
+
+def test_style_with_dict_and_kwargs():
+ result = style("Test content", style={"color": "green"}, font_size="20px")
+ assert isinstance(result, Html)
+ assert (
+ result.text
+ == "<div style='color:green;font-size:20px'>Test content</div>"
+ )
+
+
+def test_style_with_snake_case_conversion():
+ result = style("Test content", background_color="#f0f0f0")
+ assert isinstance(result, Html)
+ assert (
+ result.text
+ == "<div style='background-color:#f0f0f0'>Test content</div>"
+ )
+
+
+def test_style_with_empty_input():
+ result = style("")
+ assert isinstance(result, Html)
+ assert result.text == "<div></div>"
+
+
+def test_style_with_non_string_input():
+ result = style(123)
+ assert isinstance(result, Html)
+ assert result.text == "<div>123</div>"
+
+
+def test_style_overwrite_dict_with_kwargs():
+ result = style("Test content", style={"color": "red"}, color="blue")
+ assert isinstance(result, Html)
+ assert result.text == "<div style='color:blue'>Test content</div>"