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.

fix: allow re-rendering anywidget js (#3022)

Myles Scolnick85b35f942325
diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
index 70e9d961b2..a7d8b47009 100644
--- a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
+++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
@@ -6,7 +6,6 @@ import type { IPluginProps } from "@/plugins/types";
import { useEffect, useMemo, 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";
import { createPlugin } from "@/plugins/core/builder";
@@ -22,6 +21,7 @@ import { updateBufferPaths } from "@/utils/date-views";
interface Data {
jsUrl: string;
+ jsHash: string;
css?: string | null;
bufferPaths?: Array<Array<string | number>> | null;
}
@@ -37,6 +37,7 @@ export const AnyWidgetPlugin = createPlugin<T>("marimo-anywidget")
.withData(
z.object({
jsUrl: z.string(),
+ jsHash: z.string(),
css: z.string().nullish(),
bufferPaths: z
.array(z.array(z.union([z.string(), z.number()])))
@@ -53,19 +54,16 @@ export const AnyWidgetPlugin = createPlugin<T>("marimo-anywidget")
type Props = IPluginProps<T, Data, PluginFunctions>;
const AnyWidgetSlot = (props: Props) => {
- const { css, jsUrl, bufferPaths } = props.data;
+ const { css, jsUrl, jsHash, bufferPaths } = 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 { data: module, error } = useAsyncData(async () => {
const baseUrl = document.baseURI;
const url = new URL(jsUrl, baseUrl).toString();
return await import(/* @vite-ignore */ url);
- }, []);
+ // Re-render on jsHash change instead of url change (since URLs may change)
+ }, [jsHash]);
const valueWithBuffer = useMemo(() => {
return updateBufferPaths(props.value, bufferPaths);
@@ -88,7 +86,7 @@ const AnyWidgetSlot = (props: Props) => {
return <ErrorBanner error={error} />;
}
- if (!module || loading) {
+ if (!module) {
return null;
}
@@ -123,6 +121,8 @@ async function runAnyWidgetModule(
throw new Error(message);
},
};
+ // Clear the element, in case the widget is re-rendering
+ el.innerHTML = "";
const widget =
typeof widgetDef === "function" ? await widgetDef() : widgetDef;
await widget.initialize?.({ model, experimental });
@@ -159,13 +159,12 @@ const LoadedSlot = ({
},
);
- useOnMount(() => {
+ useEffect(() => {
if (!ref.current) {
return;
}
runAnyWidgetModule(widget, model.current, ref.current);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- });
+ }, [widget]);
// When the value changes, update the model
useEffect(() => {
diff --git a/marimo/_plugins/ui/_impl/from_anywidget.py b/marimo/_plugins/ui/_impl/from_anywidget.py
index e6c6e8e669..92ec291025 100644
--- a/marimo/_plugins/ui/_impl/from_anywidget.py
+++ b/marimo/_plugins/ui/_impl/from_anywidget.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import hashlib
import weakref
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Dict, Optional
@@ -134,12 +135,15 @@ class anywidget(UIElement[T, T]):
_put_buffers(change, buffer_paths, buffers)
widget.set_state(change)
+ js_hash: str = hashlib.md5(js.encode("utf-8")).hexdigest()
+
super().__init__(
component_name="marimo-anywidget",
initial_value=json_args,
label="",
args={
"js-url": mo_data.js(js).url if js else "", # type: ignore [unused-ignore] # noqa: E501
+ "js-hash": js_hash,
"css": css,
"buffer-paths": buffer_paths,
},
diff --git a/marimo/_smoke_tests/anywidget_examples/esm_rerender.py b/marimo/_smoke_tests/anywidget_examples/esm_rerender.py
new file mode 100644
index 0000000000..4042cba3a6
--- /dev/null
+++ b/marimo/_smoke_tests/anywidget_examples/esm_rerender.py
@@ -0,0 +1,75 @@
+# /// script
+# requires-python = ">=3.12"
+# dependencies = [
+# "anywidget==0.9.13",
+# "marimo",
+# "traitlets==5.14.3",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.9.27"
+app = marimo.App(width="medium")
+
+
+def __():
+ import marimo as mo
+ import anywidget
+ import traitlets
+ return anywidget, mo, traitlets
+
+
+def __(anywidget, 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,)
+
+
+def __(CounterWidget, mo):
+ widget = mo.ui.anywidget(CounterWidget())
+ return (widget,)
+
+
+def __(widget):
+ widget
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_plugins/ui/_impl/test_anywidget.py b/tests/_plugins/ui/_impl/test_anywidget.py
index 03f919a95a..b4b0091382 100644
--- a/tests/_plugins/ui/_impl/test_anywidget.py
+++ b/tests/_plugins/ui/_impl/test_anywidget.py
@@ -1,6 +1,8 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+from hashlib import md5
+
import pytest
from marimo._dependencies.dependencies import DependencyManager
@@ -181,6 +183,7 @@ x = as_marimo_element.count
"buffer-paths": [],
"css": "",
"js-url": "",
+ "js-hash": md5(b"").hexdigest(),
}
@staticmethod
@@ -197,6 +200,7 @@ x = as_marimo_element.count
"buffer-paths": [["arr", "bytes"]],
"css": "",
"js-url": "",
+ "js-hash": md5(b"").hexdigest(),
}
@staticmethod
@@ -308,3 +312,22 @@ x = as_marimo_element.count
wrapped = anywidget(CSSWidget())
assert wrapped._component_args["css"] == "button { color: red; }"
+
+ @staticmethod
+ async def test_js_hash() -> None:
+ class JSWidget(_anywidget.AnyWidget):
+ _esm = ""
+ value = traitlets.Int(0).tag(sync=True)
+
+ wrapped = anywidget(JSWidget())
+ assert wrapped._component_args["js-hash"] == md5(b"").hexdigest()
+
+ class JSWidget2(_anywidget.AnyWidget):
+ _esm = "function render({ model, el }) { el.innerHTML = 'hello'; }"
+ value = traitlets.Int(0).tag(sync=True)
+
+ wrapped2 = anywidget(JSWidget2())
+ assert (
+ wrapped2._component_args["js-hash"]
+ != wrapped._component_args["js-hash"]
+ )