diff --git a/apps/docs/components/field-error.md b/apps/docs/components/field-error.md index 6411198..72a54a8 100644 --- a/apps/docs/components/field-error.md +++ b/apps/docs/components/field-error.md @@ -212,3 +212,7 @@ FieldError 组件通过以下方式确保无障碍性: ## 相关组件 [TextField 文本输入框](./text-field) · [Input 输入框](./input) · [TextArea 多行文本框](./textarea) + +### validationDetails + +作用域插槽还提供 `validationDetails?: ValidityState`。TextField/SearchField 使用真实控件的原生快照,OTP 可显式传入详情(优先)或读取其提交代理快照;其他尚未接入详情的字段为 undefined。可读取 `valueMissing`、`patternMismatch`、`typeMismatch`、`customError` 等原生标志,而不复制字段状态。详情本身不替代 `isInvalid` 或错误文本。 diff --git a/apps/docs/components/input-otp.md b/apps/docs/components/input-otp.md index 9916f65..d931a55 100644 --- a/apps/docs/components/input-otp.md +++ b/apps/docs/components/input-otp.md @@ -82,7 +82,7 @@ InputOTP 组件支持两种视觉变体: -`@complete` 在**首次填满**时触发一次;替换已满值、重复同值或父级同步同一值不会重复触发。示例使用模拟验证(定时器),不发送真实验证码。 +`@complete` 在已接受值**从未满变为满值**时触发一次;替换已满值、重复同值或父级同步同一值不会重复触发。示例使用模拟验证(定时器),不发送真实验证码。 ### 表单示例 @@ -94,7 +94,7 @@ InputOTP 组件支持两种视觉变体: -`pattern` 过滤单字符输入,可使用导出的正则常量。 +`pattern` 检查整个候选字符串,可使用导出的正则常量;不匹配时拒绝整次编辑。 ### 表单验证 @@ -177,25 +177,29 @@ InputOTP 组件使用以下 CSS 类([查看源码样式](https://github.com/he ### InputOTP / InputOTPRoot -| Prop | 类型 | 默认值 | 描述 | -| ------------------ | -------------------------- | ----------- | ---------------------------------------------------------------- | -| `modelValue` | `string` | - | 受控字符串值;下标对应槽位 | -| `defaultValue` | `string` | `''` | 非受控初始值 | -| `maxLength` | `number` | 必填 | 槽位数量 / 最大长度 | -| `variant` | `'primary' \| 'secondary'` | `'primary'` | 外观变体 | -| `isDisabled` | `boolean` | `false` | 禁用 | -| `isInvalid` | `boolean` | `false` | 无效展示状态 | -| `validationErrors` | `string[]` | `[]` | 校验错误消息 | -| `inputClassName` | `string` | - | 附加到真实 input 的类 | -| `name` | `string` | - | 表单字段名(隐藏 input 提交一份完整值) | -| `required` | `boolean` | `false` | 原生必填 | -| `pattern` | `string \| RegExp` | - | 字符过滤正则 | -| `mask` | `boolean` | `false` | 密码样式(Reka `mask`) | -| `otp` | `boolean` | `false` | 一次性验证码自动填充(`autocomplete="one-time-code"`) | -| `placeholder` | `string` | `''` | 空位占位符 | -| `id` | `string` | 自动 | 提交桥 id;真实输入派生为 id-slot-index,内部 Label 自动关联首格 | +| Prop | 类型 | 默认值 | 描述 | +| ------------------- | ------------------------------- | ------------ | ---------------------------------------------------------------- | +| `modelValue` | `string` | - | 受控字符串值;下标对应槽位 | +| `defaultValue` | `string` | `''` | 非受控初始值 | +| `maxLength` | `number` | 必填 | 槽位数量 / 最大长度 | +| `variant` | `'primary' \| 'secondary'` | `'primary'` | 外观变体 | +| `isDisabled` | `boolean` | `false` | 禁用 | +| `isInvalid` | `boolean` | `false` | 无效展示状态 | +| `validationErrors` | `string[]` | `[]` | 校验错误消息 | +| `autoFocus` | `boolean` | `false` | 挂载后聚焦真实 input | +| `pasteTransformer` | `(text: string) => string` | - | 粘贴转换先于正则检查 | +| `textAlign` | `'left' \| 'center' \| 'right'` | `'left'` | 真实 input 对齐 | +| `validationDetails` | `ValidityState` | 原生代理快照 | 显式校验标志优先,供 FieldError 读取 | +| `inputClassName` | `string` | - | 附加到真实 input 的类 | +| `name` | `string` | - | 表单字段名(隐藏 input 提交一份完整值) | +| `required` | `boolean` | `false` | 原生必填 | +| `pattern` | `string \| RegExp` | - | 整个候选字符串的正则判定 | +| `mask` | `boolean` | `false` | 密码样式(Reka `mask`) | +| `otp` | `boolean` | `false` | 一次性验证码自动填充(`autocomplete="one-time-code"`) | +| `placeholder` | `string` | `''` | 空位占位符 | +| `id` | `string` | 自动 | 提交桥 id;真实输入派生为 id-slot-index,内部 Label 自动关联首格 | -事件:`update:modelValue` / `change`(字符串)、`complete`(首次填满)。 +事件:`update:modelValue` / `change`(字符串)、`complete`(已接受值从未满变满)。 ### InputOTPGroup / InputOTPSeparator @@ -213,17 +217,17 @@ InputOTP 组件使用以下 CSS 类([查看源码样式](https://github.com/he ### 上游差异 -| 上游 React 能力 | Vue 实现 | -| ------------------------------------ | ------------------------------------------------------------------------------------- | -| `input-otp` 单隐藏 input | Reka PinInput 多 input + 隐藏提交 input | -| `value` / `onChange` 字符串 | `v-model` / `update:modelValue` / `change` | -| `onComplete` 跨过长度阈值 | `complete` 仅在首次填满触发 | -| `pattern` 整串校验 | 单字符过滤(同样接受导出常量) | -| `render` / `OTPInputContext` | 具名插槽部件;槽位状态经上下文 | -| `pushPasswordManagerStrategy` | 未提供;`otp` 覆盖 one-time-code 自动填充 | -| `validationDetails`(ValidityState) | 未提供;校验结果为 `string \| string[]` 文本 | -| `textAlign` / `pasteTransformer` | 未提供(能力缺口,见 HD 队列后续能力卡) | -| `autoFocus` / `containerClassName` | 未提供专门 prop;`containerClassName` 被上游公共类型显式 Omit,`autoFocus` 属能力缺口 | +| 上游 React 能力 | Vue 实现 | +| ------------------------------------ | ------------------------------------------------------------------------- | +| `input-otp` 单隐藏 input | Reka PinInput 多 input + 隐藏提交 input | +| `value` / `onChange` 字符串 | `v-model` / `update:modelValue` / `change` | +| `onComplete` 跨过长度阈值 | `complete` 在已接受值从未满变满时触发;满值替换不重复触发 | +| `pattern` 整串校验 | 整个候选字符串按 pattern 检查,拒绝整次不匹配编辑 | +| `render` / `OTPInputContext` | 具名插槽部件;槽位状态经上下文 | +| `pushPasswordManagerStrategy` | 未提供;`otp` 覆盖 one-time-code 自动填充 | +| `validationDetails`(ValidityState) | 作为 prop 传入并通过共享 FieldError 插槽暴露;缺省读取原生校验代理 | +| `textAlign` / `pasteTransformer` | 均已提供;转换后的整值再做 pattern 检查 | +| `autoFocus` / `containerClassName` | 提供 autoFocus;containerClassName 被上游公共类型显式 Omit,不新增该 prop | ## 字段与表单 @@ -243,3 +247,16 @@ Slot 的 keydown/paste 用户处理器在底座编辑前的 capture 边界协调 ## 相关组件 [Input 输入框](./input) · [Form 表单](./form) · [Surface 表面](./surface) + +## 粘贴、对齐与完成事件 + +- `autoFocus?: boolean`:挂载后聚焦真实槽输入;保留 PinInput 的焦点导航。 +- `pasteTransformer?: (pastedText: string) => string`:先转换剪贴板文本,再限制到 maxLength 并检查整个候选字符串。例如 `text => text.replaceAll('-', '')` 可接收带分隔符的验证码。不匹配的编辑整次拒绝,不从非法文本中悄悄筛出部分字符;空字符串始终可清空。 +- `textAlign?: 'left' | 'center' | 'right'`(默认 left):用于各真实透明 input 的文字/选区对齐,视觉 slot 仍按移植 CSS 居中。多 input 结构不伪装为单 input。 +- `validationDetails?: ValidityState`:传入全部原生 validity 标志,由 FieldError 的作用域插槽读取;显式值优先于校验代理快照。它本身不改变 isInvalid;错误文本和无效状态沿用已有字段协议。 + +`complete` 只跟随已接受值从长度不足变为 maxLength 的变化:父级拒绝满值提案不会触发;满值替换或重复相同值不触发;清空/删除后重新填满会再次触发。父级主动设置的已接受值也遵循同一阈值规则。禁用/只读不运行粘贴转换或编辑。 + +保留 PinInput 编辑约定:一份完整代码的粘贴从首格替换,短粘贴从当前格替换;完成后焦点位于末格或下一待填格,当前格字符可选择。单 input 的任意跨格文本选区与密码管理器徽标避让不承诺等价;`pushPasswordManagerStrategy` 未提供。`containerClassName` 在固定上游公共类型中已 Omit,不新增。 + +`validationErrors` 显式数组由调用方管理;Form 下同名服务端错误在有效编辑提案或 reset 时忽略当前响应,新响应会重新显示。原生 required/错误通过现有提交代理和共享 FieldError 关联;受控 reset 保留父值、非受控恢复 defaultValue,取消 reset 不改变值。 diff --git a/apps/docs/components/search-field.md b/apps/docs/components/search-field.md index beab705..ad3d4d5 100644 --- a/apps/docs/components/search-field.md +++ b/apps/docs/components/search-field.md @@ -217,6 +217,7 @@ SearchField 与 TextField 共用文本字段内核、表单策略和 ID 协议 | 属性 | 类型 | 默认值 | 描述 | | ------------------------------------- | -------------------------------------------------------------------- | ---------------------- | ------------------------------------------------- | +| `validationErrors` | `string \| string[]` | - | 字段级外部错误,与 Form 同名错误合并 | | `modelValue` / `defaultValue` | `string` | - | 受控值 / 非受控初始值 | | `variant` | `'primary' \| 'secondary'` | `'primary'` | 根与 Group 的视觉变体 | | `fullWidth` | `boolean` | `false` | 根与 Group 全宽 | @@ -232,7 +233,7 @@ SearchField 与 TextField 共用文本字段内核、表单策略和 ID 协议 | `class` / `style` | Vue class / style 绑定 | - | 根节点属性;ARIA 下发到输入 | | 默认插槽 | 作用域插槽 | - | 字段部件及状态 | -服务端错误通过 Form 的 validationErrors 按 name 映射;不提供 SearchField 独立 validationErrors 数组。validate 暂不接受 Promise;FieldError 无完整 React Aria validationDetails。 +字段级 `validationErrors`(字符串或数组)与 Form 按 name 提供的错误共同接入;`validate` 暂不接受 Promise。FieldError 可读取真实控件的 `validationDetails`(ValidityState 快照)。 ### 事件与暴露 @@ -270,3 +271,11 @@ SearchField 与 TextField 共用文本字段内核、表单策略和 ID 协议 ## 相关组件 [Label 标签](./label) · [Description 描述](./description) · [FieldError 字段错误](./field-error) + +## 字段级错误与焦点 + +`autoFocus?: boolean` 在挂载后聚焦真实 input/textarea(禁用控件不聚焦),不落到字段 div。默认插槽提供 `value`、`isFocusWithin`、`isFocusVisible`、`validationErrors` 和 `validationDetails`;根的 `data-focus-within` / `data-focus-visible` 与实际组内焦点和浏览器判定同步。 + +`validationErrors?: string | string[]` 用于字段级外部错误;显示顺序为字段错误、Form 中该 name 的错误、已触发的 validate/原生错误,字段与 Form 的重复消息去重。native 策略下外部错误写入真实控件的 customValidity,aria 策略只显示语义错误。`isInvalid` 仍只控制展示,不单独设置 customValidity。 + +改变值的输入事件会忽略当前字段错误响应与 Form 错误响应,reset 也会清除它们;新数组/对象引用视为新响应,重新显示。相同响应引用的原地修改不用于重新投递已忽略的错误。字段级响应只影响当前字段,Form 的其他字段错误保留。FieldError 的 `validationDetails` 是只读的原生 ValidityState 标志快照,不是第二套字段值。 diff --git a/apps/docs/components/text-field.md b/apps/docs/components/text-field.md index 21a5cf3..77d2ccc 100644 --- a/apps/docs/components/text-field.md +++ b/apps/docs/components/text-field.md @@ -153,6 +153,8 @@ TextField 会根据状态自动管理以下 data 属性: | Prop | 类型 | 默认值 | 描述 | | ------------------------------------- | -------------------------------------------------------------------- | -------------------------- | -------------------------------------------------- | | 默认插槽 | `Component` | - | 子组件(Label、Input、Description、FieldError 等) | +| `validationErrors` | `string \| string[]` | - | 字段级外部错误,与 Form 同名错误合并 | +| `autoFocus` | `boolean` | `false` | 挂载后聚焦真实文本控件 | | `modelValue` | `string` | - | 当前值(受控;`v-model`) | | `defaultValue` | `string` | - | 默认值(非受控) | | `name` | `string` | - | 用于 HTML 表单提交的 input 名称 | @@ -172,7 +174,7 @@ TextField 会根据状态自动管理以下 data 属性: | `form` | `string` | - | 关联外部 form 的 id(下发到真实控件) | | `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) | -值使用 `v-model`(`update:modelValue`)。受控值由父级决定,拒绝更新时恢复实际 DOM 值。`name`、原生约束、`autoComplete` / `inputMode` / `form` 与 ARIA 落在真实 `input`/`textarea` 上。服务端/外部错误通过 Form 的 `validation-errors`(按 name 映射)接入,不是 TextField 的 `validationErrors` 数组。 +值使用 `v-model`(`update:modelValue`)。受控值由父级决定,拒绝更新时恢复实际 DOM 值。`name`、原生约束、`autoComplete` / `inputMode` / `form` 与 ARIA 落在真实 `input`/`textarea` 上。服务端/外部错误既可由字段 `validationErrors`(字符串或数组)传入,也可由 Form 的 `validation-errors` 按 name 映射。 ### 事件 @@ -234,8 +236,16 @@ const hasError = ref(false); | `isInvalid` | `boolean` | 是否无效 | | `validationErrors` | `string[]` | 当前错误列表 | -与上游 `TextFieldRenderProps` 的差异:Vue 使用作用域插槽而非 render prop;无 `isFocusWithin` / `isFocusVisible`(聚焦状态由控件自身管理)。 +Vue 使用类型可解析的作用域插槽;`TextFieldRenderProps` 包含 `value`、`isFocusWithin`、`isFocusVisible` 与 `validationDetails`。组内焦点移动保持 focus-within,移出整个字段才清除。 ## 相关组件 [Input 输入框](./input) · [TextArea 多行文本框](./textarea) · [Fieldset 字段组](./fieldset) + +## 字段级错误与焦点 + +`autoFocus?: boolean` 在挂载后聚焦真实 input/textarea(禁用控件不聚焦),不落到字段 div。默认插槽提供 `value`、`isFocusWithin`、`isFocusVisible`、`validationErrors` 和 `validationDetails`;根的 `data-focus-within` / `data-focus-visible` 与实际组内焦点和浏览器判定同步。 + +`validationErrors?: string | string[]` 用于字段级外部错误;显示顺序为字段错误、Form 中该 name 的错误、已触发的 validate/原生错误,字段与 Form 的重复消息去重。native 策略下外部错误写入真实控件的 customValidity,aria 策略只显示语义错误。`isInvalid` 仍只控制展示,不单独设置 customValidity。 + +改变值的输入事件会忽略当前字段错误响应与 Form 错误响应,reset 也会清除它们;新数组/对象引用视为新响应,重新显示。相同响应引用的原地修改不用于重新投递已忽略的错误。字段级响应只影响当前字段,Form 的其他字段错误保留。FieldError 的 `validationDetails` 是只读的原生 ValidityState 标志快照,不是第二套字段值。 diff --git a/apps/playground/src/App.vue b/apps/playground/src/App.vue index 7d36771..9036444 100644 --- a/apps/playground/src/App.vue +++ b/apps/playground/src/App.vue @@ -3,6 +3,13 @@ import { defineAsyncComponent } from "vue"; // Keep regression URLs stable; load only the selected harness. const labs = [ + { + key: "field-otp", + title: "字段与验证码", + component: defineAsyncComponent( + () => import("../../../tests/fixtures/field-otp.vue"), + ), + }, { key: "link-focus", title: "链接与日期焦点", diff --git a/docs/compatibility.md b/docs/compatibility.md index de60e03..2f0db93 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -201,7 +201,7 @@ React render 自定义根类型不支持;原生 attrs/具名部件/作用域 - **Pagination**:组合式 nav 容器(无 total/page 状态机);具名部件含 Link/Previous/Next(原生 button)、Ellipsis、图标默认 SVG。9/9 基线示例。`onPress`→`@click`。详见 [M30](component-notes.md)。 - **Header**:集合/分组标题,原生 ``(已核对 RAC 契约)。基线无独立文档/演示;自编 3 例并标注。详见 [M31](component-notes.md)。 -- **InputOTP**:Reka PinInput 底座;公开字符串 + 内部索引数组(中间空位不左移);complete 仅首次填满。11/11 示例。消费 fieldContextKey,未改共享内核。真实自动填充/IME/读屏未验证。详见 [M32](component-notes.md)。 +- **InputOTP**:Reka PinInput 底座;公开字符串 + 内部索引数组(中间空位不左移);complete 已按HD-07收口为已接受值从未满变满。11/11 示例。消费 fieldContextKey,未改共享内核。真实自动填充/IME/读屏未验证。详见 [M32](component-notes.md)。 以上不构成整库完成声明;逐像素、读屏、Nuxt 水合、独立安装仍未验收。 @@ -299,3 +299,8 @@ HD-01(2026-10-28):按钮/切换组与导航示例已恢复固定cn基线 ## HD-06 链接与日期焦点(2026-10-29) 禁用 Link 移除 href/target/download,包括 asChild 子节点的导航属性,保持 aria-disabled、tabindex=-1 与暴露的 focus;启用恢复,用户事件取消和子 ref 保留。Breadcrumbs 当前/禁用项原已用 span,不重复改写;新增按 ConfigProvider locale 的默认名称及 @action(key),保持 id/key 的数字0与空串身份,取消的激活不通知 action。两个日期触发器按实际 :focus-visible 更新状态标记,鼠标/Tab/关闭恢复由浏览器判定。证据见 [HD-06结果](tasks/results/HD-06-LINK-FOCUS.md)。 + + +## HD-07 字段与OTP公共能力(2026-10-29) + +TextField/SearchField共享autoFocus、组内focus状态、字段级validationErrors与Form错误合并;SearchField槽value与文本值同源。FieldError按共享FieldContext可读取ValidityState快照,TextField/SearchField来自真实控件、OTP支持显式validationDetails或原生提交代理。OTP补autoFocus/pasteTransformer/textAlign,整值pattern与accepted complete对照固定input-otp1.5.0:非法整次编辑拒绝、受控拒绝不complete、满值替换不重复、清空重填再通知。PinInput索引空位与单字符串提交保留;视觉槽对齐、跨格选区、密码管理器策略等Vue边界见组件文档及[任务结果](tasks/results/HD-07-FIELD-OTP.md)。 diff --git a/docs/tasks/ACTIVE.md b/docs/tasks/ACTIVE.md index 88c8082..ff60bd6 100644 --- a/docs/tasks/ACTIVE.md +++ b/docs/tasks/ACTIVE.md @@ -31,3 +31,5 @@ - HD-06-LINK-FOCUS执行中:分支task/hd-06-link-focus,起点680a592e7b95bd52592edc19d1b8654b30b53a1c;本会话亲自实施并按用户授权验收后合并push。范围:Link禁用导航/asChild/ref、日期真实focus-visible、Breadcrumbs locale/action。5173保持,5174原已停止,本轮重新启动用于公开组合浏览器验收。 - HD-06 已完成验收:实施68d45c66f98eeebd5872448b839ed387bf65f0f0;Link原生/asChild禁用导航及ref/取消语义、Breadcrumbs locale/action、日期真实focus-visible全部核销,见results/HD-06-LINK-FOCUS.md。全量111文件1641项、类型、文档/playground构建、四个最终tarball契约与真实浏览器通过。按用户授权合入main并push origin/main;工作区释放,下一项HD-07-FIELD-OTP未启动,保留5173及本轮重启的5174。 + +- HD-07-FIELD-OTP执行中:分支task/hd-07-field-otp,实际起点27cc62e36f16bc16843ccf25f202340eeac38871;本会话亲自补字段focus/autoFocus/错误数组与ValidityState、SearchField槽value,以及OTP autoFocus/pasteTransformer/textAlign和固定1.5.0的pattern/complete契约,完成后按用户授权合并push。 diff --git a/docs/tasks/HD-07-FIELD-OTP.md b/docs/tasks/HD-07-FIELD-OTP.md index 3492320..b2cee25 100644 --- a/docs/tasks/HD-07-FIELD-OTP.md +++ b/docs/tasks/HD-07-FIELD-OTP.md @@ -1,5 +1,5 @@ # HD-07-FIELD-OTP:字段与 OTP 公共能力补齐 @@ -7,10 +7,10 @@ ## 执行范围 -- [ ] 补 TextField 自动聚焦、isFocusWithin/isFocusVisible 与相应 data 状态;支持 TextField/SearchField 字段级 validationErrors 并明确与 Form 错误的合并、清除和优先级;补 SearchField 插槽 value。 -- [ ] OTP 补 autoFocus、pasteTransformer、textAlign 的等价公共能力;validationDetails/FieldError 的必要校验信息复用现有字段协议,避免另建状态源。 -- [ ] 对固定 input-otp 依赖核验 pattern 和 complete:满值替换、重复值、清空重填、受控拒绝、粘贴转换后过滤均需行为证据,再修契约。不能仅依据报告把两个不同语义直接替换。 -- [ ] containerClassName 被上游公共类型 Omit 排除,不补;保留 PinInput、多真实 input、透明覆盖层和字符串/数组转换。密码管理器策略无等价能力时明确记录限制。 +- [x] 补 TextField 自动聚焦、isFocusWithin/isFocusVisible 与相应 data 状态;支持 TextField/SearchField 字段级 validationErrors 并明确与 Form 错误的合并、清除和优先级;补 SearchField 插槽 value。 +- [x] OTP 补 autoFocus、pasteTransformer、textAlign 的等价公共能力;validationDetails/FieldError 的必要校验信息复用现有字段协议,避免另建状态源。 +- [x] 对固定 input-otp 依赖核验 pattern 和 complete:满值替换、重复值、清空重填、受控拒绝、粘贴转换后过滤均需行为证据,再修契约。不能仅依据报告把两个不同语义直接替换。 +- [x] containerClassName 被上游公共类型 Omit 排除,不补;保留 PinInput、多真实 input、透明覆盖层和字符串/数组转换。密码管理器策略无等价能力时明确记录限制。 ## 用户可见通过条件 diff --git a/docs/upstream.md b/docs/upstream.md index 093becc..b84d925 100644 --- a/docs/upstream.md +++ b/docs/upstream.md @@ -366,3 +366,8 @@ Button/ButtonGroup/ToggleButton/ToggleButtonGroup与指定Accordion/Disclosure ### HD-06(2026-10-29) Link/Breadcrumbs 对照固定 ce90ea3;Breadcrumbs 的34种名称移植自该上游锁文件的 react-aria 3.52.1 `dist/private/intl/breadcrumbs`,仅数据,不引入 React 运行时。Adobe Apache-2.0声明保留于第三方许可及组件包 `LICENSE.react-aria`(随 tarball发布)。Vue identity采用 id/key/index,事件为 @action。日期焦点标记适配真实 DOM :focus-visible。 + + +### HD-07(2026-10-29) + +固定HeroUI ce90ea3的InputOTP公开类型及锁定input-otp1.5.0(npm tarball只读source map)核对:pattern.test整值、pasteTransformer先转换、complete effect只跟随accepted value跨阈值。仅在现有Vue/Reka字段/PinInput边界适配,不安装React或增加运行时依赖;底座多input、索引空位、单字段提交保留。全局/sticky RegExp去状态化延续既有Vue行为;字符选区限单槽,非单input任意跨槽选择。字段错误与focus采用现有共享上下文,新增原生ValidityState快照。 diff --git a/packages/vue/src/components/field/FieldError.vue b/packages/vue/src/components/field/FieldError.vue index 3f39d4e..1d916a7 100644 --- a/packages/vue/src/components/field/FieldError.vue +++ b/packages/vue/src/components/field/FieldError.vue @@ -19,6 +19,7 @@ const { field, id } = useFieldPart("error", attrs); {{ field?.errors.value.join(" ") }} diff --git a/packages/vue/src/components/field/context.ts b/packages/vue/src/components/field/context.ts index 9bd87ad..1a58dab 100644 --- a/packages/vue/src/components/field/context.ts +++ b/packages/vue/src/components/field/context.ts @@ -12,6 +12,7 @@ export interface FieldContext { required: ComputedRef; invalid: ComputedRef; errors: ComputedRef; + validationDetails?: ComputedRef; labelIds?: Ref; descriptionIds: Ref; errorIds: Ref; diff --git a/packages/vue/src/components/field/useTextField.ts b/packages/vue/src/components/field/useTextField.ts index 52c4d3c..cef30e3 100644 --- a/packages/vue/src/components/field/useTextField.ts +++ b/packages/vue/src/components/field/useTextField.ts @@ -12,12 +12,15 @@ import { shallowRef, useId, watchEffect, + onMounted, + nextTick, type PropType, type ExtractPropTypes, type Slots, type VNode, type VNodeChild, } from "vue"; +import { validitySnapshot } from "./validation"; import { textFieldVariants } from "@heroui-vue/styles"; import { fieldContextKey, @@ -34,6 +37,18 @@ import { import { useInheritedDisabled } from "./disabled"; +export interface TextFieldRenderProps { + value: string; + isDisabled: boolean; + isReadOnly: boolean; + isRequired: boolean; + isInvalid: boolean; + isFocusWithin: boolean; + isFocusVisible: boolean; + validationErrors: string[]; + validationDetails: ValidityState; +} + export const textFieldProps = { modelValue: String, defaultValue: String, @@ -50,6 +65,8 @@ export const textFieldProps = { isReadOnly: Boolean, isRequired: Boolean, isInvalid: Boolean, + autoFocus: Boolean, + validationErrors: [String, Array] as PropType, fullWidth: Boolean, variant: String as PropType<"primary" | "secondary">, validationBehavior: String as PropType, @@ -89,6 +106,10 @@ export function useTextField( const touched = ref(false), nativeError = ref(""); const dismissed = shallowRef(); + const dismissedLocal = shallowRef(); + const focused = ref(false), + focusVisible = ref(false); + const details = shallowRef(validitySnapshot()); const descriptionIds = ref([]), errorIds = ref([]); // Pre-plan direct/native-wrapped parts before rendering controls, so SSR has @@ -109,11 +130,19 @@ export function useTextField( ? errorMessages(source[props.name]) : []; }); + const localErrors = computed(() => + props.validationErrors !== dismissedLocal.value + ? errorMessages(props.validationErrors) + : [], + ); + const externalErrors = computed(() => [ + ...new Set([...localErrors.value, ...serverErrors.value]), + ]); const customErrors = computed(() => errorMessages(props.validate?.(value.value)), ); const errors = computed(() => [ - ...serverErrors.value, + ...externalErrors.value, ...(touched.value || behavior.value === "aria" ? customErrors.value : []), ...((touched.value || behavior.value === "aria") && nativeError.value ? [nativeError.value] @@ -128,8 +157,11 @@ export function useTextField( ); function setValue(next: string) { if (disabled.value || readOnly.value) return; + if (next !== value.value) { + dismissed.value = form?.validationErrors.value; + dismissedLocal.value = props.validationErrors; + } internal.value = next; - dismissed.value = form?.validationErrors.value; nativeError.value = ""; emit("update:modelValue", next); } @@ -148,6 +180,7 @@ export function useTextField( required, invalid, errors, + validationDetails: computed(() => details.value), descriptionIds, errorIds, value, @@ -189,7 +222,7 @@ export function useTextField( touched.value = true; const element = event.target as HTMLInputElement | HTMLTextAreaElement; nativeError.value = - customErrors.value.length || serverErrors.value.length + customErrors.value.length || externalErrors.value.length ? "" : element.validationMessage; }, @@ -198,6 +231,7 @@ export function useTextField( touched.value = false; nativeError.value = ""; dismissed.value = form?.validationErrors.value; + dismissedLocal.value = props.validationErrors; }, }; provide(fieldContextKey, field); @@ -205,16 +239,28 @@ export function useTextField( watchEffect( () => { const currentValue = value.value; + // Native constraints are patched by the leaf before this post effect. + // Track root props even when the value itself has not changed. + void [ + props.type, + props.minLength, + props.maxLength, + props.pattern, + required.value, + ]; control.value?.setCustomValidity( behavior.value === "native" && !disabled.value && !readOnly.value - ? [...serverErrors.value, ...customErrors.value].join(" ") + ? [...externalErrors.value, ...customErrors.value].join(" ") : "", ); if (behavior.value === "native" && touched.value) nativeError.value = - customErrors.value.length || serverErrors.value.length + customErrors.value.length || externalErrors.value.length ? "" : (control.value?.validationMessage ?? ""); + const snapshot = validitySnapshot(control.value?.validity); + if (JSON.stringify(snapshot) !== JSON.stringify(details.value)) + details.value = snapshot; if (behavior.value === "aria") nativeError.value = disabled.value || readOnly.value @@ -225,9 +271,30 @@ export function useTextField( }, { flush: "post" }, ); + onMounted(() => { + void nextTick(() => { + if (props.autoFocus && !disabled.value) control.value?.focus(); + }); + }); + function focusIn(event: FocusEvent) { + focused.value = true; + focusVisible.value = (event.target as HTMLElement).matches( + ":focus-visible", + ); + } + function focusOut(event: FocusEvent) { + if ( + !(event.currentTarget as HTMLElement).contains( + event.relatedTarget as Node | null, + ) + ) { + focused.value = false; + focusVisible.value = false; + } + } expose({ focus: () => control.value?.focus(), element: control }); function prepare( - nodes: VNodeChild[], + nodes: VNodeChild, found: { description: string[]; error: string[]; @@ -237,7 +304,7 @@ export function useTextField( }, path = "", ): VNodeChild[] { - return nodes.map((node, index) => { + return (Array.isArray(nodes) ? nodes : [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 }; @@ -267,7 +334,7 @@ export function useTextField( node.children && typeof node.children === "object" ) { - const groupSlots = node.children as { default?: () => VNodeChild[] }; + const groupSlots = node.children as { default?: () => VNodeChild }; if (typeof groupSlots.default === "function") { const prepared = prepare(groupSlots.default(), found, position); const clone = cloneVNode(node); @@ -305,6 +372,10 @@ export function useTextField( isRequired: required.value, isInvalid: invalid.value, validationErrors: errors.value, + validationDetails: details.value, + value: value.value, + isFocusWithin: focused.value, + isFocusVisible: focusVisible.value, ...options.slotState?.(), }) ?? [], found, @@ -330,6 +401,10 @@ export function useTextField( textFieldVariants({ fullWidth: props.fullWidth }), attrs.class, ], + onFocusin: focusIn, + onFocusout: focusOut, + "data-focus-within": focused.value || undefined, + "data-focus-visible": focusVisible.value || undefined, "data-slot": options.rootSlot ?? "textfield", "data-invalid": invalid.value || undefined, "data-disabled": disabled.value || undefined, @@ -341,5 +416,5 @@ export function useTextField( children, ); }; - return { field, element: control, render }; + return { field, element: control, render, focused, focusVisible }; } diff --git a/packages/vue/src/components/field/validation.ts b/packages/vue/src/components/field/validation.ts new file mode 100644 index 0000000..18ff36f --- /dev/null +++ b/packages/vue/src/components/field/validation.ts @@ -0,0 +1,16 @@ +/** Snapshot native readonly validity flags without retaining a live DOM object. */ +export function validitySnapshot(value?: ValidityState): ValidityState { + return { + badInput: value?.badInput ?? false, + customError: value?.customError ?? false, + patternMismatch: value?.patternMismatch ?? false, + rangeOverflow: value?.rangeOverflow ?? false, + rangeUnderflow: value?.rangeUnderflow ?? false, + stepMismatch: value?.stepMismatch ?? false, + tooLong: value?.tooLong ?? false, + tooShort: value?.tooShort ?? false, + typeMismatch: value?.typeMismatch ?? false, + valid: value?.valid ?? true, + valueMissing: value?.valueMissing ?? false, + }; +} diff --git a/packages/vue/src/components/input-otp/InputOTPRoot.vue b/packages/vue/src/components/input-otp/InputOTPRoot.vue index ee2f041..4a7282b 100644 --- a/packages/vue/src/components/input-otp/InputOTPRoot.vue +++ b/packages/vue/src/components/input-otp/InputOTPRoot.vue @@ -17,10 +17,12 @@ import { useAttrs, useId, watch, + watchEffect, type PropType, type VNode, type VNodeChild, } from "vue"; +import { validitySnapshot } from "../field/validation"; import { PinInputRoot } from "reka-ui"; import { inputOTPVariants, type InputOTPVariants } from "@heroui-vue/styles"; import { useInheritedDisabled } from "../field/disabled"; @@ -43,11 +45,11 @@ function attrBoolean(value: unknown): boolean { return value != null && value !== false; } -/** Match one character without leaking lastIndex on global/sticky regexes. */ -function charAllowed(re: RegExp, char: string): boolean { - if (!char) return true; +/** Test the whole candidate without leaking lastIndex on global/sticky regexes. */ +function valueAllowed(re: RegExp, value: string): boolean { + if (!value) return true; const flags = re.flags.replace(/[gy]/g, ""); - return new RegExp(re.source, flags).test(char); + return new RegExp(re.source, flags).test(value); } export default defineComponent({ @@ -83,6 +85,13 @@ export default defineComponent({ type: Boolean, default: false, }, + autoFocus: Boolean, + pasteTransformer: Function as PropType<(pastedText: string) => string>, + textAlign: { + type: String as PropType<"left" | "center" | "right">, + default: "left", + }, + validationDetails: Object as PropType, validationErrors: { type: Array as PropType, default: undefined, @@ -113,7 +122,7 @@ export default defineComponent({ type: String, default: "", }, - /** Character filter, e.g. REGEXP_ONLY_DIGITS. */ + /** Whole-value predicate, e.g. REGEXP_ONLY_DIGITS. */ pattern: { type: [String, RegExp] as PropType, default: undefined, @@ -179,19 +188,23 @@ export default defineComponent({ : EMPTY_ERRORS; }); + const nativeError = ref(""); const invalid = computed( () => props.isInvalid || (props.validationErrors?.length ?? 0) > 0 || serverErrors.value.length > 0 || + Boolean(nativeError.value) || attrs["aria-invalid"] === true || attrs["aria-invalid"] === "true", ); const errors = computed(() => [ ...(props.validationErrors ?? EMPTY_ERRORS), ...serverErrors.value, + ...(nativeError.value ? [nativeError.value] : []), ]); + const nativeDetails = shallowRef(validitySnapshot()); const resolvedId = computed(() => props.id ?? autoId); /** Stable id per real focusable input; Label `for` uses index 0. */ function inputId(index: number): string { @@ -206,6 +219,9 @@ export default defineComponent({ required: computed(() => props.required), invalid, errors, + validationDetails: computed( + () => props.validationDetails ?? nativeDetails.value, + ), labelIds, descriptionIds, errorIds, @@ -261,18 +277,25 @@ export default defineComponent({ const raw = next[i]; return raw == null ? "" : String(raw); }); + const proposed = stringFromChars(clamped); const re = pattern.value; - if (re) { - for (let i = 0; i < clamped.length; i++) { - const char = clamped[i]; - if (char && !charAllowed(re, char)) clamped[i] = ""; - } + if (re && !valueAllowed(re, proposed)) { + // Force the primitive and native inputs back to the accepted slots. + const accepted = [...slotChars.value]; + void nextTick(() => { + slotChars.value = accepted; + rootEl.value + ?.querySelectorAll( + 'input[data-slot="input-otp-input"]', + ) + .forEach((input, index) => { + input.value = accepted[index] ?? ""; + }); + }); + return false; } const previous = stringFromChars(slotChars.value); - const prevFilled = slotChars.value.filter(Boolean).length; - const nextFilled = clamped.filter(Boolean).length; slotChars.value = clamped; - const proposed = stringFromChars(clamped); const currentPublic = isControlled.value ? (props.modelValue ?? "") : previous; @@ -282,6 +305,7 @@ export default defineComponent({ lastEmitted = proposed; // Effective edit dismisses the current server-error response. dismissed.value = form?.validationErrors.value; + nativeError.value = ""; emit("update:modelValue", proposed); emit("change", proposed); void nextTick(() => { @@ -294,15 +318,27 @@ export default defineComponent({ } }); } - if ( - prevFilled < length.value && - nextFilled === length.value && - length.value > 0 - ) { - emit("complete", proposed); - } + return true; } + // Completion follows the accepted public value, never a rejected proposal. + watch( + () => + isControlled.value + ? (props.modelValue ?? "") + : stringFromChars(slotChars.value), + (next, previous) => { + if ( + next !== previous && + previous.length < length.value && + next.length === length.value && + length.value > 0 + ) + emit("complete", next); + }, + { flush: "post" }, + ); + function handlePinUpdate(value: unknown) { applyChars(Array.isArray(value) ? value : []); } @@ -327,6 +363,7 @@ export default defineComponent({ slotChars.value = charsFromString(incoming, length.value); } dismissed.value = form?.validationErrors.value; + nativeError.value = ""; }); } @@ -349,7 +386,46 @@ export default defineComponent({ formEl = next; formEl?.addEventListener("reset", reset); } - onMounted(bindForm); + onMounted(() => { + bindForm(); + void nextTick(() => { + if (props.autoFocus && !disabled.value) + rootEl.value + ?.querySelector( + 'input[data-slot="input-otp-input"]:not(:disabled)', + ) + ?.focus(); + }); + }); + watchEffect( + () => { + // Shared FieldContext exposes the real validation proxy, with optional + // caller-supplied ValidityState taking precedence for FieldError slots. + const proxy = rootEl.value?.querySelector( + 'input[aria-hidden="true"]', + ); + if (!proxy) return; + const source = pattern.value?.source; + if (source) proxy.setAttribute("pattern", source); + else proxy.removeAttribute("pattern"); + proxy.readOnly = readOnly.value; + if (disabled.value || readOnly.value) nativeError.value = ""; + proxy.setCustomValidity( + disabled.value || readOnly.value + ? "" + : [...(props.validationErrors ?? []), ...serverErrors.value].join( + " ", + ), + ); + // Track primitive value updates so native validity is read after DOM patch. + chars.value; + props.required; + const snapshot = validitySnapshot(proxy.validity); + if (JSON.stringify(snapshot) !== JSON.stringify(nativeDetails.value)) + nativeDetails.value = snapshot; + }, + { flush: "post" }, + ); onUpdated(bindForm); onBeforeUnmount(() => { formEl?.removeEventListener("reset", reset); @@ -369,12 +445,78 @@ export default defineComponent({ chars, mask: computed(() => props.mask), inputClassName: computed(() => props.inputClassName), + textAlign: computed(() => props.textAlign), + handlePaste, + guardInput, describedBy, inputId, labelledBy, accessibleLabel, }); + function guardInput(event: InputEvent, index: number) { + if (event.isComposing) return; + if (!(event.target instanceof HTMLInputElement)) return; + const target = event.target; + const next = [...slotChars.value]; + const multi = (event.data?.length ?? 0) > 1; + if (multi) { + const text = target.value; + const start = text.length >= length.value ? 0 : index; + for ( + let i = start; + i < Math.min(start + text.length, length.value); + i++ + ) + next[i] = text[i - start]!; + } else next[index] = event.data || target.value.slice(-1); + if ( + disabled.value || + readOnly.value || + event.defaultPrevented || + (pattern.value && !valueAllowed(pattern.value, stringFromChars(next))) + ) { + event.preventDefault(); + event.stopImmediatePropagation(); + target.value = slotChars.value[index] ?? ""; + target.select(); + } + } + + function handlePaste(event: ClipboardEvent, index: number) { + if ( + event.defaultPrevented || + disabled.value || + readOnly.value || + !event.clipboardData + ) + return; + const raw = + event.clipboardData.getData("text/plain") || + event.clipboardData.getData("text"); + const text = props.pasteTransformer ? props.pasteTransformer(raw) : raw; + event.preventDefault(); + event.stopImmediatePropagation(); + if (!text) return; + // Preserve PinInput's slot editing convention: a full code replaces + // all slots; a shorter paste starts at the focused slot. + const start = text.length >= length.value ? 0 : index; + const next = [...slotChars.value]; + for (let i = start; i < Math.min(start + text.length, length.value); i++) + next[i] = text[i - start]!; + if (!applyChars(next)) return; + void nextTick(() => { + if (isControlled.value && props.modelValue !== stringFromChars(next)) + return; + const inputs = rootEl.value?.querySelectorAll( + 'input[data-slot="input-otp-input"]', + ); + const input = inputs?.[Math.min(start + text.length, length.value - 1)]; + input?.focus(); + input?.select(); + }); + } + function prepareLabels( nodes: VNodeChild[], ids: string[], @@ -405,6 +547,19 @@ export default defineComponent({ return node; }); } + function invalidCapture(event: Event) { + const target = event.target; + if ( + target instanceof HTMLInputElement && + target.getAttribute("aria-hidden") === "true" + ) { + nativeDetails.value = validitySnapshot(target.validity); + nativeError.value = + props.validationErrors?.length || serverErrors.value.length + ? "" + : target.validationMessage; + } + } function render() { const labels: string[] = []; const children = prepareLabels(slots.default?.() ?? [], labels); @@ -413,6 +568,7 @@ export default defineComponent({ return h( PinInputRoot, { + ...attrs, ref: setRoot, modelValue: chars.value, disabled: disabled.value, @@ -423,7 +579,14 @@ export default defineComponent({ required: props.required, id: resolvedId.value, "onUpdate:modelValue": handlePinUpdate, - ...attrs, + onInvalidCapture: [ + ...(Array.isArray(attrs.onInvalidCapture) + ? attrs.onInvalidCapture + : attrs.onInvalidCapture + ? [attrs.onInvalidCapture] + : []), + invalidCapture, + ], class: [variantSlots.value.base(), attrs.class], "data-disabled": disabled.value || undefined, "data-invalid": invalid.value ? "true" : undefined, diff --git a/packages/vue/src/components/input-otp/InputOTPSlot.vue b/packages/vue/src/components/input-otp/InputOTPSlot.vue index d75deda..c183cfb 100644 --- a/packages/vue/src/components/input-otp/InputOTPSlot.vue +++ b/packages/vue/src/components/input-otp/InputOTPSlot.vue @@ -93,6 +93,7 @@ export default defineComponent({ onKeydownCapture: userKeydownCapture, onPaste: userPaste, onPasteCapture: userPasteCapture, + onInputCapture: userInputCapture, ...rest } = attrs as Record; @@ -110,6 +111,7 @@ export default defineComponent({ ...toHandlerArray(userPasteCapture), ...toHandlerArray(userPaste), stopIfPrevented, + (event) => context?.handlePaste(event as ClipboardEvent, props.index), ]; return h( @@ -117,6 +119,10 @@ export default defineComponent({ { ...rest, class: [slotClass, cls], + onInputCapture: [ + ...toHandlerArray(userInputCapture), + (event: InputEvent) => context?.guardInput(event, props.index), + ], onKeydownCapture: keydownCapture, onPasteCapture: pasteCapture, "data-active": isActive.value || undefined, @@ -151,6 +157,7 @@ export default defineComponent({ disabled: isDisabled.value, readonly: isReadOnly.value || undefined, class: inputClass, + style: { textAlign: context?.textAlign.value }, id: context?.inputId(props.index), "data-slot": "input-otp-input", autocomplete: "one-time-code", diff --git a/packages/vue/src/components/input-otp/context.ts b/packages/vue/src/components/input-otp/context.ts index 86cd805..f7276bb 100644 --- a/packages/vue/src/components/input-otp/context.ts +++ b/packages/vue/src/components/input-otp/context.ts @@ -14,6 +14,9 @@ export interface InputOTPContextValue { chars: ComputedRef; mask: ComputedRef; inputClassName: ComputedRef; + textAlign: ComputedRef<"left" | "center" | "right">; + guardInput: (event: InputEvent, index: number) => void; + handlePaste: (event: ClipboardEvent, index: number) => void; describedBy: ComputedRef; labelledBy: ComputedRef; accessibleLabel: ComputedRef; diff --git a/packages/vue/src/components/search-field/SearchField.vue b/packages/vue/src/components/search-field/SearchField.vue index f9a29b1..6078d71 100644 --- a/packages/vue/src/components/search-field/SearchField.vue +++ b/packages/vue/src/components/search-field/SearchField.vue @@ -4,21 +4,24 @@ import { defineComponent, getCurrentInstance, nextTick, - onMounted, provide, ref, + type SlotsType, + type VNode, } from "vue"; import { searchFieldVariants } from "@heroui-vue/styles"; import { textFieldProps, useTextField } from "../field/useTextField"; -import { searchFieldContextKey } from "./context"; +import { searchFieldContextKey, type SearchFieldRenderProps } from "./context"; export default defineComponent({ name: "SearchField", inheritAttrs: false, + slots: Object as SlotsType<{ + default: (state: SearchFieldRenderProps) => VNode[]; + }>, props: { ...textFieldProps, type: { type: String, default: "search" }, - autoFocus: Boolean, }, emits: { "update:modelValue": (_value: string) => true, @@ -27,32 +30,34 @@ export default defineComponent({ }, setup(props, context) { const instance = getCurrentInstance(); - const hovered = ref(false), - focused = ref(false), - focusVisible = ref(false); + const hovered = 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, - }), - }); + const { field, element, render, focused, focusVisible } = 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 ( @@ -112,9 +117,7 @@ export default defineComponent({ clear, keydown, }); - onMounted(() => { - if (props.autoFocus && !field.disabled.value) element.value?.focus(); - }); + return render; }, }); diff --git a/packages/vue/src/components/search-field/context.ts b/packages/vue/src/components/search-field/context.ts index b96ef36..72ac0df 100644 --- a/packages/vue/src/components/search-field/context.ts +++ b/packages/vue/src/components/search-field/context.ts @@ -1,6 +1,11 @@ import type { ComputedRef, InjectionKey, Ref } from "vue"; import type { searchFieldVariants } from "@heroui-vue/styles"; import type { TextFieldContext } from "../textfield/context"; +import type { TextFieldRenderProps } from "../field/useTextField"; +export interface SearchFieldRenderProps extends TextFieldRenderProps { + isEmpty: boolean; + isHovered: boolean; +} export interface SearchFieldContext { field: TextFieldContext; slots: ComputedRef>; diff --git a/packages/vue/src/components/textfield/TextField.vue b/packages/vue/src/components/textfield/TextField.vue index 723cddc..1153641 100644 --- a/packages/vue/src/components/textfield/TextField.vue +++ b/packages/vue/src/components/textfield/TextField.vue @@ -1,10 +1,17 @@ + + + + + 姓名 + + 字段内按钮 + + {{ + JSON.stringify({ + value: state.value, + within: state.isFocusWithin, + visible: state.isFocusVisible, + }) + }} + + + {{ errors.validationErrors.join("|") }} / + {{ errors.validationDetails?.customError }} + + + + 搜索 + + + + + {{ state.value }} + + 重置字段 + + 新错误响应 + + + + 挂载验证码 + + + 接受验证码 + + + + 禁用验证码 + + + + 只读验证码 + + + 输入对齐 + + left + center + right + + + + + + + + + + {{ state.validationErrors.join("|") }} / missing={{ + state.validationDetails?.valueMissing + }} + + + 校验验证码 + 重置验证码 + 清空验证码 + + + {{ JSON.stringify({ value: otp, completes, proposals }) }} + + + diff --git a/tests/input-otp.test.ts b/tests/input-otp.test.ts index a2be89c..779b4d5 100644 --- a/tests/input-otp.test.ts +++ b/tests/input-otp.test.ts @@ -219,7 +219,7 @@ describe("InputOTP value model", () => { }); describe("InputOTP pattern and states", () => { - it("filters characters with REGEXP_ONLY_CHARS and digits constants", async () => { + it("checks candidates with REGEXP_ONLY_CHARS and digits constants", async () => { expect(REGEXP_ONLY_DIGITS).toBe("^\\d+$"); expect(REGEXP_ONLY_CHARS).toBe("^[a-zA-Z]+$"); expect(REGEXP_ONLY_DIGITS_AND_CHARS).toBe("^[a-zA-Z0-9]+$"); @@ -540,3 +540,252 @@ describe("InputOTP types", () => { expect((bad as { variant?: string }).variant).toBe("ghost"); }); }); + +function pasteInto(input: Element, text: string) { + const event = new Event("paste", { bubbles: true, cancelable: true }); + Object.defineProperty(event, "clipboardData", { + value: { getData: () => text }, + }); + input.dispatchEvent(event); +} +const settleOtp = async () => { + await nextTick(); + await nextTick(); + await nextTick(); +}; +function enhancedOtp( + props: Record = {}, + slots: Record = {}, +) { + return mount(InputOTP, { + props: { maxLength: 4, ...props }, + slots: { + default: () => + h(InputOTPGroup, {}, () => + [0, 1, 2, 3].map((index) => h(InputOTPSlot, { index })), + ), + ...slots, + }, + attachTo: document.body, + }); +} +it("OTP autoFocus and textAlign reach actual inputs without leaking root props", async () => { + const w = enhancedOtp({ autoFocus: true, textAlign: "right" }); + try { + await settleOtp(); + expect(document.activeElement).toBe(slotInputs(w)[0].element); + expect((slotInputs(w)[0].element as HTMLInputElement).style.textAlign).toBe( + "right", + ); + expect(w.attributes("textalign")).toBeUndefined(); + await w.setProps({ textAlign: "center" }); + expect((slotInputs(w)[3].element as HTMLInputElement).style.textAlign).toBe( + "center", + ); + } finally { + w.unmount(); + } +}); +it.each(["isDisabled", "isReadOnly"])( + "OTP %s prevents paste transformation and edits", + async (flag) => { + const transform = vi.fn((text: string) => text.replaceAll("-", "")); + const w = enhancedOtp({ + [flag]: true, + defaultValue: "12", + pasteTransformer: transform, + autoFocus: true, + }); + try { + await settleOtp(); + pasteInto(slotInputs(w)[0].element, "34-56"); + await settleOtp(); + expect(transform).not.toHaveBeenCalled(); + expect( + slotInputs(w) + .map((i) => (i.element as HTMLInputElement).value) + .join(""), + ).toBe("12"); + if (flag === "isDisabled") + expect(w.element.contains(document.activeElement)).toBe(false); + } finally { + w.unmount(); + } + }, +); +it("OTP transforms paste before whole-value pattern checking and restores rejected DOM values", async () => { + const w = enhancedOtp({ + pattern: "^12[0-9]*$", + defaultValue: "12", + pasteTransformer: (t: string) => t.replaceAll("-", ""), + }); + try { + pasteInto(slotInputs(w)[0].element, "12-34"); + await settleOtp(); + expect( + slotInputs(w).map((i) => (i.element as HTMLInputElement).value), + ).toEqual(["1", "2", "3", "4"]); + expect(document.activeElement).toBe(slotInputs(w)[3].element); + expect((slotInputs(w)[3].element as HTMLInputElement).selectionStart).toBe( + 0, + ); + await slotInputs(w)[2].setValue("8"); + await settleOtp(); + expect( + slotInputs(w) + .map((i) => (i.element as HTMLInputElement).value) + .join(""), + ).toBe("1284"); + await slotInputs(w)[0].setValue("9"); + await settleOtp(); + expect( + slotInputs(w) + .map((i) => (i.element as HTMLInputElement).value) + .join(""), + ).toBe("1284"); + pasteInto(slotInputs(w)[0].element, "90-12"); + await settleOtp(); + expect( + slotInputs(w) + .map((i) => (i.element as HTMLInputElement).value) + .join(""), + ).toBe("1284"); + } finally { + w.unmount(); + } +}); +it("OTP rejects an invalid paste as one edit and honors consumer cancellation", async () => { + const w = enhancedOtp({ pattern: REGEXP_ONLY_DIGITS, defaultValue: "12" }); + try { + pasteInto(slotInputs(w)[0].element, "3a45"); + await settleOtp(); + expect( + slotInputs(w) + .map((i) => (i.element as HTMLInputElement).value) + .join(""), + ).toBe("12"); + const transform = vi.fn((t: string) => t); + await w.setProps({ pasteTransformer: transform }); + const slot = w.element; + slot.addEventListener("paste", (e: Event) => e.preventDefault(), { + capture: true, + }); + pasteInto(slotInputs(w)[0].element, "5678"); + await settleOtp(); + expect(transform).not.toHaveBeenCalled(); + } finally { + w.unmount(); + } +}); +it("OTP complete follows accepted threshold crossings, including external updates, rather than rejected drafts", async () => { + const w = enhancedOtp({ modelValue: "12" }); + try { + pasteInto(slotInputs(w)[0].element, "1234"); + await settleOtp(); + pasteInto(slotInputs(w)[0].element, "1234"); + await settleOtp(); + expect(w.emitted("update:modelValue")).toHaveLength(2); + expect(w.emitted("complete")).toBeUndefined(); + expect( + slotInputs(w) + .map((i) => (i.element as HTMLInputElement).value) + .join(""), + ).toBe("12"); + await w.setProps({ modelValue: "1234" }); + await settleOtp(); + expect(w.emitted("complete")).toEqual([["1234"]]); + await w.setProps({ modelValue: "9876" }); + await settleOtp(); + pasteInto(slotInputs(w)[0].element, "9876"); + await settleOtp(); + expect(w.emitted("complete")).toHaveLength(1); + await w.setProps({ modelValue: "" }); + await settleOtp(); + await w.setProps({ modelValue: "4567" }); + await settleOtp(); + expect(w.emitted("complete")).toEqual([["1234"], ["4567"]]); + } finally { + w.unmount(); + } +}); +it("OTP passes caller ValidityState through shared FieldError without emitting it on the DOM", async () => { + const { FieldError } = await import("../packages/vue/src"); + const details = { + badInput: false, + customError: true, + patternMismatch: false, + rangeOverflow: false, + rangeUnderflow: false, + stepMismatch: false, + tooLong: false, + tooShort: false, + typeMismatch: false, + valid: false, + valueMissing: false, + }; + const w = enhancedOtp( + { + isInvalid: true, + validationDetails: details, + validationErrors: ["server"], + }, + { + default: () => [ + h(InputOTPGroup, {}, () => + [0, 1, 2, 3].map((index) => h(InputOTPSlot, { index })), + ), + h( + FieldError, + {}, + { + default: (s: { validationDetails?: ValidityState }) => + String(s.validationDetails?.customError), + }, + ), + ], + }, + ); + try { + await settleOtp(); + expect(w.get('[data-slot="field-error"]').text()).toBe("true"); + expect(w.attributes("validationdetails")).toBeUndefined(); + } finally { + w.unmount(); + } +}); + +it("OTP native required validation shares FieldError details and clears on an effective edit", async () => { + const { FieldError } = await import("../packages/vue/src"); + const w = enhancedOtp( + { required: true }, + { + default: () => [ + h(InputOTPGroup, {}, () => + [0, 1, 2, 3].map((index) => h(InputOTPSlot, { index })), + ), + h( + FieldError, + {}, + { + default: (s: { validationDetails?: ValidityState }) => + String(s.validationDetails?.valueMissing), + }, + ), + ], + }, + ); + try { + await settleOtp(); + const proxy = w.get('input[aria-hidden="true"]') + .element as HTMLInputElement; + expect(proxy.checkValidity()).toBe(false); + await settleOtp(); + expect(w.get('[role="alert"]').text()).toBe("true"); + await slotInputs(w)[0].setValue("1"); + await settleOtp(); + expect(w.find('[role="alert"]').exists()).toBe(false); + expect(proxy.checkValidity()).toBe(true); + } finally { + w.unmount(); + } +}); diff --git a/tests/package/client-checks.json b/tests/package/client-checks.json index e5bb31f..2a11741 100644 --- a/tests/package/client-checks.json +++ b/tests/package/client-checks.json @@ -871,5 +871,20 @@ ".hv-date-picker__trigger", ".hv-date-range-picker__trigger" ] + }, + "field-otp": { + "exports": [ + "TextField", + "SearchField", + "FieldError", + "InputOTP", + "InputOTPSlot" + ], + "css": [ + ".hv-textfield", + ".hv-search-field", + ".hv-field-error", + ".hv-input-otp__input" + ] } } diff --git a/tests/package/field-otp-contract.ts b/tests/package/field-otp-contract.ts new file mode 100644 index 0000000..ee76ff7 --- /dev/null +++ b/tests/package/field-otp-contract.ts @@ -0,0 +1,51 @@ +import { h } from "vue"; +import { + TextField, + SearchField, + type TextFieldProps, + type SearchFieldProps, + type TextFieldRenderProps, + type SearchFieldRenderProps, + type InputOTPProps, +} from "@heroui-vue/components"; +const text: TextFieldProps = { autoFocus: true, validationErrors: ["server"] }; +const search: SearchFieldProps = { validationErrors: "local", autoFocus: true }; +const otp: InputOTPProps = { + maxLength: 4, + autoFocus: true, + textAlign: "right", + pasteTransformer: (text) => text.replaceAll("-", ""), +}; +const textSlot: NonNullable< + InstanceType["$slots"]["default"] +> = (state: TextFieldRenderProps) => [ + h( + "span", + `${state.value}/${state.isFocusWithin}/${state.validationDetails.valid}`, + ), +]; +const searchSlot: NonNullable< + InstanceType["$slots"]["default"] +> = (state: SearchFieldRenderProps) => [ + h("span", `${state.value}/${state.isEmpty}/${state.isFocusVisible}`), +]; +// @ts-expect-error errors are local text/arrays, not Form name maps +const badField: TextFieldProps = { validationErrors: { email: "wrong" } }; +// @ts-expect-error text alignment is a closed union +const badAlignment: InputOTPProps = { maxLength: 4, textAlign: "bottom" }; +// @ts-expect-error the paste transformer returns a string +const badPaste: InputOTPProps = { maxLength: 4, pasteTransformer: () => 42 }; +const badDetails: InputOTPProps = { + maxLength: 4, + // @ts-expect-error all native validity flags are required + validationDetails: { valid: false }, +}; +void text; +void search; +void otp; +void textSlot; +void searchSlot; +void badField; +void badAlignment; +void badPaste; +void badDetails;