# GroupRadioBox 组单选框组件

一个灵活的组单选框组件，允许用户从预定义的选项列表中选择单个选项。具备全面的状态管理、自定义样式变体以及焦点/失焦事件处理，可无缝集成到表单中。

## 安装

```bash
npm install @ticatec/uniface-element
```

## 导入

```typescript
import GroupRadioBox from "@ticatec/uniface-element/GroupRadioBox";
import { DisplayMode } from "@ticatec/uniface-element";
import type { OnChangeHandler } from "@ticatec/uniface-element";
```

## 基本用法

```svelte
<script>
  import GroupRadioBox from "@ticatec/uniface-element/GroupRadioBox";
  
  const options = [
    { code: "sm", text: "小号" },
    { code: "md", text: "中号" },
    { code: "lg", text: "大号" },
    { code: "xl", text: "特大号" }
  ];
  
  let selectedSize = "md";
  
  function handleChange(value) {
    console.log('选择的尺码:', value);
  }
</script>

<GroupRadioBox 
  {options} 
  bind:value={selectedSize}
  onchange={handleChange}
/>
```

## 属性

| 属性 | 类型 | 默认值 | 描述 |
|------|------|---------|-------------|
| `value` | `any` | 必需 | 选中的值 |
| `options` | `Array<any>` | 必需 | 选项对象数组 |
| `keyField` | `string` | `"code"` | 选项键/值的字段名称 |
| `textField` | `string` | `"text"` | 选项显示文本的字段名称 |
| `disabled` | `boolean` | `false` | 组件是否禁用 |
| `readonly` | `boolean` | `false` | 组件是否只读 |
| `displayMode` | `DisplayMode` | `DisplayMode.Edit` | 显示模式（编辑或查看） |
| `variant` | `"" \| "plain" \| "outlined" \| "filled"` | `""` | 视觉变体 |
| `compact` | `boolean` | `false` | 是否使用紧凑间距 |
| `disabledOptions` | `Array<string>` | `[]` | 要禁用的选项键数组 |
| `style` | `string` | `""` | 附加 CSS 样式 |
| `item$style` | `string` | `""` | 单个单选框项目的 CSS 样式 |
| `onchange` | `OnChangeHandler<any>` | `null` | 更改事件处理程序 |
| `onfocus` | `(() => void) \| null` | `null` | 焦点事件处理程序 |
| `onblur` | `(() => void) \| null` | `null` | 失焦事件处理程序 |

## 方法

| 方法 | 描述 |
|--------|-------------|
| `setFocus()` | 以编程方式聚焦第一个启用的单选框 |

## 示例

### 基本选择

```svelte
<script>
  import GroupRadioBox from "@ticatec/uniface-element/GroupRadioBox";
  import FormField from "@ticatec/uniface-element/FormField";
  
  const priorities = [
    { code: "low", text: "低优先级" },
    { code: "medium", text: "中优先级" },
    { code: "high", text: "高优先级" },
    { code: "urgent", text: "紧急" }
  ];
  
  let taskPriority = "medium";
  
  function handlePriorityChange(value) {
    console.log('优先级更改为:', value);
    
    // 处理优先级特定逻辑
    if (value === 'urgent') {
      console.log('紧急任务 - 通知团队负责人');
    }
  }
</script>

<div class="demo-section">
  <FormField label="任务优先级">
    <GroupRadioBox 
      options={priorities}
      bind:value={taskPriority}
      onchange={handlePriorityChange}
      onfocus={() => console.log('优先级字段获得焦点')}
      onblur={() => console.log('优先级字段失去焦点')}
    />
  </FormField>
  
  <div class="result">
    <p><strong>选中的优先级:</strong> {taskPriority}</p>
    <p><strong>显示文本:</strong> {priorities.find(p => p.code === taskPriority)?.text ?? '无'}</p>
  </div>
</div>

<style>
  .demo-section {
    margin: 20px;
    padding: 20px;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
  }
  
  .result {
    margin-top: 16px;
    padding: 12px;
    background: #f8fafc;
    border-radius: 6px;
  }
</style>
```

### 不同视觉变体

