A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
improvement: form customization options and validation (#614)
Myles Scolnickaaf36a7bce80
diff --git a/frontend/.storybook/preview.tsx b/frontend/.storybook/preview.tsxindex d898daab5f..20a53b2c6e 100644--- a/frontend/.storybook/preview.tsx+++ b/frontend/.storybook/preview.tsx@@ -6,6 +6,7 @@ import "tailwindcss/tailwind.css";import React, { useEffect } from "react";import { cn } from "../src/utils/cn";import { TooltipProvider } from "../src/components/ui/tooltip";+import { Toaster } from "../src/components/ui/toaster";import { TailwindIndicator } from "../src/components/ui/tailwind-indicator";const withTheme: Decorator = (Story, context) => {@@ -19,6 +20,7 @@ const withTheme: Decorator = (Story, context) => {<div className={cn(theme, "p-5")}><TooltipProvider><Story />+ <Toaster /><TailwindIndicator /></TooltipProvider></div>diff --git a/frontend/src/core/dom/UIElement.ts b/frontend/src/core/dom/UIElement.tsindex d55c38d635..2ae9356245 100644--- a/frontend/src/core/dom/UIElement.ts+++ b/frontend/src/core/dom/UIElement.ts@@ -1,4 +1,5 @@/* Copyright 2024 Marimo. All rights reserved. */+import { isCustomMarimoElement } from "@/plugins/core/registerReactComponent";import { Logger } from "../../utils/Logger";import { Functions } from "../../utils/functions";import { UIElementId } from "../cells/ids";@@ -8,6 +9,10 @@ import { UI_ELEMENT_REGISTRY } from "./uiregistry";const UI_ELEMENT_TAG_NAME = "MARIMO-UI-ELEMENT";+interface IUIElement extends HTMLElement {+ reset(): void;+}+/*** Lazily initialize the UIElement component.*/@@ -72,7 +77,7 @@ export function initializeUIElement() {* events and updating their value internally.**/- class UIElement extends HTMLElement {+ class UIElement extends HTMLElement implements IUIElement {private initialized = false;private inputListener: (e: MarimoValueInputEventType) => void =Functions.NOOP;@@ -145,6 +150,20 @@ export function initializeUIElement() {}}+ /**+ * Reset the value of the child element to its initial value.+ */+ reset() {+ const child = this.firstElementChild;+ if (isCustomMarimoElement(child)) {+ child.reset();+ } else {+ Logger.error(+ "[marimo-ui-element] first child must have a reset method"+ );+ }+ }+// We look for changes to the random-id attribute, which is effectively// used like a React key. If the random-id changes, we need to unmount and// remount its child.@@ -165,9 +184,8 @@ export function initializeUIElement() {// remove and re-add its child to force it to re-render; note that// this doesn't reconstruct the UI element, only its childconst child = this.firstElementChild;- if (child && "rerender" in child) {- // eslint-disable-next-line @typescript-eslint/no-explicit-any- (child as any).rerender();+ if (isCustomMarimoElement(child)) {+ child.rerender();} else {Logger.error("[marimo-ui-element] first child must have a rerender method"@@ -204,3 +222,7 @@ export function getUIElementObjectId(target: HTMLElement): UIElementId | null {return null;}++export function isUIElement(target: HTMLElement): target is IUIElement {+ return target.tagName === UI_ELEMENT_TAG_NAME;+}diff --git a/frontend/src/plugins/core/registerReactComponent.tsx b/frontend/src/plugins/core/registerReactComponent.tsxindex 2239e6c76f..cfff0f0a05 100644--- a/frontend/src/plugins/core/registerReactComponent.tsx+++ b/frontend/src/plugins/core/registerReactComponent.tsx@@ -60,6 +60,17 @@ export interface PluginSlotHandle {setChildren: (children: ReactNode) => void;}+export interface IMarimoHTMLElement extends HTMLElement {+ /**+ * Reset the plugin initial value and data.+ */+ reset: () => void;+ /**+ * Re-render the plugin.+ */+ rerender: () => void;+}+interface PluginSlotProps<T> {hostElement: HTMLElement;plugin: IPlugin<T, unknown>;@@ -203,6 +214,8 @@ const PluginSlot: React.ForwardRefExoticComponent<const styleSheetCache = new Map<string, CSSStyleSheet>();+const customElementLocator = "__custom_marimo_element__";+/*** Register a React component as a custom element*@@ -225,11 +238,12 @@ const styleSheetCache = new Map<string, CSSStyleSheet>();* and the React component to render*/export function registerReactComponent<T>(plugin: IPlugin<T, unknown>): void {- const WebComponent = class extends HTMLElement {+ const WebComponent = class extends HTMLElement implements IMarimoHTMLElement {private observer: MutationObserver;private root?: Root;private mounted = false;private pluginRef = createRef<PluginSlotHandle>();+ protected __type__ = customElementLocator;constructor() {super();@@ -277,6 +291,20 @@ export function registerReactComponent<T>(plugin: IPlugin<T, unknown>): void {}}+ /**+ * Reset the plugin initial value and data.+ * And then re-render the plugin.+ */+ reset() {+ this.dispatchEvent(+ createInputEvent(parseAttrValue(this.dataset.initialValue), this)+ );+ this.rerender();+ }++ /**+ * Re-render the plugin.+ */rerender() {this.pluginRef.current?.reset();}@@ -412,3 +440,16 @@ function shouldCopyStyleSheet(sheet: CSSStyleSheet): boolean {return sheet.href.startsWith(window.location.origin);}++export function isCustomMarimoElement(+ element: Element | null+): element is IMarimoHTMLElement {+ if (!element) {+ return false;+ }+ if (!(element instanceof HTMLElement)) {+ return false;+ }++ return "__type__" in element && element.__type__ === customElementLocator;+}diff --git a/frontend/src/plugins/impl/ButtonPlugin.tsx b/frontend/src/plugins/impl/ButtonPlugin.tsxindex 8243eacb17..2abf87ddad 100644--- a/frontend/src/plugins/impl/ButtonPlugin.tsx+++ b/frontend/src/plugins/impl/ButtonPlugin.tsx@@ -6,12 +6,14 @@ import { Button } from "../../components/ui/button";import { renderHTML } from "../core/RenderHTML";import { Intent, zodIntent } from "./common/intent";import { cn } from "@/utils/cn";+import { Tooltip, TooltipProvider } from "@/components/ui/tooltip";interface Data {label: string;kind: Intent;disabled: boolean;fullWidth: boolean;+ tooltip?: string;}export class ButtonPlugin implements IPlugin<number, Data> {@@ -22,14 +24,15 @@ export class ButtonPlugin implements IPlugin<number, Data> {kind: zodIntent,disabled: z.boolean().default(false),fullWidth: z.boolean().default(false),+ tooltip: z.string().optional(),});render(props: IPluginProps<number, Data>): JSX.Element {const {- data: { disabled, kind, label, fullWidth },+ data: { disabled, kind, label, fullWidth, tooltip },} = props;// value counts number of times button was clicked- return (+ const button = (<Buttonvariant={kindToButtonVariant(kind)}disabled={disabled}@@ -48,6 +51,16 @@ export class ButtonPlugin implements IPlugin<number, Data> {{renderHTML({ html: label })}</Button>);++ if (tooltip) {+ return (+ <TooltipProvider>+ <Tooltip content={tooltip}>{button}</Tooltip>+ </TooltipProvider>+ );+ }++ return button;}}diff --git a/frontend/src/plugins/impl/FormPlugin.tsx b/frontend/src/plugins/impl/FormPlugin.tsxindex ad8b01a135..e5f87048f2 100644--- a/frontend/src/plugins/impl/FormPlugin.tsx+++ b/frontend/src/plugins/impl/FormPlugin.tsx@@ -1,107 +1,216 @@/* Copyright 2024 Marimo. All rights reserved. */-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import { z } from "zod";-import { getUIElementObjectId } from "../../core/dom/UIElement";+import { getUIElementObjectId, isUIElement } from "../../core/dom/UIElement";import {marimoValueInputEvent,MarimoValueInputEventType,} from "@/core/dom/events";-import { IPlugin, IPluginProps, Setter } from "../types";+import { Setter } from "../types";import { Button } from "../../components/ui/button";import { UI_ELEMENT_REGISTRY } from "@/core/dom/uiregistry";import { cn } from "../../utils/cn";import { renderHTML } from "../core/RenderHTML";+import { Loader2Icon } from "lucide-react";+import { Tooltip, TooltipProvider } from "@/components/ui/tooltip";+import { createPlugin } from "../core/builder";+import { rpc } from "../core/rpc";+import { Banner } from "./common/error-banner";type T = unknown;interface Data {label: string | null;elementId: string;+ bordered: boolean;+ loading: boolean;+ submitButtonLabel: string;+ submitButtonTooltip?: string;+ submitButtonDisabled: boolean;+ clearOnSubmit: boolean;+ showClearButton: boolean;+ clearButtonLabel: string;+ clearButtonTooltip?: string;+ shouldValidate?: boolean;}-/** FormPlugin+/**+ * FormPlugin** Associates a plugin with a submit button. The associated plugin's* value updates are captured by this plugin; when the submit button* is clicked, this plugin assumes the value of the associated plugin.*/-export class FormPlugin implements IPlugin<T, Data> {- tagName = "marimo-form";- validator = z.object({- label: z.string().nullable(),- elementId: z.string(),- });+// eslint-disable-next-line @typescript-eslint/consistent-type-definitions+type Functions = {+ validate: (req: { value?: unknown }) => Promise<string | undefined | null>;+};- render(props: IPluginProps<T, Data>): JSX.Element {+export const FormPlugin = createPlugin("marimo-form")+ .withData<Data>(+ z.object({+ label: z.string().nullable(),+ elementId: z.string(),+ bordered: z.boolean().default(true),+ loading: z.boolean().default(false),+ submitButtonLabel: z.string().default("Submit"),+ submitButtonTooltip: z.string().optional(),+ submitButtonDisabled: z.boolean().default(false),+ clearOnSubmit: z.boolean().default(false),+ showClearButton: z.boolean().default(false),+ clearButtonLabel: z.string().default("Clear"),+ clearButtonTooltip: z.string().optional(),+ shouldValidate: z.boolean().optional(),+ })+ )+ .withFunctions<Functions>({+ validate: rpc+ .input(z.object({ value: z.unknown() }))+ .output(z.string().nullish()),+ })+ .renderer(({ data, functions, ...rest }) => {return (- <Form {...props.data} value={props.value} setValue={props.setValue}>- {props.children}- </Form>+ <TooltipProvider>+ <Form {...data} {...rest} {...functions} />+ </TooltipProvider>);- }-}+ });-interface SubmitBoxProps<T> {+export interface FormWrapperProps<T>+ extends Omit<Data, "elementId">,+ Functions {children: React.ReactNode;currentValue: T;newValue: T;setValue: Setter<T>;- label: string | null;}-const SubmitBox = <T,>({+export const FormWrapper = <T,>({children,currentValue,newValue,setValue,label,-}: SubmitBoxProps<T>) => {+ bordered,+ loading,+ submitButtonLabel,+ submitButtonTooltip,+ submitButtonDisabled,+ clearOnSubmit,+ showClearButton,+ clearButtonLabel,+ clearButtonTooltip,+ validate,+ shouldValidate,+}: FormWrapperProps<T>) => {+ const formDiv = useRef<HTMLFormElement>(null);const synchronized = newValue === currentValue;const variant = synchronized ? "secondary" : "action";+ const [error, setError] = useState<string | null>(null);++ const clear = () => {+ if (formDiv.current) {+ clearInputs(formDiv.current);+ }+ };return (- <div- className={cn("rounded-lg border mt-2 mb-2 shadow-md", {- "bg-[var(--gray-1)] border-input": synchronized,- "bg-[var(--amber-1)] border-[var(--amber-7)]": !synchronized,- })}- onKeyDown={(evt) => {- // Handle enter + ctrl/meta key- if (evt.key === "Enter" && (evt.ctrlKey || evt.metaKey)) {- evt.preventDefault();- evt.stopPropagation();- setValue(newValue);+ <form+ className="contents"+ ref={formDiv}+ onSubmit={async (evt) => {+ evt.preventDefault();++ if (shouldValidate) {+ const response = await validate({ value: newValue }).catch(+ (error_) => {+ setError(error_.message ?? "Error validating");+ }+ );+ if (response != null) {+ setError(response);+ return;+ }+ }++ setError(null);+ setValue(newValue);+ if (clearOnSubmit) {+ clear();}}}>- {label === null ? null : (- <div className="text-center mt-4">{renderHTML({ html: label })}</div>- )}- <div className="pl-12 pr-12 pt-4">{children}</div>- <div className="text-right mt-0.5 font-code p-4">- <Button- variant={variant}- onClick={() => {+ <div+ className={cn("flex flex-col gap-4 rounded-lg py-4 px-8", {+ "bg-[var(--gray-1)] shadow-md border border-input": bordered,+ "bg-[var(--amber-1)] border-[var(--amber-7)]":+ !synchronized && bordered,+ })}+ onKeyDown={(evt) => {+ // Handle enter + ctrl/meta key+ if (evt.key === "Enter" && (evt.ctrlKey || evt.metaKey)) {+ evt.preventDefault();+ evt.stopPropagation();setValue(newValue);- }}- type="submit"- >- Submit- </Button>+ }+ }}+ >+ {label === null ? null : (+ <div className="text-center">{renderHTML({ html: label })}</div>+ )}+ {error != null && (+ <Banner kind="danger" className="rounded">+ {error ?? "Invalid input"}+ </Banner>+ )}+ <div>{children}</div>+ <div className="flex justify-end gap-2 font-code">+ {showClearButton &&+ withTooltip(+ <Button+ variant="text"+ onClick={(e) => {+ e.preventDefault();+ clear();+ }}+ >+ {clearButtonLabel}+ </Button>,+ clearButtonTooltip+ )}+ {withTooltip(+ <Button+ variant={variant}+ disabled={submitButtonDisabled || loading}+ type="submit"+ >+ {loading && <Loader2Icon className="h-4 w-4 mr-2 animate-spin" />}+ {submitButtonLabel}+ </Button>,+ submitButtonTooltip+ )}+ </div></div>- </div>+ </form>);};-interface SubmitProps extends Data {+interface FormProps extends Data, Functions {value: T;setValue: Setter<T>;children?: React.ReactNode | undefined;}-const Form = ({ elementId, value, setValue, children, label }: SubmitProps) => {+const Form = ({+ elementId,+ value,+ setValue,+ children,+ validate,+ ...data+}: FormProps) => {// The internal (buffered) value is initialized as the current value of the// wrapped plugin; this buffered value is in contrast to the actual// value of the plugin, which is the value of the wrapped plugin when@@ -135,13 +244,42 @@ const Form = ({ elementId, value, setValue, children, label }: SubmitProps) => {}, [elementId, setValue]);return (- <SubmitBox<T>+ <FormWrapper<T>currentValue={value}newValue={internalValue}setValue={setValue}- label={label}+ validate={validate}+ {...data}>{children}- </SubmitBox>+ </FormWrapper>);};++function withTooltip(element: JSX.Element, tooltip?: string) {+ if (tooltip) {+ return <Tooltip content={tooltip}>{element}</Tooltip>;+ }+ return element;+}++/**+ * Traverse the input elements and find all IUIElement instances and reset them.+ */+function clearInputs(element: Element) {+ if (!(element instanceof HTMLElement)) {+ return;+ }++ // If the element has a shadowRoot, traverse its children+ if (element.shadowRoot) {+ [...element.shadowRoot.children].forEach(clearInputs);+ }++ // Traverse the children of the element in the light DOM+ [...element.children].forEach(clearInputs);++ if (isUIElement(element)) {+ element.reset();+ }+}diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.tsindex c5a816e007..7a4a2724c4 100644--- a/frontend/src/plugins/plugins.ts+++ b/frontend/src/plugins/plugins.ts@@ -45,7 +45,7 @@ export const UI_PLUGINS: Array<IPlugin<any, unknown>> = [new CodeEditorPlugin(),new DropdownPlugin(),new FileUploadPlugin(),- new FormPlugin(),+ FormPlugin,new MicrophonePlugin(),new MultiselectPlugin(),new NumberPlugin(),diff --git a/frontend/src/stories/form-wrapper.stories.tsx b/frontend/src/stories/form-wrapper.stories.tsxnew file mode 100644index 0000000000..83eaded998--- /dev/null+++ b/frontend/src/stories/form-wrapper.stories.tsx@@ -0,0 +1,147 @@+/* Copyright 2024 Marimo. All rights reserved. */+import type { Meta, StoryObj } from "@storybook/react";+import { TooltipProvider } from "../components/ui/tooltip";+import { FormWrapper, FormWrapperProps } from "@/plugins/impl/FormPlugin";+import { Input } from "@/components/ui/input";+import { Textarea } from "@/components/ui/textarea";+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";+import { Checkbox } from "@/components/ui/checkbox";+import { toast } from "@/components/ui/use-toast";++const meta: Meta<typeof FormWrapper> = {+ title: "FormWrapper",+ component: FormWrapper,+ args: {},+};++export default meta;+type Story = StoryObj<typeof FormWrapper>;++const props: FormWrapperProps<string> = {+ currentValue: "currentValue",+ newValue: "currentValue",+ setValue: (v) => {+ toast({+ title: "Form submitted",+ });+ },+ children: (+ <div className="space-y-4">+ <Input />+ <Checkbox />+ <Textarea />+ <RadioGroup>+ One+ <RadioGroupItem value="1" />+ Two+ <RadioGroupItem value="2" />+ </RadioGroup>+ </div>+ ),+ label: "My Form",+ bordered: true,+ loading: false,+ submitButtonLabel: "Submit",+ submitButtonTooltip: "Submit the form",+ submitButtonDisabled: false,+ clearOnSubmit: false,+ showClearButton: false,+ clearButtonLabel: "Clear",+ clearButtonTooltip: "Clear the form",+ shouldValidate: false,+ validate: async () => {+ return null;+ },+};++export const Primary: Story = {+ render: () => (+ <div className="p-20 max-w-4xl">+ <TooltipProvider>+ <FormWrapper {...props} />+ </TooltipProvider>+ </div>+ ),+};++export const Loading: Story = {+ render: () => (+ <div className="p-20 max-w-4xl">+ <TooltipProvider>+ <FormWrapper {...props} loading={true} />+ </TooltipProvider>+ </div>+ ),+};++export const Stale: Story = {+ render: () => (+ <div className="p-20 max-w-4xl">+ <TooltipProvider>+ <FormWrapper+ {...props}+ currentValue="currentValue"+ newValue="newValue"+ />+ </TooltipProvider>+ </div>+ ),+};++export const WithCustomValues: Story = {+ render: () => (+ <div className="p-20 max-w-4xl">+ <TooltipProvider>+ <FormWrapper+ {...props}+ submitButtonLabel="Go"+ submitButtonTooltip="Run!"+ clearButtonLabel="Reset"+ clearButtonTooltip="Reset the form"+ showClearButton={true}+ clearOnSubmit={true}+ />+ </TooltipProvider>+ </div>+ ),+};++export const Borderless: Story = {+ render: () => (+ <div className="p-20 max-w-4xl">+ <TooltipProvider>+ <FormWrapper {...props} bordered={false} />+ </TooltipProvider>+ </div>+ ),+};++export const BorderlessAndStale: Story = {+ render: () => (+ <div className="p-20 max-w-4xl">+ <TooltipProvider>+ <FormWrapper {...props} bordered={false} newValue="newValue" />+ </TooltipProvider>+ </div>+ ),+};++export const Validate: Story = {+ render: () => (+ <div className="p-20 max-w-4xl">+ <TooltipProvider>+ <FormWrapper+ {...props}+ shouldValidate={true}+ validate={async ({ value }) => {+ const random = Math.random();+ if (random < 0.8) {+ return `Failed to validate. Random number was ${random}`;+ }+ return null;+ }}+ />+ </TooltipProvider>+ </div>+ ),+};diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.pyindex eb074ec1c0..fe1a1c2482 100644--- a/marimo/_plugins/ui/_core/ui_element.py+++ b/marimo/_plugins/ui/_core/ui_element.py@@ -249,7 +249,24 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):return self._value@mddoc- def form(self, label: str = "") -> form_plugin[S, T]:+ def form(+ self,+ label: str = "",+ *,+ bordered: bool = True,+ loading: bool = False,+ submit_button_label: str = "Submit",+ submit_button_tooltip: Optional[str] = None,+ submit_button_disabled: bool = False,+ clear_on_submit: bool = False,+ show_clear_button: bool = False,+ clear_button_label: str = "Clear",+ clear_button_tooltip: Optional[str] = None,+ validate: Optional[+ Callable[[Optional[JSONType]], Optional[str]]+ ] = None,+ on_change: Optional[Callable[[Optional[T]], None]] = None,+ ) -> form_plugin[S, T]:"""Create a submittable form out of this `UIElement`.Use this method to create a form that gates the submission@@ -289,10 +306,38 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):**Args.**- `label`: A text label for the form.+ - `bordered`: whether the form should have a border+ - `loading`: whether the form should be in a loading state+ - `submit_button_label`: the label of the submit button+ - `submit_button_tooltip`: the tooltip of the submit button+ - `submit_button_disabled`: whether the submit button should be+ disabled+ - `clear_on_submit`: whether the form should clear its contents after+ submitting+ - `show_clear_button`: whether the form should show a clear button+ - `clear_button_label`: the label of the clear button+ - `clear_button_tooltip`: the tooltip of the clear button+ - `validate`: a function that takes the form's value and returns an+ error message if the value is invalid,+ or `None` if the value is valid"""from marimo._plugins.ui._impl.input import form as form_plugin- return form_plugin(element=self, label=label)+ return form_plugin(+ element=self,+ label=label,+ bordered=bordered,+ loading=loading,+ submit_button_label=submit_button_label,+ submit_button_tooltip=submit_button_tooltip,+ submit_button_disabled=submit_button_disabled,+ clear_on_submit=clear_on_submit,+ show_clear_button=show_clear_button,+ clear_button_label=clear_button_label,+ clear_button_tooltip=clear_button_tooltip,+ validate=validate,+ on_change=on_change,+ )def _update(self, value: S) -> None:"""Update value, given a value from the frontenddiff --git a/marimo/_plugins/ui/_impl/input.py b/marimo/_plugins/ui/_impl/input.pyindex d56885cbe9..51a898a819 100644--- a/marimo/_plugins/ui/_impl/input.py+++ b/marimo/_plugins/ui/_impl/input.py@@ -2,6 +2,7 @@from __future__ import annotationsimport base64+import dataclassesimport datetime as dtimport tracebackfrom dataclasses import dataclass@@ -21,8 +22,10 @@ from typing import (from marimo import _loggersfrom marimo._output.rich_help import mddoc+from marimo._plugins.core.web_component import JSONTypefrom marimo._plugins.ui._core.ui_element import S as JSONTypeBoundfrom marimo._plugins.ui._core.ui_element import UIElement+from marimo._runtime.functions import FunctionLOGGER = _loggers.marimo_logger()@@ -709,6 +712,7 @@ class button(UIElement[Any, Any]):value: Optional[Any] = None,kind: Literal["neutral", "success", "warn", "danger"] = "neutral",disabled: bool = False,+ tooltip: Optional[str] = None,*,label: str = "click here",on_change: Optional[Callable[[Any], None]] = None,@@ -724,6 +728,7 @@ class button(UIElement[Any, Any]):args={"kind": kind,"disabled": disabled,+ "tooltip": tooltip,"full-width": full_width,},on_change=on_change,@@ -993,6 +998,11 @@ class date(UIElement[str, dt.date]):T = TypeVar("T")+class ValueArgs:+ value: Optional[JSONType] = None++@mddocclass form(UIElement[Optional[JSONTypeBound], Optional[T]]):"""@@ -1022,7 +1032,7 @@ class form(UIElement[Optional[JSONTypeBound], Optional[T]]):''').batch(name=mo.ui.text(label='name'),date=mo.ui.date(label='date'),- ).form()+ ).form(show_clear_button=True, bordered=False)``````python@@ -1039,6 +1049,18 @@ class form(UIElement[Optional[JSONTypeBound], Optional[T]]):**Initialization Args.**- `element`: the element to wrap+ - `bordered`: whether the form should have a border+ - `loading`: whether the form should be in a loading state+ - `submit_button_label`: the label of the submit button+ - `submit_button_tooltip`: the tooltip of the submit button+ - `submit_button_disabled`: whether the submit button should be disabled+ - `clear_on_submit`: whether the form should clear its contents after+ submitting+ - `show_clear_button`: whether the form should show a clear button+ - `clear_button_label`: the label of the clear button+ - `clear_button_tooltip`: the tooltip of the clear button+ - `validate`: a function that takes the form's value and returns an error+ message if the value is invalid, or `None` if the value is valid- `label`: text label for the form- `on_change`: optional callback to run when this element's value changes"""@@ -1049,19 +1071,56 @@ class form(UIElement[Optional[JSONTypeBound], Optional[T]]):self,element: UIElement[JSONTypeBound, T],*,+ bordered: bool = True,+ loading: bool = False,+ submit_button_label: str = "Submit",+ submit_button_tooltip: Optional[str] = None,+ submit_button_disabled: bool = False,+ clear_on_submit: bool = False,+ show_clear_button: bool = False,+ clear_button_label: str = "Clear",+ clear_button_tooltip: Optional[str] = None,+ validate: Optional[+ Callable[[Optional[JSONType]], Optional[str]]+ ] = None,label: str = "",on_change: Optional[Callable[[Optional[T]], None]] = None,) -> None:self.element = element._clone()+ self.validate = validatesuper().__init__(component_name=form._name,initial_value=None,label=label,- args={"element-id": self.element._id},+ args={+ "element-id": self.element._id,+ "loading": loading,+ "bordered": bordered,+ "submit-button-label": submit_button_label,+ "submit-button-tooltip": submit_button_tooltip,+ "submit-button-disabled": submit_button_disabled,+ "clear-on-submit": clear_on_submit,+ "show-clear-button": show_clear_button,+ "clear-button-label": clear_button_label,+ "clear-button-tooltip": clear_button_tooltip,+ "should-validate": validate is not None,+ },slotted_html=self.element.text,on_change=on_change,+ functions=(+ Function(+ name="validate",+ arg_cls=ValueArgs,+ function=self._validate,+ ),+ ),)+ def _validate(self, value: ValueArgs) -> Optional[str]:+ if self.validate is None:+ return None+ return self.validate(value.value)+def _convert_value(self, value: Optional[JSONTypeBound]) -> Optional[T]:if value is None:return Nonediff --git a/marimo/_smoke_tests/forms.py b/marimo/_smoke_tests/forms.pyindex 312cd7b04f..b25d571d68 100644--- a/marimo/_smoke_tests/forms.py+++ b/marimo/_smoke_tests/forms.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.import marimo-__generated_with = "0.1.39"+__generated_with = "0.1.79"app = marimo.App()@@ -9,14 +9,38 @@ app = marimo.App()def __():import marimo as moimport random+return mo, random@app.celldef __(mo):- form_1 = mo.ui.text_area(label="Form 1").form()+ mo.md("# Basic form")+ return+++def __(mo):+ clear_on_submit_input = mo.ui.checkbox(True, label="Clear on submit")+ bordered_input = mo.ui.checkbox(False, label="Bordered")+ show_clear_button_input = mo.ui.checkbox(False, label="Show clear button")+ mo.hstack([clear_on_submit_input, bordered_input, show_clear_button_input])+ return bordered_input, clear_on_submit_input, show_clear_button_input+++def __(bordered_input, clear_on_submit_input, mo, show_clear_button_input):+ form_1 = mo.ui.text_area(+ label="Form label", full_width=True, placeholder="Type..."+ ).form(+ submit_button_label="Go!",+ clear_on_submit=clear_on_submit_input.value,+ submit_button_tooltip="Click me",+ bordered=bordered_input.value,+ show_clear_button=show_clear_button_input.value,+ )form_1- return form_1,+ return (form_1,)@app.cell@@ -24,24 +48,41 @@ 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}**"),+ mo.md("## Basic form value"),+ mo.md(+ f"Random number (to monitor re-renders) **{random_number}**"+ ),form_1.value,])- return random_number,+ return (random_number,)@app.celldef __(mo):+ mo.md(+ """+ -------++ # Validating forms"""+ )+ return+++def __(mo):+ years_experience = mo.ui.slider(1, 10, value=3)fn = mo.ui.text()ln = mo.ui.text()- return fn, ln+ def validate(value):+ if "first_name" not in value or len(value["first_name"]) == 0:+ return "Missing first name"+ if "last_name" not in value or len(value["last_name"]) == 0:+ return "Missing last name"+ if value["years_experience"] < 4:+ return "Must have at least 4 years experience"-def __(fn, ln, mo):- years_experience = mo.ui.slider(1, 10, value=4)form_2 = (mo.md("""@@ -57,11 +98,15 @@ def __(fn, ln, mo):last_name=ln,years_experience=years_experience,)- .form()+ .form(+ bordered=False,+ validate=validate,+ show_clear_button=True,+ ))form_2- return form_2, years_experience+ return fn, form_2, ln, validate, years_experience@app.cell@@ -69,7 +114,7 @@ def __(form_2, mo, random):_random_number = random.randint(1, 100)mo.vstack([- mo.md("### Form 2 Value"),+ mo.md("### Validate form value"),mo.md(f"Random number **{_random_number}**"),form_2.value,]@@ -79,7 +124,11 @@ def __(form_2, mo, random):@app.celldef __(mo):- mo.md("## Dictionary")+ mo.md(+ """+ ------+ # Dictionary"""+ )return@@ -99,14 +148,14 @@ def __(mo):})dict- return dict,+ return (dict,)@app.celldef __(dict, mo):mo.vstack([- mo.md("### Dict Value"),+ mo.md("## Dictionary Value"),dict.value,])