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: Debounce mo.ui.text and text_area (#2333)
Wasim Sandhucd0a73e6289e
diff --git a/frontend/src/components/ui/input.tsx b/frontend/src/components/ui/input.tsxindex 619c972b7b..609cd220fc 100644--- a/frontend/src/components/ui/input.tsx+++ b/frontend/src/components/ui/input.tsx@@ -9,6 +9,7 @@ import {type NumberFieldProps,} from "@/components/ui/number-field";import { SearchIcon, XIcon } from "lucide-react";+import { useControllableState } from "@radix-ui/react-use-controllable-state";export type InputProps = React.InputHTMLAttributes<HTMLInputElement> & {icon?: React.ReactNode;@@ -59,12 +60,12 @@ export const DebouncedInput = React.forwardRef<InputProps & {value: string;onValueChange: (value: string) => void;+ delay?: number;}>(({ className, onValueChange, ...props }, ref) => {- // Create a debounced value of 200const { value, onChange } = useDebounceControlledState<string>({initialValue: props.value,- delay: 200,+ delay: props.delay,onChange: onValueChange,});@@ -155,4 +156,42 @@ export const SearchInput = React.forwardRef<});SearchInput.displayName = "SearchInput";+export const OnBlurredInput = React.forwardRef<+ HTMLInputElement,+ InputProps & {+ value: string;+ onValueChange: (value: string) => void;+ }+>(({ className, onValueChange, ...props }, ref) => {+ const [internalValue, setInternalValue] = React.useState(props.value);++ const [value, setValue] = useControllableState<string>({+ prop: props.value,+ defaultProp: internalValue,+ onChange: onValueChange,+ });++ React.useEffect(() => {+ setInternalValue(value || "");+ }, [value]);++ return (+ <Input+ ref={ref}+ className={className}+ {...props}+ value={internalValue}+ onChange={(event) => setInternalValue(event.target.value)}+ onBlur={() => setValue(internalValue || "")}+ onKeyDown={(event) => {+ if (event.key !== "Enter") {+ return;+ }+ setValue(internalValue || "");+ }}+ />+ );+});+OnBlurredInput.displayName = "OnBlurredInput";+export { Input };diff --git a/frontend/src/components/ui/textarea.tsx b/frontend/src/components/ui/textarea.tsxindex 17e4efef12..41e00d0c87 100644--- a/frontend/src/components/ui/textarea.tsx+++ b/frontend/src/components/ui/textarea.tsx@@ -3,6 +3,8 @@ import * as React from "react";import { cn } from "@/utils/cn";import { Events } from "@/utils/events";+import { useDebounceControlledState } from "@/hooks/useDebounce";+import { useControllableState } from "@radix-ui/react-use-controllable-state";export interface TextareaPropsextends React.TextareaHTMLAttributes<HTMLTextAreaElement> {@@ -34,4 +36,69 @@ const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>();Textarea.displayName = "Textarea";+export const DebouncedTextarea = React.forwardRef<+ HTMLTextAreaElement,+ TextareaProps & {+ value: string;+ onValueChange: (value: string) => void;+ delay?: number;+ }+>(({ className, onValueChange, ...props }, ref) => {+ const { value, onChange } = useDebounceControlledState<string>({+ initialValue: props.value,+ delay: props.delay,+ onChange: onValueChange,+ });++ return (+ <Textarea+ ref={ref}+ className={className}+ {...props}+ onChange={(evt) => onChange(evt.target.value)}+ value={value}+ />+ );+});+DebouncedTextarea.displayName = "DebouncedTextarea";++export const OnBlurredTextarea = React.forwardRef<+ HTMLTextAreaElement,+ TextareaProps & {+ value: string;+ onValueChange: (value: string) => void;+ }+>(({ className, onValueChange, ...props }, ref) => {+ const [internalValue, setInternalValue] = React.useState(props.value);++ const [value, setValue] = useControllableState<string>({+ prop: props.value,+ defaultProp: internalValue,+ onChange: onValueChange,+ });++ React.useEffect(() => {+ setInternalValue(value || "");+ }, [value]);++ return (+ <Textarea+ ref={ref}+ className={className}+ {...props}+ value={internalValue}+ onChange={(event) => setInternalValue(event.target.value)}+ onBlur={() => setValue(internalValue)}+ onKeyDown={(event) => {+ if (!(event.ctrlKey && event.key === "Enter")) {+ return;+ }+ event.preventDefault();+ setValue(internalValue);+ }}+ />+ );+});+OnBlurredTextarea.displayName = "OnBlurredTextarea";+export { Textarea };diff --git a/frontend/src/plugins/impl/TextAreaPlugin.tsx b/frontend/src/plugins/impl/TextAreaPlugin.tsxindex 1d3b468354..83e31646f4 100644--- a/frontend/src/plugins/impl/TextAreaPlugin.tsx+++ b/frontend/src/plugins/impl/TextAreaPlugin.tsx@@ -2,7 +2,11 @@import { z } from "zod";import type { IPlugin, IPluginProps, Setter } from "../types";-import { Textarea } from "../../components/ui/textarea";+import {+ DebouncedTextarea,+ OnBlurredTextarea,+ Textarea,+} from "../../components/ui/textarea";import { Labeled } from "./common/labeled";import { cn } from "@/utils/cn";@@ -14,6 +18,7 @@ interface Data {maxLength?: number;minLength?: number;disabled?: boolean;+ debounce?: boolean | number;rows: number;fullWidth: boolean;}@@ -28,6 +33,7 @@ export class TextAreaPlugin implements IPlugin<T, Data> {maxLength: z.number().optional(),minLength: z.number().optional(),disabled: z.boolean().optional(),+ debounce: z.optional(z.union([z.boolean(), z.number()])),rows: z.number().default(4),fullWidth: z.boolean().default(false),});@@ -55,6 +61,51 @@ const TextAreaComponent = (props: TextAreaComponentProps) => {</span>) : null;+ if (props.debounce === true) {+ return (+ <Labeled label={props.label} align="top" fullWidth={props.fullWidth}>+ <OnBlurredTextarea+ className={cn("font-code", {+ "w-full": props.fullWidth,+ })}+ rows={props.rows}+ cols={33}+ maxLength={props.maxLength}+ minLength={props.minLength}+ required={props.minLength != null && props.minLength > 0}+ disabled={props.disabled}+ bottomAdornment={bottomAdornment}+ value={props.value}+ onValueChange={props.setValue}+ placeholder={props.placeholder}+ />+ </Labeled>+ );+ }++ if (typeof props.debounce === "number") {+ return (+ <Labeled label={props.label} align="top" fullWidth={props.fullWidth}>+ <DebouncedTextarea+ className={cn("font-code", {+ "w-full": props.fullWidth,+ })}+ rows={props.rows}+ cols={33}+ maxLength={props.maxLength}+ minLength={props.minLength}+ required={props.minLength != null && props.minLength > 0}+ disabled={props.disabled}+ bottomAdornment={bottomAdornment}+ value={props.value}+ onValueChange={props.setValue}+ placeholder={props.placeholder}+ delay={props.debounce}+ />+ </Labeled>+ );+ }+return (<Labeled label={props.label} align="top" fullWidth={props.fullWidth}><Textareadiff --git a/frontend/src/plugins/impl/TextInputPlugin.tsx b/frontend/src/plugins/impl/TextInputPlugin.tsxindex 9c92abc0a5..5b13d7a8dd 100644--- a/frontend/src/plugins/impl/TextInputPlugin.tsx+++ b/frontend/src/plugins/impl/TextInputPlugin.tsx@@ -2,7 +2,11 @@import { z } from "zod";import type { IPlugin, IPluginProps, Setter } from "../types";-import { Input } from "../../components/ui/input";+import {+ DebouncedInput,+ Input,+ OnBlurredInput,+} from "../../components/ui/input";import { cn } from "../../utils/cn";import { AtSignIcon, GlobeIcon, LockIcon } from "lucide-react";import { useState } from "react";@@ -19,6 +23,7 @@ interface Data {maxLength?: number;minLength?: number;disabled?: boolean;+ debounce?: boolean | number;fullWidth: boolean;}@@ -34,6 +39,7 @@ export class TextInputPlugin implements IPlugin<T, Data> {minLength: z.number().optional(),fullWidth: z.boolean().default(false),disabled: z.boolean().optional(),+ debounce: z.optional(z.union([z.boolean(), z.number()])),});render(props: IPluginProps<T, Data>): JSX.Element {@@ -71,6 +77,56 @@ const TextComponent = (props: TextComponentProps) => {</span>) : null;+ if (props.debounce === true) {+ return (+ <Labeled label={props.label} fullWidth={props.fullWidth}>+ <OnBlurredInput+ data-testid="marimo-plugin-text-input"+ type={props.kind}+ icon={icon[props.kind]}+ placeholder={props.placeholder}+ maxLength={props.maxLength}+ minLength={props.minLength}+ required={props.minLength != null && props.minLength > 0}+ disabled={props.disabled}+ className={cn({+ "border-destructive": !isValid,+ "w-full": props.fullWidth,+ })}+ endAdornment={endAdornment}+ value={props.value}+ onValueChange={props.setValue}+ />+ </Labeled>+ );+ }++ if (typeof props.debounce === "number") {+ return (+ <Labeled label={props.label} fullWidth={props.fullWidth}>+ <DebouncedInput+ data-testid="marimo-plugin-text-input"+ type={props.kind}+ icon={icon[props.kind]}+ placeholder={props.placeholder}+ maxLength={props.maxLength}+ minLength={props.minLength}+ required={props.minLength != null && props.minLength > 0}+ disabled={props.disabled}+ className={cn({+ "border-destructive": !isValid,+ "w-full": props.fullWidth,+ })}+ endAdornment={endAdornment}+ value={props.value}+ onValueChange={props.setValue}+ onBlur={(event) => setValueOnBlur(event.currentTarget.value)}+ delay={props.debounce}+ />+ </Labeled>+ );+ }+return (<Labeled label={props.label} fullWidth={props.fullWidth}><Inputdiff --git a/marimo/_plugins/ui/_impl/input.py b/marimo/_plugins/ui/_impl/input.pyindex 762427ab29..643c3d5280 100644--- a/marimo/_plugins/ui/_impl/input.py+++ b/marimo/_plugins/ui/_impl/input.py@@ -664,6 +664,9 @@ class text(UIElement[str, str]):defaults to `"text"`- `max_length`: maximum length of input- `disabled`: whether the input is disabled+ - `debounce`: whether the input is debounced. If number, debounce by+ that many milliseconds. If True, then value is only emitted on Enter+ or when the input loses focus.- `label`: text label for the element- `on_change`: optional callback to run when this element's value changes- `full_width`: whether the input should take up the full width of its@@ -679,6 +682,7 @@ class text(UIElement[str, str]):kind: Literal["text", "password", "email", "url"] = "text",max_length: Optional[int] = None,disabled: bool = False,+ debounce: bool | int = True,*,label: str = "",on_change: Optional[Callable[[str], None]] = None,@@ -694,6 +698,7 @@ class text(UIElement[str, str]):"max-length": max_length,"full-width": full_width,"disabled": disabled,+ "debounce": debounce,},on_change=on_change,)@@ -723,6 +728,9 @@ class text_area(UIElement[str, str]):- `placeholder`: placeholder text to display when the text area is empty- `max_length`: maximum length of input- `disabled`: whether the input is disabled+ - `debounce`: whether the input is debounced. If number, debounce by that+ many milliseconds. If True, then value is only emitted on Ctrl+Enter+ or when the input loses focus.- `rows`: number of rows of text to display- `label`: text label for the element- `on_change`: optional callback to run when this element's value changes@@ -738,6 +746,7 @@ class text_area(UIElement[str, str]):placeholder: str = "",max_length: Optional[int] = None,disabled: bool = False,+ debounce: bool | int = True,rows: Optional[int] = None,*,label: str = "",@@ -752,6 +761,7 @@ class text_area(UIElement[str, str]):"placeholder": placeholder,"max-length": max_length,"disabled": disabled,+ "debounce": debounce,"full-width": full_width,"rows": rows,},diff --git a/marimo/_smoke_tests/debounce_input.py b/marimo/_smoke_tests/debounce_input.pynew file mode 100644index 0000000000..08aec6b017--- /dev/null+++ b/marimo/_smoke_tests/debounce_input.py@@ -0,0 +1,72 @@+import marimo++__generated_with = "0.8.15"+app = marimo.App()+++def __(mo):+ mo.md(r"""[Debounce mo.ui.text and mo.ui.text_area #2218](https://github.com/marimo-team/marimo/issues/2218)""")+ return+++def __(debounce, debounce_options, mo):+ name_input = mo.ui.text(+ label="Enter your name for the greeting of a lifetime:", debounce=debounce+ )+ mo.vstack([debounce_options, name_input, name_input])+ return name_input,+++def __(name_input):+ if len(name_input.value) > 0:+ print(f"Hello {name_input.value}!")+ return+++def __(debounce, debounce_options, mo):+ story_input = mo.ui.text_area(+ label="Now tell me a story from your childhood:", debounce=debounce+ )+ mo.vstack([debounce_options, mo.hstack([story_input, story_input])])+ return story_input,+++def __(story_input):+ if (len(story_input.value) > 0):+ print(story_input.value)+ return+++def __(mo):+ debounce_options = mo.ui.dropdown(+ label="Choose debounce option",+ options=["True", "500", "1000", "False"],+ value="True",+ )+ return debounce_options,+++def __(debounce_options):+ debounce = debounce_options.value+ debounce = (+ int(debounce) if debounce != "True" and debounce != "False" else debounce+ )+ debounce = debounce == "True" if isinstance(debounce, str) else debounce+ return debounce,+++def __():+ import marimo as mo+ return mo,+++if __name__ == "__main__":+ app.run()