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
feat: Support anywidget lifecycle hooks (#1902)
Trevor Manz58b7996c9145
diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsxindex 53d058a7bd..33050f233a 100644--- a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx+++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx@@ -11,7 +11,7 @@ import { useDeepCompareMemoize } from "@/hooks/useDeepCompareMemoize";import { ErrorBanner } from "../common/error-banner";import { createPlugin } from "@/plugins/core/builder";import { rpc } from "@/plugins/core/rpc";-import type { AnyModel, EventHandler } from "./types";+import type { AnyModel, AnyWidget, EventHandler, Experimental } from "./types";import { Logger } from "@/utils/Logger";import { useEventListener } from "@/hooks/useEventListener";import { MarimoIncomingMessageEvent } from "@/core/dom/events";@@ -82,25 +82,57 @@ const AnyWidgetSlot = (props: Props) => {return null;}- if (!module.default.render) {+ if (!isAnyWidgetModule(module)) {const error = new Error(- `Module at ${jsUrl} does not have a default export with a render function`,+ `Module at ${jsUrl} does not appear to be a valid anywidget`,);return <ErrorBanner error={error} />;}- return <LoadedSlot {...props} render={module.default.render} />;+ return <LoadedSlot {...props} widget={module.default} />;};+/**+ * Run the anywidget module+ *+ * @param widgetDef - The anywidget definition+ * @param model - The model to pass to the widget+ */+async function runAnyWidgetModule(+ widgetDef: AnyWidget,+ model: Model<T>,+ el: HTMLElement,+) {+ const experimental: Experimental = {+ invoke: async (name, msg, options) => {+ const message =+ "anywidget.invoke not supported in marimo. Please file an issue at https://github.com/marimo-team/marimo/issues";+ Logger.warn(message);+ throw new Error(message);+ },+ };+ const widget =+ typeof widgetDef === "function" ? await widgetDef() : widgetDef;+ await widget.initialize?.({ model, experimental });+ await widget.render?.({ model, el, experimental });+}++function isAnyWidgetModule(mod: any): mod is { default: AnyWidget } {+ return (+ mod.default &&+ (typeof mod.default === "function" ||+ mod.default?.render ||+ mod.default?.initialize)+ );+}+const LoadedSlot = ({value,setValue,- render,+ widget,functions,host,-}: Props & {- render: ({ model, el }: any) => void;-}) => {+}: Props & { widget: AnyWidget }) => {const ref = useRef<HTMLDivElement>(null);const model = useRef<Model<T>>(new Model(value, setValue, functions.send_to_widget),@@ -115,8 +147,7 @@ const LoadedSlot = ({if (!ref.current) {return;}-- render({ model: model.current, el: ref.current });+ runAnyWidgetModule(widget, model.current, ref.current);// eslint-disable-next-line react-hooks/exhaustive-deps});diff --git a/frontend/src/plugins/impl/anywidget/types.ts b/frontend/src/plugins/impl/anywidget/types.tsindex 43470079f2..2411ebf8d3 100644--- a/frontend/src/plugins/impl/anywidget/types.ts+++ b/frontend/src/plugins/impl/anywidget/types.ts@@ -1,10 +1,13 @@/* Copyright 2024 Marimo. All rights reserved. */+/* eslint-disable @typescript-eslint/no-invalid-void-type *//* eslint-disable @typescript-eslint/no-explicit-any */// Copied from https://github.com/manzt/anywidget/blob/main/packages/types/index.ts// with slight modifications// - removed widget_manager+// We copy this for now since `@anywidget/types` pulls in jquery and backbone, which we don't need+type Awaitable<T> = T | Promise<T>;export type EventHandler = (...args: any[]) => void;type ObjectHash = Record<string, any>;export type ChangeEventHandler<Payload> = (_: unknown, value: Payload) => void;@@ -36,3 +39,37 @@ export interface AnyModel<T extends ObjectHash = ObjectHash> {): void;widget_manager: {};}++export interface Experimental {+ invoke: <T>(+ name: string,+ msg?: any,+ options?: {+ buffers?: DataView[];+ signal?: AbortSignal;+ },+ ) => Promise<[T, DataView[]]>;+}+export interface RenderProps<T extends ObjectHash = ObjectHash> {+ model: AnyModel<T>;+ el: HTMLElement;+ experimental: Experimental;+}+export type Render<T extends ObjectHash = ObjectHash> = (+ props: RenderProps<T>,+) => Awaitable<void | (() => Awaitable<void>)>;+export interface InitializeProps<T extends ObjectHash = ObjectHash> {+ model: AnyModel<T>;+ experimental: Experimental;+}++export type Initialize<T extends ObjectHash = ObjectHash> = (+ props: InitializeProps<T>,+) => Awaitable<void | (() => Awaitable<void>)>;+interface WidgetDef<T extends ObjectHash = ObjectHash> {+ initialize?: Initialize<T>;+ render?: Render<T>;+}+export type AnyWidget<T extends ObjectHash = ObjectHash> =+ | WidgetDef<T>+ | (() => Awaitable<WidgetDef<T>>);diff --git a/marimo/_plugins/ui/_impl/from_anywidget.py b/marimo/_plugins/ui/_impl/from_anywidget.pyindex 3881d6b086..ca548d1583 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 jsonimport weakreffrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, Dict, Optional@@ -8,6 +9,7 @@ from typing import TYPE_CHECKING, Any, Dict, Optionalimport marimo._output.data.data as mo_datafrom marimo import _loggersfrom marimo._output.rich_help import mddoc+from marimo._plugins.core.json_encoder import WebComponentEncoderfrom marimo._plugins.ui._core.ui_element import UIElementfrom marimo._runtime.functions import Function@@ -86,12 +88,32 @@ class anywidget(UIElement[T, T]):"tabbable","tooltip","keys",+ "_esm",+ "_anywidget_id",+ "_dom_classes",+ "_model_module",+ "_model_module_version",+ "_model_name",+ "_property_lock",+ "_states_to_send",+ "_view_count",+ "_view_module",+ "_view_module_version",+ "_view_name",]# Remove ignored traitsfor 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("_")}+ # Keep only classes that are json serialize-able+ json_args: T = {}+ for k, v in args.items():+ try:+ # Try to see if it is json-serializable+ json.dumps(v, cls=WebComponentEncoder)+ # Just add the plain value, it will be json-serialized later+ json_args[k] = v+ except TypeError:+ passdef on_change(change: T) -> None:for key, value in change.items():@@ -104,7 +126,7 @@ class anywidget(UIElement[T, T]):super().__init__(component_name="marimo-anywidget",- initial_value=args,+ initial_value=json_args,label="",args={"js-url": mo_data.js(js).url if js else "", # type: ignore [unused-ignore] # noqa: E501diff --git a/marimo/_smoke_tests/quak-demo.py b/marimo/_smoke_tests/quak-demo.pynew file mode 100644index 0000000000..839c3fe4d6--- /dev/null+++ b/marimo/_smoke_tests/quak-demo.py@@ -0,0 +1,37 @@+import marimo++__generated_with = "0.7.12"+app = marimo.App(width="medium")+++def __():+ import marimo as mo+ import polars as pl+ import quak+ from vega_datasets import data+ return data, mo, pl, quak+++def __(data):+ df = data.cars()+ return df,+++def __(df, mo, quak):+ qwidget = quak.Widget(df)+ w = mo.ui.anywidget(qwidget)+ w+ return qwidget, w+++def __():+ # w.value+ return+++if __name__ == "__main__":+ app.run()