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
fix: fix stale values in DictPlugin and allow re-submitting in FormPlugin (#276)
Myles Scolnick54629846a529
diff --git a/frontend/src/core/dom/htmlUtils.ts b/frontend/src/core/dom/htmlUtils.tsindex 32a9fe0fd4..d7d78bf9f2 100644--- a/frontend/src/core/dom/htmlUtils.ts+++ b/frontend/src/core/dom/htmlUtils.ts@@ -2,6 +2,7 @@import { assertExists } from "@/utils/assertExists";import { UI_ELEMENT_REGISTRY } from "./uiregistry";import { jsonParseWithSpecialChar } from "@/utils/json-parser";+import { Objects } from "@/utils/objects";/*** Parse an attribute value as JSON.@@ -10,6 +11,12 @@ export function parseAttrValue<T>(value: string | undefined): T {return jsonParseWithSpecialChar(value ?? "");}+export function parseDataset(element: HTMLElement): Record<string, unknown> {+ return Objects.mapValues(element.dataset, (value) =>+ typeof value === "string" ? parseAttrValue(value) : value+ );+}+/*** Parse the initial value.* It will first check if the parent element is a <marimo-ui-element/> with an object-id thatdiff --git a/frontend/src/plugins/core/registerReactComponent.tsx b/frontend/src/plugins/core/registerReactComponent.tsxindex 21c4a6177d..e9a12cfbf4 100644--- a/frontend/src/plugins/core/registerReactComponent.tsx+++ b/frontend/src/plugins/core/registerReactComponent.tsx@@ -10,11 +10,10 @@import React, {createRef,ReactNode,- useCallback,+ SetStateAction,useEffect,useImperativeHandle,useMemo,- useRef,useState,} from "react";import ReactDOM, { Root } from "react-dom/client";@@ -25,7 +24,11 @@ import {MarimoValueUpdateEventType,} from "@/core/dom/events";import { defineCustomElement } from "../../core/dom/defineCustomElement";-import { parseAttrValue, parseInitialValue } from "../../core/dom/htmlUtils";+import {+ parseAttrValue,+ parseDataset,+ parseInitialValue,+} from "../../core/dom/htmlUtils";import { IPlugin } from "../types";import { Objects } from "../../utils/objects";import { renderError } from "./BadPlugin";@@ -37,6 +40,8 @@ import { FUNCTIONS_REGISTRY } from "@/core/functions/FunctionRegistry";import { getUIElementObjectId } from "@/core/dom/UIElement";import { PluginFunctions } from "./rpc";import { ZodSchema } from "zod";+import useEvent from "react-use-event-hook";+import { Functions } from "@/utils/functions";export interface PluginSlotHandle {/**@@ -67,44 +72,20 @@ function PluginSlotInternal<T>(const [value, setValue] = useState<T>(getInitialValue());const { theme } = useThemeForPlugin();- const [parseResult, setParseResult] = useState(() => {- return plugin.validator.safeParse({- // For any string values, unescape/parse them- ...Objects.mapValues(hostElement.dataset, (value) =>- typeof value === "string" ? parseAttrValue(value) : value- ),- });+ const [parsedResult, setParsedResult] = useState(() => {+ return plugin.validator.safeParse(parseDataset(hostElement));});useImperativeHandle(ref, () => ({reset: () => {setValue(getInitialValue());- setParseResult(- plugin.validator.safeParse({- // For any string values, unescape/parse them- ...Objects.mapValues(hostElement.dataset, (value) =>- typeof value === "string" ? parseAttrValue(value) : value- ),- })- );+ setParsedResult(plugin.validator.safeParse(parseDataset(hostElement)));},setChildren: (children) => {setChildNodes(children);},}));- // When the component's value changes due to an interaction, an input- // event should be dispatched; an event should not be dispatched when- // the value changes due to an update event broadcast by another component.- // TODO: is this still needed ...? might want to dispatch value update- // even when value hasn't changed (so python kernel gets triggered ...)- const shouldDispatchInput = useRef(false);-- if (shouldDispatchInput.current) {- hostElement.dispatchEvent(createInputEvent(value, hostElement));- shouldDispatchInput.current = false;- }-useEffect(() => {const handleValue = (e: MarimoValueUpdateEventType) => {if (e.detail.element === hostElement) {@@ -120,14 +101,7 @@ function PluginSlotInternal<T>(mutation.attributeName?.startsWith("data-"));if (hasAttributeMutation) {- setParseResult(- plugin.validator.safeParse({- // For any string values, unescape/parse them- ...Objects.mapValues(hostElement.dataset, (value) =>- typeof value === "string" ? parseAttrValue(value) : value- ),- })- );+ setParsedResult(plugin.validator.safeParse(parseDataset(hostElement)));}});@@ -144,13 +118,15 @@ function PluginSlotInternal<T>(};}, [hostElement, plugin.validator]);- const setValueAndSendInput = useCallback(- (value: T | ((prevValue: T) => T)): void => {- shouldDispatchInput.current = true;- setValue(value);- },- [setValue, shouldDispatchInput]- );+ // When the value changes, send an input event+ const setValueAndSendInput = useEvent((value: SetStateAction<T>): void => {+ setValue((prevValue) => {+ const updater = Functions.asUpdater(value);+ const nextValue = updater(prevValue);+ hostElement.dispatchEvent(createInputEvent(nextValue, hostElement));+ return nextValue;+ });+ });// Create a map of functions that can be called by the pluginconst functionMethods = useMemo<PluginFunctions>(() => {@@ -188,9 +164,9 @@ function PluginSlotInternal<T>(}, [plugin.functions, hostElement]);// If we failed to parse the initial value, render an error- if (!parseResult.success) {+ if (!parsedResult.success) {return renderError(- parseResult.error,+ parsedResult.error,Objects.mapValues(hostElement.dataset, (value) =>typeof value === "string" ? parseAttrValue(value) : value),@@ -204,7 +180,7 @@ function PluginSlotInternal<T>({plugin.render({setValue: setValueAndSendInput,value,- data: parseResult.data,+ data: parsedResult.data,children: childNodes,host: hostElement,functions: functionMethods,diff --git a/frontend/src/plugins/impl/DictPlugin.tsx b/frontend/src/plugins/impl/DictPlugin.tsxindex ce646c623b..dc1b56cc89 100644--- a/frontend/src/plugins/impl/DictPlugin.tsx+++ b/frontend/src/plugins/impl/DictPlugin.tsx@@ -64,12 +64,11 @@ const Dict = ({// If the UI element firing the event is not in the dict, ignore itreturn;}-- // Tell Python to update the dict at the given key with the new value- setValue(() => {- const updates: Record<string, unknown> = {};- updates[key] = e.detail.value;- return updates;+ // Update the dict at the given key with the new value+ setValue((prevValue) => {+ const nextValue = prevValue ? { ...prevValue } : {};+ nextValue[key] = e.detail.value;+ return nextValue;});};document.addEventListener(marimoValueInputEvent, handleUpdate);diff --git a/frontend/src/utils/functions.ts b/frontend/src/utils/functions.tsindex 77b39c7f2c..2a928f13ce 100644--- a/frontend/src/utils/functions.ts+++ b/frontend/src/utils/functions.ts@@ -6,4 +6,9 @@ export const Functions = {THROW: () => {throw new Error("Should not be called");},+ asUpdater: <T>(updater: T | ((value: T) => T)): ((value: T) => T) => {+ return typeof updater === "function"+ ? (updater as (value: T) => T)+ : () => updater;+ },};diff --git a/marimo/_plugins/ui/_impl/array.py b/marimo/_plugins/ui/_impl/array.pyindex db44ce97a6..a9117028ad 100644--- a/marimo/_plugins/ui/_impl/array.py+++ b/marimo/_plugins/ui/_impl/array.py@@ -96,7 +96,10 @@ class array(UIElement[Dict[str, JSONType], Sequence[object]]):def _convert_value(self, value: dict[str, JSONType]) -> Sequence[object]:if self._initialized:for k, v in value.items():- self._elements[int(k)]._update(v)+ element = self._elements[int(k)]+ # only call update if the value has changed+ if element and element._value != v:+ element._update(v)return [e._value for e in self._elements]def _clone(self) -> array:diff --git a/marimo/_smoke_tests/forms.py b/marimo/_smoke_tests/forms.pynew file mode 100644index 0000000000..32bb98207a--- /dev/null+++ b/marimo/_smoke_tests/forms.py@@ -0,0 +1,116 @@+import marimo++__generated_with = "0.1.39"+app = marimo.App()+++def __():+ import marimo as mo+ import random+ return mo, random+++def __(mo):+ form_1 = mo.ui.text_area(label="Form 1").form()+ form_1+ return form_1,+++def __(form_1, mo, random):+ random_number = random.randint(1, 100)+ mo.vstack(+ [+ mo.md("### Form 1 Value"),+ mo.md(f"Random number **{random_number}**"),+ form_1.value,+ ]+ )+ return random_number,+++def __(mo):+ fn = mo.ui.text()+ ln = mo.ui.text()+ return fn, ln+++def __(fn, ln, mo):+ years_experience = mo.ui.slider(1, 10, value=4)+ form_2 = (+ mo.md(+ """+ First name: {first_name}++ Last name: {last_name}++ Years Experience: {years_experience}+ """+ )+ .batch(+ first_name=fn,+ last_name=ln,+ years_experience=years_experience,+ )+ .form()+ )++ form_2+ return form_2, years_experience+++def __(form_2, mo, random):+ _random_number = random.randint(1, 100)+ mo.vstack(+ [+ mo.md("### Form 2 Value"),+ mo.md(f"Random number **{_random_number}**"),+ form_2.value,+ ]+ )+ return+++def __(mo):+ mo.md("## Dictionary")+ return+++def __(mo):+ dict = mo.ui.dictionary(+ {+ "slider": mo.ui.slider(1, 10),+ "text": mo.ui.text("type something!"),+ "array": mo.ui.array(+ [+ mo.ui.button(value=0, on_click=lambda v: v + 1)+ for _ in range(3)+ ],+ label="buttons",+ ),+ }+ )+ dict+ return dict,+++def __(dict, mo):+ mo.vstack(+ [+ mo.md("### Dict Value"),+ dict.value,+ ]+ )+ return+++if __name__ == "__main__":+ app.run()