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
feat: Create range slider component (#1193)
Wasim Sandhu2a44e4fef817
diff --git a/docs/api/inputs/index.md b/docs/api/inputs/index.mdindex 931171f09e..605415d08d 100644--- a/docs/api/inputs/index.md+++ b/docs/api/inputs/index.md@@ -22,6 +22,7 @@multiselectnumberradio+ range_sliderrefreshsliderswitch@@ -56,6 +57,7 @@ powerful notebooks and apps. These elements are available in `marimo.ui`.marimo.ui.multiselectmarimo.ui.numbermarimo.ui.radio+ marimo.ui.range_slidermarimo.ui.refreshmarimo.ui.slidermarimo.ui.switchdiff --git a/docs/api/inputs/range_slider.md b/docs/api/inputs/range_slider.mdnew file mode 100644index 0000000000..28ad083860--- /dev/null+++ b/docs/api/inputs/range_slider.md@@ -0,0 +1,21 @@+# Range Slider++```{eval-rst}+.. marimo-embed::+ @app.cell+ def __():+ range_slider = mo.ui.range_slider(start=1, stop=10, step=2, value=[2, 6], full_width=True)+ return++ @app.cell+ def __():+ mo.hstack([range_slider, mo.md(f"Has value: {range_slider.value}")])+ return+```++```{eval-rst}+.. autoclass:: marimo.ui.range_slider+ :members:++ .. autoclasstoc:: marimo._plugins.ui._impl.input.range_slider+```diff --git a/frontend/src/components/ui/range-slider.tsx b/frontend/src/components/ui/range-slider.tsxnew file mode 100644index 0000000000..8a498052b2--- /dev/null+++ b/frontend/src/components/ui/range-slider.tsx@@ -0,0 +1,98 @@+/* Copyright 2024 Marimo. All rights reserved. */+import * as React from "react";+import * as SliderPrimitive from "@radix-ui/react-slider";++import { cn } from "@/utils/cn";+import {+ TooltipContent,+ TooltipProvider,+ TooltipRoot,+ TooltipTrigger,+} from "./tooltip";+import { useBoolean } from "../../hooks/useBoolean";+import { TooltipPortal } from "@radix-ui/react-tooltip";+import { prettyNumber } from "@/utils/numbers";++const RangeSlider = React.forwardRef<+ React.ElementRef<typeof SliderPrimitive.Root>,+ React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>+>(({ className, ...props }, ref) => {+ const [open, openActions] = useBoolean(false);++ return (+ <SliderPrimitive.Root+ ref={ref}+ className={cn(+ "relative flex touch-none select-none hover:cursor-pointer",+ "data-[orientation=horizontal]:w-full data-[orientation=horizontal]:items-center",+ "data-[orientation=vertical]:h-full data-[orientation=vertical]:justify-center",+ className,+ )}+ {...props}+ >+ <SliderPrimitive.Track+ data-testid="track"+ className={cn(+ "relative grow overflow-hidden rounded-full bg-slate-200 dark:bg-accent/60",+ "data-[orientation=horizontal]:h-2 data-[orientation=horizontal]:w-full",+ "data-[orientation=vertical]:h-full data-[orientation=vertical]:w-2",+ )}+ >+ <SliderPrimitive.Range+ data-testid="range"+ className={cn(+ "absolute bg-blue-500 dark:bg-primary",+ "data-[orientation=horizontal]:h-full",+ "data-[orientation=vertical]:w-full",+ )}+ />+ </SliderPrimitive.Track>+ <TooltipProvider>+ <TooltipRoot delayDuration={0} open={open}>+ <TooltipTrigger asChild={true}>+ <SliderPrimitive.Thumb+ data-testid="thumb"+ className="block h-4 w-4 rounded-full shadow-xsSolid border border-blue-500 dark:border-primary dark:bg-accent bg-white hover:bg-blue-300 focus:bg-blue-300 transition-colors focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50"+ onFocus={openActions.setTrue}+ onBlur={openActions.setFalse}+ onMouseEnter={openActions.setTrue}+ onMouseLeave={openActions.setFalse}+ />+ </TooltipTrigger>+ <TooltipPortal>+ {props.value != null && props.value.length === 2 && (+ <TooltipContent key={props.value[0]}>+ {prettyNumber(props.value[0])}+ </TooltipContent>+ )}+ </TooltipPortal>+ </TooltipRoot>+ </TooltipProvider>+ <TooltipProvider>+ <TooltipRoot delayDuration={0} open={open}>+ <TooltipTrigger asChild={true}>+ <SliderPrimitive.Thumb+ data-testid="thumb"+ className="block h-4 w-4 rounded-full shadow-xsSolid border border-blue-500 dark:border-primary dark:bg-accent bg-white hover:bg-blue-300 focus:bg-blue-300 transition-colors focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50"+ onFocus={openActions.setTrue}+ onBlur={openActions.setFalse}+ onMouseEnter={openActions.setTrue}+ onMouseLeave={openActions.setFalse}+ />+ </TooltipTrigger>+ <TooltipPortal>+ {props.value != null && props.value.length === 2 && (+ <TooltipContent key={props.value[1]}>+ {prettyNumber(props.value[1])}+ </TooltipContent>+ )}+ </TooltipPortal>+ </TooltipRoot>+ </TooltipProvider>+ </SliderPrimitive.Root>+ );+});++RangeSlider.displayName = SliderPrimitive.Root.displayName;++export { RangeSlider };diff --git a/frontend/src/plugins/impl/RangeSliderPlugin.tsx b/frontend/src/plugins/impl/RangeSliderPlugin.tsxnew file mode 100644index 0000000000..492c15c814--- /dev/null+++ b/frontend/src/plugins/impl/RangeSliderPlugin.tsx@@ -0,0 +1,131 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { useEffect, useId, useState } from "react";+import { z } from "zod";++import { IPlugin, IPluginProps, Setter } from "../types";+import { RangeSlider } from "../../components/ui/range-slider";+import { Labeled } from "./common/labeled";+import { cn } from "@/utils/cn";+import { prettyNumber } from "@/utils/numbers";++type T = number[];++interface Data {+ start: number;+ stop: number;+ step?: number;+ label: string | null;+ debounce: boolean;+ orientation: "horizontal" | "vertical";+ showValue: boolean;+ fullWidth: boolean;+}++export class RangeSliderPlugin implements IPlugin<T, Data> {+ tagName = "marimo-range-slider";++ validator = z.object({+ initialValue: z.array(z.number()),+ label: z.string().nullable(),+ start: z.number(),+ stop: z.number(),+ step: z.number().optional(),+ debounce: z.boolean().default(false),+ orientation: z.enum(["horizontal", "vertical"]).default("horizontal"),+ showValue: z.boolean().default(false),+ fullWidth: z.boolean().default(false),+ });++ render(props: IPluginProps<T, Data>): JSX.Element {+ return (+ <RangeSliderComponent+ {...props.data}+ value={props.value}+ setValue={props.setValue}+ />+ );+ }+}++interface RangeSliderProps extends Data {+ value: T;+ setValue: Setter<T>;+}++const RangeSliderComponent = ({+ label,+ setValue,+ value,+ start,+ stop,+ step,+ debounce,+ orientation,+ showValue,+ fullWidth,+}: RangeSliderProps): JSX.Element => {+ const id = useId();++ // Hold internal value+ const [internalValue, setInternalValue] = useState(value);++ // Update internal value on prop change+ useEffect(() => {+ setInternalValue(value);+ }, [value]);++ const sliderElement = (+ <Labeled+ label={label}+ id={id}+ align={orientation === "horizontal" ? "left" : "top"}+ fullWidth={fullWidth}+ >+ <div+ className={cn(+ "flex items-center gap-2",+ orientation === "vertical" &&+ "items-end inline-flex justify-center self-center mx-2",+ )}+ >+ <RangeSlider+ id={id}+ className={cn(+ "relative flex items-center select-none",+ !fullWidth && "data-[orientation=horizontal]:w-36 ",+ "data-[orientation=vertical]:h-36",+ )}+ value={internalValue}+ min={start}+ max={stop}+ step={step}+ orientation={orientation}+ // Triggered on all value changes+ onValueChange={(nextValue: number[]) => {+ setInternalValue(nextValue);+ if (!debounce) {+ setValue(nextValue);+ }+ }}+ // Triggered on mouse up+ onValueCommit={(nextValue: number[]) => {+ if (debounce) {+ setValue(nextValue);+ }+ }}+ />+ {showValue && (+ <div className="text-xs text-muted-foreground min-w-[16px]">+ {`${prettyNumber(internalValue[0])}, ${prettyNumber(internalValue[1])}`}+ </div>+ )}+ </div>+ </Labeled>+ );++ return fullWidth ? (+ <div className="my-3">{sliderElement}</div>+ ) : (+ sliderElement+ );+};diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.tsindex db1b6cc89d..e3d0562a8a 100644--- a/frontend/src/plugins/plugins.ts+++ b/frontend/src/plugins/plugins.ts@@ -13,6 +13,7 @@ import { FormPlugin } from "./impl/FormPlugin";import { MultiselectPlugin } from "./impl/MultiselectPlugin";import { NumberPlugin } from "./impl/NumberPlugin";import { RadioPlugin } from "./impl/RadioPlugin";+import { RangeSliderPlugin } from "./impl/RangeSliderPlugin";import { SliderPlugin } from "./impl/SliderPlugin";import { SwitchPlugin } from "./impl/SwitchPlugin";import { TextInputPlugin } from "./impl/TextInputPlugin";@@ -57,6 +58,7 @@ export const UI_PLUGINS: Array<IPlugin<any, unknown>> = [new NumberPlugin(),new RadioPlugin(),new RefreshPlugin(),+ new RangeSliderPlugin(),new SliderPlugin(),new SwitchPlugin(),new TabsPlugin(),diff --git a/marimo/_plugins/ui/__init__.py b/marimo/_plugins/ui/__init__.pyindex cabcd70eb1..279f2807e4 100644--- a/marimo/_plugins/ui/__init__.py+++ b/marimo/_plugins/ui/__init__.py@@ -25,6 +25,7 @@ __all__ = ["number","plotly","radio",+ "range_slider","refresh","slider","switch",@@ -53,6 +54,7 @@ from marimo._plugins.ui._impl.input import (multiselect,number,radio,+ range_slider,slider,text,text_area,diff --git a/marimo/_plugins/ui/_impl/input.py b/marimo/_plugins/ui/_impl/input.pyindex 52a27e08fc..d69aa0f4fc 100644--- a/marimo/_plugins/ui/_impl/input.py+++ b/marimo/_plugins/ui/_impl/input.py@@ -216,6 +216,106 @@ class slider(UIElement[Numeric, Numeric]):return cast(Numeric, self._dtype(value))+@mddoc+class range_slider(UIElement[List[Numeric], Sequence[Numeric]]):+ """+ A numeric slider for specifying a range over an interval.++ **Example.**++ ```python+ range_slider = mo.ui.range_slider(start=1, stop=10, step=2, value=[2, 6])+ ```++ **Attributes.**++ - `value`: the current range value of the slider+ - `start`: the minimum value of the interval+ - `stop`: the maximum value of the interval+ - `step`: the slider increment++ **Initialization Args.**++ - `start`: the minimum value of the interval+ - `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+ - `orientation`: the orientation of the slider,+ either "horizontal" or "vertical"+ - `show_value`: whether to display the current value of the slider+ - `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+ container+ """++ _name: Final[str] = "marimo-range-slider"++ def __init__(+ self,+ start: float,+ stop: float,+ step: Optional[float] = None,+ value: Optional[List[float]] = None,+ debounce: bool = False,+ orientation: Literal["horizontal", "vertical"] = "horizontal",+ show_value: bool = False,+ *,+ label: str = "",+ on_change: Optional[Callable[[Sequence[Numeric]], None]] = None,+ full_width: bool = False,+ ) -> None:+ value_has_float = (+ any(isinstance(num, float) for num in (value[0], value[1]))+ if value is not None+ else False+ )++ self._dtype = (+ float+ if any(isinstance(num, float) for num in (start, stop, step))+ or value_has_float+ else int+ )++ value = [start, stop] if value is None else value++ if stop < start or value[1] < value[0]:+ raise ValueError(+ "Invalid bounds: stop value must be greater than start value."+ )+ elif value[0] < start or value[1] > stop:+ raise ValueError(+ f"Value out of bounds: default value ({value}) must be "+ f"a range within start ({start}) and stop ({stop})."+ )++ self.start = start+ self.stop = stop+ self.step = step++ super().__init__(+ component_name=range_slider._name,+ initial_value=value,+ label=label,+ args={+ "start": start,+ "stop": stop,+ "step": step if step is not None else None,+ "debounce": debounce,+ "orientation": orientation,+ "show-value": show_value,+ "full-width": full_width,+ },+ on_change=on_change,+ )++ def _convert_value(self, value: List[Numeric]) -> Sequence[Numeric]:+ return cast(Sequence[Numeric], list(self._dtype(v) for v in value))++@mddocclass checkbox(UIElement[bool, bool]):"""diff --git a/marimo/_tutorials/ui.py b/marimo/_tutorials/ui.pyindex 713526ba31..aa433b0d31 100644--- a/marimo/_tutorials/ui.py+++ b/marimo/_tutorials/ui.py@@ -562,6 +562,7 @@ def __(mo):"multiselect": mo.ui.multiselect,"number": mo.ui.number,"radio": mo.ui.radio,+ "range_slider": mo.ui.range_slider,"slider": mo.ui.slider,"switch": mo.ui.switch,"tabs": mo.ui.tabs,@@ -623,6 +624,8 @@ def __(mo):return mo.ui.number(start=1, stop=10, step=0.5)elif value == mo.ui.radio:return mo.ui.radio(["a", "b", "c"], value="a")+ elif value == mo.ui.range_slider:+ return mo.ui.range_slider(start=1, stop=10, step=0.5)elif value == mo.ui.slider:return mo.ui.slider(start=1, stop=10, step=0.5)elif value == mo.ui.switch:diff --git a/tests/_plugins/ui/_impl/test_input.py b/tests/_plugins/ui/_impl/test_input.pyindex 4b8364d17d..ab9e1be1ee 100644--- a/tests/_plugins/ui/_impl/test_input.py+++ b/tests/_plugins/ui/_impl/test_input.py@@ -87,6 +87,53 @@ def test_slider_out_of_bounds() -> None:assert "out of bounds" in str(e.value)+def test_range_slider_init() -> None:+ slider = ui.range_slider(1, 10)+ assert slider.start == 1+ assert slider.stop == 10+ assert slider.step is None+ assert slider.value == [1, 10]++ slider = ui.range_slider(1, 10, value=[2, 5])+ assert slider.start == 1+ assert slider.stop == 10+ assert slider.step is None+ assert slider.value == [2, 5]+ for num in slider.value:+ assert isinstance(num, int)++ slider = ui.range_slider(1, 10, value=[2.0, 5.0])+ assert slider.value == [2.0, 5.0]+ for num in slider.value:+ assert isinstance(num, float)++ slider._update([3, 6])+ assert slider.value == [3.0, 6.0]+ for num in slider.value:+ # initial value was a float, so ints should be+ # cast to floats+ assert isinstance(num, float)+++def test_range_slider_invalid_bounds() -> None:+ with pytest.raises(ValueError) as e:+ ui.range_slider(1, 0)++ assert "Invalid bounds" in str(e.value)+++def test_range_slider_out_of_bounds() -> None:+ with pytest.raises(ValueError) as e:+ ui.range_slider(1, 10, value=[1, 11])++ assert "out of bounds" in str(e.value)++ with pytest.raises(ValueError) as e:+ ui.range_slider(1, 10, value=[0, 10])++ assert "out of bounds" in str(e.value)++def test_text() -> None:assert ui.text().value == ""assert ui.text(value="hello world").value == "hello world"