| 1 | import { Children, cloneElement, isValidElement, type ButtonHTMLAttributes, type HTMLAttributes } from "react"; |
| 2 | |
| 3 | if (import.meta.env?.MODE) void import("./SettingsOptions.css"); |
| 4 | |
| 5 | /** Shared segmented choices; callers retain their labels, state and save handlers. */ |
| 6 | export function SettingsOptions({ |
| 7 | children, |
| 8 | className = "", |
| 9 | layout = "content", |
| 10 | onKeyDown, |
| 11 | role = "group", |
| 12 | ...props |
| 13 | }: HTMLAttributes<HTMLDivElement> & { layout?: "content" | "field" | "fill" }) { |
| 14 | return ( |
| 15 | <div |
| 16 | {...props} |
| 17 | role={role} |
| 18 | className={`settings-options settings-options--${layout} ${className}`} |
| 19 | onKeyDown={(event) => { |
| 20 | onKeyDown?.(event); |
| 21 | if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey) return; |
| 22 | const buttons = Array.from(event.currentTarget.querySelectorAll<HTMLButtonElement>(":scope > button:not(:disabled)")); |
| 23 | const index = buttons.indexOf(event.target as HTMLButtonElement); |
| 24 | if (index < 0 || !["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return; |
| 25 | event.preventDefault(); |
| 26 | const next = event.key === "Home" ? 0 : event.key === "End" ? buttons.length - 1 |
| 27 | : (index + (event.key === "ArrowRight" ? 1 : -1) + buttons.length) % buttons.length; |
| 28 | buttons[next].focus(); |
| 29 | buttons[next].click(); |
| 30 | }} |
| 31 | > |
| 32 | {Children.map(children, (child) => { |
| 33 | if (!isValidElement<ButtonHTMLAttributes<HTMLButtonElement>>(child) || child.type !== "button") return child; |
| 34 | const selected = child.props["aria-checked"] ?? child.props["aria-selected"] ?? child.props["aria-pressed"] |
| 35 | ?? /(?:set-seg__btn--on|provider-add-segmented__item--active)/.test(child.props.className ?? ""); |
| 36 | return cloneElement(child, { |
| 37 | type: child.props.type ?? "button", |
| 38 | title: child.props.title ?? (typeof child.props.children === "string" ? child.props.children : undefined), |
| 39 | "aria-pressed": child.props.role === "radio" || child.props.role === "tab" ? undefined : selected, |
| 40 | "data-selected": selected ? "true" : "false", |
| 41 | } as ButtonHTMLAttributes<HTMLButtonElement>); |
| 42 | })} |
| 43 | </div> |
| 44 | ); |
| 45 | } |
| 46 |