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
improvement: support AnyWidget.send, mosaic_widget example (#1776)
Myles Scolnick73d0853af568
diff --git a/frontend/src/core/dom/events.ts b/frontend/src/core/dom/events.tsindex 473b03fa25..34d7529157 100644--- a/frontend/src/core/dom/events.ts+++ b/frontend/src/core/dom/events.ts@@ -1,22 +1,53 @@/* Copyright 2024 Marimo. All rights reserved. */-import { UIElementId } from "../cells/ids";+import type { UIElementId } from "../cells/ids";++export function defineCustomEvent<T extends string>(eventName: T) {+ return <D>() => ({+ TYPE: eventName,+ is(event: Event): event is CustomEvent<D> {+ return event.type === eventName;+ },+ create(init: CustomEventInit<D>) {+ return new CustomEvent(eventName, init);+ },+ });+}export type ValueType = unknown;-export type MarimoValueInputEventType = CustomEvent<{+export const MarimoValueInputEvent = defineCustomEvent("marimo-value-input")<{value: ValueType;element: HTMLElement;-}>;-export const marimoValueInputEvent = "marimo-value-input";+}>();+export type MarimoValueInputEventType = ReturnType<+ typeof MarimoValueInputEvent.create+>;-export type MarimoValueUpdateEventType = CustomEvent<{+export const MarimoValueUpdateEvent = defineCustomEvent("marimo-value-update")<{value: ValueType;element: HTMLElement;-}>;-export const marimoValueUpdateEvent = "marimo-value-update";+}>();+export type MarimoValueUpdateEventType = ReturnType<+ typeof MarimoValueUpdateEvent.create+>;++export const MarimoValueReadyEvent = defineCustomEvent("marimo-value-ready")<{+ objectId: UIElementId;+}>();+export type MarimoValueReadyEventType = ReturnType<+ typeof MarimoValueReadyEvent.create+>;-export type MarimoValueReadyEventType = CustomEvent<{ objectId: UIElementId }>;-export const marimoValueReadyEvent = "marimo-value-ready";+export const MarimoIncomingMessageEvent = defineCustomEvent(+ "marimo-incoming-message",+)<{+ objectId: UIElementId;+ message: unknown;+ buffers: DataView[] | undefined;+}>();+export type MarimoIncomingMessageEventType = ReturnType<+ typeof MarimoIncomingMessageEvent.create+>;/*** Create a custom event to communicate a change in value@@ -38,7 +69,7 @@ export function createInputEvent(value: ValueType,element: HTMLElement,): MarimoValueInputEventType {- return new CustomEvent(marimoValueInputEvent, {+ return MarimoValueInputEvent.create({bubbles: true, // bubble to tell marimo that a value has changedcomposed: true,detail: { value: value, element: element },@@ -48,14 +79,16 @@ export function createInputEvent(// Augment the global namespace to include the custom eventsdeclare global {interface HTMLElementEventMap {- "marimo-value-input": MarimoValueInputEventType;- "marimo-value-update": MarimoValueUpdateEventType;- "marimo-value-ready": MarimoValueReadyEventType;+ [MarimoValueInputEvent.TYPE]: MarimoValueInputEventType;+ [MarimoValueUpdateEvent.TYPE]: MarimoValueUpdateEventType;+ [MarimoValueReadyEvent.TYPE]: MarimoValueReadyEventType;+ [MarimoIncomingMessageEvent.TYPE]: MarimoIncomingMessageEventType;}interface DocumentEventMap {- "marimo-value-input": MarimoValueInputEventType;- "marimo-value-update": MarimoValueUpdateEventType;- "marimo-value-ready": MarimoValueReadyEventType;+ [MarimoValueInputEvent.TYPE]: MarimoValueInputEventType;+ [MarimoValueUpdateEvent.TYPE]: MarimoValueUpdateEventType;+ [MarimoValueReadyEvent.TYPE]: MarimoValueReadyEventType;+ [MarimoIncomingMessageEvent.TYPE]: MarimoIncomingMessageEventType;}}diff --git a/frontend/src/core/dom/ui-element.ts b/frontend/src/core/dom/ui-element.tsindex 0ee2a27d48..32a74a40e6 100644--- a/frontend/src/core/dom/ui-element.ts+++ b/frontend/src/core/dom/ui-element.ts@@ -4,7 +4,10 @@ import { Logger } from "../../utils/Logger";import { Functions } from "../../utils/functions";import { UIElementId } from "../cells/ids";import { defineCustomElement } from "./defineCustomElement";-import { MarimoValueInputEventType, marimoValueInputEvent } from "./events";+import {+ MarimoValueInputEvent,+ type MarimoValueInputEventType,+} from "./events";import { UI_ELEMENT_REGISTRY } from "./uiregistry";import "./ui-element.css";@@ -68,11 +71,11 @@ export function initializeUIElement() {* COMMUNICATION* Communication between marimo and the child of a UIElement is facilitated* by two events:- * 1. marimoValueInputEvent: the child publishes its value by dispatching- * a marimoValueInputEvent, with `detail` set to+ * 1. MarimoValueInputEvent: the child publishes its value by dispatching+ * a MarimoValueInputEvent, with `detail` set to* `{ value: <the new value> }`;- * 2. marimoValueUpdateEvent: the UIElement node broadcasts a- * marimoValueUpdateEvent to every element registered under its+ * 2. MarimoValueUpdateEvent: the UIElement node broadcasts a+ * MarimoValueUpdateEvent to every element registered under its* objectId when a new value is available; the targets of these* events (i.e., the child node of each UIElement in the equivalence* class of the objectId) are responsible for listening to these@@ -136,14 +139,20 @@ export function initializeUIElement() {// Listen to marimo input events provided by the child element: these// events are signals to this UIElement that our value should change.- document.addEventListener(marimoValueInputEvent, this.inputListener);+ document.addEventListener(+ MarimoValueInputEvent.TYPE,+ this.inputListener,+ );}}disconnectedCallback() {if (this.initialized) {// Unregister everything- document.removeEventListener(marimoValueInputEvent, this.inputListener);+ document.removeEventListener(+ MarimoValueInputEvent.TYPE,+ this.inputListener,+ );const objectId = UIElementId.parseOrThrow(this);UI_ELEMENT_REGISTRY.removeInstance(objectId,diff --git a/frontend/src/core/dom/uiregistry.ts b/frontend/src/core/dom/uiregistry.tsindex 2163da8dbe..db890f80ba 100644--- a/frontend/src/core/dom/uiregistry.ts+++ b/frontend/src/core/dom/uiregistry.ts@@ -1,9 +1,10 @@/* Copyright 2024 Marimo. All rights reserved. */import type { CellId, UIElementId } from "../cells/ids";import {- ValueType,- marimoValueUpdateEvent,- marimoValueReadyEvent,+ type ValueType,+ MarimoIncomingMessageEvent,+ MarimoValueReadyEvent,+ MarimoValueUpdateEvent,} from "./events";import { parseInitialValue } from "./htmlUtils";@@ -127,6 +128,38 @@ export class UIElementRegistry {return entry === undefined ? undefined : entry.value;}+ broadcastMessage(+ objectId: UIElementId,+ message: unknown,+ buffers: string[] | undefined | null,+ ): void {+ const entry = this.entries.get(objectId);+ if (entry !== undefined) {+ const base64ToDataView = (base64: string) => {+ const bytes = window.atob(base64);+ const buffer = new ArrayBuffer(bytes.length);+ const view = new DataView(buffer);+ for (let i = 0; i < bytes.length; i++) {+ view.setUint8(i, bytes.charCodeAt(i));+ }+ return view;+ };+ entry.elements.forEach((element) => {+ element.dispatchEvent(+ MarimoIncomingMessageEvent.create({+ bubbles: false, // only the intended target gets the message+ composed: true,+ detail: {+ objectId: objectId,+ message: message,+ buffers: buffers ? buffers.map(base64ToDataView) : undefined,+ },+ }),+ );+ });+ }+ }+/*** Broadcast `value` to instances of the component with id `objectId`*@@ -148,7 +181,7 @@ export class UIElementRegistry {entry.elements.forEach((element) => {if (element !== initiator) {element.dispatchEvent(- new CustomEvent(marimoValueUpdateEvent, {+ MarimoValueUpdateEvent.create({bubbles: false, // only the intended target gets the messagecomposed: true,detail: { value: value, element: element },@@ -158,7 +191,7 @@ export class UIElementRegistry {});document.dispatchEvent(- new CustomEvent(marimoValueReadyEvent, {+ MarimoValueReadyEvent.create({bubbles: true,composed: true,detail: {diff --git a/frontend/src/core/islands/main.ts b/frontend/src/core/islands/main.tsindex 460be88427..7b41c2dae5 100644--- a/frontend/src/core/islands/main.ts+++ b/frontend/src/core/islands/main.ts@@ -27,7 +27,9 @@ import { defineCustomElement } from "../dom/defineCustomElement";import { MarimoIslandElement } from "./components/web-components";import { RuntimeState } from "../kernel/RuntimeState";import { sendComponentValues } from "../network/requests";-import { RequestId } from "../network/DeferredRequestRegistry";+import type { RequestId } from "../network/DeferredRequestRegistry";+import { UI_ELEMENT_REGISTRY } from "../dom/uiregistry";+import type { UIElementId } from "../cells/ids";/*** Main entry point for the js bundle for embedded marimo apps.@@ -93,6 +95,14 @@ export async function initialize() {return;case "interrupted":return;+ case "send-ui-element-message":+ UI_ELEMENT_REGISTRY.broadcastMessage(+ msg.data.ui_element as UIElementId,+ msg.data.message,+ msg.data.buffers,+ );+ return;+case "remove-ui-elements":handleRemoveUIElements(msg.data);return;diff --git a/frontend/src/core/kernel/RuntimeState.ts b/frontend/src/core/kernel/RuntimeState.tsindex f714e7cd63..2533631bc8 100644--- a/frontend/src/core/kernel/RuntimeState.ts+++ b/frontend/src/core/kernel/RuntimeState.ts@@ -1,10 +1,10 @@/* Copyright 2024 Marimo. All rights reserved. */import {- marimoValueReadyEvent,- MarimoValueReadyEventType,+ MarimoValueReadyEvent,+ type MarimoValueReadyEventType,} from "../dom/events";-import { UI_ELEMENT_REGISTRY, UIElementRegistry } from "../dom/uiregistry";-import { RunRequests } from "../network/types";+import { UI_ELEMENT_REGISTRY, type UIElementRegistry } from "../dom/uiregistry";+import type { RunRequests } from "../network/types";import { Logger } from "@/utils/Logger";/**@@ -47,7 +47,10 @@ export class RuntimeState {return;}this._sendComponentValues = sendComponentValues;- document.addEventListener(marimoValueReadyEvent, this.handleReadyEvent);+ document.addEventListener(+ MarimoValueReadyEvent.TYPE,+ this.handleReadyEvent,+ );this.hasStarted = true;}@@ -59,7 +62,10 @@ export class RuntimeState {Logger.warn("RuntimeState already stopped");return;}- document.removeEventListener(marimoValueReadyEvent, this.handleReadyEvent);+ document.removeEventListener(+ MarimoValueReadyEvent.TYPE,+ this.handleReadyEvent,+ );this.hasStarted = false;}diff --git a/frontend/src/core/kernel/__tests__/RuntimeState.test.ts b/frontend/src/core/kernel/__tests__/RuntimeState.test.tsindex 49b3ea6437..ba00e13b45 100644--- a/frontend/src/core/kernel/__tests__/RuntimeState.test.ts+++ b/frontend/src/core/kernel/__tests__/RuntimeState.test.ts@@ -1,9 +1,16 @@/* Copyright 2024 Marimo. All rights reserved. */-import { marimoValueReadyEvent } from "@/core/dom/events";import { UIElementRegistry } from "@/core/dom/uiregistry";-import { describe, beforeEach, expect, vi, test, MockedFunction } from "vitest";+import {+ describe,+ beforeEach,+ expect,+ vi,+ test,+ type MockedFunction,+} from "vitest";import { RuntimeState } from "../RuntimeState";-import { RunRequests } from "@/core/network/types";+import type { RunRequests } from "@/core/network/types";+import { MarimoValueReadyEvent } from "@/core/dom/events";const addEventListenerSpy = vi.spyOn(document, "addEventListener");const removeEventListenerSpy = vi.spyOn(document, "removeEventListener");@@ -27,7 +34,7 @@ describe("RuntimeState", () => {test("start should register event listener", () => {runtimeState.start(mockSendComponentValues);expect(addEventListenerSpy).toHaveBeenCalledWith(- marimoValueReadyEvent,+ MarimoValueReadyEvent.TYPE,expect.any(Function),);});@@ -42,7 +49,7 @@ describe("RuntimeState", () => {runtimeState.start(mockSendComponentValues);runtimeState.stop();expect(removeEventListenerSpy).toHaveBeenCalledWith(- marimoValueReadyEvent,+ MarimoValueReadyEvent.TYPE,expect.any(Function),);});diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsxindex 6893094118..05ddd53842 100644--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx@@ -32,12 +32,13 @@ import {import { queryParamHandlers } from "../kernel/queryParamHandlers";import type { JsonString } from "@/utils/json/base64";import { useDatasetsActions } from "../datasets/state";-import { RequestId } from "../network/DeferredRequestRegistry";-import { VariableName } from "../variables/types";-import { CellId } from "../cells/ids";+import type { RequestId } from "../network/DeferredRequestRegistry";+import type { VariableName } from "../variables/types";+import type { CellId, UIElementId } from "../cells/ids";import { kioskModeAtom } from "../mode";import { focusAndScrollCellOutputIntoView } from "../cells/scrollCellIntoView";import { capabilitiesAtom } from "../config/capabilities";+import { UI_ELEMENT_REGISTRY } from "../dom/uiregistry";/*** WebSocket that connects to the Marimo kernel and handles incoming messages.@@ -87,6 +88,14 @@ export function useMarimoWebSocket(opts: {case "interrupted":return;+ case "send-ui-element-message":+ UI_ELEMENT_REGISTRY.broadcastMessage(+ msg.data.ui_element as UIElementId,+ msg.data.message,+ msg.data.buffers,+ );+ return;+case "remove-ui-elements":handleRemoveUIElements(msg.data);return;diff --git a/frontend/src/plugins/core/registerReactComponent.tsx b/frontend/src/plugins/core/registerReactComponent.tsxindex 6100f704f5..f831fc1ccf 100644--- a/frontend/src/plugins/core/registerReactComponent.tsx+++ b/frontend/src/plugins/core/registerReactComponent.tsx@@ -9,28 +9,24 @@*/import React, {createRef,- ReactNode,- SetStateAction,+ type ReactNode,+ type SetStateAction,Suspense,useEffect,useImperativeHandle,useMemo,useState,} from "react";-import ReactDOM, { Root } from "react-dom/client";+import ReactDOM, { type Root } from "react-dom/client";-import {- createInputEvent,- marimoValueUpdateEvent,- MarimoValueUpdateEventType,-} from "@/core/dom/events";+import { createInputEvent, MarimoValueUpdateEvent } from "@/core/dom/events";import { defineCustomElement } from "../../core/dom/defineCustomElement";import {parseAttrValue,parseDataset,parseInitialValue,} from "../../core/dom/htmlUtils";-import { IPlugin } from "../types";+import type { IPlugin } from "../types";import { Objects } from "../../utils/objects";import { renderError } from "./BadPlugin";import { renderHTML } from "./RenderHTML";@@ -39,12 +35,13 @@ import { Logger } from "../../utils/Logger";import { useTheme } from "@/theme/useTheme";import { FUNCTIONS_REGISTRY } from "@/core/functions/FunctionRegistry";import { getUIElementObjectId } from "@/core/dom/ui-element";-import { PluginFunctions } from "./rpc";-import { ZodSchema } from "zod";+import type { PluginFunctions } from "./rpc";+import type { ZodSchema } from "zod";import useEvent from "react-use-event-hook";import { Functions } from "@/utils/functions";import { StyleNamespace } from "@/theme/namespace";import { UIElementRegistry } from "@/core/dom/uiregistry";+import { useEventListener } from "@/hooks/useEventListener";export interface PluginSlotHandle {/**@@ -100,14 +97,16 @@ function PluginSlotInternal<T>(},}));+ // Listen to value updates+ useEventListener(hostElement, MarimoValueUpdateEvent.TYPE, (e) => {+ if (e.detail.element === hostElement) {+ setValue(e.detail.value as T);+ }+ });++ // We create a mutation observer to listen for changes to the host element's attributes+ // and update the plugin's data accordinglyuseEffect(() => {- const handleValue = (e: MarimoValueUpdateEventType) => {- if (e.detail.element === hostElement) {- setValue(e.detail.value as T);- }- };- // We create a mutation observer to listen for changes to the host element's attributes- // and update the plugin's data accordinglyconst observer = new MutationObserver((mutations) => {const hasAttributeMutation = mutations.some((mutation) =>@@ -119,15 +118,13 @@ function PluginSlotInternal<T>(}});- // Create listeners- hostElement.addEventListener(marimoValueUpdateEvent, handleValue);+ // Create listenerobserver.observe(hostElement, {attributes: true, // configure it to listen to attribute changes});return () => {- // Remove listeners- hostElement.removeEventListener(marimoValueUpdateEvent, handleValue);+ // Remove listenerobserver.disconnect();};}, [hostElement, plugin.validator]);diff --git a/frontend/src/plugins/impl/DictPlugin.tsx b/frontend/src/plugins/impl/DictPlugin.tsxindex e15fe02d24..59e8f7ed20 100644--- a/frontend/src/plugins/impl/DictPlugin.tsx+++ b/frontend/src/plugins/impl/DictPlugin.tsx@@ -4,10 +4,10 @@ import { z } from "zod";import { getUIElementObjectId } from "../../core/dom/ui-element";import {- marimoValueInputEvent,- MarimoValueInputEventType,+ MarimoValueInputEvent,+ type MarimoValueInputEventType,} from "../../core/dom/events";-import { IPlugin, IPluginProps, Setter } from "../types";+import type { IPlugin, IPluginProps, Setter } from "../types";// key => value updatestype T = Record<string, unknown> | null;@@ -71,9 +71,9 @@ const Dict = ({return nextValue;});};- document.addEventListener(marimoValueInputEvent, handleUpdate);+ document.addEventListener(MarimoValueInputEvent.TYPE, handleUpdate);return () => {- document.removeEventListener(marimoValueInputEvent, handleUpdate);+ document.removeEventListener(MarimoValueInputEvent.TYPE, handleUpdate);};}, [elementIds, setValue]);diff --git a/frontend/src/plugins/impl/FormPlugin.tsx b/frontend/src/plugins/impl/FormPlugin.tsxindex 30acc4e951..ebd254adb0 100644--- a/frontend/src/plugins/impl/FormPlugin.tsx+++ b/frontend/src/plugins/impl/FormPlugin.tsx@@ -4,10 +4,10 @@ import { z } from "zod";import { getUIElementObjectId, isUIElement } from "../../core/dom/ui-element";import {- marimoValueInputEvent,- MarimoValueInputEventType,+ MarimoValueInputEvent,+ type MarimoValueInputEventType,} from "@/core/dom/events";-import { Setter } from "../types";+import type { Setter } from "../types";import { Button } from "../../components/ui/button";import { UI_ELEMENT_REGISTRY } from "@/core/dom/uiregistry";import { cn } from "../../utils/cn";@@ -247,9 +247,9 @@ const Form = ({setInternalValue(e.detail.value);}};- document.addEventListener(marimoValueInputEvent, handleUpdate);+ document.addEventListener(MarimoValueInputEvent.TYPE, handleUpdate);return () => {- document.removeEventListener(marimoValueInputEvent, handleUpdate);+ document.removeEventListener(MarimoValueInputEvent.TYPE, handleUpdate);};}, [elementId, setValue]);diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsxindex 60b7c1aa6a..53d058a7bd 100644--- a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx+++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx@@ -2,13 +2,19 @@/* eslint-disable @typescript-eslint/no-explicit-any */import { z } from "zod";-import { IPlugin, IPluginProps } from "@/plugins/types";+import type { IPluginProps } from "@/plugins/types";import { useEffect, 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";+import { rpc } from "@/plugins/core/rpc";+import type { AnyModel, EventHandler } from "./types";+import { Logger } from "@/utils/Logger";+import { useEventListener } from "@/hooks/useEventListener";+import { MarimoIncomingMessageEvent } from "@/core/dom/events";interface Data {jsUrl: string;@@ -17,20 +23,30 @@ interface Data {type T = Record<string, any>;-export class AnyWidgetPlugin implements IPlugin<T, Data> {- tagName = "marimo-anywidget";-- validator = z.object({- jsUrl: z.string(),- css: z.string().nullish(),- });-- render(props: IPluginProps<T, Data>): JSX.Element {- return <AnyWidgetSlot {...props} />;- }-}+// eslint-disable-next-line @typescript-eslint/consistent-type-definitions+type PluginFunctions = {+ send_to_widget: <T>(req: {+ content?: any;+ }) => Promise<null | undefined>;+};-const AnyWidgetSlot = (props: IPluginProps<T, Data>) => {+export const AnyWidgetPlugin = createPlugin<T>("marimo-anywidget")+ .withData(+ z.object({+ jsUrl: z.string(),+ css: z.string().nullish(),+ }),+ )+ .withFunctions<PluginFunctions>({+ send_to_widget: rpc+ .input(z.object({ content: z.any() }))+ .output(z.null().optional()),+ })+ .renderer((props) => <AnyWidgetSlot {...props} />);++type Props = IPluginProps<T, Data, PluginFunctions>;++const AnyWidgetSlot = (props: Props) => {const { css, jsUrl } = props.data;// JS is an ESM file with a render function on it// export function render({ model, el }) {@@ -80,11 +96,20 @@ const LoadedSlot = ({value,setValue,render,-}: IPluginProps<T, Data> & {+ functions,+ host,+}: Props & {render: ({ model, el }: any) => void;}) => {const ref = useRef<HTMLDivElement>(null);- const model = useRef<Model<T>>(new Model(value, setValue));+ const model = useRef<Model<T>>(+ new Model(value, setValue, functions.send_to_widget),+ );++ // Listen to incoming messages+ useEventListener(host, MarimoIncomingMessageEvent.TYPE, (e) => {+ model.current.receiveCustomMessage(e.detail.message, e.detail.buffers);+ });useOnMount(() => {if (!ref.current) {@@ -104,28 +129,68 @@ const LoadedSlot = ({return <div ref={ref} />;};-class Model<T extends Record<string, any>> {+class Model<T extends Record<string, any>> implements AnyModel<T> {constructor(- public data: T,- public onChange: (value: T) => void,+ private data: T,+ private onChange: (value: T) => void,+ private send_to_widget: (req: { content?: any }) => Promise<+ null | undefined+ >,) {}- private listeners: Record<string, Array<(value: any) => void>> = {};+ off(eventName?: string | null, callback?: EventHandler | null): void {+ if (!eventName) {+ this.listeners = {};+ return;+ }- public get<K extends keyof T>(key: K): T[K] {+ if (!callback) {+ this.listeners[eventName] = new Set();+ return;+ }++ this.listeners[eventName]?.delete(callback);+ }++ send(+ content: any,+ callbacks?: any,+ buffers?: ArrayBuffer[] | ArrayBufferView[],+ ): void {+ if (buffers) {+ Logger.warn("buffers not supported in marimo anywidget.send");+ }+ this.send_to_widget({ content }).then(callbacks);+ }++ widget_manager = new Proxy(+ {},+ {+ get() {+ throw new Error("widget_manager not supported in marimo");+ },+ set() {+ throw new Error("widget_manager not supported in marimo");+ },+ },+ );++ private listeners: Record<string, Set<EventHandler>> = {};++ get<K extends keyof T>(key: K): T[K] {return this.data[key];}- public set<K extends keyof T>(key: K, value: T[K]): void {+ set<K extends keyof T>(key: K, value: T[K]): void {this.data = { ...this.data, [key]: value };this.emit(`change:${key as K & string}`, value);}- public save_changes(): void {+ save_changes(): void {this.onChange(this.data);}- public updateAndEmitDiffs(value: T): void {+ updateAndEmitDiffs(value: T): void {Object.keys(value).forEach((key) => {const k = key as keyof T;if (!dequal(this.data[k], value[k])) {@@ -134,14 +199,19 @@ class Model<T extends Record<string, any>> {});}- public on<K extends keyof T>(- event: `change:${K & string}`,- callback: (value: T[K]) => void,- ): void {- if (!this.listeners[event]) {- this.listeners[event] = [];+ /**+ * When receiving a message from the backend.+ * We want to notify all listeners with `msg:custom`+ */+ receiveCustomMessage(message: any, buffers?: DataView[]): void {+ this.listeners["msg:custom"]?.forEach((cb) => cb(message, buffers));+ }++ on(eventName: string, callback: EventHandler): void {+ if (!this.listeners[eventName]) {+ this.listeners[eventName] = new Set();}- this.listeners[event].push(callback);+ this.listeners[eventName].add(callback);}private emit<K extends keyof T>(event: `change:${K & string}`, value: T[K]) {diff --git a/frontend/src/plugins/impl/anywidget/types.ts b/frontend/src/plugins/impl/anywidget/types.tsnew file mode 100644index 0000000000..43470079f2--- /dev/null+++ b/frontend/src/plugins/impl/anywidget/types.ts@@ -0,0 +1,38 @@+/* Copyright 2024 Marimo. All rights reserved. */+/* 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++export type EventHandler = (...args: any[]) => void;+type ObjectHash = Record<string, any>;+export type ChangeEventHandler<Payload> = (_: unknown, value: Payload) => void;+type LiteralUnion<T, U = string> = T | (U & {});++export interface AnyModel<T extends ObjectHash = ObjectHash> {+ get<K extends keyof T>(key: K): T[K];+ set<K extends keyof T>(key: K, value: T[K]): void;+ off<K extends keyof T>(+ eventName?: LiteralUnion<`change:${K & string}` | "msg:custom"> | null,+ callback?: EventHandler | null,+ ): void;+ on(+ eventName: "msg:custom",+ callback: (msg: any, buffers: DataView[]) => void,+ ): void;+ on<K extends `change:${keyof T & string}`>(+ eventName: K,+ callback: K extends `change:${infer Key}`+ ? ChangeEventHandler<T[Key]>+ : never,+ ): void;+ on(eventName: string, callback: EventHandler): void;+ save_changes(): void;+ send(+ content: any,+ callbacks?: any,+ buffers?: ArrayBuffer[] | ArrayBufferView[],+ ): void;+ widget_manager: {};+}diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.tsindex b2fc75e979..e135b59f39 100644--- a/frontend/src/plugins/plugins.ts+++ b/frontend/src/plugins/plugins.ts@@ -18,9 +18,9 @@ import { SliderPlugin } from "./impl/SliderPlugin";import { SwitchPlugin } from "./impl/SwitchPlugin";import { TextInputPlugin } from "./impl/TextInputPlugin";import { TextAreaPlugin } from "./impl/TextAreaPlugin";-import { IPlugin } from "./types";+import type { IPlugin } from "./types";import { DataTablePlugin } from "./impl/DataTablePlugin";-import { IStatelessPlugin } from "./stateless-plugin";+import type { IStatelessPlugin } from "./stateless-plugin";import { AccordionPlugin } from "./layout/AccordionPlugin";import { CalloutPlugin } from "./layout/CalloutPlugin";import { JsonOutputPlugin } from "./layout/JsonOutputPlugin";@@ -72,7 +72,7 @@ export const UI_PLUGINS: Array<IPlugin<any, unknown>> = [DataExplorerPlugin,DataFramePlugin,LazyPlugin,- new AnyWidgetPlugin(),+ AnyWidgetPlugin,];// List of output / layout pluginsdiff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.pyindex 94216bc20a..d10fab1289 100644--- a/marimo/_cli/development/commands.py+++ b/marimo/_cli/development/commands.py@@ -64,6 +64,7 @@ def _generate_schema() -> dict[str, Any]:ops.CellOp,ops.HumanReadableStatus,ops.FunctionCallResult,+ ops.SendUIElementMessage,ops.RemoveUIElements,ops.Interrupted,ops.CompletedRun,diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex 3f10d969c2..89b7edcac5 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -308,6 +308,16 @@ class RemoveUIElements(Op):cell_id: CellId_t+@dataclass+class SendUIElementMessage(Op):+ """Send a message to a UI element."""++ name: ClassVar[str] = "send-ui-element-message"+ ui_element: str+ message: JSONType+ buffers: Optional[Sequence[str]]++@dataclassclass Interrupted(Op):"""Written when the kernel is interrupted by the user."""@@ -568,6 +578,7 @@ MessageOperation = Union[# Cell operationsCellOp,FunctionCallResult,+ SendUIElementMessage,RemoveUIElements,# Notebook operationsReload,diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.pyindex e5bef61d98..b51a2d6389 100644--- a/marimo/_plugins/ui/_core/ui_element.py+++ b/marimo/_plugins/ui/_core/ui_element.py@@ -2,6 +2,7 @@from __future__ import annotationsimport abc+import base64import copyimport uuidimport weakref@@ -12,6 +13,7 @@ from typing import (Callable,Generic,Optional,+ Sequence,TypeVar,cast,)@@ -389,6 +391,24 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):on_change=on_change,)+ def send_message(+ self, message: JSONType, buffers: Optional[Sequence[bytes]]+ ) -> None:+ """+ Send a message to the element rendered on the frontend+ from the backend.+ """++ from marimo._messaging.ops import SendUIElementMessage++ SendUIElementMessage(+ ui_element=self._id,+ message=message,+ buffers=[+ base64.b64encode(buffer).decode() for buffer in (buffers or [])+ ],+ ).broadcast()+def _update(self, value: S) -> None:"""Update value, given a value from the frontenddiff --git a/marimo/_plugins/ui/_impl/from_anywidget.py b/marimo/_plugins/ui/_impl/from_anywidget.pyindex 775a3c3fb3..3881d6b086 100644--- a/marimo/_plugins/ui/_impl/from_anywidget.py+++ b/marimo/_plugins/ui/_impl/from_anywidget.py@@ -2,17 +2,22 @@from __future__ import annotationsimport weakref-from typing import TYPE_CHECKING, Any, Dict+from dataclasses import dataclass+from typing import TYPE_CHECKING, Any, Dict, Optionalimport marimo._output.data.data as mo_data+from marimo import _loggersfrom marimo._output.rich_help import mddocfrom marimo._plugins.ui._core.ui_element import UIElement+from marimo._runtime.functions import Functionif TYPE_CHECKING:from anywidget import ( # type: ignore [import-not-found,unused-ignore] # noqa: E501AnyWidget,)+LOGGER = _loggers.marimo_logger()+# Weak dictionary# When the widget is deleted, the UIElement will be deleted as well@@ -29,6 +34,12 @@ def from_anywidget(widget: "AnyWidget") -> UIElement[Any, Any]:T = Dict[str, Any]+@dataclass+class SendToWidgetArgs:+ content: Any+ buffers: Optional[Any] = None++@mddocclass anywidget(UIElement[T, T]):"""@@ -89,6 +100,8 @@ class anywidget(UIElement[T, T]):js: str = widget._esm if hasattr(widget, "_esm") else "" # type: ignore [unused-ignore] # noqa: E501css: str = widget._css if hasattr(widget, "_css") else "" # type: ignore [unused-ignore] # noqa: E501+ self.widget.comm = _maybe_create_comm(self)+super().__init__(component_name="marimo-anywidget",initial_value=args,@@ -98,11 +111,56 @@ class anywidget(UIElement[T, T]):"css": css,},on_change=on_change,+ functions=(+ Function(+ name="send_to_widget",+ arg_cls=SendToWidgetArgs,+ function=self._receive_from_frontend,+ ),+ ),)+ def _send_to_frontend(+ self, value: T, buffers: Optional[Any] = None+ ) -> None:+ self.send_message(value, buffers)++ def _receive_from_frontend(self, args: SendToWidgetArgs) -> None:+ self.widget._handle_custom_msg(args.content, args.buffers)+def _convert_value(self, value: T) -> T:return value# Proxy all the widget's attributesdef __getattr__(self, name: str) -> Any:return getattr(self.widget, name)+++def _maybe_create_comm(widget: "anywidget") -> Any:+ try:+ from comm.base_comm import BaseComm # type: ignore++ class MarimoComm(BaseComm): # type: ignore+ def publish_msg(+ self,+ msg_type: str,+ data: Any = None,+ metadata: Any = None,+ buffers: Any = None,+ **keys: Any,+ ) -> None:+ del metadata+ del keys+ if (+ msg_type == "comm_msg"+ and "method" in data+ and data["method"] == "custom"+ ):+ if "content" in data:+ widget._send_to_frontend(data["content"], buffers)+ else:+ LOGGER.warning("No content in custom message")++ return MarimoComm()+ except ImportError:+ LOGGER.warning("Comm is not available")diff --git a/marimo/_smoke_tests/anywidget/maplibre.py b/marimo/_smoke_tests/anywidget/maplibre.pynew file mode 100644index 0000000000..994aaca3db--- /dev/null+++ b/marimo/_smoke_tests/anywidget/maplibre.py@@ -0,0 +1,99 @@+# Copyright 2024 Marimo. All rights reserved.+import marimo++__generated_with = "0.7.2"+app = marimo.App(width="medium")+++def __():+ import marimo as mo+ import functools+ return functools, mo+++def __():+ from maplibre.controls import NavigationControl, ScaleControl+ from maplibre.ipywidget import MapOptions, MapWidget+ return MapOptions, MapWidget, NavigationControl, ScaleControl+++def __():+ deck_grid_layer = {+ "@@type": "GridLayer",+ "id": "GridLayer",+ "data": "https://raw.githubusercontent.com/visgl/deck.gl-data/master/website/sf-bike-parking.json",+ "extruded": True,+ "getPosition": "@@=COORDINATES",+ "getColorWeight": "@@=SPACES",+ "getElevationWeight": "@@=SPACES",+ "elevationScale": 4,+ "cellSize": 200,+ "pickable": True,+ }+ return deck_grid_layer,+++def __(MapOptions):+ map_options = MapOptions(+ center=(-122.4, 37.74),+ zoom=12,+ hash=True,+ pitch=40,+ )+ return map_options,+++def __(MapWidget, NavigationControl, deck_grid_layer, map_options, mo):+ m = MapWidget(map_options)+ m.use_message_queue(False)+ m.add_control(NavigationControl())+ m.add_deck_layers([deck_grid_layer])+ m = mo.ui.anywidget(m)+ m+ return m,+++def __(mo):+ add_control_button = mo.ui.run_button(label="add scale control")+ add_control_button+ return add_control_button,+++def __(ScaleControl, add_control_button, m):+ if add_control_button.value:+ m.add_control(ScaleControl())+ return+++def __(m):+ m.clicked+ return+++def __(m):+ m.zoom+ return+++def __(m):+ m.center+ return+++def __():+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_smoke_tests/anywidget/mosaic.py b/marimo/_smoke_tests/anywidget/mosaic.pynew file mode 100644index 0000000000..a98284acf8--- /dev/null+++ b/marimo/_smoke_tests/anywidget/mosaic.py@@ -0,0 +1,41 @@+# Copyright 2024 Marimo. All rights reserved.+import marimo++__generated_with = "0.7.2"+app = marimo.App(width="medium")+++def __(__file__):+ import pandas as pd+ import marimo as mo+ import os+ import yaml++ dir_path = os.path.dirname(os.path.realpath(__file__))+++ from mosaic_widget import MosaicWidget++ weather = pd.read_csv(+ "https://uwdata.github.io/mosaic-datasets/data/seattle-weather.csv",+ parse_dates=["date"],+ )++ # Load weather spec, remove data key to ensure load from Pandas+ with open(dir_path + "/weather.yaml") as f:+ spec = yaml.safe_load(f)+ spec.pop("data")++ w = mo.ui.anywidget(MosaicWidget(spec, data={"weather": weather}))+ return MosaicWidget, dir_path, f, mo, os, pd, spec, w, weather, yaml+++def __(w):+ w+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_smoke_tests/anywidget/weather.yaml b/marimo/_smoke_tests/anywidget/weather.yamlnew file mode 100644index 0000000000..5457de5e71--- /dev/null+++ b/marimo/_smoke_tests/anywidget/weather.yaml@@ -0,0 +1,55 @@+data:+ weather: { file: data/seattle-weather.parquet }+params:+ click: { select: single }+ domain: [sun, fog, drizzle, rain, snow]+ colors: ['#e7ba52', '#a7a7a7', '#aec7e8', '#1f77b4', '#9467bd']+vconcat:+- hconcat:+ - plot:+ - mark: dot+ data: { from: weather, filterBy: $click }+ x: { dateMonthDay: date }+ y: temp_max+ fill: weather+ r: precipitation+ fillOpacity: 0.7+ - select: intervalX+ as: $range+ brush: { fill: none, stroke: '#888' }+ - select: highlight+ by: $range+ fill: '#ccc'+ fillOpacity: 0.2+ - legend: color+ as: $click+ columns: 1+ xyDomain: Fixed+ colorDomain: $domain+ colorRange: $colors+ rDomain: Fixed+ rRange: [2, 10]+ width: 680+ height: 300+- plot:+ - mark: barX+ data: { from: weather }+ x: { count: }+ y: weather+ fill: '#ccc'+ fillOpacity: 0.2+ - mark: barX+ data: { from: weather, filterBy: $range }+ x: { count: }+ y: weather+ fill: weather+ - select: toggleY+ as: $click+ - select: highlight+ by: $click+ xDomain: Fixed+ yDomain: $domain+ yLabel: null+ colorDomain: $domain+ colorRange: $colors+ width: 680diff --git a/marimo/_smoke_tests/bugs/1710.py b/marimo/_smoke_tests/bugs/1710.pyindex 8d5d961248..cb65bbaedc 100644--- a/marimo/_smoke_tests/bugs/1710.py+++ b/marimo/_smoke_tests/bugs/1710.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.import marimo__generated_with = "0.6.25"diff --git a/marimo/_smoke_tests/bugs/1711.py b/marimo/_smoke_tests/bugs/1711.pyindex 0fce81e78f..de489dfdaf 100644--- a/marimo/_smoke_tests/bugs/1711.py+++ b/marimo/_smoke_tests/bugs/1711.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.import marimo__generated_with = "0.6.25"diff --git a/marimo/_sql/sql.py b/marimo/_sql/sql.pyindex 81a67a9373..5a803e7cc6 100644--- a/marimo/_sql/sql.py+++ b/marimo/_sql/sql.py@@ -30,15 +30,15 @@ def sql(query: str) -> Any:import duckdb # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501if DependencyManager.has_polars():- df = duckdb.execute(query=query).pl()- t = table.table(df, selection=None, page_size=5, pagination=True)+ pl_df = duckdb.execute(query=query).pl()+ t = table.table(pl_df, selection=None, page_size=5, pagination=True)output.replace(t)- return df+ return pl_dfif DependencyManager.has_pandas():- df = duckdb.execute(query=query).df()- t = table.table(df, selection=None, page_size=5, pagination=True)+ pd_df = duckdb.execute(query=query).df()+ t = table.table(pd_df, selection=None, page_size=5, pagination=True)output.replace(t)- return df+ return pd_dfraise ModuleNotFoundError("pandas or polars is required to execute sql. "diff --git a/marimo/_tutorials/sql.py b/marimo/_tutorials/sql.pyindex beb943d068..2163e380ef 100644--- a/marimo/_tutorials/sql.py+++ b/marimo/_tutorials/sql.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.import marimo__generated_with = "0.7.1"diff --git a/openapi/api.yaml b/openapi/api.yamlindex 163f8505c9..74df98b1c2 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -1178,6 +1178,7 @@ components:oneOf:- $ref: '#/components/schemas/CellOp'- $ref: '#/components/schemas/FunctionCallResult'+ - $ref: '#/components/schemas/SendUIElementMessage'- $ref: '#/components/schemas/RemoveUIElements'- $ref: '#/components/schemas/Reload'- $ref: '#/components/schemas/Reconnected'@@ -1471,6 +1472,25 @@ components:required:- configtype: object+ SendUIElementMessage:+ properties:+ buffers:+ items:+ type: string+ nullable: true+ type: array+ message:+ $ref: '#/components/schemas/JSONType'+ name:+ enum:+ - send-ui-element-message+ type: string+ ui_element:+ type: string+ required:+ - ui_element+ - name+ type: objectSetCellConfigRequest:properties:configs:@@ -1699,7 +1719,7 @@ components:type: objectinfo:title: marimo API- version: 0.7.1+ version: 0.7.2openapi: 3.1.0paths:/@file/{filename_and_length}:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex 81f9ce56aa..fca178d88b 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -1202,6 +1202,7 @@ export interface components {MessageOperation:| components["schemas"]["CellOp"]| components["schemas"]["FunctionCallResult"]+ | components["schemas"]["SendUIElementMessage"]| components["schemas"]["RemoveUIElements"]| components["schemas"]["Reload"]| components["schemas"]["Reconnected"]@@ -1332,6 +1333,13 @@ export interface components {SaveUserConfigurationRequest: {config: components["schemas"]["MarimoConfig"];};+ SendUIElementMessage: {+ buffers?: string[] | null;+ message?: components["schemas"]["JSONType"];+ /** @enum {string} */+ name: "send-ui-element-message";+ ui_element: string;+ };SetCellConfigRequest: {configs: {[key: string]: {