```svelte
<script>
  import GroupRadioBox from "@ticatec/uniface-element/GroupRadioBox";
  import FormField from "@ticatec/uniface-element/FormField";
  
  const themes = [
    { code: "light", text: "浅色主题" },
    { code: "dark", text: "深色主题" },
    { code: "auto", text: "自动（系统）" }
  ];
  
  let selectedTheme = "auto";
</script>

<div class="variants-demo">
  <div class="variant-section">
    <h3>默认变体</h3>
    <FormField label="主题偏好">
      <GroupRadioBox options={themes} bind:value={selectedTheme} />
    </FormField>
  </div>
  
  <div class="variant-section">
    <h3>轮廓变体</h3>
    <FormField label="主题偏好">
      <GroupRadioBox 
        options={themes} 
        variant="outlined"
        bind:value={selectedTheme} 
      />
    </FormField>
  </div>
  
  <div class="variant-section">
    <h3>填充变体</h3>
    <FormField label="主题偏好">
      <GroupRadioBox 
        options={themes} 
        variant="filled"
        bind:value={selectedTheme} 
      />
    </FormField>
  </div>
  
  <div class="variant-section">
    <h3>紧凑变体</h3>
    <FormField label="主题偏好">
      <GroupRadioBox 
        options={themes} 
        compact={true}
        bind:value={selectedTheme} 
      />
    </FormField>
  </div>
</div>

<style>
  .variants-demo {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin: 20px;
  }
  
  .variant-section {
    padding: 16px;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
  }
</style>
```

### 条件选项和动态行为

```svelte
<script>
  import GroupRadioBox from "@ticatec/uniface-element/GroupRadioBox";
  import FormField from "@ticatec/uniface-element/FormField";
  
  const paymentMethods = [
    { code: "card", text: "信用卡" },
    { code: "alipay", text: "支付宝" },
    { code: "weixin", text: "微信支付" },
    { code: "crypto", text: "加密货币" },
    { code: "cash", text: "货到付款" }
  ];
  
  let selectedPayment = "card";
  let disabledOptions = [];
  let orderTotal = 1500.00;
  let region = "domestic";
  
  // 根据订单条件更新可用支付方式
  $: {
    disabledOptions = [];
    
    // 小额订单禁用加密货币
    if (orderTotal < 1000) {
      disabledOptions.push("crypto");
    }
    
    // 国际订单禁用货到付款
    if (region === "international") {
      disabledOptions.push("cash");
    }
    
    // 如果当前选择被禁用，自动选择可用选项
    if (disabledOptions.includes(selectedPayment)) {
      const availableOptions = paymentMethods.filter(method => 
        !disabledOptions.includes(method.code)
      );
      if (availableOptions.length > 0) {
        selectedPayment = availableOptions[0].code;
      }
    }
  }
  
  function handlePaymentChange(value) {
    console.log('支付方式更改为:', value);
    
    // 处理支付特定逻辑
    if (value === 'crypto') {
      console.log('选择了加密货币支付 - 显示钱包选项');
    } else if (value === 'weixin') {
      console.log('选择了微信支付 - 显示二维码');
    }
  }
</script>

<div class="conditional-demo">
  <div class="controls">
    <FormField label="订单总计">
      <input 
        type="number" 
        bind:value={orderTotal} 
        min="100" 
        step="100"
        class="number-input"
      />
    </FormField>
    
    <FormField label="地区">
      <select bind:value={region} class="select-input">
        <option value="domestic">国内</option>
        <option value="international">国际</option>
      </select>
    </FormField>
  </div>
  
  <FormField label="支付方式">
    <GroupRadioBox 
      options={paymentMethods}
      bind:value={selectedPayment}
      {disabledOptions}
      onchange={handlePaymentChange}
      variant="outlined"
    />
  </FormField>
  
  <div class="info-panel">
    <p><strong>已选择:</strong> {selectedPayment}</p>
    <p><strong>订单总计:</strong> ¥{orderTotal}</p>
    <p><strong>地区:</strong> {region === 'domestic' ? '国内' : '国际'}</p>
    <p><strong>禁用的支付方式:</strong> {disabledOptions.join(', ') || '无'}</p>
    
    {#if disabledOptions.includes('crypto')}
      <p class="info-note">💡 加密货币支付要求最低订单金额 ¥1000</p>
    {/if}
    
    {#if disabledOptions.includes('cash')}
      <p class="info-note">💡 国际订单不可使用货到付款</p>
    {/if}
  </div>
</div>

<style>
  .conditional-demo {
    margin: 20px;
    padding: 20px;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
  }
  
  .controls {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    margin-bottom: 20px;
  }
  
  .number-input, .select-input {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #d1d5db;
    border-radius: 6px;
  }
  
  .info-panel {
    margin-top: 16px;
    padding: 12px;
    background: #f8fafc;
    border-radius: 6px;
  }
  
  .info-note {
    color: #6b7280;
    font-style: italic;
    margin-top: 8px;
  }
</style>
```

### 自定义字段配置

