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.

feat: add debounce to slider and number input (#44)

Myles Scolnick23a3c639d100
diff --git a/frontend/src/hooks/useDebounce.ts b/frontend/src/hooks/useDebounce.ts
new file mode 100644
index 0000000000..436d6d49e4
--- /dev/null
+++ b/frontend/src/hooks/useDebounce.ts
@@ -0,0 +1,77 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+import { useEffect, useState } from "react";
+import useEvent from "react-use-event-hook";
+
+export function useDebounce<T>(value: T, delay: number): T {
+ const [debouncedValue, setDebouncedValue] = useState<T>(value);
+
+ useEffect(() => {
+ const timer = setTimeout(() => setDebouncedValue(value), delay);
+
+ return () => {
+ clearTimeout(timer);
+ };
+ }, [value, delay]);
+
+ return debouncedValue;
+}
+
+/**
+ * A hook that allows you to control a state value, but also get a debounced version of that value.
+ */
+export function useDebounceControlledState<T>(opts: {
+ /**
+ * Initial value of the state.
+ */
+ initialValue: T;
+ /**
+ * Callback to run when the state changes.
+ * This will be debounced.
+ */
+ onChange: (value: T) => void;
+ /**
+ * The delay to debounce the state change by.
+ * @default 200
+ */
+ delay?: number;
+ /**
+ * Whether the state is disabled.
+ */
+ disabled?: boolean;
+}) {
+ const { initialValue, onChange, delay, disabled } = opts;
+ const [internalValue, setInternalValue] = useState<T>(initialValue);
+ const debouncedValue = useDebounce(internalValue, delay || 200);
+
+ const onUpdate = useEvent(onChange);
+
+ // If the initialValue changes, update the internal value
+ useEffect(() => {
+ setInternalValue(initialValue);
+ }, [initialValue]);
+
+ useEffect(() => {
+ if (disabled) {
+ return;
+ }
+
+ onUpdate(debouncedValue);
+ }, [debouncedValue, disabled, onUpdate]);
+
+ // If disabled, just pass through the initialValue and onChange
+ if (disabled) {
+ return {
+ value: internalValue,
+ debouncedValue: internalValue,
+ onChange: onChange,
+ };
+ }
+
+ return {
+ value: internalValue,
+ debouncedValue,
+ onChange: (value: T) => {
+ setInternalValue(value);
+ },
+ };
+}
diff --git a/frontend/src/plugins/impl/NumberPlugin.tsx b/frontend/src/plugins/impl/NumberPlugin.tsx
index fd562330f2..55a122be32 100644
--- a/frontend/src/plugins/impl/NumberPlugin.tsx
+++ b/frontend/src/plugins/impl/NumberPlugin.tsx
@@ -1,10 +1,11 @@
/* Copyright 2023 Marimo. All rights reserved. */
-import { useEffect, useId, useRef } from "react";
+import { useId, useRef } from "react";
import { z } from "zod";
import { IPlugin, IPluginProps, Setter } from "../types";
import { Input } from "../../components/ui/input";
import { Labeled } from "./common/labeled";
+import { useDebounceControlledState } from "@/hooks/useDebounce";
type T = number;
@@ -13,6 +14,7 @@ interface Data {
stop: T;
step?: T;
label: string | null;
+ debounce: boolean;
}
export class NumberPlugin implements IPlugin<T, Data> {
@@ -24,6 +26,7 @@ export class NumberPlugin implements IPlugin<T, Data> {
start: z.number(),
stop: z.number(),
step: z.number().optional(),
+ debounce: z.boolean().default(false),
});
render(props: IPluginProps<T, Data>): JSX.Element {
@@ -44,30 +47,16 @@ interface NumberComponentProps extends Data {
const NumberComponent = (props: NumberComponentProps): JSX.Element => {
const inputRef = useRef<HTMLInputElement>(null);
- const oninput = () => {
- if (inputRef.current !== null) {
- props.setValue(inputRef.current.valueAsNumber);
- }
- };
-
- useEffect(() => {
- // scrolling inside the input causes the value to change, which
- // is very surprising, so we disable it.
- if (inputRef.current !== null) {
- inputRef.current.addEventListener(
- "wheel",
- (e) => {
- if (e.target === inputRef.current) {
- e.preventDefault();
- }
- },
- { passive: false }
- );
- }
- }, [inputRef]);
-
const id = useId();
+ // Create a debounced value of 200
+ const { value, onChange } = useDebounceControlledState({
+ initialValue: props.value,
+ delay: 200,
+ disabled: !props.debounce,
+ onChange: props.setValue,
+ });
+
return (
<Labeled label={props.label} id={id}>
<Input
@@ -77,8 +66,13 @@ const NumberComponent = (props: NumberComponentProps): JSX.Element => {
min={props.start}
max={props.stop}
step={props.step}
- value={props.value}
- onInput={oninput}
+ value={value}
+ onWheel={(e) => {
+ e.preventDefault();
+ }}
+ onChange={(e) => {
+ onChange(e.target.valueAsNumber);
+ }}
id={id}
/>
</Labeled>
diff --git a/frontend/src/plugins/impl/SliderPlugin.tsx b/frontend/src/plugins/impl/SliderPlugin.tsx
index b40b8b77da..b83ba77a37 100644
--- a/frontend/src/plugins/impl/SliderPlugin.tsx
+++ b/frontend/src/plugins/impl/SliderPlugin.tsx
@@ -1,5 +1,5 @@
/* Copyright 2023 Marimo. All rights reserved. */
-import { useCallback, useId } from "react";
+import { useEffect, useId, useState } from "react";
import { z } from "zod";
import { IPlugin, IPluginProps, Setter } from "../types";
@@ -13,6 +13,7 @@ interface Data {
stop: T;
step?: T;
label: string | null;
+ debounce: boolean;
}
export class SliderPlugin implements IPlugin<T, Data> {
@@ -24,6 +25,7 @@ export class SliderPlugin implements IPlugin<T, Data> {
start: z.number(),
stop: z.number(),
step: z.number().optional(),
+ debounce: z.boolean().default(false),
});
render(props: IPluginProps<T, Data>): JSX.Element {
@@ -42,26 +44,46 @@ interface SliderProps extends Data {
setValue: Setter<T>;
}
-const SliderComponent = (props: SliderProps): JSX.Element => {
- const setValue = props.setValue;
- const onValueChange = useCallback(
- (values: number[]) => {
- setValue(values[0]);
- },
- [setValue]
- );
+const SliderComponent = ({
+ label,
+ setValue,
+ value,
+ start,
+ stop,
+ step,
+ debounce,
+}: SliderProps): JSX.Element => {
const id = useId();
+ // Hold internal value
+ const [internalValue, setInternalValue] = useState(value);
+ // Update internal value on prop change
+ useEffect(() => {
+ setInternalValue(value);
+ }, [value]);
+
return (
- <Labeled label={props.label} id={id}>
+ <Labeled label={label} id={id}>
<Slider
- className={"relative flex items-center select-none w-36"}
- value={[props.value]}
- min={props.start}
- max={props.stop}
- step={props.step}
- onValueChange={onValueChange}
id={id}
+ className={"relative flex items-center select-none w-36"}
+ value={[internalValue]}
+ min={start}
+ max={stop}
+ step={step}
+ // Triggered on all value changes
+ onValueChange={([nextValue]) => {
+ setInternalValue(nextValue);
+ if (!debounce) {
+ setValue(nextValue);
+ }
+ }}
+ // Triggered on mouse up
+ onValueCommit={([nextValue]) => {
+ if (debounce) {
+ setValue(nextValue);
+ }
+ }}
/>
</Labeled>
);
diff --git a/marimo/_plugins/ui/_impl/input.py b/marimo/_plugins/ui/_impl/input.py
index ec4ccecc43..a58127b63d 100644
--- a/marimo/_plugins/ui/_impl/input.py
+++ b/marimo/_plugins/ui/_impl/input.py
@@ -54,6 +54,8 @@ class number(UIElement[Optional[Numeric], Optional[Numeric]]):
- `stop`: the maximum value of the interval
- `step`: the number increment
- `value`: default value
+ - `debounce`: whether to debounce (rate-limit) value
+ updates from the frontend
- `label`: text label for the element
"""
@@ -65,6 +67,7 @@ class number(UIElement[Optional[Numeric], Optional[Numeric]]):
stop: float,
step: Optional[float] = None,
value: Optional[float] = None,
+ debounce: bool = False,
label: str = "",
) -> None:
value = start if value is None else value
@@ -93,6 +96,7 @@ class number(UIElement[Optional[Numeric], Optional[Numeric]]):
"start": start,
"stop": stop,
"step": step if step is not None else None,
+ "debounce": debounce,
},
)
@@ -125,6 +129,8 @@ class slider(UIElement[Numeric, Numeric]):
- `stop`: the maximum value of the interval
- `step`: the slider increment
- `value`: default value
+ - `debounce`: whether to debounce the slider to only send
+ the value on mouse-up or drag-end
- `label`: text label for the element
"""
@@ -136,6 +142,7 @@ class slider(UIElement[Numeric, Numeric]):
stop: float,
step: Optional[float] = None,
value: Optional[float] = None,
+ debounce: bool = False,
label: str = "",
) -> None:
self._dtype = (
@@ -173,6 +180,7 @@ class slider(UIElement[Numeric, Numeric]):
"start": start,
"stop": stop,
"step": step if step is not None else None,
+ "debounce": debounce,
},
)
diff --git a/marimo/_smoke_tests/buttons.py b/marimo/_smoke_tests/buttons.py
index da17f27204..19e5bd9154 100644
--- a/marimo/_smoke_tests/buttons.py
+++ b/marimo/_smoke_tests/buttons.py
@@ -1,3 +1,4 @@
+# Copyright 2023 Marimo. All rights reserved.
import marimo
__generated_with = "0.1.2"
diff --git a/marimo/_smoke_tests/debounce.py b/marimo/_smoke_tests/debounce.py
new file mode 100644
index 0000000000..4f4982b2b3
--- /dev/null
+++ b/marimo/_smoke_tests/debounce.py
@@ -0,0 +1,72 @@
+# Copyright 2023 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.1.3"
+app = marimo.App()
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+def __(mo):
+ slider = mo.ui.slider(1, 10, label="Slider")
+ debounced_slider = mo.ui.slider(1, 10, debounce=True, label="Debounced Slider")
+
+ number = mo.ui.number(1, 10, label="Number")
+ debounced_number = mo.ui.number(1, 10, debounce=True, label="Debounced Number")
+ return debounced_number, debounced_slider, number, slider
+
+
+def __(debounced_number, debounced_slider, mo, number, slider):
+ mo.md(f"""
+ Controls:
+
+ {slider}
+
+ {debounced_slider}
+
+ {number}
+
+ {debounced_number}
+ """)
+ return
+
+
+def __(debounced_number, debounced_slider, mo, number, slider):
+ # Values
+ mo.md(f"""
+ slider: {slider.value}
+
+ debounced slider: {debounced_slider.value}
+
+ number: {number.value}
+
+ debounced number: {debounced_number.value}
+ """)
+ return
+
+
+def __(debounced_number, debounced_slider, mo, number, slider):
+ mo.md(f"""
+ Controls and Values:
+
+ {slider} -> {slider.value}
+
+ {debounced_slider} -> {debounced_slider.value}
+
+ {number} -> {number.value}
+
+ {debounced_number} -> {debounced_number.value}
+ """)
+ return
+
+
+if __name__ == "__main__":
+ app.run()