import React, { useRef } from 'react'; import { Tooltip } from '@/components/ui'; import { optionKey, optionValue } from './constraints'; import './creation-params.css'; /** * 通用单选按钮组(radiogroup 语义 + roving tabindex),供 RatioPicker / * ChipGroup / DurationSegmented 复用。 * * - 方向键在可用选项间移动并选中,Home / End 跳到首尾; * - 被禁用的选项用 aria-disabled(而非 disabled),以便悬停 / 聚焦时仍能看到原因 Tooltip; * - 整组禁用(disabledReason)时所有选项不可选,原因挂在组外层 Tooltip 上。 */ const OptionGroup = ({ options = [], value, onChange, ariaLabel, optionDisabledReasons = {}, disabledReason = '', renderOption, getOptionAriaLabel, variant = 'chips', className = '', }) => { const refs = useRef([]); const groupDisabled = Boolean(disabledReason); const selectedKey = value === undefined || value === null ? null : optionKey(value); const isDisabled = (opt) => groupDisabled || Boolean(optionDisabledReasons[optionKey(opt)]); const selectedIndex = options.findIndex((o) => optionKey(o) === selectedKey); const firstEnabled = options.findIndex((o) => !isDisabled(o)); const tabStop = selectedIndex >= 0 ? selectedIndex : firstEnabled >= 0 ? firstEnabled : 0; const select = (opt) => { if (isDisabled(opt)) return; if (optionKey(opt) === selectedKey) return; onChange && onChange(optionValue(opt)); }; const moveTo = (from, step) => { const n = options.length; for (let i = 1; i <= n; i += 1) { const idx = (from + step * i + n * n) % n; if (!isDisabled(options[idx])) { refs.current[idx] && refs.current[idx].focus(); select(options[idx]); return; } } }; const onKeyDown = (e, idx) => { switch (e.key) { case 'ArrowRight': case 'ArrowDown': e.preventDefault(); moveTo(idx, 1); break; case 'ArrowLeft': case 'ArrowUp': e.preventDefault(); moveTo(idx, -1); break; case 'Home': e.preventDefault(); moveTo(-1, 1); break; case 'End': e.preventDefault(); moveTo(options.length, -1); break; default: } }; const group = (
{options.map((opt, idx) => { const key = optionKey(opt); const selected = key === selectedKey; const reason = groupDisabled ? '' : optionDisabledReasons[key] || ''; const disabled = isDisabled(opt); const btn = ( ); return reason ? ( {btn} ) : ( btn ); })}
); return groupDisabled ? ( {group} ) : ( group ); }; export default OptionGroup;