import * as SliderPrimitive from "@radix-ui/react-slider"; import { ComponentProps, ComponentRef, forwardRef, useEffect, useMemo, useState } from "react"; import { cn } from "../hooks"; interface SliderProps extends ComponentProps { showStep?: boolean; } /** * Slider with optional step markers and multi-thumb support. */ const Slider = forwardRef, SliderProps>( function SliderRoot( { className, defaultValue, value, onValueChange, showStep = false, step = 1, min = 0, max = 100, ...props }, ref, ) { const [currentValue, setCurrentValue] = useState(value ?? defaultValue ?? [0]); const _values = useMemo( () => Array.isArray(value) ? value : Array.isArray(defaultValue) ? defaultValue : [min, max], [value, defaultValue, min, max], ); useEffect(() => { if (value) { setCurrentValue(value); } }, [value]); return ( { onValueChange?.(v); setCurrentValue(v); }} ref={ref} min={min} max={max} step={step} className={cn( "relative", "flex", "w-full", "touch-none", "select-none", "items-center", "data-[orientation=vertical]:h-full", "data-[orientation=vertical]:min-h-44", "data-[orientation=vertical]:w-auto", "data-[orientation=vertical]:flex-col", className, )} {...props} > {showStep && } {Array.from({ length: _values.length }, (_, index) => ( ))} ); }, ); interface SliderStepsProps { min: number; max: number; step: number; currentValue: number[]; } /** * Visual step indicators drawn on the track. */ function SliderSteps({ step, min, max, currentValue }: SliderStepsProps) { const steps = useMemo(() => { const value = max - min; const stepCount = Math.ceil(value / step); return Array.from({ length: stepCount + 1 }, (_, i) => { return { position: Math.min((100 / value) * (i * step), 100), v: i * step + min }; }); }, [max, min, step]); const [minRange, maxRange] = useMemo(() => { if (currentValue.length > 1) { return [Math.min(...currentValue), Math.max(...currentValue)]; } else { return [0, ...currentValue]; } }, [currentValue]); return steps.map((step, i) => { /* * 9.6 is the width of the thumb in pixels * 1 is the direction of the thumb (1 for right, -1 for left) * */ const thumbInBoundsOffset = getThumbInBoundsOffset(9.6, step.position, 1); return ( maxRange }, )} /> ); }); } /** * Offsets the thumb centre point while sliding to ensure it remains * within the bounds of the slider when reaching the edges */ function getThumbInBoundsOffset(width: number, left: number, direction: number) { const halfWidth = width / 2; const halfPercent = 50; const offset = linearScale([0, halfPercent], [0, halfWidth]); return (halfWidth - offset(left) * direction) * direction; } function linearScale(input: [number, number], output: [number, number]) { return (value: number) => { if (input[0] === input[1] || output[0] === output[1]) return output[0]; const ratio = (output[1] - output[0]) / (input[1] - input[0]); return output[0] + ratio * (value - input[0]); }; } export { Slider }; export type { SliderProps };