```svelte
<script>
  import GroupRadioBox from "@ticatec/uniface-element/GroupRadioBox";
  import FormField from "@ticatec/uniface-element/FormField";
  
  // 使用自定义字段名称
  const departments = [
    { id: "eng", name: "工程部", active: true },
    { id: "sales", name: "销售与市场部", active: true },
    { id: "hr", name: "人力资源部", active: false },
    { id: "finance", name: "财务与会计部", active: true }
  ];
  
  let selectedDepartment = "eng";
  
  function handleDepartmentChange(value) {
    const selected = departments.find(dept => dept.id === value);
    console.log('部门更改为:', selected);
  }
</script>

<div class="custom-demo">
  <FormField label="选择部门">
    <GroupRadioBox 
      options={departments}
      keyField="id"
      textField="name"
      bind:value={selectedDepartment}
      onchange={handleDepartmentChange}
      variant="filled"
      style="padding: 16px; background: linear-gradient(145deg, #f8fafc, #e2e8f0);"
      item$style="margin: 8px 0; padding: 6px 12px; border-radius: 8px; background: white;"
    />
  </FormField>
  
  <div class="department-info">
    {#each departments as dept}
      {#if dept.id === selectedDepartment}
        <div class="selected-dept">
          <h4>{dept.name}</h4>
          <p>状态: {dept.active ? '✅ 活跃' : '❌ 非活跃'}</p>
          <p>部门ID: {dept.id}</p>
        </div>
      {/if}
    {/each}
  </div>
</div>

<style>
  .custom-demo {
    margin: 20px;
    padding: 20px;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
  }
  
  .department-info {
    margin-top: 16px;
  }
  
  .selected-dept {
    padding: 16px;
    background: #dbeafe;
    border-radius: 8px;
    border-left: 4px solid #3b82f6;
  }
</style>
```

### 只读和显示模式

```svelte
<script>
  import GroupRadioBox from "@ticatec/uniface-element/GroupRadioBox";
  import FormField from "@ticatec/uniface-element/FormField";
  import { DisplayMode } from "@ticatec/uniface-element";
  
  const subscriptionPlans = [
    { code: "basic", text: "基础计划" },
    { code: "premium", text: "高级计划" },
    { code: "enterprise", text: "企业计划" }
  ];
  
  let currentPlan = "premium";  // 预选计划
</script>

<div class="readonly-demo">
  <div class="mode-section">
    <h3>可编辑模式</h3>
    <FormField label="更改订阅计划">
      <GroupRadioBox 
        options={subscriptionPlans}
        bind:value={currentPlan}
      />
    </FormField>
  </div>
  
  <div class="mode-section">
    <h3>只读模式</h3>
    <FormField label="当前计划（只读）">
      <GroupRadioBox 
        options={subscriptionPlans}
        value={currentPlan}
        readonly={true}
      />
    </FormField>
  </div>
  
  <div class="mode-section">
    <h3>禁用模式</h3>
    <FormField label="计划选择（禁用）">
      <GroupRadioBox 
        options={subscriptionPlans}
        value={currentPlan}
        disabled={true}
      />
    </FormField>
  </div>
  
  <div class="mode-section">
    <h3>仅显示模式</h3>
    <FormField label="活跃计划">
      <GroupRadioBox 
        options={subscriptionPlans}
        value={currentPlan}
        displayMode={DisplayMode.View}
      />
    </FormField>
  </div>
</div>

<style>
  .readonly-demo {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin: 20px;
  }
  
  .mode-section {
    padding: 16px;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
  }
</style>
```

### 表单集成与验证

