import { type ComponentPropsWithoutRef, useEffect, useRef } from 'react'; import { ToggleGroup as RToggleGroup } from 'radix-ui'; import { cx } from '../utils'; type SegProps = Omit< ComponentPropsWithoutRef, 'type' | 'onValueChange' | 'defaultValue' | 'value' > & { value: string; defaultValue?: string; onValueChange: (v: string) => void; items: Array<{ value: string; label: string }>; }; export const SegmentedControl = ({ value, onValueChange, items, className, ...props }: SegProps) => { const rootRef = useRef(null); const thumbRef = useRef(null); const initialized = useRef(false); useEffect(() => { const root = rootRef.current; const thumb = thumbRef.current; if (!root || !thumb) return; const selected = root.querySelector('[data-state="on"]'); if (!selected) return; if (!initialized.current) { thumb.style.transition = 'none'; } thumb.style.transform = `translateX(${selected.offsetLeft}px)`; thumb.style.width = `${selected.offsetWidth}px`; if (!initialized.current) { thumb.getBoundingClientRect(); thumb.style.transition = ''; initialized.current = true; } }, [value]); return ( v && onValueChange(v)} {...props} > {items.map((it) => ( {it.label} ))} ); };