import React, { useEffect, useRef, useState } from 'react'; interface SliderProps { label: string; min?: number; max?: number; step?: number; initialValue?: number; heightPx?: number; minLabel?: string; maxLabel?: string; minIcon?: React.ReactNode; maxIcon?: React.ReactNode; bubbleElement?: React.ReactNode; bubbleLabel?: string; className?: string; minClassName?: string; maxClassName?: string; bubbleClassName?: string; onChange?: (value: number) => void; valueToPosition?: (value: number, min: number, max: number) => number; positionToValue?: (position: number, min: number, max: number) => number; } const Slider: React.FC = ({ label, min = 0, max = 100, step = 1, initialValue = 50, heightPx = 40, minLabel = '', maxLabel = '', minIcon, maxIcon, bubbleElement, bubbleLabel = '', className = '', minClassName = '', maxClassName = '', bubbleClassName = '', onChange, valueToPosition, positionToValue, }) => { const [value, setValue] = useState(initialValue); const [isRtl, setIsRtl] = useState(false); const sliderRef = useRef(null); // Default linear mapping functions const defaultValueToPosition = (val: number, minVal: number, maxVal: number) => { return ((val - minVal) / (maxVal - minVal)) * 100; }; const defaultPositionToValue = (pos: number, minVal: number, maxVal: number) => { return minVal + (pos / 100) * (maxVal - minVal); }; const valueToPos = valueToPosition || defaultValueToPosition; const posToValue = positionToValue || defaultPositionToValue; const handleChange = (e: React.ChangeEvent) => { const position = parseInt((e.target as HTMLInputElement).value, 10); const newValue = Math.round(posToValue(position, min, max) / step) * step; setValue(newValue); if (onChange) { onChange(newValue); } }; useEffect(() => { let node: HTMLElement | null = sliderRef.current; while (node) { if (node.getAttribute('dir') === 'rtl') { setIsRtl(true); break; } node = node.parentElement; } }, []); useEffect(() => { setValue(initialValue); }, [initialValue]); const percentage = valueToPos(value, min, max); const visualPercentage = (percentage / 100) * 95; return (
{/* Background track */}
{/* Filled portion */}
0 ? `max(calc(${visualPercentage}% + ${heightPx / 2}px), ${heightPx}px)` : '0px', [isRtl ? 'right' : 'left']: 0, }} >
{/* Min/Max labels */}
{minIcon ? minIcon : {minLabel}} {maxIcon ? maxIcon : {maxLabel}}
{/* Thumb bubble */}
{bubbleElement || bubbleLabel}
); }; export default Slider;