import cx from 'clsx'; import { isEqual, isNil } from 'lodash-es'; import { useCallback, useRef, useState } from 'react'; import type { Option } from '../models'; import styles from './HSegmentedControl.module.css'; type HSegmentedControlProps = { options?: Option[]; value?: Option['value']; onChange?: (value: Option['value']) => void; }; export function HSegmentedControl({ options = [], value, onChange }: HSegmentedControlProps) { const [selected, setSelected] = useState(value ?? options[0].value ?? null); const [sliderPosition, setSliderPosition] = useState(0); const [sliderWidth, setSliderWidth] = useState(0); const sliderRef = useRef(null); const optionsRef = useRef([]); const handleSelectAction = useCallback((option: Option['value'], index: number) => { setSelected(option); onChange?.(option); if (optionsRef.current && optionsRef.current.length > index) { const optionElement = optionsRef.current[index]; setSliderPosition(optionElement.offsetLeft); setSliderWidth(optionElement.offsetWidth); } }, []); return (
{options.map((option, index) => (
(optionsRef.current[index] = el!)} onClick={() => handleSelectAction(option.value, index)}> {option.label}
))} {!isNil(selected) && (
)}
); }