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.

Add anywidget formatter (#906)

Myles Scolnickddee048d2420
diff --git a/docs/api/inputs/anywidget.md b/docs/api/inputs/anywidget.md
new file mode 100644
index 0000000000..ede818fbe7
--- /dev/null
+++ b/docs/api/inputs/anywidget.md
@@ -0,0 +1,72 @@
+# AnyWidget
+
+[AnyWidget](https://anywidget.dev/) is a Python library and specification for creating custom Jupyter-compatible widgets. marimo supports AnyWidget, allowing you to import AnyWidget widgets or create your own custom widgets and use them in your notebooks and apps.
+
+## Custom widget
+
+```python
+import anywidget
+import traitlets
+import marimo as mo
+
+class CounterWidget(anywidget.AnyWidget):
+ # Widget front-end JavaScript code
+ _esm = """
+ function render({ model, el }) {
+ let getCount = () => model.get("count");
+ let button = document.createElement("button");
+ button.innerHTML = `count is ${getCount()}`;
+ button.addEventListener("click", () => {
+ model.set("count", getCount() + 1);
+ model.save_changes();
+ });
+ model.on("change:count", () => {
+ button.innerHTML = `count is ${getCount()}`;
+ });
+ el.appendChild(button);
+ }
+ export default { render };
+ """
+ _css = """
+ button {
+ padding: 5px !important;
+ border-radius: 5px !important;
+ background-color: #f0f0f0 !important;
+
+ &:hover {
+ background-color: lightblue !important;
+ color: white !important;
+ }
+ }
+ """
+
+ # Stateful property that can be accessed by JavaScript & Python
+ count = traitlets.Int(0).tag(sync=True)
+
+widget = mo.ui.anywidget(CounterWidget())
+
+
+# In another cell, you can access the widget's value
+widget.value
+```
+
+## Importing a widget
+
+```python
+# pip install drawdata
+from drawdata import ScatterWidget
+
+widget mo.ui.anywidget(ScatterWidget())
+
+# In another cell, you can access the widget's value
+widget.value
+```
+
+---
+
+```{eval-rst}
+.. autoclass:: marimo._plugins.ui._impl.from_anywidget._anywidget
+ :members:
+
+ .. autoclasstoc:: marimo._plugins.ui._impl.from_anywidget._anywidget
+```
diff --git a/docs/api/inputs/index.md b/docs/api/inputs/index.md
index 5be5ec8911..0bd41c0c0f 100644
--- a/docs/api/inputs/index.md
+++ b/docs/api/inputs/index.md
@@ -28,6 +28,7 @@
tabs
text
text_area
+ anywidget
```
marimo comes packaged with interactive UI elements that you can use to build
@@ -76,4 +77,5 @@ automatically run with the element's latest value.
marimo.ui.altair_chart
marimo.ui.plotly
marimo.mpl.interactive
+ marimo.ui.anywidget
```
diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
new file mode 100644
index 0000000000..299adbef59
--- /dev/null
+++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
@@ -0,0 +1,153 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+/* eslint-disable @typescript-eslint/no-explicit-any */
+import { z } from "zod";
+
+import { IPlugin, IPluginProps } from "@/plugins/types";
+import { useEffect, useRef } from "react";
+import { useAsyncData } from "@/hooks/useAsyncData";
+import { dequal } from "dequal";
+import { useOnMount } from "@/hooks/useLifecycle";
+import { useDeepCompareMemoize } from "@/hooks/useDeepCompareMemoize";
+import { ErrorBanner } from "../common/error-banner";
+
+interface Data {
+ jsUrl: string;
+ css?: string | null;
+}
+
+type T = Record<string, any>;
+
+export class AnyWidgetPlugin implements IPlugin<T, Data> {
+ tagName = "marimo-anywidget";
+
+ validator = z.object({
+ jsUrl: z.string(),
+ css: z.string().nullish(),
+ });
+
+ render(props: IPluginProps<T, Data>): JSX.Element {
+ return <AnyWidgetSlot {...props} />;
+ }
+}
+
+const AnyWidgetSlot = (props: IPluginProps<T, Data>) => {
+ const { css, jsUrl } = props.data;
+ // JS is an ESM file with a render function on it
+ // export function render({ model, el }) {
+ // ...
+ const {
+ data: module,
+ loading,
+ error,
+ } = useAsyncData(async () => {
+ const baseUrl = document.baseURI;
+ const url = new URL(jsUrl, baseUrl).toString();
+ return await import(url);
+ }, []);
+
+ // Mount the CSS
+ useEffect(() => {
+ if (!css || !props.host.shadowRoot) {
+ return;
+ }
+ const style = document.createElement("style");
+ style.innerHTML = css;
+ props.host.shadowRoot.append(style);
+ return () => {
+ style.remove();
+ };
+ }, [css, props.host]);
+
+ if (error) {
+ return <ErrorBanner error={error} />;
+ }
+
+ if (!module || loading) {
+ return null;
+ }
+
+ if (!module.default.render) {
+ const error = new Error(
+ `Module at ${jsUrl} does not have a default export with a render function`,
+ );
+ return <ErrorBanner error={error} />;
+ }
+
+ return <LoadedSlot {...props} render={module.default.render} />;
+};
+
+const LoadedSlot = ({
+ value,
+ setValue,
+ render,
+}: IPluginProps<T, Data> & {
+ render: ({ model, el }: any) => void;
+}) => {
+ const ref = useRef<HTMLDivElement>(null);
+ const model = useRef<Model<T>>(new Model(value, setValue));
+
+ useOnMount(() => {
+ if (!ref.current) {
+ return;
+ }
+
+ render({ model: model.current, el: ref.current });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ });
+
+ // When the value changes, update the model
+ useEffect(() => {
+ model.current.updateAndEmitDiffs(value);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [useDeepCompareMemoize([value])]);
+
+ return <div ref={ref} />;
+};
+
+class Model<T extends Record<string, any>> {
+ constructor(
+ public data: T,
+ public onChange: (value: T) => void,
+ ) {}
+
+ private listeners: Record<string, Array<(value: any) => void>> = {};
+
+ public get<K extends keyof T>(key: K): T[K] {
+ return this.data[key];
+ }
+
+ public set<K extends keyof T>(key: K, value: T[K]): void {
+ this.data = { ...this.data, [key]: value };
+ this.emit(`change:${key as K & string}`, value);
+ }
+
+ public save_changes(): void {
+ this.onChange(this.data);
+ }
+
+ public updateAndEmitDiffs(value: T): void {
+ Object.keys(value).forEach((key) => {
+ const k = key as keyof T;
+ if (!dequal(this.data[k], value[k])) {
+ this.set(k, value[k]);
+ }
+ });
+ }
+
+ public on<K extends keyof T>(
+ event: `change:${K & string}`,
+ callback: (value: T[K]) => void,
+ ): void {
+ if (!this.listeners[event]) {
+ this.listeners[event] = [];
+ }
+ this.listeners[event].push(callback);
+ }
+
+ private emit<K extends keyof T>(event: `change:${K & string}`, value: T[K]) {
+ if (!this.listeners[event]) {
+ return;
+ }
+ this.listeners[event].forEach((cb) => cb(value));
+ }
+}
diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.ts
index 6846b25783..4df777c2bc 100644
--- a/frontend/src/plugins/plugins.ts
+++ b/frontend/src/plugins/plugins.ts
@@ -36,6 +36,7 @@ import { PlotlyPlugin } from "./impl/plotly/PlotlyPlugin";
import { CodeEditorPlugin } from "./impl/CodeEditorPlugin";
import { DataExplorerPlugin } from "./impl/data-explorer/DataExplorerPlugin";
import { MermaidPlugin } from "./layout/mermaid/MermaidPlugin";
+import { AnyWidgetPlugin } from "./impl/anywidget/AnyWidgetPlugin";
// List of UI plugins
export const UI_PLUGINS: Array<IPlugin<any, unknown>> = [
@@ -62,6 +63,7 @@ export const UI_PLUGINS: Array<IPlugin<any, unknown>> = [
new PlotlyPlugin(),
DataExplorerPlugin,
DataFramePlugin,
+ new AnyWidgetPlugin(),
];
// List of output / layout plugins
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index cbcd61bd65..76e6a7f85b 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -107,6 +107,11 @@ class DependencyManager:
"""Return True if plotly is installed."""
return importlib.util.find_spec("plotly") is not None
+ @staticmethod
+ def has_anywidget() -> bool:
+ """Return True if anywidget is installed."""
+ return importlib.util.find_spec("anywidget") is not None
+
@staticmethod
def has_watchdog() -> bool:
"""Return True if watchdog is installed."""
diff --git a/marimo/_output/data/data.py b/marimo/_output/data/data.py
index cbc5d7e91c..9d47f91568 100644
--- a/marimo/_output/data/data.py
+++ b/marimo/_output/data/data.py
@@ -117,6 +117,20 @@ def json(
return any_data(data, ext="json") # type: ignore
+def js(data: str) -> VirtualFile:
+ """Create a virtual file for JavaScript data.
+
+ **Args.**
+
+ - data: JavaScript data as a string
+
+ **Returns.**
+
+ A `VirtualFile` object.
+ """
+ return any_data(data, ext="js")
+
+
def html(data: str) -> VirtualFile:
"""Create a virtual file for HTML data.
diff --git a/marimo/_output/formatters/anywidget_formatters.py b/marimo/_output/formatters/anywidget_formatters.py
new file mode 100644
index 0000000000..31b8cbb170
--- /dev/null
+++ b/marimo/_output/formatters/anywidget_formatters.py
@@ -0,0 +1,21 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from marimo._messaging.mimetypes import KnownMimeType
+from marimo._output.formatters.formatter_factory import FormatterFactory
+from marimo._plugins.ui._impl.from_anywidget import from_anywidget
+
+
+class AnyWidgetFormatter(FormatterFactory):
+ @staticmethod
+ def package_name() -> str:
+ return "anywidget"
+
+ def register(self) -> None:
+ import anywidget # type: ignore [import-not-found]
+
+ from marimo._output import formatting
+
+ @formatting.formatter(anywidget.AnyWidget)
+ def _from(lmap: anywidget.AnyWidget) -> tuple[KnownMimeType, str]:
+ return from_anywidget(lmap)._mime_()
diff --git a/marimo/_output/formatters/formatters.py b/marimo/_output/formatters/formatters.py
index 0999a12d10..8c135ae864 100644
--- a/marimo/_output/formatters/formatters.py
+++ b/marimo/_output/formatters/formatters.py
@@ -5,6 +5,7 @@ import sys
from typing import Any, Callable, Sequence
from marimo._output.formatters.altair_formatters import AltairFormatter
+from marimo._output.formatters.anywidget_formatters import AnyWidgetFormatter
from marimo._output.formatters.bokeh_formatters import BokehFormatter
from marimo._output.formatters.cell import CellFormatter
from marimo._output.formatters.formatter_factory import FormatterFactory
@@ -28,6 +29,7 @@ THIRD_PARTY_FACTORIES: dict[str, FormatterFactory] = {
LeafmapFormatter.package_name(): LeafmapFormatter(),
BokehFormatter.package_name(): BokehFormatter(),
HoloViewsFormatter.package_name(): HoloViewsFormatter(),
+ AnyWidgetFormatter.package_name(): AnyWidgetFormatter(),
}
# Formatters for builtin types and other things that don't require a
diff --git a/marimo/_plugins/ui/__init__.py b/marimo/_plugins/ui/__init__.py
index 4926b8b5ce..20ea5d6a27 100644
--- a/marimo/_plugins/ui/__init__.py
+++ b/marimo/_plugins/ui/__init__.py
@@ -18,6 +18,7 @@ __all__ = [
"dropdown",
"file",
"form",
+ "anywidget",
"microphone",
"multiselect",
"number",
@@ -39,6 +40,7 @@ from marimo._plugins.ui._impl.batch import batch
from marimo._plugins.ui._impl.data_explorer import data_explorer
from marimo._plugins.ui._impl.dataframes.dataframe import dataframe
from marimo._plugins.ui._impl.dictionary import dictionary
+from marimo._plugins.ui._impl.from_anywidget import _anywidget as anywidget
from marimo._plugins.ui._impl.input import (
button,
checkbox,
diff --git a/marimo/_plugins/ui/_impl/from_anywidget.py b/marimo/_plugins/ui/_impl/from_anywidget.py
new file mode 100644
index 0000000000..aac7fdc19a
--- /dev/null
+++ b/marimo/_plugins/ui/_impl/from_anywidget.py
@@ -0,0 +1,92 @@
+# Copyright 2024 Marimo. All rights reserved.
+import weakref
+from typing import TYPE_CHECKING, Any, Dict
+
+import marimo._output.data.data as mo_data
+from marimo._output.rich_help import mddoc
+from marimo._plugins.ui._core.ui_element import UIElement
+
+if TYPE_CHECKING:
+ import anywidget # type: ignore [import-not-found, unused-ignore]
+
+# Weak dictionary
+# When the widget is deleted, the UIElement will be deleted as well
+cache: Dict[Any, UIElement[Any, Any]] = weakref.WeakKeyDictionary() # type: ignore[no-untyped-call, unused-ignore, assignment]
+
+
+def from_anywidget(widget: "anywidget.AnyWidget") -> UIElement[Any, Any]:
+ """Create a UIElement from an AnyWidget."""
+ if widget not in cache:
+ cache[widget] = _anywidget(widget) # type: ignore[no-untyped-call, unused-ignore, assignment]
+ return cache[widget]
+
+
+T = Dict[str, Any]
+
+
+@mddoc
+class _anywidget(UIElement[T, T]):
+ """
+ Create a UIElement from an AnyWidget.
+
+ **Example.**
+
+ ```python
+ from drawdata import ScatterWidget
+ import marimo as mo
+
+ widget = mo.ui.anywidget(ScatterWidget())
+
+ # In another cell, access its value
+ widget.value
+ ```
+
+ **Attributes.**
+
+ - `value`: The value of the widget's traits as a dictionary.
+ - `widget`: The widget being wrapped.
+
+ **Initialization Args.**
+
+ - `widget`: The widget to wrap.
+ """
+
+ def __init__(self, widget: "anywidget.AnyWidget"):
+ self.widget = widget
+
+ # Get all the traits of the widget
+ args: T = widget.trait_values()
+ ignored_traits = [
+ "comm",
+ "layout",
+ "log",
+ "tabbable",
+ "tooltip",
+ "keys",
+ ]
+ # Remove ignored traits
+ for trait_name in ignored_traits:
+ args.pop(trait_name, None)
+ # Remove all private traits
+ args = {k: v for k, v in args.items() if not k.startswith("_")}
+
+ def on_change(change: T) -> None:
+ for key, value in change.items():
+ widget.set_trait(key, value)
+
+ js: str = widget._esm if hasattr(widget, "_esm") else "" # type: ignore [unused-ignore]
+ css: str = widget._css if hasattr(widget, "_css") else "" # type: ignore [unused-ignore]
+
+ super().__init__(
+ component_name="marimo-anywidget",
+ initial_value=args,
+ label="",
+ args={
+ "js-url": mo_data.js(js).url if js else "", # type: ignore [unused-ignore]
+ "css": css,
+ },
+ on_change=on_change,
+ )
+
+ def _convert_value(self, value: T) -> T:
+ return value
diff --git a/marimo/_smoke_tests/anywidget_compat.py b/marimo/_smoke_tests/anywidget_compat.py
new file mode 100644
index 0000000000..354a021cff
--- /dev/null
+++ b/marimo/_smoke_tests/anywidget_compat.py
@@ -0,0 +1,128 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.2.13"
+app = marimo.App(width="medium")
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+def __():
+ import anywidget
+ import traitlets
+
+
+ class CounterWidget(anywidget.AnyWidget):
+ # Widget front-end JavaScript code
+ _esm = """
+ function render({ model, el }) {
+ let getCount = () => model.get("count");
+ let button = document.createElement("button");
+ button.innerHTML = `count is ${getCount()}`;
+ button.addEventListener("click", () => {
+ model.set("count", getCount() + 1);
+ model.save_changes();
+ });
+ model.on("change:count", () => {
+ button.innerHTML = `count is ${getCount()}`;
+ });
+ el.appendChild(button);
+ }
+ export default { render };
+ """
+ _css = """
+ button {
+ padding: 5px !important;
+ border-radius: 5px !important;
+ background-color: #f0f0f0 !important;
+
+ &:hover {
+ background-color: lightblue !important;
+ color: white !important;
+ }
+ }
+ """
+
+ # Stateful property that can be accessed by JavaScript & Python
+ count = traitlets.Int(0).tag(sync=True)
+ return CounterWidget, anywidget, traitlets
+
+
+def __(CounterWidget):
+ # Non-reactive
+ w = CounterWidget()
+ w
+ return w,
+
+
+def __(w):
+ # Non-reactive, but class is cached
+ w
+ return
+
+
+def __(w):
+ w.trait_values()["count"]
+ return
+
+
+def __(CounterWidget, mo):
+ w_reactive = mo.ui.anywidget(CounterWidget())
+ w_reactive
+ return w_reactive,
+
+
+def __(w_reactive):
+ w_reactive
+ return
+
+
+def __(w_reactive):
+ w_reactive.value
+ return
+
+
+def __(w_reactive):
+ w_reactive.widget.trait_values()["count"]
+ return
+
+
+def __():
+ import altair as alt
+ import pandas as pd
+ return alt, pd
+
+
+def __(mo):
+ from drawdata import ScatterWidget
+
+ dd_widget = mo.ui.anywidget(ScatterWidget())
+ dd_widget
+ return ScatterWidget, dd_widget
+
+
[email protected](hide_code=True)
+def __(alt, dd_widget, mo, pd):
+ mo.stop(not dd_widget.value["data"])
+ df = pd.DataFrame(dd_widget.value["data"])
+ chart = alt.Chart(df).mark_point().encode(x="x", y="y", color="color")
+ mo.ui.altair_chart(chart)
+ return chart, df
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_plugins/ui/_impl/test_anywidget.py b/tests/_plugins/ui/_impl/test_anywidget.py
new file mode 100644
index 0000000000..6a17e6b69d
--- /dev/null
+++ b/tests/_plugins/ui/_impl/test_anywidget.py
@@ -0,0 +1,109 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import pytest
+
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._plugins.ui._impl.from_anywidget import _anywidget
+from marimo._runtime.runtime import Kernel
+from tests.conftest import ExecReqProvider
+
+HAS_DEPS = DependencyManager.has_anywidget()
+
+if HAS_DEPS:
+ import anywidget
+ import traitlets
+
+ class CounterWidget(anywidget.AnyWidget):
+ _esm = """
+ function render({ model, el }) {
+ let getCount = () => model.get("count");
+ let button = document.createElement("button");
+ button.innerHTML = `count is ${getCount()}`;
+ el.appendChild(button);
+ }
+ export default { render };
+ """
+ _css = """button { padding: 5px !important; }"""
+ count = traitlets.Int(0).tag(sync=True)
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+class TestAnywidget:
+ @staticmethod
+ async def test_instances(k: Kernel, exec_req: ExecReqProvider) -> None:
+ import anywidget
+
+ await k.run(
+ [
+ exec_req.get(
+ """
+import anywidget
+import traitlets
+import marimo as mo
+
+class CounterWidget(anywidget.AnyWidget):
+ _esm = \"\"\"
+ function render({ model, el }) {
+ let getCount = () => model.get("count");
+ let button = document.createElement("button");
+ button.innerHTML = `count is ${getCount()}`;
+ el.appendChild(button);
+ }
+ export default { render };
+ \"\"\"
+ _css = \"\"\"button { padding: 5px !important; }\"\"\"
+ count = traitlets.Int(10).tag(sync=True)
+
+base_widget = CounterWidget()
+
+are_same = mo.as_html(base_widget).text == mo.as_html(base_widget).text
+are_different = mo.as_html(CounterWidget()) != mo.as_html(CounterWidget())
+as_marimo_element = mo.ui.anywidget(base_widget)
+"""
+ )
+ ]
+ )
+ assert k.globals["are_same"] is True
+ assert k.globals["are_different"] is True
+ assert isinstance(k.globals["base_widget"], anywidget.AnyWidget)
+ assert "marimo-anywidget" in k.globals["as_marimo_element"].text
+
+ @staticmethod
+ async def test_value(k: Kernel, exec_req: ExecReqProvider) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import anywidget
+ import traitlets
+
+ class CounterWidget(anywidget.AnyWidget):
+ _esm = \"\"\"
+ function render({ model, el }) {
+ let getCount = () => model.get("count");
+ let button = document.createElement("button");
+ button.innerHTML = `count is ${getCount()}`;
+ el.appendChild(button);
+ }
+ export default { render };
+ \"\"\"
+ _css = \"\"\"button { padding: 5px !important; }\"\"\"
+ count = traitlets.Int(10).tag(sync=True)
+ """
+ ),
+ exec_req.get(
+ """
+ import marimo as mo
+ w = mo.ui.anywidget(CounterWidget())
+ """
+ ),
+ exec_req.get(
+ """
+ w_value = w.value
+ """
+ ),
+ ]
+ )
+ assert isinstance(k.globals["w"], _anywidget)
+ assert k.globals["w_value"]["count"] == 10