feat: add Fieldset and SearchField infrastructure

This commit is contained in:
maoyingjie
2026-10-22 08:46:02 +08:00
parent 116056832c
commit a4fb3c550a
59 changed files with 3131 additions and 331 deletions
+7
View File
@@ -303,3 +303,10 @@ Vaul Vue 官方已说明停止维护并推荐 Reka Drawer;新项目不采用 V
- 本库 InputGroup 是 TextField SSR 预规划支持的透明包装层,InputGroupInput/TextArea 显式 id 必须在服务端首屏就与 Label 匹配,并回归实际水合、动态 id 与插槽;不能只用直接 Input 的旧测试代替组合组件测试。任意用户 Vue 包装组件仍有已记录限制。
- invalid 与父字段错误合并;叶子 disabled/readonly/required 不能通过 false 解除父字段状态。文档不得把这些描述成可自由覆盖。
- 示例中的上游复制图标按钮若没有处理器,明确仅演示布局,不声称复制已经生效。未迁移 Tooltip 时,不能将其内容直接移到常驻操作栏改变布局;定时交互清理卸载时的定时器。
## FORM-02 之后的共享文件边界(2026-10-22)
- TextField 与 SearchField 共用 `field/useTextField.ts`,真实输入共用 useTextControl;Fieldset 禁用统一用 field/disabled.ts。不复制第二份值/reset/校验状态,不给一个字段生成重复表单值。
- 集成人维护上述内核、Fieldset/Legend、SearchField、Form 与 Switch。普通迁移任务遇到缺口先交失败场景,不自行改共享协议。
- 首个直接 Legend 与嵌套禁用必须按原生语义回归,不能简单给所有后代设置 disabled。SearchField 输入 Enter 的专属 submit 与原生表单提交不得重复,调用者取消、IME、Escape 空值与受控拒绝都有既有测试。
- 下一阶段 Checkbox/Radio 协议见 docs/decisions/selection-field-foundation.md;当前 Reka 的 CheckboxGroup 隐藏值序列化/禁用/reset 与目标有实际差异,不直接传 name 就宣布表单兼容。
+2
View File
@@ -55,11 +55,13 @@ const groups = [
{ title: "CloseButton 关闭按钮", url: "/components/close-button" },
{ title: "Description 描述", url: "/components/description" },
{ title: "FieldError 字段错误", url: "/components/field-error" },
{ title: "Fieldset 字段组", url: "/components/fieldset" },
{ title: "Input 输入框", url: "/components/input" },
{ title: "InputGroup 输入框组", url: "/components/input-group" },
{ title: "Kbd 键盘按键", url: "/components/kbd" },
{ title: "Label 标签", url: "/components/label" },
{ title: "Link 链接", url: "/components/link" },
{ title: "SearchField 搜索框", url: "/components/search-field" },
{ title: "Separator 分隔符", url: "/components/separator" },
{ title: "Skeleton 骨架屏", url: "/components/skeleton" },
{ title: "Spinner 加载指示器", url: "/components/spinner" },
+3
View File
@@ -25,3 +25,6 @@ description: 已迁移组件及文档
- [Switch 开关](./components/switch)
- [TextArea 多行文本框](./components/textarea)
- [TextField 文本输入框](./components/text-field)
- [Fieldset 字段组](./components/fieldset)
- [SearchField 搜索框](./components/search-field)
+130
View File
@@ -0,0 +1,130 @@
---
title: Fieldset 字段组
description: 将相关表单控件与图例、描述和操作组合在一起
component: fieldset
group: 组件
---
## 用法
```vue
<script setup lang="ts">
import {
Fieldset,
FieldsetLegend,
FieldGroup,
FieldsetActions,
} from "@heroui-vue/components";
</script>
```
<ComponentPreview name="fieldset-basic" />
## 组件结构
```vue
<script setup lang="ts">
import {
Fieldset,
FieldsetLegend,
FieldGroup,
FieldsetActions,
} from "@heroui-vue/components";
</script>
<template>
<Fieldset>
<FieldsetLegend />
<FieldGroup><!-- 表单字段 --></FieldGroup>
<FieldsetActions><!-- 操作按钮 --></FieldsetActions>
</Fieldset>
</template>
```
## 示例
### 表面样式
在 [Surface](/components/surface) 内使用时,请在表单控件(Input、TextArea 等)上使用 `variant="secondary"`,以应用适合 Surface 背景的低强调变体。
<ComponentPreview name="fieldset-on-surface" />
## 自定义样式
### Tailwind CSS
<ComponentPreview name="fieldset-custom-styles" />
### 全局 CSS
使用 `@layer components` 指令定位 Fieldset 的 [BEM](https://getbem.com/) 风格类。
```css
@layer components {
.hv-fieldset {
@apply gap-5 rounded-xl border border-border/60 bg-surface p-6 shadow-field;
}
.hv-fieldset__legend {
@apply text-lg font-semibold;
}
.hv-fieldset__field-group {
@apply gap-3 md:grid md:grid-cols-2;
}
.hv-fieldset__actions {
@apply flex justify-end gap-2 pt-2;
}
}
```
## 样式参考
HeroUI 遵循 [BEM](https://getbem.com/) 方法论,确保组件变体与状态可复用且易于自定义。
### CSS 类
Fieldset 复合组件暴露以下 CSS 选择器:
#### 基础类 [!toc]
- `.hv-fieldset` – 根容器
- `.hv-fieldset__legend` – 图例元素
- `.hv-fieldset__field-group` – 分组字段包裹层
- `.hv-fieldset__actions` – 字段下方的操作栏
## 禁用继承
原生 `disabled` 同步到本库文本输入、SearchField、Switch、Button、CloseButton 与 Link 的状态、事件和表单值。内层字段组不能解除祖先禁用;首个**直接** Legend 内的控件保留原生例外,仍受外层字段组与自身禁用约束。原生 legend 也支持,第三方自定义包装内部的 legend 不作静态识别,请直接使用 FieldsetLegend。
下面是本库新增的协议验证例,不属于上游三项基线示例。
<ComponentPreview name="fieldset-disabled" />
## API 参考
### Fieldset
| 属性 | 类型 | 默认值 | 描述 |
| --------------- | --------------------------- | ------- | ------------------------------ |
| `disabled` | `boolean` | `false` | 原生禁用并下发组件禁用上下文 |
| `name` / `form` | `string` | - | 原生 fieldset 属性,透传根节点 |
| `class` | `string \| Array \| Object` | - | 合并基础类 |
| 默认插槽 | 内容 | - | Legend、字段和操作区 |
### FieldsetLegend / FieldGroup / FieldsetActions
| 部件 | 根元素 | 属性与插槽 |
| --------------- | -------- | ----------------------------------------- |
| FieldsetLegend | `legend` | 原生属性、class/style、DOM 事件、默认插槽 |
| FieldGroup | `div` | 原生属性、class/style、DOM 事件、默认插槽 |
| FieldsetActions | `div` | 原生属性、class/style、DOM 事件、默认插槽 |
三个部件使用对应 BEM 基础类,class 接受字符串、数组和对象。命名导出替代 React 对象式子部件;原生属性直接传递,不使用 nativeProps 对象。根元素固定为语义化原生元素,暂不提供 React render 根元素替换。
Fieldset 不维护字段值或校验队列。请使用 Form + TextField / SearchField,提交与 reset 沿用原生表单;示例展示实际 FormData 与成功反馈,不执行后台保存。
## 相关组件
[TextField](./text-field) · [SearchField](./search-field) · [Input](./input)
+272
View File
@@ -0,0 +1,272 @@
---
title: SearchField 搜索框
description: 搜索输入字段,包含清除按钮与搜索图标。
component: search-field
group: 组件
---
## 用法
```vue
<script setup lang="ts">
import {
SearchField,
SearchFieldGroup,
SearchFieldInput,
SearchFieldSearchIcon,
SearchFieldClearButton,
Label,
Description,
FieldError,
} from "@heroui-vue/components";
</script>
```
<ComponentPreview name="search-field-basic" />
## 组件结构
```vue
<script setup lang="ts">
import {
SearchField,
SearchFieldGroup,
SearchFieldInput,
SearchFieldSearchIcon,
SearchFieldClearButton,
Label,
Description,
FieldError,
} from "@heroui-vue/components";
</script>
<template>
<SearchField>
<Label />
<SearchFieldGroup>
<SearchFieldSearchIcon />
<SearchFieldInput />
<SearchFieldClearButton />
</SearchFieldGroup>
<Description />
<FieldError />
</SearchField>
</template>
```
> **SearchField** 允许用户输入并清空搜索关键词。它包含搜索图标,并提供可选的清除按钮以便快速重置。
## 示例
### 变体
SearchField 组件支持两种视觉变体:
- **`primary`**(默认)— 带阴影的标准样式,适用于大多数场景
- **`secondary`** — 低强调、无阴影,适合在 Surface 等表面背景上使用
<ComponentPreview name="search-field-variants" />
### 表面样式
在 [Surface](/components/surface) 内使用时,请使用 `variant="secondary"`,以应用适合表面背景的低强调变体。
<ComponentPreview name="search-field-on-surface" />
### 带描述
<ComponentPreview name="search-field-with-description" />
### 必填字段
<ComponentPreview name="search-field-required" />
### 禁用状态
<ComponentPreview name="search-field-disabled" />
### 宽度充满
<ComponentPreview name="search-field-full-width" />
### 表单校验
将 `is-invalid` 与 `FieldError` 配合使用,以展示校验消息。
<ComponentPreview name="search-field-validation" />
### 受控组件
使用 v-model 控制值 以与其他组件同步或执行自定义格式化。
<ComponentPreview name="search-field-controlled" />
### 表单示例
完整的表单集成示例,包含校验、实际 FormData 和模拟提交反馈;没有后台搜索请求。
<ComponentPreview name="search-field-form-example" />
### 带校验
通过受控 value 实现自定义校验逻辑。
<ComponentPreview name="search-field-with-validation" />
### 自定义图标
自定义搜索图标与清除按钮图标。
<ComponentPreview name="search-field-custom-icons" />
### 键盘快捷键
添加快捷键以快速聚焦搜索框。
<ComponentPreview name="search-field-with-keyboard-shortcut" />
### 渲染函数
基线示例的根为 div + data-custom;Vue 通过根属性透传保留效果,暂不提供 React render 根类型替换。
<ComponentPreview
name="search-field-render-function"
/>
## 自定义样式
### Tailwind CSS
<ComponentPreview name="search-field-custom-styles" />
### 全局 CSS
若要自定义组件类,可使用 `@layer components` 指令。[了解更多](https://tailwindcss.com/docs/adding-custom-styles#adding-component-classes)。
```css
@layer components {
.hv-search-field {
@apply flex flex-col gap-1;
}
/* When invalid, the description is hidden automatically */
.hv-search-field[data-invalid],
.hv-search-field[aria-invalid] {
[data-slot="description"] {
@apply hidden;
}
}
.hv-search-field__group {
@apply bg-field text-field-foreground shadow-field rounded-field inline-flex h-9 items-center overflow-hidden border;
}
.hv-search-field__input {
@apply flex-1 rounded-none border-0 bg-transparent px-3 py-2 shadow-none outline-none;
}
.hv-search-field__search-icon {
@apply text-field-placeholder pointer-events-none shrink-0 ml-3 mr-0 size-4;
}
.hv-search-field__clear-button {
@apply mr-1 shrink-0;
}
}
```
## 样式参考
HeroUI 遵循 [BEM](https://getbem.com/) 方法论,确保组件变体与状态可复用且易于自定义。
### CSS 类
#### 基础类 [!toc]
- `.hv-search-field` – 根容器,样式非常克制(`flex flex-col gap-1`)
- `.hv-search-field__group` – 搜索图标、输入框与清除按钮的容器,包含边框与背景样式
- `.hv-search-field__input` – 搜索输入字段
- `.hv-search-field__search-icon` – 左侧显示的搜索图标
- `.hv-search-field__clear-button` – 用于清空搜索字段的按钮
#### 变体类 [!toc]
- `.hv-search-field--primary` – 带阴影的主变体(默认)
- `.hv-search-field--secondary` – 无阴影的次变体,适合用在 surface 上
> **说明:** 子组件([Label](/components/label)、[Description](/components/description)、[FieldError](/components/field-error))拥有各自的 CSS 类与样式。自定义方式请参见对应文档。
### 交互状态
SearchField 会根据状态自动管理以下 data 属性:
- **Invalid**:`[data-invalid="true"]` 或 `[aria-invalid="true"]` – 无效时会自动隐藏 description 插槽
- **Disabled**:`[data-disabled="true"]` – 当 `isDisabled` 为 true 时应用
- **Focus Within**:`[data-focus-within="true"]` – 当输入框聚焦时应用
- **Focus Visible**:`[data-focus-visible="true"]` – 当焦点可见(键盘导航)时应用
- **Hovered**:`[data-hovered="true"]` – 当悬停在整个组合上时应用
- **Empty**:`[data-empty="true"]` – 当字段为空时应用(会隐藏清除按钮)
更多状态由 Vue 作用域插槽提供,见下方 API。
## API 参考
### SearchField
SearchField 与 TextField 共用文本字段内核、表单策略和 ID 协议。一个根对应一个 SearchFieldInput;推荐在根使用 v-model。与父 TextField 嵌套时,搜索字段拥有独立上下文,不共享一个值。
| 属性 | 类型 | 默认值 | 描述 |
| ------------------------------------- | -------------------------------------------------------------------- | ---------------------- | ------------------------------------------------- |
| `modelValue` / `defaultValue` | `string` | - | 受控值 / 非受控初始值 |
| `variant` | `'primary' \| 'secondary'` | `'primary'` | 根与 Group 的视觉变体 |
| `fullWidth` | `boolean` | `false` | 根与 Group 全宽 |
| `isDisabled` / `isReadOnly` | `boolean` | `false` | 禁用 / 只读;均禁止清空,只读仍允许提交现有关键词 |
| `isRequired` | `boolean` | `false` | 原生或 aria 必填校验 |
| `isInvalid` | `boolean` | `false` | 错误展示状态,不单独阻止提交 |
| `validate` | `(value: string) => string \| string[] \| true \| null \| undefined` | - | 同步自定义校验 |
| `validationBehavior` | `'native' \| 'aria'` | 继承 Form,否则 native | native 拦截无效提交;aria 仅提供语义 |
| `name` / `id` / `type` | `string` | - / 自动 / `'search'` | 落在真实输入;叶子显式 id 优先 |
| `minLength` / `maxLength` / `pattern` | `number` / `number` / `string` | - | 下发原生约束 |
| `autoComplete` / `inputMode` / `form` | `string` | - | 下发真实输入 |
| `autoFocus` | `boolean` | `false` | 挂载后聚焦可用输入 |
| `class` / `style` | Vue class / style 绑定 | - | 根节点属性;ARIA 下发到输入 |
| 默认插槽 | 作用域插槽 | - | 字段部件及状态 |
服务端错误通过 Form 的 validationErrors 按 name 映射;不提供 SearchField 独立 validationErrors 数组。validate 暂不接受 Promise;FieldError 无完整 React Aria validationDetails。
### 事件与暴露
| 接口 | 参数 / 类型 | 行为 |
| ------------------- | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `update:modelValue` | `string` | 值变更请求;父级拒绝后恢复 DOM 值 |
| `submit` | `string` | 输入 Enter 时触发一次;忽略组合输入、重复按键和被取消的 keydown。注册 @submit 时接管该次 Enter,native 模式先校验;不再触发表单默认提交 |
| `clear` | 无参数 | 按钮或非空时 Escape 发出清空请求;恢复输入焦点,受控值仍由父级决定 |
| `focus()` | 无参数 | 模板 ref 方法,聚焦真实输入 |
| `element` | `HTMLInputElement \| undefined` | 模板 ref 公开实例中的实际控件 |
未监听 @submit 时,Enter 保留原生表单的隐式提交。@keydown.prevent 可取消搜索键盘行为,清除按钮的 @click.prevent 可取消清空。空值时按钮透明、不可交互且移出 Tab 顺序;只读/禁用时不可清空。Escape 空值时不拦截,可由外层弹层处理。
### 子部件
| 部件 | API / 根元素 | 说明 |
| ---------------------- | ------------------------------------------------------------ | ---------------------------------------------------------------------------------------------- |
| SearchFieldGroup | `div`,默认插槽,原生属性/事件 | 管理组合焦点、悬停、无效、禁用状态;继承根的变体/全宽 |
| SearchFieldInput | `input`;modelValue/defaultValue/type/invalid;原生属性/事件 | 共用 useTextControl;类型默认 search;name/约束/ARIA 落点为该 input;暴露 focus()/element |
| SearchFieldSearchIcon | 默认 SVG,或唯一默认插槽根 | 基线 IconSearch;自定义图标通过插槽合并 class,默认装饰语义 |
| SearchFieldClearButton | CloseButton;variant/isDisabled/disabled、DOM 事件及默认插槽 | type 固定 button;复用 CloseButton 外观与基线关闭图标;aria-label 默认 Clear,可按 locale 覆盖 |
各部件 class 均支持字符串、数组、对象,合并对应基础类;不使用 className/children 或 React render prop。
### 作用域插槽状态
| 参数 | 类型 | 说明 |
| ------------------------------------------------------------ | ---------- | ---------------------- |
| `isDisabled` / `isReadOnly` / `isRequired` / `isInvalid` | `boolean` | 当前字段状态 |
| `validationErrors` | `string[]` | 当前错误列表 |
| `isEmpty` / `isHovered` / `isFocusWithin` / `isFocusVisible` | `boolean` | 值、组合悬停与焦点状态 |
默认 SSR 关联包括直接或原生/Fragment/SearchFieldGroup 包裹的字段部件;任意 Vue 自定义包装仍需显式 id / aria-describedby 保证首屏引用,详情见字段协议。浅深主题、RTL 逻辑边距与 reduced-motion CSS 沿用基线,不据此宣称完成全部读屏/触屏/RTL 验收。
## 相关组件
[TextField](./text-field) · [InputGroup](./input-group) · [FieldError](./field-error)
+67
View File
@@ -0,0 +1,67 @@
<script setup lang="ts">
import {
Button,
Description,
FieldError,
FieldGroup,
Fieldset,
FieldsetLegend,
FieldsetActions,
Form,
Input,
Label,
TextArea,
TextField,
} from "@heroui-vue/components";
import { IconDeviceFloppy } from "@tabler/icons-vue";
import { ref } from "vue";
const result = ref("");
function validateName(value: string) {
return value.length < 3 ? "姓名至少需要 3 个字符" : null;
}
function validateBio(value: string) {
return value.length < 10 ? "简介至少需要 10 个字符" : null;
}
function submit(event: Event) {
const data = Object.fromEntries(
new FormData(event.currentTarget as HTMLFormElement),
);
result.value = `表单提交成功!${JSON.stringify(data)}`;
}
</script>
<template>
<Form class="w-full max-w-96" @submit.prevent="submit">
<Fieldset>
<FieldsetLegend>个人资料设置</FieldsetLegend>
<Description>更新你的个人资料信息。</Description>
<FieldGroup>
<TextField is-required name="name" :validate="validateName">
<Label>姓名</Label>
<Input placeholder="John Doe" />
<FieldError />
</TextField>
<TextField is-required name="email" type="email">
<Label>邮箱</Label>
<Input placeholder="john@example.com" />
<FieldError />
</TextField>
<TextField is-required name="bio" :validate="validateBio">
<Label>简介</Label>
<TextArea placeholder="介绍一下你自己…" />
<Description>至少 10 个字符</Description>
<FieldError />
</TextField>
</FieldGroup>
<FieldsetActions>
<Button type="submit">
<IconDeviceFloppy aria-hidden="true" />
保存更改
</Button>
<Button type="reset" variant="secondary" @click="result = ''">
取消
</Button>
</FieldsetActions>
</Fieldset>
<p v-if="result" class="text-sm text-muted" role="status">{{ result }}</p>
</Form>
</template>
@@ -0,0 +1,77 @@
<script setup lang="ts">
import {
Button,
Description,
FieldError,
FieldGroup,
Fieldset,
FieldsetLegend,
FieldsetActions,
Form,
Input,
Label,
TextArea,
TextField,
} from "@heroui-vue/components";
import { IconDeviceFloppy } from "@tabler/icons-vue";
import { ref } from "vue";
const result = ref("");
function validateName(value: string) {
return value.length < 3 ? "姓名至少需要 3 个字符" : null;
}
function validateBio(value: string) {
return value.length < 10 ? "简介至少需要 10 个字符" : null;
}
function submit(event: Event) {
const data = Object.fromEntries(
new FormData(event.currentTarget as HTMLFormElement),
);
result.value = `表单提交成功!${JSON.stringify(data)}`;
}
const shell =
"rounded-xl border border-border/70 bg-linear-to-b from-neutral-50/90 to-white p-4 ring-1 ring-black/5 dark:from-neutral-900/80 dark:to-neutral-900 dark:ring-white/10";
const fieldClass =
"rounded-xl border border-border/80 bg-surface shadow-sm ring-1 ring-black/5 transition-[box-shadow,border-color] focus-visible:ring-2 focus-visible:ring-neutral-400/25 dark:ring-white/10 dark:focus-visible:ring-neutral-500/30";
</script>
<template>
<Form class="w-full max-w-96" @submit.prevent="submit">
<Fieldset :class="shell">
<FieldsetLegend
class="font-medium text-neutral-800 dark:text-neutral-100"
>
个人资料设置
</FieldsetLegend>
<Description class="text-neutral-600 dark:text-neutral-400">
更新你的个人资料信息。
</Description>
<FieldGroup>
<TextField is-required name="name" :validate="validateName">
<Label>姓名</Label>
<Input :class="fieldClass" placeholder="John Doe" />
<FieldError />
</TextField>
<TextField is-required name="email" type="email">
<Label>邮箱</Label>
<Input :class="fieldClass" placeholder="john@example.com" />
<FieldError />
</TextField>
<TextField is-required name="bio" :validate="validateBio">
<Label>简介</Label>
<TextArea :class="fieldClass" placeholder="介绍一下你自己…" />
<Description>至少 10 个字符</Description>
<FieldError />
</TextField>
</FieldGroup>
<FieldsetActions>
<Button type="submit">
<IconDeviceFloppy aria-hidden="true" />
保存更改
</Button>
<Button type="reset" variant="secondary" @click="result = ''">
取消
</Button>
</FieldsetActions>
</Fieldset>
<p v-if="result" class="text-sm text-muted" role="status">{{ result }}</p>
</Form>
</template>
+76
View File
@@ -0,0 +1,76 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import {
Button,
FieldGroup,
Fieldset,
FieldsetActions,
FieldsetLegend,
Form,
Input,
Label,
Link,
Switch,
TextField,
} from "@heroui-vue/components";
const disabled = ref(true);
const result = ref("");
const buttonLabel = computed(() =>
disabled.value ? "启用字段组" : "禁用字段组",
);
function submit(event: Event) {
result.value = JSON.stringify(
Object.fromEntries(new FormData(event.currentTarget as HTMLFormElement)),
);
}
</script>
<template>
<div class="flex w-full max-w-96 flex-col gap-4">
<Button variant="secondary" @click="disabled = !disabled">
{{ buttonLabel }}
</Button>
<Form @submit.prevent="submit">
<Fieldset :disabled="disabled">
<FieldsetLegend>
禁用继承验证
<Label for="legend-action">可用的 Legend 标签</Label>
<Button
id="legend-action"
size="sm"
variant="ghost"
@click="result = 'Legend 操作可用'"
>
Legend 操作
</Button>
</FieldsetLegend>
<FieldGroup>
<TextField name="name" default-value="Jane">
<Label>姓名</Label>
<Input />
</TextField>
<Switch name="notifications" default-checked aria-label="接收通知" />
<Link
href="#disabled-inheritance"
@click.prevent="result = '链接操作可用'"
>
链接操作
</Link>
<Fieldset>
<FieldsetLegend>嵌套字段组</FieldsetLegend>
<Input name="nested" default-value="nested" aria-label="嵌套字段" />
</Fieldset>
</FieldGroup>
<FieldsetActions>
<Button type="submit">提交字段组</Button>
<Button type="reset" variant="secondary">重置</Button>
</FieldsetActions>
</Fieldset>
<Button type="submit" variant="tertiary" class="mt-4">
在组外查看提交值
</Button>
</Form>
<p role="status" aria-label="字段组结果" class="text-sm text-muted">
{{ result }}
</p>
</div>
</template>
+74
View File
@@ -0,0 +1,74 @@
<script setup lang="ts">
import {
Button,
Description,
FieldError,
FieldGroup,
Fieldset,
FieldsetLegend,
FieldsetActions,
Form,
Input,
Label,
TextArea,
TextField,
Surface,
} from "@heroui-vue/components";
import { IconDeviceFloppy } from "@tabler/icons-vue";
import { ref } from "vue";
const result = ref("");
function validateName(value: string) {
return value.length < 3 ? "姓名至少需要 3 个字符" : null;
}
function validateBio(value: string) {
return value.length < 10 ? "简介至少需要 10 个字符" : null;
}
function submit(event: Event) {
const data = Object.fromEntries(
new FormData(event.currentTarget as HTMLFormElement),
);
result.value = `表单提交成功!${JSON.stringify(data)}`;
}
</script>
<template>
<div class="flex items-center justify-center rounded-3xl bg-surface p-6">
<Surface class="w-full min-w-[380px] max-sm:min-w-0">
<Form @submit.prevent="submit">
<Fieldset class="w-full">
<FieldsetLegend>个人资料设置</FieldsetLegend>
<Description>更新你的个人资料信息。</Description>
<FieldGroup>
<TextField is-required name="name" :validate="validateName">
<Label>姓名</Label>
<Input variant="secondary" placeholder="John Doe" />
<FieldError />
</TextField>
<TextField is-required name="email" type="email">
<Label>邮箱</Label>
<Input variant="secondary" placeholder="john@example.com" />
<FieldError />
</TextField>
<TextField is-required name="bio" :validate="validateBio">
<Label>简介</Label>
<TextArea variant="secondary" placeholder="介绍一下你自己…" />
<Description>至少 10 个字符</Description>
<FieldError />
</TextField>
</FieldGroup>
<FieldsetActions>
<Button type="submit">
<IconDeviceFloppy aria-hidden="true" />
保存更改
</Button>
<Button type="reset" variant="tertiary" @click="result = ''">
取消
</Button>
</FieldsetActions>
</Fieldset>
<p v-if="result" class="text-sm text-muted" role="status">
{{ result }}
</p>
</Form>
</Surface>
</div>
</template>
+21
View File
@@ -0,0 +1,21 @@
<script setup lang="ts">
import {
SearchFieldClearButton,
SearchFieldSearchIcon,
SearchFieldGroup,
SearchFieldInput,
SearchField,
Label,
} from "@heroui-vue/components";
</script>
<template>
<SearchField name="search">
<Label>搜索</Label>
<SearchFieldGroup>
<SearchFieldSearchIcon />
<SearchFieldInput class="w-[280px]" placeholder="搜索…" />
<SearchFieldClearButton />
</SearchFieldGroup>
</SearchField>
</template>
@@ -0,0 +1,32 @@
<script setup lang="ts">
import {
SearchFieldClearButton,
SearchFieldSearchIcon,
SearchFieldGroup,
SearchFieldInput,
SearchField,
Label,
Description,
Button,
} from "@heroui-vue/components";
import { ref } from "vue";
const value = ref("");
</script>
<template>
<div class="flex flex-col gap-4">
<SearchField v-model="value" name="search">
<Label>搜索</Label>
<SearchFieldGroup>
<SearchFieldSearchIcon />
<SearchFieldInput class="w-[280px]" placeholder="搜索…" />
<SearchFieldClearButton />
</SearchFieldGroup>
<Description>当前值: {{ value || "(空)" }}</Description>
</SearchField>
<div class="flex gap-2">
<Button variant="tertiary" @click="value = ''">Clear</Button>
<Button variant="tertiary" @click="value = '示例查询'">设置示例</Button>
</div>
</div>
</template>
@@ -0,0 +1,30 @@
<script setup lang="ts">
import {
SearchFieldClearButton,
SearchFieldSearchIcon,
SearchFieldGroup,
SearchFieldInput,
SearchField,
Label,
Description,
} from "@heroui-vue/components";
import { IconFilter, IconCircleX } from "@tabler/icons-vue";
</script>
<template>
<div class="flex flex-col gap-4">
<SearchField name="search-custom">
<Label>搜索(自定义图标)</Label>
<SearchFieldGroup>
<SearchFieldSearchIcon>
<IconFilter aria-hidden="true" />
</SearchFieldSearchIcon>
<SearchFieldInput class="w-[280px]" placeholder="搜索…" />
<SearchFieldClearButton>
<IconCircleX aria-hidden="true" />
</SearchFieldClearButton>
</SearchFieldGroup>
<Description>自定义图标子元素</Description>
</SearchField>
</div>
</template>
@@ -0,0 +1,24 @@
<script setup lang="ts">
import {
SearchFieldClearButton,
SearchFieldSearchIcon,
SearchFieldGroup,
SearchFieldInput,
SearchField,
Label,
} from "@heroui-vue/components";
</script>
<template>
<SearchField class="w-full max-w-64" name="docs" variant="secondary">
<Label class="font-medium text-foreground">搜索文档</Label>
<SearchFieldGroup class="rounded-xl bg-default">
<SearchFieldSearchIcon class="text-muted" />
<SearchFieldInput
class="placeholder:text-muted"
placeholder="组件、指南..."
/>
<SearchFieldClearButton class="text-muted" />
</SearchFieldGroup>
</SearchField>
</template>
+34
View File
@@ -0,0 +1,34 @@
<script setup lang="ts">
import {
SearchFieldClearButton,
SearchFieldSearchIcon,
SearchFieldGroup,
SearchFieldInput,
SearchField,
Label,
Description,
} from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-4">
<SearchField is-disabled name="search" model-value="已禁用的搜索">
<Label>搜索</Label>
<SearchFieldGroup>
<SearchFieldSearchIcon />
<SearchFieldInput class="w-[280px]" placeholder="搜索…" />
<SearchFieldClearButton />
</SearchFieldGroup>
<Description>此搜索框已禁用</Description>
</SearchField>
<SearchField is-disabled name="search-empty">
<Label>搜索</Label>
<SearchFieldGroup>
<SearchFieldSearchIcon />
<SearchFieldInput class="w-[280px]" placeholder="搜索…" />
<SearchFieldClearButton />
</SearchFieldGroup>
<Description>此搜索框已禁用</Description>
</SearchField>
</div>
</template>
@@ -0,0 +1,70 @@
<script setup lang="ts">
import {
SearchFieldClearButton,
SearchFieldSearchIcon,
SearchFieldGroup,
SearchFieldInput,
SearchField,
Label,
Description,
FieldError,
Button,
Spinner,
} from "@heroui-vue/components";
import { Form } from "@heroui-vue/components";
import { computed, onBeforeUnmount, ref } from "vue";
const value = ref("");
const isSubmitting = ref(false);
const result = ref("");
const isInvalid = computed(
() => value.value.length > 0 && value.value.length < 3,
);
let timer: ReturnType<typeof setTimeout> | undefined;
onBeforeUnmount(() => clearTimeout(timer));
function submit(event: Event) {
if (value.value.length < 3 || isSubmitting.value) return;
const query = new FormData(event.currentTarget as HTMLFormElement).get(
"search",
);
isSubmitting.value = true;
timer = setTimeout(() => {
result.value = `已模拟提交搜索:${query}`;
value.value = "";
isSubmitting.value = false;
}, 1500);
}
</script>
<template>
<Form class="flex w-[280px] flex-col gap-4" @submit.prevent="submit">
<SearchField
v-model="value"
is-required
:is-invalid="isInvalid"
name="search"
>
<Label>搜索产品</Label>
<SearchFieldGroup>
<SearchFieldSearchIcon />
<SearchFieldInput class="w-full" placeholder="搜索产品…" />
<SearchFieldClearButton />
</SearchFieldGroup>
<FieldError v-if="isInvalid">搜索内容至少需要 3 个字符</FieldError>
<Description v-else>请输入至少 3 个字符后再搜索</Description>
</SearchField>
<Button
class="w-full"
:is-disabled="value.length < 3"
:is-pending="isSubmitting"
type="submit"
variant="primary"
>
<template v-if="isSubmitting">
<Spinner color="current" size="sm" />
搜索中…
</template>
<template v-else>搜索</template>
</Button>
<p v-if="result" role="status" class="text-sm text-muted">{{ result }}</p>
</Form>
</template>
@@ -0,0 +1,23 @@
<script setup lang="ts">
import {
SearchFieldClearButton,
SearchFieldSearchIcon,
SearchFieldGroup,
SearchFieldInput,
SearchField,
Label,
} from "@heroui-vue/components";
</script>
<template>
<div class="w-[400px] space-y-4">
<SearchField full-width name="search">
<Label>搜索</Label>
<SearchFieldGroup>
<SearchFieldSearchIcon />
<SearchFieldInput placeholder="搜索…" />
<SearchFieldClearButton />
</SearchFieldGroup>
</SearchField>
</div>
</template>
@@ -0,0 +1,35 @@
<script setup lang="ts">
import {
SearchFieldClearButton,
SearchFieldSearchIcon,
SearchFieldGroup,
SearchFieldInput,
SearchField,
Label,
Description,
Surface,
} from "@heroui-vue/components";
</script>
<template>
<Surface class="flex w-full max-w-sm flex-col gap-4 rounded-3xl p-6">
<SearchField name="search" variant="secondary">
<Label>搜索</Label>
<SearchFieldGroup>
<SearchFieldSearchIcon />
<SearchFieldInput class="w-full" placeholder="搜索…" />
<SearchFieldClearButton />
</SearchFieldGroup>
<Description>输入关键词进行搜索</Description>
</SearchField>
<SearchField name="search-2" variant="secondary">
<Label>高级搜索</Label>
<SearchFieldGroup>
<SearchFieldSearchIcon />
<SearchFieldInput class="w-full" placeholder="高级搜索…" />
<SearchFieldClearButton />
</SearchFieldGroup>
<Description>使用筛选条件细化搜索</Description>
</SearchField>
</Surface>
</template>
@@ -0,0 +1,21 @@
<script setup lang="ts">
import {
SearchFieldClearButton,
SearchFieldSearchIcon,
SearchFieldGroup,
SearchFieldInput,
SearchField,
Label,
} from "@heroui-vue/components";
</script>
<template>
<SearchField name="search" data-custom="foo">
<Label>搜索</Label>
<SearchFieldGroup>
<SearchFieldSearchIcon />
<SearchFieldInput class="w-[280px]" placeholder="搜索…" />
<SearchFieldClearButton />
</SearchFieldGroup>
</SearchField>
</template>
+33
View File
@@ -0,0 +1,33 @@
<script setup lang="ts">
import {
SearchFieldClearButton,
SearchFieldSearchIcon,
SearchFieldGroup,
SearchFieldInput,
SearchField,
Label,
Description,
} from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-4">
<SearchField is-required name="search">
<Label>搜索</Label>
<SearchFieldGroup>
<SearchFieldSearchIcon />
<SearchFieldInput class="w-[280px]" placeholder="搜索…" />
<SearchFieldClearButton />
</SearchFieldGroup>
</SearchField>
<SearchField is-required name="search-query">
<Label>搜索内容</Label>
<SearchFieldGroup>
<SearchFieldSearchIcon />
<SearchFieldInput class="w-[280px]" placeholder="输入搜索内容…" />
<SearchFieldClearButton />
</SearchFieldGroup>
<Description>至少需要 3 个字符</Description>
</SearchField>
</div>
</template>
@@ -0,0 +1,38 @@
<script setup lang="ts">
import {
SearchFieldClearButton,
SearchFieldSearchIcon,
SearchFieldGroup,
SearchFieldInput,
SearchField,
Label,
FieldError,
} from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-4">
<SearchField is-invalid is-required name="search" model-value="ab">
<Label>搜索</Label>
<SearchFieldGroup>
<SearchFieldSearchIcon />
<SearchFieldInput class="w-[280px]" placeholder="搜索…" />
<SearchFieldClearButton />
</SearchFieldGroup>
<FieldError>搜索内容至少需要 3 个字符</FieldError>
</SearchField>
<SearchField is-invalid name="search-invalid">
<Label>搜索</Label>
<SearchFieldGroup>
<SearchFieldSearchIcon />
<SearchFieldInput
class="w-[280px]"
placeholder="搜索…"
model-value="invalid@query"
/>
<SearchFieldClearButton />
</SearchFieldGroup>
<FieldError>搜索内容包含无效字符</FieldError>
</SearchField>
</div>
</template>
+31
View File
@@ -0,0 +1,31 @@
<script setup lang="ts">
import {
SearchFieldClearButton,
SearchFieldSearchIcon,
SearchFieldGroup,
SearchFieldInput,
SearchField,
Label,
} from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-4">
<SearchField name="primary-search" variant="primary">
<Label>主要变体</Label>
<SearchFieldGroup>
<SearchFieldSearchIcon />
<SearchFieldInput class="w-[280px]" placeholder="搜索…" />
<SearchFieldClearButton />
</SearchFieldGroup>
</SearchField>
<SearchField name="secondary-search" variant="secondary">
<Label>次要变体</Label>
<SearchFieldGroup>
<SearchFieldSearchIcon />
<SearchFieldInput class="w-[280px]" placeholder="搜索…" />
<SearchFieldClearButton />
</SearchFieldGroup>
</SearchField>
</div>
</template>
@@ -0,0 +1,34 @@
<script setup lang="ts">
import {
SearchFieldClearButton,
SearchFieldSearchIcon,
SearchFieldGroup,
SearchFieldInput,
SearchField,
Label,
Description,
} from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-4">
<SearchField name="search">
<Label>搜索产品</Label>
<SearchFieldGroup>
<SearchFieldSearchIcon />
<SearchFieldInput class="w-[280px]" placeholder="搜索产品…" />
<SearchFieldClearButton />
</SearchFieldGroup>
<Description>输入关键词进行搜索 for products</Description>
</SearchField>
<SearchField name="search-users">
<Label>搜索用户</Label>
<SearchFieldGroup>
<SearchFieldSearchIcon />
<SearchFieldInput class="w-[280px]" placeholder="搜索用户…" />
<SearchFieldClearButton />
</SearchFieldGroup>
<Description>按姓名、邮箱或用户名搜索</Description>
</SearchField>
</div>
</template>
@@ -0,0 +1,58 @@
<script setup lang="ts">
import {
SearchFieldClearButton,
SearchFieldSearchIcon,
SearchFieldGroup,
SearchFieldInput,
SearchField,
Label,
Description,
KbdAbbr,
KbdContent,
Kbd,
} from "@heroui-vue/components";
import { onBeforeUnmount, onMounted, ref } from "vue";
const input = ref<{ focus: () => void; element?: HTMLInputElement }>();
const value = ref("");
function keydown(event: KeyboardEvent) {
if (
event.shiftKey &&
event.key === "S" &&
!event.metaKey &&
!event.ctrlKey &&
!event.altKey &&
!event.isComposing
) {
event.preventDefault();
input.value?.focus();
}
if (event.key === "Escape" && document.activeElement === input.value?.element)
input.value.element.blur();
}
onMounted(() => window.addEventListener("keydown", keydown));
onBeforeUnmount(() => window.removeEventListener("keydown", keydown));
</script>
<template>
<div class="flex flex-col gap-4">
<div>
<SearchField v-model="value" name="search">
<Label>搜索</Label>
<SearchFieldGroup>
<SearchFieldSearchIcon />
<SearchFieldInput ref="input" class="w-[280px]" placeholder="搜索…" />
<SearchFieldClearButton />
</SearchFieldGroup>
<Description>使用键盘快捷键快速聚焦此输入框</Description>
</SearchField>
</div>
<div class="text-default-500 flex items-center gap-2 text-sm">
<span>按</span>
<Kbd>
<KbdAbbr key-value="shift" />
<KbdContent>S</KbdContent>
</Kbd>
<span>聚焦搜索框</span>
</div>
</div>
</template>
@@ -0,0 +1,37 @@
<script setup lang="ts">
import {
SearchFieldClearButton,
SearchFieldSearchIcon,
SearchFieldGroup,
SearchFieldInput,
SearchField,
Label,
Description,
FieldError,
} from "@heroui-vue/components";
import { computed, ref } from "vue";
const value = ref("");
const isInvalid = computed(
() => value.value.length > 0 && value.value.length < 3,
);
</script>
<template>
<div class="flex flex-col gap-4">
<SearchField
v-model="value"
is-required
:is-invalid="isInvalid"
name="search"
>
<Label>搜索</Label>
<SearchFieldGroup>
<SearchFieldSearchIcon />
<SearchFieldInput class="w-[280px]" placeholder="搜索…" />
<SearchFieldClearButton />
</SearchFieldGroup>
<FieldError v-if="isInvalid">搜索内容至少需要 3 个字符</FieldError>
<Description v-else>请输入至少 3 个字符后再搜索</Description>
</SearchField>
</div>
</template>
+6 -2
View File
@@ -57,13 +57,13 @@
| input-group | 验证中(字段接入) | Root/Input/TextArea/Prefix/Suffix;复用 useTextControl;变体继承 TextField 可覆盖;前后缀非表单字段 |
| textarea | 验证中(字段接入) | rows 默认 3;变体/fullWidth/受控/FormData/reset;独立页 7/7 示例;接入 useTextControl |
| textfield | 验证中(字段接入) | 值/状态/约束/校验/ID;独立页 13/13 示例;render 自定义根类型未支持(data-* 透传) |
| search-field | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| search-field | 验证中(FORM-02) | 五部件、15 基线例;共享文本内核、clear/submit/IME/reset/SSR,边界见 FORM-02 |
| typography | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| label | 验证中(通用字段) | 自动 for、Switch 内 span、状态继承;独立页 2/2 示例 |
| description | 验证中(通用字段) | 动态 ID 清理、外部 describedby 合并;独立页 2/2 示例;SSR 包装限制见基础协议 |
| empty-state | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| field-error | 验证中(通用字段) | 作用域插槽 validationErrors;独立页 2/2 示例;无完整 validationDetails(见基础协议) |
| fieldset | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| fieldset | 验证中(FORM-02) | 四部件、3 基线例与禁用验证例;响应式禁用、首 Legend 例外,边界见 FORM-02 |
| form | 验证中(基础设施) | native/aria 校验、FormData/reset、服务端错误;完整基线文档与生态集成未完成 |
| header | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| radio | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
@@ -161,3 +161,7 @@ Card 图片、头像、横向布局、表单与自定义样式已补齐;Input
- Label/Description/FieldError 正文中的必填/禁用/无效、表单组合、动态/多条错误示例已改为可运行 Vue 写法(v-model、作用域插槽)。
- TextArea:补 `rows` 默认 3;7 例齐全。值/reset/ARIA 仍由 useTextControl 管理。
- 差异:TextField `render` 不支持替换根元素类型(data-* 透传);FieldError 无 validationDetails,动态错误用作用域插槽。
## 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)。不据此声明整套表单体系完成。
+12 -8
View File
@@ -6,14 +6,14 @@
## 职责与文件
| 层次 | 实现 | 责任 |
| ---------------- | ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| 字段公共上下文 | `packages/vue/src/components/field/context.ts` | controlId、kind、禁用/只读/必填/错误状态、错误数组及描述/错误 ID 集合;Form 的策略与服务端错误上下文 |
| 字段部件 | `field/useFieldPart.ts`、Label、Description、FieldError | 标签与实际控件关联;动态 ID 注册与卸载清理;最邻近字段隔离 |
| 文本字段上下文 | `textfield/context.ts`、TextField.vue | 字符串值、初始值、校验、原生约束、继承变体、控件引用;标准组合的 SSR 描述预规划 |
| 原生文本控件适配 | `field/useTextControl.ts` | Input / TextArea 复用;值恢复、DOM 事件、ARIA/属性落点、原生 form reset 与清理 |
| Form | `form/Form.vue` | validationBehavior / validationErrors、提交校验、聚焦、原生 reset;不维护另一份字段值模型 |
| 既有 Switch | Switch.vue | 保留已验证的布尔值/原生 checkbox 逻辑,提供公共 FieldContext,接入 Form 策略与服务端错误 |
| 层次 | 实现 | 责任 |
| ---------------- | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| 字段公共上下文 | `packages/vue/src/components/field/context.ts` | controlId、kind、禁用/只读/必填/错误状态、错误数组及描述/错误 ID 集合;Form 的策略与服务端错误上下文 |
| 字段部件 | `field/useFieldPart.ts`、Label、Description、FieldError | 标签与实际控件关联;动态 ID 注册与卸载清理;最邻近字段隔离 |
| 文本字段上下文 | `textfield/context.ts`、TextField.vue / field/useTextField.ts | 字符串值、初始值、校验、原生约束、继承变体、控件引用;标准组合的 SSR 描述预规划 |
| 原生文本控件适配 | `field/useTextControl.ts` | Input / TextArea 复用;值恢复、DOM 事件、ARIA/属性落点、原生 form reset 与清理 |
| Form | `form/Form.vue` | validationBehavior / validationErrors、提交校验、聚焦、原生 reset;不维护另一份字段值模型 |
| 既有 Switch | Switch.vue | 保留已验证的布尔值/原生 checkbox 逻辑,提供公共 FieldContext,接入 Form 策略与服务端错误 |
## 不变条件
@@ -49,3 +49,7 @@
| M14 TextArea 文档与消费验证 | 对照上游核对 TextArea 缺口,补独立文档、示例和适用测试 | 已有 TextArea 值/表单逻辑不复制;尚不支持的能力列清单,必要协议修改由集成人完成 |
一次先交 M12 或 M13,两者共享导航、导出、矩阵等文件由单一负责人整合;尚未安排或派发这些任务。SearchField 的清空/提交事件语义、Fieldset 与 Checkbox/Radio 体系仍由集成人先验证,不在本次交出的范围。
## FORM-02 更新(2026-10-22)
M12–M14 已提交并复核,以上阶段 0 的“示例仅三项、尚未派发”属于历史。TextField 的状态/SSR/校验实现现位于 field/useTextField.ts,SearchField 复用同一内核;useTextControl 仍负责真实 Input/TextArea 的值恢复/reset。Fieldset 的独立禁用作用域已接入现有控件,首个直接 Legend 例外和嵌套有专项测试。完整交付见 FORM-02 报告;选择分组后续实施契约见 selection-field-foundation.md。
@@ -0,0 +1,35 @@
# Checkbox / Radio 分组协议准备(FORM-03 前置)
日期:2026-10-22。固定 HeroUI ce90ea3;以锁文件中的 Reka 2.11.x 实际安装代码为依据。
这是集成人下一阶段的实施边界与已验证缺口,**不是已实现的 Checkbox / Radio 公共组件**。
## 已经可以复用的设施
- `field/disabled.ts` 提供响应式禁用作用域;Fieldset 已处理父级禁用合并和首个直接 Legend 例外。新的 Reka Root 与其真实表单值层都必须接入,不能只改视觉 data 属性。
- `field/context.ts` 的表单策略与错误数据源继续沿用,Description/FieldError 的 ID 与错误展示协议不能另起一套。组字段需要明确的 group 语义与 Label aria-labelledby 注册;不把组标签的 for 指向 div,也不把每个组选项的必填星号重复展示。
- 单文本字段 `useTextField` 不承载集合模型。分组值使用 Vue 数组/标量状态协议,校验/原生字段层应与文本内核分开,但接入相同 Form。
## 本地实测底座缺口
临时行为探针直接导入已安装 Reka 的 CheckboxGroupRoot/CheckboxRoot 与 RadioGroupRoot/RadioGroupItem,挂载真实 form 后读取 FormData,未修改 node_modules:
1. disabled=true、defaultValue=['a']、name='choices' 的 CheckboxGroupRoot,FormData 仍有 `choices[0]=a`;禁用 RadioGroup 的值已省略。CheckboxGroup 内置 VisuallyHiddenInput 未接 disabled,且数组序列化为带索引键。
2. 非受控 CheckboxGroup 初始 ['a'],点击 b 后两个项目均 aria-checked=true;form.reset 后仍均为 true,没有恢复初始选择。
源码依据:`reka-ui/src/Checkbox/CheckboxGroupRoot.vue`、`CheckboxRoot.vue`、`RadioGroup/RadioGroupRoot.vue`、`RadioGroupItem.vue`、`shared/useFormControl.ts`。探针运行 1 项通过,输出复现上述事实,验证后移除;这不计入库的最终测试套件。
## 集成人实现约定
- 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 直接当作约束失败。
- reset 监听原生 form,非受控恢复初始副本,受控保留父级值;preventDefault 的 reset 保留当前状态。监听随 form 关联/卸载更新,数组必须复制,不能直接改 props。
- 组/成员 readonly 必须阻止鼠标、空格、方向键引起的值更新,并保留可聚焦性;拒绝更新后 Reka 的可见状态和原生值层必须恢复一致。
- 单一组选项注册表负责可用成员与焦点目标;稳定 key、条件插槽、成员重排、动态值、空组与重复值有明确策略。正式实现前用行为测试确定异常处理,不静默选择另一个成员。
- 读屏关联、orientation/dir/loop 和键盘行为按固定基线验收;CheckboxGroup 是否采用 Reka 默认 rovingFocus=true 需对照上游实际键盘契约,不能默认继承。
## 下一阶段完成条件
先做 Checkbox/CheckboxGroup 的真实状态与原生值层,再做 Radio/RadioGroup,并覆盖提交/reset、required 聚焦、readonly 键盘路径、Fieldset 嵌套、SSR/水合和成员变化。通过这些验证后才交出其文档/样式扩展任务。当前可继续交给其他 AI 的仍是 Typography、EmptyState、Breadcrumbs;不把这些分组协议准备写成 UI 已迁移。
@@ -0,0 +1,39 @@
# FORM-02 Fieldset / SearchField 与禁用基建
日期:2026-10-22。起点 `1160568`,初始工作区干净;本批由集成人实施。
## 范围与架构
- Fieldset / FieldsetLegend / FieldGroup / FieldsetActions 四个具名部件,原生语义,CSS 与 tv 从固定 ce90ea3 移植,仅 hv- 命名空间适配。
- 禁用作用域 `field/disabled.ts` 接入 TextField、独立 Input/TextArea、Label、Button、CloseButton、Link、Switch、SearchField。动态变化保持 ARIA/data/可交互性与 FormData 一致;本库 Fieldset 的首个直接 Legend 保留原生例外,内层 disabled=false 不能解除祖先禁用。keyed Legend 例外位置变化保留输入状态。
- 从既有 TextField 抽取 `field/useTextField.ts`,保持原有值、初始值、校验、Form、描述注册与 SSR 预规划。TextField 与 SearchField 共用内核,后者不挂额外 TextField DOM/CSS,也不复制字段状态。已存在测试全部回归。
- SearchField / Group / Input / SearchIcon / ClearButton 五个部件;Group 预规划明确的控件 ID,原始 Enter 表单提交与专属 submit 回调分开,调用方 root/input keydown 可取消;支持 IME/repeat 防护、Escape 非空清空、readonly/disabled、受控拒绝与焦点恢复。
- CloseButton 允许 data-slot 覆盖以接 SearchField 清除状态;其捕获 guard 和 Button guard 在用户捕获监听前阻止禁用激活。默认 IconSearch 来自基线 icons.tsx,沿用现有默认 CloseIcon;示例自定义图标使用 Tabler。
## 基线内容
- Fieldset 3/3:basic、on-surface、custom-styles;姓名/邮箱/简介、同步校验、保存/取消、Surface 与定制样式保持。新增 disabled 协议验证例另计。
- SearchField 15/15:basic、variants、on-surface、with-description、required、disabled、full-width、validation、controlled、form-example、with-validation、custom-icons、with-keyboard-shortcut、render-function、custom-styles。预览/复制/高亮共用 SFC。
- 基线 alert/console 提交反馈在 Vue 演示中改为 role=status 的实际 FormData/模拟查询结果;没有后台保存或搜索。定时器和快捷键监听卸载清理。Fieldset Surface 示例补窄屏 min-width 约束;未改变桌面目标宽度。
- Vue 不提供 React render 自定义根类型,根属性透传保留基线 div+data-custom 示例效果。原生属性直接透传而非 nativeProps。错误仍通过 Form.validationErrors,校验暂仅同步。
## 验证
- `pnpm test`:14 文件 / 226 项,含 node SSR 4 项。
- `pnpm test:unit`:13 文件 / 222 项,不含 node SSR;包含实际 jsdom 水合。
- `pnpm typecheck`、`pnpm build:docs`、`pnpm format`、`git diff --check` 通过。
- 新增专项 17 项、node SSR 1 项:禁用传播、首个/多个/原生/动态 Legend、嵌套、FormData、省略、受控拒绝、reset/取消、clear/focus、Enter/Escape、IME/repeat、事件取消/数组、SSR/水合、动态 attrs/变体/图标、实际字段演示提交与 reset、SSR 叶子初始值和显式 ID 删除。
- 组件 CSS 还原 hv- 前缀、去注释与空白后与固定基线一致;styles/index.css 另有明确的 Vue Legend 标签适配,防止祖先禁用选择器压暗原生例外中的可用标签;公共类型产物检查见 verification.md。
## 浏览器实测(5173)
- /components/search-field:清空后 value=''、实际 input 保持焦点、按钮 aria-hidden=true 且 opacity=0;Escape 清空;Enter 表单提交出现搜索中…,完成反馈“已模拟提交搜索:verified query”,值恢复为空。
- SearchField 浅/深切换,深色 group 背景 oklch(0.2103 0.0059 285.89),高度 36px、圆角 12px。390×844 时所有 group 在视口内,四张 API/事件/插槽表 350px,无水平溢出。
- /components/fieldset:无效提交显示姓名/邮箱/简介错误;填入 Jane / jane@example.com / 详细简介后真实 FormData 反馈正确。禁用例组外提交={};Legend 操作可用;启用后提交 name/notifications/nested 值。首个 Legend 内 Label 实测 opacity=1、pointer-events=auto,点击能激活其关联按钮。390×844 页面与表格无溢出;1280×900 表格均为 736px 与正文等宽。
- 控制台 error/warn 为空。临时主题恢复浅色,视口恢复正常。截图 `/private/tmp/heroui-vue-form02-fieldset.png`。
## 边界与后续
未完成独立打包安装、自动视觉比较、完整读屏/触屏/RTL、Nuxt;没有据 CSS 一致宣称逐像素一致。Fieldset 仅静态识别直接/Fragment 中的 Legend,不识别任意自定义 Vue 包装内部的原生 Legend。
Checkbox/Radio 分组底座发现 disabled 原生值与 reset 缺口,实测和实施契约见 `docs/decisions/selection-field-foundation.md`,仍由集成人先实施。Typography/EmptyState/Breadcrumbs 可继续交给其他 AI,明确冻结共享字段、禁用、Form 与 SearchField 协议。
@@ -0,0 +1,42 @@
# M15–M17 下一轮迁移提示词
可交给其他 AI;此文件不代表已派发。
```text
在 heroui-vue 独立仓库依次迁移 M15 Typography、M16 EmptyState、M17 Breadcrumbs。
先读取 AGENTS.md、docs/migration-handoff.md、docs/compatibility.md、docs/upstream.md、
docs/migrations/FORM-02-fieldset-search-field.md,记录实际起始 Git HEAD。
上游只读 ../heroui,固定 HeroUI 3.2.6 / ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960。
先核对实际导出、React 实现、CSS/tv、中文文档和全部基线示例,再列清单实施。
Typography 不能只做一个 p:核对 Typography/Heading/Paragraph/Code/Prose 的真实导出,
覆盖默认语义元素、全部变体、标题级别、字重/颜色/对齐/截断与正文排版。
EmptyState 在基线有实现,但没有独立中文组件页。依据真实源码/现有消费场景建立明确标注的
Vue 文档和示例,不虚构官方文案或示例数量;默认 fallback、空/条件插槽、class/attrs 需验证。
Breadcrumbs 核对全部子部件、分隔符、当前页、禁用与链接、折叠/省略等实际基线能力;
检查 aria-current、导航名称与键盘焦点,不擅自加入未存在的自动折叠状态机。
组件和文档的样式、布局、文案、参数默认值、主题和状态高度对齐固定基线,
只把框架机制改成 Vue v-model/插槽/具名导出;React 专属或不支持的能力记录准确差异。
图标用 @tabler/icons-vue,禁止自绘 SVG;基础包不引入整套图标依赖。
预览、复制和高亮来自同一 SFC。API 对每个部件核对 class、属性落点、事件、默认插槽和暴露。
正文表格铺满内容区、长内容自动换行,不缩字号、不截断、不横向滚动。
Markdown 中完整 Vue 示例也要真实提取编译/运行,不把字符串断言或正则绑定检查称作编译。
共享边界:不改 field/*、TextField、Form、Fieldset、SearchField、Switch 的核心协议;
不重写主题、文档布局或构建链路。Checkbox/Radio 基建仍由集成人处理。
复用既有 Link 和 disabled 作用域,若需要公共行为补充,提供最小失败用例给集成人。
各自新增组件目录、CSS/变体、导出/类型、独立文档与全部基线演示;共享入口/导航/矩阵仅
本批必要增量。同一 checkout 如有集成人并行工作,先约定共享文件归属,禁止双方同时编辑。
行为验证按适用性覆盖动态 attrs 空→增→改→删→再增、class 字符串/数组/对象、事件更换与取消、
动态/空/条件/Fragment 插槽与 key 保留、禁用和主题;公开 dist 类型既测合法值也测非法值。
真实浏览器 5173 检查桌面/窄屏、浅深主题、主要状态和长短表格,不换端口、不结束他人服务。
执行 pnpm test、pnpm test:unit、pnpm typecheck、pnpm build:docs、pnpm format;
新测试文件加入 unit 列表,分别记录各入口实际文件数/项数/SSR,未验证范围明确说明。
每项写 docs/migrations/M15-typography.md、M16-empty-state.md、M17-breadcrumbs.md,
包含来源许可、API/示例逐项对照、改动文件、检查结果、浏览器证据、差异及最短复核步骤。
按顺序完成,三个任务报告分别保留;遇到核心协议阻断先交失败场景,其余无依赖任务可继续。
不自行提交/推送,不宣布集成人验收通过,交回检查后统一提交。
```
+4
View File
@@ -55,3 +55,7 @@
- InputGroup 演示图标由 `@gravity-ui/icons` 替换为 Tabler(IconMail/IconWorld/IconCopy/IconEye/IconEyeOff/IconAt/IconPlus/IconPlugConnected/IconMicrophone/IconArrowUp);with-textarea 的 Tooltip 以原生 title/aria-label 适配。
- M13–M14:`apps/docs/content/docs/cn/react/components/(forms)/{text-field,label,description,field-error,text-area}.mdx` 与 `apps/docs/src/demos/cn/{textfield,textarea,label,description,field-error}/` 的文档结构、正文代码示例与 26 个文档引用预览(TextField 13 + Label 2 + Description 2 + FieldError 2 + TextArea 7)。
- TextArea `rows` 默认值 3 来自上游 API 表;CSS/变体此前已移植为 hv- 命名空间。
## 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 在窄屏解除。
+10
View File
@@ -264,3 +264,13 @@
结论见 [独立报告](./migrations/M13-M14-review.md#返工后独立复核2026-10-21):FieldError 正文完整 SFC 经独立提取、vue-tsc 检查及原文动态/多条错误运行检查通过,TextField/ TextArea 公共接口文档补齐。公开 element 直接断言真实 DOM,focus 确认实际焦点。
最终 pnpm test 为 13 文件 / 208 项(含 node SSR 3 项);pnpm test:unit 为 12 文件 / 205 项(不含 node SSR)。pnpm typecheck、pnpm build:docs、pnpm format、git diff --check 通过。另有临时正文原文行为探针 2 项通过、dist 类型探针通过,探针验证后删除,不计入最终套件数量。未重新逐页浏览器检查,未新增逐像素、Nuxt、RTL、读屏或独立安装验收。
## FORM-02(2026-10-22)
详细步骤、差异与证据见 [FORM-02 报告](./migrations/FORM-02-fieldset-search-field.md)。`pnpm test` 14 文件 / 226 项(含 node SSR 4);`pnpm test:unit` 13 文件 / 222 项(不含 node SSR)。typecheck/build:docs/format/diff-check 通过。
5173 的 SearchField 实测 clear/Escape/焦点/原生 Enter 提交与加载恢复,浅深主题、390×844 四表均 350px 无溢出。Fieldset 实测三字段校验与真实提交、禁用省略/Legend 例外/嵌套与启用恢复,390px 无溢出,1280×900 两表为 736px。error/warn 控制台为空;视口和主题恢复。截图 `/private/tmp/heroui-vue-form02-fieldset.png`。没有独立安装、自动视觉、完整触屏/读屏/RTL 或 Nuxt 验收。
CheckboxGroup 底座行为临时探针单独验证了禁用值仍提交与 reset 不恢复,1 项运行后移除,不计入最终226项;不能将它描述为本库已支持分组。
公共 dist 类型探针由 vue-tsc 验证:Fieldset disabled、SearchField 合法 variant/modelValue 可用,非法 variant、数字 modelValue 和异步 validate 被拒绝。临时探针移除。新增 SSR 预规划覆盖叶子初始值的 empty 状态,显式控件 ID 删除后恢复自动 ID。
+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/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/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 .",
+20
View File
@@ -0,0 +1,20 @@
/* Adapted from HeroUI v3 ce90ea3. Copyright 2025 NextUI Inc.
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix. */
/* Base component styles */
.hv-fieldset {
@apply flex flex-col gap-6;
/* fix flexbox issue in Safari when fieldset with legend is inside a flexbox */
@apply shrink grow basis-0;
}
.hv-fieldset__legend {
@apply text-base font-medium text-foreground;
}
.hv-fieldset__field-group {
@apply w-full space-y-4;
}
.hv-fieldset__actions {
@apply flex items-center gap-2 pt-1;
}
+188
View File
@@ -0,0 +1,188 @@
/* Adapted from HeroUI v3 ce90ea3. Copyright 2025 NextUI Inc.
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix. */
/* Search field styles */
.hv-search-field {
@apply flex flex-col gap-1;
&[data-invalid="true"],
&[aria-invalid="true"] {
[data-slot="description"] {
@apply hidden;
}
}
[data-slot="label"] {
@apply w-fit;
}
&[data-empty="true"] {
[data-slot="search-field-clear-button"] {
@apply pointer-events-none opacity-0;
}
}
}
.hv-search-field__group {
@apply relative inline-flex h-9 items-center overflow-hidden rounded-field border bg-field text-sm text-field-foreground shadow-field outline-none;
border-width: var(--border-width-field);
border-color: var(--field-border);
/**
* Transitions
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
*/
transition:
background-color 150ms var(--ease-smooth),
border-color 150ms var(--ease-smooth),
box-shadow 150ms var(--ease-out);
@apply motion-reduce:transition-none;
/* Hover state */
@media (hover: hover) {
&:hover:not(:focus-within),
&[data-hovered="true"]:not([data-focus-within="true"]) {
@apply bg-field-hover;
border-color: var(--field-border-hover);
}
}
/* Focus within state */
&[data-focus-within="true"],
&:focus-within {
@apply status-focused-field;
}
/* Invalid state */
&[data-invalid="true"] {
@apply status-invalid-field;
background-color: var(--field-focus);
border-color: var(--color-field-border-invalid);
}
/* Disabled state */
&[data-disabled="true"],
&[aria-disabled="true"] {
@apply status-disabled;
}
/**
* Browser autofill state.
* The user-agent paints `:-webkit-autofill`/`:autofill` on the inner <input>
* only. Because the input has its border-radius stripped on whichever side
* touches the search icon or clear button, the autofill highlight ends up
* as a sharp-cornered rectangle and the sibling slots receive no highlight.
* Lift the highlight onto the group so the rounded shell + icon + clear
* button all share it.
*/
&:has([data-slot="search-field-input"]:-webkit-autofill),
&:has([data-slot="search-field-input"]:autofill) {
background-color: var(--field-focus);
border-color: var(--field-border-focus);
}
}
.hv-search-field__input {
@apply flex-1 rounded-none border-0 bg-transparent px-3 py-2 text-base shadow-none outline-none sm:text-sm;
/* Hide browser default search clear button */
&::-webkit-search-cancel-button,
&::-webkit-search-decoration {
-webkit-appearance: none;
appearance: none;
}
/* Remove border radius on left side when search icon is present */
.hv-search-field__group:has([data-slot="search-field-search-icon"]) & {
@apply rounded-s-none ps-2;
}
/* Remove border radius on right side when clear button is present */
.hv-search-field__group:has([slot="clear"]) & {
@apply rounded-e-none pe-2;
}
/* Focus state - handled by group */
&:focus,
&:focus-visible {
@apply outline-none;
}
/**
* Neutralize the browser's per-input autofill paint so the inner <input>
* doesn't draw a sharp-cornered yellow rectangle. The unified highlight
* is applied to `.hv-search-field__group` above. Preserve the autofilled
* text and caret colors, and pin the background-color transition so the
* inset box-shadow trick doesn't flicker on state changes.
*/
&:-webkit-autofill,
&:-webkit-autofill:hover,
&:-webkit-autofill:focus,
&:-webkit-autofill:active,
&:autofill {
-webkit-box-shadow: 0 0 0 1000px transparent inset;
box-shadow: 0 0 0 1000px transparent inset;
-webkit-text-fill-color: var(--field-foreground);
caret-color: var(--field-foreground);
transition: background-color 9999s ease-in-out 0s;
}
}
.hv-search-field__search-icon {
@apply pointer-events-none shrink-0 text-field-placeholder;
@apply ms-3 me-0 size-4;
}
.hv-search-field__clear-button {
@apply me-2 size-5 shrink-0;
/* Overrides close button default icon size from 16px to 12px */
[data-slot="close-button-icon"] {
@apply size-3;
}
}
/* Variant property definitions */
.hv-search-field--primary {
/* Default styles */
}
.hv-search-field--secondary .hv-search-field__group {
@apply shadow-none;
background-color: var(--search-field-group-bg);
--search-field-group-bg: var(--default);
--search-field-group-bg-hover: var(--default-hover);
--search-field-group-bg-focus: var(--default);
@media (hover: hover) {
&:hover:not(:focus-within),
&[data-hovered="true"]:not([data-focus-within="true"]) {
background-color: var(--search-field-group-bg-hover);
}
}
&:focus-within,
&[data-focus-within="true"] {
background-color: var(--search-field-group-bg-focus);
}
/* Invalid state */
&[data-invalid="true"] {
@apply status-invalid-field;
border-color: var(--color-field-border-invalid);
background-color: var(--search-field-group-bg-focus);
}
[data-slot="search-field-input"] {
@apply bg-transparent;
}
}
/* Full width modifier */
.hv-search-field--full-width {
@apply w-full;
}
.hv-search-field__group--full-width {
@apply w-full;
}
+17
View File
@@ -60,3 +60,20 @@
@import "./components/textfield.css";
@import "./components/field-error.css";
@import "./components/fieldset.css" layer(components);
@import "./components/search-field.css" layer(components);
/* Vue disabled scopes preserve native first-legend semantics. A label in the
* exempt legend must not pick up the baseline blanket ancestor opacity rule.
* Local and outer disabled labels still carry hv-label--disabled. */
@layer components {
.hv-fieldset[data-disabled="true"]
> legend
.hv-label:not(.hv-label--disabled) {
opacity: 1;
cursor: inherit;
pointer-events: auto;
}
}
+45
View File
@@ -529,3 +529,48 @@ export const inputGroupVariants = tv({
});
export type InputGroupVariants = VariantProps<typeof inputGroupVariants>;
export const fieldsetVariants = tv({
slots: {
actions: "hv-fieldset__actions",
base: "hv-fieldset",
description: "hv-fieldset__description",
fieldGroup: "hv-fieldset__field-group",
legend: "hv-fieldset__legend",
},
});
export type FieldsetVariants = VariantProps<typeof fieldsetVariants>;
export const searchFieldVariants = tv({
defaultVariants: {
fullWidth: false,
variant: "primary",
},
slots: {
base: "hv-search-field",
clearButton: "hv-search-field__clear-button",
group: "hv-search-field__group",
input: "hv-search-field__input",
searchIcon: "hv-search-field__search-icon",
},
variants: {
fullWidth: {
false: {},
true: {
base: "hv-search-field--full-width",
group: "hv-search-field__group--full-width",
},
},
variant: {
primary: {
base: "hv-search-field--primary",
},
secondary: {
base: "hv-search-field--secondary",
},
},
},
});
export type SearchFieldVariants = VariantProps<typeof searchFieldVariants>;
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { useInheritedDisabled } from "../field/disabled";
import { computed, ref, watch } from "vue";
import { Primitive } from "reka-ui";
import type { ButtonHTMLAttributes } from "vue";
@@ -21,7 +22,7 @@ const props = withDefaults(
{ type: "button" },
);
const pending = computed(() => props.isPending || props.loading);
const disabled = computed(() => props.isDisabled || props.disabled);
const disabled = useInheritedDisabled(() => props.isDisabled || props.disabled);
const hovered = ref(false),
pressed = ref(false),
focused = ref(false),
@@ -37,7 +38,7 @@ watch(
{ flush: "sync" },
);
function guard(e: MouseEvent) {
if (pending.value) {
if (pending.value || disabled.value) {
e.preventDefault();
e.stopImmediatePropagation();
}
@@ -49,6 +50,7 @@ function focus(e: FocusEvent) {
</script>
<template>
<Primitive
@click.capture="guard"
as="button"
:as-child="asChild"
v-bind="$attrs"
@@ -63,7 +65,6 @@ function focus(e: FocusEvent) {
:data-focused="focused || undefined"
:data-focus-visible="focusVisible || undefined"
data-slot="button"
@click.capture="guard"
@pointerenter="hovered = !pending && !disabled"
@pointerleave="
hovered = false;
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { useInheritedDisabled } from "../field/disabled";
import { computed, ref, useAttrs, watch } from "vue";
import {
closeButtonVariants,
@@ -17,7 +18,7 @@ const props = withDefaults(
);
const attrs = useAttrs();
const disabled = computed(() => props.isDisabled || props.disabled);
const disabled = useInheritedDisabled(() => props.isDisabled || props.disabled);
const ariaLabel = computed(() =>
typeof attrs["aria-label"] === "string" ? attrs["aria-label"] : "Close",
);
@@ -62,6 +63,8 @@ function focus(e: FocusEvent) {
<template>
<button
@click.capture="guard"
@keydown.capture="onKeydownGuard"
v-bind="attrs"
:type="'button'"
:class="closeButtonVariants({ variant })"
@@ -72,9 +75,7 @@ function focus(e: FocusEvent) {
:data-pressed="(!disabled && pressed) || undefined"
:data-focused="focused || undefined"
:data-focus-visible="focusVisible || undefined"
data-slot="close-button"
@click.capture="guard"
@keydown.capture="onKeydownGuard"
:data-slot="attrs['data-slot'] ?? 'close-button'"
@pointerenter="hovered = !disabled"
@pointerleave="
hovered = false;
@@ -0,0 +1,9 @@
import { computed, inject, type ComputedRef, type InjectionKey } from "vue";
/** Semantic disabled scope, including controls with no native disabled attribute. */
export const disabledContextKey: InjectionKey<ComputedRef<boolean>> =
Symbol("HeroUIVue.Disabled");
export function useInheritedDisabled(local: () => unknown = () => false) {
const parent = inject(disabledContextKey, undefined);
return computed(() => Boolean(local() || parent?.value));
}
@@ -8,6 +8,7 @@ import {
ref,
watch,
} from "vue";
import { useInheritedDisabled } from "./disabled";
import { mergeIds, formContextKey } from "./context";
import { textFieldContextKey } from "../textfield/context";
@@ -41,8 +42,11 @@ export function useTextControl(
() => props.modelValue ?? field?.value.value ?? internal.value,
);
const attrBoolean = (value: unknown) => value != null && value !== false;
const inheritedDisabled = useInheritedDisabled();
const disabled = () =>
attrBoolean(attrs.disabled) || Boolean(field?.disabled.value);
inheritedDisabled.value ||
attrBoolean(attrs.disabled) ||
Boolean(field?.disabled.value);
const readOnly = () =>
attrBoolean(attrs.readonly ?? attrs.readOnly) ||
Boolean(field?.readOnly.value);
@@ -97,7 +101,10 @@ export function useTextControl(
form = next;
form?.addEventListener("reset", reset);
}
onMounted(bindForm);
onMounted(() => {
field?.setControl(element.value);
bindForm();
});
onUpdated(bindForm);
onBeforeUnmount(() => {
form?.removeEventListener("reset", reset);
@@ -0,0 +1,346 @@
import {
Comment,
Fragment,
cloneVNode,
computed,
h,
mergeProps,
inject,
isVNode,
provide,
ref,
shallowRef,
useId,
watchEffect,
type PropType,
type ExtractPropTypes,
type Slots,
type VNode,
type VNodeChild,
} from "vue";
import {
fieldContextKey,
formContextKey,
errorMessages,
mergeIds,
type ValidateResult,
type ValidationBehavior,
} from "./context";
import {
textFieldContextKey,
type TextFieldContext,
} from "../textfield/context";
import { useInheritedDisabled } from "./disabled";
export const textFieldProps = {
modelValue: String,
defaultValue: String,
name: String,
id: String,
type: String,
minLength: Number,
maxLength: Number,
pattern: String,
autoComplete: String,
inputMode: String,
form: String,
isDisabled: Boolean,
isReadOnly: Boolean,
isRequired: Boolean,
isInvalid: Boolean,
fullWidth: Boolean,
variant: String as PropType<"primary" | "secondary">,
validationBehavior: String as PropType<ValidationBehavior>,
validate: Function as PropType<(value: string) => ValidateResult>,
} as const;
export function useTextField(
props: Readonly<ExtractPropTypes<typeof textFieldProps>>,
{
attrs,
slots,
emit,
expose,
}: {
attrs: Record<string, unknown>;
slots: Slots;
emit: (event: "update:modelValue", value: string) => void;
expose: (exposed: Record<string, unknown>) => void;
},
options: {
rootSlot?: string;
rootClass?: () => unknown;
rootAttrs?: () => Record<string, unknown>;
slotState?: () => Record<string, unknown>;
} = {},
) {
const form = inject(formContextKey, undefined);
const generated = useId();
const leafId = ref<string>();
const controlId = computed(() => leafId.value ?? props.id ?? generated);
const internal = ref(props.defaultValue ?? "");
let initialized =
props.modelValue !== undefined || props.defaultValue !== undefined;
let initialValue = props.defaultValue ?? "";
const value = computed(() => props.modelValue ?? internal.value);
const control = shallowRef<HTMLInputElement | HTMLTextAreaElement>();
const touched = ref(false),
nativeError = ref("");
const dismissed = shallowRef<object>();
const descriptionIds = ref<string[]>([]),
errorIds = ref<string[]>([]);
// Pre-plan direct/native-wrapped parts before rendering controls, so SSR has
// complete ID associations even when Description follows Input.
const plannedDescriptions = ref<string[]>([]),
plannedErrors = ref<string[]>([]);
let lastPlan = "";
const behavior = computed(
() =>
props.validationBehavior ?? form?.validationBehavior.value ?? "native",
);
const disabled = useInheritedDisabled(() => props.isDisabled);
const readOnly = computed(() => props.isReadOnly);
const required = computed(() => props.isRequired);
const serverErrors = computed(() => {
const source = form?.validationErrors.value;
return source && source !== dismissed.value && props.name
? errorMessages(source[props.name])
: [];
});
const customErrors = computed(() =>
errorMessages(props.validate?.(value.value)),
);
const errors = computed(() => [
...serverErrors.value,
...(touched.value || behavior.value === "aria" ? customErrors.value : []),
...((touched.value || behavior.value === "aria") && nativeError.value
? [nativeError.value]
: []),
]);
const invalid = computed(
() =>
props.isInvalid ||
attrs["aria-invalid"] === true ||
attrs["aria-invalid"] === "true" ||
errors.value.length > 0,
);
function setValue(next: string) {
if (disabled.value || readOnly.value) return;
internal.value = next;
dismissed.value = form?.validationErrors.value;
nativeError.value = "";
emit("update:modelValue", next);
}
function initialize(next: string) {
if (!initialized) {
internal.value = next;
initialValue = next;
initialized = true;
}
}
const field: TextFieldContext = {
controlId,
kind: "text",
disabled,
readOnly,
required,
invalid,
errors,
descriptionIds,
errorIds,
value,
name: computed(() => props.name),
type: computed(() => props.type),
variant: computed(() => props.variant),
validationBehavior: behavior,
controlAttrs: () => ({
minlength: props.minLength,
maxlength: props.maxLength,
pattern: props.pattern,
autocomplete: props.autoComplete,
inputmode: props.inputMode,
form: props.form,
...Object.fromEntries(
Object.entries(attrs).filter(([key]) => key.startsWith("aria-")),
),
}),
describedBy: () =>
mergeIds(
attrs["aria-describedby"] as string | undefined,
descriptionIds.value,
plannedDescriptions.value,
invalid.value ? [...errorIds.value, ...plannedErrors.value] : [],
),
setControlId: (id) => {
leafId.value = id;
},
initialize,
setValue,
syncValue: (next) => {
internal.value = next;
},
setControl: (next) => {
control.value = next;
},
onInvalid(event) {
if (behavior.value === "aria") return;
touched.value = true;
const element = event.target as HTMLInputElement | HTMLTextAreaElement;
nativeError.value =
customErrors.value.length || serverErrors.value.length
? ""
: element.validationMessage;
},
onReset() {
internal.value = initialValue;
touched.value = false;
nativeError.value = "";
dismissed.value = form?.validationErrors.value;
},
};
provide(fieldContextKey, field);
provide(textFieldContextKey, field);
watchEffect(
() => {
const currentValue = value.value;
control.value?.setCustomValidity(
behavior.value === "native" && !disabled.value && !readOnly.value
? [...serverErrors.value, ...customErrors.value].join(" ")
: "",
);
if (behavior.value === "native" && touched.value)
nativeError.value =
customErrors.value.length || serverErrors.value.length
? ""
: (control.value?.validationMessage ?? "");
if (behavior.value === "aria")
nativeError.value =
disabled.value || readOnly.value
? ""
: required.value && !currentValue
? "请填写此字段。"
: (control.value?.validationMessage ?? "");
},
{ flush: "post" },
);
expose({ focus: () => control.value?.focus(), element: control });
function prepare(
nodes: VNodeChild[],
found: {
description: string[];
error: string[];
controlId?: string;
controlValue?: string;
hasControl?: boolean;
},
path = "",
): VNodeChild[] {
return nodes.map((node, index) => {
if (!isVNode(node) || node.type === Comment) return node;
const position = `${path}-${index}`;
const type = node.type as { name?: string; __name?: string };
const name = type?.name ?? type?.__name;
if (
name === "Input" ||
name === "TextArea" ||
name === "InputGroupInput" ||
name === "InputGroupTextArea" ||
name === "SearchFieldInput"
) {
found.hasControl = true;
found.controlId = node.props?.id;
found.controlValue = node.props?.modelValue ?? node.props?.defaultValue;
}
if (name === "Description" || name === "FieldError") {
const kind = name === "Description" ? "description" : "error";
const id = node.props?.id ?? `${generated}-${kind}${position}`;
found[kind].push(String(id));
return cloneVNode(node, { id });
}
// InputGroup is a library-owned transparent field wrapper. Prepare its
// default slot once, preserving the current render's values and keys.
// Arbitrary consumer components remain opaque to SSR planning.
if (
(name === "InputGroup" || name === "SearchFieldGroup") &&
node.children &&
typeof node.children === "object"
) {
const groupSlots = node.children as { default?: () => VNodeChild[] };
if (typeof groupSlots.default === "function") {
const prepared = prepare(groupSlots.default(), found, position);
const clone = cloneVNode(node);
clone.children = { ...groupSlots, default: () => prepared };
return clone;
}
}
if (
(typeof node.type === "string" || node.type === Fragment) &&
Array.isArray(node.children)
) {
const clone = cloneVNode(node);
clone.children = prepare(
node.children as VNodeChild[],
found,
position,
) as VNode[];
return clone;
}
return node;
});
}
const render = () => {
const found: {
description: string[];
error: string[];
controlId?: string;
controlValue?: string;
hasControl?: boolean;
} = { description: [], error: [] };
const children = prepare(
slots.default?.({
isDisabled: disabled.value,
isReadOnly: readOnly.value,
isRequired: required.value,
isInvalid: invalid.value,
validationErrors: errors.value,
...options.slotState?.(),
}) ?? [],
found,
);
if (found.hasControl && leafId.value !== found.controlId)
leafId.value = found.controlId;
if (found.controlValue !== undefined) initialize(found.controlValue);
const nextPlan = JSON.stringify(found);
if (lastPlan !== nextPlan) {
lastPlan = nextPlan;
plannedDescriptions.value = found.description;
plannedErrors.value = found.error;
}
return h(
"div",
mergeProps(
{
...Object.fromEntries(
Object.entries(attrs).filter(([key]) => !key.startsWith("aria-")),
),
class: [
options.rootClass?.() ?? [
"hv-textfield",
props.fullWidth && "hv-textfield--full-width",
],
attrs.class,
],
"data-slot": options.rootSlot ?? "textfield",
"data-invalid": invalid.value || undefined,
"data-disabled": disabled.value || undefined,
"data-required": required.value || undefined,
"data-readonly": readOnly.value || undefined,
},
options.rootAttrs?.() ?? {},
),
children,
);
};
return { field, element: control, render };
}
@@ -0,0 +1,14 @@
<script setup lang="ts">
import { fieldsetVariants } from "@heroui-vue/styles";
defineOptions({ inheritAttrs: false });
const styles = fieldsetVariants();
</script>
<template>
<div
v-bind="$attrs"
:class="[styles.fieldGroup(), $attrs.class]"
data-slot="fieldset-field-group"
>
<slot />
</div>
</template>
@@ -0,0 +1,80 @@
<script lang="ts">
import {
computed,
defineComponent,
Fragment,
h,
inject,
isVNode,
provide,
type VNode,
type VNodeChild,
} from "vue";
import { fieldsetVariants } from "@heroui-vue/styles";
import { disabledContextKey } from "../field/disabled";
// A renderless scope preserves the native first direct legend exemption.
const LegendScope = defineComponent({
props: { disabled: Boolean },
setup(props, { slots }) {
provide(
disabledContextKey,
computed(() => props.disabled),
);
return () => slots.default?.();
},
});
export default defineComponent({
name: "Fieldset",
inheritAttrs: false,
props: { disabled: Boolean },
setup(props, { attrs, slots }) {
const parent = inject(disabledContextKey, undefined);
const disabled = computed(() => props.disabled || Boolean(parent?.value));
provide(disabledContextKey, disabled);
const styles = fieldsetVariants();
return () => {
let firstLegend = true;
function prepare(nodes: VNodeChild[]): VNodeChild[] {
return nodes.flatMap((node) => {
if (!isVNode(node)) return [node];
if (node.type === Fragment && Array.isArray(node.children))
return prepare(node.children as VNode[]);
const type = node.type as { name?: string; __name?: string };
if (
node.type === "legend" ||
(type.name ?? type.__name) === "FieldsetLegend"
) {
const legendDisabled = firstLegend
? Boolean(parent?.value)
: disabled.value;
firstLegend = false;
return [
h(
LegendScope,
{
key: node.key ?? undefined,
disabled: legendDisabled,
},
() => node,
),
];
}
return [node];
});
}
return h(
"fieldset",
{
...attrs,
disabled: props.disabled,
"data-disabled": disabled.value || undefined,
"data-slot": "fieldset",
class: [styles.base(), attrs.class],
},
prepare(slots.default?.() ?? []),
);
};
},
});
</script>
@@ -0,0 +1,14 @@
<script setup lang="ts">
import { fieldsetVariants } from "@heroui-vue/styles";
defineOptions({ inheritAttrs: false });
const styles = fieldsetVariants();
</script>
<template>
<div
v-bind="$attrs"
:class="[styles.actions(), $attrs.class]"
data-slot="fieldset-actions"
>
<slot />
</div>
</template>
@@ -0,0 +1,14 @@
<script setup lang="ts">
import { fieldsetVariants } from "@heroui-vue/styles";
defineOptions({ inheritAttrs: false });
const styles = fieldsetVariants();
</script>
<template>
<legend
v-bind="$attrs"
:class="[styles.legend(), $attrs.class]"
data-slot="fieldset-legend"
>
<slot />
</legend>
</template>
+5 -1
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { inject, useAttrs } from "vue";
import { useInheritedDisabled } from "../field/disabled";
import { fieldContextKey } from "../field/context";
defineOptions({ inheritAttrs: false });
const field = inject(fieldContextKey, undefined);
@@ -9,6 +10,9 @@ const props = defineProps<{
isDisabled?: boolean;
isInvalid?: boolean;
}>();
const disabled = useInheritedDisabled(
() => props.isDisabled || field?.disabled.value,
);
</script>
<template>
<component
@@ -20,7 +24,7 @@ const props = defineProps<{
class="hv-label"
:class="{
'hv-label--required': props.isRequired || field?.required.value,
'hv-label--disabled': props.isDisabled || field?.disabled.value,
'hv-label--disabled': disabled,
'hv-label--invalid': props.isInvalid || field?.invalid.value,
}"
data-slot="label"
+21 -11
View File
@@ -1,10 +1,12 @@
<script setup lang="ts">
import { useInheritedDisabled } from "../field/disabled";
import {
provide,
ref,
computed,
useAttrs,
onMounted,
watch,
onBeforeUnmount,
} from "vue";
import { Primitive } from "reka-ui";
@@ -30,6 +32,7 @@ const props = withDefaults(
},
);
const disabled = useInheritedDisabled(() => props.isDisabled);
const slots = linkVariants();
provide(linkContextKey, { slots });
@@ -39,6 +42,13 @@ const hovered = ref(false),
focused = ref(false),
focusVisible = ref(false);
watch(disabled, (value) => {
if (value) {
hovered.value = false;
pressed.value = false;
}
});
const element = ref<HTMLElement>();
function resolveElement(raw: unknown): HTMLElement | undefined {
@@ -110,7 +120,7 @@ function liveAttr(name: string): MaybeHandlers {
}
function guardClick(e: Event, parent: MaybeHandlers) {
if (props.isDisabled) {
if (disabled.value) {
e.preventDefault();
e.stopImmediatePropagation();
return;
@@ -121,7 +131,7 @@ function guardClick(e: Event, parent: MaybeHandlers) {
/** Disabled-only gate for key events that must not synthesize activation. */
function guardKeyPassthrough(e: Event, parent: MaybeHandlers) {
const ke = e as KeyboardEvent;
if (props.isDisabled && isActivationKey(ke)) {
if (disabled.value && isActivationKey(ke)) {
ke.preventDefault();
ke.stopImmediatePropagation();
return;
@@ -131,7 +141,7 @@ function guardKeyPassthrough(e: Event, parent: MaybeHandlers) {
function guardKeydownBubble(e: Event, parent: MaybeHandlers) {
const ke = e as KeyboardEvent;
if (props.isDisabled && isActivationKey(ke)) {
if (disabled.value && isActivationKey(ke)) {
ke.preventDefault();
ke.stopImmediatePropagation();
return;
@@ -139,7 +149,7 @@ function guardKeydownBubble(e: Event, parent: MaybeHandlers) {
callHandlers(parent, e);
if (
!props.asChild ||
props.isDisabled ||
disabled.value ||
!isEnterKey(ke) ||
ke.defaultPrevented ||
wasImmediateStopped(e)
@@ -254,19 +264,19 @@ defineExpose({
:download="downloadAttr"
:class="slots.base()"
:role="asChild ? 'link' : undefined"
:tabindex="asChild ? 0 : undefined"
:aria-disabled="isDisabled || undefined"
:data-hovered="(!isDisabled && hovered) || undefined"
:data-pressed="(!isDisabled && pressed) || undefined"
:tabindex="disabled ? -1 : asChild ? 0 : undefined"
:aria-disabled="disabled || undefined"
:data-hovered="(!disabled && hovered) || undefined"
:data-pressed="(!disabled && pressed) || undefined"
:data-focused="focused || undefined"
:data-focus-visible="focusVisible || undefined"
data-slot="link"
@pointerenter="hovered = !isDisabled"
@pointerenter="hovered = !disabled"
@pointerleave="
hovered = false;
pressed = false;
"
@pointerdown="pressed = !isDisabled"
@pointerdown="pressed = !disabled"
@pointerup="pressed = false"
@focus="focus"
@blur="
@@ -276,7 +286,7 @@ defineExpose({
"
>
<slot
:is-disabled="isDisabled"
:is-disabled="Boolean(disabled)"
:is-hovered="hovered"
:is-pressed="pressed"
:is-focused="focused"
@@ -0,0 +1,121 @@
<script lang="ts">
import {
computed,
defineComponent,
getCurrentInstance,
nextTick,
onMounted,
provide,
ref,
} from "vue";
import { searchFieldVariants } from "@heroui-vue/styles";
import { textFieldProps, useTextField } from "../field/useTextField";
import { searchFieldContextKey } from "./context";
export default defineComponent({
name: "SearchField",
inheritAttrs: false,
props: {
...textFieldProps,
type: { type: String, default: "search" },
autoFocus: Boolean,
},
emits: {
"update:modelValue": (_value: string) => true,
submit: (_value: string) => true,
clear: () => true,
},
setup(props, context) {
const instance = getCurrentInstance();
const hovered = ref(false),
focused = ref(false),
focusVisible = ref(false);
const slots = computed(() =>
searchFieldVariants({
variant: props.variant,
fullWidth: props.fullWidth,
}),
);
const { field, element, render } = useTextField(props, context, {
rootSlot: "search-field",
rootClass: () => slots.value.base(),
rootAttrs: () => ({
onKeydown: keydown,
"data-empty": !field.value.value || undefined,
"data-focus-within": focused.value || undefined,
"data-focus-visible": focusVisible.value || undefined,
"data-hovered": (!field.disabled.value && hovered.value) || undefined,
}),
slotState: () => ({
isEmpty: !field.value.value,
isHovered: !field.disabled.value && hovered.value,
isFocusWithin: focused.value,
isFocusVisible: focusVisible.value,
}),
});
function clear(event?: Event) {
const input = element.value;
if (
event?.defaultPrevented ||
!input ||
field.disabled.value ||
field.readOnly.value ||
!field.value.value
)
return;
// The native input path also updates an explicitly controlled leaf and
// restores rejected values through the same useTextControl adapter.
input.value = "";
input.dispatchEvent(new Event("input", { bubbles: true }));
context.emit("clear");
void nextTick(() => input.focus());
}
function keydown(event: KeyboardEvent) {
if (event.target !== element.value) return;
if (
event.defaultPrevented ||
event.isComposing ||
event.keyCode === 229 ||
event.repeat ||
field.disabled.value
)
return;
if (
event.key === "Escape" &&
!field.readOnly.value &&
field.value.value
) {
event.preventDefault();
clear();
} else if (
event.key === "Enter" &&
(instance?.vnode.props?.onSubmit || instance?.vnode.props?.onSubmitOnce)
) {
event.preventDefault();
if (
field.validationBehavior.value === "native" &&
element.value &&
!element.value.reportValidity()
)
return;
context.emit("submit", field.value.value);
}
// Without @submit, let the browser perform the enclosing form's normal
// implicit submission. Never synthesize a second form submission.
}
provide(searchFieldContextKey, {
field,
slots,
hovered,
focused,
focusVisible,
clear,
keydown,
});
onMounted(() => {
if (props.autoFocus && !field.disabled.value) element.value?.focus();
});
return render;
},
});
</script>
@@ -0,0 +1,45 @@
<script setup lang="ts">
import { inject } from "vue";
import {
searchFieldVariants,
type CloseButtonVariants,
} from "@heroui-vue/styles";
import CloseButton from "../close-button/CloseButton.vue";
import { searchFieldContextKey } from "./context";
defineOptions({ inheritAttrs: false });
defineProps<{
variant?: CloseButtonVariants["variant"];
isDisabled?: boolean;
disabled?: boolean;
}>();
const context = inject(searchFieldContextKey, undefined);
const fallback = searchFieldVariants();
</script>
<template>
<CloseButton
v-bind="$attrs"
:class="[
context?.slots.value.clearButton() ?? fallback.clearButton(),
$attrs.class,
]"
:variant="variant"
:is-disabled="
isDisabled ||
disabled ||
context?.field.disabled.value ||
context?.field.readOnly.value
"
:aria-label="$attrs['aria-label'] ?? 'Clear'"
:aria-hidden="!context?.field.value.value || undefined"
:tabindex="
!context?.field.value.value ? -1 : ($attrs.tabindex as number | undefined)
"
data-slot="search-field-clear-button"
slot="clear"
@click="context?.clear"
>
<template v-if="$slots.default" #default="state">
<slot v-bind="state" />
</template>
</CloseButton>
</template>
@@ -0,0 +1,50 @@
<script setup lang="ts">
import { inject, watch } from "vue";
import { searchFieldVariants } from "@heroui-vue/styles";
import { searchFieldContextKey } from "./context";
defineOptions({ inheritAttrs: false });
const context = inject(searchFieldContextKey, undefined);
const fallback = searchFieldVariants();
watch(
() => context?.field.disabled.value,
(disabled) => {
if (disabled && context) {
context.hovered.value = false;
context.focused.value = false;
context.focusVisible.value = false;
}
},
);
function blur(event: FocusEvent) {
if (
context &&
!(event.currentTarget as HTMLElement).contains(
event.relatedTarget as Node | null,
)
) {
context.focused.value = false;
context.focusVisible.value = false;
}
}
</script>
<template>
<div
v-bind="$attrs"
:class="[context?.slots.value.group() ?? fallback.group(), $attrs.class]"
:role="typeof $attrs.role === 'string' ? $attrs.role : 'group'"
data-slot="search-field-group"
:data-disabled="context?.field.disabled.value || undefined"
:data-invalid="context?.field.invalid.value || undefined"
:data-hovered="context?.hovered.value || undefined"
:data-focus-within="context?.focused.value || undefined"
:aria-disabled="context?.field.disabled.value || undefined"
@pointerenter="
context && (context.hovered.value = !context.field.disabled.value)
"
@pointerleave="context && (context.hovered.value = false)"
@focusin="context && (context.focused.value = true)"
@focusout="blur"
>
<slot />
</div>
</template>
@@ -0,0 +1,51 @@
<script setup lang="ts">
import { inject, useAttrs } from "vue";
import { useTextControl } from "../field/useTextControl";
import { searchFieldContextKey } from "./context";
defineOptions({ inheritAttrs: false });
const props = defineProps<{
modelValue?: string;
defaultValue?: string;
invalid?: boolean;
type?: string;
}>();
const emit = defineEmits<{ "update:modelValue": [value: string] }>();
const attrs = useAttrs();
const group = inject(searchFieldContextKey, undefined);
const control = useTextControl(props, attrs, emit);
const { element, value } = control;
defineExpose({ focus: () => element.value?.focus(), element });
</script>
<template>
<input
ref="element"
v-bind="{ ...control.inheritedAttrs(), ...attrs }"
:value="value"
:id="control.id()"
:name="control.name()"
:type="control.type()"
:disabled="control.disabled()"
:readonly="control.readOnly()"
:required="control.required()"
:class="[group?.slots.value.input(), attrs.class]"
:data-invalid="control.invalid() || undefined"
:aria-invalid="control.invalid() || undefined"
:aria-readonly="control.readOnly() || undefined"
:aria-describedby="control.describedBy()"
:data-validation-behavior="control.validationBehavior()"
data-slot="search-field-input"
@input="control.update"
@invalid="control.onInvalid"
@focus="
group &&
(group.focusVisible.value = ($event.target as HTMLElement).matches(
':focus-visible',
))
"
/>
</template>
@@ -0,0 +1,48 @@
<script setup lang="ts">
import { inject } from "vue";
import { Primitive } from "reka-ui";
import { searchFieldVariants } from "@heroui-vue/styles";
import { searchFieldContextKey } from "./context";
defineOptions({ inheritAttrs: false });
const context = inject(searchFieldContextKey, undefined);
const fallback = searchFieldVariants();
</script>
<template>
<Primitive
v-if="$slots.default"
as-child
v-bind="$attrs"
:class="[
context?.slots.value.searchIcon() ?? fallback.searchIcon(),
$attrs.class,
]"
aria-hidden="true"
data-slot="search-field-search-icon"
>
<slot />
</Primitive>
<!-- Default IconSearch ported from the fixed HeroUI icons.tsx baseline; see HEROUI-LICENSE. -->
<svg
v-else
v-bind="$attrs"
:class="[
context?.slots.value.searchIcon() ?? fallback.searchIcon(),
$attrs.class,
]"
aria-hidden="true"
fill="none"
height="16"
role="presentation"
viewBox="0 0 16 16"
width="16"
xmlns="http://www.w3.org/2000/svg"
data-slot="search-field-search-icon"
>
<path
clip-rule="evenodd"
d="M11.5 7a4.5 4.5 0 1 1-9 0a4.5 4.5 0 0 1 9 0m-.82 4.74a6 6 0 1 1 1.06-1.06l2.79 2.79a.75.75 0 1 1-1.06 1.06z"
fill="currentColor"
fill-rule="evenodd"
/>
</svg>
</template>
@@ -0,0 +1,15 @@
import type { ComputedRef, InjectionKey, Ref } from "vue";
import type { searchFieldVariants } from "@heroui-vue/styles";
import type { TextFieldContext } from "../textfield/context";
export interface SearchFieldContext {
field: TextFieldContext;
slots: ComputedRef<ReturnType<typeof searchFieldVariants>>;
hovered: Ref<boolean>;
focused: Ref<boolean>;
focusVisible: Ref<boolean>;
clear: (event?: Event) => void;
keydown: (event: KeyboardEvent) => void;
}
export const searchFieldContextKey: InjectionKey<SearchFieldContext> = Symbol(
"HeroUIVue.SearchField",
);
@@ -1,4 +1,5 @@
<script setup lang="ts">
import { useInheritedDisabled } from "../field/disabled";
import {
computed,
inject,
@@ -97,7 +98,7 @@ const serverMessages = computed(() => {
const checked = computed(
() => props.isSelected ?? props.checked ?? internal.value,
);
const disabled = computed(() => props.isDisabled || props.disabled);
const disabled = useInheritedDisabled(() => props.isDisabled || props.disabled);
const readOnly = computed(() => props.isReadOnly);
const required = computed(() => props.isRequired || props.required);
const invalid = computed(
@@ -1,306 +1,13 @@
<script lang="ts">
import {
Comment,
Fragment,
cloneVNode,
computed,
defineComponent,
h,
inject,
isVNode,
provide,
ref,
shallowRef,
useId,
watchEffect,
type PropType,
type VNode,
type VNodeChild,
} from "vue";
import {
fieldContextKey,
formContextKey,
errorMessages,
mergeIds,
type ValidateResult,
type ValidationBehavior,
} from "../field/context";
import { textFieldContextKey, type TextFieldContext } from "./context";
import { defineComponent } from "vue";
import { textFieldProps, useTextField } from "../field/useTextField";
export default defineComponent({
name: "TextField",
inheritAttrs: false,
props: {
modelValue: String,
defaultValue: String,
name: String,
id: String,
type: String,
minLength: Number,
maxLength: Number,
pattern: String,
autoComplete: String,
inputMode: String,
form: String,
isDisabled: Boolean,
isReadOnly: Boolean,
isRequired: Boolean,
isInvalid: Boolean,
fullWidth: Boolean,
variant: String as PropType<"primary" | "secondary">,
validationBehavior: String as PropType<ValidationBehavior>,
validate: Function as PropType<(value: string) => ValidateResult>,
},
props: textFieldProps,
emits: { "update:modelValue": (_value: string) => true },
setup(props, { attrs, slots, emit, expose }) {
const form = inject(formContextKey, undefined);
const generated = useId();
const leafId = ref<string>();
const controlId = computed(() => leafId.value ?? props.id ?? generated);
const internal = ref(props.defaultValue ?? "");
let initialized =
props.modelValue !== undefined || props.defaultValue !== undefined;
let initialValue = props.defaultValue ?? "";
const value = computed(() => props.modelValue ?? internal.value);
const control = shallowRef<HTMLInputElement | HTMLTextAreaElement>();
const touched = ref(false),
nativeError = ref("");
const dismissed = shallowRef<object>();
const descriptionIds = ref<string[]>([]),
errorIds = ref<string[]>([]);
// Pre-plan direct/native-wrapped parts before rendering controls, so SSR has
// complete ID associations even when Description follows Input.
const plannedDescriptions = ref<string[]>([]),
plannedErrors = ref<string[]>([]);
let lastPlan = "";
const behavior = computed(
() =>
props.validationBehavior ?? form?.validationBehavior.value ?? "native",
);
const disabled = computed(() => props.isDisabled),
readOnly = computed(() => props.isReadOnly);
const required = computed(() => props.isRequired);
const serverErrors = computed(() => {
const source = form?.validationErrors.value;
return source && source !== dismissed.value && props.name
? errorMessages(source[props.name])
: [];
});
const customErrors = computed(() =>
errorMessages(props.validate?.(value.value)),
);
const errors = computed(() => [
...serverErrors.value,
...(touched.value || behavior.value === "aria" ? customErrors.value : []),
...((touched.value || behavior.value === "aria") && nativeError.value
? [nativeError.value]
: []),
]);
const invalid = computed(
() =>
props.isInvalid ||
attrs["aria-invalid"] === true ||
attrs["aria-invalid"] === "true" ||
errors.value.length > 0,
);
function setValue(next: string) {
if (disabled.value || readOnly.value) return;
internal.value = next;
dismissed.value = form?.validationErrors.value;
nativeError.value = "";
emit("update:modelValue", next);
}
function initialize(next: string) {
if (!initialized) {
internal.value = next;
initialValue = next;
initialized = true;
}
}
const field: TextFieldContext = {
controlId,
kind: "text",
disabled,
readOnly,
required,
invalid,
errors,
descriptionIds,
errorIds,
value,
name: computed(() => props.name),
type: computed(() => props.type),
variant: computed(() => props.variant),
validationBehavior: behavior,
controlAttrs: () => ({
minlength: props.minLength,
maxlength: props.maxLength,
pattern: props.pattern,
autocomplete: props.autoComplete,
inputmode: props.inputMode,
form: props.form,
...Object.fromEntries(
Object.entries(attrs).filter(([key]) => key.startsWith("aria-")),
),
}),
describedBy: () =>
mergeIds(
attrs["aria-describedby"] as string | undefined,
descriptionIds.value,
plannedDescriptions.value,
invalid.value ? [...errorIds.value, ...plannedErrors.value] : [],
),
setControlId: (id) => {
leafId.value = id;
},
initialize,
setValue,
syncValue: (next) => {
internal.value = next;
},
setControl: (next) => {
control.value = next;
},
onInvalid(event) {
if (behavior.value === "aria") return;
touched.value = true;
const element = event.target as HTMLInputElement | HTMLTextAreaElement;
nativeError.value =
customErrors.value.length || serverErrors.value.length
? ""
: element.validationMessage;
},
onReset() {
internal.value = initialValue;
touched.value = false;
nativeError.value = "";
dismissed.value = form?.validationErrors.value;
},
};
provide(fieldContextKey, field);
provide(textFieldContextKey, field);
watchEffect(
() => {
const currentValue = value.value;
control.value?.setCustomValidity(
behavior.value === "native" && !disabled.value && !readOnly.value
? [...serverErrors.value, ...customErrors.value].join(" ")
: "",
);
if (behavior.value === "native" && touched.value)
nativeError.value =
customErrors.value.length || serverErrors.value.length
? ""
: (control.value?.validationMessage ?? "");
if (behavior.value === "aria")
nativeError.value =
disabled.value || readOnly.value
? ""
: required.value && !currentValue
? "请填写此字段。"
: (control.value?.validationMessage ?? "");
},
{ flush: "post" },
);
expose({ focus: () => control.value?.focus(), element: control });
function prepare(
nodes: VNodeChild[],
found: { description: string[]; error: string[]; controlId?: string },
path = "",
): VNodeChild[] {
return nodes.map((node, index) => {
if (!isVNode(node) || node.type === Comment) return node;
const position = `${path}-${index}`;
const type = node.type as { name?: string; __name?: string };
const name = type?.name ?? type?.__name;
if (
name === "Input" ||
name === "TextArea" ||
name === "InputGroupInput" ||
name === "InputGroupTextArea"
)
found.controlId = node.props?.id;
if (name === "Description" || name === "FieldError") {
const kind = name === "Description" ? "description" : "error";
const id = node.props?.id ?? `${generated}-${kind}${position}`;
found[kind].push(String(id));
return cloneVNode(node, { id });
}
// InputGroup is a library-owned transparent field wrapper. Prepare its
// default slot once, preserving the current render's values and keys.
// Arbitrary consumer components remain opaque to SSR planning.
if (
name === "InputGroup" &&
node.children &&
typeof node.children === "object"
) {
const groupSlots = node.children as { default?: () => VNodeChild[] };
if (typeof groupSlots.default === "function") {
const prepared = prepare(groupSlots.default(), found, position);
const clone = cloneVNode(node);
clone.children = { ...groupSlots, default: () => prepared };
return clone;
}
}
if (
(typeof node.type === "string" || node.type === Fragment) &&
Array.isArray(node.children)
) {
const clone = cloneVNode(node);
clone.children = prepare(
node.children as VNodeChild[],
found,
position,
) as VNode[];
return clone;
}
return node;
});
}
return () => {
const found: {
description: string[];
error: string[];
controlId?: string;
} = { description: [], error: [] };
const children = prepare(
slots.default?.({
isDisabled: disabled.value,
isReadOnly: readOnly.value,
isRequired: required.value,
isInvalid: invalid.value,
validationErrors: errors.value,
}) ?? [],
found,
);
if (found.controlId !== undefined && leafId.value !== found.controlId)
leafId.value = found.controlId;
const nextPlan = JSON.stringify(found);
if (lastPlan !== nextPlan) {
lastPlan = nextPlan;
plannedDescriptions.value = found.description;
plannedErrors.value = found.error;
}
return h(
"div",
{
...Object.fromEntries(
Object.entries(attrs).filter(([key]) => !key.startsWith("aria-")),
),
class: [
"hv-textfield",
props.fullWidth && "hv-textfield--full-width",
attrs.class,
],
"data-slot": "textfield",
"data-invalid": invalid.value || undefined,
"data-disabled": disabled.value || undefined,
"data-required": required.value || undefined,
"data-readonly": readOnly.value || undefined,
},
children,
);
};
setup(props, context) {
return useTextField(props, context).render;
},
});
</script>
+34
View File
@@ -199,3 +199,37 @@ export {
type InputGroupContextValue,
type InputGroupSlots,
} from "./components/input-group/context";
export { default as Fieldset } from "./components/fieldset/Fieldset.vue";
export type { FieldsetProps } from "./types";
export { default as FieldsetLegend } from "./components/fieldset/FieldsetLegend.vue";
export type { FieldsetLegendProps } from "./types";
export { default as FieldGroup } from "./components/fieldset/FieldGroup.vue";
export type { FieldGroupProps } from "./types";
export { default as FieldsetActions } from "./components/fieldset/FieldsetActions.vue";
export type { FieldsetActionsProps } from "./types";
export { default as SearchField } from "./components/search-field/SearchField.vue";
export type { SearchFieldProps } from "./types";
export { default as SearchFieldGroup } from "./components/search-field/SearchFieldGroup.vue";
export type { SearchFieldGroupProps } from "./types";
export { default as SearchFieldInput } from "./components/search-field/SearchFieldInput.vue";
export type { SearchFieldInputProps } from "./types";
export { default as SearchFieldSearchIcon } from "./components/search-field/SearchFieldSearchIcon.vue";
export type { SearchFieldSearchIconProps } from "./types";
export { default as SearchFieldClearButton } from "./components/search-field/SearchFieldClearButton.vue";
export type { SearchFieldClearButtonProps } from "./types";
export {
fieldsetVariants,
searchFieldVariants,
type FieldsetVariants,
type SearchFieldVariants,
} from "@heroui-vue/styles";
+37
View File
@@ -101,3 +101,40 @@ export type InputGroupPrefixProps = InstanceType<
export type InputGroupSuffixProps = InstanceType<
typeof InputGroupSuffix
>["$props"];
import type Fieldset from "./components/fieldset/Fieldset.vue";
export type FieldsetProps = InstanceType<typeof Fieldset>["$props"];
import type FieldsetLegend from "./components/fieldset/FieldsetLegend.vue";
export type FieldsetLegendProps = InstanceType<typeof FieldsetLegend>["$props"];
import type FieldGroup from "./components/fieldset/FieldGroup.vue";
export type FieldGroupProps = InstanceType<typeof FieldGroup>["$props"];
import type FieldsetActions from "./components/fieldset/FieldsetActions.vue";
export type FieldsetActionsProps = InstanceType<
typeof FieldsetActions
>["$props"];
import type SearchField from "./components/search-field/SearchField.vue";
export type SearchFieldProps = InstanceType<typeof SearchField>["$props"];
import type SearchFieldGroup from "./components/search-field/SearchFieldGroup.vue";
export type SearchFieldGroupProps = InstanceType<
typeof SearchFieldGroup
>["$props"];
import type SearchFieldInput from "./components/search-field/SearchFieldInput.vue";
export type SearchFieldInputProps = InstanceType<
typeof SearchFieldInput
>["$props"];
import type SearchFieldSearchIcon from "./components/search-field/SearchFieldSearchIcon.vue";
export type SearchFieldSearchIconProps = InstanceType<
typeof SearchFieldSearchIcon
>["$props"];
import type SearchFieldClearButton from "./components/search-field/SearchFieldClearButton.vue";
export type SearchFieldClearButtonProps = InstanceType<
typeof SearchFieldClearButton
>["$props"];
+520
View File
@@ -0,0 +1,520 @@
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 {
Button,
CloseButton,
Description,
FieldError,
FieldGroup,
Fieldset,
FieldsetActions,
FieldsetLegend,
Form,
Input,
Label,
Link,
SearchField,
SearchFieldClearButton,
SearchFieldGroup,
SearchFieldInput,
SearchFieldSearchIcon,
Switch,
TextArea,
TextField,
} from "../packages/vue/src";
afterEach(() => {
document.body.innerHTML = "";
});
const settle = async () => {
await nextTick();
await nextTick();
};
function search(
props: Record<string, unknown> = {},
inputProps = {},
clearProps = {},
) {
return h(SearchField, props, () => [
h(Label, {}, () => "Search"),
h(SearchFieldGroup, {}, () => [
h(SearchFieldSearchIcon),
h(SearchFieldInput, inputProps),
h(SearchFieldClearButton, clearProps),
]),
h(Description, {}, () => "Hint"),
h(FieldError),
]);
}
describe("Fieldset disabled scope", () => {
it("renders native semantics and the four baseline parts", () => {
const w = mount(Fieldset, {
attrs: { class: ["extra", { more: true }], name: "profile" },
slots: {
default: () => [
h(FieldsetLegend, {}, () => "Profile"),
h(FieldGroup),
h(FieldsetActions),
],
},
});
expect(w.element.tagName).toBe("FIELDSET");
expect(w.classes()).toContain("hv-fieldset");
expect(w.classes()).toContain("more");
expect(w.get("legend").classes()).toContain("hv-fieldset__legend");
expect(w.get("[data-slot=fieldset-field-group]").classes()).toContain(
"hv-fieldset__field-group",
);
w.unmount();
});
it("inherits disabled into native and non-native controls, slots and FormData", async () => {
const disabled = ref(true);
const clicked = vi.fn();
const w = mount(
defineComponent({
render: () =>
h(Form, {}, () => [
h(Fieldset, { disabled: disabled.value }, () => [
h(TextField, { name: "a", defaultValue: "x" }, () => [
h(Label, {}, () => "A"),
h(Input),
]),
h(TextArea, { name: "b", defaultValue: "y" }),
h(Switch, { name: "switch", defaultChecked: true }),
h(
Button,
{ onClick: clicked },
{
default: (s: { isDisabled: boolean }) => String(s.isDisabled),
},
),
h(
Link,
{ href: "#go", onClick: clicked },
{
default: (s: { isDisabled: boolean }) => String(s.isDisabled),
},
),
h(CloseButton, { onClick: clicked }),
search({ name: "query", defaultValue: "q" }),
]),
]),
}),
{ attachTo: document.body },
);
expect(w.get("input[name=a]").attributes("disabled")).toBeDefined();
expect(w.get("textarea").attributes("disabled")).toBeDefined();
expect(w.get("[data-slot=button]").text()).toBe("true");
expect(w.get("a").text()).toBe("true");
await w.get("a").trigger("click");
await w.get("[role=switch]").trigger("click");
expect(clicked).not.toHaveBeenCalled();
expect(w.get("[role=switch]").attributes("aria-checked")).toBe("true");
expect([...new FormData(w.get("form").element as HTMLFormElement)]).toEqual(
[],
);
disabled.value = false;
await settle();
expect(w.get("[data-slot=button]").text()).toBe("false");
expect(
Object.fromEntries(
new FormData(w.get("form").element as HTMLFormElement),
),
).toEqual({ a: "x", b: "y", switch: "on", query: "q" });
w.unmount();
});
it("preserves the first direct legend exception, nested fieldsets and local disabled", async () => {
const w = mount(
defineComponent({
render: () =>
h(Form, {}, () =>
h(Fieldset, { disabled: true }, () => [
h(FieldsetLegend, {}, () => [
h(Label, { for: "legend-input" }, () => "Exempt label"),
h(Input, {
id: "legend-input",
name: "legend",
defaultValue: "allowed",
}),
h(Button, {}, () => "Legend"),
]),
h(FieldsetLegend, {}, () => h(Input, { name: "second" })),
h(Fieldset, { disabled: false }, () => [
h(FieldsetLegend, {}, () => h(Input, { name: "innerLegend" })),
h(Input, { name: "inner" }),
]),
]),
),
}),
{ attachTo: document.body },
);
expect(w.get("input[name=legend]").attributes("disabled")).toBeUndefined();
expect(w.get('label[for="legend-input"]').classes()).not.toContain(
"hv-label--disabled",
);
expect(w.get("input[name=second]").attributes("disabled")).toBeDefined();
expect(
w.get("input[name=innerLegend]").attributes("disabled"),
).toBeDefined();
expect(w.get("input[name=inner]").attributes("disabled")).toBeDefined();
expect(
Object.fromEntries(
new FormData(w.get("form").element as HTMLFormElement),
),
).toEqual({ legend: "allowed" });
w.unmount();
});
it("handles a dynamically inserted first legend and native legend children", async () => {
const first = ref(true);
const w = mount(
defineComponent({
render: () =>
h(Fieldset, { disabled: true }, () => [
first.value
? h(FieldsetLegend, { key: "one" }, () =>
h(Input, { name: "one" }),
)
: null,
h("legend", { key: "two" }, [h(Input, { name: "two" })]),
]),
}),
);
expect(w.get("input[name=two]").attributes("disabled")).toBeDefined();
first.value = false;
await settle();
expect(w.get("input[name=two]").attributes("disabled")).toBeUndefined();
w.unmount();
});
});
describe("SearchField shared text state", () => {
it("renders search type, unique label/description/error references and empty state", async () => {
const w = mount(search({ isInvalid: true }));
await settle();
expect(w.get("input").attributes("type")).toBe("search");
expect(w.get("label").attributes("for")).toBe(
w.get("input").attributes("id"),
);
expect(w.attributes("data-empty")).toBe("true");
expect(
w.get("[data-slot=search-field-clear-button]").attributes("tabindex"),
).toBe("-1");
for (const id of w.get("input").attributes("aria-describedby")!.split(" "))
expect(w.find(`[id="${id}"]`).exists()).toBe(true);
expect(w.classes()).not.toContain("hv-textfield");
w.unmount();
});
it("clears once, emits the value, focuses the input, and does not submit the form", async () => {
const clear = vi.fn(),
change = vi.fn(),
submit = vi.fn((e: Event) => e.preventDefault());
const w = mount(
defineComponent({
render: () =>
h(Form, { onSubmit: submit }, () =>
search({
defaultValue: "hello",
onClear: clear,
"onUpdate:modelValue": change,
}),
),
}),
{ attachTo: document.body },
);
await w.get("[data-slot=search-field-clear-button]").trigger("click");
await settle();
expect((w.get("input").element as HTMLInputElement).value).toBe("");
expect(clear).toHaveBeenCalledOnce();
expect(change).toHaveBeenCalledExactlyOnceWith("");
expect(submit).not.toHaveBeenCalled();
expect(document.activeElement).toBe(w.get("input").element);
w.unmount();
});
it("restores a rejected root or leaf controlled clear", async () => {
for (const leaf of [false, true]) {
const change = vi.fn();
const w = mount(
search(
leaf ? {} : { modelValue: "keep", "onUpdate:modelValue": change },
leaf ? { modelValue: "keep", "onUpdate:modelValue": change } : {},
),
{ attachTo: document.body },
);
await w.get("[data-slot=search-field-clear-button]").trigger("click");
await settle();
expect((w.get("input").element as HTMLInputElement).value).toBe("keep");
expect(change).toHaveBeenCalledExactlyOnceWith("");
w.unmount();
}
});
it("supports Escape clear and Enter submit once, ignoring IME/repeat and cancellation", async () => {
const submit = vi.fn(),
clear = vi.fn();
const w = mount(
search({ defaultValue: "query", onSubmit: submit, onClear: clear }),
);
await w
.get("input")
.trigger("keydown", { key: "Enter", isComposing: true });
await w.get("input").trigger("keydown", { key: "Enter", keyCode: 229 });
await w.get("input").trigger("keydown", { key: "Enter", repeat: true });
expect(submit).not.toHaveBeenCalled();
await w.get("input").trigger("keydown", { key: "Enter" });
await w.get("input").trigger("keyup", { key: "Enter" });
expect(submit).toHaveBeenCalledExactlyOnceWith("query");
await w.get("input").trigger("keydown", { key: "Escape" });
await settle();
expect(clear).toHaveBeenCalledOnce();
await w.get("input").trigger("keydown", { key: "Escape" });
expect(clear).toHaveBeenCalledOnce();
w.unmount();
const canceled = mount(
search(
{ defaultValue: "q", onSubmit: submit },
{ onKeydown: (e: Event) => e.preventDefault() },
),
);
await canceled.get("input").trigger("keydown", { key: "Enter" });
expect(submit).toHaveBeenCalledTimes(1);
canceled.unmount();
});
it("lets implicit native form submission proceed without a search submit listener", async () => {
const w = mount(search({ defaultValue: "q" }));
const event = new KeyboardEvent("keydown", {
key: "Enter",
bubbles: true,
cancelable: true,
});
w.get("input").element.dispatchEvent(event);
expect(event.defaultPrevented).toBe(false);
w.unmount();
});
it("respects readonly, disabled, caller cancellation, and native validation", async () => {
for (const state of [{ isReadOnly: true }, { isDisabled: true }]) {
const clear = vi.fn();
const w = mount(search({ ...state, defaultValue: "q", onClear: clear }));
await w.get("[data-slot=search-field-clear-button]").trigger("click");
await w.get("input").trigger("keydown", { key: "Escape" });
expect(clear).not.toHaveBeenCalled();
expect((w.get("input").element as HTMLInputElement).value).toBe("q");
w.unmount();
}
const submit = vi.fn();
const w = mount(search({ isRequired: true, onSubmit: submit }));
await w.get("input").trigger("keydown", { key: "Enter" });
await settle();
expect(submit).not.toHaveBeenCalled();
expect(w.get("input").attributes("aria-invalid")).toBe("true");
w.unmount();
const canceled = mount(
search(
{ defaultValue: "q" },
{},
{ onClick: (e: Event) => e.preventDefault() },
),
);
await canceled
.get("[data-slot=search-field-clear-button]")
.trigger("click");
await settle();
expect((canceled.get("input").element as HTMLInputElement).value).toBe("q");
canceled.unmount();
});
it("shares FormData, default reset and canceled reset without a second value source", async () => {
const w = mount(
defineComponent({
render: () =>
h(Form, {}, () => search({ name: "q", defaultValue: "initial" })),
}),
{ attachTo: document.body },
);
await w.get("input").setValue("changed");
const form = w.get("form").element as HTMLFormElement;
expect(Object.fromEntries(new FormData(form))).toEqual({ q: "changed" });
form.reset();
await settle();
expect((w.get("input").element as HTMLInputElement).value).toBe("initial");
form.addEventListener("reset", (e) => e.preventDefault());
await w.get("input").setValue("keep");
form.reset();
await settle();
expect((w.get("input").element as HTMLInputElement).value).toBe("keep");
w.unmount();
});
it("supports SSR and hydration with explicit control ID inside group", async () => {
const view = defineComponent({
render: () =>
search({ name: "q", defaultValue: "query" }, { id: "explicit-search" }),
});
const host = document.createElement("div");
host.innerHTML = await renderToString(createSSRApp(view));
document.body.append(host);
expect(host.querySelector("label")?.htmlFor).toBe("explicit-search");
const warn = vi.spyOn(console, "warn"),
error = vi.spyOn(console, "error");
const app = createSSRApp(view);
try {
app.mount(host);
await settle();
expect(warn).not.toHaveBeenCalled();
expect(error).not.toHaveBeenCalled();
} finally {
app.unmount();
warn.mockRestore();
error.mockRestore();
host.remove();
}
});
it("updates variant, attrs, event handlers and conditional slots without stale classes", async () => {
const attrs = ref<Record<string, unknown>>({}),
variant = ref<"primary" | "secondary">("primary"),
prefix = ref(true);
const w = mount(
defineComponent({
render: () =>
h(SearchField, { ...attrs.value, variant: variant.value }, () =>
h(SearchFieldGroup, {}, () => [
prefix.value ? h(SearchFieldSearchIcon) : null,
h(SearchFieldInput),
h(SearchFieldClearButton),
]),
),
}),
);
const change = vi.fn();
attrs.value = {
class: ["custom", { more: true }],
"aria-label": "New",
"onUpdate:modelValue": change,
};
variant.value = "secondary";
prefix.value = false;
await settle();
expect(w.classes()).toContain("hv-search-field--secondary");
expect(w.classes()).not.toContain("hv-search-field--primary");
expect(w.classes()).toContain("more");
expect(w.get("input").attributes("aria-label")).toBe("New");
expect(w.find("[data-slot=search-field-search-icon]").exists()).toBe(false);
await w.get("input").setValue("x");
expect(change).toHaveBeenCalledExactlyOnceWith("x");
attrs.value = {};
await settle();
expect(w.classes()).not.toContain("custom");
expect(w.get("input").attributes("aria-label")).toBeUndefined();
attrs.value = { "aria-label": "Again" };
await settle();
expect(w.get("input").attributes("aria-label")).toBe("Again");
w.unmount();
});
});
it("allows root handlers and handler arrays to cancel search keyboard actions", async () => {
for (const stop of ["preventDefault", "stopImmediatePropagation"] as const) {
const submit = vi.fn(),
after = vi.fn();
const w = mount(
search({
defaultValue: "q",
onSubmit: submit,
onKeydown: [(e: KeyboardEvent) => e[stop](), after],
}),
);
await w.get("input").trigger("keydown", { key: "Enter" });
expect(submit).not.toHaveBeenCalled();
expect(after).toHaveBeenCalledTimes(stop === "preventDefault" ? 1 : 0);
w.unmount();
}
});
it("preserves a keyed legend control's value when the first-legend exemption moves", async () => {
const first = ref(false);
const w = mount(
defineComponent({
render: () =>
h(Fieldset, { disabled: true }, () => [
first.value
? h(FieldsetLegend, { key: "first" }, () => "First")
: null,
h(FieldsetLegend, { key: "second" }, () =>
h(Input, { name: "keyed" }),
),
]),
}),
);
await w.get("input").setValue("retained");
first.value = true;
await settle();
expect(w.get("input").attributes("disabled")).toBeDefined();
expect((w.get("input").element as HTMLInputElement).value).toBe("retained");
first.value = false;
await settle();
expect((w.get("input").element as HTMLInputElement).value).toBe("retained");
w.unmount();
});
it("keeps the baseline preview inventories and exact fieldset submission feedback", async () => {
const { readFileSync } = await import("node:fs");
const searchNames = [
"basic",
"variants",
"on-surface",
"with-description",
"required",
"disabled",
"full-width",
"validation",
"controlled",
"form-example",
"with-validation",
"custom-icons",
"with-keyboard-shortcut",
"render-function",
"custom-styles",
];
const doc = readFileSync("apps/docs/components/search-field.md", "utf8");
expect(
[...doc.matchAll(/<ComponentPreview\s+name="search-field-([^"]+)"/g)].map(
(m) => m[1],
),
).toEqual(searchNames);
for (const name of searchNames)
expect(
readFileSync(`apps/docs/demos/search-field-${name}.vue`, "utf8"),
).toContain("<template>");
const { default: Demo } =
await import("../apps/docs/demos/fieldset-basic.vue");
const w = mount(Demo, { attachTo: document.body });
await w.get("input[name=name]").setValue("Jane");
await w.get("input[name=email]").setValue("jane@example.com");
await w.get("textarea").setValue("A detailed biography.");
(w.get("form").element as HTMLFormElement).requestSubmit();
await settle();
const status = w.get('[role="status"]');
expect(status.text()).toContain('"name":"Jane"');
expect(status.text()).toContain('"email":"jane@example.com"');
await w.get('button[type="reset"]').trigger("click");
await settle();
expect((w.get("input[name=name]").element as HTMLInputElement).value).toBe(
"",
);
w.unmount();
});
it("plans a grouped leaf's initial search value in SSR and restores the default ID after explicit removal", async () => {
const id = ref<string | undefined>("temporary-search");
const view = defineComponent({
render: () => search({}, { id: id.value, defaultValue: "leaf initial" }),
});
const html = await renderToString(createSSRApp(view));
expect(html).not.toContain('data-empty="true"');
expect(html).toContain('value="leaf initial"');
const w = mount(view);
expect(w.get("label").attributes("for")).toBe("temporary-search");
id.value = undefined;
await settle();
expect(w.get("input").attributes("id")).not.toBe("temporary-search");
expect(w.get("input").attributes("id")).toBe(
w.get("label").attributes("for"),
);
w.unmount();
});
+34
View File
@@ -110,3 +110,37 @@ it("associates labels with explicit grouped control IDs on the server", async ()
expect(new Set(ids).size).toBe(ids.length);
for (const id of refs) expect(ids).toContain(id);
});
it("renders disabled fieldsets and search fields without browser globals", async () => {
const {
Fieldset,
FieldsetLegend,
SearchField,
SearchFieldGroup,
SearchFieldInput,
SearchFieldClearButton,
Label,
Description,
} = await import("../packages/vue/src");
const html = await renderToString(
createSSRApp({
render: () =>
h(Fieldset, { disabled: true }, () => [
h(FieldsetLegend, {}, () => h(Button, {}, () => "Exempt")),
h(SearchField, { defaultValue: "query", name: "q" }, () => [
h(Label, {}, () => "Query"),
h(SearchFieldGroup, {}, () => [
h(SearchFieldInput, { id: "ssr-search" }),
h(SearchFieldClearButton),
]),
h(Description, {}, () => "Hint"),
]),
]),
}),
);
expect(html).toContain('for="ssr-search"');
expect(html).toContain('type="search"');
expect(html).toContain('value="query"');
expect(html).toContain('data-slot="search-field-clear-button"');
expect(html).toContain('data-disabled="true"');
});