import React from "react"; /** * Radio group — role="radiogroup" with roving tabindex. * Arrow keys move and select (WAI-ARIA radio pattern); only the checked * radio is in the tab order. * R03: 선택 항목이 disabled면 첫 사용 가능 항목을 진입점으로. R08: 숨긴 native input에도 disabled 전달. */ export function RadioGroup({ name, options = [], value, defaultValue, onChange, label, description, orientation = "vertical", disabled = false, style }) { const [internal, setInternal] = React.useState(defaultValue); const current = value !== undefined ? value : internal; const refs = React.useRef([]); const labelId = React.useId(); const norm = options.map((o) => (typeof o === "string" ? { value: o, label: o } : o)); const pickable = disabled ? [] : norm.map((o, i) => (o.disabled ? -1 : i)).filter((i) => i >= 0); const pick = (v) => { if (disabled) return; if (value === undefined) setInternal(v); if (onChange) onChange(v); }; const move = (from, dir) => { if (!pickable.length) return; const at = pickable.indexOf(from); const next = at === -1 ? pickable[0] : pickable[(at + dir + pickable.length) % pickable.length]; pick(norm[next].value); refs.current[next]?.focus(); }; const onKeyDown = (e, i) => { if (["ArrowDown", "ArrowRight"].includes(e.key)) { e.preventDefault(); move(i, 1); } else if (["ArrowUp", "ArrowLeft"].includes(e.key)) { e.preventDefault(); move(i, -1); } else if (e.key === " ") { e.preventDefault(); pick(norm[i].value); } }; const checkedIndex = norm.findIndex((o) => o.value === current); // 키보드 진입점: 선택 항목이 사용 가능하면 그 항목, 아니면 첫 사용 가능 항목 const entryIndex = pickable.includes(checkedIndex) ? checkedIndex : pickable[0] ?? -1; return (
{label &&
{label}
} {description &&
{description}
}
{norm.map((o, i) => { const checked = o.value === current; const off = disabled || o.disabled; return ( (refs.current[i] = el)} role="radio" data-ds-focus aria-checked={checked} aria-disabled={off || undefined} tabIndex={i === entryIndex ? 0 : -1} onClick={() => !off && pick(o.value)} onKeyDown={(e) => !off && onKeyDown(e, i)} style={{ display: "inline-flex", alignItems: "flex-start", gap: 8, borderRadius: 6, cursor: off ? "not-allowed" : "pointer", userSelect: "none", fontSize: 14, color: off ? "hsl(var(--disabled-foreground))" : "hsl(var(--foreground))", }} > ); })}
); }