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: mo.icon (#619)

Myles Scolnick7cf556eed89e
diff --git a/docs/api/markdown.md b/docs/api/markdown.md
index 308f1fecee..0df2c09d4a 100644
--- a/docs/api/markdown.md
+++ b/docs/api/markdown.md
@@ -7,3 +7,11 @@ elements.
```{eval-rst}
.. autofunction:: marimo.md
```
+
+## Icons
+
+You can render icons from [Iconify](https://icon-sets.iconify.design/) with `mo.icon`.
+
+```{eval-rst}
+.. autofunction:: marimo.icon
+```
diff --git a/frontend/package.json b/frontend/package.json
index 764d586c42..f3ae3a65d7 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -81,6 +81,7 @@
"html-react-parser": "^5.1.1",
"html-to-image": "^1.11.11",
"humanize-duration": "^3.31.0",
+ "iconify-icon": "^1.0.8",
"jotai": "^2.6.2",
"js-cookie": "^3.0.5",
"katex": "^0.16.9",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 45e451d61c..41482f1178 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -212,6 +212,9 @@ dependencies:
humanize-duration:
specifier: ^3.31.0
version: 3.31.0
+ iconify-icon:
+ specifier: ^1.0.8
+ version: 1.0.8
jotai:
specifier: ^2.6.2
version: 2.6.2(@types/[email protected])([email protected])
@@ -2932,6 +2935,10 @@ packages:
/@humanwhocodes/[email protected]:
resolution: {integrity: sha512-dvuCeX5fC9dXgJn9t+X5atfmgQAzUOWqS1254Gh0m6i8wKd10ebXkfNKiRK+1GWi/yTvvLDHpoxLr0xxxeslWw==}
+ /@iconify/[email protected]:
+ resolution: {integrity: sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==}
+ dev: false
+
resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==}
engines: {node: '>=12'}
@@ -11341,6 +11348,12 @@ packages:
resolution: {integrity: sha512-fRrehgBG26NNZysRlTq1S+HPtDpp3u+Jzdc/d5A4cEzOD86YLAkDaJyJg8krSdCi7CJ+s7ht3fwRj8Dl+Btd0w==}
dev: false
+ resolution: {integrity: sha512-jvbUKHXf8EnGGArmhlP2IG8VqQLFFyTvTqb9LVL2TKTh7/eCCD1o2HHE9thpbJJb6B8hzhcFb6rOKhvo7reNKA==}
+ dependencies:
+ '@iconify/types': 2.0.0
+ dev: false
+
resolution: {integrity: sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==}
engines: {node: '>=0.10.0'}
diff --git a/frontend/src/core/MarimoApp.tsx b/frontend/src/core/MarimoApp.tsx
index 0918c50486..795b4a09b0 100644
--- a/frontend/src/core/MarimoApp.tsx
+++ b/frontend/src/core/MarimoApp.tsx
@@ -1,5 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
import "../css/index.css";
+import "iconify-icon";
import { useEffect } from "react";
import { ErrorBoundary } from "../components/editor/boundary/ErrorBoundary";
diff --git a/marimo/__init__.py b/marimo/__init__.py
index e7e18fd0e6..d4486f34ed 100644
--- a/marimo/__init__.py
+++ b/marimo/__init__.py
@@ -27,6 +27,7 @@ __all__ = [
"download",
"hstack",
"Html",
+ "icon",
"image",
"left",
"md",
@@ -65,6 +66,7 @@ from marimo._plugins.stateless.audio import audio
from marimo._plugins.stateless.callout import callout
from marimo._plugins.stateless.download import download
from marimo._plugins.stateless.flex import hstack, vstack
+from marimo._plugins.stateless.icon import icon
from marimo._plugins.stateless.image import image
from marimo._plugins.stateless.mermaid import mermaid
from marimo._plugins.stateless.pdf import pdf
diff --git a/marimo/_output/builder.py b/marimo/_output/builder.py
index 0b33975eda..370731661a 100644
--- a/marimo/_output/builder.py
+++ b/marimo/_output/builder.py
@@ -11,7 +11,7 @@ class _HTMLBuilder:
[children] if isinstance(children, str) else children
)
- params: List[Tuple[str, str]] = []
+ params: List[Tuple[str, Union[str, None]]] = []
if style:
params.append(("style", style))
@@ -28,7 +28,7 @@ class _HTMLBuilder:
alt: Optional[str] = None,
style: Optional[str] = None,
) -> str:
- params: List[Tuple[str, str]] = []
+ params: List[Tuple[str, Union[str, None]]] = []
if src:
params.append(("src", src))
if alt:
@@ -50,7 +50,7 @@ class _HTMLBuilder:
loop: bool = False,
style: Optional[str] = None,
) -> str:
- params: List[Tuple[str, str]] = []
+ params: List[Tuple[str, Union[str, None]]] = []
if src:
params.append(("src", src))
if controls:
@@ -74,7 +74,7 @@ class _HTMLBuilder:
src: Optional[str] = None,
controls: bool = True,
) -> str:
- params: List[Tuple[str, str]] = []
+ params: List[Tuple[str, Union[str, None]]] = []
if src:
params.append(("src", src))
if controls:
@@ -92,7 +92,7 @@ class _HTMLBuilder:
height: Optional[str] = None,
style: Optional[str] = None,
) -> str:
- params: List[Tuple[str, str]] = []
+ params: List[Tuple[str, Union[str, None]]] = []
if src:
params.append(("src", src))
if width:
@@ -109,7 +109,7 @@ class _HTMLBuilder:
@staticmethod
def pre(child: str, style: Optional[str] = None) -> str:
- params: List[Tuple[str, str]] = []
+ params: List[Tuple[str, Union[str, None]]] = []
if style is not None:
params.append(("style", style))
@@ -118,8 +118,23 @@ class _HTMLBuilder:
else:
return f"<pre {_join_params(params)}>{child}</pre>"
+ @staticmethod
+ def component(
+ component_name: str,
+ params: List[Tuple[str, Union[str, None]]],
+ ) -> str:
+ if len(params) == 0:
+ return f"<{component_name}></{component_name}>"
+ else:
+ return (
+ f"<{component_name} {_join_params(params)}></{component_name}>"
+ )
+
+
+def _join_params(params: List[Tuple[str, Union[str, None]]]) -> str:
+ # Filter None
+ params = [(k, v) for k, v in params if v is not None]
-def _join_params(params: List[Tuple[str, str]]) -> str:
return " ".join([f"{k}='{v}'" if v != "" else f"{k}" for k, v in params])
diff --git a/marimo/_output/utils.py b/marimo/_output/utils.py
index 5ca79a0ba4..f9b964347b 100644
--- a/marimo/_output/utils.py
+++ b/marimo/_output/utils.py
@@ -1,7 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Dict, Union
+from typing import Optional, Union
def build_data_url(mimetype: str, data: bytes) -> str:
@@ -13,5 +13,10 @@ def flatten_string(text: str) -> str:
return "".join([line.strip() for line in text.split("\n")])
-def create_style(pairs: Dict[str, Union[str, int, float, None]]) -> str:
+def create_style(
+ pairs: dict[str, Union[str, int, float, None]]
+) -> Optional[str]:
+ if not pairs:
+ return None
+
return ";".join([f"{k}: {v}" for k, v in pairs.items() if v is not None])
diff --git a/marimo/_plugins/stateless/flex.py b/marimo/_plugins/stateless/flex.py
index f12693bc49..f0a65d16ac 100644
--- a/marimo/_plugins/stateless/flex.py
+++ b/marimo/_plugins/stateless/flex.py
@@ -48,7 +48,7 @@ def _flex(
}
)
- def create_style_for_item(idx: int) -> str:
+ def create_style_for_item(idx: int) -> Optional[str]:
if widths is None:
return ""
width = widths[idx]
diff --git a/marimo/_plugins/stateless/icon.py b/marimo/_plugins/stateless/icon.py
new file mode 100644
index 0000000000..1406fb854b
--- /dev/null
+++ b/marimo/_plugins/stateless/icon.py
@@ -0,0 +1,90 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Literal, Optional, Union
+
+from marimo._output.builder import h
+from marimo._output.hypertext import Html
+from marimo._output.rich_help import mddoc
+from marimo._output.utils import create_style
+
+
+@mddoc
+def icon(
+ icon_name: str,
+ *,
+ size: Optional[int] = None,
+ color: Optional[str] = None,
+ inline: bool = True,
+ flip: Optional[
+ Literal["horizontal", "vertical", "horizontal,vertical"]
+ ] = None,
+ rotate: Optional[Literal["90deg", "180deg", "270deg"]] = None,
+ style: Optional[dict[str, Union[str, int, float, None]]] = None,
+) -> Html:
+ """
+ Displays an icon. These icons are referenced by name from the
+ [Iconify](https://iconify.design/) library.
+
+ They are named in the format `icon-set:icon-name`, e.g.
+ `lucide:leaf`.
+
+ Icons are lazily loaded from a CDN, so they will not be loaded when
+ not connected to the internet.
+
+ These can be used in buttons, tabs, and other UI elements.
+
+ **Examples.**
+
+ ```python
+ mo.md(f"# {mo.icon('lucide:leaf')} Leaf")
+
+ mo.ui.button(
+ label=f"{mo.icon('lucide:rocket')} Submit",
+ )
+ ```
+
+ **Args.**
+
+ - `icon_name`: the name of the icon to display
+ - `size`: the size of the icon in pixels
+ - `color`: the color of the icon
+ - `inline`: whether to display the icon inline or as a block element
+ - `flip`: whether to flip the icon horizontally, vertically, or both
+ - `rotate`: whether to rotate the icon 90, 180, or 270 degrees
+ - `style`: a dictionary of CSS styles to apply to the icon
+
+ **Returns.**
+
+ - An `Html` object.
+ """
+
+ if style is None:
+ style = {}
+
+ if color is not None:
+ style["color"] = color
+
+ return Html(
+ h.component(
+ "iconify-icon",
+ [
+ ("icon", icon_name),
+ ("width", _space_to_string(size)),
+ ("height", _space_to_string(size)),
+ ("inline", "" if inline else None),
+ ("flip", flip),
+ ("rotate", rotate),
+ ("style", create_style(style)),
+ ],
+ )
+ )
+
+
+def _space_to_string(value: Union[str, int, float, None]) -> Optional[str]:
+ if value is None:
+ return None
+ if isinstance(value, str):
+ return value
+ else:
+ return f"{value}px"
diff --git a/marimo/_plugins/stateless/test_icon.py b/marimo/_plugins/stateless/test_icon.py
new file mode 100644
index 0000000000..37c2e2ed92
--- /dev/null
+++ b/marimo/_plugins/stateless/test_icon.py
@@ -0,0 +1,35 @@
+# Copyright 2024 Marimo. All rights reserved.
+
+from marimo._plugins.stateless.icon import icon
+
+
+def test_mo_icon() -> None:
+ assert (
+ icon("lucide:leaf").text
+ == "<iconify-icon icon='lucide:leaf' inline></iconify-icon>"
+ )
+
+ expected = (
+ "<iconify-icon icon='lucide:leaf' width='32px' height='32px' inline>"
+ + "</iconify-icon>"
+ )
+
+ assert icon("lucide:leaf", size=32).text == expected
+
+ expected = (
+ "<iconify-icon icon='lucide:leaf' inline style='color: red'>"
+ + "</iconify-icon>"
+ )
+ assert icon("lucide:leaf", color="red").text == expected
+
+ assert (
+ icon("lucide:leaf", inline=False).text
+ == "<iconify-icon icon='lucide:leaf'></iconify-icon>"
+ )
+
+ expected = (
+ "<iconify-icon icon='lucide:leaf' inline flip='horizontal'>"
+ + "</iconify-icon>"
+ )
+
+ assert icon("lucide:leaf", flip="horizontal").text == expected
diff --git a/marimo/_smoke_tests/icons.py b/marimo/_smoke_tests/icons.py
new file mode 100644
index 0000000000..ec543cf455
--- /dev/null
+++ b/marimo/_smoke_tests/icons.py
@@ -0,0 +1,118 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.1.79"
+app = marimo.App()
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+def __(mo):
+ mo.hstack(
+ [
+ mo.md("Icon sets"),
+ mo.icon("lucide:leaf", size=20),
+ mo.icon("material-symbols:rocket-launch", size=20),
+ mo.icon("ic:twotone-rocket-launch", size=20),
+ ],
+ justify="start",
+ )
+ return
+
+
+def __(mo):
+ mo.hstack(
+ [
+ mo.md("Color"),
+ mo.icon("lucide:leaf", size=20),
+ mo.icon("lucide:leaf", size=20, color="blue"),
+ mo.icon("lucide:leaf", size=20, color="tomato"),
+ mo.icon("lucide:leaf", size=20, color="green"),
+ mo.icon("lucide:leaf", size=20, color="navy"),
+ ],
+ justify="start",
+ )
+ return
+
+
+def __(mo):
+ mo.hstack(
+ [
+ mo.md("Flip"),
+ mo.icon("lucide:leaf", size=20),
+ mo.icon("lucide:leaf", size=20, flip="vertical"),
+ mo.icon("lucide:leaf", size=20, flip="horizontal"),
+ mo.icon("lucide:leaf", size=20, flip="vertical,horizontal"),
+ ],
+ justify="start",
+ )
+ return
+
+
+def __(mo):
+ mo.hstack(
+ [
+ mo.md("Rotate"),
+ mo.icon("lucide:leaf", size=20),
+ mo.icon("lucide:leaf", size=20, rotate="90deg"),
+ mo.icon("lucide:leaf", size=20, rotate="180deg"),
+ mo.icon("lucide:leaf", size=20, rotate="270deg"),
+ ],
+ justify="start",
+ )
+ return
+
+
+def __(mo):
+ mo.hstack(
+ [
+ mo.md("In buttons"),
+ mo.ui.button(
+ label=f"{mo.icon('material-symbols:rocket-launch')} Launch"
+ ),
+ mo.ui.button(
+ label=f"Clear {mo.icon('material-symbols:close-rounded')}"
+ ),
+ # Left and right
+ mo.ui.button(
+ label=f"{mo.icon('material-symbols:download')} Download {mo.icon('material-symbols:csv')}"
+ ),
+ ],
+ justify="start",
+ )
+ return
+
+
+def __(mo):
+ mo.md(
+ f"""
+ ## {mo.icon('material-symbols:edit')} Icons in markdown
+ """
+ )
+ return
+
+
+def __(mo):
+ mo.tabs(
+ {
+ f"{mo.icon('material-symbols:group')} Overview": mo.md("Tab 1"),
+ f"{mo.icon('material-symbols:group-add')} Add": mo.md("Tab 2"),
+ f"{mo.icon('material-symbols:group-remove')} Remove": mo.md("Tab 3"),
+ }
+ )
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_output/test_builder.py b/tests/_output/test_builder.py
index 1dd2d5c56b..cb76d79cb3 100644
--- a/tests/_output/test_builder.py
+++ b/tests/_output/test_builder.py
@@ -45,7 +45,19 @@ def test_pre() -> None:
def test_join_params() -> None:
assert (
- _join_params([("style", "color:red"), ("class", "myClass")])
- == "style='color:red' class='myClass'"
+ _join_params([("style", "color:red"), ("class", "my-class")])
+ == "style='color:red' class='my-class'"
)
assert _join_params([]) == ""
+
+
+def test_component() -> None:
+ assert (
+ h.component(
+ "my-comp",
+ [("style", "color:red"), ("class", "my-class")],
+ )
+ == "<my-comp style='color:red' class='my-class'></my-comp>"
+ )
+
+ assert h.component("my-comp", []) == "<my-comp></my-comp>"