/** * ButtonGroup - buttons joined edge-to-edge into one segmented control. * * Two modes: * - Wrapper: pass Button children; the group flattens their touching corners * (only the outer edges stay rounded) and collapses the doubled borders with * a -1px overlap. Good for a toolbar of related actions. * - Segmented: pass `items` + `value` + `onChange` for a single-choice control * (radio-like); the active segment takes the accent, the rest are neutral. * role="radiogroup" / aria-checked so AT reads the selection. * * Colours from the theme, radii from tokens; both themes. */ import { Children, cloneElement, isValidElement } from "react"; import type { CSSProperties, ReactElement, ReactNode } from "react"; import { FS, FW, R, SP } from "@rukin/tokens"; import { useTheme } from "./theme"; export type SegmentItem = { value: string; label: ReactNode; disabled?: boolean }; export type ButtonGroupProps = { /** Wrapper mode: Button children to fuse. */ children?: ReactNode; /** Segmented mode: single-choice options. */ items?: SegmentItem[]; value?: string; onChange?: (value: string) => void; style?: CSSProperties; }; function edgeRadius(i: number, n: number): CSSProperties { const left = i === 0 ? R.md : 0; const right = i === n - 1 ? R.md : 0; return { borderTopLeftRadius: left, borderBottomLeftRadius: left, borderTopRightRadius: right, borderBottomRightRadius: right, }; } export function ButtonGroup({ children, items, value, onChange, style }: ButtonGroupProps) { const { C } = useTheme(); const wrap: CSSProperties = { display: "inline-flex", ...style, }; // Segmented single-choice control. if (items && items.length > 0) { return (
{items.map((it, i) => { const on = it.value === value; return ( ); })}
); } // Wrapper mode: fuse arbitrary Button children. const arr = Children.toArray(children).filter(isValidElement) as ReactElement<{ style?: CSSProperties }>[]; return (
{arr.map((child, i) => cloneElement(child, { key: child.key ?? i, style: { ...edgeRadius(i, arr.length), marginLeft: i === 0 ? 0 : -1, ...(child.props.style ?? {}), }, }), )}
); }