```svelte
<script>
  import GroupRadioBox from "@ticatec/uniface-element/GroupRadioBox";
  import FormField from "@ticatec/uniface-element/FormField";
  
  const shippingOptions = [
    { code: "standard", text: "标准配送（5-7天）" },
    { code: "express", text: "快递（2-3天）" },
    { code: "overnight", text: "次日达" }
  ];
  
  const countries = [
    { code: "cn", text: "中国" },
    { code: "us", text: "美国" },
    { code: "uk", text: "英国" },
    { code: "au", text: "澳大利亚" }
  ];
  
  let formData = {
    name: '',
    country: '',
    shipping: ''
  };
  
  let errors = {};
  let groupRadioBoxRef;
  
  function validateForm() {
    errors = {};
    
    if (!formData.name.trim()) {
      errors.name = '姓名是必填项';
    }
    
    if (!formData.country) {
      errors.country = '请选择一个国家';
    }
    
    if (!formData.shipping) {
      errors.shipping = '请选择配送方式';
    }
    
    return Object.keys(errors).length === 0;
  }
  
  function handleSubmit() {
    if (validateForm()) {
      console.log('表单提交:', formData);
      alert('订单提交成功！');
    } else {
      console.log('验证错误:', errors);
      // 聚焦第一个错误字段
      if (errors.shipping) {
        groupRadioBoxRef.setFocus();
      }
    }
  }
  
  function handleShippingChange(value) {
    formData.shipping = value;
    // 用户选择时清除错误
    if (errors.shipping && value) {
      delete errors.shipping;
      errors = { ...errors };
    }
  }
  
  function handleCountryChange(value) {
    formData.country = value;
    // 更改国家时清除配送选择（可能有不同的选项）
    if (formData.shipping) {
      formData.shipping = '';
    }
    // 清除错误
    if (errors.country && value) {
      delete errors.country;
      errors = { ...errors };
    }
  }
</script>

<div class="form-demo">
  <form on:submit|preventDefault={handleSubmit}>
    <FormField label="全名" error={errors.name}>
      <input 
        type="text" 
        bind:value={formData.name}
        class="form-input"
        class:error={errors.name}
        placeholder="输入您的全名"
      />
    </FormField>
    
    <FormField label="国家" error={errors.country}>
      <GroupRadioBox 
        options={countries}
        bind:value={formData.country}
        onchange={handleCountryChange}
        variant="outlined"
      />
    </FormField>
    
    <FormField label="配送方式" error={errors.shipping}>
      <GroupRadioBox 
        bind:this={groupRadioBoxRef}
        options={shippingOptions}
        bind:value={formData.shipping}
        onchange={handleShippingChange}
        variant="outlined"
      />
      <p class="field-hint">配送费用将根据您的选择计算</p>
    </FormField>
    
    <div class="form-actions">
      <button type="submit" class="submit-btn">提交订单</button>
      <button type="button" on:click={() => console.log(formData)} class="preview-btn">
        预览订单
      </button>
    </div>
    
    {#if formData.country && formData.shipping}
      <div class="order-summary">
        <h4>订单摘要</h4>
        <p>配送至: {countries.find(c => c.code === formData.country)?.text}</p>
        <p>配送方式: {shippingOptions.find(s => s.code === formData.shipping)?.text}</p>
      </div>
    {/if}
  </form>
</div>

<style>
  .form-demo {
    max-width: 500px;
    margin: 20px;
    padding: 24px;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
  }
  
  .form-input {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #d1d5db;
    border-radius: 6px;
  }
  
  .form-input.error {
    border-color: #dc2626;
  }
  
  .field-hint {
    margin-top: 4px;
    font-size: 0.875rem;
    color: #6b7280;
  }
  
  .form-actions {
    display: flex;
    gap: 12px;
    margin-top: 20px;
  }
  
  .submit-btn, .preview-btn {
    padding: 10px 20px;
    border-radius: 6px;
    border: none;
    cursor: pointer;
  }
  
  .submit-btn {
    background: #3b82f6;
    color: white;
  }
  
  .preview-btn {
    background: #f3f4f6;
    color: #374151;
    border: 1px solid #d1d5db;
  }
  
  .order-summary {
    margin-top: 20px;
    padding: 16px;
    background: #f0f9ff;
    border-radius: 8px;
    border-left: 4px solid #3b82f6;
  }
</style>
```

### 调查和评分实现

