import classNames from "classnames"; import { type ReactNode, useRef } from "react"; import { useStateWithDeps } from "../../hooks/useStateWithDeps"; import { generateId } from "../../lib/generateId"; import { Button } from "./Button"; import type { IconProps } from "./Icon"; import { IconButton, type IconButtonProps } from "./IconButton"; import { Label } from "./Label"; import { HStack } from "./Stacks"; interface Props { options: { value: T; label: string; icon?: IconProps["icon"] }[]; onChange: (value: T) => void; value: T; name: string; size?: IconButtonProps["size"]; label: string; className?: string; hideLabel?: boolean; labelClassName?: string; help?: ReactNode; } export function SegmentedControl({ value, onChange, options, size = "xs", label, hideLabel, labelClassName, help, className, }: Props) { const [selectedValue, setSelectedValue] = useStateWithDeps(value, [value]); const containerRef = useRef(null); const id = useRef(`input-${generateId()}`); return (
{ const selectedIndex = options.findIndex((o) => o.value === selectedValue); if (e.key === "ArrowRight") { e.preventDefault(); const newIndex = Math.abs((selectedIndex + 1) % options.length); if (options[newIndex]) setSelectedValue(options[newIndex].value); const child = containerRef.current?.children[newIndex] as HTMLButtonElement; child.focus(); } else if (e.key === "ArrowLeft") { e.preventDefault(); const newIndex = Math.abs((selectedIndex - 1) % options.length); if (options[newIndex]) setSelectedValue(options[newIndex].value); const child = containerRef.current?.children[newIndex] as HTMLButtonElement; child.focus(); } }} > {options.map((o) => { const isSelected = selectedValue === o.value; const isActive = value === o.value; if (o.icon == null) { return ( ); } else { return ( onChange(o.value)} /> ); } })}
); }