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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: anywidget re-render (#3986)
Myles Scolnick333a5312ece2
diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsxindex c8b749d6da..6d1fb42d65 100644--- a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx+++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx@@ -18,12 +18,14 @@ import {import { MarimoIncomingMessageEvent } from "@/core/dom/events";import { updateBufferPaths } from "@/utils/data-views";import { Model } from "./model";+import { isEqual } from "lodash-es";interface Data {jsUrl: string;jsHash: string;css?: string | null;bufferPaths?: Array<Array<string | number>> | null;+ initialValue: T;}type T = Record<string, any>;@@ -42,6 +44,7 @@ export const AnyWidgetPlugin = createPlugin<T>("marimo-anywidget")bufferPaths: z.array(z.array(z.union([z.string(), z.number()]))).nullish(),+ initialValue: z.object({}).passthrough(),}),).withFunctions<PluginFunctions>({@@ -166,16 +169,30 @@ function isAnyWidgetModule(mod: any): mod is { default: AnyWidget } {);}+export function getDirtyFields(value: T, initialValue: T): Set<keyof T> {+ return new Set(+ Object.keys(value).filter((key) => !isEqual(value[key], initialValue[key])),+ );+}+const LoadedSlot = ({value,setValue,widget,functions,+ data,host,}: Props & { widget: AnyWidget }) => {const ref = useRef<HTMLDivElement>(null);const model = useRef<Model<T>>(- new Model(value, setValue, functions.send_to_widget),+ new Model(+ // Merge the initial value with the current value+ // since we only send partial updates to the backend+ { ...data.initialValue, ...value },+ setValue,+ functions.send_to_widget,+ getDirtyFields(value, data.initialValue),+ ),);// Listen to incoming messagesdiff --git a/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.ts b/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsindex 67ed37e97f..ccb321efec 100644--- a/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.ts+++ b/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.ts@@ -1,4 +1,5 @@/* Copyright 2024 Marimo. All rights reserved. */+import { getDirtyFields } from "../AnyWidgetPlugin";import { Model } from "../model";import { vi, describe, it, expect, beforeEach } from "vitest";@@ -12,7 +13,12 @@ describe("Model", () => {beforeEach(() => {onChange = vi.fn();sendToWidget = vi.fn().mockResolvedValue(null);- model = new Model({ foo: "test", bar: 123 }, onChange, sendToWidget);+ model = new Model(+ { foo: "test", bar: 123 },+ onChange,+ sendToWidget,+ new Set(),+ );});describe("get/set", () => {@@ -51,7 +57,25 @@ describe("Model", () => {});});- it("should clear dirty fields after save", () => {+ it("should send all dirty fields", () => {+ model.set("foo", "new value");+ model.save_changes();++ expect(onChange).toHaveBeenCalledWith({+ foo: "new value",+ });++ model.set("bar", 456);+ model.save_changes();++ expect(onChange).toHaveBeenCalledWith({+ foo: "new value",+ bar: 456,+ });+ });++ // Skip because we don't clear the dirty fields after save+ it.skip("should clear dirty fields after save", () => {model.set("foo", "new value");model.save_changes();model.save_changes(); // Second save should not call onChange@@ -145,6 +169,7 @@ describe("Model", () => {{ foo: { nested: "test" } },onChange,sendToWidget,+ new Set(),);const callback = vi.fn();modelWithObject.on("change:foo", callback);@@ -213,3 +238,54 @@ describe("Model", () => {});});});++describe("getDirtyFields", () => {+ it("should return empty set when values are equal", () => {+ const value = { foo: "bar", baz: 123 };+ const initialValue = { foo: "bar", baz: 123 };++ const result = getDirtyFields(value, initialValue);++ expect(result.size).toBe(0);+ });++ it("should return keys of changed values", () => {+ const value = { foo: "changed", baz: 123 };+ const initialValue = { foo: "bar", baz: 123 };++ const result = getDirtyFields(value, initialValue);++ expect(result.size).toBe(1);+ expect(result.has("foo")).toBe(true);+ });++ it("should handle multiple changed values", () => {+ const value = { foo: "changed", baz: 456, extra: "new" };+ const initialValue = { foo: "bar", baz: 123, extra: "old" };++ const result = getDirtyFields(value, initialValue);++ expect(result.size).toBe(3);+ expect(result.has("foo")).toBe(true);+ expect(result.has("baz")).toBe(true);+ expect(result.has("extra")).toBe(true);+ });++ it("should handle nested objects correctly", () => {+ const value = { foo: "bar", nested: { a: 1, b: 2 } };+ const initialValue = { foo: "bar", nested: { a: 1, b: 3 } };++ const result = getDirtyFields(value, initialValue);++ expect(result.size).toBe(1);+ expect(result.has("nested")).toBe(true);+ });++ it("should handle subset of initial fields", () => {+ const value = { foo: "bar", baz: 123 };+ const initialValue = { foo: "bar", baz: 123, full: "value" };++ const result = getDirtyFields(value, initialValue);+ expect(result.size).toBe(0);+ });+});diff --git a/frontend/src/plugins/impl/anywidget/model.ts b/frontend/src/plugins/impl/anywidget/model.tsindex 663ba3a742..82a6edf7dd 100644--- a/frontend/src/plugins/impl/anywidget/model.ts+++ b/frontend/src/plugins/impl/anywidget/model.ts@@ -10,14 +10,17 @@ export type EventHandler = (...args: any[]) => void;export class Model<T extends Record<string, any>> implements AnyModel<T> {private ANY_CHANGE_EVENT = "change";+ private dirtyFields;constructor(private data: T,private onChange: (value: Partial<T>) => void,private sendToWidget: (req: { content?: any }) => Promise<null | undefined>,- ) {}+ initialDirtyFields: Set<keyof T>,+ ) {+ this.dirtyFields = new Set(initialDirtyFields);+ }- private dirtyFields = new Set<keyof T>();private listeners: Record<string, Set<EventHandler>> = {};off(eventName?: string | null, callback?: EventHandler | null): void {@@ -72,7 +75,13 @@ export class Model<T extends Record<string, any>> implements AnyModel<T> {this.dirtyFields.forEach((key) => {partialData[key] = this.data[key];});- this.dirtyFields.clear();+ // We don't clear the dirty fields here, because we want+ // to send all fields that different from the initial value (have ever been changed).+ // This is less performant, but more correct, because the backend+ // stores the last value sent, and not a merge of the values.+ // When the backend knows to merge the partial updates, then we can clear+ // the dirty fields.+ // this.dirtyFields.clear();this.onChange(partialData);}diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex a5d0e1568b..4a63bcf79e 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -390,8 +390,8 @@ class SendUIElementMessage(Op):name: ClassVar[str] = "send-ui-element-message"ui_element: str- message: dict[str, object]- buffers: Optional[Sequence[str]]+ message: dict[str, Any]+ buffers: Optional[list[str]]@dataclassdiff --git a/openapi/api.yaml b/openapi/api.yamlindex fb199caf4a..32c032a57f 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -2015,9 +2015,7 @@ components:nullable: truetype: arraymessage:- additionalProperties:- additionalProperties: true- type: object+ additionalProperties: {}type: objectname:enum:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex a7147f66ac..76c1f537b2 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -3001,9 +3001,7 @@ export interface components {SendUIElementMessage: {buffers?: string[] | null;message: {- [key: string]: {- [key: string]: unknown;- };+ [key: string]: unknown;};/** @enum {string} */name: "send-ui-element-message";