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.

chore: panel FE refactor (#2723)

Myles Scolnickc9948dca8134
diff --git a/frontend/src/plugins/impl/panel/PanelPlugin.tsx b/frontend/src/plugins/impl/panel/PanelPlugin.tsx
index 5da1368e3c..c59e1de0c5 100644
--- a/frontend/src/plugins/impl/panel/PanelPlugin.tsx
+++ b/frontend/src/plugins/impl/panel/PanelPlugin.tsx
@@ -8,14 +8,68 @@ import { createPlugin } from "@/plugins/core/builder";
import { rpc } from "@/plugins/core/rpc";
import { useEventListener } from "@/hooks/useEventListener";
import { MarimoIncomingMessageEvent } from "@/core/dom/events";
+import { MessageSchema, extractBuffers, EventBuffer } from "./utils";
+import { useEvent } from "@dnd-kit/utilities";
-interface Data {
+interface BokehDocument {
+ create_json_patch: (events: unknown[]) => unknown;
+ apply_json_patch: (content: unknown, buffers: ArrayBuffer[]) => void;
+ on_change: (callback: (event: unknown) => void) => void;
+ _all_models: Set<string>;
+}
+
+interface RenderItems {
+ roots: Record<string, HTMLElement | null>;
+ [key: string]: unknown;
+}
+
+declare global {
+ interface Window {
+ Bokeh: {
+ embed: {
+ embed_items_notebook: (
+ docs_json: Record<string, unknown>,
+ render_items: unknown[],
+ ) => Promise<void>;
+ };
+ index: {
+ get_by_id: (id: string) => { model: { document: BokehDocument } };
+ };
+ protocol: {
+ Message: {
+ create: (
+ type: string,
+ metadata: Record<string, unknown>,
+ content: unknown,
+ ) => Record<string, unknown>;
+ };
+ Receiver: new () => {
+ consume: (data: ArrayBuffer | string) => void;
+ message: {
+ content: {
+ events?: Array<{
+ model?: { id?: string };
+ }>;
+ [key: string]: unknown;
+ };
+ buffers: ArrayBuffer[];
+ } | null;
+ };
+ };
+ };
+ }
+}
+
+interface PanelData {
extension: string | null;
- docs_json: Record<string, any>;
- render_json: Record<string, any>;
+ docs_json: Record<string, unknown>;
+ render_json: {
+ roots: Record<string, string>;
+ [key: string]: unknown;
+ };
}
-type T = Record<string, any>;
+type T = Record<string, unknown>;
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
type PluginFunctions = {
@@ -24,207 +78,179 @@ type PluginFunctions = {
>;
};
-declare global {
- const Bokeh: any;
-}
-
export const PanelPlugin = createPlugin<T>("marimo-panel")
.withData(
z.object({
extension: z.string().nullable(),
- docs_json: z.record(z.any()),
- render_json: z.record(z.any()),
+ docs_json: z.record(z.unknown()),
+ render_json: z
+ .object({
+ roots: z.record(z.string()),
+ })
+ .catchall(z.unknown()),
}),
)
.withFunctions<PluginFunctions>({
send_to_widget: rpc
- .input(z.object({ message: z.any(), buffers: z.array(z.any()) }))
+ .input(
+ z.object({
+ message: z.unknown(),
+ buffers: z.array(z.instanceof(ArrayBuffer)),
+ }),
+ )
.output(z.null().optional()),
})
.renderer((props) => <PanelSlot {...props} />);
-function isObject(obj: unknown): obj is object {
- const tp = typeof obj;
- return tp === "function" || (tp === "object" && !!obj);
-}
-
-function is_nullish(obj: unknown): obj is null | undefined {
- return obj == null;
-}
-
-function isPlainObject<T>(obj: unknown): obj is { [key: string]: T } {
- return (
- isObject(obj) && (is_nullish(obj.constructor) || obj.constructor === Object)
- );
-}
-
-function isBuffer(obj: unknown): obj is { buffer: ArrayBuffer } {
- return typeof obj === "object" && obj !== null && "to_base64" in obj;
-}
-function extract_buffers(value: unknown, buffers: ArrayBuffer[]): any {
- if (Array.isArray(value)) {
- for (const val of value) {
- extract_buffers(val, buffers);
- }
- } else if (value instanceof Map) {
- for (const key of value.keys()) {
- const v = value.get(key);
- extract_buffers(v, buffers);
- }
- } else if (isBuffer(value)) {
- const { buffer } = value;
- const id = buffers.length;
- buffers.push(buffer);
- return { id };
- } else if (isPlainObject(value)) {
- for (const key of Object.keys(value)) {
- const replaced = extract_buffers(value[key], buffers);
- if (replaced != null) {
- value[key] = replaced;
- }
- }
- }
+function isBokehLoaded() {
+ return window.Bokeh != null;
}
-type Props = IPluginProps<T, Data, PluginFunctions>;
-
const PanelSlot = (props: Props) => {
const { data, functions, host } = props;
- const { extension, docs_json, render_json } = data;
+ const { extension, docs_json: docsJson, render_json: renderJson } = data;
const ref = useRef<HTMLDivElement>(null);
- const blocked = useRef<boolean>(false);
- const doc = useRef<any>(null);
- const receiver = useRef<any>(null);
+ const docRef = useRef<BokehDocument | null>(null);
+ const receiverRef = useRef<InstanceType<
+ typeof window.Bokeh.protocol.Receiver
+ > | null>(null);
const [loaded, setLoaded] = useState<boolean>(false);
const [rendered, setRendered] = useState<string | null>(null);
- const event_buffer: any[] = [];
- let timeout = Date.now();
+ const processEvents = useEvent(() => {
+ if (!eventBufferRef.current || !docRef.current) {
+ return;
+ }
- const process_events = () => {
- const events = event_buffer.splice(0);
- const patch = doc.current.create_json_patch(events);
+ const events = eventBufferRef.current.getAndClear();
+ const patch = docRef.current.create_json_patch(events);
const message = {
- ...Bokeh.protocol.Message.create("PATCH-DOC", {}, patch),
+ ...window.Bokeh.protocol.Message.create("PATCH-DOC", {}, patch),
};
const buffers: ArrayBuffer[] = [];
- extract_buffers(message.content, buffers);
+ extractBuffers(message.content, buffers);
functions.send_to_widget({ message, buffers });
- };
+ });
+
+ const eventBufferRef = useRef<EventBuffer<unknown> | null>(
+ new EventBuffer(processEvents),
+ );
+ // Load the bokeh extension
useEffect(() => {
- if (loaded || rendered) {
+ // Already loaded
+ if (isBokehLoaded()) {
+ setLoaded(true);
return;
}
- let script: HTMLScriptElement;
- if (extension != null && extension.length > 0) {
- script = document.createElement("script");
+
+ // Load the extension
+ if (extension) {
+ const script = document.createElement("script");
script.innerHTML = extension;
document.head.append(script);
}
+ // Check if Bokeh is loaded every 10ms
const checkBokeh = setInterval(() => {
- if (window.Bokeh) {
+ if (isBokehLoaded()) {
setLoaded(true);
clearInterval(checkBokeh);
}
}, 10);
- return () => {
- clearInterval(checkBokeh);
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [extension]);
+ return () => clearInterval(checkBokeh);
+ }, [extension, setLoaded]);
- // Listen to incoming messages
+ // Listen for incoming messages
useEventListener(host, MarimoIncomingMessageEvent.TYPE, (e) => {
- // const doc_id = Object.keys(docs_json)[0];
- // const metadata = e.detail.metadata;
- const buffers = e.detail.buffers;
if (e.detail.message == null) {
return;
}
+
const message = MessageSchema.parse(e.detail.message);
- if (message.content.type === "ACK") {
- if (event_buffer.length > 0) {
- process_events();
- timeout = Date.now();
- } else {
- blocked.current = false;
+ const buffers = e.detail.buffers;
+ const receiver = receiverRef.current;
+ const doc = docRef.current;
+
+ if (!message.content) {
+ return;
+ }
+
+ if (!receiver || !doc) {
+ return;
+ }
+
+ // Handle ACK messages
+ if (typeof message.content !== "string") {
+ if (eventBufferRef.current && eventBufferRef.current.size() > 0) {
+ processEvents();
}
return;
}
+
+ // Handle non-ACK messages
const content = message.content;
if (content.length > 0) {
- receiver.current.consume(content);
+ receiver.consume(content);
} else if (buffers !== undefined && buffers.length > 0) {
- receiver.current.consume(buffers[0].buffer);
+ receiver.consume(buffers[0].buffer);
} else {
return;
}
- const comm_msg = receiver.current.message;
- if (comm_msg != null && Object.keys(comm_msg.content).length > 0) {
- if (comm_msg.content.events !== undefined) {
- comm_msg.content.events = comm_msg.content.events.filter((e: any) =>
- doc.current._all_models.has(e.model.id),
+
+ const commMessage = receiver.message;
+ if (commMessage != null && Object.keys(commMessage.content).length > 0) {
+ if (commMessage.content.events !== undefined) {
+ commMessage.content.events = commMessage.content.events.filter(
+ (e: any) => doc._all_models.has(e.model.id),
);
}
- doc.current.apply_json_patch(comm_msg.content, comm_msg.buffers);
+ doc.apply_json_patch(commMessage.content, commMessage.buffers);
}
});
+ // Embed the items on the first render
useEffect(() => {
- const doc_id = Object.keys(docs_json)[0];
- if (!loaded || rendered === doc_id) {
+ const docId = Object.keys(docsJson)[0];
+
+ // Skip if not loaded or already rendered
+ if (!loaded || rendered === docId) {
return;
}
- event_buffer.length = 0;
-
- const sendEvent = (event: any) => {
- event_buffer.push(event);
- if (!blocked.current || Date.now() > timeout) {
- setTimeout(() => process_events(), 50);
- blocked.current = true;
- // eslint-disable-next-line react-hooks/exhaustive-deps
- timeout = Date.now() + 5000;
- }
- };
const embedItems = async () => {
- const render_item = { ...render_json };
- const roots: Record<string, HTMLElement | null> = {};
- for (const model_id of Object.keys(render_json.roots)) {
- const root_id = render_json.roots[model_id];
+ const renderItem: RenderItems = {
+ ...renderJson,
+ roots: {},
+ };
+ for (const model_id of Object.keys(renderJson.roots)) {
+ const root_id = renderJson.roots[model_id];
if (ref.current) {
const el = ref.current.querySelector(`#${root_id}`);
- roots[model_id] = el as HTMLElement | null;
+ renderItem.roots[model_id] = el as HTMLElement | null;
}
}
- render_item.roots = roots;
- const model_id = Object.keys(roots)[0];
- await Bokeh.embed.embed_items_notebook(docs_json, [render_item]);
- doc.current = Bokeh.index.get_by_id(model_id).model.document;
- receiver.current = new Bokeh.protocol.Receiver();
- doc.current.on_change(sendEvent);
- setRendered(doc_id);
+ const modelId = Object.keys(renderItem.roots)[0];
+ await window.Bokeh.embed.embed_items_notebook(docsJson, [renderItem]);
+ docRef.current = window.Bokeh.index.get_by_id(modelId).model.document;
+ receiverRef.current = new window.Bokeh.protocol.Receiver();
+ docRef.current.on_change((event) => eventBufferRef.current?.add(event));
+ setRendered(docId);
};
+
embedItems();
- }, [docs_json, functions, loaded, render_json, rendered]);
+ }, [docsJson, loaded, renderJson, rendered]);
return (
<div ref={ref}>
- {Object.keys(render_json.roots).map((model_id) => {
- const root_id = render_json.roots[model_id];
- return (
- <div key={root_id} id={root_id}>
- <div data-root-id={root_id} style={{ display: "contents" }} />
- </div>
- );
- })}
+ {Object.values(renderJson.roots).map((rootId) => (
+ <div key={rootId} id={rootId}>
+ <div data-root-id={rootId} style={{ display: "contents" }} />
+ </div>
+ ))}
</div>
);
};
-const MessageSchema = z.object({
- content: z.any(),
-});
+type Props = IPluginProps<T, PanelData, PluginFunctions>;
diff --git a/frontend/src/plugins/impl/panel/__tests__/utils.test.ts b/frontend/src/plugins/impl/panel/__tests__/utils.test.ts
new file mode 100644
index 0000000000..45f37d7372
--- /dev/null
+++ b/frontend/src/plugins/impl/panel/__tests__/utils.test.ts
@@ -0,0 +1,119 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { MessageSchema, extractBuffers, EventBuffer } from "../utils";
+
+describe("MessageSchema", () => {
+ it("should validate ACK message", () => {
+ const result = MessageSchema.safeParse({ content: { type: "ACK" } });
+ expect(result.success).toBe(true);
+ });
+
+ it("should validate string message", () => {
+ const result = MessageSchema.safeParse({ content: "Hello" });
+ expect(result.success).toBe(true);
+ });
+
+ it("should reject invalid message", () => {
+ const result = MessageSchema.safeParse({ content: { type: "INVALID" } });
+ expect(result.success).toBe(false);
+ });
+});
+
+describe("extractBuffers", () => {
+ it("should extract ArrayBuffer and replace with id", () => {
+ const buffer = new ArrayBuffer(8);
+ const input = { data: buffer };
+ const buffers: ArrayBuffer[] = [];
+
+ const result = extractBuffers(input, buffers);
+
+ expect(result).toEqual({ data: { id: 0 } });
+ expect(buffers).toEqual([buffer]);
+ });
+
+ it("should handle nested objects and arrays", () => {
+ const buffer1 = new ArrayBuffer(8);
+ const buffer2 = new ArrayBuffer(16);
+ const input = {
+ nested: {
+ array: [1, buffer1, { buf: buffer2 }],
+ },
+ };
+ const buffers: ArrayBuffer[] = [];
+
+ const result = extractBuffers(input, buffers);
+
+ expect(result).toEqual({
+ nested: {
+ array: [1, { id: 0 }, { buf: { id: 1 } }],
+ },
+ });
+ expect(buffers).toEqual([buffer1, buffer2]);
+ });
+
+ it("should handle Map objects", () => {
+ const buffer = new ArrayBuffer(8);
+ const input = new Map([["key", buffer]]);
+ const buffers: ArrayBuffer[] = [];
+
+ const result = extractBuffers(input, buffers);
+
+ expect(result).toEqual({ key: { id: 0 } });
+ expect(buffers).toEqual([buffer]);
+ });
+});
+
+describe("EventBuffer", () => {
+ let processEvents: () => void;
+ let eventBuffer: EventBuffer<string>;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ processEvents = vi.fn();
+ eventBuffer = new EventBuffer(processEvents, 50);
+ });
+
+ it("should add events to buffer", () => {
+ eventBuffer.add("event1");
+ eventBuffer.add("event2");
+
+ expect(eventBuffer.size()).toBe(2);
+ });
+
+ it("should process events immediately on first add", () => {
+ eventBuffer.add("event1");
+
+ expect(processEvents).toHaveBeenCalledTimes(1);
+ });
+
+ it("should block processing for specified duration", () => {
+ eventBuffer.add("event1");
+ eventBuffer.add("event2");
+
+ expect(processEvents).toHaveBeenCalledTimes(1);
+
+ vi.advanceTimersByTime(49);
+ expect(processEvents).toHaveBeenCalledTimes(1);
+
+ vi.advanceTimersByTime(1);
+ expect(processEvents).toHaveBeenCalledTimes(2);
+ });
+
+ it("should clear buffer", () => {
+ eventBuffer.add("event1");
+ eventBuffer.add("event2");
+ eventBuffer.clear();
+
+ expect(eventBuffer.size()).toBe(0);
+ });
+
+ it("should get and clear buffer", () => {
+ eventBuffer.add("event1");
+ eventBuffer.add("event2");
+
+ const events = eventBuffer.getAndClear();
+
+ expect(events).toEqual(["event1", "event2"]);
+ expect(eventBuffer.size()).toBe(0);
+ });
+});
diff --git a/frontend/src/plugins/impl/panel/utils.ts b/frontend/src/plugins/impl/panel/utils.ts
new file mode 100644
index 0000000000..fb440ed5ab
--- /dev/null
+++ b/frontend/src/plugins/impl/panel/utils.ts
@@ -0,0 +1,100 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { z } from "zod";
+
+export const MessageSchema = z.object({
+ content: z
+ .union([
+ z.object({
+ type: z.literal("ACK"),
+ }),
+ z.string(),
+ ])
+ .nullable(),
+});
+
+/**
+ * Extracts buffers from a message.
+ * This mutates the buffers array.
+ */
+export function extractBuffers(
+ value: unknown,
+ buffers: ArrayBuffer[],
+): unknown {
+ if (Array.isArray(value)) {
+ return value.map((v) => extractBuffers(v, buffers));
+ }
+ if (value instanceof Map) {
+ const result: Record<string, unknown> = {};
+ for (const [key, v] of value.entries()) {
+ result[String(key)] = extractBuffers(v, buffers);
+ }
+ return result;
+ }
+ if (value instanceof ArrayBuffer) {
+ // TODO: this does not seem correct
+ const id = buffers.length;
+ buffers.push(value);
+ return { id };
+ }
+ if (typeof value === "object" && value !== null) {
+ const result: Record<string, unknown> = {};
+ for (const key of Object.keys(value)) {
+ result[key] = extractBuffers(
+ (value as Record<string, unknown>)[key],
+ buffers,
+ );
+ }
+ return result;
+ }
+ return value;
+}
+
+export class EventBuffer<T> {
+ private buffer: T[] = [];
+ private isBlocked = false;
+ private timeout: number | null = null;
+
+ constructor(
+ private processEvents: () => void,
+ private blockDuration = 200,
+ ) {}
+
+ add(event: T) {
+ this.buffer.push(event);
+ this.flush();
+ }
+
+ private flush() {
+ if (!this.isBlocked) {
+ this.processEvents();
+ this.block();
+ }
+ }
+
+ private block() {
+ this.isBlocked = true;
+ if (this.timeout !== null) {
+ clearTimeout(this.timeout);
+ }
+ this.timeout = window.setTimeout(() => {
+ this.isBlocked = false;
+ if (this.buffer.length > 0) {
+ this.flush();
+ }
+ }, this.blockDuration);
+ }
+
+ size() {
+ return this.buffer.length;
+ }
+
+ clear() {
+ this.buffer = [];
+ }
+
+ getAndClear() {
+ const events = [...this.buffer];
+ this.clear();
+ return events;
+ }
+}
diff --git a/marimo/_output/formatters/holoviews_formatters.py b/marimo/_output/formatters/holoviews_formatters.py
index 5896440883..ac962520c2 100644
--- a/marimo/_output/formatters/holoviews_formatters.py
+++ b/marimo/_output/formatters/holoviews_formatters.py
@@ -5,7 +5,7 @@ from marimo._config.config import Theme
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.formatters.formatter_factory import FormatterFactory
-from marimo._plugins.ui._impl.from_panel import from_panel
+from marimo._plugins.ui._impl.from_panel import panel as from_panel
class HoloViewsFormatter(FormatterFactory):
diff --git a/marimo/_output/formatters/panel_formatters.py b/marimo/_output/formatters/panel_formatters.py
index 7588a985c3..539b134eed 100644
--- a/marimo/_output/formatters/panel_formatters.py
+++ b/marimo/_output/formatters/panel_formatters.py
@@ -5,7 +5,7 @@ from typing import Any
from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.formatters.formatter_factory import FormatterFactory
-from marimo._plugins.ui._impl.from_panel import from_panel
+from marimo._plugins.ui._impl.from_panel import panel as from_panel
class PanelFormatter(FormatterFactory):
diff --git a/marimo/_plugins/ui/_impl/from_panel.py b/marimo/_plugins/ui/_impl/from_panel.py
index 17432045cb..a0f6e3655f 100644
--- a/marimo/_plugins/ui/_impl/from_panel.py
+++ b/marimo/_plugins/ui/_impl/from_panel.py
@@ -3,8 +3,17 @@ from __future__ import annotations
import sys
from dataclasses import dataclass
-from functools import partial
-from typing import Any, Dict, List, Optional, Tuple
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Dict,
+ List,
+ Optional,
+ Tuple,
+ Type,
+ TypeVar,
+ cast,
+)
from marimo import _loggers
from marimo._output.rich_help import mddoc
@@ -12,21 +21,18 @@ from marimo._plugins.ui._core.ui_element import InitializationArgs, UIElement
from marimo._plugins.ui._impl.comm import MarimoComm, MarimoCommManager
from marimo._runtime.functions import Function
+if TYPE_CHECKING:
+ from panel.viewable import Viewable
+
LOGGER = _loggers.marimo_logger()
COMM_MANAGER = MarimoCommManager()
-comm_class = None
+comm_class: Optional[Type[Any]] = None
loaded_extension: int = 0
loaded_extensions: list[str] = []
-
-def from_panel(obj: Any) -> UIElement[Any, Any]:
- """Create a UIElement from an Panel."""
- return panel(obj)
-
-
-T = Dict[str, Any]
+T = TypeVar("T", bound=Dict[str, Any])
@dataclass
@@ -35,7 +41,8 @@ class SendToWidgetArgs:
buffers: Optional[List[Any]] = None
-def _get_comm_class() -> Any:
+# Singleton, we only create one instance of this class
+def _get_comm_class() -> Type[Any]:
global comm_class
if comm_class:
return comm_class
@@ -75,9 +82,19 @@ def _get_comm_class() -> Any:
def render_extension(load_timeout: int = 500, loaded: bool = False) -> str:
+ """
+ Render Panel extension JavaScript.
+
+ Args:
+ load_timeout: Timeout for loading resources (in milliseconds)
+ loaded: Whether the extension has been loaded before
+
+ Returns:
+ JavaScript code for Panel extension
+ """
from panel.config import panel_extension
- new_exts = [
+ new_exts: list[str] = [
ext
for ext in panel_extension._loaded_extensions
if ext not in loaded_extensions
@@ -86,16 +103,15 @@ def render_extension(load_timeout: int = 500, loaded: bool = False) -> str:
return ""
from bokeh.io.notebook import curstate # type: ignore
- from panel.config import config # type: ignore
+ from bokeh.resources import CDN, INLINE
+ from bokeh.settings import settings
+ from panel.config import config
from panel.io.notebook import ( # type: ignore
- CDN,
- INLINE,
Resources,
_autoload_js,
_Unset,
bundle_resources,
require_components,
- settings,
state,
)
@@ -106,6 +122,7 @@ def render_extension(load_timeout: int = 500, loaded: bool = False) -> str:
user_resources = settings.resources._user_value is not _Unset
nb_endpoint = not state._is_pyodide
resources = Resources.from_bokeh(resources, notebook=nb_endpoint) # type: ignore[no-untyped-call]
+
try:
bundle = bundle_resources( # type: ignore[no-untyped-call]
None,
@@ -135,7 +152,18 @@ def render_extension(load_timeout: int = 500, loaded: bool = False) -> str:
return bokeh_js # type: ignore[no-any-return]
-def render_component(obj: Any) -> Tuple[str, dict[str, Any], dict[str, Any]]:
+def render_component(
+ obj: Viewable,
+) -> Tuple[str, dict[str, Any], dict[str, Any]]:
+ """
+ Render a Panel component.
+
+ Args:
+ obj: Panel Viewable object
+
+ Returns:
+ Tuple containing reference ID, docs JSON, and render JSON
+ """
from bokeh.document import Document
from bokeh.embed.util import standalone_docs_json_and_render_items
from panel.io.model import add_to_doc
@@ -184,13 +212,14 @@ class panel(UIElement[T, T]):
def __init__(self, obj: Any):
from panel.models.comm_manager import CommManager as PanelCommManager
- from panel.pane import panel
+ from panel.pane import panel as panel_func
- self.obj = obj = panel(obj)
+ self.obj = obj = panel_func(obj)
# This gets set to True in super().__init__()
self._initialized = False
ref, docs_json, render_json = render_component(obj)
+ self._ref = ref
self._manager = PanelCommManager(plot_id=ref) # type: ignore[no-untyped-call]
global loaded_extension
@@ -200,7 +229,7 @@ class panel(UIElement[T, T]):
super().__init__(
component_name="marimo-panel",
- initial_value=dict(),
+ initial_value=cast(T, {}),
label="",
args={
"extension": extension,
@@ -212,12 +241,13 @@ class panel(UIElement[T, T]):
Function(
name="send_to_widget",
arg_cls=SendToWidgetArgs,
- function=partial(self._handle_msg, ref),
+ function=self._handle_msg,
),
),
)
- def _handle_msg(self, ref: str, msg: SendToWidgetArgs) -> None:
+ def _handle_msg(self, msg: SendToWidgetArgs) -> None:
+ ref = self._ref
comm = self.obj._comms[ref][0]
msg = comm.decode(msg)
self.obj._on_msg(ref, self._manager, msg)
@@ -225,9 +255,7 @@ class panel(UIElement[T, T]):
def _initialize(
self,
- initialization_args: InitializationArgs[
- Dict[str, Any], Dict[str, Any]
- ],
+ initialization_args: InitializationArgs[T, T],
) -> None:
super()._initialize(initialization_args)
for comm, _ in self.obj._comms.values():
diff --git a/marimo/_smoke_tests/third_party/panel_example.py b/marimo/_smoke_tests/third_party/panel_example.py
new file mode 100644
index 0000000000..e60e0aaa92
--- /dev/null
+++ b/marimo/_smoke_tests/third_party/panel_example.py
@@ -0,0 +1,48 @@
+import marimo
+
+__generated_with = "0.9.14"
+app = marimo.App(width="medium")
+
+
+def __():
+ import marimo as mo
+ import panel as pn
+
+ pn.extension("vega")
+ return mo, pn
+
+
+def __(pn):
+ slider = pn.widgets.IntSlider(start=0, end=10, value=5)
+
+ slider.rx() * "🚀"
+ return (slider,)
+
+
+def __(pn, slider):
+ pn.Column(slider, pn.pane.Markdown("🚀"))
+ return
+
+
+def __(pn):
+ [
+ pn.widgets.FloatSlider(value=3.14),
+ pn.widgets.Select(
+ options=[
+ {"label": "Option 1", "value": 1},
+ {"label": "Option 2", "value": 2},
+ ]
+ ),
+ pn.widgets.Checkbox(name="Check me"),
+ pn.widgets.DatePicker(),
+ pn.widgets.FileInput(multiple=True),
+ ]
+ return
+
+
+if __name__ == "__main__":
+ app.run()