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: anywidget should re-render whenever re-created (#3998)

Myles Scolnicka3f717329fd1
diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
index 6d1fb42d65..8bd23e2d9a 100644
--- a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
+++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
@@ -183,7 +183,7 @@ const LoadedSlot = ({
data,
host,
}: Props & { widget: AnyWidget }) => {
- const ref = useRef<HTMLDivElement>(null);
+ const htmlRef = useRef<HTMLDivElement>(null);
const model = useRef<Model<T>>(
new Model(
// Merge the initial value with the current value
@@ -205,11 +205,16 @@ const LoadedSlot = ({
);
useEffect(() => {
- if (!ref.current) {
+ if (!htmlRef.current) {
return;
}
- runAnyWidgetModule(widget, model.current, ref.current);
- }, [widget]);
+ runAnyWidgetModule(widget, model.current, htmlRef.current);
+ // We re-run the widget when the jsUrl changes, which means the cell
+ // that created the Widget has been re-run.
+ // We need to re-run the widget because it may contain initialization code
+ // that could be reset by the new widget.
+ // See example: https://github.com/marimo-team/marimo/issues/3962#issuecomment-2703184123
+ }, [widget, data.jsUrl]);
// When the value changes, update the model
const valueMemo = useDeepCompareMemoize(value);
@@ -217,5 +222,12 @@ const LoadedSlot = ({
model.current.updateAndEmitDiffs(valueMemo);
}, [valueMemo]);
- return <div ref={ref} />;
+ return <div ref={htmlRef} />;
+};
+
+export const visibleForTesting = {
+ LoadedSlot,
+ runAnyWidgetModule,
+ isAnyWidgetModule,
+ getDirtyFields,
};
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.ts b/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx
similarity index 71%
rename from frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.ts
rename to frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx
index ccb321efec..2c1250504a 100644
--- a/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.ts
+++ b/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx
@@ -1,7 +1,12 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { getDirtyFields } from "../AnyWidgetPlugin";
+import { getDirtyFields, visibleForTesting } from "../AnyWidgetPlugin";
import { Model } from "../model";
import { vi, describe, it, expect, beforeEach } from "vitest";
+import { render, act, waitFor } from "@testing-library/react";
+import { MarimoIncomingMessageEvent } from "@/core/dom/events";
+import type { UIElementId } from "@/core/cells/ids";
+
+const { LoadedSlot } = visibleForTesting;
describe("Model", () => {
let model: Model<{ foo: string; bar: number }>;
@@ -289,3 +294,122 @@ describe("getDirtyFields", () => {
expect(result.size).toBe(0);
});
});
+
+// Mock a minimal AnyWidget implementation
+const mockWidget = {
+ initialize: vi.fn(),
+ render: vi.fn(),
+};
+
+vi.mock("../AnyWidgetPlugin", async () => {
+ const originalModule = await vi.importActual("../AnyWidgetPlugin");
+ return {
+ ...originalModule,
+ runAnyWidgetModule: vi.fn(),
+ };
+});
+
+describe("LoadedSlot", () => {
+ const mockProps = {
+ value: { count: 0 },
+ setValue: vi.fn(),
+ widget: mockWidget,
+ functions: {
+ send_to_widget: vi.fn().mockResolvedValue(null),
+ },
+ data: {
+ jsUrl: "http://example.com/widget.js",
+ jsHash: "abc123",
+ initialValue: { count: 0 },
+ },
+ host: document.createElement("div"),
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("should render a div with ref", () => {
+ const { container } = render(<LoadedSlot {...mockProps} />);
+ expect(container.querySelector("div")).not.toBeNull();
+ });
+
+ it("should initialize model with merged values", () => {
+ const modelSpy = vi.spyOn(Model.prototype, "updateAndEmitDiffs");
+ render(<LoadedSlot {...mockProps} />);
+
+ expect(modelSpy).toHaveBeenCalledExactlyOnceWith({ count: 0 });
+ });
+
+ it("should update model when value prop changes", async () => {
+ const { rerender } = render(<LoadedSlot {...mockProps} />);
+ const modelSpy = vi.spyOn(Model.prototype, "updateAndEmitDiffs");
+
+ // Update the value prop
+ rerender(<LoadedSlot {...mockProps} value={{ count: 5 }} />);
+
+ // Model should be updated with the new value
+ expect(modelSpy).toHaveBeenCalledWith({ count: 5 });
+ });
+
+ it("should listen for incoming messages", async () => {
+ render(<LoadedSlot {...mockProps} />);
+
+ // Send a mock message
+ const mockMessageEvent = MarimoIncomingMessageEvent.create({
+ detail: {
+ objectId: "test-id" as UIElementId,
+ message: {
+ method: "update",
+ state: { count: 10 },
+ },
+ buffers: undefined,
+ },
+ bubbles: false,
+ composed: true,
+ });
+ const updateAndEmitDiffsSpy = vi.spyOn(Model.prototype, "set");
+
+ // Dispatch the event on the host element
+ act(() => {
+ mockProps.host.dispatchEvent(mockMessageEvent);
+ });
+
+ await waitFor(() => {
+ expect(updateAndEmitDiffsSpy).toHaveBeenCalledWith("count", 10);
+ });
+ });
+
+ it("should call runAnyWidgetModule on initialization", async () => {
+ const { rerender } = render(<LoadedSlot {...mockProps} />);
+
+ // Wait a render
+ await waitFor(() => {
+ expect(mockWidget.render).toHaveBeenCalled();
+ });
+
+ // Render without any prop changes
+ rerender(<LoadedSlot {...mockProps} />);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ // Still only called once
+ expect(mockWidget.render).toHaveBeenCalledTimes(1);
+
+ // Change the jsUrl
+ rerender(
+ <LoadedSlot
+ {...mockProps}
+ data={{
+ ...mockProps.data,
+ jsUrl: "http://example.com/widget-updated.js",
+ }}
+ />,
+ );
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ // Wait a render
+ await waitFor(() => {
+ expect(mockWidget.render).toHaveBeenCalledTimes(2);
+ });
+ });
+});
diff --git a/marimo/_smoke_tests/issues/3962-anywidget-partial-state-2.py b/marimo/_smoke_tests/issues/3962-anywidget-partial-state-2.py
new file mode 100644
index 0000000000..ec69849ed6
--- /dev/null
+++ b/marimo/_smoke_tests/issues/3962-anywidget-partial-state-2.py
@@ -0,0 +1,61 @@
+import marimo
+
+__generated_with = "0.11.16"
+app = marimo.App(width="medium")
+
+
+def _():
+ import marimo as mo
+ import anywidget
+ import traitlets
+ return anywidget, mo, traitlets
+
+
+def _(anywidget, traitlets):
+ class MyWidget(anywidget.AnyWidget):
+ _esm = """
+ function render({ model, el }) {
+ let in_value = model.get("in_value");
+ console.log("[debug:init] in_value", in_value);
+ model.set("out_value", in_value * 2);
+ console.log("[debug:init] out_value", in_value * 2);
+ model.save_changes();
+
+ model.on("change:in_value", () => {
+ let in_value = model.get("in_value");
+ console.log("[debug:change] in_value", in_value);
+ model.set("out_value", in_value * 2);
+ console.log("[debug:change] out_value", in_value * 2);
+ model.save_changes();
+ })
+ }
+ export default { render };
+ """
+ in_value = traitlets.Int(0).tag(sync=True)
+ out_value = traitlets.Int(123).tag(sync=True)
+ return (MyWidget,)
+
+
+def _(MyWidget):
+ widget_instance = MyWidget(in_value=8)
+ return (widget_instance,)
+
+
+def _(mo, widget_instance):
+ m = mo.ui.anywidget(widget_instance)
+ m
+ return (m,)
+
+
+def _(m):
+ m.widget.out_value
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_smoke_tests/issues/3962-anywidget-partial-state.py b/marimo/_smoke_tests/issues/3962-anywidget-partial-state.py
new file mode 100644
index 0000000000..3e45e6fa8d
--- /dev/null
+++ b/marimo/_smoke_tests/issues/3962-anywidget-partial-state.py
@@ -0,0 +1,58 @@
+import marimo
+
+__generated_with = "0.11.16"
+app = marimo.App(width="medium")
+
+
+def _():
+ import anywidget
+ import traitlets
+ import marimo as mo
+ from svg import SVG, Circle
+ return Circle, SVG, anywidget, mo, traitlets
+
+
+def _(anywidget, traitlets):
+ class HoverWidget(anywidget.AnyWidget):
+ _esm = """
+ function render({ model, el }) {
+ el.innerHTML = model.get("svg");
+ el.querySelectorAll("circle").forEach((circle) => {
+ circle.addEventListener("mouseover", () => {
+ model.set("selected_id", circle.getAttribute("id"));
+ model.save_changes();
+ });
+ });
+ }
+ export default { render };
+ """
+ svg = traitlets.Unicode().tag(sync=True)
+ selected_id = traitlets.Any().tag(sync=True)
+ return (HoverWidget,)
+
+
+def _(Circle, SVG):
+ my_svg = SVG(
+ width=200,
+ height=100,
+ elements=[
+ Circle(id="circle 1", cx=50, cy=50, r=20, fill="red"),
+ Circle(id="circle 2", cx=100, cy=50, r=20, fill="blue"),
+ Circle(id="circle 3", cx=150, cy=50, r=20, fill="green"),
+ ],
+ )
+ return (my_svg,)
+
+
+def _(HoverWidget, mo, my_svg):
+ w = mo.ui.anywidget(HoverWidget(svg=my_svg.as_str(), selected_id=""))
+ [w]
+ return (w,)
+
+
+if __name__ == "__main__":
+ app.run()