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.

fix(slider): correct editable input behavior with steps and fractional values (#9860)

Shahmir Varqha60724deb1a9d
diff --git a/frontend/src/components/ui/number-field.tsx b/frontend/src/components/ui/number-field.tsx
index 4791ede54a..0ea9415591 100644
--- a/frontend/src/components/ui/number-field.tsx
+++ b/frontend/src/components/ui/number-field.tsx
@@ -25,7 +25,10 @@ export interface NumberFieldProps extends AriaNumberFieldProps {
}
export const NumberField = React.forwardRef<HTMLInputElement, NumberFieldProps>(
- ({ placeholder, variant = "default", onInputText, ...props }, ref) => {
+ (
+ { placeholder, variant = "default", onInputText, formatOptions, ...props },
+ ref,
+ ) => {
const { locale } = useLocale();
return (
<AriaNumberField
@@ -33,6 +36,7 @@ export const NumberField = React.forwardRef<HTMLInputElement, NumberFieldProps>(
formatOptions={{
minimumFractionDigits: 0,
maximumFractionDigits: maxFractionalDigits(locale),
+ ...formatOptions,
}}
>
<div
diff --git a/frontend/src/plugins/impl/SliderPlugin.tsx b/frontend/src/plugins/impl/SliderPlugin.tsx
index 7545dc8419..08ecebc6ee 100644
--- a/frontend/src/plugins/impl/SliderPlugin.tsx
+++ b/frontend/src/plugins/impl/SliderPlugin.tsx
@@ -1,10 +1,15 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { type JSX, useEffect, useId, useState } from "react";
+import { type JSX, useEffect, useId, useMemo, useState } from "react";
import { useLocale } from "react-aria";
import { z } from "zod";
import { NumberField } from "@/components/ui/number-field";
import { cn } from "@/utils/cn";
-import { prettyScientificNumber } from "@/utils/numbers";
+import { clamp } from "@/utils/math";
+import {
+ maxFractionDigitsForSteps,
+ prettyScientificNumber,
+ roundToFractionDigits,
+} from "@/utils/numbers";
import { Slider } from "../../components/ui/slider";
import type { IPlugin, IPluginProps, Setter } from "../types";
import { Labeled } from "./common/labeled";
@@ -46,8 +51,9 @@ export class SliderPlugin implements IPlugin<T, Data> {
render(props: IPluginProps<T, Data>): JSX.Element {
// Create the valueMap function
const valueMap = (sliderValue: number): number => {
- if (props.data.steps && props.data.steps.length > 0) {
- return props.data.steps[sliderValue];
+ const { steps } = props.data;
+ if (steps && steps.length > 0) {
+ return steps[clamp(sliderValue, 0, steps.length - 1)];
}
return sliderValue;
};
@@ -69,6 +75,66 @@ interface SliderProps extends Data {
valueMap: (sliderValue: number) => number;
}
+interface StepsConfig {
+ steps: T[];
+ fractionDigits: number;
+ minValue: number;
+ maxValue: number;
+ inputStep: number;
+ formatOptions: {
+ minimumFractionDigits: number;
+ maximumFractionDigits: number;
+ };
+}
+
+// Index of the step whose value is closest to `target`.
+function nearestStepIndex(stepValues: T[], target: number): number {
+ let bestIndex = 0;
+ let bestDistance = Number.POSITIVE_INFINITY;
+ for (let i = 0; i < stepValues.length; i++) {
+ const distance = Math.abs(stepValues[i] - target);
+ if (distance < bestDistance) {
+ bestDistance = distance;
+ bestIndex = i;
+ }
+ }
+ return bestIndex;
+}
+
+// When `steps` are provided, the slider runs in *index* space (start=0,
+// stop=len-1, step=1) while the input must display and accept the *actual*
+// step values. This config maps the input back into value space.
+function computeStepsConfig(steps: T[] | null): StepsConfig | null {
+ if (!steps || steps.length === 0) {
+ return null;
+ }
+ const sorted = steps.toSorted((a, b) => a - b);
+ // Smallest positive gap between consecutive step values, used as the input's
+ // increment/decrement amount. Falls back to 1 when undefined.
+ let inputStep = Number.POSITIVE_INFINITY;
+ for (let i = 1; i < sorted.length; i++) {
+ const gap = sorted[i] - sorted[i - 1];
+ if (gap > 0 && gap < inputStep) {
+ inputStep = gap;
+ }
+ }
+ if (!Number.isFinite(inputStep) || inputStep <= 0) {
+ inputStep = 1;
+ }
+ const fractionDigits = maxFractionDigitsForSteps(steps, inputStep);
+ return {
+ steps,
+ fractionDigits,
+ minValue: roundToFractionDigits(sorted[0], fractionDigits),
+ maxValue: roundToFractionDigits(sorted[sorted.length - 1], fractionDigits),
+ inputStep: roundToFractionDigits(inputStep, fractionDigits),
+ formatOptions: {
+ minimumFractionDigits: 0,
+ maximumFractionDigits: fractionDigits,
+ },
+ };
+}
+
const SliderComponent = ({
label,
setValue,
@@ -95,6 +161,64 @@ const SliderComponent = ({
setInternalValue(value);
}, [value]);
+ const stepsConfig = useMemo(() => computeStepsConfig(steps), [steps]);
+
+ const handleInputChange = (nextValue: number | null | undefined): void => {
+ if (stepsConfig) {
+ const { steps: stepValues, fractionDigits } = stepsConfig;
+ // Cleared input -> reset to the first step.
+ if (nextValue == null || Number.isNaN(nextValue)) {
+ setInternalValue(0);
+ setValue(0);
+ return;
+ }
+ const roundedNext = roundToFractionDigits(nextValue, fractionDigits);
+ let index = nearestStepIndex(stepValues, roundedNext);
+ // If the nearest step is the current one but the value actually moved
+ // (e.g. stepper arrows on non-uniform steps), nudge one index in the
+ // direction of travel so the input never gets "stuck". Caveat: a typed
+ // value closest to the current step but past it nudges too, so on
+ // non-uniform steps typing a nearby number can jump to the adjacent step.
+ const currentValue = roundToFractionDigits(
+ stepValues[internalValue] ?? stepValues[0],
+ fractionDigits,
+ );
+ if (index === internalValue && roundedNext !== currentValue) {
+ index =
+ roundedNext > currentValue
+ ? Math.min(internalValue + 1, stepValues.length - 1)
+ : Math.max(internalValue - 1, 0);
+ }
+ setInternalValue(index);
+ setValue(index);
+ return;
+ }
+
+ // No steps: the input value is the slider value directly.
+ const resolved =
+ nextValue == null || Number.isNaN(nextValue) ? Number(start) : nextValue;
+ setInternalValue(resolved);
+ setValue(resolved);
+ };
+
+ const inputProps = stepsConfig
+ ? {
+ value: roundToFractionDigits(
+ valueMap(internalValue),
+ stepsConfig.fractionDigits,
+ ),
+ minValue: stepsConfig.minValue,
+ maxValue: stepsConfig.maxValue,
+ step: stepsConfig.inputStep,
+ formatOptions: stepsConfig.formatOptions,
+ }
+ : {
+ value: valueMap(internalValue),
+ minValue: start,
+ maxValue: stop,
+ step,
+ };
+
const sliderElement = (
<Labeled
label={label}
@@ -123,14 +247,14 @@ const SliderComponent = ({
step={step}
orientation={orientation}
// Triggered on all value changes
- onValueChange={([nextValue]) => {
+ onValueChange={([nextValue]: number[]) => {
setInternalValue(nextValue);
if (!debounce) {
setValue(nextValue);
}
}}
// Triggered on mouse up
- onValueCommit={([nextValue]) => {
+ onValueCommit={([nextValue]: [number]) => {
if (debounce) {
setValue(nextValue);
}
@@ -145,18 +269,8 @@ const SliderComponent = ({
)}
{includeInput && (
<NumberField
- value={valueMap(internalValue)}
- onChange={(nextValue) => {
- // If nextValue is null/undefined/NaN (input cleared), set to start
- if (nextValue == null || Number.isNaN(nextValue)) {
- nextValue = Number(start);
- }
- setInternalValue(nextValue);
- setValue(nextValue);
- }}
- minValue={start}
- maxValue={stop}
- step={step}
+ {...inputProps}
+ onChange={handleInputChange}
className="w-24"
aria-label={`${label || "Slider"} value input`}
isDisabled={disabled}
diff --git a/frontend/src/plugins/impl/__tests__/SliderPlugin.test.tsx b/frontend/src/plugins/impl/__tests__/SliderPlugin.test.tsx
index 9ded85e333..c678669761 100644
--- a/frontend/src/plugins/impl/__tests__/SliderPlugin.test.tsx
+++ b/frontend/src/plugins/impl/__tests__/SliderPlugin.test.tsx
@@ -50,11 +50,18 @@ describe("SliderPlugin", () => {
vi.useRealTimers();
});
- const createProps = (
- debounce: boolean,
- includeInput: boolean,
- setValue: ReturnType<typeof vi.fn>,
- ): IPluginProps<number, z.infer<typeof SliderPlugin.prototype.validator>> => {
+ const createProps = ({
+ debounce,
+ includeInput,
+ setValue,
+ }: {
+ debounce: boolean;
+ includeInput: boolean;
+ setValue: ReturnType<typeof vi.fn>;
+ }): IPluginProps<
+ number,
+ z.infer<typeof SliderPlugin.prototype.validator>
+ > => {
return {
host: document.createElement("div"),
value: 5,
@@ -76,10 +83,57 @@ describe("SliderPlugin", () => {
};
};
+ // When `steps` are provided, the slider works in *index* space: `value`,
+ // `start`, `stop` and `step` are all indices into the `steps` array, while
+ // the editable input shows/accepts the actual step values.
+ const createStepsProps = ({
+ steps,
+ valueIndex,
+ setValue,
+ }: {
+ steps: number[];
+ valueIndex: number;
+ setValue: ReturnType<typeof vi.fn>;
+ }): IPluginProps<
+ number,
+ z.infer<typeof SliderPlugin.prototype.validator>
+ > => {
+ return {
+ host: document.createElement("div"),
+ value: valueIndex,
+ setValue,
+ data: {
+ initialValue: valueIndex,
+ start: 0,
+ stop: steps.length - 1,
+ step: 1,
+ label: "Test Slider",
+ debounce: false,
+ orientation: "horizontal" as const,
+ showValue: false,
+ fullWidth: false,
+ includeInput: true,
+ steps,
+ },
+ functions: {},
+ };
+ };
+
+ const typeAndCommit = (input: HTMLElement, value: string) => {
+ act(() => {
+ fireEvent.change(input, { target: { value } });
+ fireEvent.blur(input);
+ });
+ };
+
it("slider triggers setValue immediately when debounce is false", () => {
const plugin = new SliderPlugin();
const setValue = vi.fn();
- const props = createProps(false, false, setValue);
+ const props = createProps({
+ debounce: false,
+ includeInput: false,
+ setValue,
+ });
const { getByRole } = render(plugin.render(props));
act(() => {
@@ -98,7 +152,11 @@ describe("SliderPlugin", () => {
it("slider waits until commit before calling setValue when debounce is true", () => {
const plugin = new SliderPlugin();
const setValue = vi.fn();
- const props = createProps(true, false, setValue);
+ const props = createProps({
+ debounce: true,
+ includeInput: false,
+ setValue,
+ });
const { getByRole } = render(plugin.render(props));
act(() => {
@@ -124,7 +182,7 @@ describe("SliderPlugin", () => {
it("editable input triggers setValue immediately even when slider debounce is true", () => {
const plugin = new SliderPlugin();
const setValue = vi.fn();
- const props = createProps(true, true, setValue);
+ const props = createProps({ debounce: true, includeInput: true, setValue });
const { getByRole } = render(plugin.render(props));
act(() => {
@@ -145,4 +203,216 @@ describe("SliderPlugin", () => {
// setValue should be called immediately regardless of debounce=true.
expect(setValue).toHaveBeenCalledWith(9);
});
+
+ describe("editable input with steps (regression for #9850)", () => {
+ it("displays the actual step value, not the index", () => {
+ const plugin = new SliderPlugin();
+ const setValue = vi.fn();
+ // steps[0] === -4, displayed value must be -4 (not the index 0).
+ const props = createStepsProps({
+ steps: [-4, -3, -2, -1],
+ valueIndex: 0,
+ setValue,
+ });
+ const { getByRole } = render(plugin.render(props));
+
+ act(() => {
+ vi.advanceTimersByTime(0);
+ });
+
+ const input = getByRole("textbox") as HTMLInputElement;
+ expect(input.value).toBe("-4");
+ });
+
+ it("displays decimal step values without float artifacts", () => {
+ const plugin = new SliderPlugin();
+ const setValue = vi.fn();
+ const props = createStepsProps({
+ steps: [0.1, 0.2, 0.3, 0.4],
+ valueIndex: 2,
+ setValue,
+ });
+ const { getByRole } = render(plugin.render(props));
+
+ act(() => {
+ vi.advanceTimersByTime(0);
+ });
+
+ const input = getByRole("textbox") as HTMLInputElement;
+ expect(input.value).toBe("0.3");
+ });
+
+ it("steps decimal input increment and decrement buttons move between steps", () => {
+ const plugin = new SliderPlugin();
+ const setValue = vi.fn();
+ const props = createStepsProps({
+ steps: [0.1, 0.2, 0.3, 0.4],
+ valueIndex: 2,
+ setValue,
+ });
+ const { getByRole } = render(plugin.render(props));
+
+ act(() => {
+ vi.advanceTimersByTime(0);
+ });
+
+ const decrement = getByRole("button", {
+ name: "Decrease Test Slider value input",
+ });
+ const increment = getByRole("button", {
+ name: "Increase Test Slider value input",
+ });
+
+ expect(decrement).not.toBeDisabled();
+
+ act(() => {
+ fireEvent.click(decrement);
+ });
+ expect(setValue.mock.calls).toEqual([[1]]);
+
+ act(() => {
+ fireEvent.click(increment);
+ });
+ expect(setValue).toHaveBeenLastCalledWith(2);
+ });
+
+ it("maps a typed integer step value back to its index", () => {
+ const plugin = new SliderPlugin();
+ const setValue = vi.fn();
+ const props = createStepsProps({
+ steps: [1, 2, 3, 4],
+ valueIndex: 0,
+ setValue,
+ });
+ const { getByRole } = render(plugin.render(props));
+
+ act(() => {
+ vi.advanceTimersByTime(0);
+ });
+
+ const input = getByRole("textbox");
+ // Typing "4" should select the last step (index 3), not index 4.
+ typeAndCommit(input, "4");
+ expect(setValue).toHaveBeenLastCalledWith(3);
+
+ // Typing "2" should select index 1, not get "stuck" on 3.
+ typeAndCommit(input, "2");
+ expect(setValue).toHaveBeenLastCalledWith(1);
+ });
+
+ it("maps fractional step values back to their index", () => {
+ const plugin = new SliderPlugin();
+ const setValue = vi.fn();
+ const props = createStepsProps({
+ steps: [0.1, 0.2, 0.3, 0.4],
+ valueIndex: 0,
+ setValue,
+ });
+ const { getByRole } = render(plugin.render(props));
+
+ act(() => {
+ vi.advanceTimersByTime(0);
+ });
+
+ const input = getByRole("textbox");
+ typeAndCommit(input, "0.3");
+ expect(setValue).toHaveBeenLastCalledWith(2);
+ });
+
+ it("maps negative step values back to their index", () => {
+ const plugin = new SliderPlugin();
+ const setValue = vi.fn();
+ const props = createStepsProps({
+ steps: [-4, -3, -2, -1],
+ valueIndex: 0,
+ setValue,
+ });
+ const { getByRole } = render(plugin.render(props));
+
+ act(() => {
+ vi.advanceTimersByTime(0);
+ });
+
+ const input = getByRole("textbox");
+ typeAndCommit(input, "-2");
+ expect(setValue).toHaveBeenLastCalledWith(2);
+ });
+
+ it("clamps out-of-range typed values to the nearest step index", () => {
+ const plugin = new SliderPlugin();
+ const setValue = vi.fn();
+ const props = createStepsProps({
+ steps: [1, 2, 3, 4],
+ valueIndex: 0,
+ setValue,
+ });
+ const { getByRole } = render(plugin.render(props));
+
+ act(() => {
+ vi.advanceTimersByTime(0);
+ });
+
+ const input = getByRole("textbox");
+ // Above the max step -> clamps to the last index.
+ typeAndCommit(input, "100");
+ expect(setValue).toHaveBeenLastCalledWith(3);
+ });
+
+ it("does not crash when steps shrink while the index is temporarily out of range", () => {
+ const plugin = new SliderPlugin();
+ const setValue = vi.fn();
+ // Start at the last index of a 5-element steps array.
+ const props = createStepsProps({
+ steps: [10, 20, 30, 40, 50],
+ valueIndex: 4,
+ setValue,
+ });
+ const { getByRole, rerender } = render(plugin.render(props));
+
+ act(() => {
+ vi.advanceTimersByTime(0);
+ });
+
+ // Shrink `steps` so the held index (4) is now out of range. The index
+ // syncs in an effect after this render, so the render must not throw on
+ // the stale, out-of-range index.
+ const shrunkProps = createStepsProps({
+ steps: [10, 20],
+ valueIndex: 1,
+ setValue,
+ });
+ expect(() => {
+ act(() => {
+ rerender(plugin.render(shrunkProps));
+ vi.advanceTimersByTime(0);
+ });
+ }).not.toThrow();
+
+ const input = getByRole("textbox") as HTMLInputElement;
+ expect(input.value).toBe("20");
+ });
+
+ it("nudges to the adjacent step on non-uniform steps even when the current step is nearest (known caveat)", () => {
+ const plugin = new SliderPlugin();
+ const setValue = vi.fn();
+ // Non-uniform steps; start at index 2 (value 10).
+ const props = createStepsProps({
+ steps: [0, 1, 10, 100],
+ valueIndex: 2,
+ setValue,
+ });
+ const { getByRole } = render(plugin.render(props));
+
+ act(() => {
+ vi.advanceTimersByTime(0);
+ });
+
+ const input = getByRole("textbox");
+ // 10 is far closer to 12 than 100 is, but because 12 > 10 the input nudges
+ // up one index. This documents the stepper-vs-typing limitation: onChange
+ // can't distinguish a typed value from a stepper-button increment.
+ typeAndCommit(input, "12");
+ expect(setValue).toHaveBeenLastCalledWith(3);
+ });
+ });
});
diff --git a/frontend/src/utils/__tests__/numbers.test.ts b/frontend/src/utils/__tests__/numbers.test.ts
index d64e6ce8dd..36d71e3877 100644
--- a/frontend/src/utils/__tests__/numbers.test.ts
+++ b/frontend/src/utils/__tests__/numbers.test.ts
@@ -1,6 +1,8 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { describe, expect, it } from "vitest";
import {
+ countFractionDigits,
+ maxFractionDigitsForSteps,
prettyEngineeringNumber,
prettyNumber,
prettyScientificNumber,
@@ -86,3 +88,21 @@ describe("prettyEngineeringNumber", () => {
expect(prettyEngineeringNumber(-0.000_123_4, locale)).toBe("-123µ");
});
});
+
+describe("countFractionDigits", () => {
+ it("counts decimal places without float noise", () => {
+ expect(countFractionDigits(1)).toBe(0);
+ expect(countFractionDigits(0.1)).toBe(1);
+ expect(countFractionDigits(0.3)).toBe(1);
+ expect(countFractionDigits(0.000025)).toBe(6);
+ expect(countFractionDigits(3.5)).toBe(1);
+ });
+});
+
+describe("maxFractionDigitsForSteps", () => {
+ it("infers precision from steps and gaps", () => {
+ expect(maxFractionDigitsForSteps([0.1, 0.2, 0.3, 0.4], 0.1)).toBe(1);
+ expect(maxFractionDigitsForSteps([1, 2, 3.5, 4], 0.5)).toBe(1);
+ expect(maxFractionDigitsForSteps([1, 2, 3, 4], 1)).toBe(0);
+ });
+});
diff --git a/frontend/src/utils/numbers.ts b/frontend/src/utils/numbers.ts
index e471a7229f..a9283eea59 100644
--- a/frontend/src/utils/numbers.ts
+++ b/frontend/src/utils/numbers.ts
@@ -23,6 +23,33 @@ export const maxFractionalDigits = memoizeLastValue((locale: string) => {
return 0;
});
+/** Decimal places needed to display `n` without float noise. */
+export function countFractionDigits(n: number): number {
+ if (!Number.isFinite(n) || n === 0) {
+ return 0;
+ }
+ const normalized = n.toFixed(12).replace(/\.?0+$/, "");
+ const dot = normalized.indexOf(".");
+ return dot === -1 ? 0 : normalized.length - dot - 1;
+}
+
+/** Max fraction digits to display a set of step values cleanly. */
+export function maxFractionDigitsForSteps(
+ steps: number[],
+ minGap: number,
+): number {
+ let max = countFractionDigits(minGap);
+ for (const step of steps) {
+ max = Math.max(max, countFractionDigits(step));
+ }
+ return max;
+}
+
+/** Round away float noise so step-based inputs stay on a clean decimal grid. */
+export function roundToFractionDigits(n: number, digits: number): number {
+ return Number(n.toFixed(digits));
+}
+
export function prettyNumber(value: unknown, locale: string): string {
if (value === undefined || value === null) {
return "";
diff --git a/marimo/_smoke_tests/inputs/sliders.py b/marimo/_smoke_tests/inputs/sliders.py
index 16e4930f36..e718b6e89a 100644
--- a/marimo/_smoke_tests/inputs/sliders.py
+++ b/marimo/_smoke_tests/inputs/sliders.py
@@ -1,40 +1,246 @@
import marimo
-__generated_with = "0.15.5"
+__generated_with = "0.23.9"
app = marimo.App(width="medium")
@app.cell
def _():
import marimo as mo
+
return (mo,)
@app.cell
def _(mo):
- # Precision should be accurate, no rounding
- mo.ui.slider(
- label="1/1000 precision value",
+ mo.md("""
+ # Slider smoke tests
+ """)
+ return
+
+
+def _(mo):
+ # --- Basic interval sliders ---
+ basic = mo.ui.slider(1, 10)
+ with_step = mo.ui.slider(1, 10, step=2, value=5, show_value=True)
+ float_slider = mo.ui.slider(0.0, 1.0, step=0.1, value=0.5, show_value=True)
+ negative = mo.ui.slider(-10, 10, value=0, show_value=True)
+ with_input = mo.ui.slider(0, 100, value=42, include_input=True, show_value=True)
+ debounced = mo.ui.slider(0, 10, value=5, debounce=True, show_value=True)
+ disabled = mo.ui.slider(0, 10, value=3, disabled=True, show_value=True)
+ vertical = mo.ui.slider(
+ 0, 10, value=5, orientation="vertical", show_value=True, label="Vertical"
+ )
+ full_width = mo.ui.slider(0, 10, value=5, full_width=True, label="Full width")
+ labeled = mo.ui.slider(1, 5, value=2, label="**Markdown** label", show_value=True)
+ return (
+ basic,
+ debounced,
+ disabled,
+ float_slider,
+ full_width,
+ labeled,
+ negative,
+ vertical,
+ with_input,
+ with_step,
+ )
+
+
+def _(basic, float_slider, mo, negative, with_input, with_step):
+ mo.vstack(
+ [
+ mo.md("## Basic interval sliders"),
+ mo.hstack([basic, mo.md("`start`/`stop` only (default value = start)")]),
+ mo.hstack([with_step, mo.md("Integer range with `step=2`")]),
+ mo.hstack([float_slider, mo.md("Float range with `step=0.1`")]),
+ mo.hstack([negative, mo.md("Negative to positive range")]),
+ mo.hstack([with_input, mo.md("`include_input=True` — type or use arrows")]),
+ ],
+ gap=1,
+ )
+ return
+
+
+def _(debounced, disabled, full_width, labeled, mo, vertical):
+ mo.vstack(
+ [
+ mo.md("## Options"),
+ mo.hstack([debounced, mo.md("`debounce=True` — value commits on release")]),
+ mo.hstack([disabled, mo.md("`disabled=True`")]),
+ vertical,
+ full_width,
+ labeled,
+ ],
+ gap=1,
+ )
+ return
+
+
+def _(mo):
+ # --- High-precision floats ---
+ precision_milli = mo.ui.slider(
+ label="1/1000 precision",
start=0,
stop=0.1,
step=0.001,
value=0.025,
show_value=True,
+ include_input=True,
+ )
+ precision_micro = mo.ui.slider(
+ label="1/1,000,000 precision",
+ start=0,
+ stop=0.0001,
+ step=0.000001,
+ value=0.000025,
+ show_value=True,
+ include_input=True,
+ )
+ return precision_micro, precision_milli
+
+
+def _(mo, precision_micro, precision_milli):
+ mo.vstack(
+ [
+ mo.md("## Precision"),
+ mo.md(
+ "Values must display exactly — no rounding in the input or label."
+ ),
+ precision_milli,
+ precision_micro,
+ ],
+ gap=1,
)
return
@app.cell
def _(mo):
- # Precision should be accurate, no rounding
- mo.ui.slider(
- label="1/1000 precision value",
- start=0,
- stop=0.0001,
- step=0.000001,
- value=0.000025,
+ # --- Custom steps (regression for #9850) ---
+ steps_int = mo.ui.slider(
+ steps=[1, 2, 3, 4],
+ value=3,
+ include_input=True,
+ show_value=True,
+ label="Integer steps",
+ )
+ steps_mixed = mo.ui.slider(
+ steps=[1, 2, 3.5, 4],
+ value=3.5,
+ include_input=True,
show_value=True,
+ label="Mixed float steps",
)
+ steps_decimal = mo.ui.slider(
+ steps=[0.1, 0.2, 0.3, 0.4],
+ value=0.3,
+ include_input=True,
+ show_value=True,
+ label="Decimal steps",
+ )
+ steps_negative = mo.ui.slider(
+ steps=[-4, -3, -2, -1],
+ value=-2,
+ include_input=True,
+ show_value=True,
+ label="Negative steps",
+ )
+ return steps_decimal, steps_int, steps_mixed, steps_negative
+
+
+def _(mo, steps_decimal, steps_int, steps_mixed, steps_negative):
+ mo.vstack(
+ [
+ mo.md("## Custom `steps`"),
+ mo.md(
+ """
+ With `include_input=True`, the text field must show the **actual**
+ step value (not the index). Arrow keys and typing should move to
+ valid steps only.
+ """
+ ),
+ steps_int,
+ steps_mixed,
+ steps_decimal,
+ steps_negative,
+ ],
+ gap=1,
+ )
+ return
+
+
+def _(mo):
+ import numpy as np
+
+ steps_numpy = mo.ui.slider(
+ steps=np.logspace(0, 2, 5),
+ show_value=True,
+ include_input=True,
+ label="NumPy logspace steps",
+ )
+ return (steps_numpy,)
+
+
+def _(mo, steps_numpy):
+ mo.vstack(
+ [
+ mo.md("## NumPy `steps`"),
+ steps_numpy,
+ ],
+ gap=1,
+ )
+ return
+
+
+def _(mo):
+ # --- Range sliders ---
+ range_basic = mo.ui.range_slider(1, 10)
+ range_with_value = mo.ui.range_slider(1, 10, step=2, value=[2, 6], show_value=True)
+ range_steps = mo.ui.range_slider(
+ steps=[1, 3, 6, 10, 17, 20],
+ value=[3, 17],
+ show_value=True,
+ label="Range with custom steps",
+ )
+ return range_basic, range_steps, range_with_value
+
+
+def _(mo, range_basic, range_steps, range_with_value):
+ mo.vstack(
+ [
+ mo.md("## Range sliders"),
+ range_basic,
+ range_with_value,
+ range_steps,
+ ],
+ gap=1,
+ )
+ return
+
+
+def test_invalid_slider_raises(mo):
+ import pytest
+
+ with pytest.raises(ValueError, match="Invalid bounds"):
+ mo.ui.slider(10, 1)
+
+ with pytest.raises(ValueError, match="out of bounds"):
+ mo.ui.slider(1, 10, value=11)
+
+ with pytest.raises(ValueError, match="Invalid arguments"):
+ mo.ui.slider(start=1, stop=10, steps=[1, 2, 3])
return