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.

Remote Function Registry + ui.table download function (#227)

Akshay Agrawalcc759d52b2a1
diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsx
index 88a68df61d..f5f268fae3 100644
--- a/frontend/src/components/data-table/data-table.tsx
+++ b/frontend/src/components/data-table/data-table.tsx
@@ -21,8 +21,9 @@ import {
TableRow,
} from "@/components/ui/table";
import { DataTablePagination } from "./pagination";
+import { DownloadActionProps, DownloadAs } from "./download-actions";
-interface DataTableProps<TData, TValue> {
+interface DataTableProps<TData, TValue> extends Partial<DownloadActionProps> {
columns: Array<ColumnDef<TData, TValue>>;
data: TData[];
pagination?: boolean;
@@ -35,6 +36,7 @@ export const DataTable = <TData, TValue>({
columns,
data,
rowSelection,
+ downloadAs,
pagination = false,
onRowSelectionChange,
}: DataTableProps<TData, TValue>) => {
@@ -106,7 +108,10 @@ export const DataTable = <TData, TValue>({
</TableBody>
</Table>
</div>
- {pagination && <DataTablePagination table={table} />}
+ <div className="flex align-items justify-between">
+ {pagination ? <DataTablePagination table={table} /> : <div />}
+ {downloadAs && <DownloadAs downloadAs={downloadAs} />}
+ </div>
</div>
);
};
diff --git a/frontend/src/components/data-table/download-actions.tsx b/frontend/src/components/data-table/download-actions.tsx
new file mode 100644
index 0000000000..653d96bd34
--- /dev/null
+++ b/frontend/src/components/data-table/download-actions.tsx
@@ -0,0 +1,65 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import React from "react";
+import { Button } from "../ui/button";
+import { CaretDownIcon } from "@radix-ui/react-icons";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "../ui/dropdown-menu";
+import { toast } from "../ui/use-toast";
+
+export interface DownloadActionProps {
+ downloadAs: (req: { format: "csv" | "json" }) => Promise<string>;
+}
+
+const options = [
+ { label: "CSV", format: "csv" },
+ { label: "JSON", format: "json" },
+] as const;
+
+export const DownloadAs: React.FC<DownloadActionProps> = (props) => {
+ const button = (
+ <Button size="xs" variant="link">
+ Download <CaretDownIcon className="w-3 h-3 ml-1" />
+ </Button>
+ );
+
+ return (
+ <DropdownMenu modal={false}>
+ <DropdownMenuTrigger asChild={true}>{button}</DropdownMenuTrigger>
+ <DropdownMenuContent side="bottom" className="no-print">
+ {options.map((option) => (
+ <DropdownMenuItem
+ key={option.label}
+ onSelect={async () => {
+ const downloadUrl = await props
+ .downloadAs({
+ format: option.format,
+ })
+ .catch((error) => {
+ toast({
+ title: "Failed to download",
+ description:
+ "message" in error ? error.message : String(error),
+ });
+ });
+ if (!downloadUrl) {
+ return;
+ }
+ const link = document.createElement("a");
+ link.href = downloadUrl;
+ link.setAttribute("download", "download");
+ document.body.append(link);
+ link.click();
+ link.remove();
+ }}
+ >
+ {option.label}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+};
diff --git a/frontend/src/components/data-table/pagination.tsx b/frontend/src/components/data-table/pagination.tsx
index 5cb93b426e..66fb020d8c 100644
--- a/frontend/src/components/data-table/pagination.tsx
+++ b/frontend/src/components/data-table/pagination.tsx
@@ -56,7 +56,7 @@ export const DataTablePagination = <TData,>({
};
return (
- <div className="flex items-center justify-between px-2">
+ <div className="flex flex-1 items-center justify-between px-2">
<div className="text-sm text-muted-foreground">{renderTotal()}</div>
<div className="flex items-center space-x-2">
<Button
diff --git a/frontend/src/core/codemirror/completion/Autocompleter.ts b/frontend/src/core/codemirror/completion/Autocompleter.ts
index ea37fb8599..8ebde60358 100644
--- a/frontend/src/core/codemirror/completion/Autocompleter.ts
+++ b/frontend/src/core/codemirror/completion/Autocompleter.ts
@@ -1,20 +1,14 @@
/* Copyright 2023 Marimo. All rights reserved. */
import { CompletionResult } from "@codemirror/autocomplete";
-import { Deferred } from "../../../utils/Deferred";
import {
CompletionOption,
CompletionResultMessage,
} from "../../kernel/messages";
-import { generateUUID } from "@/utils/uuid";
-import { CellId } from "@/core/model/ids";
import { sendCodeCompletionRequest } from "@/core/network/requests";
import { Tooltip } from "@codemirror/view";
-
-interface Entry {
- deferred: Deferred<CompletionResultMessage>;
- pos: number;
-}
+import { DeferredRequestRegistry } from "@/core/network/DeferredRequestRegistry";
+import { CodeCompletionRequest } from "@/core/network/types";
function constructCompletionInfoNode(innerHtml?: string): HTMLElement | null {
if (!innerHtml) {
@@ -29,53 +23,21 @@ function constructCompletionInfoNode(innerHtml?: string): HTMLElement | null {
return container;
}
-export class Autocompleter {
- public static INSTANCE = new Autocompleter();
-
- // TODO: maybe we store at most one request, evicting old ones
- private requests = new Map<string, Entry>();
-
- private constructor() {
- // Singleton
- }
-
- /**
- * Request completions for the given query
- */
- async request(opts: {
- pos: number;
- query: string;
- cellId: CellId;
- }): Promise<CompletionResultMessage> {
- const completionId = generateUUID();
- const deferred = new Deferred<CompletionResultMessage>();
-
- this.requests.set(completionId, { deferred: deferred, pos: opts.pos });
-
- // On failures, remove the request and rethrow the error
- deferred.promise.catch((error) => {
- this.requests.delete(completionId);
- throw error;
- });
-
- await sendCodeCompletionRequest(completionId, opts.query, opts.cellId);
- return deferred.promise;
- }
-
- resolve(msg: CompletionResultMessage) {
- const entry = this.requests.get(msg.completion_id);
- if (entry === undefined) {
- return;
- }
-
- entry.deferred.resolve(msg);
- this.requests.delete(msg.completion_id);
- }
-
+export const AUTOCOMPLETER = new DeferredRequestRegistry<
+ Omit<CodeCompletionRequest, "id">,
+ CompletionResultMessage
+>("function-call-result", async (requestId, req) => {
+ await sendCodeCompletionRequest({
+ id: requestId,
+ ...req,
+ });
+});
+
+export const Autocompleter = {
/**
* Convert a CompletionResultMessage to a CompletionResult
*/
- static asCompletionResult(
+ asCompletionResult(
position: number,
message: CompletionResultMessage
): CompletionResult {
@@ -90,12 +52,12 @@ export class Autocompleter {
}),
validFor: /^\w*$/,
};
- }
+ },
/**
* Convert a CompletionResultMessage to a Tooltip
*/
- static asHoverTooltip({
+ asHoverTooltip({
position,
message,
limitToType,
@@ -140,5 +102,5 @@ export class Autocompleter {
above: true,
create: () => ({ dom, resize: false }),
};
- }
-}
+ },
+};
diff --git a/frontend/src/core/codemirror/completion/completer.ts b/frontend/src/core/codemirror/completion/completer.ts
index 8bcf3430c2..24ab2ec2e2 100644
--- a/frontend/src/core/codemirror/completion/completer.ts
+++ b/frontend/src/core/codemirror/completion/completer.ts
@@ -1,7 +1,7 @@
/* Copyright 2023 Marimo. All rights reserved. */
import { CompletionContext, CompletionResult } from "@codemirror/autocomplete";
-import { Autocompleter } from "./Autocompleter";
+import { AUTOCOMPLETER, Autocompleter } from "./Autocompleter";
import { Logger } from "../../../utils/Logger";
import { CellId, HTMLCellId } from "@/core/model/ids";
import { getCells } from "@/core/state/cells";
@@ -25,9 +25,8 @@ export async function completer(
return null;
}
- const result = await Autocompleter.INSTANCE.request({
- pos: context.pos,
- query: query,
+ const result = await AUTOCOMPLETER.request({
+ document: query,
cellId: cellId,
});
diff --git a/frontend/src/core/codemirror/completion/hints.ts b/frontend/src/core/codemirror/completion/hints.ts
index e0da0194df..c6c6a6ce08 100644
--- a/frontend/src/core/codemirror/completion/hints.ts
+++ b/frontend/src/core/codemirror/completion/hints.ts
@@ -7,7 +7,7 @@ import {
hoverTooltip,
showTooltip,
} from "@codemirror/view";
-import { Autocompleter } from "./Autocompleter";
+import { AUTOCOMPLETER, Autocompleter } from "./Autocompleter";
import { Logger } from "@/utils/Logger";
import { closeCompletion } from "@codemirror/autocomplete";
import { StateField, StateEffect } from "@codemirror/state";
@@ -50,9 +50,8 @@ export function hintTooltip() {
endToken++;
}
- const result = await Autocompleter.INSTANCE.request({
- pos: endToken, // Send up to the end of the word, so the results are more accurate
- query: view.state.doc.slice(0, endToken).toString(), // convert Text to string
+ const result = await AUTOCOMPLETER.request({
+ document: view.state.doc.slice(0, endToken).toString(), // convert Text to string
cellId: cellId,
});
diff --git a/frontend/src/core/dom/UIElement.ts b/frontend/src/core/dom/UIElement.ts
index 1289a38fb4..70885e6d22 100644
--- a/frontend/src/core/dom/UIElement.ts
+++ b/frontend/src/core/dom/UIElement.ts
@@ -5,7 +5,7 @@ import { defineCustomElement } from "./defineCustomElement";
import { MarimoValueInputEventType, marimoValueInputEvent } from "./events";
import { UI_ELEMENT_REGISTRY } from "./uiregistry";
-export const UI_ELEMENT_TAG_NAME = "MARIMO-UI-ELEMENT";
+const UI_ELEMENT_TAG_NAME = "MARIMO-UI-ELEMENT";
/**
* Lazily initialize the UIElement component.
@@ -182,3 +182,24 @@ export function initializeUIElement() {
defineCustomElement(UI_ELEMENT_TAG_NAME.toLowerCase(), UIElement);
}
+
+/**
+ * Given a node, check if its parent or itself is a UIElement,
+ * and return its objectId if so.
+ */
+export function getUIElementObjectId(target: HTMLElement): string | null {
+ if (!target) {
+ return null;
+ }
+
+ if (target.nodeName === UI_ELEMENT_TAG_NAME) {
+ return target.getAttribute("object-id");
+ }
+
+ const node = target.parentElement;
+ if (node?.nodeName === UI_ELEMENT_TAG_NAME) {
+ return node.getAttribute("object-id");
+ }
+
+ return null;
+}
diff --git a/frontend/src/core/functions/FunctionRegistry.ts b/frontend/src/core/functions/FunctionRegistry.ts
new file mode 100644
index 0000000000..25ab6ddb52
--- /dev/null
+++ b/frontend/src/core/functions/FunctionRegistry.ts
@@ -0,0 +1,16 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+
+import { sendFunctionRequest } from "@/core/network/requests";
+import { FunctionCallResultMessage } from "../kernel/messages";
+import { DeferredRequestRegistry } from "../network/DeferredRequestRegistry";
+import { SendFunctionRequest } from "../network/types";
+
+export const FUNCTIONS_REGISTRY = new DeferredRequestRegistry<
+ Omit<SendFunctionRequest, "functionCallId">,
+ FunctionCallResultMessage
+>("function-call-result", async (requestId, req) => {
+ await sendFunctionRequest({
+ functionCallId: requestId,
+ ...req,
+ });
+});
diff --git a/frontend/src/core/kernel/messages.tsx b/frontend/src/core/kernel/messages.ts
similarity index 86%
rename from frontend/src/core/kernel/messages.tsx
rename to frontend/src/core/kernel/messages.ts
index a9afa74da4..2695b95de3 100644
--- a/frontend/src/core/kernel/messages.tsx
+++ b/frontend/src/core/kernel/messages.ts
@@ -4,6 +4,7 @@ import { LayoutType } from "@/editor/renderers/types";
import { CellConfig, CellStatus } from "../model/cells";
import { CellId } from "../model/ids";
import { VariableName } from "../variables/types";
+import { RequestId } from "../network/DeferredRequestRegistry";
export type OutputChannel =
| "output"
@@ -102,7 +103,7 @@ export interface CompletionResultMessage {
/**
* The ID of the completion request
*/
- completion_id: string;
+ completion_id: RequestId;
prefix_length: number;
/**
* The options for completion
@@ -110,6 +111,33 @@ export interface CompletionResultMessage {
options: CompletionOption[];
}
+/**
+ * Status code, and human readable explanation.
+ */
+export interface HumanReadableStatus {
+ code: "ok" | "error";
+ title?: string;
+ message?: string;
+}
+
+/**
+ * Message for function call results
+ */
+export interface FunctionCallResultMessage {
+ /**
+ * The ID of the function call
+ */
+ function_call_id: RequestId;
+ /**
+ * The result of the function call
+ */
+ return_value: unknown;
+ /**
+ * Status code and human readable info.
+ */
+ status: HumanReadableStatus;
+}
+
/**
* Message sent from the frontend to the kernel via the websocket.
*/
@@ -166,6 +194,10 @@ export type OperationMessage =
op: "completion-result";
data: CompletionResultMessage;
}
+ | {
+ op: "function-call-result";
+ data: FunctionCallResultMessage;
+ }
| {
op: "cell-op";
data: CellMessage;
diff --git a/frontend/src/core/network/DeferredRequestRegistry.ts b/frontend/src/core/network/DeferredRequestRegistry.ts
new file mode 100644
index 0000000000..9e3f36dc99
--- /dev/null
+++ b/frontend/src/core/network/DeferredRequestRegistry.ts
@@ -0,0 +1,49 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+/* eslint-disable @typescript-eslint/no-redeclare */
+import { Deferred } from "@/utils/Deferred";
+import { generateUUID } from "@/utils/uuid";
+import { TypedString } from "../model/typed";
+
+export type RequestId = TypedString<"RequestId">;
+export const RequestId = {
+ create(): RequestId {
+ return generateUUID() as RequestId;
+ },
+};
+
+/**
+ * Helper class to manage deferred requests.
+ * We send a request via HTTP and then wait for the response from the kernel
+ * via a websocket.
+ */
+export class DeferredRequestRegistry<REQ, RES> {
+ public requests = new Map<RequestId, Deferred<RES>>();
+
+ constructor(
+ public operation: string,
+ private makeRequest: (id: RequestId, req: REQ) => Promise<void>
+ ) {}
+
+ async request(opts: REQ): Promise<RES> {
+ const requestId = RequestId.create();
+ const deferred = new Deferred<RES>();
+
+ this.requests.set(requestId, deferred);
+
+ await this.makeRequest(requestId, opts).catch((error) => {
+ deferred.reject(error);
+ this.requests.delete(requestId);
+ });
+ return deferred.promise;
+ }
+
+ resolve(requestId: RequestId, response: RES) {
+ const entry = this.requests.get(requestId);
+ if (entry === undefined) {
+ return;
+ }
+
+ entry.resolve(response);
+ this.requests.delete(requestId);
+ }
+}
diff --git a/frontend/src/core/network/__tests__/DeferredRequestRegistry.test.ts b/frontend/src/core/network/__tests__/DeferredRequestRegistry.test.ts
new file mode 100644
index 0000000000..4ab66cfa87
--- /dev/null
+++ b/frontend/src/core/network/__tests__/DeferredRequestRegistry.test.ts
@@ -0,0 +1,34 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { beforeEach, expect, vi, describe, it } from "vitest";
+import { DeferredRequestRegistry, RequestId } from "../DeferredRequestRegistry";
+
+vi.mock("@/utils/uuid", () => ({
+ generateUUID: vi.fn().mockReturnValue("uuid"),
+}));
+
+describe("DeferredRequestRegistry", () => {
+ const REQUEST_ID = "uuid" as RequestId;
+ let makeRequestMock = vi.fn();
+ let registry: DeferredRequestRegistry<unknown, unknown>;
+
+ beforeEach(() => {
+ makeRequestMock = vi.fn().mockResolvedValue(undefined);
+ registry = new DeferredRequestRegistry("operation", makeRequestMock);
+ });
+
+ it("should create and resolve new request", async () => {
+ const promise = registry.request("requestOptions");
+ expect(makeRequestMock).toHaveBeenCalledWith("uuid", "requestOptions");
+ expect(registry.requests.has(REQUEST_ID)).toBe(true);
+
+ // resolve
+ registry.resolve(REQUEST_ID, "response");
+ await expect(promise).resolves.toBe("response");
+ });
+
+ it("should handle request failure", async () => {
+ makeRequestMock.mockRejectedValue(new Error("request error"));
+ const promise = registry.request("requestOptions");
+ await expect(promise).rejects.toThrow("request error");
+ });
+});
diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.ts
index 1450027470..0823a6cd04 100644
--- a/frontend/src/core/network/requests.ts
+++ b/frontend/src/core/network/requests.ts
@@ -16,6 +16,7 @@ import {
SaveUserConfigRequest,
SaveAppConfigRequest,
SaveCellConfigRequest,
+ SendFunctionRequest,
} from "./types";
import { invariant } from "@/utils/invariant";
@@ -112,15 +113,9 @@ export async function sendDirectoryAutocompleteRequest(prefix: string) {
}
export async function sendCodeCompletionRequest(
- id: string,
- document: string,
- cellId: CellId
+ request: CodeCompletionRequest
) {
- return API.post<CodeCompletionRequest>("/kernel/code_autocomplete/", {
- id: id,
- document: document,
- cellId: cellId,
- });
+ return API.post<CodeCompletionRequest>("/kernel/code_autocomplete/", request);
}
export function saveUserConfig(request: SaveUserConfigRequest) {
@@ -134,3 +129,7 @@ export function saveAppConfig(request: SaveAppConfigRequest) {
export function saveCellConfig(request: SaveCellConfigRequest) {
return API.post<SaveCellConfigRequest>("/kernel/set_cell_config/", request);
}
+
+export function sendFunctionRequest(request: SendFunctionRequest) {
+ return API.post<SendFunctionRequest>("/kernel/function_call/", request);
+}
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index a5f2e4e3f3..9dbedd570e 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -3,6 +3,7 @@ import { AppConfig, UserConfig } from "../config/config";
import { LayoutType } from "@/editor/renderers/types";
import { CellId } from "../../core/model/ids";
import { CellConfig } from "../model/cells";
+import { RequestId } from "./DeferredRequestRegistry";
export interface DeleteRequest {
cellId: CellId;
@@ -65,7 +66,7 @@ export interface SetComponentValuesRequest {
}
export interface CodeCompletionRequest {
- id: string;
+ id: RequestId;
document: string;
cellId: CellId;
}
@@ -81,3 +82,10 @@ export interface SaveAppConfigRequest {
export interface SaveCellConfigRequest {
configs: Record<CellId, CellConfig>;
}
+
+export interface SendFunctionRequest {
+ functionCallId: RequestId;
+ args: unknown;
+ namespace: string;
+ functionName: string;
+}
diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsx
index 5c40226ad3..ecef4f823d 100644
--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx
+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx
@@ -6,7 +6,7 @@ import { useWebSocket } from "@/core/websocket/useWebSocket";
import { logNever } from "@/utils/assertNever";
import { useCellActions } from "@/core/state/cells";
import { RuntimeState } from "@/core/RuntimeState";
-import { Autocompleter } from "@/core/codemirror/completion/Autocompleter";
+import { AUTOCOMPLETER } from "@/core/codemirror/completion/Autocompleter";
import { UI_ELEMENT_REGISTRY } from "@/core/dom/uiregistry";
import { OperationMessage } from "@/core/kernel/messages";
import { saveCellConfig, sendInstantiate } from "../network/requests";
@@ -20,6 +20,7 @@ import { deserializeLayout } from "@/editor/renderers/plugins";
import { useVariablesActions } from "../variables/state";
import { toast } from "@/components/ui/use-toast";
import { renderHTML } from "@/plugins/core/RenderHTML";
+import { FUNCTIONS_REGISTRY } from "../functions/FunctionRegistry";
/**
* WebSocket that connects to the Marimo kernel and handles incoming messages.
@@ -142,7 +143,10 @@ export function useMarimoWebSocket(opts: {
return;
}
case "completion-result":
- Autocompleter.INSTANCE.resolve(msg.data);
+ AUTOCOMPLETER.resolve(msg.data.completion_id, msg.data);
+ return;
+ case "function-call-result":
+ FUNCTIONS_REGISTRY.resolve(msg.data.function_call_id, msg.data);
return;
case "cell-op": {
/* Register a state transition for a cell.
diff --git a/frontend/src/css/codemirror.css b/frontend/src/css/codemirror.css
index dbc263e403..ab094cfdff 100644
--- a/frontend/src/css/codemirror.css
+++ b/frontend/src/css/codemirror.css
@@ -59,10 +59,8 @@
white-space: normal;
display: block;
list-style-type: disc;
- margin-block-start: 0;
- margin-block-end: 0;
- margin-inline-start: 0;
- margin-inline-end: 0;
+ margin-block: 0 0;
+ margin-inline: 0 0;
padding-inline-start: 40px;
}
@@ -71,10 +69,8 @@
white-space: normal;
display: block;
list-style-type: decimal;
- margin-block-start: 0;
- margin-block-end: 0;
- margin-inline-start: 0;
- margin-inline-end: 0;
+ margin-block: 0 0;
+ margin-inline: 0 0;
padding-inline-start: 40px;
}
@@ -87,10 +83,8 @@
.mo-cm-tooltip blockquote {
display: contents;
- margin-block-start: 0;
- margin-block-end: 0;
- margin-inline-start: 0;
- margin-inline-end: 0;
+ margin-block: 0 0;
+ margin-inline: 0 0;
}
.mo-cm-tooltip pre {
diff --git a/frontend/src/css/md.css b/frontend/src/css/md.css
index cac6f73e49..19573da67c 100644
--- a/frontend/src/css/md.css
+++ b/frontend/src/css/md.css
@@ -32,10 +32,8 @@
/* provide by the browser, but removed from 'reset' */
display: block;
font-size: 2rem;
- margin-block-start: 0.67rem;
- margin-block-end: 0.67rem;
- margin-inline-start: 0;
- margin-inline-end: 0;
+ margin-block: 0.67rem 0.67rem;
+ margin-inline: 0 0;
text-align: center;
}
@@ -48,40 +46,32 @@
/* provide by the browser, but removed from 'reset' */
display: block;
font-size: 1.5rem;
- margin-block-start: 0.83rem;
- margin-block-end: 0.83rem;
- margin-inline-start: 0;
- margin-inline-end: 0;
+ margin-block: 0.83rem 0.83rem;
+ margin-inline: 0 0;
}
.markdown h3 {
/* provide by the browser, but removed from 'reset' */
display: block;
font-size: 1.17rem;
- margin-block-start: 1rem;
- margin-block-end: 1rem;
- margin-inline-start: 0;
- margin-inline-end: 0;
+ margin-block: 1rem 1rem;
+ margin-inline: 0 0;
}
.markdown p,
.markdown .paragraph {
/* provide by the browser, but removed from 'reset' */
display: block;
- margin-block-start: 1rem;
- margin-block-end: 1rem;
- margin-inline-start: 0;
- margin-inline-end: 0;
+ margin-block: 1rem 1rem;
+ margin-inline: 0 0;
}
.markdown ul {
/* provide by the browser, but removed from 'reset' */
display: block;
list-style-type: disc;
- margin-block-start: 1rem;
- margin-block-end: 1rem;
- margin-inline-start: 0;
- margin-inline-end: 0;
+ margin-block: 1rem 1rem;
+ margin-inline: 0 0;
padding-inline-start: 40px;
}
@@ -89,10 +79,8 @@
/* provide by the browser, but removed from 'reset' */
display: block;
list-style-type: decimal;
- margin-block-start: 1rem;
- margin-block-end: 1rem;
- margin-inline-start: 0;
- margin-inline-end: 0;
+ margin-block: 1rem 1rem;
+ margin-inline: 0 0;
padding-inline-start: 40px;
}
diff --git a/frontend/src/plugins/core/builder.ts b/frontend/src/plugins/core/builder.ts
new file mode 100644
index 0000000000..2579209953
--- /dev/null
+++ b/frontend/src/plugins/core/builder.ts
@@ -0,0 +1,50 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { ZodType, ZodTypeDef } from "zod";
+import { IPluginProps, IPlugin } from "../types";
+import { FunctionSchemas, PluginFunctions } from "./rpc";
+
+type Renderer<S, D, F> = (props: IPluginProps<S, D, F>) => JSX.Element;
+// If this simple builder pattern becomes unwieldy, we can switch to a more
+// complex builder pattern with individual classes.
+
+export function createPlugin<S>(tagName: string) {
+ return {
+ /**
+ * Data schema for the plugin.
+ */
+ withData<D>(validator: ZodType<D, ZodTypeDef, unknown>) {
+ return {
+ /**
+ * Functions that the plugin can call.
+ */
+ withFunctions<F extends PluginFunctions>(
+ functions: FunctionSchemas<F>
+ ) {
+ return {
+ /**
+ * Render the plugin.
+ */
+ renderer(renderer: Renderer<S, D, F>): IPlugin<S, D, F> {
+ return {
+ tagName,
+ validator,
+ functions,
+ render: renderer,
+ };
+ },
+ };
+ },
+ /**
+ * Render the plugin.
+ */
+ renderer(renderer: Renderer<S, D, unknown>): IPlugin<S, D, {}> {
+ return {
+ tagName,
+ validator,
+ render: renderer,
+ };
+ },
+ };
+ },
+ };
+}
diff --git a/frontend/src/plugins/core/componentFactory.tsx b/frontend/src/plugins/core/registerReactComponent.tsx
similarity index 89%
rename from frontend/src/plugins/core/componentFactory.tsx
rename to frontend/src/plugins/core/registerReactComponent.tsx
index c388d10ce4..eb1640fab8 100644
--- a/frontend/src/plugins/core/componentFactory.tsx
+++ b/frontend/src/plugins/core/registerReactComponent.tsx
@@ -13,6 +13,7 @@ import React, {
useCallback,
useEffect,
useImperativeHandle,
+ useMemo,
useRef,
useState,
} from "react";
@@ -32,6 +33,10 @@ import { renderHTML } from "./RenderHTML";
import { invariant } from "../../utils/invariant";
import { Logger } from "../../utils/Logger";
import { getTheme } from "@/theme/useTheme";
+import { FUNCTIONS_REGISTRY } from "@/core/functions/FunctionRegistry";
+import { getUIElementObjectId } from "@/core/dom/UIElement";
+import { PluginFunctions } from "./rpc";
+import { ZodSchema } from "zod";
export interface PluginSlotHandle {
/**
@@ -146,6 +151,40 @@ function PluginSlotInternal<T>(
[setValue, shouldDispatchInput]
);
+ // Create a map of functions that can be called by the plugin
+ const functionMethods = useMemo<PluginFunctions>(() => {
+ if (!plugin.functions) {
+ return {};
+ }
+
+ const methods: PluginFunctions = {};
+ for (const [key, schemas] of Objects.entries(plugin.functions)) {
+ const { input, output } = schemas as {
+ input: ZodSchema<unknown>;
+ output: ZodSchema<unknown>;
+ };
+ methods[key] = async (...args: unknown[]) => {
+ invariant(
+ args.length <= 1,
+ `Plugin functions only supports a single argument. Called ${key}`
+ );
+ const objectId = getUIElementObjectId(hostElement);
+ invariant(objectId, "Object ID should exist");
+ const response = await FUNCTIONS_REGISTRY.request({
+ args: input.parse(args[0]),
+ functionName: key,
+ namespace: objectId,
+ });
+ if (response.status.code !== "ok") {
+ throw new Error(response.status.message);
+ }
+ return output.parse(response.return_value);
+ };
+ }
+
+ return methods;
+ }, [plugin.functions, hostElement]);
+
// If we failed to parse the initial value, render an error
if (!parseResult.success) {
return renderError(parseResult.error);
@@ -161,6 +200,7 @@ function PluginSlotInternal<T>(
data: parseResult.data,
children: childNodes,
host: hostElement,
+ functions: functionMethods,
})}
</div>
);
diff --git a/frontend/src/plugins/core/rpc.ts b/frontend/src/plugins/core/rpc.ts
new file mode 100644
index 0000000000..baa7083c3f
--- /dev/null
+++ b/frontend/src/plugins/core/rpc.ts
@@ -0,0 +1,55 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+/* eslint-disable @typescript-eslint/no-explicit-any */
+
+import { ZodType, ZodTypeDef } from "zod";
+
+export type PluginFunction<REQ = any, RES = any> = (args: REQ) => Promise<RES>;
+
+/**
+ * Functions that can be called from the plugin.
+ */
+export type PluginFunctions = Record<string, PluginFunction>;
+
+// Utility types for extracting schemas from functions.
+export type ExtractInputSchema<F extends PluginFunction> = F extends (
+ args: infer REQ
+) => Promise<any>
+ ? ZodType<REQ, ZodTypeDef, unknown>
+ : never;
+export type ExtractOutputSchema<F extends PluginFunction> = F extends (
+ args: any
+) => Promise<infer RES>
+ ? ZodType<RES, ZodTypeDef, unknown>
+ : never;
+
+/**
+ * Schemas for the plugin functions.
+ */
+export type FunctionSchemas<F extends PluginFunctions> = {
+ [K in keyof F]: {
+ /**
+ * Validate the function arguments.
+ */
+ input: ExtractInputSchema<F[K]>;
+ /**
+ * Validate the function output.
+ */
+ output: ExtractOutputSchema<F[K]>;
+ };
+};
+
+/**
+ * RPC builder for plugin functions.
+ */
+export const rpc = {
+ input<I>(inputSchema: ZodType<I, ZodTypeDef, unknown>) {
+ return {
+ output<O>(outputSchema: ZodType<O, ZodTypeDef, unknown>) {
+ return {
+ input: inputSchema,
+ output: outputSchema,
+ };
+ },
+ };
+ },
+};
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index 81beb41c62..6999bf2d16 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -4,12 +4,13 @@ import { z } from "zod";
// @ts-expect-error - no types
import { loader as createLoader, read } from "vega-loader";
-import { IPlugin, IPluginProps } from "@/plugins/types";
import { DataTable } from "../../components/data-table/data-table";
import { generateColumns } from "../../components/data-table/columns";
import { Labeled } from "./common/labeled";
import { useAsyncData } from "@/hooks/useAsyncData";
import { Alert, AlertTitle } from "@/components/ui/alert";
+import { rpc } from "../core/rpc";
+import { createPlugin } from "../core/builder";
/**
* Arguments for a data table
@@ -22,29 +23,40 @@ interface Data<T> {
data: T[] | string;
pagination: boolean;
selection: "single" | "multi" | null;
+ showDownload: boolean;
}
-// Value is selection, but it is not currently exposed to the user
+// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
+type Functions = {
+ download_as: (req: { format: "csv" | "json" }) => Promise<string>;
+};
+
type S = Array<string | number>;
const loader = createLoader();
-export class DataTablePlugin implements IPlugin<S, Data<unknown>> {
- tagName = "marimo-table";
-
- validator = z.object({
- initialValue: z.array(z.number()),
- label: z.string().nullable(),
- data: z.union([z.string(), z.array(z.object({}).passthrough())]),
- pagination: z.boolean().default(false),
- selection: z.enum(["single", "multi"]).nullable().default(null),
- });
-
- render(props: IPluginProps<S, Data<unknown>>): JSX.Element {
+export const DataTablePlugin = createPlugin<S>("marimo-table")
+ .withData(
+ z.object({
+ initialValue: z.array(z.number()),
+ label: z.string().nullable(),
+ data: z.union([z.string(), z.array(z.object({}).passthrough())]),
+ pagination: z.boolean().default(false),
+ selection: z.enum(["single", "multi"]).nullable().default(null),
+ showDownload: z.boolean().default(false),
+ })
+ )
+ .withFunctions<Functions>({
+ download_as: rpc
+ .input(z.object({ format: z.enum(["csv", "json"]) }))
+ .output(z.string()),
+ })
+ .renderer((props) => {
if (typeof props.data.data === "string") {
return (
<LoadingDataTableComponent
{...props.data}
+ {...props.functions}
data={props.data.data}
value={props.value}
setValue={props.setValue}
@@ -54,15 +66,15 @@ export class DataTablePlugin implements IPlugin<S, Data<unknown>> {
return (
<DataTableComponent
{...props.data}
+ {...props.functions}
data={props.data.data}
value={props.value}
setValue={props.setValue}
/>
);
- }
-}
+ });
-interface DataTableProps extends Data<unknown> {
+interface DataTableProps extends Data<unknown>, Functions {
value: S;
setValue: (value: S) => void;
}
@@ -101,6 +113,8 @@ const DataTableComponent = ({
pagination,
selection,
value,
+ showDownload,
+ download_as: downloadAs,
setValue,
}: DataTableProps & {
data: unknown[];
@@ -119,6 +133,7 @@ const DataTableComponent = ({
columns={columns}
pagination={pagination}
rowSelection={rowSelection}
+ downloadAs={showDownload ? downloadAs : undefined}
onRowSelectionChange={(updater) => {
if (selection === "single") {
const nextValue =
diff --git a/frontend/src/plugins/impl/DictPlugin.tsx b/frontend/src/plugins/impl/DictPlugin.tsx
index df6df638cc..ce646c623b 100644
--- a/frontend/src/plugins/impl/DictPlugin.tsx
+++ b/frontend/src/plugins/impl/DictPlugin.tsx
@@ -2,7 +2,7 @@
import { useEffect } from "react";
import { z } from "zod";
-import { UI_ELEMENT_TAG_NAME } from "../../core/dom/UIElement";
+import { getUIElementObjectId } from "../../core/dom/UIElement";
import {
marimoValueInputEvent,
MarimoValueInputEventType,
@@ -55,13 +55,11 @@ const Dict = ({
if (target === null || !(target instanceof Node)) {
return;
}
- const node = target.parentNode;
- if (node === null || node.nodeName !== UI_ELEMENT_TAG_NAME) {
- // If something other than a UI element triggered an event, ignore it
+ const objectId = getUIElementObjectId(target);
+ if (objectId === null) {
return;
}
- const id = (node as Element).getAttribute("object-id") as string;
- const key = elementIds[id];
+ const key = elementIds[objectId];
if (key === undefined) {
// If the UI element firing the event is not in the dict, ignore it
return;
diff --git a/frontend/src/plugins/impl/FormPlugin.tsx b/frontend/src/plugins/impl/FormPlugin.tsx
index 04b6e2daf4..92e9b6c65e 100644
--- a/frontend/src/plugins/impl/FormPlugin.tsx
+++ b/frontend/src/plugins/impl/FormPlugin.tsx
@@ -2,7 +2,7 @@
import { useEffect, useState } from "react";
import { z } from "zod";
-import { UI_ELEMENT_TAG_NAME } from "../../core/dom/UIElement";
+import { getUIElementObjectId } from "../../core/dom/UIElement";
import {
marimoValueInputEvent,
MarimoValueInputEventType,
@@ -123,15 +123,8 @@ const Form = ({ elementId, value, setValue, children, label }: SubmitProps) => {
if (target === null || !(target instanceof Node)) {
return;
}
- const node = target.parentNode;
-
- // If something other than a UI element triggered an event, ignore it
- if (node === null || node.nodeName !== UI_ELEMENT_TAG_NAME) {
- return;
- }
-
- const id = (node as Element).getAttribute("object-id") as string;
- if (id === elementId) {
+ const objectId = getUIElementObjectId(target);
+ if (objectId === elementId) {
setInternalValue(e.detail.value);
}
};
diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.ts
index 7233c58f3a..e0c2f316a9 100644
--- a/frontend/src/plugins/plugins.ts
+++ b/frontend/src/plugins/plugins.ts
@@ -1,7 +1,7 @@
/* Copyright 2023 Marimo. All rights reserved. */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { initializeUIElement } from "../core/dom/UIElement";
-import { registerReactComponent } from "./core/componentFactory";
+import { registerReactComponent } from "./core/registerReactComponent";
import { ButtonPlugin } from "./impl/ButtonPlugin";
import { CheckboxPlugin } from "./impl/CheckboxPlugin";
import { DatePickerPlugin } from "./impl/DatePickerPlugin";
@@ -35,7 +35,7 @@ import { StatPlugin } from "./layout/StatPlugin";
const UI_PLUGINS: Array<IPlugin<any, unknown>> = [
new ButtonPlugin(),
new CheckboxPlugin(),
- new DataTablePlugin(),
+ DataTablePlugin,
new DatePickerPlugin(),
new DictPlugin(),
new DropdownPlugin(),
diff --git a/frontend/src/plugins/stateless-plugin.ts b/frontend/src/plugins/stateless-plugin.ts
index e8c121a0a9..1519f2600e 100644
--- a/frontend/src/plugins/stateless-plugin.ts
+++ b/frontend/src/plugins/stateless-plugin.ts
@@ -18,7 +18,8 @@ export interface IStatelessPluginProps<D> {
children?: React.ReactNode | undefined;
}
-export interface IStatelessPlugin<D> extends Omit<IPlugin<never, D>, "render"> {
+export interface IStatelessPlugin<D>
+ extends Omit<IPlugin<never, D>, "render" | "functions"> {
/**
* Render the plugin.
*/
diff --git a/frontend/src/plugins/types.ts b/frontend/src/plugins/types.ts
index 1304941e40..87c925692f 100644
--- a/frontend/src/plugins/types.ts
+++ b/frontend/src/plugins/types.ts
@@ -1,5 +1,6 @@
/* Copyright 2023 Marimo. All rights reserved. */
import { ZodType, ZodTypeDef } from "zod";
+import { PluginFunctions, FunctionSchemas } from "./core/rpc";
/**
* State setter. Either a value or a function that takes the previous value and
@@ -9,10 +10,8 @@ export type Setter<S> = (value: S | ((prev: S) => S)) => void;
/**
* Props for a plugin.
- *
- * TODO(akshayka): (Maybe) add children elements for composition
*/
-export interface IPluginProps<S, D> {
+export interface IPluginProps<S, D, F = {}> {
/**
* Host element.
*/
@@ -30,6 +29,11 @@ export interface IPluginProps<S, D> {
*/
data: D;
+ /**
+ * Functions that can be called from the plugin.
+ */
+ functions: F;
+
/**
* Children elements.
*/
@@ -48,7 +52,11 @@ export type StringifiedPluginData<D> = {
* @template S - the type of the state
* @template P - the type of the props
*/
-export interface IPlugin<S, D = Record<string, never>> {
+export interface IPlugin<
+ S,
+ D = Record<string, never>,
+ F extends PluginFunctions = {}
+> {
/**
* The html tag name to render the plugin.
*/
@@ -59,8 +67,13 @@ export interface IPlugin<S, D = Record<string, never>> {
*/
validator: ZodType<D, ZodTypeDef, unknown>;
+ /**
+ * Functions definitions and validation.
+ */
+ functions?: FunctionSchemas<F>;
+
/**
* Render the plugin.
*/
- render(props: IPluginProps<S, D>): JSX.Element;
+ render(props: IPluginProps<S, D, F>): JSX.Element;
}
diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.py
index 9391b037a2..bcb1057497 100644
--- a/marimo/_messaging/ops.py
+++ b/marimo/_messaging/ops.py
@@ -192,6 +192,26 @@ class CellOp(Op):
).broadcast()
+@dataclass
+class HumanReadableStatus(Op):
+ """Human-readable status."""
+
+ code: Literal["ok", "error"]
+ title: str | None = None
+ message: str | None = None
+
+
+@dataclass
+class FunctionCallResult(Op):
+ """Result of calling a function."""
+
+ name: ClassVar[str] = "function-call-result"
+
+ function_call_id: str
+ return_value: JSONType
+ status: HumanReadableStatus
+
+
@dataclass
class RemoveUIElements(Op):
"""Invalidate UI elements for a given cell."""
diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.py
index ef01712ca8..e5d3315c51 100644
--- a/marimo/_plugins/ui/_core/ui_element.py
+++ b/marimo/_plugins/ui/_core/ui_element.py
@@ -4,7 +4,15 @@ from __future__ import annotations
import abc
import copy
import uuid
-from typing import TYPE_CHECKING, Callable, Generic, Optional, TypeVar, cast
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Generic,
+ Optional,
+ TypeVar,
+ cast,
+)
from marimo import _loggers
from marimo._output.hypertext import Html
@@ -12,6 +20,7 @@ from marimo._output.rich_help import mddoc
from marimo._plugins.core.web_component import JSONType, build_ui_plugin
from marimo._plugins.ui._core import ids
from marimo._runtime.context import ContextNotInitializedError, get_context
+from marimo._runtime.functions import Function
if TYPE_CHECKING:
from marimo._plugins.ui._impl.input import form as form_plugin
@@ -70,6 +79,7 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
on_change: Optional[Callable[[T], None]],
args: dict[str, JSONType],
slotted_html: str = "",
+ functions: tuple[Function[Any, Any], ...] = (),
) -> None:
"""Initialize a UIElement
@@ -78,9 +88,10 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
component_name: tag name of the custom element
initial_value: initial value of the element in the frontend
label: markdown string, label of element
+ on_change: callback, called with element's new value on change
args: arguments that the element takes
slotted_html: any html to slot in the custom element
- on_change: callback, called with element's new value on change
+ functions: any functions to register with the graph
"""
# arguments stored in signature order for cloning
self._args = (
@@ -90,6 +101,7 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
on_change,
args,
slotted_html,
+ functions,
)
self._initialized = False
self._initialize(*self._args)
@@ -103,6 +115,7 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
on_change: Optional[Callable[[T], None]],
args: dict[str, JSONType],
slotted_html: str,
+ functions: tuple[Function[Any, Any], ...] = (),
) -> None:
"""Initialize the UIElement
@@ -139,9 +152,7 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
if ctx is not None:
ctx.ui_element_registry.register(self._id, self)
-
- # an Instantiate request may want us to override the initial value
- if ctx is not None:
+ # an Instantiate request may want us to override the initial value
try:
# NB: If a cell produces a non-deterministic set of
# UI elements, a UI element may be matched with an initial
@@ -159,6 +170,10 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
except KeyError:
# we weren't asked to override the UI element's value
pass
+ for function in functions:
+ ctx.function_registry.register(
+ namespace=self._id, function=function
+ )
self._initial_value_frontend = initial_value
self._value = self._initial_value = self._convert_value(initial_value)
self._on_change = on_change
@@ -273,6 +288,7 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
try:
ctx = get_context()
ctx.ui_element_registry.delete(self._id, id(self))
+ ctx.function_registry.delete(namespace=self._id)
except ContextNotInitializedError:
pass
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index 5dea25b3a0..4be1a5d3a7 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -1,6 +1,7 @@
# Copyright 2023 Marimo. All rights reserved.
from __future__ import annotations
+from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
Callable,
@@ -21,6 +22,7 @@ from marimo._output.mime import MIME
from marimo._output.rich_help import mddoc
from marimo._plugins.core.web_component import JSONType
from marimo._plugins.ui._core.ui_element import UIElement
+from marimo._runtime.functions import Function
LOGGER = _loggers.marimo_logger()
@@ -36,6 +38,11 @@ TableData = Union[
]
+@dataclass
+class DownloadAsArgs:
+ format: Literal["csv", "json"]
+
+
@mddoc
class table(UIElement[List[str], Union[List[object], "pd.DataFrame"]]):
"""
@@ -103,6 +110,7 @@ class table(UIElement[List[str], Union[List[object], "pd.DataFrame"]]):
) -> None:
self._data = data
normalized_data = _normalize_data(data)
+ self._normalized_data = normalized_data
# pagination defaults to True if there are more than 10 rows
if pagination is None:
@@ -116,8 +124,16 @@ class table(UIElement[List[str], Union[List[object], "pd.DataFrame"]]):
"data": normalized_data,
"pagination": pagination,
"selection": selection,
+ "show-download": DependencyManager.has_pandas(),
},
on_change=on_change,
+ functions=(
+ Function(
+ name=self.download_as.__name__,
+ arg_cls=DownloadAsArgs,
+ function=self.download_as,
+ ),
+ ),
)
@property
@@ -136,7 +152,32 @@ class table(UIElement[List[str], Union[List[object], "pd.DataFrame"]]):
return self._data.iloc[[int(v) for v in value]]
return [self._data[int(v)] for v in value]
+ def download_as(self, args: DownloadAsArgs) -> str:
+ if not DependencyManager.has_pandas():
+ raise RuntimeError("Pandas must be installed to download tables.")
+
+ import pandas as pd
+
+ # download selected rows if there are any, otherwise use all rows
+ data = self._value if len(self._value) > 0 else self._data
+
+ as_dataframe = (
+ data
+ if isinstance(data, pd.DataFrame)
+ # TODO: fix types to remove type ignore
+ else pd.DataFrame(self._normalized_data) # type:ignore[arg-type]
+ )
+
+ ext = args.format
+ if ext == "csv":
+ return mo_data.csv(as_dataframe).url
+ elif ext == "json":
+ return mo_data.json(as_dataframe).url
+ else:
+ raise ValueError("format must be one of 'csv' or 'json'.")
+
+# TODO: more narrow return type
def _normalize_data(data: TableData) -> JSONType:
# Handle pandas
if DependencyManager.has_pandas():
diff --git a/marimo/_runtime/context.py b/marimo/_runtime/context.py
index 458275b568..f8ad7832ef 100644
--- a/marimo/_runtime/context.py
+++ b/marimo/_runtime/context.py
@@ -14,6 +14,7 @@ from typing import TYPE_CHECKING, Iterator, Optional
from marimo._plugins.ui._core.ids import IDProvider, NoIDProviderException
from marimo._runtime.cell_lifecycle_registry import CellLifecycleRegistry
+from marimo._runtime.functions import FunctionRegistry
if TYPE_CHECKING:
from marimo._ast.cell import CellId_t
@@ -50,6 +51,7 @@ class RuntimeContext:
kernel: Kernel
ui_element_registry: UIElementRegistry
+ function_registry: FunctionRegistry
cell_lifecycle_registry: CellLifecycleRegistry
virtual_file_registry: VirtualFileRegistry
stream: Stream
@@ -119,6 +121,7 @@ def initialize_context(
runtime_context = RuntimeContext(
kernel=kernel,
ui_element_registry=UIElementRegistry(),
+ function_registry=FunctionRegistry(),
cell_lifecycle_registry=CellLifecycleRegistry(),
virtual_file_registry=VirtualFileRegistry(),
stream=stream,
diff --git a/marimo/_runtime/functions.py b/marimo/_runtime/functions.py
new file mode 100644
index 0000000000..3c53ae37a8
--- /dev/null
+++ b/marimo/_runtime/functions.py
@@ -0,0 +1,79 @@
+# Copyright 2023 Marimo. All rights reserved.
+"""Functions associated with a graph.
+"""
+from __future__ import annotations
+
+import dataclasses
+from typing import Any, Callable, Generic, Type, TypeVar
+
+from marimo._ast.cell import CellId_t
+from marimo._utils.parse_dataclass import build_dataclass
+
+S = TypeVar("S")
+T = TypeVar("T")
+
+
+class Function(Generic[S, T]):
+ name: str
+ arg_cls: Type[S]
+ function: Callable[[S], T]
+ cell_id: CellId_t | None
+
+ def __init__(
+ self,
+ name: str,
+ arg_cls: Type[S],
+ function: Callable[[S], T],
+ ) -> None:
+ from marimo._runtime.context import get_context
+
+ self.name = name
+ self.arg_cls = arg_cls
+ self.function = function
+
+ ctx = get_context()
+ if ctx is not None and ctx.kernel.execution_context is not None:
+ self.cell_id = ctx.kernel.execution_context.cell_id
+ else:
+ self.cell_id = None
+
+ def __call__(self, args: dict[Any, Any]) -> T:
+ return self.function(build_dataclass(args, self.arg_cls))
+
+
+class FunctionNamespace:
+ namespace: str
+ functions: dict[str, Function[Any, Any]] = dataclasses.field(
+ default_factory=dict
+ )
+
+ def add(self, function: Function[Any, Any]) -> None:
+ self.functions[function.name] = function
+
+ def get(self, name: str) -> Function[Any, Any] | None:
+ if name in self.functions:
+ return self.functions[name]
+ return None
+
+
+class FunctionRegistry:
+ def __init__(self) -> None:
+ self.namespaces: dict[str, FunctionNamespace] = {}
+
+ def register(self, namespace: str, function: Function[Any, Any]) -> None:
+ if namespace not in self.namespaces:
+ self.namespaces[namespace] = FunctionNamespace(namespace=namespace)
+ self.namespaces[namespace].add(function)
+
+ def get_function(
+ self, namespace: str, function_name: str
+ ) -> Function[Any, Any] | None:
+ if namespace in self.namespaces:
+ return self.namespaces[namespace].get(function_name)
+ return None
+
+ def delete(self, namespace: str) -> None:
+ if namespace in self.namespaces:
+ del self.namespaces[namespace]
diff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.py
index e25d809fb5..24e54c93e5 100644
--- a/marimo/_runtime/requests.py
+++ b/marimo/_runtime/requests.py
@@ -25,6 +25,14 @@ class SetUIElementValueRequest:
ids_and_values: Iterable[tuple[str, Any]]
+@dataclass
+class FunctionCallRequest:
+ function_call_id: str
+ namespace: str
+ function_name: str
+ args: dict[str, Any]
+
+
@dataclass
class SetCellConfigRequest:
configs: dict[CellId_t, dict[str, object]]
@@ -64,6 +72,7 @@ Request = Union[
ExecuteMultipleRequest,
CreationRequest,
DeleteRequest,
+ FunctionCallRequest,
SetCellConfigRequest,
SetUIElementValueRequest,
StopRequest,
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 071fcc6e44..df38247cff 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -31,6 +31,8 @@ from marimo._messaging.errors import (
from marimo._messaging.ops import (
CellOp,
CompletedRun,
+ FunctionCallResult,
+ HumanReadableStatus,
Interrupted,
RemoveUIElements,
VariableDeclaration,
@@ -41,6 +43,7 @@ from marimo._messaging.ops import (
from marimo._messaging.streams import Stderr, Stdout, Stream
from marimo._output import formatting
from marimo._output.rich_help import mddoc
+from marimo._plugins.core.web_component import JSONType
from marimo._plugins.ui._core.ui_element import MarimoConvertValueException
from marimo._runtime import cell_runner, dataflow
from marimo._runtime.complete import complete
@@ -59,6 +62,7 @@ from marimo._runtime.requests import (
DeleteRequest,
ExecuteMultipleRequest,
ExecutionRequest,
+ FunctionCallRequest,
Request,
SetCellConfigRequest,
SetUIElementValueRequest,
@@ -886,6 +890,57 @@ class Kernel:
def reset_ui_initializers(self) -> None:
self.ui_initializers = {}
+ def function_call_request(
+ self, request: FunctionCallRequest
+ ) -> tuple[HumanReadableStatus, JSONType]:
+ function = get_context().function_registry.get_function(
+ request.namespace, request.function_name
+ )
+ error_title, error_message = "", ""
+
+ def debug(title: str, message: str) -> None:
+ return LOGGER.debug("%s: %s", title, message)
+
+ if function is None:
+ error_title = "Function not found"
+ error_message = (
+ "Could not find function given request: %s" % request
+ )
+ debug(error_title, error_message)
+ elif function.cell_id is None:
+ error_title = "Function not associated with cell"
+ error_message = (
+ "Attempted to call a function without a cell id: %s" % request
+ )
+ debug(error_title, error_message)
+ else:
+ with self._install_execution_context(cell_id=function.cell_id):
+ try:
+ return HumanReadableStatus(code="ok"), function(
+ request.args
+ )
+ except MarimoInterrupt:
+ error_title = "Interrupted"
+ error_message = (
+ "Function call (%s) was interrupted by the user"
+ % request.function_name
+ )
+ debug(error_title, error_message)
+ except Exception as e:
+ error_title = "Exception"
+ error_message = (
+ "Function call (name: %s, args: %s) failed with exception %s" # noqa: E501
+ % (request.function_name, request.args, str(e))
+ )
+ debug(error_title, error_message)
+ # Couldn't call function, or function call failed
+ return (
+ HumanReadableStatus(
+ code="error", title=error_title, message=error_message
+ ),
+ None,
+ )
+
def complete(self, request: CompletionRequest) -> None:
"""Code completion"""
if self.completion_thread is None:
@@ -1015,6 +1070,14 @@ def launch_kernel(
elif isinstance(request, SetUIElementValueRequest):
kernel.set_ui_element_value(request)
CompletedRun().broadcast()
+ elif isinstance(request, FunctionCallRequest):
+ status, ret = kernel.function_call_request(request)
+ FunctionCallResult(
+ function_call_id=request.function_call_id,
+ return_value=ret,
+ status=status,
+ ).broadcast()
+ CompletedRun().broadcast()
elif isinstance(request, DeleteRequest):
kernel.delete(request)
elif isinstance(request, CompletionRequest):
diff --git a/marimo/_server/api/__init__.py b/marimo/_server/api/__init__.py
index f0b66cc852..5f062402a8 100644
--- a/marimo/_server/api/__init__.py
+++ b/marimo/_server/api/__init__.py
@@ -4,6 +4,7 @@ __all__ = [
"DeleteHandler",
"DirectoryAutocompleteHandler",
"FormatHandler",
+ "FunctionHandler",
"InstantiateHandler",
"InterruptHandler",
"RenameHandler",
@@ -22,6 +23,7 @@ from marimo._server.api.directory_autocomplete import (
DirectoryAutocompleteHandler,
)
from marimo._server.api.format import FormatHandler
+from marimo._server.api.function_call import FunctionHandler
from marimo._server.api.instantiate import InstantiateHandler
from marimo._server.api.interrupt import InterruptHandler
from marimo._server.api.rename import RenameHandler
diff --git a/marimo/_server/api/code_complete.py b/marimo/_server/api/code_complete.py
index 8b838f19d9..f180dfcc1e 100644
--- a/marimo/_server/api/code_complete.py
+++ b/marimo/_server/api/code_complete.py
@@ -8,7 +8,7 @@ import tornado.web
from marimo._ast.cell import CellId_t
from marimo._runtime import requests
from marimo._server import sessions
-from marimo._server.api.model import parse_raw
+from marimo._utils.parse_dataclass import parse_raw
@dataclass
diff --git a/marimo/_server/api/delete.py b/marimo/_server/api/delete.py
index 01402c07d8..a4ce467d04 100644
--- a/marimo/_server/api/delete.py
+++ b/marimo/_server/api/delete.py
@@ -8,7 +8,7 @@ import tornado.web
from marimo._ast.cell import CellId_t
from marimo._runtime import requests
from marimo._server import sessions
-from marimo._server.api.model import parse_raw
+from marimo._utils.parse_dataclass import parse_raw
@dataclass
diff --git a/marimo/_server/api/directory_autocomplete.py b/marimo/_server/api/directory_autocomplete.py
index 2ceb26266f..739d84d590 100644
--- a/marimo/_server/api/directory_autocomplete.py
+++ b/marimo/_server/api/directory_autocomplete.py
@@ -6,7 +6,7 @@ from dataclasses import dataclass
import tornado.web
-from marimo._server.api.model import parse_raw
+from marimo._utils.parse_dataclass import parse_raw
@dataclass
diff --git a/marimo/_server/api/format.py b/marimo/_server/api/format.py
index fd6cc30ee8..646a2a160d 100644
--- a/marimo/_server/api/format.py
+++ b/marimo/_server/api/format.py
@@ -9,7 +9,7 @@ import tornado.web
from marimo import _loggers
from marimo._ast import cell
from marimo._server import sessions
-from marimo._server.api.model import parse_raw
+from marimo._utils.parse_dataclass import parse_raw
LOGGER = _loggers.marimo_logger()
diff --git a/marimo/_server/api/function_call.py b/marimo/_server/api/function_call.py
new file mode 100644
index 0000000000..e2eb6659c7
--- /dev/null
+++ b/marimo/_server/api/function_call.py
@@ -0,0 +1,38 @@
+# Copyright 2023 Marimo. All rights reserved.
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any, Dict
+
+import tornado.web
+
+from marimo import _loggers
+from marimo._runtime import requests
+from marimo._server import sessions
+from marimo._utils.parse_dataclass import parse_raw
+
+LOGGER = _loggers.marimo_logger()
+
+
+@dataclass
+class FunctionCall:
+ # unique token associated with the function call
+ function_call_id: str
+ namespace: str
+ function_name: str
+ args: Dict[str, Any]
+
+
+class FunctionHandler(tornado.web.RequestHandler):
+ """Invoke an RPC"""
+
+ def post(self) -> None:
+ session = sessions.require_session_from_header(self.request.headers)
+ args = parse_raw(self.request.body, FunctionCall)
+ request = requests.FunctionCallRequest(
+ function_call_id=args.function_call_id,
+ namespace=args.namespace,
+ function_name=args.function_name,
+ args=args.args,
+ )
+ session.queue.put(request)
diff --git a/marimo/_server/api/instantiate.py b/marimo/_server/api/instantiate.py
index 4f33688ba3..1d1102e876 100644
--- a/marimo/_server/api/instantiate.py
+++ b/marimo/_server/api/instantiate.py
@@ -9,7 +9,7 @@ import tornado.web
from marimo._ast.app import App
from marimo._runtime import requests
from marimo._server import sessions
-from marimo._server.api.model import parse_raw
+from marimo._utils.parse_dataclass import parse_raw
@dataclass
diff --git a/marimo/_server/api/rename.py b/marimo/_server/api/rename.py
index 2bbfe22f7d..2f7be7efc2 100644
--- a/marimo/_server/api/rename.py
+++ b/marimo/_server/api/rename.py
@@ -9,8 +9,8 @@ import tornado.web
from marimo import _loggers
from marimo._server import sessions
from marimo._server.api import status
-from marimo._server.api.model import parse_raw
from marimo._server.utils import canonicalize_filename
+from marimo._utils.parse_dataclass import parse_raw
LOGGER = _loggers.marimo_logger()
diff --git a/marimo/_server/api/run.py b/marimo/_server/api/run.py
index e61370c7b0..dbd799ee02 100644
--- a/marimo/_server/api/run.py
+++ b/marimo/_server/api/run.py
@@ -9,7 +9,7 @@ import tornado.web
from marimo._ast.cell import CellId_t
from marimo._runtime import requests
from marimo._server import sessions
-from marimo._server.api.model import parse_raw
+from marimo._utils.parse_dataclass import parse_raw
@dataclass
diff --git a/marimo/_server/api/save.py b/marimo/_server/api/save.py
index 5811f188d3..6f705c029b 100644
--- a/marimo/_server/api/save.py
+++ b/marimo/_server/api/save.py
@@ -11,10 +11,10 @@ from marimo import _loggers
from marimo._ast import codegen
from marimo._ast.cell import CellConfig
from marimo._server import sessions
-from marimo._server.api.model import parse_raw
from marimo._server.api.status import HTTPStatus
from marimo._server.layout import LayoutConfig, save_layout_config
from marimo._server.utils import canonicalize_filename
+from marimo._utils.parse_dataclass import parse_raw
LOGGER = _loggers.marimo_logger()
diff --git a/marimo/_server/api/save_app_config.py b/marimo/_server/api/save_app_config.py
index 8435c26461..6ede662f42 100644
--- a/marimo/_server/api/save_app_config.py
+++ b/marimo/_server/api/save_app_config.py
@@ -9,8 +9,8 @@ import tornado.web
from marimo import _loggers
from marimo._ast import codegen
from marimo._server import sessions
-from marimo._server.api.model import parse_raw
from marimo._server.api.status import HTTPStatus
+from marimo._utils.parse_dataclass import parse_raw
LOGGER = _loggers.marimo_logger()
diff --git a/marimo/_server/api/save_user_config.py b/marimo/_server/api/save_user_config.py
index d2a3aa9a9a..af6c9bd7a3 100644
--- a/marimo/_server/api/save_user_config.py
+++ b/marimo/_server/api/save_user_config.py
@@ -13,8 +13,8 @@ from marimo._config.config import MarimoConfig, configure
from marimo._config.utils import get_config_path
from marimo._runtime import requests
from marimo._server import sessions
-from marimo._server.api.model import parse_raw
from marimo._server.api.status import HTTPStatus
+from marimo._utils.parse_dataclass import parse_raw
LOGGER = _loggers.marimo_logger()
diff --git a/marimo/_server/api/set_cell_config.py b/marimo/_server/api/set_cell_config.py
index 05d284e299..241f366664 100644
--- a/marimo/_server/api/set_cell_config.py
+++ b/marimo/_server/api/set_cell_config.py
@@ -9,7 +9,7 @@ import tornado.web
from marimo._ast.cell import CellId_t
from marimo._runtime import requests
from marimo._server import sessions
-from marimo._server.api.model import parse_raw
+from marimo._utils.parse_dataclass import parse_raw
@dataclass
diff --git a/marimo/_server/api/set_ui_element_value.py b/marimo/_server/api/set_ui_element_value.py
index 3a6d0f751d..fd5523c02c 100644
--- a/marimo/_server/api/set_ui_element_value.py
+++ b/marimo/_server/api/set_ui_element_value.py
@@ -8,7 +8,7 @@ import tornado.web
from marimo._runtime import requests
from marimo._server import sessions
-from marimo._server.api.model import parse_raw
+from marimo._utils.parse_dataclass import parse_raw
@dataclass
diff --git a/marimo/_server/server.py b/marimo/_server/server.py
index 36c99f644a..5ae99ee1a4 100644
--- a/marimo/_server/server.py
+++ b/marimo/_server/server.py
@@ -157,6 +157,10 @@ def construct_app(
r"/api/kernel/set_ui_element_value/",
api.SetUIElementValueHandler,
),
+ (
+ r"/api/kernel/function_call/",
+ api.FunctionHandler,
+ ),
(
r"/api/kernel/set_cell_config/",
api.SetCellConfigHandler,
diff --git a/marimo/_server/api/model.py b/marimo/_utils/parse_dataclass.py
similarity index 92%
rename from marimo/_server/api/model.py
rename to marimo/_utils/parse_dataclass.py
index bef72d2c28..72cb33eca2 100644
--- a/marimo/_server/api/model.py
+++ b/marimo/_utils/parse_dataclass.py
@@ -38,12 +38,12 @@ def _build_value(value: Any, cls: Type[T]) -> T:
}
)
elif dataclasses.is_dataclass(cls):
- return _build_dataclass(value, cls) # type: ignore[return-value]
+ return build_dataclass(value, cls) # type: ignore[return-value]
else:
return value # type: ignore[no-any-return]
-def _build_dataclass(value: dict[Any, Any], cls: Type[T]) -> T:
+def build_dataclass(value: dict[Any, Any], cls: Type[T]) -> T:
types = get_type_hints(cls)
transformed = {
to_snake(k): _build_value(v, types[to_snake(k)])
@@ -70,4 +70,4 @@ def parse_raw(message: bytes, cls: Type[T]) -> T:
cls: the type to instantiate
"""
parsed = json.loads(message)
- return _build_dataclass(parsed, cls)
+ return build_dataclass(parsed, cls)
diff --git a/marimo/_server/api/test_model.py b/marimo/_utils/test_parse_dataclass.py
similarity index 98%
rename from marimo/_server/api/test_model.py
rename to marimo/_utils/test_parse_dataclass.py
index bff7ece757..59b9653cd3 100644
--- a/marimo/_server/api/test_model.py
+++ b/marimo/_utils/test_parse_dataclass.py
@@ -6,8 +6,8 @@ from dataclasses import asdict, dataclass
from typing import Any, Dict, List, Tuple
from marimo._server import api
-from marimo._server.api.model import parse_raw
from marimo._server.api.set_cell_config import SetCellConfig
+from marimo._utils.parse_dataclass import parse_raw
@dataclass