feat: add Checkbox and Radio field families

This commit is contained in:
maoyingjie
2026-10-22 09:15:27 +08:00
parent a4fb3c550a
commit bcadbeaf8c
75 changed files with 5293 additions and 22 deletions
+9
View File
@@ -310,3 +310,12 @@ Vaul Vue 官方已说明停止维护并推荐 Reka Drawer;新项目不采用 V
- 集成人维护上述内核、Fieldset/Legend、SearchField、Form 与 Switch。普通迁移任务遇到缺口先交失败场景,不自行改共享协议。
- 首个直接 Legend 与嵌套禁用必须按原生语义回归,不能简单给所有后代设置 disabled。SearchField 输入 Enter 的专属 submit 与原生表单提交不得重复,调用者取消、IME、Escape 空值与受控拒绝都有既有测试。
- 下一阶段 Checkbox/Radio 协议见 docs/decisions/selection-field-foundation.md;当前 Reka 的 CheckboxGroup 隐藏值序列化/禁用/reset 与目标有实际差异,不直接传 name 就宣布表单兼容。
## FORM-03 选择字段约束(2026-10-22)
- 后续先读 [Checkbox/Radio 协议](docs/decisions/selection-field-foundation.md)。这两个家族已采用原生 label/input + choice 共享内核,原因是已证实的 Reka 禁用提交/reset 缺口与固定上游本身的 label/input 结构;不再套一份 Reka 隐藏值层。
- choice 的值、成员注册/焦点、reset、校验及共享字段协议由集成人维护。模型类型分别是 Checkbox boolean、CheckboxGroup string[]、RadioGroup string | undefined,不能为了复用把公共类型扩大成联合。
- defaultChecked/defaultSelected、checked/isSelected 的优先级必须区分“未传”与 false/undefined。受控属性动态增删也要恢复真实 DOM;不能只让 computed 读取非响应式 vnode key 并缓存旧归属。
- 组 required 不等于每项必选;组无名约束代理不得进入 FormData/Tab。测试实际同名多值、禁用省略、取消 reset、受控拒绝、空组聚焦与新的服务端错误响应。成员 Description/FieldError 必须隔离,同时引用组说明;组 Label 不用 for 指向 div。
- CSS 状态属性需要与存在选择器对应,尤其 Radio 的 [data-selected] 未选中时必须移除;默认 RadioIndicator 真实 DOM 要满足 :empty,不能留下插槽注释/空文本导致默认圆点消失。定制 Content 的 data-selected/indeterminate/focus-visible 标记也需验证。
- Tailwind 嵌套伪元素下 motion-reduce 如生成无效 :not(:is()),采用等价原生 media,保留动效数值和减少动画语义,并记录源样式适配差异。构建 CSS 警告不能忽略。
+17 -2
View File
@@ -2,7 +2,11 @@
import { IconCode, IconCopy } from "@tabler/icons-vue";
import { computed, ref, watch, onBeforeUnmount, useId } from "vue";
import { highlights } from "virtual:docs-data";
const props = defineProps<{ name: string }>();
const props = defineProps<{
name: string;
align?: "center" | "start" | "end";
isBgSolid?: boolean;
}>();
const demos = import.meta.glob("../../demos/*.vue", {
eager: true,
import: "default",
@@ -53,7 +57,18 @@ onBeforeUnmount(() => clearTimeout(timer));
</script>
<template>
<div class="component-preview-container" :data-name="name">
<div class="preview not-prose">
<div
class="preview not-prose"
:style="{
alignItems:
align === 'start'
? 'flex-start'
: align === 'end'
? 'flex-end'
: undefined,
background: isBgSolid ? 'var(--background)' : undefined,
}"
>
<div class="demo-row">
<component :is="component" v-if="component" />
<p v-else role="alert">示例不存在:{{ name }}</p>
+3
View File
@@ -51,6 +51,8 @@ const groups = [
{ title: "Badge 徽章", url: "/components/badge" },
{ title: "Button 按钮", url: "/components/button" },
{ title: "Card 卡片", url: "/components/card" },
{ title: "Checkbox 复选框", url: "/components/checkbox" },
{ title: "CheckboxGroup 复选框组", url: "/components/checkbox-group" },
{ title: "Chip 标签", url: "/components/chip" },
{ title: "CloseButton 关闭按钮", url: "/components/close-button" },
{ title: "Description 描述", url: "/components/description" },
@@ -61,6 +63,7 @@ const groups = [
{ title: "Kbd 键盘按键", url: "/components/kbd" },
{ title: "Label 标签", url: "/components/label" },
{ title: "Link 链接", url: "/components/link" },
{ title: "RadioGroup 单选框组", url: "/components/radio-group" },
{ title: "SearchField 搜索框", url: "/components/search-field" },
{ title: "Separator 分隔符", url: "/components/separator" },
{ title: "Skeleton 骨架屏", url: "/components/skeleton" },
+4
View File
@@ -28,3 +28,7 @@ description: 已迁移组件及文档
- [Fieldset 字段组](./components/fieldset)
- [SearchField 搜索框](./components/search-field)
- [Checkbox 复选框](./components/checkbox)
- [CheckboxGroup 复选框组](./components/checkbox-group)
- [RadioGroup 单选框组](./components/radio-group)
+203
View File
@@ -0,0 +1,203 @@
---
title: CheckboxGroup 复选框组
description: 用于管理多个复选框选择的复选框组组件
icon: updated
component: checkbox-group
group: 组件
---
## 用法
```vue
<script setup lang="ts">
import {
Checkbox,
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Label,
Description,
FieldError,
CheckboxGroup,
} from "@heroui-vue/components";
</script>
```
<ComponentPreview
name="checkbox-group-basic"
/>
## 组件结构
```vue
<script setup lang="ts">
import {
Checkbox,
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Label,
Description,
FieldError,
CheckboxGroup,
} from "@heroui-vue/components";
</script>
<template>
<CheckboxGroup>
<Label>选择选项</Label>
<Checkbox value="option">
<CheckboxContent>
<CheckboxControl><CheckboxIndicator /></CheckboxControl>
<Label>选项</Label>
</CheckboxContent>
<Description />
</Checkbox>
<FieldError />
</CheckboxGroup>
</template>
```
## 示例
### 表面样式
在 [Surface](/components/surface) 组件内使用时,请使用 `variant="secondary"` 以应用适合 Surface 背景的低强调变体。
<ComponentPreview
name="checkbox-group-on-surface"
/>
### 禁用
<ComponentPreview
name="checkbox-group-disabled"
/>
### 半选状态
<ComponentPreview
name="checkbox-group-indeterminate"
/>
### 受控组件
<ComponentPreview
name="checkbox-group-controlled"
/>
### 表单校验
<ComponentPreview
name="checkbox-group-validation"
/>
### 功能扩展示例
<ComponentPreview
name="checkbox-group-features-and-addons"
/>
### 自定义指示器
<ComponentPreview
name="checkbox-group-with-custom-indicator"
/>
### 渲染函数
<ComponentPreview
name="checkbox-group-render-function"
/>
## 自定义样式
### Tailwind CSS
<ComponentPreview name="checkbox-group-custom-styles" />
### 全局 CSS
可使用 `@layer components` 指令自定义 CheckboxGroup 组件类。
[了解更多](https://tailwindcss.com/docs/adding-custom-styles#adding-component-classes)。
```css
@layer components {
.hv-checkbox-group {
@apply flex flex-col gap-2;
}
}
```
## 样式参考
HeroUI 遵循 [BEM](https://getbem.com/) 方法论,确保组件变体与状态可复用且易于自定义。
### CSS 类
CheckboxGroup 组件使用以下 CSS 类([查看源码样式](https://github.com/heroui-inc/heroui/blob/v3/packages/styles/components/checkbox-group.css)):
#### 基础类
- `.hv-checkbox-group` - 复选框组根容器
## API 参考
本库采用原生 label/input 承载选择与提交,复用共享字段、Form、Fieldset 禁用和错误协议。原生输入是唯一的提交值来源;组内没有 Reka 的重复隐藏值或带索引字段名。组校验另有无 name、不可 Tab 聚焦的约束代理,不产生 FormData 条目。
### CheckboxGroup
| 属性 | 类型 | 默认值 | 描述 |
| -------------------------- | ---------------------------------------------------------------------- | ---------------------- | -------------------------------------- |
| `modelValue` | `string[]` | 非受控 | 当前值,使用 v-model |
| `defaultValue` | `string[]` | `[]` | 非受控初始值副本 |
| `name` / `form` / `id` | `string` | - / - / 自动 | 统一原生提交键、表单归属及组 ID |
| `variant` | `'primary' \| 'secondary'` | `'primary'` | 组视觉样式;Checkbox 成员可显式覆盖 |
| `isDisabled` / `disabled` | `boolean` | `false` | 合并 Fieldset 禁用,后代不能解除 |
| `isReadOnly` | `boolean` | `false` | 阻止成员点击、空格和方向键修改 |
| `isRequired` / `isInvalid` | `boolean` | `false` | 要求至少一项可用选择 / 错误展示 |
| `validate` | `(value: string[]) => string \| string[] \| true \| null \| undefined` | - | 同步组校验 |
| `validationBehavior` | `'native' \| 'aria'` | 继承 Form,否则 native | 原生提交拦截或仅错误语义 |
| `class` / `style` | Vue class/style 绑定 | - | 合并根样式,接受字符串/数组/对象 class |
| 默认插槽 | 作用域插槽 | - | 标签、说明、成员、错误 |
### 事件与暴露
| 接口 | 行为 |
| ------------------------------ | ---------------------------------------------------------------------- |
| `update:modelValue` / `change` | 发出新的数组或标量;不修改传入数组;父级拒绝后恢复所有原生 checked |
| `focus()` / `element` | 聚焦选中可用成员或首个可用成员;空组聚焦组根。element 是组 HTMLElement |
CheckboxGroup 按原生约定提交同名重复条目,通过 FormData.getAll(name) 获取;RadioGroup 只提交一个选中可用值。未指定 name 不产生提交值。每个成员 value 必须唯一;重复或动态改成重复值会抛出明确错误。不为移除的选择自动选择别的成员;模型保留调用者的值,FormData 只包含实际存在的可用成员。
required 检查整个组,不能让每个 Checkbox 都变成必选;native 无效提交聚焦第一个可用成员,空组聚焦根。只读保留提交值并跳过必填/自定义约束。reset 尊重 preventDefault,受控值不覆盖,非受控恢复初始副本。动态 name/form 会更新提交和 reset 归属。
Label 在组中渲染 span 并注册 aria-labelledby;不要手写 for 指向组 div。每个成员独立隔离 Description/FieldError,同时合并组描述和当前组错误。后端错误使用 Form.validationErrors 按 name 映射,编辑后忽略当前响应,新对象可恢复错误。暂不提供异步 validate 或完整 validationDetails。
### CheckboxContent / Control / Indicator
| 部件 | 根与插槽 | 属性落点 |
| --------- | ------------------------------------------ | ------------------------------------------ |
| Content | 原生 label,包含实际 input;默认作用域插槽 | class/style/原生 label 属性及事件 |
| Control | span,默认插槽 | class/style/DOM 属性与事件 |
| Indicator | span,默认作用域插槽 | 装饰 aria-hidden;自定义内容替换基线指示器 |
具名导出使用 CheckboxContent、CheckboxControl、CheckboxIndicator;不使用 React 对象式子部件。class 均支持字符串、数组和对象。默认图形精确来自基线,文档自定义图标使用 Tabler。Content 输出 selected/indeterminate/hovered/pressed/focus-visible 状态标记供定制样式使用。
### 作用域插槽状态
| 参数 | 类型 | 说明 |
| ---------------------------------------------------------- | --------- | ------------------------------ |
| `isSelected` / `isIndeterminate` | `boolean` | 选中 / 半选(半选仅 Checkbox) |
| `isDisabled` / `isReadOnly` / `isRequired` / `isInvalid` | `boolean` | 当前状态 |
| `isHovered` / `isPressed` / `isFocused` / `isFocusVisible` | `boolean` | 单成员交互状态 |
组作用域提供 value、validationErrors、isDisabled/isReadOnly/isRequired/isInvalid,以及 state.value/state.setValue;单成员另提供 state.isSelected/state.setSelected/state.toggle。不把组值和单成员状态混用。
### 框架适配与边界
render 自定义根类型未支持;基线 div+data-custom 示例以 Vue 根属性透传保留效果。SSR 预规划直接/原生/Fragment 包裹的标签、说明、错误与直接成员;本库 Content 内的说明也支持。任意用户 Vue 包装组件无法静态展开,需要显式 aria-labelledby/aria-describedby 和 ID 保证首屏关联。没有宣称完整读屏、触屏、Nuxt 或逐像素验收。
## 相关组件
[Checkbox](./checkbox) · [CheckboxGroup](./checkbox-group) · [RadioGroup](./radio-group) · [Fieldset](./fieldset)
+269
View File
@@ -0,0 +1,269 @@
---
title: Checkbox 复选框
description: 复选框允许用户从列表中选择多项,或标记单个项目为选中状态
icon: updated
component: checkbox
group: 组件
---
## 用法
```vue
<script setup lang="ts">
import {
Checkbox,
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Label,
Description,
FieldError,
} from "@heroui-vue/components";
</script>
```
<ComponentPreview
name="checkbox-basic"
/>
## 组件结构
```vue
<script setup lang="ts">
import {
Checkbox,
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Label,
Description,
FieldError,
} from "@heroui-vue/components";
</script>
<template>
<Checkbox>
<CheckboxContent>
<CheckboxControl><CheckboxIndicator /></CheckboxControl>
<Label>选项</Label>
</CheckboxContent>
<Description />
</Checkbox>
</template>
```
## 示例
### 变体
Checkbox 组件支持两种视觉变体:
- **`primary`**(默认)- 标准样式与默认背景,适用于大多数场景
- **`secondary`** - 低强调变体,适用于 Surface 组件内
<ComponentPreview name="checkbox-variants" />
### 全圆角
<ComponentPreview
name="checkbox-full-rounded"
/>
### 禁用
<ComponentPreview
name="checkbox-disabled"
/>
### 外部标签
<ComponentPreview
name="checkbox-external-label"
/>
### 带描述
<ComponentPreview
name="checkbox-with-description"
/>
### 默认选中
<ComponentPreview
name="checkbox-default-selected"
/>
### 无效状态
<ComponentPreview
name="checkbox-invalid"
/>
### 受控组件
<ComponentPreview
name="checkbox-controlled"
/>
### 半选状态
<ComponentPreview
name="checkbox-indeterminate"
/>
### 表单集成
<ComponentPreview
name="checkbox-form"
/>
### 渲染属性
<ComponentPreview
name="checkbox-render-props"
/>
### 渲染函数
<ComponentPreview
name="checkbox-render-function"
/>
### 自定义指示器
<ComponentPreview
name="checkbox-custom-indicator"
/>
## 自定义样式
### Tailwind CSS
<ComponentPreview name="checkbox-custom-styles" />
### 全局 CSS
可使用 `@layer components` 指令自定义 Checkbox 组件类。
[了解更多](https://tailwindcss.com/docs/adding-custom-styles#adding-component-classes)。
```css
@layer components {
.hv-checkbox {
@apply inline-flex gap-3 items-center;
}
.hv-checkbox__control {
@apply size-5 border-2 border-gray-400 rounded data-[selected=true]:bg-blue-500 data-[selected=true]:border-blue-500;
/* Animated background indicator */
&::before {
@apply bg-accent pointer-events-none absolute inset-0 z-0 origin-center scale-50 rounded-md opacity-0 content-[''];
transition:
scale 200ms linear,
opacity 200ms linear,
background-color 200ms ease-out;
}
/* Show indicator when selected */
&[data-selected="true"]::before {
@apply scale-100 opacity-100;
}
}
.hv-checkbox__indicator {
@apply text-white;
}
.hv-checkbox__content {
@apply items-center gap-3;
}
}
```
## 样式参考
HeroUI 遵循 [BEM](https://getbem.com/) 方法论,确保组件变体与状态可复用且易于自定义。
### CSS 类
Checkbox 组件使用以下 CSS 类([查看源码样式](https://github.com/heroui-inc/heroui/blob/v3/packages/styles/components/checkbox.css)):
#### 基础类
- `.hv-checkbox` - 基础复选框容器(字段)
- `.hv-checkbox__content` - 包裹控件与标签文本的可点击 label
- `.hv-checkbox__control` - 复选框控件框
- `.hv-checkbox__indicator` - 复选框勾选指示器
### 交互状态
复选框同时支持 CSS 伪类与 data 属性:
- **Selected**:`[data-selected="true"]` 或 `[aria-checked="true"]`(显示勾选与背景色变化)
- **Indeterminate**:`[data-indeterminate="true"]`(显示不确定状态的短横线)
- **Invalid**:`[data-invalid="true"]` 或 `[aria-invalid="true"]`(显示 danger 色错误状态)
- **Hover**:`CheckboxContent`(可点击标签)上的 `:hover` 或 `[data-hovered="true"]`
- **Focus**:按钮上的 `:focus-visible` 或 `[data-focus-visible="true"]`(控件上显示焦点环)
- **Disabled**:字段上的 `[data-disabled="true"]`(降低透明度,包括帮助文本)
- **Pressed**:`:active` 或 `[data-pressed="true"]`
## API 参考
本库采用原生 label/input 承载选择与提交,复用共享字段、Form、Fieldset 禁用和错误协议。原生输入是唯一的提交值来源;组内没有 Reka 的重复隐藏值或带索引字段名。组校验另有无 name、不可 Tab 聚焦的约束代理,不产生 FormData 条目。
### Checkbox
| 属性 | 类型 | 默认值 | 描述 |
| ------------------------------------ | --------------------------------------------------------------------- | -------------------------- | ----------------------------------------------------------------------- |
| `checked` | `boolean` | 非受控 | 当前选择,推荐 `v-model:checked` |
| `isSelected` | `boolean` | - | 保留上游受控属性,支持 `v-model:isSelected`;同时传值时 checked 优先 |
| `defaultChecked` / `defaultSelected` | `boolean` | `false` | 非受控初始值;defaultChecked 优先 |
| `isIndeterminate` | `boolean` | `false` | 独立的半选外观;不将 mixed 字符串提交。点击后是否解除由调用方更新该属性 |
| `value` | `string` | `'on'` | 原生提交值;组内应显式指定唯一 value |
| `name` / `form` / `id` | `string` | - / - / 自动 | 落在真实 checkbox;组内 name/form 由组统一管理 |
| `variant` | `'primary' \| 'secondary'` | 继承组,否则 primary | 显式子变体优先 |
| `isDisabled` / `disabled` | `boolean` | `false` | 禁用,不能解除组/Fieldset 禁用 |
| `isReadOnly` | `boolean` | `false` | 保持可聚焦,阻止鼠标和键盘更新 |
| `isRequired` / `isInvalid` | `boolean` | `false` | 必填约束 / 纯展示错误状态;后者不单独阻止提交 |
| `validate` | `(value: boolean) => string \| string[] \| true \| null \| undefined` | - | 同步校验 |
| `validationBehavior` | `'native' \| 'aria'` | 继承组或 Form,否则 native | native 拦截;aria 只显示语义 |
| `class` / `style` | Vue class/style 绑定 | - | 字段容器;ARIA 和 DOM 监听落在真实 input |
| 默认插槽 | 作用域插槽 | 默认 control/indicator | 字段部件与状态 |
### 事件与暴露
| 接口 | 参数 / 行为 |
| ------------------------------------------------- | -------------------------------------------------------- |
| `update:checked` / `update:isSelected` / `change` | 每次修改请求发出 boolean;受控拒绝后恢复原生 checked |
| `focus()` / `element` | 模板 ref 暴露;实际 HTMLInputElement(公开实例自动解包) |
默认控件空内容时需提供 aria-label;推荐显式组合 Content 与文案。原生 Space 切换;外部 Label 的 for 与 Checkbox id 对应真实输入。禁用项不提交,未选中项不提交,非受控 reset 恢复初始值;取消 reset 保留当前值。
### CheckboxContent / Control / Indicator
| 部件 | 根与插槽 | 属性落点 |
| --------- | ------------------------------------------ | ------------------------------------------ |
| Content | 原生 label,包含实际 input;默认作用域插槽 | class/style/原生 label 属性及事件 |
| Control | span,默认插槽 | class/style/DOM 属性与事件 |
| Indicator | span,默认作用域插槽 | 装饰 aria-hidden;自定义内容替换基线指示器 |
具名导出使用 CheckboxContent、CheckboxControl、CheckboxIndicator;不使用 React 对象式子部件。class 均支持字符串、数组和对象。默认图形精确来自基线,文档自定义图标使用 Tabler。Content 输出 selected/indeterminate/hovered/pressed/focus-visible 状态标记供定制样式使用。
### 作用域插槽状态
| 参数 | 类型 | 说明 |
| ---------------------------------------------------------- | --------- | ------------------------------ |
| `isSelected` / `isIndeterminate` | `boolean` | 选中 / 半选(半选仅 Checkbox) |
| `isDisabled` / `isReadOnly` / `isRequired` / `isInvalid` | `boolean` | 当前状态 |
| `isHovered` / `isPressed` / `isFocused` / `isFocusVisible` | `boolean` | 单成员交互状态 |
组作用域提供 value、validationErrors、isDisabled/isReadOnly/isRequired/isInvalid,以及 state.value/state.setValue;单成员另提供 state.isSelected/state.setSelected/state.toggle。不把组值和单成员状态混用。
### 框架适配与边界
render 自定义根类型未支持;基线 div+data-custom 示例以 Vue 根属性透传保留效果。SSR 预规划直接/原生/Fragment 包裹的标签、说明、错误与直接成员;本库 Content 内的说明也支持。任意用户 Vue 包装组件无法静态展开,需要显式 aria-labelledby/aria-describedby 和 ID 保证首屏关联。没有宣称完整读屏、触屏、Nuxt 或逐像素验收。
## 相关组件
[Checkbox](./checkbox) · [CheckboxGroup](./checkbox-group) · [RadioGroup](./radio-group) · [Fieldset](./fieldset)
+272
View File
@@ -0,0 +1,272 @@
---
title: RadioGroup 单选框组
description: 用于从列表中选择单个选项的单选组。
icon: updated
component: radio-group
group: 组件
---
## 用法
```vue
<script setup lang="ts">
import {
Radio,
RadioContent,
RadioControl,
RadioIndicator,
Label,
Description,
FieldError,
RadioGroup,
} from "@heroui-vue/components";
</script>
```
<ComponentPreview
name="radio-group-basic"
/>
## 组件结构
使用 RadioGroup、Radio、RadioContent、RadioControl 和 RadioIndicator 具名导出组合。
```vue
<script setup lang="ts">
import {
Radio,
RadioContent,
RadioControl,
RadioIndicator,
Label,
Description,
FieldError,
RadioGroup,
} from "@heroui-vue/components";
</script>
<template>
<RadioGroup>
<Label>选择选项</Label>
<Radio value="basic">
<RadioContent>
<RadioControl><RadioIndicator /></RadioControl>
<Label>选项</Label>
</RadioContent>
<Description />
</Radio>
<FieldError />
</RadioGroup>
</template>
```
## 示例
### 水平排列
<ComponentPreview
name="radio-group-horizontal"
/>
### 变体
RadioGroup 组件支持两种视觉变体:
- **`primary`**(默认)— 带默认背景的标准样式,适用于大多数场景
- **`secondary`** — 低强调变体,适合在 Surface 等表面背景上使用
<ComponentPreview name="radio-group-variants" />
### 表面样式
在 [Surface](/components/surface) 内使用时,请使用 `variant="secondary"`,以应用适合表面背景的低强调变体。
<ComponentPreview
name="radio-group-on-surface"
/>
### 禁用
<ComponentPreview
name="radio-group-disabled"
/>
### 受控组件
<ComponentPreview
name="radio-group-controlled"
/>
### 非受控
仅需响应更新时,将 `defaultValue` 与 `update:modelValue` 配合使用。
<ComponentPreview
name="radio-group-uncontrolled"
/>
### 表单校验
<ComponentPreview
name="radio-group-validation"
/>
### 配送与支付
<ComponentPreview
isBgSolid
align="start"
name="radio-group-delivery-and-payment"
/>
### 自定义指示器
<ComponentPreview
name="radio-group-custom-indicator"
/>
### 渲染函数
<ComponentPreview
name="radio-group-render-function"
/>
## 自定义样式
### Tailwind CSS
<ComponentPreview name="radio-group-custom-styles" />
### 全局 CSS
若要自定义组件类,可使用 `@layer components` 指令。[了解更多](https://tailwindcss.com/docs/adding-custom-styles#adding-component-classes)。
```css
@layer components {
.hv-radio-group {
@apply gap-2;
}
.hv-radio {
@apply gap-4 rounded-lg border border-border p-3 hover:bg-surface-hovered;
}
.hv-radio__control {
@apply border-2 border-accent;
}
.hv-radio__indicator {
@apply bg-primary;
}
.hv-radio__content {
@apply gap-1;
}
}
```
## 样式参考
HeroUI 遵循 [BEM](https://getbem.com/) 方法论,确保组件变体与状态可复用且易于自定义。
### CSS 类
RadioGroup 使用以下 CSS 类([查看源码样式](https://github.com/heroui-inc/heroui/blob/v3/packages/styles/components/radio-group.css)):
#### 基础类
- `.hv-radio-group` - 单选组基础容器
- `.hv-radio` - 单个单选项
- `.hv-radio__control` - 单选控件(圆形按钮)
- `.hv-radio__indicator` - 单选指示器(内部圆点)
- `.hv-radio__content` - 单选内容包裹层
#### 修饰类
禁用态通过 `.hv-radio` 上的 `[data-disabled="true"]` / `[aria-disabled="true"]`(以及 `:disabled`)应用——没有 `.hv-radio--disabled` 修饰类。
### 交互状态
单选项同时支持 CSS 伪类与 data 属性,便于灵活定制:
- **Selected**:`[aria-checked="true"]` 或 `[data-selected="true"]`(显示指示器)
- **Hover**:`:hover` 或 `[data-hovered="true"]`(边框颜色变化)
- **Focus**:`:focus-visible` 或 `[data-focus-visible="true"]`(显示焦点环)
- **Pressed**:`:active` 或 `[data-pressed="true"]`(缩放变换)
- **Disabled**:`:disabled` 或 `[aria-disabled="true"]`(降低透明度并禁用指针事件)
- **Invalid**:`[data-invalid="true"]` 或 `[aria-invalid="true"]`(错误边框颜色)
## API 参考
本库采用原生 label/input 承载选择与提交,复用共享字段、Form、Fieldset 禁用和错误协议。原生输入是唯一的提交值来源;组内没有 Reka 的重复隐藏值或带索引字段名。组校验另有无 name、不可 Tab 聚焦的约束代理,不产生 FormData 条目。
### RadioGroup
| 属性 | 类型 | 默认值 | 描述 |
| -------------------------- | --------------------------------------------------------------------------------- | ---------------------- | -------------------------------------- |
| `modelValue` | `string \| undefined` | 非受控 | 当前值,使用 v-model |
| `defaultValue` | `string \| undefined` | `undefined` | 非受控初始值副本 |
| `name` / `form` / `id` | `string` | - / - / 自动 | 统一原生提交键、表单归属及组 ID |
| `variant` | `'primary' \| 'secondary'` | `'primary'` | 组视觉样式;Checkbox 成员可显式覆盖 |
| `isDisabled` / `disabled` | `boolean` | `false` | 合并 Fieldset 禁用,后代不能解除 |
| `isReadOnly` | `boolean` | `false` | 阻止成员点击、空格和方向键修改 |
| `isRequired` / `isInvalid` | `boolean` | `false` | 要求至少一项可用选择 / 错误展示 |
| `validate` | `(value: string \| undefined) => string \| string[] \| true \| null \| undefined` | - | 同步组校验 |
| `validationBehavior` | `'native' \| 'aria'` | 继承 Form,否则 native | 原生提交拦截或仅错误语义 |
| `class` / `style` | Vue class/style 绑定 | - | 合并根样式,接受字符串/数组/对象 class |
| 默认插槽 | 作用域插槽 | - | 标签、说明、成员、错误 |
| `orientation` | `'vertical' \| 'horizontal'` | `'vertical'` | 布局及 aria-orientation |
| `dir` / `loop` | `'ltr' \| 'rtl'` / `boolean` | 继承方向 / `true` | 方向键映射及循环 |
### Radio
| 属性 | 类型 | 默认值 | 描述 |
| ------------------------------------------------------ | -------------------- | ------- | --------------------------- |
| `value` | `string` | 必填 | 组内唯一值 |
| `id` | `string` | 自动 | 实际 radio ID |
| `isDisabled` / `disabled` / `isReadOnly` / `isInvalid` | `boolean` | `false` | 成员状态,与组状态合并 |
| `class` / `style` | Vue class/style 绑定 | - | 字段根;ARIA/事件落在 input |
| `name` / `form` | `string` | - | 组内统一由 RadioGroup 管理 |
Radio 必须在 RadioGroup 中使用。不为未选中的 Radio 输出 data-selected;默认 Indicator 保持 CSS :empty 内圆点。Tab 进入选中可用成员或首个可用成员;方向键跳过禁用项,支持 RTL、Home/End,且调用者 keydown.prevent 可以取消。
### 事件与暴露
| 接口 | 行为 |
| ------------------------------ | ---------------------------------------------------------------------- |
| `update:modelValue` / `change` | 发出新的数组或标量;不修改传入数组;父级拒绝后恢复所有原生 checked |
| `focus()` / `element` | 聚焦选中可用成员或首个可用成员;空组聚焦组根。element 是组 HTMLElement |
CheckboxGroup 按原生约定提交同名重复条目,通过 FormData.getAll(name) 获取;RadioGroup 只提交一个选中可用值。未指定 name 不产生提交值。每个成员 value 必须唯一;重复或动态改成重复值会抛出明确错误。不为移除的选择自动选择别的成员;模型保留调用者的值,FormData 只包含实际存在的可用成员。
required 检查整个组,不能让每个 Checkbox 都变成必选;native 无效提交聚焦第一个可用成员,空组聚焦根。只读保留提交值并跳过必填/自定义约束。reset 尊重 preventDefault,受控值不覆盖,非受控恢复初始副本。动态 name/form 会更新提交和 reset 归属。
Label 在组中渲染 span 并注册 aria-labelledby;不要手写 for 指向组 div。每个成员独立隔离 Description/FieldError,同时合并组描述和当前组错误。后端错误使用 Form.validationErrors 按 name 映射,编辑后忽略当前响应,新对象可恢复错误。暂不提供异步 validate 或完整 validationDetails。
### RadioContent / Control / Indicator
| 部件 | 根与插槽 | 属性落点 |
| --------- | ------------------------------------------ | ------------------------------------------ |
| Content | 原生 label,包含实际 input;默认作用域插槽 | class/style/原生 label 属性及事件 |
| Control | span,默认插槽 | class/style/DOM 属性与事件 |
| Indicator | span,默认作用域插槽 | 装饰 aria-hidden;自定义内容替换基线指示器 |
具名导出使用 RadioContent、RadioControl、RadioIndicator;不使用 React 对象式子部件。class 均支持字符串、数组和对象。默认图形精确来自基线,文档自定义图标使用 Tabler。Content 输出 selected/indeterminate/hovered/pressed/focus-visible 状态标记供定制样式使用。
### 作用域插槽状态
| 参数 | 类型 | 说明 |
| ---------------------------------------------------------- | --------- | ------------------------------ |
| `isSelected` / `isIndeterminate` | `boolean` | 选中 / 半选(半选仅 Checkbox) |
| `isDisabled` / `isReadOnly` / `isRequired` / `isInvalid` | `boolean` | 当前状态 |
| `isHovered` / `isPressed` / `isFocused` / `isFocusVisible` | `boolean` | 单成员交互状态 |
组作用域提供 value、validationErrors、isDisabled/isReadOnly/isRequired/isInvalid,以及 state.value/state.setValue;单成员另提供 state.isSelected/state.setSelected/state.toggle。不把组值和单成员状态混用。
### 框架适配与边界
render 自定义根类型未支持;基线 div+data-custom 示例以 Vue 根属性透传保留效果。SSR 预规划直接/原生/Fragment 包裹的标签、说明、错误与直接成员;本库 Content 内的说明也支持。任意用户 Vue 包装组件无法静态展开,需要显式 aria-labelledby/aria-describedby 和 ID 保证首屏关联。没有宣称完整读屏、触屏、Nuxt 或逐像素验收。
## 相关组件
[Checkbox](./checkbox) · [CheckboxGroup](./checkbox-group) · [RadioGroup](./radio-group) · [Fieldset](./fieldset)
+18
View File
@@ -0,0 +1,18 @@
<script setup lang="ts">
import {
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
} from "@heroui-vue/components";
</script>
<template>
<Checkbox name="basic-terms">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
接受条款与条件
</CheckboxContent>
</Checkbox>
</template>
+30
View File
@@ -0,0 +1,30 @@
<script setup lang="ts">
import {
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
} from "@heroui-vue/components";
import { ref } from "vue";
const isSelected = ref(true);
</script>
<template>
<div class="flex flex-col gap-3">
<Checkbox
id="email-notifications"
:is-selected="isSelected"
@update:checked="isSelected = $event"
>
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
邮件通知
</CheckboxContent>
</Checkbox>
<p class="text-sm text-muted">
状态:
<span class="font-medium">{{ isSelected ? "已勾选" : "未勾选" }}</span>
</p>
</div>
</template>
@@ -0,0 +1,43 @@
<script setup lang="ts">
import {
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
} from "@heroui-vue/components";
import { IconHeartFilled, IconPlus, IconMinus } from "@tabler/icons-vue";
</script>
<template>
<div class="flex gap-4">
<Checkbox default-selected name="heart">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator v-slot="{ isSelected }">
<IconHeartFilled v-if="isSelected" aria-hidden="true" />
</CheckboxIndicator>
</CheckboxControl>
心形
</CheckboxContent>
</Checkbox>
<Checkbox default-selected name="plus">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator v-slot="{ isSelected }">
<IconPlus v-if="isSelected" aria-hidden="true" />
</CheckboxIndicator>
</CheckboxControl>
加号
</CheckboxContent>
</Checkbox>
<Checkbox is-indeterminate name="indeterminate">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator v-slot="{ isIndeterminate }">
<IconMinus v-if="isIndeterminate" aria-hidden="true" />
</CheckboxIndicator>
</CheckboxControl>
部分选中
</CheckboxContent>
</Checkbox>
</div>
</template>
@@ -0,0 +1,20 @@
<script setup lang="ts">
import {
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
} from "@heroui-vue/components";
</script>
<template>
<Checkbox id="custom">
<CheckboxContent>
<CheckboxControl class="bg-success-soft before:bg-success">
<CheckboxIndicator
class="**:data-[slot=checkbox-default-indicator--checkmark]:text-success-foreground"
/>
</CheckboxControl>
自定义样式复选框
</CheckboxContent>
</Checkbox>
</template>
@@ -0,0 +1,18 @@
<script setup lang="ts">
import {
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
} from "@heroui-vue/components";
</script>
<template>
<Checkbox default-selected id="default-notifications">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
启用邮件通知
</CheckboxContent>
</Checkbox>
</template>
+20
View File
@@ -0,0 +1,20 @@
<script setup lang="ts">
import {
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
Description,
} from "@heroui-vue/components";
</script>
<template>
<Checkbox is-disabled id="feature">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
高级功能
</CheckboxContent>
<Description>该功能即将推出</Description>
</Checkbox>
</template>
@@ -0,0 +1,21 @@
<script setup lang="ts">
import {
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
Label,
} from "@heroui-vue/components";
</script>
<template>
<div class="flex items-center gap-3">
<Checkbox id="label-marketing">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
</CheckboxContent>
</Checkbox>
<Label for="label-marketing">给我发送营销邮件</Label>
</div>
</template>
+53
View File
@@ -0,0 +1,53 @@
<script setup lang="ts">
import {
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
Button,
} from "@heroui-vue/components";
import { ref } from "vue";
const result = ref("");
function submit(event: Event) {
const data = new FormData(event.currentTarget as HTMLFormElement);
result.value =
"表单提交数据:\n" +
Array.from(data)
.map(([key, value]) => `${key}: ${value}`)
.join("\n");
}
</script>
<template>
<form class="flex flex-col gap-4" @submit.prevent="submit">
<div class="flex flex-col gap-3">
<Checkbox name="notifications" value="on">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
启用通知
</CheckboxContent>
</Checkbox>
<Checkbox default-selected name="newsletter" value="on">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
订阅新闻通讯
</CheckboxContent>
</Checkbox>
<Checkbox name="marketing" value="on">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
接收营销更新
</CheckboxContent>
</Checkbox>
</div>
<Button class="mt-4" size="sm" type="submit" variant="primary">提交</Button>
<pre v-if="result" role="status" class="whitespace-pre-wrap text-sm">{{
result
}}</pre>
</form>
</template>
+60
View File
@@ -0,0 +1,60 @@
<script setup lang="ts">
import {
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
Label,
} from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-6">
<div class="flex flex-col gap-3">
<Label class="text-muted">圆角复选框</Label>
<Checkbox
class="[&_[data-slot='checkbox-default-indicator--checkmark']]:size-2"
name="small-rounded"
>
<CheckboxContent>
<CheckboxControl class="size-3 rounded-full before:rounded-full">
<CheckboxIndicator />
</CheckboxControl>
小尺寸
</CheckboxContent>
</Checkbox>
</div>
<div class="flex flex-col gap-3">
<Checkbox name="default-rounded">
<CheckboxContent>
<CheckboxControl class="size-4 rounded-full before:rounded-full">
<CheckboxIndicator />
</CheckboxControl>
默认尺寸
</CheckboxContent>
</Checkbox>
</div>
<div class="flex flex-col gap-3">
<Checkbox name="large-rounded">
<CheckboxContent>
<CheckboxControl class="size-5 rounded-full before:rounded-full">
<CheckboxIndicator />
</CheckboxControl>
大尺寸
</CheckboxContent>
</Checkbox>
</div>
<div class="flex flex-col gap-3">
<Checkbox
class="[&_[data-slot='checkbox-default-indicator--checkmark']]:size-4"
name="xl-rounded"
>
<CheckboxContent>
<CheckboxControl class="size-6 rounded-full before:rounded-full">
<CheckboxIndicator />
</CheckboxControl>
特大尺寸
</CheckboxContent>
</Checkbox>
</div>
</div>
</template>
+44
View File
@@ -0,0 +1,44 @@
<script setup lang="ts">
import {
CheckboxGroup,
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
Label,
Description,
} from "@heroui-vue/components";
</script>
<template>
<CheckboxGroup name="interests">
<Label>选择你的兴趣</Label>
<Description>可多选</Description>
<Checkbox value="coding">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
编程
</CheckboxContent>
<Description>热爱构建软件</Description>
</Checkbox>
<Checkbox value="design">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
设计
</CheckboxContent>
<Description>喜欢打造精美界面</Description>
</Checkbox>
<Checkbox value="writing">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
写作
</CheckboxContent>
<Description>热衷于内容创作</Description>
</Checkbox>
</CheckboxGroup>
</template>
@@ -0,0 +1,49 @@
<script setup lang="ts">
import {
CheckboxGroup,
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
Label,
} from "@heroui-vue/components";
import { ref } from "vue";
const selected = ref(["coding", "design"]);
</script>
<template>
<CheckboxGroup
class="min-w-[320px]"
name="skills"
:model-value="selected"
@update:model-value="selected = $event"
>
<Label>你的技能</Label>
<Checkbox value="coding">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
编程
</CheckboxContent>
</Checkbox>
<Checkbox value="design">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
设计
</CheckboxContent>
</Checkbox>
<Checkbox value="writing">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
写作
</CheckboxContent>
</Checkbox>
<Label class="my-4 text-sm text-muted">
已选:{{ selected.join(", ") || "无" }}
</Label>
</CheckboxGroup>
</template>
@@ -0,0 +1,37 @@
<script setup lang="ts">
import {
CheckboxGroup,
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
Label,
Description,
} from "@heroui-vue/components";
const controlClassName = "bg-success-soft before:bg-success";
const indicatorClassName =
"**:data-[slot=checkbox-default-indicator--checkmark]:text-success-foreground";
const channels = [
{ label: "电子邮件", value: "email" },
{ label: "短信", value: "sms" },
{ label: "推送", value: "push" },
] as const;
</script>
<template>
<CheckboxGroup
class="gap-3 **:data-[slot=checkbox]:mt-0"
:default-value="['email']"
name="notification-channels"
>
<Label>通知渠道</Label>
<Description>选择我们通过何种方式向您发送账户更新。</Description>
<Checkbox v-for="{ label, value } in channels" :key="value" :value="value">
<CheckboxContent>
<CheckboxControl :class="controlClassName">
<CheckboxIndicator :class="indicatorClassName" />
</CheckboxControl>
{{ label }}
</CheckboxContent>
</Checkbox>
</CheckboxGroup>
</template>
@@ -0,0 +1,35 @@
<script setup lang="ts">
import {
CheckboxGroup,
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
Label,
Description,
} from "@heroui-vue/components";
</script>
<template>
<CheckboxGroup is-disabled name="disabled-features">
<Label>功能</Label>
<Description>功能选择暂时不可用</Description>
<Checkbox value="feature1">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
功能一
</CheckboxContent>
<Description>该功能即将推出</Description>
</Checkbox>
<Checkbox value="feature2">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
功能二
</CheckboxContent>
<Description>该功能即将推出</Description>
</Checkbox>
</CheckboxGroup>
</template>
@@ -0,0 +1,69 @@
<script setup lang="ts">
import {
CheckboxGroup,
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
Label,
Description,
} from "@heroui-vue/components";
import { IconMail, IconMessage, IconBell } from "@tabler/icons-vue";
const addOns = [
{
description: "通过邮件接收更新",
icon: IconMail,
title: "邮件通知",
value: "email",
},
{
description: "即时短信通知",
icon: IconMessage,
title: "短信提醒",
value: "sms",
},
{
description: "浏览器与移动端推送提醒",
icon: IconBell,
title: "推送通知",
value: "push",
},
];
</script>
<template>
<div class="flex w-full flex-col items-center gap-10 px-4 py-8">
<section class="flex w-full min-w-[320px] max-sm:min-w-0 flex-col gap-4">
<CheckboxGroup name="notification-preferences">
<Label>通知偏好</Label>
<Description>选择接收更新的方式</Description>
<div class="flex flex-col gap-2">
<Checkbox
v-for="addon in addOns"
:key="addon.value"
:value="addon.value"
variant="secondary"
>
<CheckboxContent
class="group relative flex w-full flex-row items-start justify-start gap-4 rounded-3xl bg-surface px-5 py-4 transition-all data-[selected=true]:bg-accent/10"
>
<CheckboxControl
class="absolute end-4 top-3 size-5 rounded-full before:rounded-full"
>
<CheckboxIndicator />
</CheckboxControl>
<component
:is="addon.icon"
class="size-5 text-accent-soft-foreground"
aria-hidden="true"
/>
<div class="flex flex-col gap-1">
<span>{{ addon.title }}</span>
<Description>{{ addon.description }}</Description>
</div>
</CheckboxContent>
</Checkbox>
</div>
</CheckboxGroup>
</section>
</div>
</template>
@@ -0,0 +1,57 @@
<script setup lang="ts">
import {
CheckboxGroup,
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
} from "@heroui-vue/components";
import { ref } from "vue";
const selected = ref(["coding"]);
const allOptions = ["coding", "design", "writing"];
</script>
<template>
<div>
<Checkbox
:is-indeterminate="
selected.length > 0 && selected.length < allOptions.length
"
:checked="selected.length === allOptions.length"
name="select-all"
@update:checked="selected = $event ? [...allOptions] : []"
>
<CheckboxContent>
<CheckboxControl><CheckboxIndicator /></CheckboxControl>
全选
</CheckboxContent>
</Checkbox>
<div class="ms-6 flex flex-col gap-2">
<CheckboxGroup v-model="selected">
<Checkbox value="coding">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
编程
</CheckboxContent>
</Checkbox>
<Checkbox value="design">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
设计
</CheckboxContent>
</Checkbox>
<Checkbox value="writing">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
写作
</CheckboxContent>
</Checkbox>
</CheckboxGroup>
</div>
</div>
</template>
@@ -0,0 +1,47 @@
<script setup lang="ts">
import {
CheckboxGroup,
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
Label,
Description,
Surface,
} from "@heroui-vue/components";
</script>
<template>
<Surface class="w-full rounded-3xl p-6">
<CheckboxGroup name="interests" variant="secondary">
<Label>选择你的兴趣</Label>
<Description>可多选</Description>
<Checkbox value="coding">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
编程
</CheckboxContent>
<Description>热爱构建软件</Description>
</Checkbox>
<Checkbox value="design">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
设计
</CheckboxContent>
<Description>喜欢打造精美界面</Description>
</Checkbox>
<Checkbox value="writing">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
写作
</CheckboxContent>
<Description>热衷于内容创作</Description>
</Checkbox>
</CheckboxGroup>
</Surface>
</template>
@@ -0,0 +1,44 @@
<script setup lang="ts">
import {
CheckboxGroup,
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
Label,
Description,
} from "@heroui-vue/components";
</script>
<template>
<CheckboxGroup name="interests" data-custom="foo">
<Label>选择你的兴趣</Label>
<Description>可多选</Description>
<Checkbox value="coding">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
编程
</CheckboxContent>
<Description>热爱构建软件</Description>
</Checkbox>
<Checkbox value="design">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
设计
</CheckboxContent>
<Description>喜欢打造精美界面</Description>
</Checkbox>
<Checkbox value="writing">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
写作
</CheckboxContent>
<Description>热衷于内容创作</Description>
</Checkbox>
</CheckboxGroup>
</template>
@@ -0,0 +1,53 @@
<script setup lang="ts">
import {
CheckboxGroup,
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
Label,
FieldError,
Button,
Form,
} from "@heroui-vue/components";
import { ref } from "vue";
const result = ref("");
function submit(event: Event) {
const data = new FormData(event.currentTarget as HTMLFormElement);
result.value = "已选偏好:" + data.getAll("preferences").join(", ");
}
</script>
<template>
<Form class="flex flex-col gap-4 px-4" @submit.prevent="submit">
<CheckboxGroup is-required name="preferences">
<Label>偏好设置</Label>
<Checkbox value="email">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
邮件通知
</CheckboxContent>
</Checkbox>
<Checkbox value="sms">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
短信通知
</CheckboxContent>
</Checkbox>
<Checkbox value="push">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
推送通知
</CheckboxContent>
</Checkbox>
<FieldError>请至少选择一种通知方式。</FieldError>
</CheckboxGroup>
<Button type="submit">提交</Button>
<p v-if="result" role="status" class="text-sm">{{ result }}</p>
</Form>
</template>
@@ -0,0 +1,40 @@
<script setup lang="ts">
import {
CheckboxGroup,
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
Label,
Description,
} from "@heroui-vue/components";
import { IconX } from "@tabler/icons-vue";
</script>
<template>
<CheckboxGroup name="features">
<Label>功能</Label>
<Description>选择你需要的功能</Description>
<Checkbox value="notifications">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator v-slot="{ isSelected }">
<IconX v-if="isSelected" aria-hidden="true" />
</CheckboxIndicator>
</CheckboxControl>
邮件通知
</CheckboxContent>
<Description>通过邮件接收更新</Description>
</Checkbox>
<Checkbox value="newsletter">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator v-slot="{ isSelected }">
<IconX v-if="isSelected" aria-hidden="true" />
</CheckboxIndicator>
</CheckboxControl>
邮件通讯
</CheckboxContent>
<Description>每周接收邮件简报</Description>
</Checkbox>
</CheckboxGroup>
</template>
@@ -0,0 +1,30 @@
<script setup lang="ts">
import { ref } from "vue";
import {
Checkbox,
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Description,
} from "@heroui-vue/components";
const isIndeterminate = ref(true),
isSelected = ref(false);
function update(value: boolean) {
isSelected.value = value;
isIndeterminate.value = false;
}
</script>
<template>
<Checkbox
id="select-all"
:is-indeterminate="isIndeterminate"
:checked="isSelected"
@update:checked="update"
>
<CheckboxContent>
<CheckboxControl><CheckboxIndicator /></CheckboxControl>
全选
</CheckboxContent>
<Description>展示部分选中状态(短横线图标)</Description>
</Checkbox>
</template>
+20
View File
@@ -0,0 +1,20 @@
<script setup lang="ts">
import {
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
FieldError,
} from "@heroui-vue/components";
</script>
<template>
<Checkbox is-invalid is-required name="agreement">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
我同意条款
</CheckboxContent>
<FieldError>您必须接受条款才能继续</FieldError>
</Checkbox>
</template>
@@ -0,0 +1,18 @@
<script setup lang="ts">
import {
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
} from "@heroui-vue/components";
</script>
<template>
<Checkbox data-custom="bar">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
接受条款与条件
</CheckboxContent>
</Checkbox>
</template>
+20
View File
@@ -0,0 +1,20 @@
<script setup lang="ts">
import {
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
Description,
} from "@heroui-vue/components";
</script>
<template>
<Checkbox id="render-props-terms" v-slot="{ isSelected }">
<CheckboxContent>
<CheckboxControl><CheckboxIndicator /></CheckboxControl>
{{ isSelected ? "已同意条款" : "接受条款" }}
</CheckboxContent>
<Description>
{{ isSelected ? "感谢您的确认" : "请先阅读并接受条款" }}
</Description>
</Checkbox>
</template>
+37
View File
@@ -0,0 +1,37 @@
<script setup lang="ts">
import {
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
Description,
} from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-4">
<div class="flex flex-col gap-2">
<p class="text-sm font-medium text-muted">主要变体</p>
<Checkbox id="primary" name="primary" variant="primary">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
主要复选框
</CheckboxContent>
<Description>默认背景的标准样式</Description>
</Checkbox>
</div>
<div class="flex flex-col gap-2">
<p class="text-sm font-medium text-muted">次要变体</p>
<Checkbox id="secondary" name="secondary" variant="secondary">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
次要复选框
</CheckboxContent>
<Description>用于表面容器的低强调样式</Description>
</Checkbox>
</div>
</div>
</template>
@@ -0,0 +1,20 @@
<script setup lang="ts">
import {
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
Checkbox,
Description,
} from "@heroui-vue/components";
</script>
<template>
<Checkbox name="description-notifications">
<CheckboxContent>
<CheckboxControl>
<CheckboxIndicator />
</CheckboxControl>
邮件通知
</CheckboxContent>
<Description>当有人在评论中提及您时收到通知</Description>
</Checkbox>
</template>
+44
View File
@@ -0,0 +1,44 @@
<script setup lang="ts">
import {
RadioGroup,
RadioContent,
RadioControl,
RadioIndicator,
Radio,
Label,
Description,
} from "@heroui-vue/components";
</script>
<template>
<RadioGroup default-value="premium" name="plan">
<Label>选择套餐</Label>
<Description>选择最适合你的套餐</Description>
<Radio value="basic">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
基础版
</RadioContent>
<Description>每月包含 100 条消息</Description>
</Radio>
<Radio value="premium">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
高级版
</RadioContent>
<Description>每月包含 200 条消息</Description>
</Radio>
<Radio value="business">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
商业版
</RadioContent>
<Description>无限消息</Description>
</Radio>
</RadioGroup>
</template>
@@ -0,0 +1,55 @@
<script setup lang="ts">
import {
RadioGroup,
RadioContent,
RadioControl,
RadioIndicator,
Radio,
Label,
Description,
} from "@heroui-vue/components";
import { ref } from "vue";
const value = ref<string | undefined>("pro");
</script>
<template>
<div class="flex flex-col gap-4">
<RadioGroup
name="plan-controlled"
:model-value="value"
@update:model-value="value = $event"
>
<Label>订阅套餐</Label>
<Radio value="starter">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
入门版
</RadioContent>
<Description>适合副项目和小型团队</Description>
</Radio>
<Radio value="pro">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
专业版
</RadioContent>
<Description>高级报表与分析</Description>
</Radio>
<Radio value="teams">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
团队版
</RadioContent>
<Description>最多可与 10 名队友共享访问权限</Description>
</Radio>
</RadioGroup>
<p class="text-sm text-muted">
已选套餐:
<span class="font-medium">{{ value }}</span>
</p>
</div>
</template>
@@ -0,0 +1,63 @@
<script setup lang="ts">
import {
RadioGroup,
RadioContent,
RadioControl,
RadioIndicator,
Radio,
Label,
Description,
} from "@heroui-vue/components";
import { IconCheck } from "@tabler/icons-vue";
</script>
<template>
<RadioGroup default-value="premium" name="plan-custom-indicator">
<Label>选择套餐</Label>
<Description>选择最适合你的套餐</Description>
<Radio value="basic">
<RadioContent>
<RadioControl>
<RadioIndicator v-slot="{ isSelected }">
<IconCheck
v-if="isSelected"
class="size-3 text-background"
aria-hidden="true"
/>
</RadioIndicator>
</RadioControl>
基础版
</RadioContent>
<Description>每月包含 100 条消息</Description>
</Radio>
<Radio value="premium">
<RadioContent>
<RadioControl>
<RadioIndicator v-slot="{ isSelected }">
<IconCheck
v-if="isSelected"
class="size-3 text-background"
aria-hidden="true"
/>
</RadioIndicator>
</RadioControl>
高级版
</RadioContent>
<Description>每月包含 200 条消息</Description>
</Radio>
<Radio value="business">
<RadioContent>
<RadioControl>
<RadioIndicator v-slot="{ isSelected }">
<IconCheck
v-if="isSelected"
class="size-3 text-background"
aria-hidden="true"
/>
</RadioIndicator>
</RadioControl>
商业版
</RadioContent>
<Description>无限消息</Description>
</Radio>
</RadioGroup>
</template>
@@ -0,0 +1,55 @@
<script setup lang="ts">
import {
RadioGroup,
RadioContent,
RadioControl,
RadioIndicator,
Radio,
Label,
Description,
} from "@heroui-vue/components";
const contentClassName =
"group flex w-full items-start gap-3 rounded-xl border border-success/10 bg-success-soft/30 px-4 py-3 transition-colors data-[focus-visible=true]:ring-2 data-[focus-visible=true]:ring-success/15 data-[hovered=true]:bg-success-soft-hover data-[selected=true]:border-success/30 data-[selected=true]:bg-success-soft data-[selected=true]:data-[hovered=true]:bg-success-soft-hover";
const controlClassName =
"mt-0.5 size-5 shrink-0 rounded-full border border-border bg-default shadow-none group-data-[pressed=true]:scale-95 group-data-[selected=true]:border-transparent group-data-[selected=true]:bg-success group-data-[selected=true]:group-data-[pressed=true]:bg-success-hover";
const indicatorClassName =
"before:rounded-full before:bg-default group-data-[selected=true]:before:scale-50 group-data-[selected=true]:before:bg-success-foreground group-data-[selected=true]:group-data-[pressed=true]:before:scale-[0.57]";
const options = [
{ description: "每月扣费 $12", label: "按月", value: "monthly" },
{ description: "每年一次性扣费 $120", label: "按年", value: "yearly" },
] as const;
</script>
<template>
<RadioGroup
class="w-full max-w-sm gap-3 **:data-[slot=radio]:mt-0"
default-value="yearly"
name="billing"
variant="secondary"
>
<Label class="font-medium text-foreground">计费周期</Label>
<Description>选择你的扣费频率。</Description>
<Radio
v-for="{ description, label, value } in options"
:key="value"
:value="value"
>
<RadioContent :class="contentClassName">
<RadioControl :class="controlClassName">
<RadioIndicator :class="indicatorClassName" />
</RadioControl>
<div class="flex flex-col gap-0.5">
<span
class="font-medium text-foreground group-data-[selected=true]:text-success-soft-foreground"
>
{{ label }}
</span>
<Description
class="group-data-[selected=true]:text-success-soft-foreground/80"
>
{{ description }}
</Description>
</div>
</RadioContent>
</Radio>
</RadioGroup>
</template>
@@ -0,0 +1,122 @@
<script setup lang="ts">
import {
RadioGroup,
RadioContent,
RadioControl,
RadioIndicator,
Radio,
Label,
Description,
} from "@heroui-vue/components";
import {
IconBrandMastercard,
IconBrandVisa,
IconBrandPaypal,
} from "@tabler/icons-vue";
const deliveryOptions = [
{
description: "4–10 个工作日",
price: "$5.00",
title: "标准",
value: "standard",
},
{
description: "2–5 个工作日",
price: "$16.00",
title: "快递",
value: "express",
},
{
description: "1 个工作日",
price: "$25.00",
title: "极速",
value: "super-fast",
},
];
const paymentOptions = [
{
description: "有效期至 2026/01",
icon: IconBrandMastercard,
title: "**** 8304",
value: "mastercard",
},
{
description: "有效期至 2026/01",
icon: IconBrandVisa,
title: "**** 0123",
value: "visa",
},
{
description: "使用 PayPal 支付",
icon: IconBrandPaypal,
title: "PayPal",
value: "paypal",
},
];
</script>
<template>
<div
class="flex w-full flex-col items-center gap-10"
style="
--accent: #006fee;
--accent-foreground: #fff;
--accent-hover: #006fee;
--border-width: 2px;
--border-width-field: 2px;
--focus: #006fee;
"
>
<section class="flex w-full max-w-lg flex-col gap-4">
<RadioGroup default-value="express" name="delivery" variant="secondary">
<Label>配送方式</Label>
<div class="grid gap-x-4 md:grid-cols-3">
<Radio
v-for="option in deliveryOptions"
:key="option.value"
:value="option.value"
>
<RadioContent
class="group relative flex w-full flex-col gap-6 rounded-xl border border-transparent bg-surface px-5 py-4 transition-all data-[selected=true]:border-accent data-[selected=true]:bg-accent/10 data-[focus-visible=true]:border-accent data-[focus-visible=true]:bg-accent/10"
>
<RadioControl class="absolute end-4 top-3 size-5">
<RadioIndicator />
</RadioControl>
<div class="flex flex-col gap-1">
<span>{{ option.title }}</span>
<Description>{{ option.description }}</Description>
</div>
<span class="text-sm font-semibold">{{ option.price }}</span>
</RadioContent>
</Radio>
</div>
</RadioGroup>
</section>
<section class="flex w-full max-w-lg flex-col gap-4">
<RadioGroup default-value="visa" name="payment" variant="secondary">
<div class="flex flex-wrap items-center justify-between gap-4">
<Label>支付方式</Label>
</div>
<div class="grid gap-x-4 md:grid-cols-2">
<Radio
v-for="option in paymentOptions"
:key="option.value"
:value="option.value"
>
<RadioContent
class="group relative flex w-full flex-row items-start justify-start gap-4 rounded-xl border border-transparent bg-surface px-5 py-4 transition-all data-[selected=true]:border-accent data-[selected=true]:bg-accent/10"
>
<RadioControl class="absolute end-4 top-3 size-5">
<RadioIndicator />
</RadioControl>
<component :is="option.icon" class="size-6" aria-hidden="true" />
<div class="flex flex-col gap-1">
<span>{{ option.title }}</span>
<Description>{{ option.description }}</Description>
</div>
</RadioContent>
</Radio>
</div>
</RadioGroup>
</section>
</div>
</template>
+44
View File
@@ -0,0 +1,44 @@
<script setup lang="ts">
import {
RadioGroup,
RadioContent,
RadioControl,
RadioIndicator,
Radio,
Label,
Description,
} from "@heroui-vue/components";
</script>
<template>
<RadioGroup is-disabled default-value="pro" name="plan-disabled">
<Label>订阅套餐</Label>
<Description>我们正在发布更新,暂时无法更改套餐。</Description>
<Radio value="starter">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
入门版
</RadioContent>
<Description>适合副项目和小型团队</Description>
</Radio>
<Radio value="pro">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
专业版
</RadioContent>
<Description>高级报表与分析</Description>
</Radio>
<Radio value="teams">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
团队版
</RadioContent>
<Description>最多可与 10 名队友共享访问权限</Description>
</Radio>
</RadioGroup>
</template>
@@ -0,0 +1,50 @@
<script setup lang="ts">
import {
RadioGroup,
RadioContent,
RadioControl,
RadioIndicator,
Radio,
Label,
Description,
} from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-4">
<Label id="plan-orientation-label">订阅套餐</Label>
<RadioGroup
default-value="pro"
name="plan-orientation"
aria-labelledby="plan-orientation-label"
orientation="horizontal"
>
<Radio value="starter">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
入门版
</RadioContent>
<Description>适合副项目</Description>
</Radio>
<Radio value="pro">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
专业版
</RadioContent>
<Description>高级报表</Description>
</Radio>
<Radio value="teams">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
团队版
</RadioContent>
<Description>最多 10 名队友</Description>
</Radio>
</RadioGroup>
</div>
</template>
@@ -0,0 +1,51 @@
<script setup lang="ts">
import {
RadioGroup,
RadioContent,
RadioControl,
RadioIndicator,
Radio,
Label,
Description,
Surface,
} from "@heroui-vue/components";
</script>
<template>
<Surface class="w-full rounded-3xl p-6">
<RadioGroup
default-value="premium"
name="plan-on-surface"
variant="secondary"
>
<Label>选择套餐</Label>
<Description>选择最适合你的套餐</Description>
<Radio value="basic">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
基础版
</RadioContent>
<Description>每月包含 100 条消息</Description>
</Radio>
<Radio value="premium">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
高级版
</RadioContent>
<Description>每月包含 200 条消息</Description>
</Radio>
<Radio value="business">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
商业版
</RadioContent>
<Description>无限消息</Description>
</Radio>
</RadioGroup>
</Surface>
</template>
@@ -0,0 +1,48 @@
<script setup lang="ts">
import {
RadioGroup,
RadioContent,
RadioControl,
RadioIndicator,
Radio,
Label,
Description,
} from "@heroui-vue/components";
</script>
<template>
<RadioGroup
default-value="premium"
name="plan-custom-render"
data-custom="foo"
>
<Label>选择套餐</Label>
<Description>选择最适合你的套餐</Description>
<Radio value="basic">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
基础版
</RadioContent>
<Description>每月包含 100 条消息</Description>
</Radio>
<Radio value="premium">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
高级版
</RadioContent>
<Description>每月包含 200 条消息</Description>
</Radio>
<Radio value="business">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
商业版
</RadioContent>
<Description>无限消息</Description>
</Radio>
</RadioGroup>
</template>
@@ -0,0 +1,55 @@
<script setup lang="ts">
import {
RadioGroup,
RadioContent,
RadioControl,
RadioIndicator,
Radio,
Label,
Description,
} from "@heroui-vue/components";
import { ref } from "vue";
const selection = ref<string | undefined>("pro");
</script>
<template>
<div class="flex flex-col gap-4">
<RadioGroup
default-value="pro"
name="plan-uncontrolled"
@update:model-value="selection = $event"
>
<Label>订阅套餐</Label>
<Radio value="starter">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
入门版
</RadioContent>
<Description>适合副项目和小型团队</Description>
</Radio>
<Radio value="pro">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
专业版
</RadioContent>
<Description>高级报表与分析</Description>
</Radio>
<Radio value="teams">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
团队版
</RadioContent>
<Description>最多可与 10 名队友共享访问权限</Description>
</Radio>
</RadioGroup>
<p class="text-sm text-muted">
上次选择的套餐:
<span class="font-medium">{{ selection }}</span>
</p>
</div>
</template>
@@ -0,0 +1,57 @@
<script setup lang="ts">
import {
RadioGroup,
RadioContent,
RadioControl,
RadioIndicator,
Radio,
Label,
Description,
FieldError,
Button,
Form,
} from "@heroui-vue/components";
import { ref } from "vue";
const result = ref("");
function submit(event: Event) {
const data = new FormData(event.currentTarget as HTMLFormElement);
result.value = "你选择的套餐是: " + data.get("plan-validation");
}
</script>
<template>
<Form class="flex flex-col gap-4" @submit.prevent="submit">
<RadioGroup is-required name="plan-validation">
<Label>订阅套餐</Label>
<Radio value="starter">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
入门版
</RadioContent>
<Description>适合副项目和小型团队</Description>
</Radio>
<Radio value="pro">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
专业版
</RadioContent>
<Description>高级报表与分析</Description>
</Radio>
<Radio value="teams">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
团队版
</RadioContent>
<Description>最多可与 10 名队友共享访问权限</Description>
</Radio>
<FieldError>请先选择订阅套餐再继续。</FieldError>
</RadioGroup>
<Button class="mt-2 w-fit" type="submit">Submit</Button>
<p v-if="result" role="status" class="text-sm">{{ result }}</p>
</Form>
</template>
+64
View File
@@ -0,0 +1,64 @@
<script setup lang="ts">
import {
RadioGroup,
RadioContent,
RadioControl,
RadioIndicator,
Radio,
Description,
} from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-8">
<div class="flex flex-col gap-2">
<p class="text-sm font-medium text-muted">主要变体</p>
<RadioGroup default-value="option1" name="primary-plan" variant="primary">
<Radio value="option1">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
选项 1
</RadioContent>
<Description>默认背景的标准样式</Description>
</Radio>
<Radio value="option2">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
选项 2
</RadioContent>
<Description>另一种主要样式选项</Description>
</Radio>
</RadioGroup>
</div>
<div class="flex flex-col gap-2">
<p class="text-sm font-medium text-muted">次要变体</p>
<RadioGroup
default-value="option1"
name="secondary-plan"
variant="secondary"
>
<Radio value="option1">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
选项 1
</RadioContent>
<Description>用于表面上的低强调变体</Description>
</Radio>
<Radio value="option2">
<RadioContent>
<RadioControl>
<RadioIndicator />
</RadioControl>
选项 2
</RadioContent>
<Description>另一种次要样式选项</Description>
</Radio>
</RadioGroup>
</div>
</div>
</template>
+11 -5
View File
@@ -14,8 +14,8 @@
| button | 验证中(最小实现) | 基线全部 7 种变体、尺寸、isIconOnly/isDisabled/isPending;PressEvent 与 Vue click 差异见文档 |
| button-group | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| card | 验证中(最小实现) | 4 种表面变体;Header/Title/Description/Content/Footer 已实现;以基线 CSS 为准 |
| checkbox | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| checkbox-group | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| checkbox | 验证中(基线实现) | 原生 label/input;checked/isSelected、半选、primary/secondary、Content/Control/Indicator;15 个基线预览 |
| checkbox-group | 验证中(基线实现) | 数组模型、同名重复提交、required/readonly/disabled/reset、组标签与成员描述隔离;10 个基线预览 |
| chip | 验证中(最小实现) | color/size/variant;纯文本/数字自动包装为 ChipLabel;显式部件不重复包装;组合内容可动态切换 |
| color-area | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| color-field | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
@@ -66,8 +66,8 @@
| fieldset | 验证中(FORM-02) | 四部件、3 基线例与禁用验证例;响应式禁用、首 Legend 例外,边界见 FORM-02 |
| form | 验证中(基础设施) | native/aria 校验、FormData/reset、服务端错误;完整基线文档与生态集成未完成 |
| header | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| radio | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| radio-group | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| radio | 验证中(基线实现) | 原生 radio + Content/Control/Indicator;须在 RadioGroup 内,成员禁用/只读、作用域状态 |
| radio-group | 验证中(基线实现) | 标量模型、roving Tab/方向键/dir/loop、原生提交/校验/reset;12 个基线预览 |
| input-otp | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| alert | 验证中(最小实现) | status 五态;默认图标随 status;自定义 Indicator 空内容回退;内部 Surface 重置为 default |
| list-box | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
@@ -164,4 +164,10 @@ Card 图片、头像、横向布局、表单与自定义样式已补齐;Input
## FORM-02 当前范围
Fieldset 3/3、SearchField 15/15 预览已迁移,另有 Fieldset disabled 基建验证例。行为、差异与真实浏览器验证见 [FORM-02 报告](./migrations/FORM-02-fieldset-search-field.md)。Fieldset 禁用接入已有按钮/链接/切换/输入;TextField 内核移到 field/useTextField.ts 与 SearchField 共用。Checkbox/Radio 家族仍计划中,其底座已知缺口见 [选择字段协议准备](./decisions/selection-field-foundation.md)。不据此声明整套表单体系完成。
Fieldset 3/3、SearchField 15/15 预览已迁移,另有 Fieldset disabled 基建验证例。行为、差异与真实浏览器验证见 [FORM-02 报告](./migrations/FORM-02-fieldset-search-field.md)。Fieldset 禁用接入已有按钮/链接/切换/输入;TextField 内核移到 field/useTextField.ts 与 SearchField 共用。Checkbox/Radio 已在后续 FORM-03 实施,底座缺口与最终局部适配见 [选择字段协议](./decisions/selection-field-foundation.md)。不据此声明整套表单体系完成。
## FORM-03 Checkbox / Radio(2026-10-22)
10 个具名部件、四份样式与 tv、三个文档页、37/37 基线预览。使用原生 label/input 与共享 choice 状态层,接入既有 Form/Fieldset/Label/Description/FieldError,不运行 Reka 重复隐藏值层。详细差异、测试和浏览器记录见 [FORM-03 报告](./migrations/FORM-03-checkbox-radio.md)。
React render 自定义根类型不支持;原生 attrs/具名部件/作用域插槽替代框架机制;校验暂同步,不提供 validationDetails。RadioGroup 在同一表单的不同组需不同 name,遵循原生 HTML 分组规则。任意自定义 Vue 包装内部的 SSR 静态关联仍需显式 ID/ARIA。未宣称完整读屏、RTL、触屏、Nuxt、独立安装或逐像素一致。
+15 -9
View File
@@ -1,12 +1,12 @@
# Checkbox / Radio 分组协议准备(FORM-03 前置)
# Checkbox / Radio 分组协议(FORM-03)
日期:2026-10-22。固定 HeroUI ce90ea3;以锁文件中的 Reka 2.11.x 实际安装代码为依据。
这是集成人下一阶段的实施边界与已验证缺口,**不是已实现的 Checkbox / Radio 公共组件**。
前置探针记录保留在下方;FORM-03 已实现 Checkbox/CheckboxGroup、Radio/RadioGroup 及其部件。行为与验收边界见 [实施报告](../migrations/FORM-03-checkbox-radio.md)。
## 已经可以复用的设施
- `field/disabled.ts` 提供响应式禁用作用域;Fieldset 已处理父级禁用合并和首个直接 Legend 例外。新的 Reka Root 与其真实表单值层都必须接入,不能只改视觉 data 属性。
- `field/disabled.ts` 提供响应式禁用作用域;Fieldset 已处理父级禁用合并和首个直接 Legend 例外。选择字段的真实输入与组约束层都必须接入,不能只改视觉 data 属性。
- `field/context.ts` 的表单策略与错误数据源继续沿用,Description/FieldError 的 ID 与错误展示协议不能另起一套。组字段需要明确的 group 语义与 Label aria-labelledby 注册;不把组标签的 for 指向 div,也不把每个组选项的必填星号重复展示。
- 单文本字段 `useTextField` 不承载集合模型。分组值使用 Vue 数组/标量状态协议,校验/原生字段层应与文本内核分开,但接入相同 Form。
@@ -23,13 +23,19 @@
- Checkbox 二态使用 v-model:checked;indeterminate 独立状态,不能当作真实提交值。CheckboxGroup 使用 v-model 字符串数组,空集合=[];RadioGroup 使用 v-model 字符串或 undefined,空值不提交。
- 原生提交沿用 HTML 语义:CheckboxGroup 每个选中且可用成员产生同名 name/value 条目,通过 FormData.getAll(name) 读取;不默认改名为 name[0],不提交禁用成员。Radio 提交唯一的选中可用值。成员自身 disabled 与组/Fieldset 禁用合并。
- Reka 仅提供交互/roving focus,不给其 Root 注入 name;本库维护唯一的原生表单值层,避免其隐藏项与本库项重复。动态 name/form、移除选项、禁用选项与 controlled 值拒绝都要验证实际 FormData。
- required 对 CheckboxGroup 是“至少选择一个可用成员”,不能给每个原生 checkbox 同时 required。RadioGroup 要求一项;native 拦截与首个可用可见控件聚焦由组适配层实现,aria 模式仅报告错误。不能新增无 name 的隐藏校验字段污染 FormData,也不能将 invalid 直接当作约束失败。
- **最终局部适配:这两个家族使用原生 label/input,不运行 Reka Checkbox/Radio Root。** 固定基线本身采用 CheckboxField/CheckboxButton、RadioField/RadioButton 的 label+input 组合。原生输入承载唯一提交值、Space 与点击;共享 choice 层承载组模型/校验/reset/成员注册,Radio 的方向键与单一 Tab 停靠点由薄适配实现。未引入第二套无样式库。动态 name/form、移除选项、禁用选项与 controlled 值拒绝必须验证实际 FormData。
- required 对 CheckboxGroup 是“至少选择一个可用成员”,不能给每个原生 checkbox 同时 required。RadioGroup 要求一项;native 拦截与首个可用可见控件聚焦由组适配层实现,aria 模式仅报告错误。组用无 name、aria-hidden、tabindex=-1 的 checkbox 代理承载组约束,且必须验证其不产生 FormData 条目;不能生成额外有名值,也不能将 invalid 直接当作约束失败。
- reset 监听原生 form,非受控恢复初始副本,受控保留父级值;preventDefault 的 reset 保留当前状态。监听随 form 关联/卸载更新,数组必须复制,不能直接改 props。
- 组/成员 readonly 必须阻止鼠标、空格、方向键引起的值更新,并保留可聚焦性;拒绝更新后 Reka 的可见状态和原生值层必须恢复一致。
- 组/成员 readonly 必须阻止鼠标、空格、方向键引起的值更新,并保留可聚焦性;拒绝更新后 data 状态和原生值层必须恢复一致。
- 单一组选项注册表负责可用成员与焦点目标;稳定 key、条件插槽、成员重排、动态值、空组与重复值有明确策略。正式实现前用行为测试确定异常处理,不静默选择另一个成员。
- 读屏关联、orientation/dir/loop 和键盘行为按固定基线验收;CheckboxGroup 是否采用 Reka 默认 rovingFocus=true 需对照上游实际键盘契约,不能默认继承。
- 读屏关联、orientation/dir/loop 和键盘行为按固定基线验收;CheckboxGroup 保留原生逐项 Tab,RadioGroup 单停靠点,不继承 Reka CheckboxGroup 默认 rovingFocus=true。
## 下一阶段完成条件
## 当前交付与后续边界
先做 Checkbox/CheckboxGroup 的真实状态与原生值层,再做 Radio/RadioGroup,并覆盖提交/reset、required 聚焦、readonly 键盘路径、Fieldset 嵌套、SSR/水合和成员变化。通过这些验证后才交出其文档/样式扩展任务。当前可继续交给其他 AI 的仍是 Typography、EmptyState、Breadcrumbs;不把这些分组协议准备写成 UI 已迁移。
- Checkbox 使用 `v-model:checked`,兼容 `isSelected`;defaultChecked 显式存在才优先于 defaultSelected,不能让 Vue Boolean 的隐式 false 吞掉别名。半选是独立外观状态。
- CheckboxGroup 用 `string[]`,RadioGroup 用 `string | undefined`;类型不可合并成宽泛联合。组拥有 name/form,成员不重复注入。缺少 name 不提交;移除成员不替调用者清理模型,实际提交仅包含现存可用项。重复 value(含动态变化)报错。
- Checkbox 可用成员逐项 Tab;Radio 选中可用成员或第一个可用成员为 Tab 停靠点。方向键/Home/End、dir/loop、禁用跳过、readonly、调用者取消和 IME 有专项测试。只读成员可被方向键聚焦但不能被改选。
- 组 Label 使用 span + aria-labelledby;成员 Content 是 label;Description/FieldError 在成员上下文隔离,并合并组说明/错误。SSR 支持本库 Content 插槽以及直接/原生/Fragment 包裹;任意用户 Vue 包装仍需显式 ID 和 ARIA 关联。
- 校验继承 Form native/aria;组 required 是至少一个现存可用选择。isInvalid 仅展示,readonly 保留值并跳过约束;无效组聚焦可见成员,空组聚焦根。同步 validate、服务端 validationErrors 编辑消退/新响应恢复已验证;异步校验和 validationDetails 未扩展。
- 37 个基线预览:Checkbox 15、CheckboxGroup 10、RadioGroup 12,含自定义指示器、render、表单、全选、功能卡片和配送支付。预览/高亮/复制复用 SFC,自定义图标用 Tabler。
- 后续其他 AI 可做 Typography、EmptyState、Breadcrumbs 等展示任务;本协议与 choice 内核继续由集成人维护。复杂集合/弹层/日期等先另定共享协议,不能套用 choice 值模型。
+41
View File
@@ -0,0 +1,41 @@
# FORM-03 Checkbox / Radio
日期:2026-10-22。起始 HEAD `a4fb3c5`,初始工作区干净;由集成人实施。
## 实现与基线
- Checkbox / CheckboxContent / CheckboxControl / CheckboxIndicator / CheckboxGroup,Radio / RadioContent / RadioControl / RadioIndicator / RadioGroup,共 10 个具名导出及 Props 类型。
- `choice/{shared,context,group,item}` 管理值、成员、组键盘、错误、reset;接入同一 Form/Fieldset/Label/Description/FieldError 协议。Label 增加 group span + ID 注册,不改变文本字段的原生 label。
- 已安装 Reka 的 CheckboxGroup 有禁用隐藏值仍提交、带索引序列化、reset 不恢复的实证缺口;固定上游也采用 Field/Button 的 label+input 结构,因此局部采用原生 label/input。原生 input 是唯一有名提交层,组代理无 name、aria-hidden、tabindex=-1,不产生值。不引入新运行时依赖。
- 单 Checkbox boolean(checked 优先 isSelected)、组数组、Radio 组标量分别定义类型。defaultChecked 未传时不能隐式 false 覆盖 defaultSelected;控制属性动态添加/删除(含显式 undefined)会同步真实输入。
- Checkbox 每项 Tab,Radio 单 Tab 停靠点 + 方向键/Home/End/dir/loop/禁用跳过;调用者事件取消优先,readonly 不更新。组标签和成员说明隔离;Content 内说明支持 SSR 静态规划。
- 四份 CSS 和 tv 来自 ce90ea3。还原 hv-、去注释/空白并还原 reduced-motion 等价 media 后,CSS 与固定基线一致;将嵌套伪元素的 motion-reduce 改为原生媒体查询以消除 Tailwind 生成的无效选择器。RadioIndicator 保持真实 :empty;单选 data-selected 未选中时移除。
## 文档与演示
- Checkbox 15/15、CheckboxGroup 10/10、RadioGroup 12/12,保留标题、文案、顺序、变体、on-surface、自定义指示器、render、全选、功能卡片、配送支付;共 37 份可运行 SFC。
- Vue 状态/插槽/事件替代 React 机制;默认图形精确来自基线,示例自定义图标用 Tabler。预览、复制、高亮共用 SFC;FormData 反馈代替 alert,不执行真实业务。
- Radio 水平示例补外部标签显式关联;窄屏解除固定最小宽度。公共 Demo 支持可选 align/isBgSolid,以保留配送支付基线预览配置。
- API 明确实际属性/事件/插槽/focus/element、原生表单语义、校验策略和 SSR 包装边界;表格铺满正文并自动换行。
## 验证
- `pnpm test`:16 文件 / 259 项,含 node SSR 5 项。
- `pnpm test:unit`:15 文件 / 254 项,不含 node SSR,含实际 jsdom 水合。
- 新增 choice 行为 30 项、37 个预览挂载/清单 2 项、node SSR 1 项:同名多值/禁用省略、受控拒绝与控制归属切换、默认值别名、reset/取消、整组 required/aria/readonly/空组聚焦、外部动态 form/name、成员重排/移除/恢复、RTL 方向键/禁用跳过/事件取消、组/成员说明关联、服务端错误消退及新响应恢复、SSR 水合与动态 ID/attrs。
- typecheck/build:docs/format/diff-check 通过。build:docs 保留既有大于 500kB 文档 chunk 提醒,CSS 语法警告已消除。
- dist 公共 Props 经临时 vue-tsc 正反例验证:boolean/数组/标量与合法变体可用;mixed 字符串、错误模型类型、非法变体、异步 validate、缺少 Radio.value 均被拒绝。探针已移除,不计入测试数量。
## 真实浏览器(127.0.0.1:5173,CUA)
- Checkbox 原生 Space 切换与半选→全选、默认选中、展开代码后的实际 Shiki 多色 token 已确认。
- CheckboxGroup 未选提交显示错误并聚焦真实 email checkbox;选择 email、sms 后反馈 `已选偏好:email, sms`。全选示例从半选变为全部选中。
- RadioGroup 方向键从 premium 到 business 后唯一选中且唯一 tabindex=0;无效提交聚焦实际 starter radio,随后选 pro 提交反馈正确。配送卡片点击标准后选中边框 rgb(0,111,238),原快递卡片移除边框。
- 三页桌面 1280×900 表格全部 736px;390×844 全部 350px,无页面/预览水平溢出。深浅主题、功能卡片与配送支付窄屏布局检查通过。控制台 warn/error 为空,主题/临时视口已恢复。
- 浅色 1280×900 配送支付截图:`/private/tmp/heroui-vue-form03-radio.png`。
## 边界与后续
未完成独立安装、自动逐像素、完整读屏/触屏/RTL、Nuxt 验收。RTL 单元键盘验证不等于整站 RTL 验收。同步 validate,不提供完整 RAC validationDetails;render 自定义根类型不支持。任意用户 Vue 包装内部的 SSR 关联仍需显式 ID/ARIA;不同 RadioGroup 在同一 form 使用不同 name,遵循 HTML 原生分组语义。
共享 choice/field/Form/Fieldset 内核继续由集成人维护;Typography、EmptyState、Breadcrumbs 等低冲突展示任务可交给其他 AI。集合、弹层、日期等需另立状态与交互协议。
+9 -1
View File
@@ -3,7 +3,7 @@
- 项目:https://github.com/heroui-inc/heroui
- 基线版本:3.2.6
- 提交:ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960
- 本次更新:2026-10-21
- 本次更新:2026-10-22
## 已移植
@@ -59,3 +59,11 @@
## FORM-02 来源(2026-10-22)
同一固定 HeroUI 3.2.6 / ce90ea3 基线:packages/react/src/components/{fieldset,search-field}、packages/styles/components/{fieldset,search-field}.css、packages/styles/src/components/{fieldset,search-field}、CN (forms)/{fieldset,search-field}.mdx 与 demos/cn/{fieldset,search-field}。默认搜索 SVG 精确移植 icons.tsx 的 IconSearch,保留默认 CloseButton 图标;文档自定义图标为 Tabler。源 CSS 仅 hv- 命名空间、Vue状态适配与格式;继续保留 third-party/HEROUI-LICENSE(Apache-2.0)。演示将 alert/console 输出改为实际 FormData/模拟提交状态反馈,定时器与事件清理;Surface 的桌面 min-width 在窄屏解除。
## FORM-03 来源(2026-10-22)
固定 ce90ea3 / HeroUI 3.2.6 的 packages/react/src/components/{checkbox,checkbox-group,radio,radio-group}、packages/styles/components/{checkbox,checkbox-group,radio,radio-group}.css 与同名 tv 映射、CN (forms)/{checkbox,checkbox-group,radio-group}.mdx 和 demos/cn 对应目录。Checkbox 默认勾选/半选 SVG 精确移植 checkbox.tsx,保留 Apache-2.0 来源与 third-party/HEROUI-LICENSE;Radio 默认点由 CSS :empty::before 渲染。
CSS 仅 hv- 命名空间及 reduced-motion 的等价原生 media 适配(避免 Tailwind 嵌套伪元素生成无效 :not(:is()));规范化后其余样式与基线相同。原生输入与组约束代理的隐藏样式在 index.css 明确维护。Vue 行为实现见 selection-field-foundation.md,不移植 RAC runtime。
37 个文档引用预览全部迁移。自定义图标使用 Tabler(Heart/Plus/Minus/X/Mail/Message/Bell/Check 与三种支付品牌图标),没有复制 React 图标依赖或在示例内自绘 SVG。表单 alert 改为 role=status 的真实 FormData 反馈;水平 Radio 示例补外部 Label 的显式 aria-labelledby;固定宽度卡片在窄屏解除最小宽度,保留桌面基线布局。Demo 仅补 align/isBgSolid 可选配置,对应上游配送支付预览配置。
+6
View File
@@ -274,3 +274,9 @@
CheckboxGroup 底座行为临时探针单独验证了禁用值仍提交与 reset 不恢复,1 项运行后移除,不计入最终226项;不能将它描述为本库已支持分组。
公共 dist 类型探针由 vue-tsc 验证:Fieldset disabled、SearchField 合法 variant/modelValue 可用,非法 variant、数字 modelValue 和异步 validate 被拒绝。临时探针移除。新增 SSR 预规划覆盖叶子初始值的 empty 状态,显式控件 ID 删除后恢复自动 ID。
## FORM-03(2026-10-22)
详细架构、差异与证据见 [Checkbox/Radio 报告](./migrations/FORM-03-checkbox-radio.md)。最终 `pnpm test` 16 文件 / 259 项(含 node SSR 5);`pnpm test:unit` 15 文件 / 254 项(不含 node SSR,包含 jsdom 水合);typecheck/build:docs/format/diff-check 通过。37 个预览均可挂载,且顺序与基线清单相同;CSS 规范化比对通过(hv- 与等价 reduced-motion media 差异已记录)。临时 dist Props 正反类型探针通过并移除。
浏览器在 5173 实测 Checkbox Space/默认值/半选、CheckboxGroup required 聚焦/同名多值提交/全选、RadioGroup 方向键与 roving Tab/校验聚焦/实际提交、配送卡片选中边框。三个页面桌面表格 736px、390 窄屏表格 350px,均无横向溢出;浅深主题、定制卡片、代码实际多色高亮已检查。warn/error 为空,恢复浅色与默认视口;截图 `/private/tmp/heroui-vue-form03-radio.png`。没有新增独立安装、自动视觉、完整读屏/触屏/RTL 或 Nuxt 验收。
+1 -1
View File
@@ -15,7 +15,7 @@
"build:docs": "pnpm build && pnpm --filter @heroui-vue/docs build",
"typecheck": "vue-tsc --noEmit",
"test": "vitest run",
"test:unit": "vitest run tests/fieldset-search-field.test.ts tests/components.test.ts tests/composition.test.ts tests/docs-search.test.ts tests/button-demos.test.ts tests/aligned-components.test.ts tests/surface-link-spinner.test.ts tests/close-button-avatar-skeleton.test.ts tests/separator-kbd-chip.test.ts tests/badge-alert.test.ts tests/input-group.test.ts tests/field-docs-textarea.test.ts tests/field-foundation.test.ts",
"test:unit": "vitest run tests/choice-demos.test.ts tests/choice-fields.test.ts tests/fieldset-search-field.test.ts tests/components.test.ts tests/composition.test.ts tests/docs-search.test.ts tests/button-demos.test.ts tests/aligned-components.test.ts tests/surface-link-spinner.test.ts tests/close-button-avatar-skeleton.test.ts tests/separator-kbd-chip.test.ts tests/badge-alert.test.ts tests/input-group.test.ts tests/field-docs-textarea.test.ts tests/field-foundation.test.ts",
"test:ssr": "vitest run tests/ssr.test.ts",
"format": "prettier --check .",
"format:fix": "prettier --write .",
@@ -0,0 +1,9 @@
/* Adapted from HeroUI ce90ea3. Copyright 2025 NextUI Inc.
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix. */
.hv-checkbox-group {
@apply flex flex-col;
[data-slot="checkbox"] {
@apply mt-4;
}
}
+269
View File
@@ -0,0 +1,269 @@
/* Adapted from HeroUI ce90ea3. Copyright 2025 NextUI Inc.
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix; native reduced-motion media. */
/* ==========================================================================
Base checkbox styles
========================================================================== */
.hv-checkbox {
@apply flex flex-col items-start gap-1 outline-none no-highlight;
cursor: var(--cursor-interactive);
/* Field-level help text (siblings of the button), indented to align under the label */
& > [data-slot="description"],
& > [data-slot="field-error"] {
@apply w-full min-w-0 cursor-default ps-7 text-xs text-wrap wrap-break-word text-muted select-none;
}
[data-slot="label"] {
@apply select-none;
}
.hv-checkbox__content [data-slot="label"] {
cursor: var(--cursor-interactive);
}
/* Disabled state */
&[data-disabled="true"] {
@apply status-disabled;
[data-slot="description"],
[data-slot="field-error"] {
@apply status-disabled;
}
}
/* Indicator styles */
&[data-selected="true"],
&[data-indeterminate="true"] {
.hv-checkbox__indicator {
border-color: var(--accent-foreground);
}
}
/* Checkmark SVG indicator */
[data-slot="checkbox-default-indicator--checkmark"] {
@apply size-2.5 stroke-[2.5px] text-accent-foreground;
/**
* Transitions
*/
@apply transition-all duration-200 motion-reduce:transition-none;
}
&[data-selected="true"] [data-slot="checkbox-default-indicator--checkmark"] {
transition: stroke-dashoffset 150ms linear 15ms;
}
/* Invalid + Selected: checkmark icon color */
&[data-invalid="true"][data-selected="true"]
[data-slot="checkbox-default-indicator--checkmark"],
&[data-invalid="true"][aria-checked="true"]
[data-slot="checkbox-default-indicator--checkmark"],
&[aria-invalid="true"][data-selected="true"]
[data-slot="checkbox-default-indicator--checkmark"],
&[aria-invalid="true"][aria-checked="true"]
[data-slot="checkbox-default-indicator--checkmark"] {
@apply text-danger-foreground;
}
/* Indeterminate line indicator */
&[data-indeterminate="true"] {
[data-slot="checkbox-default-indicator--indeterminate"] {
@apply size-3;
}
}
/* Invalid + Indeterminate: indeterminate icon color */
&[data-indeterminate="true"][data-invalid="true"]
[data-slot="checkbox-default-indicator--indeterminate"],
&[data-indeterminate="true"][aria-invalid="true"]
[data-slot="checkbox-default-indicator--indeterminate"] {
@apply text-danger-foreground;
}
}
/* ==========================================================================
Checkbox control (the square button)
========================================================================== */
.hv-checkbox__control {
@apply relative inline-flex size-4 shrink-0 items-center justify-center overflow-hidden rounded-md border [border-width:var(--border-width-field)] border-field-border bg-field shadow-field outline-none no-highlight;
/**
* Transitions
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
*/
transition:
background-color 200ms var(--ease-out),
border-color 200ms var(--ease-out),
transform 100ms var(--ease-out);
@media (prefers-reduced-motion: reduce) {
transition: none;
}
cursor: var(--cursor-interactive);
/* Background indicator pseudo-element */
&::before {
@apply pointer-events-none absolute inset-0 z-0 origin-center scale-70 rounded-md bg-accent opacity-0 content-[''];
/**
* Transitions
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
*/
transition:
scale 100ms var(--ease-linear),
opacity 200ms var(--ease-linear),
background-color 200ms var(--ease-out);
@media (prefers-reduced-motion: reduce) {
transition: none;
}
}
/* Interactive states */
/* Focus */
.hv-checkbox:focus-visible &,
.hv-checkbox:has([data-slot="checkbox-content"][data-focus-visible="true"]) &,
.hv-checkbox [data-slot="checkbox-content"][data-focus-visible="true"] & {
@apply status-focused;
}
/* Hover */
.hv-checkbox:hover &,
.hv-checkbox:has([data-slot="checkbox-content"][data-hovered="true"]) &,
.hv-checkbox [data-slot="checkbox-content"][data-hovered="true"] & {
@apply border-field-border-hover;
&::before {
@apply bg-accent-hover;
}
}
/* Pressed */
.hv-checkbox:active &,
.hv-checkbox:has([data-slot="checkbox-content"][data-pressed="true"]) &,
.hv-checkbox [data-slot="checkbox-content"][data-pressed="true"] & {
}
/* Selection states */
/* Selected */
.hv-checkbox[aria-checked="true"] &,
.hv-checkbox[data-selected="true"] & {
@apply border-transparent text-accent-foreground;
&::before {
@apply scale-100 opacity-100;
}
}
/* Indeterminate */
.hv-checkbox[data-indeterminate="true"] & {
@apply bg-accent text-accent-foreground;
}
/* Indeterminate + Pressed */
.hv-checkbox:active[data-indeterminate="true"] &,
.hv-checkbox[data-pressed="true"][data-indeterminate="true"] &,
.hv-checkbox:has(
[data-slot="checkbox-content"][data-pressed="true"]
)[data-indeterminate="true"]
& {
@apply bg-accent-hover;
}
/* Validation states */
/* Invalid (only when not selected/indeterminate) */
.hv-checkbox[data-invalid="true"]:not([aria-checked="true"]):not(
[data-selected="true"]
):not([data-indeterminate="true"])
&,
.hv-checkbox[aria-invalid="true"]:not([aria-checked="true"]):not(
[data-selected="true"]
):not([data-indeterminate="true"])
& {
@apply status-invalid-field;
}
/* Invalid + Selected */
.hv-checkbox[data-invalid="true"][aria-checked="true"] &,
.hv-checkbox[data-invalid="true"][data-selected="true"] &,
.hv-checkbox[aria-invalid="true"][aria-checked="true"] &,
.hv-checkbox[aria-invalid="true"][data-selected="true"] & {
@apply border-transparent bg-danger text-danger-foreground;
&::before {
@apply scale-100 bg-danger opacity-100;
}
}
/* Invalid + Indeterminate */
.hv-checkbox[data-indeterminate="true"][aria-invalid="true"] &,
.hv-checkbox[data-indeterminate="true"][data-invalid="true"] & {
@apply bg-danger text-danger-foreground;
}
}
/* ==========================================================================
Checkbox indicator
========================================================================== */
.hv-checkbox__indicator {
@apply relative z-10 flex size-3 items-center justify-center;
& svg {
@apply size-full transform-gpu;
}
}
/* ==========================================================================
Variant property definitions
========================================================================== */
.hv-checkbox--primary {
/* Default styles */
}
.hv-checkbox--secondary .hv-checkbox__control {
@apply shadow-none;
background-color: var(--checkbox-control-bg);
--checkbox-control-bg: var(--default);
/* Hover state */
.hv-checkbox:hover &,
.hv-checkbox:has([data-slot="checkbox-content"][data-hovered="true"]) &,
.hv-checkbox [data-slot="checkbox-content"][data-hovered="true"] & {
@apply border-field-border-hover;
}
}
/* Checkbox content — the clickable label (control + label text) */
.hv-checkbox__content {
@apply relative inline-flex cursor-[inherit] items-center gap-3 text-sm font-medium text-foreground outline-none select-none no-highlight;
}
/* Unselected state background for secondary variant */
.hv-checkbox--secondary:not([aria-checked="true"]):not(
[data-selected="true"]
):not([data-indeterminate="true"])
.hv-checkbox__control {
background-color: var(--checkbox-control-bg);
}
/* Selected state on secondary variant */
.hv-checkbox--secondary[aria-checked="true"] .hv-checkbox__control,
.hv-checkbox--secondary[data-selected="true"] .hv-checkbox__control {
&::before {
@apply bg-accent;
}
}
/* Indeterminate state on secondary variant */
.hv-checkbox--secondary[data-indeterminate="true"] .hv-checkbox__control {
@apply bg-accent;
&::before {
@apply bg-accent;
}
}
@@ -0,0 +1,53 @@
/* Adapted from HeroUI ce90ea3. Copyright 2025 NextUI Inc.
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix. */
/* Radio Group base styles */
.hv-radio-group {
@apply flex flex-col;
/* Default orientation */
&[data-orientation="vertical"] {
[data-slot="radio"] {
@apply mt-4;
}
}
&[data-orientation="horizontal"] {
@apply flex-row flex-wrap gap-4;
}
}
/* Variant property definitions */
.hv-radio-group--primary {
/* Default styles */
}
.hv-radio-group--secondary .hv-radio__control {
@apply shadow-none;
background-color: var(--radio-control-bg);
--radio-control-bg: var(--default);
--radio-control-bg-hover: var(--default-hover);
/* Hover state */
.hv-radio:has([data-slot="radio-content"][data-hovered="true"]) &,
.hv-radio [data-slot="radio-content"][data-hovered="true"] & {
@apply border-field-border-hover;
}
/* Default indicator color (unselected) */
.hv-radio:not([data-selected]):not(:has(input:checked))
&
.hv-radio__indicator:empty::before {
background-color: var(--radio-control-bg);
}
/* Hover indicator color (unselected) */
.hv-radio:has([data-slot="radio-content"][data-hovered="true"]):not(
[data-selected]
):not(:has(input:checked))
& {
.hv-radio__indicator:empty::before {
background-color: var(--radio-control-bg-hover);
}
}
}
+193
View File
@@ -0,0 +1,193 @@
/* Adapted from HeroUI ce90ea3. Copyright 2025 NextUI Inc.
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix; native reduced-motion media. */
/* ==========================================================================
Base radio styles
Structure (explicit composition):
.hv-radio → RadioField wrapper (column)
.hv-radio__content → RadioButton: the clickable row (control + label)
.hv-radio__control
[data-slot="label"]
[data-slot="description"] → field-level sibling, below the row
[data-slot="field-error"]
========================================================================== */
.hv-radio {
@apply flex flex-col items-start gap-1 outline-none no-highlight;
cursor: var(--cursor-interactive);
[data-slot="label"] {
@apply select-none;
}
.hv-radio__content [data-slot="label"] {
cursor: var(--cursor-interactive);
}
/* Field-level help text (siblings of the button), indented to align under the label */
& > [data-slot="description"],
& > [data-slot="field-error"] {
@apply w-full min-w-0 cursor-default ps-7 text-xs text-wrap wrap-break-word text-muted select-none;
}
/* Disabled state */
&:disabled,
&[data-disabled="true"],
&[aria-disabled="true"] {
@apply status-disabled;
[data-slot="description"],
[data-slot="field-error"] {
@apply status-disabled;
}
}
}
/* Radio content — the clickable label (control + label text) */
.hv-radio__content {
@apply relative inline-flex cursor-[inherit] items-center gap-3 text-sm font-medium text-foreground outline-none select-none no-highlight;
}
/* ==========================================================================
Radio control (the circular button)
========================================================================== */
.hv-radio__control {
@apply relative inline-flex size-4 shrink-0 items-center justify-center rounded-lg border [border-width:var(--border-width-field)] border-field-border bg-field shadow-field outline-none no-highlight;
/**
* Transitions
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
*/
transition:
background-color 200ms var(--ease-out),
border-color 200ms var(--ease-out),
transform 100ms var(--ease-out);
@media (prefers-reduced-motion: reduce) {
transition: none;
}
cursor: var(--cursor-interactive);
/* Interactive states */
/* Focus */
.hv-radio:has([data-slot="radio-content"][data-focus-visible="true"]) &,
.hv-radio [data-slot="radio-content"][data-focus-visible="true"] & {
@apply status-focused;
}
/* Hover */
.hv-radio:has([data-slot="radio-content"][data-hovered="true"]) &,
.hv-radio [data-slot="radio-content"][data-hovered="true"] & {
@apply border-field-border-hover;
}
/* Hover - only when not selected */
.hv-radio:has([data-slot="radio-content"][data-hovered="true"]):not(
[data-selected]
):not(:has(input:checked))
& {
.hv-radio__indicator:empty::before {
@apply bg-field-hover;
}
}
/* Pressed */
.hv-radio:has([data-slot="radio-content"][data-pressed="true"]) &,
.hv-radio [data-slot="radio-content"][data-pressed="true"] & {
@apply scale-95;
}
/* Selection states */
/* Selected */
.hv-radio[data-selected] &,
.hv-radio:has([data-slot="radio-content"][aria-checked="true"]) &,
.hv-radio:has(input:checked) & {
@apply border-transparent bg-accent;
}
/* Selected + Pressed */
.hv-radio[data-selected]:has([data-slot="radio-content"][data-pressed="true"])
&,
.hv-radio:has(
[data-slot="radio-content"][data-pressed="true"][aria-checked="true"]
)
&,
.hv-radio:has(input:checked):has(
[data-slot="radio-content"][data-pressed="true"]
)
& {
@apply bg-accent-hover;
}
/* Validation states */
/* Invalid */
.hv-radio[data-invalid="true"] &,
.hv-radio[aria-invalid="true"] & {
@apply status-invalid-field;
}
/* Invalid + Selected */
.hv-radio[data-invalid="true"][data-selected] &,
.hv-radio[aria-invalid="true"][data-selected] &,
.hv-radio[data-invalid="true"]:has(input:checked) &,
.hv-radio[aria-invalid="true"]:has(input:checked) & {
@apply status-invalid-field;
}
}
/* ==========================================================================
Radio indicator (the inner dot)
========================================================================== */
.hv-radio__indicator {
@apply absolute inset-0 flex items-center justify-center;
pointer-events: none;
}
/* :empty pseudo-class ensures these styles only apply when the indicator has no custom children
(e.g., custom icon). When custom content is present, these default dot styles are not applied. */
.hv-radio__indicator:empty::before {
content: "";
@apply rounded-lg bg-field;
width: 100%;
height: 100%;
scale: 1;
/**
* Transitions
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
*/
transition:
scale 200ms var(--ease-out),
background-color 200ms var(--ease-out);
@media (prefers-reduced-motion: reduce) {
transition: none;
}
}
/* Selected state */
.hv-radio[data-selected] .hv-radio__indicator:empty::before,
.hv-radio:has([data-slot="radio-content"][aria-checked="true"])
.hv-radio__indicator:empty::before,
.hv-radio:has(input:checked) .hv-radio__indicator:empty::before {
@apply bg-accent-foreground;
scale: 0.4286; /* 6px */
}
/* Selected + Pressed state */
.hv-radio[data-selected]:has([data-slot="radio-content"][data-pressed="true"])
.hv-radio__indicator:empty::before,
.hv-radio:has(
[data-slot="radio-content"][data-pressed="true"][aria-checked="true"]
)
.hv-radio__indicator:empty::before,
.hv-radio:has(input:checked):has(
[data-slot="radio-content"][data-pressed="true"]
)
.hv-radio__indicator:empty::before {
scale: 0.5714; /* 8px */
}
+23
View File
@@ -77,3 +77,26 @@
pointer-events: auto;
}
}
@import "./components/checkbox.css" layer(components);
@import "./components/checkbox-group.css" layer(components);
@import "./components/radio.css" layer(components);
@import "./components/radio-group.css" layer(components);
@layer components {
.hv-choice-input,
.hv-choice-validation {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
}
+65
View File
@@ -574,3 +574,68 @@ export const searchFieldVariants = tv({
});
export type SearchFieldVariants = VariantProps<typeof searchFieldVariants>;
export const checkboxVariants = tv({
defaultVariants: {
variant: "primary",
},
slots: {
base: "hv-checkbox",
content: "hv-checkbox__content",
control: "hv-checkbox__control",
indicator: "hv-checkbox__indicator",
},
variants: {
variant: {
primary: {
base: "hv-checkbox--primary",
},
secondary: {
base: "hv-checkbox--secondary",
},
},
},
});
export type CheckboxVariants = VariantProps<typeof checkboxVariants>;
export const checkboxGroupVariants = tv({
base: "hv-checkbox-group",
defaultVariants: {
variant: "primary",
},
variants: {
variant: {
primary: "hv-checkbox-group--primary",
secondary: "hv-checkbox-group--secondary",
},
},
});
export type CheckboxGroupVariants = VariantProps<typeof checkboxGroupVariants>;
export const radioVariants = tv({
slots: {
base: "hv-radio",
content: "hv-radio__content",
control: "hv-radio__control",
indicator: "hv-radio__indicator",
},
});
export type RadioVariants = VariantProps<typeof radioVariants>;
export const radioGroupVariants = tv({
base: "hv-radio-group",
defaultVariants: {
variant: "primary",
},
variants: {
variant: {
primary: "hv-radio-group--primary",
secondary: "hv-radio-group--secondary",
},
},
});
export type RadioGroupVariants = VariantProps<typeof radioGroupVariants>;
@@ -0,0 +1,11 @@
<script lang="ts">
import { defineComponent, h } from "vue";
import ChoiceContent from "../choice/ChoiceContent.vue";
export default defineComponent({
name: "CheckboxContent",
inheritAttrs: false,
setup(_, { attrs, slots }) {
return () => h(ChoiceContent, attrs, slots);
},
});
</script>
@@ -0,0 +1,16 @@
<script setup lang="ts">
import { inject } from "vue";
import { choiceKey } from "../choice/context";
defineOptions({ inheritAttrs: false });
const context = inject(choiceKey);
if (!context) throw new Error("CheckboxControl must be inside Checkbox");
</script>
<template>
<span
v-bind="$attrs"
:class="[context.slots.value.control(), $attrs.class]"
data-slot="checkbox-control"
>
<slot v-bind="context.state()"></slot>
</span>
</template>
@@ -0,0 +1,49 @@
<script setup lang="ts">
// Default SVGs adapted from HeroUI ce90ea3 checkbox.tsx, Copyright 2025 NextUI Inc.
// See third-party/HEROUI-LICENSE (Apache-2.0).
import { inject } from "vue";
import { choiceKey } from "../choice/context";
defineOptions({ inheritAttrs: false });
const context = inject(choiceKey);
if (!context) throw new Error("CheckboxIndicator must be inside Checkbox");
</script>
<template>
<span
v-bind="$attrs"
:class="[context.slots.value.indicator(), $attrs.class]"
aria-hidden="true"
data-slot="checkbox-indicator"
>
<slot v-bind="context.state()">
<svg
v-if="context.state().isIndeterminate"
aria-hidden="true"
data-slot="checkbox-default-indicator--indeterminate"
fill="none"
role="presentation"
stroke="currentColor"
stroke-linecap="round"
stroke-width="3"
viewBox="0 0 24 24"
>
<line x1="21" x2="3" y1="12" y2="12" />
</svg>
<svg
v-else
aria-hidden="true"
data-slot="checkbox-default-indicator--checkmark"
fill="none"
role="presentation"
stroke="currentColor"
stroke-dasharray="22"
:stroke-dashoffset="context.state().isSelected ? 44 : 66"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
viewBox="0 0 17 18"
>
<polyline points="1 9 7 14 15 4" />
</svg>
</slot>
</span>
</template>
@@ -0,0 +1,61 @@
<script setup lang="ts">
import { inject } from "vue";
import { choiceKey } from "./context";
defineOptions({ inheritAttrs: false });
const context = inject(choiceKey);
if (!context) throw new Error("ChoiceContent must be inside Checkbox or Radio");
</script>
<template>
<label
v-bind="$attrs"
:class="[context.slots.value.content(), $attrs.class]"
:data-slot="`${context.kind}-content`"
:data-selected="context.state().isSelected || undefined"
:data-indeterminate="context.state().isIndeterminate || undefined"
:data-disabled="context.field.disabled.value || undefined"
:data-hovered="context.hover.value || undefined"
:data-pressed="context.pressed.value || undefined"
:data-focus-visible="context.focusVisible.value || undefined"
@pointerenter="context.hover.value = !context.field.disabled.value"
@pointerleave="
context.hover.value = false;
context.pressed.value = false;
"
@pointerdown="
context.pressed.value =
!context.field.disabled.value && !context.field.readOnly.value
"
@pointerup="context.pressed.value = false"
>
<input
:ref="
(el) =>
context &&
(context.input.value = el ? (el as HTMLInputElement) : undefined)
"
@click.capture="context.guard"
@keydown.capture="context.keydown"
@keydown.space="
context.pressed.value =
!context.field.disabled.value && !context.field.readOnly.value
"
@keyup="context.pressed.value = false"
v-bind="context.inputAttrs()"
class="hv-choice-input"
@change="context.onChange"
@invalid="context.onInvalid"
@focus="
context.focused.value = true;
context.focusVisible.value = ($event.target as HTMLElement).matches(
':focus-visible',
);
"
@blur="
context.focused.value = false;
context.focusVisible.value = false;
context.pressed.value = false;
"
/>
<slot v-bind="context.state()" />
</label>
</template>
@@ -0,0 +1,60 @@
import type { ComputedRef, InjectionKey, Ref } from "vue";
import type { checkboxVariants, radioVariants } from "@heroui-vue/styles";
import type { FieldContext } from "../field/context";
export interface ChoiceState {
isSelected: boolean;
isIndeterminate: boolean;
isDisabled: boolean;
isReadOnly: boolean;
isRequired: boolean;
isInvalid: boolean;
isHovered: boolean;
isPressed: boolean;
isFocused: boolean;
isFocusVisible: boolean;
}
export interface ChoiceMember {
value: () => string;
disabled: ComputedRef<boolean>;
readOnly: ComputedRef<boolean>;
input: Ref<HTMLInputElement | undefined>;
}
export interface ChoiceGroupContext {
kind: "checkbox" | "radio";
field: FieldContext;
behavior: ComputedRef<import("../field/context").ValidationBehavior>;
name: () => string | undefined;
form: () => string | undefined;
variant: ComputedRef<"primary" | "secondary" | undefined>;
selected: (value: string) => boolean;
select: (value: string) => void;
register: (member: ChoiceMember) => () => void;
tabIndex: (member: ChoiceMember) => number;
keydown: (event: KeyboardEvent, member: ChoiceMember) => void;
describedBy: () => string | undefined;
restore: () => void;
}
export const choiceGroupKey: InjectionKey<ChoiceGroupContext> = Symbol(
"HeroUIVue.ChoiceGroup",
);
export interface ChoiceContext {
kind: "checkbox" | "radio";
field: FieldContext;
slots: ComputedRef<
ReturnType<typeof checkboxVariants> | ReturnType<typeof radioVariants>
>;
state: () => ChoiceState;
input: Ref<HTMLInputElement | undefined>;
rootAttrs: () => Record<string, unknown>;
inputAttrs: () => Record<string, unknown>;
onChange: (event: Event) => void;
onInvalid: (event: Event) => void;
guard: (event: Event) => void;
keydown: (event: KeyboardEvent) => void;
hover: Ref<boolean>;
pressed: Ref<boolean>;
focused: Ref<boolean>;
focusVisible: Ref<boolean>;
}
export const choiceKey: InjectionKey<ChoiceContext> =
Symbol("HeroUIVue.Choice");
+420
View File
@@ -0,0 +1,420 @@
import {
computed,
defineComponent,
h,
mergeProps,
isVNode,
nextTick,
onMounted,
onUpdated,
provide,
ref,
shallowRef,
watchEffect,
type PropType,
type VNodeChild,
} from "vue";
import { checkboxGroupVariants, radioGroupVariants } from "@heroui-vue/styles";
import {
choiceGroupKey,
type ChoiceGroupContext,
type ChoiceMember,
} from "./context";
import {
useChoiceField,
useChoiceForm,
useChoiceValue,
validationInput,
type ChoiceFieldProps,
type ChoiceSetupContext,
} from "./shared";
import type { ValidateResult, ValidationBehavior } from "../field/context";
export const choiceGroupProps = {
id: String,
name: String,
form: String,
isDisabled: Boolean,
disabled: Boolean,
isReadOnly: Boolean,
isRequired: Boolean,
isInvalid: Boolean,
validationBehavior: String as PropType<ValidationBehavior>,
variant: String as PropType<"primary" | "secondary">,
};
interface GroupProps<T> extends ChoiceFieldProps {
modelValue?: T;
defaultValue?: T;
validate?: (value: T) => ValidateResult;
variant?: "primary" | "secondary";
orientation?: "horizontal" | "vertical";
dir?: "ltr" | "rtl";
loop?: boolean;
}
function setupGroup<T extends string[] | string | undefined>(
kind: "checkbox" | "radio",
props: GroupProps<T>,
context: ChoiceSetupContext,
config: {
initial: () => T;
read: () => T;
change: (value: T) => void;
selected: (model: T, value: string) => boolean;
toggle: (model: T, value: string) => T;
},
) {
const { attrs, slots, expose } = context;
const model = useChoiceValue(
config.read,
config.initial,
["modelValue", "model-value"],
config.change,
);
const root = ref<HTMLElement>(),
proxy = ref<HTMLInputElement>();
const members = shallowRef(new Map<symbol, ChoiceMember>());
const planned = shallowRef<{ value: string; disabled: boolean }[]>([]),
mounted = ref(false);
const order = ref<HTMLInputElement[]>([]);
const eligible = () =>
[...members.value.values()].filter(
(member) =>
!member.disabled.value && !member.input.value?.matches(":disabled"),
);
const selected = (value: string) => config.selected(model.value.value, value);
const validator = useChoiceField(props, attrs, {
kind: "group",
value: model.value,
validate: (value) => props.validate?.(value),
satisfied: () =>
(mounted.value
? eligible().map((member) => ({
value: member.value(),
disabled: false,
}))
: planned.value
).some((member) => !member.disabled && selected(member.value)),
requiredMessage:
kind === "checkbox" ? "请选择至少一个选项。" : "请选择一个选项。",
});
const field = validator.field;
function ordered() {
const available = eligible();
return available.sort(
(a, b) =>
order.value.indexOf(a.input.value!) -
order.value.indexOf(b.input.value!),
);
}
function focus() {
const member =
ordered().find((member) => selected(member.value())) ?? ordered()[0];
if (member?.input.value) member.input.value.focus();
else root.value?.focus();
}
function restore() {
for (const member of members.value.values())
if (member.input.value)
member.input.value.checked = selected(member.value());
}
function select(value: string) {
const member = [...members.value.values()].find(
(item) => item.value() === value,
);
if (
field.disabled.value ||
field.readOnly.value ||
member?.disabled.value ||
member?.readOnly.value
)
return;
validator.edit();
model.request(config.toggle(model.value.value, value));
void nextTick(restore);
}
function syncOrder() {
const own = new Set(
[...members.value.values()].map((member) => member.input.value),
);
const current = [
...(root.value?.querySelectorAll<HTMLInputElement>(
"input[data-choice-input]",
) ?? []),
].filter((input) => own.has(input));
if (
current.length !== order.value.length ||
current.some((input, index) => input !== order.value[index])
)
order.value = current;
}
function register(member: ChoiceMember) {
if (
[...members.value.values()].some(
(item) => item.value() === member.value(),
)
)
throw new Error(`${kind} group values must be unique: ${member.value()}`);
const key = Symbol();
members.value = new Map(members.value).set(key, member);
return () => {
const next = new Map(members.value);
next.delete(key);
members.value = next;
};
}
function tabIndex(member: ChoiceMember) {
if (kind === "checkbox") return member.disabled.value ? -1 : 0;
if (!mounted.value && planned.value.length) {
const available = planned.value.filter((item) => !item.disabled);
const target =
available.find((item) => selected(item.value)) ?? available[0];
return !member.disabled.value && target?.value === member.value()
? 0
: -1;
}
const available = ordered();
const target =
available.find((item) => selected(item.value())) ?? available[0];
return !member.disabled.value && target === member ? 0 : -1;
}
function keydown(event: KeyboardEvent, member: ChoiceMember) {
if (
kind !== "radio" ||
event.defaultPrevented ||
event.isComposing ||
event.keyCode === 229 ||
![
"ArrowLeft",
"ArrowRight",
"ArrowUp",
"ArrowDown",
"Home",
"End",
].includes(event.key)
)
return;
event.preventDefault();
if (field.disabled.value || field.readOnly.value || member.disabled.value)
return;
const available = ordered();
if (!available.length) return;
const current = available.indexOf(member);
const rtl =
(props.dir ?? root.value?.closest<HTMLElement>("[dir]")?.dir) === "rtl";
const previous =
event.key === "ArrowUp" ||
event.key === (rtl ? "ArrowRight" : "ArrowLeft");
let index =
event.key === "Home"
? 0
: event.key === "End"
? available.length - 1
: current + (previous ? -1 : 1);
index =
props.loop === false
? Math.max(0, Math.min(available.length - 1, index))
: (index + available.length) % available.length;
available[index].input.value?.focus();
select(available[index].value());
}
const group: ChoiceGroupContext = {
kind,
field,
behavior: validator.behavior,
name: () => props.name,
form: () => props.form,
variant: computed(() => props.variant),
selected,
select,
register,
tabIndex,
keydown,
describedBy: validator.describedBy,
restore,
};
provide(choiceGroupKey, group);
useChoiceForm(
proxy,
() => {
model.reset();
validator.reset();
},
restore,
);
watchEffect(() => validator.validity(proxy.value), { flush: "post" });
onMounted(() => {
mounted.value = true;
syncOrder();
validator.validity(proxy.value);
});
onUpdated(syncOrder);
// Re-check dynamic member values, not only registration-time values.
watchEffect(() => {
const values = [...members.value.values()].map((member) => member.value());
if (new Set(values).size !== values.length)
throw new Error(`${kind} group values must be unique`);
});
expose({ element: root, focus });
return () => {
const children =
slots.default?.({
isDisabled: field.disabled.value,
isReadOnly: field.readOnly.value,
isRequired: field.required.value,
isInvalid: field.invalid.value,
validationErrors: field.errors.value,
value: model.value.value,
state: {
value: model.value.value,
setValue: (value: T) => {
if (!field.disabled.value && !field.readOnly.value) {
validator.edit();
model.request(value);
void nextTick(restore);
}
},
},
}) ?? [];
const found: { value: string; disabled: boolean }[] = [];
function scan(nodes: VNodeChild[]) {
for (const node of nodes) {
if (!isVNode(node)) continue;
const type = node.type as { name?: string; __name?: string };
const name = type.name ?? type.__name;
if (name === (kind === "checkbox" ? "Checkbox" : "Radio"))
found.push({
value: String(node.props?.value ?? "on"),
disabled: Boolean(
node.props?.isDisabled ||
node.props?.["is-disabled"] ||
node.props?.disabled,
),
});
else if (Array.isArray(node.children))
scan(node.children as VNodeChild[]);
}
}
scan(children);
if (JSON.stringify(found) !== JSON.stringify(planned.value))
planned.value = found;
const prepared = validator.prepare(children, true);
return h(
"div",
mergeProps(
{
...attrs,
ref: root,
id: field.controlId.value,
class: [
kind === "checkbox"
? checkboxGroupVariants({ variant: props.variant })
: radioGroupVariants({ variant: props.variant }),
attrs.class,
],
role: kind === "checkbox" ? "group" : "radiogroup",
tabindex: attrs.tabindex ?? -1,
dir: props.dir,
"aria-labelledby": validator.labelledBy(),
"aria-describedby": validator.describedBy(),
"aria-invalid": field.invalid.value || undefined,
"aria-disabled": field.disabled.value || undefined,
"aria-readonly":
kind === "radio" ? field.readOnly.value || undefined : undefined,
"aria-required":
kind === "radio" ? field.required.value || undefined : undefined,
"data-slot": `${kind}-group`,
"data-orientation":
kind === "radio" ? (props.orientation ?? "vertical") : undefined,
"data-disabled": field.disabled.value || undefined,
"data-readonly": field.readOnly.value || undefined,
"data-required": field.required.value || undefined,
"data-invalid": field.invalid.value || undefined,
},
{
onKeydown: (event: KeyboardEvent) => {
const member = [...members.value.values()].find(
(item) => item.input.value === event.target,
);
if (member) keydown(event, member);
},
},
),
[
...prepared,
validationInput(
proxy,
props,
field.disabled.value,
validator.behavior.value,
(event) => validator.invalidEvent(event, focus),
field.required.value &&
!field.readOnly.value &&
validator.behavior.value === "native",
!validator.constraints.value.length,
),
],
);
};
}
export const CheckboxGroup = defineComponent({
name: "CheckboxGroup",
inheritAttrs: false,
props: {
...choiceGroupProps,
modelValue: Array as PropType<string[]>,
defaultValue: Array as PropType<string[]>,
validate: Function as PropType<(value: string[]) => ValidateResult>,
},
emits: {
"update:modelValue": (_value: string[]) => true,
change: (_value: string[]) => true,
},
setup(props, ctx) {
return setupGroup("checkbox", props, ctx, {
initial: () => props.defaultValue ?? [],
read: () => props.modelValue ?? [],
change: (value) => {
ctx.emit("update:modelValue", value);
ctx.emit("change", value);
},
selected: (model, value) => model.includes(value),
toggle: (model, value) =>
model.includes(value)
? model.filter((item) => item !== value)
: [...model, value],
});
},
});
export const RadioGroup = defineComponent({
name: "RadioGroup",
inheritAttrs: false,
props: {
...choiceGroupProps,
modelValue: String,
defaultValue: String,
validate: Function as PropType<
(value: string | undefined) => ValidateResult
>,
orientation: {
type: String as PropType<"horizontal" | "vertical">,
default: "vertical",
},
dir: String as PropType<"ltr" | "rtl">,
loop: { type: Boolean, default: true },
},
emits: {
"update:modelValue": (_value: string | undefined) => true,
change: (_value: string | undefined) => true,
},
setup(props, ctx) {
return setupGroup("radio", props, ctx, {
initial: () => props.defaultValue,
read: () => props.modelValue,
change: (value) => {
ctx.emit("update:modelValue", value);
ctx.emit("change", value);
},
selected: (model, value) => model === value,
toggle: (_model, value) => value,
});
},
});
+333
View File
@@ -0,0 +1,333 @@
import {
computed,
defineComponent,
h,
inject,
nextTick,
onBeforeUnmount,
onMounted,
provide,
ref,
watchEffect,
type PropType,
} from "vue";
import { checkboxVariants, radioVariants } from "@heroui-vue/styles";
import {
choiceGroupKey,
choiceKey,
type ChoiceContext,
type ChoiceMember,
} from "./context";
import { choiceGroupProps } from "./group";
import {
useChoiceField,
useChoiceForm,
useChoiceValue,
type ChoiceSetupContext,
} from "./shared";
import { mergeIds, type ValidateResult } from "../field/context";
import CheckboxContent from "../checkbox/CheckboxContent.vue";
import CheckboxControl from "../checkbox/CheckboxControl.vue";
import CheckboxIndicator from "../checkbox/CheckboxIndicator.vue";
import RadioContent from "../radio/RadioContent.vue";
import RadioControl from "../radio/RadioControl.vue";
import RadioIndicator from "../radio/RadioIndicator.vue";
interface ItemProps {
id?: string;
name?: string;
form?: string;
value?: string;
checked?: boolean;
isSelected?: boolean;
defaultChecked?: boolean;
defaultSelected?: boolean;
isIndeterminate?: boolean;
isDisabled?: boolean;
disabled?: boolean;
isReadOnly?: boolean;
isRequired?: boolean;
isInvalid?: boolean;
validationBehavior?: "native" | "aria";
variant?: "primary" | "secondary";
validate?: (value: boolean) => ValidateResult;
}
function setupItem(
kind: "checkbox" | "radio",
props: ItemProps,
ctx: ChoiceSetupContext,
emit: (value: boolean) => void,
) {
const group = inject(choiceGroupKey, undefined);
if (kind === "radio" && group?.kind !== "radio")
throw new Error("Radio must be inside RadioGroup");
if (group && group.kind !== kind)
throw new Error(
`${kind} cannot be placed directly in a ${group.kind} group`,
);
const input = ref<HTMLInputElement>();
const model = useChoiceValue(
() => props.checked ?? props.isSelected ?? false,
() => props.defaultChecked ?? props.defaultSelected ?? false,
["checked", "isSelected", "is-selected"],
emit,
);
const selected = computed(() =>
group ? group.selected(props.value ?? "on") : model.value.value,
);
const validator = useChoiceField(props, ctx.attrs, {
kind: "toggle",
value: selected,
validate: (value) => props.validate?.(value),
satisfied: () => selected.value,
requiredMessage: "请选择此选项。",
parent: group?.field,
parentBehavior: group?.behavior,
});
const field = validator.field;
const hovered = ref(false),
pressed = ref(false),
focused = ref(false),
focusVisible = ref(false);
const member: ChoiceMember = {
value: () => props.value ?? "on",
disabled: field.disabled,
readOnly: field.readOnly,
input,
};
const unregister = group?.register(member);
onBeforeUnmount(() => unregister?.());
const slots = computed(() =>
kind === "checkbox"
? checkboxVariants({ variant: props.variant ?? group?.variant.value })
: radioVariants(),
);
function restore() {
if (input.value) {
input.value.checked = selected.value;
input.value.indeterminate =
kind === "checkbox" && Boolean(props.isIndeterminate);
}
}
function change(event: Event) {
if (field.disabled.value || field.readOnly.value) {
restore();
return;
}
validator.edit();
if (group) group.select(member.value());
else model.request((event.target as HTMLInputElement).checked);
void nextTick(() => {
restore();
group?.restore();
});
}
function guard(event: Event) {
if (field.disabled.value || field.readOnly.value) {
event.preventDefault();
event.stopImmediatePropagation();
}
}
const state = () => ({
isSelected: selected.value,
isIndeterminate: kind === "checkbox" && Boolean(props.isIndeterminate),
isDisabled: field.disabled.value,
isReadOnly: field.readOnly.value,
isRequired: field.required.value,
isInvalid: field.invalid.value,
isHovered: hovered.value,
isPressed: pressed.value,
isFocused: focused.value,
isFocusVisible: focusVisible.value,
});
const controlAttrs = () =>
Object.fromEntries(
Object.entries(ctx.attrs).filter(
([key]) =>
key !== "class" && key !== "style" && !key.startsWith("data-"),
),
);
const rootAttrs = () =>
Object.fromEntries(
Object.entries(ctx.attrs).filter(
([key]) =>
key === "class" || key === "style" || key.startsWith("data-"),
),
);
const context: ChoiceContext = {
kind,
field,
slots,
state,
input,
rootAttrs,
inputAttrs: () => ({
...controlAttrs(),
id: field.controlId.value,
type: kind,
name: group ? group.name() : props.name,
form: group ? group.form() : props.form,
value: props.value ?? "on",
checked: selected.value,
disabled: field.disabled.value,
required:
field.required.value &&
!field.readOnly.value &&
validator.behavior.value === "native",
tabindex: group ? group.tabIndex(member) : (ctx.attrs.tabindex ?? 0),
"aria-readonly":
kind === "checkbox" ? field.readOnly.value || undefined : undefined,
"aria-invalid": field.invalid.value || undefined,
"aria-required": field.required.value || undefined,
"aria-describedby": mergeIds(
validator.describedBy(),
group?.describedBy(),
),
"data-validation-behavior": validator.behavior.value,
"data-choice-input": "",
}),
onChange: change,
onInvalid: (event) =>
validator.invalidEvent(event, () => input.value?.focus()),
guard,
keydown: (event) => {
if (event.defaultPrevented) return;
if (
[
" ",
"Enter",
"ArrowUp",
"ArrowDown",
"ArrowLeft",
"ArrowRight",
"Home",
"End",
].includes(event.key) &&
(field.readOnly.value || field.disabled.value)
) {
guard(event);
return;
}
},
hover: hovered,
pressed,
focused,
focusVisible,
};
provide(choiceKey, context);
if (!group)
useChoiceForm(
input,
() => {
model.reset();
validator.reset();
},
restore,
);
watchEffect(
() => {
restore();
validator.validity(input.value);
if (field.disabled.value || field.readOnly.value) {
hovered.value = false;
pressed.value = false;
}
},
{ flush: "post" },
);
onMounted(() => {
restore();
validator.validity(input.value);
});
ctx.expose({ element: input, focus: () => input.value?.focus() });
return () =>
h(
"div",
{
...rootAttrs(),
class: [slots.value.base(), ctx.attrs.class],
"data-slot": kind,
"data-selected": selected.value || undefined,
"data-indeterminate":
(kind === "checkbox" && props.isIndeterminate) || undefined,
"data-disabled": field.disabled.value || undefined,
"data-readonly": field.readOnly.value || undefined,
"data-required": field.required.value || undefined,
"data-invalid": field.invalid.value || undefined,
},
validator.prepare(
ctx.slots.default?.({
...state(),
state: {
isSelected: selected.value,
setSelected: (value: boolean) => {
if (field.disabled.value || field.readOnly.value) return;
validator.edit();
if (group) {
if (selected.value !== value) group.select(member.value());
} else model.request(value);
void nextTick(restore);
},
toggle: () => {
if (field.disabled.value || field.readOnly.value) return;
validator.edit();
if (group) group.select(member.value());
else model.request(!selected.value);
void nextTick(restore);
},
},
}) ?? [
h(kind === "checkbox" ? CheckboxContent : RadioContent, {}, () =>
h(kind === "checkbox" ? CheckboxControl : RadioControl, {}, () =>
h(kind === "checkbox" ? CheckboxIndicator : RadioIndicator),
),
),
],
false,
"",
state(),
),
);
}
export const Checkbox = defineComponent({
name: "Checkbox",
inheritAttrs: false,
props: {
...choiceGroupProps,
value: String,
checked: { type: Boolean, default: undefined },
isSelected: { type: Boolean, default: undefined },
defaultChecked: { type: Boolean, default: undefined },
defaultSelected: Boolean,
isIndeterminate: Boolean,
validate: Function as PropType<(value: boolean) => ValidateResult>,
},
emits: {
"update:checked": (_value: boolean) => true,
"update:isSelected": (_value: boolean) => true,
change: (_value: boolean) => true,
},
setup(props, ctx) {
return setupItem("checkbox", props, ctx, (value) => {
ctx.emit("update:checked", value);
ctx.emit("update:isSelected", value);
ctx.emit("change", value);
});
},
});
export const Radio = defineComponent({
name: "Radio",
inheritAttrs: false,
props: {
id: String,
value: { type: String, required: true },
name: String,
form: String,
isDisabled: Boolean,
disabled: Boolean,
isReadOnly: Boolean,
isInvalid: Boolean,
},
setup(props, ctx) {
return setupItem("radio", props, ctx, () => {});
},
});
@@ -0,0 +1,326 @@
import {
Comment,
Fragment,
cloneVNode,
computed,
getCurrentInstance,
h,
inject,
isVNode,
nextTick,
onBeforeUnmount,
onBeforeUpdate,
onMounted,
onUpdated,
provide,
ref,
shallowRef,
useId,
watchEffect,
type ComputedRef,
type Ref,
type Slots,
type VNode,
type VNodeChild,
} from "vue";
import {
errorMessages,
fieldContextKey,
formContextKey,
mergeIds,
type FieldContext,
type ValidateResult,
type ValidationBehavior,
} from "../field/context";
import { useInheritedDisabled } from "../field/disabled";
export interface ChoiceFieldProps {
id?: string;
name?: string;
form?: string;
isDisabled?: boolean;
disabled?: boolean;
isReadOnly?: boolean;
isRequired?: boolean;
isInvalid?: boolean;
validationBehavior?: ValidationBehavior;
}
export interface ChoiceSetupContext {
attrs: Record<string, unknown>;
slots: Slots;
expose: (value: Record<string, unknown>) => void;
}
export function useChoiceValue<T>(
read: () => T,
defaults: () => T,
keys: string[],
emit: (value: T) => void,
) {
const instance = getCurrentInstance();
const copy = (value: T): T =>
Array.isArray(value) ? ([...value] as T) : value;
const initial = copy(defaults());
const internal = ref<T>(copy(initial)) as Ref<T>;
const controlled = () =>
keys.some((key) => Object.hasOwn(instance?.vnode.props ?? {}, key));
const isControlled = ref(controlled());
onBeforeUpdate(() => {
isControlled.value = controlled();
});
const value = computed(() => {
const external = read();
return isControlled.value ? external : internal.value;
});
function request(next: T) {
if (!controlled()) internal.value = copy(next);
emit(copy(next));
}
function reset() {
if (!controlled()) internal.value = copy(initial);
}
return { value, request, reset };
}
export function useChoiceField<T>(
props: ChoiceFieldProps,
attrs: Record<string, unknown>,
options: {
kind: "group" | "toggle";
value: ComputedRef<T>;
validate?: (value: T) => ValidateResult;
satisfied: () => boolean;
requiredMessage: string;
parent?: FieldContext;
parentBehavior?: ComputedRef<ValidationBehavior>;
},
) {
const form = inject(formContextKey, undefined);
const id = useId();
const disabled = useInheritedDisabled(
() => props.isDisabled || props.disabled || options.parent?.disabled.value,
);
const readOnly = computed(() =>
Boolean(props.isReadOnly || options.parent?.readOnly.value),
);
const required = computed(() => Boolean(props.isRequired));
const behavior = computed(
() =>
props.validationBehavior ??
options.parentBehavior?.value ??
form?.validationBehavior.value ??
"native",
);
const touched = ref(false),
dismissed = shallowRef<object>();
const registeredDescriptions = ref<string[]>([]),
registeredErrors = ref<string[]>([]),
labels = ref<string[]>([]);
const planned = shallowRef({
labels: [] as string[],
descriptions: [] as string[],
errors: [] as string[],
});
const server = computed(() => {
const source = form?.validationErrors.value;
return props.name && source && source !== dismissed.value
? errorMessages(source[props.name])
: [];
});
const constraints = computed(() =>
disabled.value || readOnly.value
? []
: [
...server.value,
...errorMessages(options.validate?.(options.value.value)),
...(required.value && !options.satisfied()
? [options.requiredMessage]
: []),
],
);
const errors = computed(() =>
disabled.value || readOnly.value
? []
: [
...server.value,
...(touched.value || behavior.value === "aria"
? constraints.value.filter(
(message) => !server.value.includes(message),
)
: []),
],
);
const invalid = computed(() =>
Boolean(
props.isInvalid || options.parent?.invalid.value || errors.value.length,
),
);
const field: FieldContext = {
kind: options.kind,
controlId: computed(() => props.id ?? id),
disabled,
readOnly,
required,
invalid,
errors,
descriptionIds: registeredDescriptions,
errorIds: registeredErrors,
labelIds: labels,
};
provide(fieldContextKey, field);
const describedBy = () =>
mergeIds(
attrs["aria-describedby"] as string | undefined,
registeredDescriptions.value,
planned.value.descriptions,
invalid.value ? [...registeredErrors.value, ...planned.value.errors] : [],
);
const labelledBy = () =>
mergeIds(
attrs["aria-labelledby"] as string | undefined,
labels.value,
planned.value.labels,
);
function edit() {
dismissed.value = form?.validationErrors.value;
}
function reset() {
touched.value = false;
dismissed.value = form?.validationErrors.value;
}
function invalidEvent(event: Event, focus: () => void) {
event.preventDefault();
touched.value = true;
void nextTick(focus);
}
function validity(control: HTMLInputElement | undefined) {
control?.setCustomValidity(
behavior.value === "native" ? constraints.value.join(" ") : "",
);
}
function prepare(
nodes: VNodeChild[],
groupLabels = false,
path = "",
slotState: Record<string, unknown> = {},
): VNodeChild[] {
const found = {
labels: [] as string[],
descriptions: [] as string[],
errors: [] as string[],
};
function walk(children: VNodeChild[], position: string): VNodeChild[] {
return children.map((node, index) => {
if (!isVNode(node) || node.type === Comment) return node;
const at = `${position}-${index}`;
const type = node.type as { name?: string; __name?: string };
const name = type.name ?? type.__name;
const part =
name === "Description"
? "descriptions"
: name === "FieldError"
? "errors"
: groupLabels && name === "Label"
? "labels"
: undefined;
if (part) {
const partId = String(node.props?.id ?? `${id}-${part}${at}`);
found[part].push(partId);
return cloneVNode(node, { id: partId });
}
if (
(name === "CheckboxContent" || name === "RadioContent") &&
node.children &&
typeof node.children === "object"
) {
const contentSlots = node.children as {
default?: (
state: Record<string, unknown>,
) => VNodeChild | VNodeChild[];
};
if (contentSlots.default) {
const raw = contentSlots.default(slotState);
const prepared = walk(Array.isArray(raw) ? raw : [raw], at);
const clone = cloneVNode(node);
clone.children = { ...contentSlots, default: () => prepared };
return clone;
}
}
if (
(node.type === Fragment || typeof node.type === "string") &&
Array.isArray(node.children)
) {
const clone = cloneVNode(node);
clone.children = walk(node.children as VNodeChild[], at) as VNode[];
return clone;
}
return node;
});
}
const result = walk(nodes, path);
if (JSON.stringify(found) !== JSON.stringify(planned.value))
planned.value = found;
return result;
}
return {
field,
behavior,
constraints,
describedBy,
labelledBy,
edit,
reset,
invalidEvent,
validity,
prepare,
};
}
export function useChoiceForm(
input: Ref<HTMLInputElement | undefined>,
reset: () => void,
restore: () => void,
) {
let owner: HTMLFormElement | null = null;
function onReset(event: Event) {
void nextTick(() => {
if (event.defaultPrevented) return;
reset();
restore();
});
}
function bind() {
const next = input.value?.form ?? null;
if (next !== owner) {
owner?.removeEventListener("reset", onReset);
owner = next;
owner?.addEventListener("reset", onReset);
}
}
onMounted(bind);
onUpdated(bind);
onBeforeUnmount(() => owner?.removeEventListener("reset", onReset));
}
export function validationInput(
input: Ref<HTMLInputElement | undefined>,
props: ChoiceFieldProps,
disabled: boolean,
behavior: ValidationBehavior,
invalid: (event: Event) => void,
required = false,
checked = true,
) {
return h("input", {
ref: input,
type: "checkbox",
checked,
required,
class: "hv-choice-validation",
tabindex: -1,
"aria-hidden": "true",
form: props.form,
disabled,
"data-validation-behavior": behavior,
onInvalid: invalid,
});
}
+3 -2
View File
@@ -3,15 +3,16 @@ import type { ComputedRef, InjectionKey, Ref } from "vue";
export type ValidationBehavior = "native" | "aria";
export type ValidationErrors = Record<string, string | string[]>;
export type ValidateResult = string | string[] | true | null | undefined;
export type FieldPart = "description" | "error";
export type FieldPart = "description" | "error" | "label";
export interface FieldContext {
controlId: ComputedRef<string>;
kind: "text" | "toggle";
kind: "text" | "toggle" | "group";
disabled: ComputedRef<boolean>;
readOnly: ComputedRef<boolean>;
required: ComputedRef<boolean>;
invalid: ComputedRef<boolean>;
errors: ComputedRef<string[]>;
labelIds?: Ref<string[]>;
descriptionIds: Ref<string[]>;
errorIds: Ref<string[]>;
}
@@ -8,7 +8,12 @@ export function useFieldPart(part: FieldPart, attrs: Record<string, unknown>) {
const id = computed(() =>
typeof attrs.id === "string" ? attrs.id : generated,
);
const ids = part === "description" ? field?.descriptionIds : field?.errorIds;
const ids =
part === "label"
? field?.labelIds
: part === "description"
? field?.descriptionIds
: field?.errorIds;
const stop = watch(
id,
(current, _, cleanup) => {
+9 -1
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { inject, useAttrs } from "vue";
import { useFieldPart } from "../field/useFieldPart";
import { useInheritedDisabled } from "../field/disabled";
import { fieldContextKey } from "../field/context";
defineOptions({ inheritAttrs: false });
@@ -10,14 +11,21 @@ const props = defineProps<{
isDisabled?: boolean;
isInvalid?: boolean;
}>();
const labelPart =
field?.kind === "group" ? useFieldPart("label", attrs) : undefined;
const disabled = useInheritedDisabled(
() => props.isDisabled || field?.disabled.value,
);
</script>
<template>
<component
:is="field?.kind === 'toggle' && !attrs.for ? 'span' : 'label'"
:is="
(field?.kind === 'toggle' || field?.kind === 'group') && !attrs.for
? 'span'
: 'label'
"
v-bind="attrs"
:id="labelPart?.id.value ?? attrs.id"
:for="
attrs.for ?? (field?.kind === 'text' ? field.controlId.value : undefined)
"
@@ -0,0 +1,11 @@
<script lang="ts">
import { defineComponent, h } from "vue";
import ChoiceContent from "../choice/ChoiceContent.vue";
export default defineComponent({
name: "RadioContent",
inheritAttrs: false,
setup(_, { attrs, slots }) {
return () => h(ChoiceContent, attrs, slots);
},
});
</script>
@@ -0,0 +1,16 @@
<script setup lang="ts">
import { inject } from "vue";
import { choiceKey } from "../choice/context";
defineOptions({ inheritAttrs: false });
const context = inject(choiceKey);
if (!context) throw new Error("RadioControl must be inside Radio");
</script>
<template>
<span
v-bind="$attrs"
:class="[context.slots.value.control(), $attrs.class]"
data-slot="radio-control"
>
<slot v-bind="context.state()"></slot>
</span>
</template>
@@ -0,0 +1,23 @@
<script lang="ts">
import { defineComponent, h, inject } from "vue";
import { choiceKey } from "../choice/context";
export default defineComponent({
name: "RadioIndicator",
inheritAttrs: false,
setup(_, { attrs, slots }) {
const context = inject(choiceKey);
if (!context) throw new Error("RadioIndicator must be inside Radio");
return () =>
h(
"span",
{
...attrs,
class: [context.slots.value.indicator(), attrs.class],
"aria-hidden": "true",
"data-slot": "radio-indicator",
},
slots.default?.(context.state()),
);
},
});
</script>
+29
View File
@@ -233,3 +233,32 @@ export {
type FieldsetVariants,
type SearchFieldVariants,
} from "@heroui-vue/styles";
export { Checkbox, Radio } from "./components/choice/item";
export { CheckboxGroup, RadioGroup } from "./components/choice/group";
export type { CheckboxProps } from "./types";
export type { RadioProps } from "./types";
export type { CheckboxGroupProps } from "./types";
export type { RadioGroupProps } from "./types";
export { default as CheckboxContent } from "./components/checkbox/CheckboxContent.vue";
export type { CheckboxContentProps } from "./types";
export { default as CheckboxControl } from "./components/checkbox/CheckboxControl.vue";
export type { CheckboxControlProps } from "./types";
export { default as CheckboxIndicator } from "./components/checkbox/CheckboxIndicator.vue";
export type { CheckboxIndicatorProps } from "./types";
export { default as RadioContent } from "./components/radio/RadioContent.vue";
export type { RadioContentProps } from "./types";
export { default as RadioControl } from "./components/radio/RadioControl.vue";
export type { RadioControlProps } from "./types";
export { default as RadioIndicator } from "./components/radio/RadioIndicator.vue";
export type { RadioIndicatorProps } from "./types";
export {
checkboxVariants,
checkboxGroupVariants,
radioVariants,
radioGroupVariants,
type CheckboxVariants,
type CheckboxGroupVariants,
type RadioVariants,
type RadioGroupVariants,
} from "@heroui-vue/styles";
+25
View File
@@ -138,3 +138,28 @@ import type SearchFieldClearButton from "./components/search-field/SearchFieldCl
export type SearchFieldClearButtonProps = InstanceType<
typeof SearchFieldClearButton
>["$props"];
import type { Checkbox, Radio } from "./components/choice/item";
import type { CheckboxGroup, RadioGroup } from "./components/choice/group";
export type CheckboxProps = InstanceType<typeof Checkbox>["$props"];
export type RadioProps = InstanceType<typeof Radio>["$props"];
export type CheckboxGroupProps = InstanceType<typeof CheckboxGroup>["$props"];
export type RadioGroupProps = InstanceType<typeof RadioGroup>["$props"];
import type CheckboxContent from "./components/checkbox/CheckboxContent.vue";
export type CheckboxContentProps = InstanceType<
typeof CheckboxContent
>["$props"];
import type CheckboxControl from "./components/checkbox/CheckboxControl.vue";
export type CheckboxControlProps = InstanceType<
typeof CheckboxControl
>["$props"];
import type CheckboxIndicator from "./components/checkbox/CheckboxIndicator.vue";
export type CheckboxIndicatorProps = InstanceType<
typeof CheckboxIndicator
>["$props"];
import type RadioContent from "./components/radio/RadioContent.vue";
export type RadioContentProps = InstanceType<typeof RadioContent>["$props"];
import type RadioControl from "./components/radio/RadioControl.vue";
export type RadioControlProps = InstanceType<typeof RadioControl>["$props"];
import type RadioIndicator from "./components/radio/RadioIndicator.vue";
export type RadioIndicatorProps = InstanceType<typeof RadioIndicator>["$props"];
+96
View File
@@ -0,0 +1,96 @@
import { expect, it, vi } from "vitest";
import { mount } from "@vue/test-utils";
import { nextTick, type Component } from "vue";
import { readFileSync } from "node:fs";
const demos = import.meta.glob<{ default: Component }>(
"../apps/docs/demos/{checkbox,checkbox-group,radio-group}-*.vue",
);
it("mounts all 37 baseline choice demos without render warnings or missing controls", async () => {
expect(Object.keys(demos)).toHaveLength(37);
const warn = vi.spyOn(console, "warn"),
error = vi.spyOn(console, "error");
try {
for (const [name, load] of Object.entries(demos)) {
const component = await load();
const w = mount(component.default, { attachTo: document.body });
try {
await nextTick();
expect(
w.findAll("input[data-choice-input]").length,
name,
).toBeGreaterThan(0);
} finally {
w.unmount();
}
}
expect(warn).not.toHaveBeenCalled();
expect(error).not.toHaveBeenCalled();
} finally {
warn.mockRestore();
error.mockRestore();
}
});
it("keeps all source previews in the documented order and uses Vue/Tabler demos", () => {
const expected = {
checkbox: [
"basic",
"variants",
"full-rounded",
"disabled",
"external-label",
"with-description",
"default-selected",
"invalid",
"controlled",
"indeterminate",
"form",
"render-props",
"render-function",
"custom-indicator",
"custom-styles",
],
"checkbox-group": [
"basic",
"on-surface",
"disabled",
"indeterminate",
"controlled",
"validation",
"features-and-addons",
"with-custom-indicator",
"render-function",
"custom-styles",
],
"radio-group": [
"basic",
"horizontal",
"variants",
"on-surface",
"disabled",
"controlled",
"uncontrolled",
"validation",
"delivery-and-payment",
"custom-indicator",
"render-function",
"custom-styles",
],
};
for (const [name, parts] of Object.entries(expected)) {
const markdown = readFileSync(`apps/docs/components/${name}.md`, "utf8");
expect(
[...markdown.matchAll(/<ComponentPreview\b[^>]*?name="([^"]+)"/g)].map(
(m) => m[1],
),
).toEqual(parts.map((part) => `${name}-${part}`));
for (const part of parts) {
const source = readFileSync(
`apps/docs/demos/${name}-${part}.vue`,
"utf8",
);
expect(source).not.toContain("<svg");
expect(source).not.toContain("className=");
expect(source).not.toContain("onChange=");
}
}
});
+666
View File
@@ -0,0 +1,666 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { mount } from "@vue/test-utils";
import { createSSRApp, defineComponent, h, nextTick, ref } from "vue";
import { renderToString } from "@vue/server-renderer";
import {
Checkbox,
CheckboxContent,
CheckboxControl,
CheckboxIndicator,
CheckboxGroup,
Radio,
RadioContent,
RadioControl,
RadioIndicator,
RadioGroup,
Description,
FieldError,
Fieldset,
FieldsetLegend,
Form,
Label,
} from "../packages/vue/src";
const tick = async () => {
await nextTick();
await nextTick();
};
afterEach(() => {
document.body.innerHTML = "";
});
function option(
kind: "checkbox" | "radio",
value: string,
props: Record<string, unknown> = {},
) {
return h(kind === "checkbox" ? Checkbox : Radio, { value, ...props }, () => [
h(kind === "checkbox" ? CheckboxContent : RadioContent, {}, () => [
h(kind === "checkbox" ? CheckboxControl : RadioControl, {}, () =>
h(kind === "checkbox" ? CheckboxIndicator : RadioIndicator),
),
h(Label, {}, () => value),
]),
h(Description, {}, () => `${value} hint`),
]);
}
function group(
kind: "checkbox" | "radio",
props: Record<string, unknown> = {},
options: Record<string, unknown>[] = [{}, {}, {}],
) {
const children = () => [
h(Label, {}, () => "Choices"),
h(Description, {}, () => "Group hint"),
...options.map((props, index) =>
option(kind, ["a", "b", "c"][index], props),
),
h(FieldError),
];
return kind === "checkbox"
? h(CheckboxGroup, props, children)
: h(RadioGroup, props, children);
}
function inForm(
content: () => ReturnType<typeof h>,
props: Record<string, unknown> = {},
) {
return defineComponent({ render: () => h(Form, props, content) });
}
const formData = (w: ReturnType<typeof mount>) =>
Array.from(new FormData(w.get("form").element as HTMLFormElement));
const inputs = (w: ReturnType<typeof mount>) =>
w.findAll<HTMLInputElement>("input[data-choice-input]");
describe("Checkbox native value protocol", () => {
it("keeps explicit composition, native semantics, default indicators and sibling descriptions", async () => {
const w = mount(option("checkbox", "a"));
await tick();
expect(w.find("label.hv-checkbox__content").exists()).toBe(true);
expect(inputs(w)[0].attributes("type")).toBe("checkbox");
expect(w.get("[data-slot=label]").element.tagName).toBe("SPAN");
expect(
w.find("[data-slot=checkbox-default-indicator--checkmark]").exists(),
).toBe(true);
const ref = inputs(w)[0].attributes("aria-describedby")!;
expect(w.get(`[id="${ref}"]`).text()).toBe("a hint");
w.unmount();
});
it("submits exactly one native value only when selected, and resets to initial selection", async () => {
const change = vi.fn();
const w = mount(
inForm(() =>
option("checkbox", "yes", {
name: "ok",
defaultChecked: true,
"onUpdate:checked": change,
}),
),
{ attachTo: document.body },
);
expect(formData(w)).toEqual([["ok", "yes"]]);
await inputs(w)[0].setValue(false);
expect(formData(w)).toEqual([]);
expect(change).toHaveBeenCalledExactlyOnceWith(false);
(w.get("form").element as HTMLFormElement).reset();
await tick();
expect(inputs(w)[0].element.checked).toBe(true);
expect(formData(w)).toEqual([["ok", "yes"]]);
w.unmount();
});
it("restores controlled rejection and honors canceled reset", async () => {
const change = vi.fn();
const w = mount(
inForm(() =>
option("checkbox", "yes", {
checked: true,
"onUpdate:checked": change,
}),
),
{ attachTo: document.body },
);
await inputs(w)[0].setValue(false);
await tick();
expect(inputs(w)[0].element.checked).toBe(true);
expect(change).toHaveBeenCalledExactlyOnceWith(false);
w.unmount();
const u = mount(
inForm(() => option("checkbox", "a")),
{ attachTo: document.body },
);
await inputs(u)[0].setValue(true);
const form = u.get("form").element as HTMLFormElement;
form.addEventListener("reset", (e) => e.preventDefault());
form.reset();
await tick();
expect(inputs(u)[0].element.checked).toBe(true);
u.unmount();
});
it("separates mixed appearance from the actual submitted boolean", async () => {
const w = mount(
inForm(() =>
option("checkbox", "yes", { name: "mixed", isIndeterminate: true }),
),
{ attachTo: document.body },
);
await tick();
expect(inputs(w)[0].element.indeterminate).toBe(true);
expect(formData(w)).toEqual([]);
expect(
w.find("[data-slot=checkbox-default-indicator--indeterminate]").exists(),
).toBe(true);
w.unmount();
});
it("blocks readonly pointer and keyboard changes without disabling focus", async () => {
const change = vi.fn();
const w = mount(
option("checkbox", "a", {
isReadOnly: true,
checked: true,
"onUpdate:checked": change,
}),
{ attachTo: document.body },
);
const input = inputs(w)[0];
await input.trigger("click");
await input.trigger("keydown", { key: " " });
await tick();
expect(change).not.toHaveBeenCalled();
expect(input.element.checked).toBe(true);
expect(input.attributes("disabled")).toBeUndefined();
input.element.focus();
expect(document.activeElement).toBe(input.element);
w.unmount();
});
it("routes an external Label for to the actual checkbox", async () => {
const w = mount(
defineComponent({
render: () =>
h("div", {}, [
option("checkbox", "a", { id: "external" }),
h(Label, { for: "external" }, () => "External"),
]),
}),
);
expect(inputs(w)[0].attributes("id")).toBe("external");
expect(w.get("label[for=external]").text()).toBe("External");
w.unmount();
});
});
for (const kind of ["checkbox", "radio"] as const) {
describe(`${kind} group`, () => {
it("uses repeated plain names or a single selected scalar, without hidden duplicate values", async () => {
const w = mount(
inForm(() =>
group(kind, {
name: "choices",
defaultValue: kind === "checkbox" ? ["a", "b"] : "b",
}),
),
{ attachTo: document.body },
);
await tick();
expect(formData(w)).toEqual(
kind === "checkbox"
? [
["choices", "a"],
["choices", "b"],
]
: [["choices", "b"]],
);
expect(w.find("input[name='choices[0]']").exists()).toBe(false);
w.unmount();
});
it("omits group, member and Fieldset disabled values and preserves first legend exemption", async () => {
const off = ref(true);
const w = mount(
inForm(() =>
h(Fieldset, { disabled: off.value }, () => [
h(FieldsetLegend, {}, () =>
option("checkbox", "legend", {
name: "legend",
defaultChecked: true,
}),
),
group(
kind,
{
name: "choices",
defaultValue: kind === "checkbox" ? ["a", "b"] : "b",
},
[{}, { isDisabled: true }, {}],
),
]),
),
{ attachTo: document.body },
);
await tick();
expect(formData(w)).toEqual([["legend", "legend"]]);
off.value = false;
await tick();
expect(formData(w)).toEqual(
kind === "checkbox"
? [
["legend", "legend"],
["choices", "a"],
]
: [["legend", "legend"]],
);
w.unmount();
});
it("restores initial values on reset, preserves controlled values and canceled resets", async () => {
const initial = kind === "checkbox" ? ["a"] : "a";
const w = mount(
inForm(() => group(kind, { name: "choice", defaultValue: initial })),
{ attachTo: document.body },
);
await inputs(w)[1].setValue(true);
await tick();
const form = w.get("form").element as HTMLFormElement;
form.reset();
await tick();
expect(formData(w)).toEqual([["choice", "a"]]);
await inputs(w)[1].setValue(true);
form.addEventListener("reset", (e) => e.preventDefault());
const before = formData(w);
form.reset();
await tick();
expect(formData(w)).toEqual(before);
w.unmount();
const change = vi.fn();
const controlled = mount(
inForm(() =>
group(kind, {
name: "choice",
modelValue: initial,
"onUpdate:modelValue": change,
}),
),
{ attachTo: document.body },
);
await inputs(controlled)[1].setValue(true);
await tick();
expect(formData(controlled)).toEqual([["choice", "a"]]);
expect(change).toHaveBeenCalledTimes(1);
(controlled.get("form").element as HTMLFormElement).reset();
await tick();
expect(formData(controlled)).toEqual([["choice", "a"]]);
controlled.unmount();
});
it("validates one group constraint, displays errors and focuses a visible available choice", async () => {
const submit = vi.fn((e: Event) => e.preventDefault());
const w = mount(
inForm(
() =>
group(kind, { name: "required", isRequired: true }, [
{ isDisabled: true },
{},
{},
]),
{ onSubmit: submit },
),
{ attachTo: document.body },
);
(w.get("form").element as HTMLFormElement).requestSubmit();
await tick();
expect(submit).not.toHaveBeenCalled();
expect(w.get("[data-slot=field-error]").text()).toContain("请选择");
expect(document.activeElement).toBe(inputs(w)[1].element);
await inputs(w)[2].setValue(true);
await tick();
(w.get("form").element as HTMLFormElement).requestSubmit();
await tick();
expect(submit).toHaveBeenCalledOnce();
expect(formData(w)).toEqual([["required", "c"]]);
w.unmount();
});
it("honors aria validation, readonly and an empty group without a focusable member", async () => {
const submit = vi.fn((e: Event) => e.preventDefault());
const w = mount(
inForm(
() => group(kind, { isRequired: true, validationBehavior: "aria" }),
{ onSubmit: submit },
),
{ attachTo: document.body },
);
await tick();
(w.get("form").element as HTMLFormElement).requestSubmit();
expect(submit).toHaveBeenCalledOnce();
expect(w.get("[data-slot=field-error]").text()).toContain("请选择");
w.unmount();
const empty = mount(
inForm(() => group(kind, { isRequired: true }, [])),
{ attachTo: document.body },
);
(empty.get("form").element as HTMLFormElement).requestSubmit();
await tick();
expect(document.activeElement).toBe(
empty.get(`[data-slot=${kind}-group]`).element,
);
empty.unmount();
const change = vi.fn();
const ro = mount(
group(kind, {
isReadOnly: true,
defaultValue: kind === "checkbox" ? ["a"] : "a",
"onUpdate:modelValue": change,
}),
{ attachTo: document.body },
);
await inputs(ro)[1].trigger("click");
await inputs(ro)[0].trigger("keydown", { key: "ArrowDown" });
expect(change).not.toHaveBeenCalled();
ro.unmount();
});
it("uses group label IDs and isolates item descriptions from group descriptions", async () => {
const w = mount(group(kind));
await tick();
const root = w.get(`[data-slot=${kind}-group]`);
const groupLabel = w.get(`[id="${root.attributes("aria-labelledby")}"]`);
expect(groupLabel.element.tagName).toBe("SPAN");
expect(groupLabel.text()).toBe("Choices");
const first = inputs(w)[0].attributes("aria-describedby")!.split(" ");
const second = inputs(w)[1].attributes("aria-describedby")!.split(" ");
expect(first).toContain(root.attributes("aria-describedby"));
expect(first.filter((id) => !second.includes(id))).toHaveLength(1);
w.unmount();
});
it("rebinds external form association and a dynamic name, including reset ownership", async () => {
const form = ref("one"),
name = ref("old");
const w = mount(
defineComponent({
render: () =>
h("div", {}, [
h("form", { id: "one" }),
h("form", { id: "two" }),
group(kind, {
form: form.value,
name: name.value,
defaultValue: kind === "checkbox" ? ["a"] : "a",
}),
]),
}),
{ attachTo: document.body },
);
await tick();
form.value = "two";
name.value = "new";
await tick();
await inputs(w)[1].setValue(true);
await tick();
const one = w.get("#one").element as HTMLFormElement,
two = w.get("#two").element as HTMLFormElement;
expect(Array.from(new FormData(one))).toEqual([]);
expect(new FormData(two).getAll("new")).toEqual(
kind === "checkbox" ? ["a", "b"] : ["b"],
);
one.reset();
await tick();
expect(inputs(w)[1].element.checked).toBe(true);
two.reset();
await tick();
expect(new FormData(two).getAll("new")).toEqual(["a"]);
w.unmount();
});
it("renders and hydrates complete SSR associations and default selection", async () => {
const view = defineComponent({
render: () =>
group(kind, {
name: "choices",
defaultValue: kind === "checkbox" ? ["b"] : "b",
isRequired: true,
validationBehavior: "aria",
}),
});
const host = document.createElement("div");
host.innerHTML = await renderToString(createSSRApp(view));
document.body.append(host);
const ids = [...host.querySelectorAll("[id]")].map((el) => el.id);
for (const el of host.querySelectorAll(
"[aria-describedby],[aria-labelledby]",
))
for (const attr of ["aria-describedby", "aria-labelledby"])
for (const id of el.getAttribute(attr)?.split(" ") ?? [])
expect(ids).toContain(id);
const error = vi.spyOn(console, "error"),
warn = vi.spyOn(console, "warn"),
app = createSSRApp(view);
try {
app.mount(host);
await tick();
expect(error).not.toHaveBeenCalled();
expect(warn).not.toHaveBeenCalled();
expect(
host.querySelectorAll<HTMLInputElement>("input[data-choice-input]")[1]
.checked,
).toBe(true);
} finally {
app.unmount();
host.remove();
error.mockRestore();
warn.mockRestore();
}
});
});
}
it("handles radio arrows, RTL, disabled skipping and caller cancellation", async () => {
const w = mount(
group("radio", { defaultValue: "a", dir: "rtl" }, [
{},
{ isDisabled: true },
{},
]),
{ attachTo: document.body },
);
await tick();
expect(inputs(w).map((x) => x.attributes("tabindex"))).toEqual([
"0",
"-1",
"-1",
]);
await inputs(w)[0].trigger("keydown", { key: "ArrowLeft" });
await tick();
expect(inputs(w)[2].element.checked).toBe(true);
expect(document.activeElement).toBe(inputs(w)[2].element);
await inputs(w)[2].trigger("keydown", { key: "Home" });
await tick();
expect(inputs(w)[0].element.checked).toBe(true);
w.unmount();
const change = vi.fn();
const canceled = mount(
group("radio", {
defaultValue: "a",
"onUpdate:modelValue": change,
onKeydown: (e: Event) => e.preventDefault(),
}),
);
await tick();
await inputs(canceled)[0].trigger("keydown", { key: "ArrowDown" });
expect(change).not.toHaveBeenCalled();
canceled.unmount();
});
it("preserves dynamic slots, selection and classes when members reorder or disappear", async () => {
const values = ref(["a", "b", "c"]),
variant = ref<"primary" | "secondary">("primary");
const w = mount(
inForm(() =>
h(
CheckboxGroup,
{ name: "choices", defaultValue: ["b"], variant: variant.value },
() => [
h(Label, {}, () => "Options"),
...values.value.map((value) =>
h(Checkbox, { key: value, value, class: { custom: true } }, () =>
h(CheckboxContent, {}, () => value),
),
),
],
),
),
{ attachTo: document.body },
);
values.value = ["c", "b", "a"];
variant.value = "secondary";
await tick();
expect(formData(w)).toEqual([["choices", "b"]]);
expect(w.get("[data-slot=checkbox]").classes()).toContain(
"hv-checkbox--secondary",
);
values.value = ["a", "c"];
await tick();
expect(formData(w)).toEqual([]);
values.value = ["b", "a"];
await tick();
expect(formData(w)).toEqual([["choices", "b"]]);
w.unmount();
});
it("clears the current server errors on edit and accepts a replacement response", async () => {
const errors = ref<Record<string, string | string[]>>({
choice: ["First error", "Second error"],
});
const w = mount(
{
render: () =>
h(Form, { validationErrors: errors.value }, () =>
group("checkbox", { name: "choice" }),
),
},
{ attachTo: document.body },
);
await tick();
expect(w.get("[data-slot=field-error]").text()).toContain("First error");
await inputs(w)[0].setValue(true);
await tick();
expect(w.find("[data-slot=field-error]").exists()).toBe(false);
errors.value = { choice: "Replacement error" };
await tick();
expect(w.get("[data-slot=field-error]").text()).toBe("Replacement error");
w.unmount();
});
it("shows standalone native validation and allows aria override on grouped members", async () => {
const submit = vi.fn((e: Event) => e.preventDefault());
const w = mount(
inForm(
() =>
h(Checkbox, { isRequired: true, name: "terms" }, () => [
h(CheckboxContent, {}, () => "Terms"),
h(FieldError),
]),
{ onSubmit: submit },
),
{ attachTo: document.body },
);
(w.get("form").element as HTMLFormElement).requestSubmit();
await tick();
expect(submit).not.toHaveBeenCalled();
expect(w.get("[data-slot=field-error]").text()).toBe("请选择此选项。");
expect(document.activeElement).toBe(inputs(w)[0].element);
w.unmount();
const aria = mount(
inForm(
() =>
group("checkbox", { validationBehavior: "aria" }, [
{ isRequired: true },
{},
]),
{ onSubmit: submit },
),
{ attachTo: document.body },
);
await tick();
(aria.get("form").element as HTMLFormElement).requestSubmit();
expect(submit).toHaveBeenCalledOnce();
aria.unmount();
});
it("removes stale group label IDs and old attrs/events when parents update", async () => {
const attrs = ref<Record<string, unknown>>({}),
id = ref("label-one"),
handler = vi.fn();
const w = mount(
defineComponent({
render: () =>
h(CheckboxGroup, attrs.value, () => [
h(Label, { id: id.value }, () => "Group"),
option("checkbox", "a"),
]),
}),
);
attrs.value = {
class: ["custom", { more: true }],
"aria-label": "Accessible",
"onUpdate:modelValue": handler,
};
id.value = "label-two";
await tick();
expect(
w.get('[data-slot="checkbox-group"]').attributes("aria-labelledby"),
).toBe("label-two");
expect(w.classes()).toContain("more");
await inputs(w)[0].setValue(true);
expect(handler).toHaveBeenCalledOnce();
attrs.value = {};
await tick();
await inputs(w)[0].setValue(false);
expect(handler).toHaveBeenCalledOnce();
expect(w.classes()).not.toContain("custom");
expect(w.attributes("aria-label")).toBeUndefined();
attrs.value = { "aria-label": "Again" };
await tick();
expect(w.attributes("aria-label")).toBe("Again");
w.unmount();
});
it("honors the defaultSelected alias unless defaultChecked is explicitly provided", async () => {
const w = mount(
inForm(() =>
h("div", {}, [
option("checkbox", "a", { name: "choices", defaultSelected: true }),
option("checkbox", "b", {
name: "choices",
defaultSelected: true,
defaultChecked: false,
}),
]),
),
);
await tick();
expect(inputs(w)[0].element.checked).toBe(true);
expect(inputs(w)[1].element.checked).toBe(false);
expect(formData(w)).toEqual([["choices", "a"]]);
w.unmount();
});
it("switches control ownership even when a newly present model is explicitly undefined", async () => {
const attrs = ref<Record<string, unknown>>({
defaultChecked: true,
name: "choice",
});
const w = mount(inForm(() => option("checkbox", "a", attrs.value)));
await tick();
expect(formData(w)).toEqual([["choice", "a"]]);
attrs.value = { ...attrs.value, checked: undefined };
await tick();
expect(formData(w)).toEqual([]);
await inputs(w)[0].setValue(true);
await tick();
expect(inputs(w)[0].element.checked).toBe(false);
attrs.value = { defaultChecked: true, name: "choice" };
await tick();
expect(formData(w)).toEqual([["choice", "a"]]);
w.unmount();
});
it("keeps a readonly radio member unchanged when arrow navigation focuses it", async () => {
const w = mount(
inForm(() =>
group("radio", { defaultValue: "a" }, [{}, { isReadOnly: true }, {}]),
),
{ attachTo: document.body },
);
await tick();
await inputs(w)[0].trigger("keydown", { key: "ArrowDown" });
await tick();
expect(document.activeElement).toBe(inputs(w)[1].element);
expect(inputs(w)[0].element.checked).toBe(true);
expect(inputs(w)[1].element.checked).toBe(false);
w.unmount();
});
+50
View File
@@ -144,3 +144,53 @@ it("renders disabled fieldsets and search fields without browser globals", async
expect(html).toContain('data-slot="search-field-clear-button"');
expect(html).toContain('data-disabled="true"');
});
it("renders choice groups and nested content associations without browser globals", async () => {
const {
CheckboxGroup,
Checkbox,
CheckboxContent,
RadioGroup,
Radio,
RadioContent,
Label,
Description,
} = await import("../packages/vue/src");
const html = await renderToString(
createSSRApp({
render: () =>
h("form", {}, [
h(
CheckboxGroup,
{ name: "features", defaultValue: ["a"], isRequired: true },
() => [
h(Label, {}, () => "Features"),
h(Checkbox, { value: "a" }, () =>
h(CheckboxContent, {}, () => [
"A",
h(Description, {}, () => "Nested hint"),
]),
),
],
),
h(RadioGroup, { name: "plan", defaultValue: "pro" }, () => [
h(Label, {}, () => "Plan"),
h(Radio, { value: "basic" }, () =>
h(RadioContent, {}, () => "Basic"),
),
h(Radio, { value: "pro" }, () => h(RadioContent, {}, () => "Pro")),
]),
]),
}),
);
expect(html).toContain('name="features"');
expect(html).toContain('name="plan"');
expect(html).toContain('value="pro" checked');
const ids = [...html.matchAll(/\sid="([^"]+)"/g)].map((m) => m[1]);
const refs = [
...html.matchAll(/aria-(?:labelledby|describedby)="([^"]+)"/g),
].flatMap((m) => m[1].split(" "));
expect(new Set(ids).size).toBe(ids.length);
expect(refs.length).toBeGreaterThan(2);
for (const id of refs) expect(ids).toContain(id);
});