```svelte
<script>
  import GroupRadioBox from "@ticatec/uniface-element/GroupRadioBox";
  import FormField from "@ticatec/uniface-element/FormField";
  
  const satisfactionLevels = [
    { code: "1", text: "非常不满意" },
    { code: "2", text: "不满意" },
    { code: "3", text: "中立" },
    { code: "4", text: "满意" },
    { code: "5", text: "非常满意" }
  ];
  
  const frequencies = [
    { code: "daily", text: "每天" },
    { code: "weekly", text: "每周" },
    { code: "monthly", text: "每月" },
    { code: "rarely", text: "很少" },
    { code: "never", text: "从不" }
  ];
  
  let surveyData = {
    satisfaction: '',
    frequency: '',
    recommendation: ''
  };
  
  let isCompleted = false;
  
  $: isCompleted = surveyData.satisfaction && surveyData.frequency && surveyData.recommendation;
  
  function handleSurveySubmit() {
    if (isCompleted) {
      console.log('调查提交:', surveyData);
      alert('感谢您的反馈！');
    }
  }
  
  function getSatisfactionColor(level) {
    const colors = {
      '1': '#dc2626', '2': '#ea580c', '3': '#d97706',
      '4': '#65a30d', '5': '#16a34a'
    };
    return colors[level] || '#6b7280';
  }
</script>

<div class="survey-demo">
  <h2>客户满意度调查</h2>
  
  <div class="survey-section">
    <FormField label="您对我们的服务满意度如何？">
      <GroupRadioBox 
        options={satisfactionLevels}
        bind:value={surveyData.satisfaction}
        variant="outlined"
        item$style="padding: 12px; margin: 4px 0; border-radius: 8px;"
      />
    </FormField>
    
    {#if surveyData.satisfaction}
      <div class="satisfaction-feedback" style="color: {getSatisfactionColor(surveyData.satisfaction)}">
        <strong>您选择了: {satisfactionLevels.find(s => s.code === surveyData.satisfaction)?.text}</strong>
      </div>
    {/if}
  </div>
  
  <div class="survey-section">
    <FormField label="您使用我们服务的频率？">
      <GroupRadioBox 
        options={frequencies}
        bind:value={surveyData.frequency}
        variant="filled"
        compact={true}
      />
    </FormField>
  </div>
  
  <div class="survey-section">
    <FormField label="您会向他人推荐我们吗？">
      <GroupRadioBox 
        options={[
          { code: "yes", text: "是的，绝对会" },
          { code: "maybe", text: "可能会" },
          { code: "no", text: "不会" }
        ]}
        bind:value={surveyData.recommendation}
        variant="outlined"
      />
    </FormField>
  </div>
  
  <div class="survey-progress">
    <div class="progress-bar">
      <div 
        class="progress-fill" 
        style="width: {(Object.values(surveyData).filter(v => v).length / 3) * 100}%"
      ></div>
    </div>
    <p>进度: {Object.values(surveyData).filter(v => v).length}/3 问题已完成</p>
  </div>
  
  <button 
    on:click={handleSurveySubmit}
    disabled={!isCompleted}
    class="submit-survey-btn"
    class:disabled={!isCompleted}
  >
    提交调查
  </button>
</div>

<style>
  .survey-demo {
    max-width: 600px;
    margin: 20px;
    padding: 24px;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
  }
  
  .survey-section {
    margin-bottom: 24px;
  }
  
  .satisfaction-feedback {
    margin-top: 8px;
    padding: 8px 12px;
    background: #f0f9ff;
    border-radius: 6px;
    font-weight: 500;
  }
  
  .survey-progress {
    margin: 24px 0;
  }
  
  .progress-bar {
    height: 8px;
    background: #e5e7eb;
    border-radius: 4px;
    overflow: hidden;
    margin-bottom: 8px;
  }
  
  .progress-fill {
    height: 100%;
    background: #3b82f6;
    transition: width 0.3s ease;
  }
  
  .submit-survey-btn {
    width: 100%;
    padding: 12px 24px;
    background: #3b82f6;
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.2s;
  }
  
  .submit-survey-btn:hover:not(.disabled) {
    background: #2563eb;
  }
  
  .submit-survey-btn.disabled {
    background: #d1d5db;
    color: #9ca3af;
    cursor: not-allowed;
  }
</style>
```

## 样式

GroupRadioBox 组件可通过 CSS 自定义属性进行样式化：

```css
.uniface-group-box {
  --radio-spacing: 8px;
  --radio-padding: 4px 8px;
  --border-color: #e2e8f0;
  --background-color: #ffffff;
  --hover-background: #f9fafb;
  --selected-color: #3b82f6;
}

/* 变体特定样式 */
.uniface-group-box.outlined {
  border: 1px solid var(--border-color);
  border-radius: 6px;
  padding: 12px;
}

.uniface-group-box.filled {
  background-color: #f8fafc;
  border-radius: 6px;
  padding: 12px;
}

.uniface-group-box.compact {
  --radio-spacing: 4px;
  --radio-padding: 2px 4px;
}
```

## 可访问性

GroupRadioBox 组件包括以下可访问性功能：

- 单选框之间的键盘导航
- 使用 `setFocus()` 方法进行焦点管理
- ARIA 标签和单选框组语义
- 选择变化的屏幕阅读器提示
- 适当的 Tab 键顺序管理

## 最佳实践

1. **选项管理**：保持选项数组的稳定性以避免不必要的重新渲染
2. **默认选择**：始终提供合理的默认值以提升用户体验
3. **验证**：为必选项目实现适当的验证
4. **用户反馈**：为选择变化提供清晰的视觉反馈
5. **可访问性**：始终提供有意义的标签和组描述
6. **状态管理**：适当地处理焦点/失焦事件以进行表单验证

## 许可证

MIT