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 emit on any change (without a key) (#3905)

Myles Scolnick8d3e4bfa2835
diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
index 06c5711f41..b944f5c4b7 100644
--- a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
+++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
@@ -18,6 +18,7 @@ import {
} from "@/hooks/useEventListener";
import { MarimoIncomingMessageEvent } from "@/core/dom/events";
import { updateBufferPaths } from "@/utils/data-views";
+import { debounce } from "lodash-es";
interface Data {
jsUrl: string;
@@ -204,6 +205,8 @@ const LoadedSlot = ({
};
export class Model<T extends Record<string, any>> implements AnyModel<T> {
+ private ANY_CHANGE_EVENT = "change";
+
constructor(
private data: T,
private onChange: (value: Partial<T>) => void,
@@ -261,6 +264,7 @@ export class Model<T extends Record<string, any>> implements AnyModel<T> {
this.data = { ...this.data, [key]: value };
this.dirtyFields.add(key);
this.emit(`change:${key as K & string}`, value);
+ this.emitAnyChange();
}
save_changes(): void {
@@ -321,6 +325,11 @@ export class Model<T extends Record<string, any>> implements AnyModel<T> {
}
this.listeners[event].forEach((cb) => cb(value));
}
+
+ // Debounce 0 to send off one request in a single frame
+ private emitAnyChange = debounce(() => {
+ this.listeners[this.ANY_CHANGE_EVENT]?.forEach((cb) => cb());
+ }, 0);
}
const WidgetMessageSchema = z.union([
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.ts b/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.ts
index b22156b59f..03e8fba0b0 100644
--- a/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.ts
+++ b/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.ts
@@ -155,7 +155,15 @@ describe("Model", () => {
modelWithObject.on("change:foo", callback);
modelWithObject.updateAndEmitDiffs({ foo: { nested: "changed" } });
- expect(callback).toHaveBeenCalled();
+ expect(callback).toHaveBeenCalledTimes(1);
+ });
+
+ it("should emit change event for any changes", async () => {
+ const callback = vi.fn();
+ model.on("change", callback);
+ model.updateAndEmitDiffs({ foo: "changed", bar: 456 });
+ await new Promise((resolve) => setTimeout(resolve, 0)); // flush
+ expect(callback).toHaveBeenCalledTimes(1);
});
});
@@ -206,7 +214,7 @@ describe("Model", () => {
});
model.receiveCustomMessage({ invalid: "message" });
- expect(consoleSpy).toHaveBeenCalled();
+ expect(consoleSpy).toHaveBeenCalledTimes(2);
});
});
});