feat: migrate public TimeField with shared date input parts

This commit is contained in:
maoyingjie
2026-10-26 17:56:41 +08:00
parent d74ad1b711
commit 97263d82e1
45 changed files with 2415 additions and 61 deletions
+5
View File
@@ -300,6 +300,11 @@ export const componentItems: DocsItem[] = [
url: "/components/text-field",
category: "forms",
},
{
title: "TimeField 时间字段",
url: "/components/time-field",
category: "date-and-time",
},
{
title: "Toast 轻提示",
url: "/components/toast",
+458
View File
@@ -0,0 +1,458 @@
---
title: TimeField 时间字段
description: 时间输入字段,包含标签、说明与校验。
---
## 用法
```ts
import {
TimeField,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
} from "@heroui-vue/components";
```
<ComponentPreview name="time-field-basic" />
## 组件结构
```vue
<script setup lang="ts">
import {
TimeField,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
Label,
Description,
FieldError,
} from "@heroui-vue/components";
</script>
<template>
<TimeField>
<Label>时间</Label>
<TimeFieldGroup>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
</TimeFieldGroup>
<Description>输入时间</Description>
<FieldError />
</TimeField>
</template>
```
> **TimeField** 将标签、时间输入、说明与错误信息组合为单个无障碍组件。
## 示例
### 带图标
添加前缀或后缀图标以增强时间字段。
<ComponentPreview name="time-field-with-prefix-icon" />
<ComponentPreview name="time-field-with-suffix-icon" />
<ComponentPreview name="time-field-with-prefix-and-suffix" />
### 表面样式
在 [Surface](/components/surface) 内使用时,请在 `TimeFieldGroup` 上使用 `variant="secondary"`,以应用适合表面背景的低强调变体。
<ComponentPreview name="time-field-on-surface" />
### 带描述
<ComponentPreview name="time-field-with-description" />
### 必填字段
<ComponentPreview name="time-field-required" />
### 禁用
<ComponentPreview name="time-field-disabled" />
### 宽度充满
<ComponentPreview name="time-field-full-width" />
### 表单校验
将 `isInvalid` 与 `FieldError` 配合使用,以展示校验消息。
<ComponentPreview name="time-field-invalid" />
### 受控组件
使用 `v-model` 控制值,以与其他组件或状态管理同步。
<ComponentPreview name="time-field-controlled" />
### 表单示例
包含校验与提交处理的完整表单示例。
<ComponentPreview name="time-field-form-example" />
### 带校验
TimeField 支持通过 `minValue`、`maxValue` 及自定义校验逻辑进行验证。
<ComponentPreview name="time-field-with-validation" />
### 渲染函数
<ComponentPreview
name="time-field-render-function"
/>
## 自定义样式
### Tailwind CSS
<ComponentPreview name="time-field-custom-styles" />
### 全局 CSS
若要自定义组件类,可使用 `@layer components` 指令。[了解更多](https://tailwindcss.com/docs/adding-custom-styles#adding-component-classes)。
```css
@layer components {
.hv-time-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-slot="description"] {
@apply px-1;
}
}
}
```
## 样式参考
HeroUI 遵循 [BEM](https://getbem.com/) 方法论,确保组件变体与状态可复用且易于自定义。
### CSS 类
- `.hv-time-field` – 轻量样式的根容器(`flex flex-col gap-1`)
> **说明:** 子组件([Label](/components/label)、[Description](/components/description)、[FieldError](/components/field-error))拥有各自的 CSS 类与样式。自定义方式请参阅对应文档。`TimeFieldGroup` 的样式见下文 API 参考。
### 交互状态
TimeField 会根据状态自动设置以下 data 属性:
- **无效**:`[data-invalid="true"]` 或 `[aria-invalid="true"]` – 无效时自动隐藏 description 插槽
- **必填**:`[data-required="true"]` – 当 `isRequired` 为 true 时添加
- **禁用**:`[data-disabled="true"]` – 当 `isDisabled` 为 true 时添加
- **焦点在内**:`[data-focus-within="true"]` – 任一子输入聚焦时添加
## API 参考
### TimeField
TimeField 使用 Vue 时间值、作用域插槽和共享字段协议,完整差异见下方兼容说明。
#### Base Props
| Prop | 类型 | 默认值 | 描述 |
| ----------- | ---------------------------------------------- | ------- | ---------------------------------------------- |
| 默认插槽 | `(values: TimeFieldRenderProps) => VNodeChild` | - | 子组件(Label、TimeFieldGroup 等)或渲染函数。 |
| `class` | `string` | - | 与默认样式合并的 CSS 类。 |
| `style` | `StyleValue` | - | Vue 内联样式。 |
| `fullWidth` | `boolean` | `false` | 时间字段是否占满容器宽度。 |
| `id` | `string` | - | 元素的唯一 id。 |
| `as` | `string` | `"div"` | 自定义根元素,attrs 和 DOM 事件透传到此节点。 |
#### Value Props
| Prop | 类型 | 默认值 | 描述 |
| ------------------------------ | ------------------------------------ | ------ | ------------------------------------------------------------------------------------------------------------ |
| `modelValue` / `value` | `TimeValue \| null` | - | 当前值(受控)。类型见 [`@internationalized/date`](https://react-aria.adobe.com/internationalized/date/)。 |
| `defaultValue` | `TimeValue \| null` | - | 默认值(非受控)。类型见 [`@internationalized/date`](https://react-aria.adobe.com/internationalized/date/)。 |
| `update:modelValue` / `change` | `(value: TimeValue \| null) => void` | - | 值变化时触发的事件处理函数。 |
| `placeholderValue` | `TimeValue \| null` | - | 影响占位符格式的占位时间;默认随小时制为 12:00 AM 或 00:00。 |
#### Validation Props
| Prop | 类型 | 默认值 | 描述 |
| -------------------- | ---------------------------------------------- | ---------- | -------------------------------------------------------------------------------------------------------------- |
| `isRequired` | `boolean` | `false` | 是否在提交表单前要求用户输入。 |
| `isInvalid` | `boolean` | - | 值是否无效。 |
| `minValue` | `TimeValue \| null` | - | 用户可选择最早时间。类型见 [`@internationalized/date`](https://react-aria.adobe.com/internationalized/date/)。 |
| `maxValue` | `TimeValue \| null` | - | 用户可选择最晚时间。类型见 [`@internationalized/date`](https://react-aria.adobe.com/internationalized/date/)。 |
| `validate` | `(value: TimeValue \| null) => ValidateResult` | - | 自定义校验函数。 |
| `validationBehavior` | `'native' \| 'aria'` | `'native'` | 使用原生 HTML 表单校验还是 ARIA 属性。 |
#### Format Props
| Prop | 类型 | 默认值 | 描述 |
| ------------------------- | -------------------------------- | ---------- | -------------------------------------------------- |
| `granularity` | `'hour' \| 'minute' \| 'second'` | `'minute'` | 时间选择器显示的最小单位。 |
| `hourCycle` | `12 \| 24` | - | 以 12 或 24 小时制显示时间;默认由语言环境决定。 |
| `hideTimeZone` | `boolean` | `false` | 是否隐藏时区缩写。 |
| `shouldForceLeadingZeros` | `boolean` | - | 是否始终为小时字段显示前导零;默认由语言环境决定。 |
#### State Props
| Prop | 类型 | 默认值 | 描述 |
| ------------ | --------- | ------ | ---------------------- |
| `isDisabled` | `boolean` | - | 是否禁用输入。 |
| `isReadOnly` | `boolean` | - | 是否可选中但不可修改。 |
#### Form Props
| Prop | 类型 | 默认值 | 描述 |
| ----------- | --------- | ------ | ------------------------------------------------------------- |
| `name` | `string` | - | 输入元素的 name,用于 HTML 表单提交;以 ISO 8601 字符串提交。 |
| `autoFocus` | `boolean` | - | 是否在渲染后自动聚焦该元素。 |
#### Accessibility Props
| Prop | 类型 | 默认值 | 描述 |
| ------------------ | -------- | ------ | -------------------------- |
| `aria-label` | `string` | - | 无可见标签时的无障碍标签。 |
| `aria-labelledby` | `string` | - | 标注该字段的元素 id。 |
| `aria-describedby` | `string` | - | 描述该字段的元素 id。 |
| `aria-details` | `string` | - | 包含额外详情的元素 id。 |
### 组合组件
TimeField 与以下独立组件配合使用,请分别导入并直接使用:
- **Label** – 来自 `@heroui-vue/components` 的字段标签
- **TimeFieldGroup** – 时间输入分组(详见下文)
- **TimeFieldInput** – 来自 `@heroui-vue/components` 的分段位编辑输入
- **TimeFieldSegment** – 单个时间段位(时、分、秒等)
- **TimeFieldPrefix** / **TimeFieldSuffix** – 输入组的前缀与后缀插槽
- **Description** – 来自 `@heroui-vue/components` 的辅助说明
- **FieldError** – 来自 `@heroui-vue/components` 的校验错误信息
这些组件各自有独立的 props API。在 TimeField 中直接组合使用:
```vue
<script setup lang="ts">
import { shallowRef } from "vue";
import { parseTime } from "@internationalized/date";
import {
TimeField,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
Label,
Description,
FieldError,
type TimeValue,
} from "@heroui-vue/components";
const time = shallowRef<TimeValue | null>(null);
</script>
<template>
<TimeField
v-model="time"
is-required
:min-value="parseTime('09:00')"
:max-value="parseTime('17:00')"
>
<Label>Appointment Time</Label>
<TimeFieldGroup>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
</TimeFieldGroup>
<Description>Select a time between 9:00 AM and 5:00 PM.</Description>
<FieldError />
</TimeField>
</template>
```
### TimeValue 类型
TimeField 使用 [`@internationalized/date`](https://react-aria.adobe.com/internationalized/date/) 中的类型:
- `Time` – 仅时间(时、分、秒)
- `CalendarDateTime` – 含日期与时间、不含时区(TimeField 仅展示时间部分)
- `ZonedDateTime` – 含日期、时间与时区(TimeField 仅展示时间部分)
示例:
```ts
import {
parseTime,
Time,
getLocalTimeZone,
now,
} from "@internationalized/date";
const time = parseTime("14:30");
const currentTime = now(getLocalTimeZone());
const timeValue = new Time(
currentTime.hour,
currentTime.minute,
currentTime.second,
);
```
> **说明:** TimeField 使用 [`@internationalized/date`](https://react-aria.adobe.com/internationalized/date/) 进行时间处理、解析与类型定义。更多类型与函数见 [Internationalized Date 文档](https://react-aria.adobe.com/internationalized/date/)。
### TimeFieldRenderProps
默认作用域插槽可读取以下状态;`class` 和 `style` 使用 Vue 原生绑定:
| Prop | 类型 | 描述 |
| ---------------- | --------- | -------------------------- |
| `isDisabled` | `boolean` | 字段是否禁用。 |
| `isInvalid` | `boolean` | 字段当前是否无效。 |
| `isReadOnly` | `boolean` | 字段是否只读。 |
| `isRequired` | `boolean` | 字段是否必填。 |
| `isFocused` | `boolean` | 字段是否聚焦。 |
| `isFocusWithin` | `boolean` | 是否有子元素聚焦。 |
| `isFocusVisible` | `boolean` | 焦点是否可见(键盘导航)。 |
### TimeFieldGroup
TimeFieldGroup 复用 DateInputGroup,支持:
| Prop | 类型 | 默认值 | 描述 |
| --------- | -------------------------- | ----------- | -------------------------------------------------------------------------------------- |
| `class` | `string` | - | 与组件样式合并的 Tailwind CSS 类。 |
| `variant` | `"primary" \| "secondary"` | `"primary"` | 视觉变体。`primary` 为默认带阴影样式;`secondary` 为低强调、无阴影,适合用于 Surface。 |
### TimeFieldInput
TimeFieldInput 复用 DateInputGroupInput,支持:
| Prop | 类型 | 默认值 | 描述 |
| ------- | -------- | ------ | ---------------------------------- |
| `class` | `string` | - | 与组件样式合并的 Tailwind CSS 类。 |
TimeFieldInput 使用 `v-slot="{ segment, index }"` 逐段渲染;省略插槽时自动渲染全部段位。视觉 `variant` 放在 TimeFieldGroup 上。
### TimeFieldSegment
TimeFieldSegment 复用 DateInputGroupSegment,支持:
| Prop | 类型 | 默认值 | 描述 |
| --------- | ------------- | ------ | --------------------------------------------------- |
| `segment` | `DateSegment` | - | 来自 TimeFieldInput 渲染函数的 `DateSegment` 对象。 |
| `class` | `string` | - | 与组件样式合并的 Tailwind CSS 类。 |
### TimeFieldInputContainer
输入组合容器,复用 DateInputGroupInputContainer。支持 `as`(默认 div)、原生 attrs 与默认插槽。
### TimeFieldPrefix
TimeFieldPrefix 接受标准 HTML `div` 属性:
| Prop | 类型 | 默认值 | 描述 |
| -------- | ------------ | ------ | ---------------------------------- |
| `class` | `string` | - | 与组件样式合并的 Tailwind CSS 类。 |
| 默认插槽 | `VNodeChild` | - | 前缀插槽中要显示的内容。 |
### TimeFieldSuffix
TimeFieldSuffix 接受标准 HTML `div` 属性:
| Prop | 类型 | 默认值 | 描述 |
| -------- | ------------ | ------ | ---------------------------------- |
| `class` | `string` | - | 与组件样式合并的 Tailwind CSS 类。 |
| 默认插槽 | `VNodeChild` | - | 后缀插槽中要显示的内容。 |
## TimeFieldGroup 样式
### 全局 CSS
基础类作用于所有实例,可通过 `@layer components` 一次性覆盖。
```css
@layer components {
.hv-date-input-group {
@apply inline-flex h-9 items-center overflow-hidden rounded-field border bg-field text-sm text-field-foreground shadow-field outline-none;
&:hover,
&[data-hovered="true"] {
@apply bg-field-hover;
}
&[data-focus-within="true"],
&:focus-within {
@apply status-focused-field;
}
&[data-invalid="true"] {
@apply status-invalid-field;
}
&[data-disabled="true"],
&[aria-disabled="true"] {
@apply status-disabled;
}
}
.hv-date-input-group__input {
@apply flex flex-1 items-center gap-px rounded-none border-0 bg-transparent px-3 py-2 shadow-none outline-none;
}
.hv-date-input-group__segment {
@apply inline-block rounded-md px-0.5 text-end tabular-nums outline-none;
&:focus,
&[data-focused="true"] {
@apply bg-accent-soft text-accent-soft-foreground;
}
}
.hv-date-input-group__prefix,
.hv-date-input-group__suffix {
@apply pointer-events-none shrink-0 text-field-placeholder flex items-center;
}
}
```
### TimeFieldGroup CSS 类
- `.hv-date-input-group` – 根容器样式
- `.hv-date-input-group__input` – 输入包裹层样式
- `.hv-date-input-group__segment` – 单个时间段位样式
- `.hv-date-input-group__prefix` – 前缀元素样式
- `.hv-date-input-group__suffix` – 后缀元素样式
### TimeFieldGroup 交互状态
- **悬停**:`:hover` 或 `[data-hovered="true"]`
- **焦点在内**:`[data-focus-within="true"]` 或 `:focus-within`
- **无效**:`[data-invalid="true"]`(同时与 `aria-invalid` 同步)
- **禁用**:`[data-disabled="true"]` 或 `[aria-disabled="true"]`
- **段位聚焦**:段位上的 `:focus` 或 `[data-focused="true"]`
- **段位占位符**:段位上的 `[data-placeholder="true"]`
## 相关组件
[DateField](/components/date-field) · [Calendar](/components/calendar)
## Vue 兼容说明
- Root 使用 `TimeField` / `TimeFieldRoot`;输入六部件以具名导出提供,并与 DateInputGroup 部件共用实现。`TimeFieldInputContainer` 用于组合输入容器。
- `modelValue`(`v-model`)优先于 `value`,包括显式 `null` / `undefined`;未传受控属性时读取 `defaultValue`。`update:modelValue` / `change` 发送值副本或 `null`。父级拒绝后恢复已接受值,保持分段 DOM 和焦点。
- `TimeValue = Time | CalendarDateTime | ZonedDateTime` 从包根导出;类型构造和解析使用 `@internationalized/date`。编辑时间保留日期、日历、时区及未显示的精度,原生提交完整 `toString()`。min/max 只比较本地时分秒,不比较日期或 UTC 时刻。
- `locale` / `dir` 默认读取 ConfigProvider(否则 en-US / ltr);可显式覆盖。`form` 支持外部表单,`autoComplete` 默认 off;`disabled` 是 isDisabled 的原生别名。Root 暴露 `element` / `focus()`。
- React `render` 改为 `as` 和原生 attrs;children render prop 改默认作用域插槽。class/style 函数不直接移植,使用插槽状态和 Vue 绑定。没有声明继承全部 RAC props;Reka 的 step/stepSnapping 不作为额外公共 API。
- Group 支持 `variant`、`fullWidth`、`as`;Input、InputContainer、Segment、Prefix、Suffix 支持 `as` 和原生 attrs,Segment 还要求 `segment`。Input 的视觉变体由 Group 设置。取消按键需在实际 Segment 上使用 `@keydown.prevent`(可按需 stop);Root 的冒泡监听晚于分段编辑,不能撤销已经完成的子处理。
- 表单示例在模拟提交后显示实际提交值并清空;替代上游控制台反馈,保留 1500ms 加载流程并在卸载时清理计时器。
- 当前仅支持浏览器客户端。未开展完整系统 IME、读屏、真机或逐像素自动对比专项。
Enter 在实际 Segment 上触发所属原生表单的 `requestSubmit()`(支持外部 form),遵守原生约束校验和 `@keydown.prevent`。blur 不重复发送已经接受的值。
+19
View File
@@ -0,0 +1,19 @@
<script setup lang="ts">
import {
TimeField,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
Label,
} from "@heroui-vue/components";
</script>
<template>
<TimeField class="w-[256px]" name="time">
<Label>时间</Label>
<TimeFieldGroup>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
</TimeFieldGroup>
</TimeField>
</template>
+38
View File
@@ -0,0 +1,38 @@
<script setup lang="ts">
import {
TimeField,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
Label,
Description,
Button,
} from "@heroui-vue/components";
import { shallowRef } from "vue";
import { Time, getLocalTimeZone, now } from "@internationalized/date";
import type { TimeValue } from "@heroui-vue/components";
const value = shallowRef<TimeValue | null>(null);
function setCurrent() {
const current = now(getLocalTimeZone());
value.value = new Time(current.hour, current.minute, current.second);
}
</script>
<template>
<div class="flex flex-col gap-4">
<TimeField class="w-[256px]" name="time" v-model="value">
<Label>时间</Label>
<TimeFieldGroup>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
</TimeFieldGroup>
<Description>
当前值:{{ value ? value.toString() : "(空)" }}
</Description>
</TimeField>
<div class="flex gap-2">
<Button variant="tertiary" @click="setCurrent">设为当前时间</Button>
<Button variant="tertiary" @click="value = null">清空</Button>
</div>
</div>
</template>
@@ -0,0 +1,23 @@
<script setup lang="ts">
import {
TimeField,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
Label,
Description,
} from "@heroui-vue/components";
</script>
<template>
<TimeField class="w-full max-w-48 gap-1.5" name="reminder">
<Label class="font-medium text-foreground">提醒时间</Label>
<Description>每日签到通知。</Description>
<TimeFieldGroup
class="rounded-xl border border-border/80 bg-surface px-2 py-1 shadow-sm ring-1 ring-accent/5 focus-within:border-accent/25 focus-within:ring-2 focus-within:ring-accent/15"
>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment class="text-foreground" :segment="segment" />
</TimeFieldInput>
</TimeFieldGroup>
</TimeField>
</template>
+39
View File
@@ -0,0 +1,39 @@
<script setup lang="ts">
import {
TimeField,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
Label,
Description,
} from "@heroui-vue/components";
import { Time, getLocalTimeZone, now } from "@internationalized/date";
const currentTime = now(getLocalTimeZone());
const timeValue = new Time(
currentTime.hour,
currentTime.minute,
currentTime.second,
);
</script>
<template>
<div class="flex flex-col gap-4">
<TimeField is-disabled class="w-[256px]" name="time" :value="timeValue">
<Label>时间</Label>
<TimeFieldGroup>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
</TimeFieldGroup>
<Description>此时间字段已禁用</Description>
</TimeField>
<TimeField is-disabled class="w-[256px]" name="time-empty">
<Label>时间</Label>
<TimeFieldGroup>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
</TimeFieldGroup>
<Description>此时间字段已禁用</Description>
</TimeField>
</div>
</template>
@@ -0,0 +1,85 @@
<script setup lang="ts">
import {
TimeField,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
TimeFieldPrefix,
Label,
Description,
FieldError,
Button,
Form,
} from "@heroui-vue/components";
import { IconClock } from "@tabler/icons-vue";
import { computed, shallowRef } from "vue";
import { parseTime, Time } from "@internationalized/date";
import type { TimeValue } from "@heroui-vue/components";
const value = shallowRef<TimeValue | null>(null);
const minTime = parseTime("09:00");
const maxTime = parseTime("17:00");
const isInvalid = computed(() => {
if (!value.value) return false;
const time = new Time(
value.value.hour,
value.value.minute,
value.value.second,
value.value.millisecond,
);
return time.compare(minTime) < 0 || time.compare(maxTime) > 0;
});
import { onBeforeUnmount } from "vue";
const isSubmitting = shallowRef(false);
const submitted = shallowRef("");
let timer: ReturnType<typeof setTimeout> | undefined;
function submit() {
if (!value.value || isInvalid.value || isSubmitting.value) return;
const payload = value.value.toString();
isSubmitting.value = true;
timer = setTimeout(() => {
submitted.value = payload;
value.value = null;
isSubmitting.value = false;
}, 1500);
}
onBeforeUnmount(() => clearTimeout(timer));
</script>
<template>
<Form class="flex w-[280px] flex-col gap-4" @submit.prevent="submit">
<TimeField
is-required
class="w-full"
name="time"
v-model="value"
:is-invalid="isInvalid"
:min-value="minTime"
:max-value="maxTime"
>
<Label>预约时间</Label>
<TimeFieldGroup>
<TimeFieldPrefix>
<IconClock class="size-4 text-muted" />
</TimeFieldPrefix>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
</TimeFieldGroup>
<FieldError v-if="isInvalid">
时间须在上午 9:00 至下午 5:00 之间
</FieldError>
<Description v-else>输入上午 9:00 至下午 5:00 之间的时间</Description>
</TimeField>
<Button
class="w-full"
:is-disabled="!value || isInvalid"
:is-pending="isSubmitting"
type="submit"
variant="primary"
>
{{ isSubmitting ? "提交中…" : "提交" }}
</Button>
<output v-if="submitted" class="text-sm text-muted">
已提交:{{ submitted }}
</output>
</Form>
</template>
+38
View File
@@ -0,0 +1,38 @@
<script setup lang="ts">
import {
TimeField,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
TimeFieldPrefix,
TimeFieldSuffix,
Label,
} from "@heroui-vue/components";
import { IconClock, IconChevronDown } from "@tabler/icons-vue";
</script>
<template>
<div class="w-[400px] space-y-4">
<TimeField full-width name="time">
<Label>时间</Label>
<TimeFieldGroup full-width>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
</TimeFieldGroup>
</TimeField>
<TimeField full-width name="time-icons">
<Label>时间</Label>
<TimeFieldGroup full-width>
<TimeFieldPrefix>
<IconClock class="size-4 text-muted" />
</TimeFieldPrefix>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
<TimeFieldSuffix>
<IconChevronDown class="size-4 text-muted" />
</TimeFieldSuffix>
</TimeFieldGroup>
</TimeField>
</div>
</template>
+32
View File
@@ -0,0 +1,32 @@
<script setup lang="ts">
import {
TimeField,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
Label,
FieldError,
} from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-4">
<TimeField is-invalid is-required class="w-[256px]" name="time">
<Label>时间</Label>
<TimeFieldGroup>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
</TimeFieldGroup>
<FieldError>请输入有效时间</FieldError>
</TimeField>
<TimeField is-invalid class="w-[256px]" name="invalid-time">
<Label>时间</Label>
<TimeFieldGroup>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
</TimeFieldGroup>
<FieldError>时间须在工作时间内</FieldError>
</TimeField>
</div>
</template>
+38
View File
@@ -0,0 +1,38 @@
<script setup lang="ts">
import {
TimeField,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
TimeFieldPrefix,
Label,
Description,
Surface,
} from "@heroui-vue/components";
import { IconClock } from "@tabler/icons-vue";
</script>
<template>
<Surface class="flex w-full max-w-sm flex-col gap-4 rounded-3xl p-6">
<TimeField class="w-full" name="time">
<Label>时间</Label>
<TimeFieldGroup variant="secondary">
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
</TimeFieldGroup>
<Description>输入时间</Description>
</TimeField>
<TimeField class="w-full" name="time-2">
<Label>预约时间</Label>
<TimeFieldGroup variant="secondary">
<TimeFieldPrefix>
<IconClock class="size-4 text-muted" />
</TimeFieldPrefix>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
</TimeFieldGroup>
<Description>输入预约时间</Description>
</TimeField>
</Surface>
</template>
@@ -0,0 +1,19 @@
<script setup lang="ts">
import {
TimeField,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
Label,
} from "@heroui-vue/components";
</script>
<template>
<TimeField as="div" data-custom="foo" class="w-[256px]" name="time">
<Label>时间</Label>
<TimeFieldGroup>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
</TimeFieldGroup>
</TimeField>
</template>
+31
View File
@@ -0,0 +1,31 @@
<script setup lang="ts">
import {
TimeField,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
Label,
Description,
} from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-4">
<TimeField is-required class="w-[256px]" name="time">
<Label>时间</Label>
<TimeFieldGroup>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
</TimeFieldGroup>
</TimeField>
<TimeField is-required class="w-[256px]" name="appointment-time">
<Label>预约时间</Label>
<TimeFieldGroup>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
</TimeFieldGroup>
<Description>必填项</Description>
</TimeField>
</div>
</template>
@@ -0,0 +1,32 @@
<script setup lang="ts">
import {
TimeField,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
Label,
Description,
} from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-4">
<TimeField class="w-[256px]" name="time">
<Label>开始时间</Label>
<TimeFieldGroup>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
</TimeFieldGroup>
<Description>输入开始时间</Description>
</TimeField>
<TimeField class="w-[256px]" name="end-time">
<Label>结束时间</Label>
<TimeFieldGroup>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
</TimeFieldGroup>
<Description>输入结束时间</Description>
</TimeField>
</div>
</template>
@@ -0,0 +1,28 @@
<script setup lang="ts">
import {
TimeField,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
TimeFieldPrefix,
TimeFieldSuffix,
Label,
Description,
} from "@heroui-vue/components";
import { IconClock, IconChevronDown } from "@tabler/icons-vue";
</script>
<template>
<TimeField class="w-[256px]" name="time">
<Label>时间</Label>
<TimeFieldGroup>
<TimeFieldPrefix><IconClock class="size-4 text-muted" /></TimeFieldPrefix>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
<TimeFieldSuffix>
<IconChevronDown class="size-4 text-muted" />
</TimeFieldSuffix>
</TimeFieldGroup>
<Description>输入时间</Description>
</TimeField>
</template>
@@ -0,0 +1,22 @@
<script setup lang="ts">
import {
TimeField,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
TimeFieldPrefix,
Label,
} from "@heroui-vue/components";
import { IconClock } from "@tabler/icons-vue";
</script>
<template>
<TimeField class="w-[256px]" name="time">
<Label>时间</Label>
<TimeFieldGroup>
<TimeFieldPrefix><IconClock class="size-4 text-muted" /></TimeFieldPrefix>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
</TimeFieldGroup>
</TimeField>
</template>
@@ -0,0 +1,22 @@
<script setup lang="ts">
import {
TimeField,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
TimeFieldSuffix,
Label,
} from "@heroui-vue/components";
import { IconClock } from "@tabler/icons-vue";
</script>
<template>
<TimeField class="w-[256px]" name="time">
<Label>时间</Label>
<TimeFieldGroup>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
<TimeFieldSuffix><IconClock class="size-4 text-muted" /></TimeFieldSuffix>
</TimeFieldGroup>
</TimeField>
</template>
@@ -0,0 +1,51 @@
<script setup lang="ts">
import {
TimeField,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
Label,
Description,
FieldError,
} from "@heroui-vue/components";
import { computed, shallowRef } from "vue";
import { parseTime, Time } from "@internationalized/date";
import type { TimeValue } from "@heroui-vue/components";
const value = shallowRef<TimeValue | null>(null);
const minTime = parseTime("09:00");
const maxTime = parseTime("17:00");
const isInvalid = computed(() => {
if (!value.value) return false;
const time = new Time(
value.value.hour,
value.value.minute,
value.value.second,
value.value.millisecond,
);
return time.compare(minTime) < 0 || time.compare(maxTime) > 0;
});
</script>
<template>
<div class="flex flex-col gap-4">
<TimeField
is-required
class="w-[256px]"
name="time"
v-model="value"
:is-invalid="isInvalid"
:min-value="minTime"
:max-value="maxTime"
>
<Label>时间</Label>
<TimeFieldGroup>
<TimeFieldInput v-slot="{ segment }">
<TimeFieldSegment :segment="segment" />
</TimeFieldInput>
</TimeFieldGroup>
<FieldError v-if="isInvalid">
时间须在上午 9:00 至下午 5:00 之间
</FieldError>
<Description v-else>输入上午 9:00 至下午 5:00 之间的时间</Description>
</TimeField>
</div>
</template>
+1 -1
View File
@@ -33,7 +33,7 @@
| drawer | 验证中(M34) | 11 部件;四方向拖动关闭(30%/0.5px/ms);9/9 基线例;Content/Dialog 职责分离 |
| progress-bar | 验证中(M18) | ProgressBar/Output/Track/Fill;7/7 基线例;确定/未知进度、min/max/formatOptions/valueLabel;custom-value 的 NumberField/Select 为原生临时控件 |
| progress-circle | 验证中(M19) | ProgressCircle/Track/TrackCircle/FillCircle;7/7 基线例;圆环几何可覆盖;与 ProgressBar 共用取值语义 |
| time-field | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| time-field | 已迁移(客户端) | TimeField/Root及六个共享输入部件;15/15基线例;Time/CalendarDateTime/ZonedDateTime、完整精度、受控拒绝、键盘/Enter、校验/提交/reset;框架差异见 TIME-FIELD 结果。 |
| disclosure | 验证中(M21) | Disclosure/Heading/Trigger/Content/Body/Indicator;3/3 基线例;v-model:expanded;asChild 触发;高度动画映射测量变量 |
| disclosure-group | 验证中(M22) | DisclosureGroup + useDisclosureGroupNavigation;3/3 基线例;展开键为数组(string 或 number);单选替换/多选增量 |
| error-message | 已迁移(有已知差异) | ErrorMessage 单部件;2/2 基线例;复用字段错误 id 与样式变量,`slot="errorMessage"` 仅为 DOM 标记,不做校验也不改 aria-invalid;见 B03 报告 |
+9 -1
View File
@@ -13,10 +13,18 @@
## 日期与颜色的当前边界
DateField/Calendar/CalendarYearPicker已公开;RangeCalendar只有私有内核,TimeField/DatePicker/DateRangePicker尚未迁移。保留DateValue、历法/时区与精度边界,不强制JS Date;本地化整日期粘贴、13月/era编辑等尚有待办。见 [日期决策](decisions/date-calendar-foundation.md)、[DateField文档](../apps/docs/components/date-field.md)、[Calendar文档](../apps/docs/components/calendar.md)。
DateField/TimeField/Calendar/CalendarYearPicker已公开;RangeCalendar只有私有内核,DatePicker/DateRangePicker尚未迁移。保留DateValue、历法/时区与精度边界,不强制JS Date;本地化整日期粘贴、13月/era编辑等尚有待办。见 [日期决策](decisions/date-calendar-foundation.md)、[DateField文档](../apps/docs/components/date-field.md)、[Calendar文档](../apps/docs/components/calendar.md)。
颜色value/model与Area/Slider/Field/InputGroup/Picker私有协议已有实现,公共Color/parseColor及组件家族仍待任务验收。不能把内核/夹具通过写成公共完成。共享owner、归一化通道、接受值与草稿保持同一状态源。见 [颜色决策](decisions/color-foundation.md);下一项只有用户选定后才按 [COLOR-SWATCH卡](tasks/COLOR-SWATCH.md) 执行。
## 当前不投入
SSR/水合/Nuxt集成不支持;逐像素自动对比、完整读屏矩阵、真机矩阵暂不投入,不开发相应工程或设为每次迁移门槛。仍保留固定基线的样式/布局/API/主题一致性,重点浏览器操作、键盘与基础可访问性检查。具体统一约定见根AGENTS.md。
## TIME-FIELD(2026-10-26)
TimeField 复用 DateInputGroup 六部件和现有接受值/字段/Form 协议;私有分段桥选择 Reka TimeField 底座。公开范围与 15 个固定源示例见 [组件文档](../apps/docs/components/time-field.md),验证见 [结果](tasks/results/TIME-FIELD.md)。
Time/CalendarDateTime/ZonedDateTime 保留值类型、日期、历法、zone 与未显示的精度。底座空模型事件会转换为 Time 并遗漏毫秒,适配层只将可编辑字段写回原值/placeholder,单一命名输入提交完整 ISO。min/max 比较本地时分秒(含毫秒),与底座按日期比较区分。Enter 通过共享字段的原生 form 触发 requestSubmit;真正 Segment 的取消事件先于底座执行。12 小时 hour 与 dayPeriod 的 ARIA 数值范围由时间适配层校正,时制/粒度/时区可见性更新后恢复到有效分段焦点。
React render 改 as/attrs,children 函数改作用域插槽;class/style 使用 Vue 绑定,Input 的 variant 放在 Group。没有扩展 Reka step API,没有声称继承全部 RAC props。整段本地化时间粘贴、系统 IME 与完整读屏/真机未验收;原生 ISO 输入边界有回归,不能等同于本地化分段粘贴。
+5 -5
View File
@@ -8,21 +8,21 @@
- 展示、按钮、导航、展开、反馈等主要家族已有公共组件与文档。
- 字段/Form、Checkbox/Radio、数值/Slider/OTP、弹层/菜单、集合/ListBox/Select、ComboBox/Autocomplete、Tag、Toast/Table已集成。
- DateField、Calendar与CalendarYearPicker已有公共组件;范围日历内核已验证,公共RangeCalendar尚未迁移。
- DateField、TimeField、Calendar与CalendarYearPicker已有公共组件;范围日历内核已验证,公共RangeCalendar尚未迁移。
- ColorSwatch/ColorSwatchRoot及Color/parseColor公共子集已公开;Area、Slider、Field/InputGroup、Picker组合协议仍有私有实现和回归夹具,尚未作为完整公共颜色家族发布。
- 兼容矩阵目前83条(包含子部件与基础设施),文档有64个组件页面。矩阵中的“验证中”保留其原有限制,不升级为完整兼容。
- 兼容矩阵目前83条(包含子部件与基础设施),文档有65个组件页面。矩阵中的“验证中”保留其原有限制,不升级为完整兼容。
## 尚未完成的公共家族
RangeCalendar、TimeField、DatePicker、DateRangePicker,以及ColorArea、ColorField、ColorSlider、ColorSwatchPicker、ColorPicker,共9项;已有私有内核不等于公共迁移完成。ColorInputGroup仍为私有协议;Color/parseColor公共边界已随COLOR-SWATCH验收。
RangeCalendar、DatePicker、DateRangePicker,以及ColorArea、ColorField、ColorSlider、ColorSwatchPicker、ColorPicker,共8项;已有私有内核不等于公共迁移完成。ColorInputGroup仍为私有协议;Color/parseColor公共边界已随COLOR-SWATCH验收。
当前可启动任务卡为 [TIME-FIELD](tasks/TIME-FIELD.md);COLOR-SWATCH 已交付到任务分支,结果见 [COLOR-SWATCH](tasks/results/COLOR-SWATCH.md)。一次选择一项,不自动按旧提示词并行推进;其余任务在前置合入后创建卡。
TIME-FIELD 已完成公共迁移和客户端验收,见 [结果](tasks/results/TIME-FIELD.md);COLOR-SWATCH 见 [结果](tasks/results/COLOR-SWATCH.md)。后续由用户选择一项,在实际前置具备后创建任务卡;不自动并行推进。
## 当前工程边界
唯一Vue工作目录heroui-vue,一任务一分支、会话串行。b01/b02/b03已删除并解除Git登记;core内容已整合,是否保留该目录不影响运行。开发默认文档5173,playground按实际脚本;服务只在任务需要时启动,结束按用户要求停止。
已完成的单目录整合见 [结果](tasks/results/WORKSPACE-CONSOLIDATION.md)。当前客户端回归86文件/1266项;SSR历史用例已删除。逐像素自动对比、完整读屏矩阵、真机矩阵及Nuxt集成暂不投入。维护清理的实际结果见 [MAINTENANCE](tasks/results/MAINTENANCE.md)。
已完成的单目录整合见 [结果](tasks/results/WORKSPACE-CONSOLIDATION.md)。当前客户端全量回归91文件/1322项通过;本轮TimeField新增2文件/27项,日期相关定向验收134项通过,见任务结果;SSR历史用例已删除。逐像素自动对比、完整读屏矩阵、真机矩阵及Nuxt集成暂不投入。维护清理的实际结果见 [MAINTENANCE](tasks/results/MAINTENANCE.md)。
## 按需入口
+7 -5
View File
@@ -1,8 +1,10 @@
# 当前工作区交接
- 任务:无进行中任务;COLOR-SWATCH 已通过集成人复核,动态移除子ID的尾部问题已补齐。
- 工作区/分支:heroui-vue / feat/color-swatch-public(起点 60af6ee,未合 main、未 push)。
- 结果入口:docs/tasks/results/COLOR-SWATCH.md(含 CS-1/CS-2 返修记录)。
- 下一步:由用户选择新任务;不自动开始下一任务。
- 任务:无进行中任务;TIME-FIELD 已完成实施与自测。
- 工作区/分支:heroui-vue / feat/time-field(未合 main、未 push)。
- 起点:d74ad1b7118ef5ffa9938a83d1f133f09593c263。
- 结果入口:docs/tasks/results/TIME-FIELD.md。
- 预览:本任务启动的文档站5173保留,/components/time-field。
- 下一步:由用户选择新任务;不自动开始下一项。
这里只记录当前占用和接续入口,不重复任务状态表。单目录串行;新会话先核对git状态,有进行中任务时不切分支覆盖。支持范围统一见AGENTS.md。
单目录串行;新会话先核对git状态与结果文件。支持范围见AGENTS.md。
+4 -3
View File
@@ -2,7 +2,7 @@
{
"base": "b129f79366e6a526e047cec917753e1434298fa3",
"upstream": "ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960",
"status": "ready",
"status": "completed",
"requires": [
"packages/vue/src/components/date-field/DateField.vue",
"packages/vue/src/components/date/model.ts",
@@ -15,7 +15,8 @@
"checks": [
"pnpm exec vitest run tests/time-field.test.ts tests/time-field-demos.test.ts tests/date-field.test.ts tests/date-model.test.ts tests/date-value.test.ts",
"pnpm typecheck",
"pnpm build:docs"
"pnpm build:docs",
"node scripts/check-package.mjs time-field date-field"
]
}
-->
@@ -51,6 +52,6 @@ TimeField公开家族完整可用,不再交一批仅私有夹具的“完成
交付 docs/tasks/results/TIME-FIELD.md,含精确SHA、源契约对照、验证及具体差异/阻断。正常完成提交任务分支,不合main、不推送;用户明确授权集成则按其指令执行。新会话接续只需该卡和结果文件,不依赖旧聊天。
浏览器入口:确认5186空闲后执行 `HEROUI_DOCS_PORT=5186 pnpm dev`,核对日志URL和当前工作区;端口已占用则另选空闲端口,不停别人的服务。
浏览器入口:确认5173空闲后执行 `pnpm dev`,核对日志URL和当前工作区;端口已占用则另选空闲端口,不停别人的服务。
单目录约定:在heroui-vue先读ACTIVE.md和git状态,前一任务交接后再新建任务分支;不另建clone/worktree,不与另一会话同时改该目录。文档默认使用5173;卡中518x仅为显式另选端口的例子,不要求同时保留多个服务。
+46
View File
@@ -0,0 +1,46 @@
# TIME-FIELD 交付 / 接续
- 分支:`feat/time-field`。
- 起点:`d74ad1b7118ef5ffa9938a83d1f133f09593c263`,包含 COLOR-SWATCH 复核修复及 TIME-FIELD 任务卡;未切回旧 main。
- 实施 SHA:以交付记录中的准确实施提交为准(提交后补入)。
- 固定源:HeroUI 3.2.6 / `ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960`。
- 仅客户端;不合 main、不 push。没有新增依赖或修改上游、node_modules。
## 改动与源契约
公开 `TimeField` / `TimeFieldRoot`,以及 Group、Input、InputContainer、Segment、Prefix、Suffix 六部件;六部件与已有 DateInputGroup 为相同实现。提供 Props 类型、`TimeValue`、`TimeFieldRenderProps`、`timeFieldVariants` 和源 CSS。Root 使用 `v-model`,保留 value/defaultValue、默认 minute、12/24 小时、locale/dir、时区显示、required/disabled/readOnly、min/max/validate、原生 name/form、ref focus 和默认作用域状态。
共享日期接受值协议扩展为 Time,不再新增一套字段、ID、校验、reset 或原生表单所有者。私有 DateSegments 桥选择 DateField/TimeField 的底座和上下文;原有 DateField 回归保留。Reka 空模型完成编辑会丢失占位模型类型和毫秒,TimeField 只把可编辑的时间字段写回原类,保留日期、历法、zone、秒/毫秒等未显示精度。最终只有一个命名值输入,提交完整 ISO;min/max 比较本地时间而非日期或 UTC 时刻。
源中文正文与 `demos/cn/time-field` 的 **15/15** 例依次迁移:basic、with-prefix-icon、with-suffix-icon、with-prefix-and-suffix、on-surface、with-description、required、disabled、full-width、invalid、controlled、form-example、with-validation、render-function、custom-styles。预览/复制/高亮共用 SFC,图标为 Tabler 官方组件。CSS/tv 保留源数值和 Apache-2.0 来源,类名加 hv 前缀。
## 验证
| 场景 | 断言 / 可复现步骤 | 结果 |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 新增公共行为 | `pnpm exec vitest run tests/time-field.test.ts tests/time-field-demos.test.ts` | 23项行为 + 4项文档测试通过;包括15例无警告挂载、受控操作、校验和模拟提交 |
| 接受值与精度 | 同上,使用 Time、CalendarDateTime、ZonedDateTime,含 Persian calendar、秒/毫秒 | 完整 ISO、类/日期/历法/zone、显示粒度与提交精度分离;受控拒绝重复提案、空值完成、清空、外部更新均有断言 |
| 表单与字段 | required/min/max/custom/server error、Fieldset disabled、readonly、name/form、reset/取消reset、Enter | 单一提交值;错误关联和原生invalid焦点;外部form与受控reset保留父值;blur无重复change,Enter可被Segment取消 |
| 分段与焦点 | 12/24小时、provider locale、RTL、数字/方向/Backspace、动态粒度/时区、IME组合键 | 焦点恢复到现存分段;hour/dayPeriod ARIA值符合范围;前导零只控制时间hour,不误删minute/second零 |
| 日期相关回归 | `pnpm exec vitest run tests/time-field.test.ts tests/time-field-demos.test.ts tests/date-field.test.ts tests/date-field-demos.test.ts tests/date-model.test.ts tests/date-value.test.ts tests/date-foundation.test.ts tests/calendar.test.ts tests/calendar-view.test.ts tests/range-calendar-foundation.test.ts` | 10文件/134项通过 |
| 全量客户端回归 | `pnpm test:unit` | 91文件/1322项通过,无SSR/水合/Nuxt专项 |
| 工作区类型 | `pnpm typecheck` | 通过 |
| 文档构建 | `pnpm build:docs` | 通过;保留大chunk提示。文档自身静态渲染不作为组件SSR验收 |
| 独立最终产物 | `node scripts/check-package.mjs time-field date-field` | tarball独立安装、ESM/CSS/别名/variants、strict NodeNext/bundler正反类型通过;最终消费者为 `/private/var/folders/ry/cj1sb3mx3wnfs8ttkxkjcbbc0000gn/T/heroui-client-package-WLwboN` |
| 真实文档核心操作 | `pnpm dev`,打开 `http://127.0.0.1:5173/components/time-field`;受控例“设为当前时间”→hour Up→Right→清空 | 值随步进更新,焦点移到minute,清空恢复占位;秒保持 |
| 真实表单操作 | 预约表单hour输入9,minute输入3、0,按Enter;也检查提交按钮路径 | 出现“提交中…”,1500ms后显示“已提交:09:30:00”,字段清空;最终重新加载后同一路径控制台无新增warn/error |
| 视觉与基础可访问性 | 1280px视口,浅/深主题与实际分段焦点;读取真实表格几何 | API表宽696px,无整页横向溢出;标签/说明/错误ID、spinbutton属性有DOM断言。未作逐像素或完整读屏结论 |
首次 offline 独立安装因缺 TypeScript tarball 失败,允许联网补齐后成功;没有用源码 alias 或失败安装替代验收。开发期间修改注入模块触发过 HMR 临时 Symbol 不匹配,完整重新加载最终代码后复验无新增错误;不把旧热更新错误误报为最终页面错误。
## 差异与限制
- React 复合对象改 Vue 具名导出;children 函数改作用域插槽,render 改 as/attrs;class/style函数使用Vue状态绑定。Input视觉variant放Group,没有声称继承全部RAC props。
- TimeFieldRenderProps 增加值/validationErrors便于Vue插槽读取;共享表单已有form/disabled别名继续支持。不新增底座step/stepSnapping等API。
- 消费者取消操作应在实际Segment监听;Root冒泡事件晚于子分段处理,不能撤销已经发生的编辑。
- 整段本地化时间粘贴、系统IME、完整读屏/真机没有验收;原生ISO输入边界与组合键已有测试,不等同于系统IME专项完成。
- SSR/水合/Nuxt服务端不支持;逐像素自动对比、完整读屏与真机矩阵不投入。
本任务无未完成阻断。后续迁移须由用户选择,不自动启动日期或颜色家族。
截图可临时查看 `/private/tmp/time-field-light.png` / `/private/tmp/time-field-dark.png`;复现步骤与断言保存在本仓库,不依赖截图继续工作。文档站5173由本任务启动,保留供用户预览。
+8
View File
@@ -252,3 +252,11 @@ CSS/tv 仅加 `hv-` 前缀与 Vue 状态适配,保留 Apache-2.0 来源。TagR
CSS/tv 仅加 `hv-` 前缀与 Apache-2.0 来源;`circle/square`、`xs/sm/md/lg/xl` 默认值与类名保持基线。组件复用已有 `components/color/value.ts` 的不可变 `Color`/`parseColor`,并从包根公开实际支持的 `Color`、`ColorValue`、`ColorChannel`、`ColorSpace`、`ColorInput` 子集;没有移植 React Stately 全量 `Color` 辅助方法、色名表或 React Aria 的 React 状态。`ColorSwatch` 省略 `color` 时读取最近的共享颜色 owner,显式 `color` 覆盖它;显式 `null`/空字符串清空继承。
上游 `render` 映射为 `as`/`asChild` 与原生 attrs;`style` render prop 的函数形式在 Vue 模板中改为 `styleFn`(Vue 编译器会规整保留的 `style` 函数值),普通样式仍用 `style`。默认作用域插槽接收 `{ color }`。未迁移 ColorSwatchPicker 的 `ColorSwatchContext`(该家族不在本任务范围),也没有运行时依赖相邻 React 仓库。
## TIME-FIELD(2026-10-26)
固定 HeroUI 3.2.6 / `ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960`:`packages/react/src/components/time-field/{index.ts,time-field.tsx}`、共享 date-input-group、`packages/styles/components/time-field.css` 与 `packages/styles/src/components/time-field/time-field.styles.ts`,中文 `(date-and-time)/time-field.mdx` 和 `demos/cn/time-field` 全部15例。
TimeField CSS/variants 仅加 hv- 前缀,保留 Apache-2.0 来源;DateInputGroup 沿用已移植样式,未重复复制。Vue 使用已安装 Reka UI 2.11.0 的公开 TimeFieldRoot/Input/context 和 @internationalized/date 3.12.4,不修改依赖或运行 React。输入六部件仍复用 DateInputGroup,只增加私有底座选择;共享接受值协议拓展为不可变 Time 值,不增加另一套表单/校验/重置状态。默认 TimeValue 子集、精度与 ARIA 适配见组件说明。
演示图标以 Tabler 官方 IconClock/IconChevronDown 替代源 Gravity 图标。render 示例改 as/原生 attrs;表单示例保留1500ms模拟提交,增加实际提交值反馈并清理计时器。无新增依赖,构建不依赖相邻 React 仓库。
+12
View File
@@ -12,3 +12,15 @@
如何选择日常/集成/真实浏览器/独立包验证见 [tests/README.md](../tests/README.md)。架构决策在docs/decisions;尚未完成的公共能力见 [当前进度](status.md) 和 [兼容矩阵](compatibility.md)。
2026-10-20至25的完整流水记录保留在Git:`git show 2af7ea1:docs/verification.md`。更多旧材料查询见 [历史入口](history.md)。旧测试数、端口、目录和“下一步”不作为新任务指令。
## TIME-FIELD(2026-10-26,客户端)
公开 TimeField/Root、六个共享 DateInputGroup 部件、timeFieldVariants 与 TimeValue/TimeFieldRenderProps。固定源15例全部迁移,预览/复制/高亮共用SFC。TimeField新增23项行为测试和4项文档测试。
- `pnpm test:unit`:91文件/1322项客户端回归通过。
- TimeField、DateField/value/model/foundation、Calendar/view、RangeCalendar foundation定向10文件/134项通过。
- `pnpm typecheck`、`pnpm build:docs`:通过。文档构建保留已有大chunk提示,不代表组件SSR验收。
- `node scripts/check-package.mjs time-field date-field`:最终tarball独立安装、ESM导出/CSS/变体及strict NodeNext/bundler类型正反例通过。首次offline因缓存缺TypeScript tarball失败,联网重跑成功,没有把安装失败记为通过。
- 真实文档5173:受控设置/步进/清空、方向键焦点、9:30键盘输入、Enter及按钮提交、1500ms加载/结果/清空、浅深主题已检查。1280px视口API表宽696px,无整页横向溢出。更改注入模块的热更新期间曾产生临时Symbol不匹配,最终完整重新加载及操作后控制台无新增warn/error。
未开展SSR/水合/Nuxt服务端、逐像素自动对比、完整读屏/真机矩阵、整段本地化时间粘贴或系统IME专项。差异及可复现步骤见 [结果](tasks/results/TIME-FIELD.md)。
+21
View File
@@ -0,0 +1,21 @@
/* Source: HeroUI 3.2.6 / ce90ea3; Apache-2.0, see third-party/HEROUI-LICENSE. */
/* Time field styles */
.hv-time-field {
@apply flex flex-col gap-1;
&[data-invalid="true"],
&[aria-invalid="true"] {
[data-slot="description"] {
@apply hidden;
}
}
[data-slot="label"] {
@apply w-fit;
}
}
/* Full width modifier */
.hv-time-field--full-width {
@apply w-full;
}
+1
View File
@@ -163,6 +163,7 @@
@import "./components/date-input-group.css" layer(components);
@import "./components/date-field.css" layer(components);
@import "./components/time-field.css" layer(components);
@import "./components/calendar.css" layer(components);
/* RangeCalendar styling staged for the private range interaction fixture. */
+8
View File
@@ -1805,3 +1805,11 @@ export const colorSwatchVariants = tv({
});
export type ColorSwatchVariants = VariantProps<typeof colorSwatchVariants>;
/** HeroUI 3.2.6 / ce90ea3, Apache-2.0; hv namespace only. */
export const timeFieldVariants = tv({
base: "hv-time-field",
defaultVariants: { fullWidth: false },
variants: { fullWidth: { false: "", true: "hv-time-field--full-width" } },
});
export type TimeFieldVariants = VariantProps<typeof timeFieldVariants>;
@@ -100,22 +100,23 @@ export default defineComponent({
setup(props, { attrs, slots, emit, expose }) {
const config = useConfig();
const instance = getCurrentInstance()!;
const accepted = useAcceptedDateValue({
value: () =>
["modelValue", "model-value"].some((key) =>
Object.hasOwn(instance.vnode.props ?? {}, key),
)
? props.modelValue
: props.value,
defaultValue: () => props.defaultValue,
onChange: (value) => {
field.edit();
emit("update:modelValue", value);
emit("change", value);
},
disabled: () => field.field.disabled.value,
readOnly: () => field.field.readOnly.value,
});
const accepted: ReturnType<typeof useAcceptedDateValue<DateValue>> =
useAcceptedDateValue<DateValue>({
value: () =>
["modelValue", "model-value"].some((key) =>
Object.hasOwn(instance.vnode.props ?? {}, key),
)
? props.modelValue
: props.value,
defaultValue: () => props.defaultValue,
onChange: (value) => {
field.edit();
emit("update:modelValue", value);
emit("change", value);
},
disabled: () => field.field.disabled.value,
readOnly: () => field.field.readOnly.value,
});
const field = useChoiceField(props, attrs, {
kind: "group",
value: accepted.value,
@@ -7,9 +7,10 @@ import {
type SlotsType,
type VNodeChild,
} from "vue";
import { injectDateFieldRootContext } from "reka-ui";
import { dateInputGroupVariants } from "@heroui-vue/styles";
import {
dateSegmentBaseKey,
dateGroupKey,
dateSegmentsKey,
useDateField,
@@ -25,7 +26,8 @@ export default defineComponent({
}>,
setup(props, { attrs, slots }) {
const field = useDateField();
const base = injectDateFieldRootContext();
const adapter = inject(dateSegmentBaseKey)!;
const base = adapter.base;
const styles = inject(dateGroupKey, undefined);
const segments = inject(dateSegmentsKey)!;
return () =>
@@ -44,6 +46,7 @@ export default defineComponent({
let text = part.value;
if (
!isPlaceholder &&
(adapter.kind !== "time" || part.part === "hour") &&
["month", "day", "hour", "minute", "second"].includes(part.part) &&
/^\d+$/.test(text)
) {
@@ -1,8 +1,20 @@
<script lang="ts">
import { defineComponent, h, inject, type PropType } from "vue";
import { DateFieldInput, injectDateFieldRootContext } from "reka-ui";
import {
computed,
defineComponent,
h,
inject,
mergeProps,
type PropType,
} from "vue";
import { dateInputGroupVariants } from "@heroui-vue/styles";
import { dateGroupKey, useDateField, type DateSegment } from "./context";
import {
dateSegmentBaseKey,
dateGroupKey,
useDateField,
type DateSegment,
} from "./context";
import PrimitiveNode from "./PrimitiveNode";
import { mergeIds } from "../field/context";
export default defineComponent({
@@ -14,7 +26,16 @@ export default defineComponent({
},
setup(props, { attrs, slots, expose }) {
const field = useDateField();
const base = injectDateFieldRootContext();
const adapter = inject(dateSegmentBaseKey)!;
const base = adapter.base;
const hour = computed(() =>
"hour" in base.segmentValues.value ? base.segmentValues.value.hour : null,
);
const dayPeriod = computed(() =>
"dayPeriod" in base.segmentValues.value
? base.segmentValues.value.dayPeriod
: undefined,
);
const styles = inject(dateGroupKey, undefined);
let node: { element?: HTMLElement } | undefined;
expose({
@@ -25,7 +46,7 @@ export default defineComponent({
});
return () =>
h(
DateFieldInput,
adapter.input,
{ part: props.segment.part, asChild: true },
{
default: () =>
@@ -36,7 +57,22 @@ export default defineComponent({
node = value as typeof node;
},
as: props.as,
consumer: attrs,
consumer:
adapter.kind === "time"
? mergeProps(attrs, {
onKeydown: (event: KeyboardEvent) => {
if (
event.key !== "Enter" ||
event.isComposing ||
event.defaultPrevented ||
field.disabled.value
)
return;
event.preventDefault();
field.form?.()?.requestSubmit();
},
})
: attrs,
overrides: {
class: (styles?.value ?? dateInputGroupVariants()).segment(),
"data-slot": "date-input-group-segment",
@@ -63,6 +99,27 @@ export default defineComponent({
}).of(props.segment.part),
}
: {}),
...(adapter.kind === "time" && props.segment.part === "hour"
? {
"aria-valuemin": base.hourCycle === 12 ? 1 : 0,
"aria-valuemax": base.hourCycle === 12 ? 12 : 23,
"aria-valuenow": props.segment.isPlaceholder
? undefined
: base.hourCycle === 12
? hour.value! % 12 || 12
: hour.value,
"aria-valuetext": props.segment.text,
}
: {}),
...(adapter.kind === "time" &&
props.segment.part === "dayPeriod"
? {
"aria-valuemin": 0,
"aria-valuemax": 1,
"aria-valuenow": dayPeriod.value === "PM" ? 1 : 0,
"aria-valuetext": props.segment.text,
}
: {}),
...(props.segment.isPlaceholder
? {
"aria-valuenow": undefined,
@@ -1,8 +1,15 @@
import { computed, defineComponent, provide, type PropType } from "vue";
import type { DateFieldInputProps } from "reka-ui";
import { dateSegmentsKey } from "./context";
import {
DateFieldInput,
TimeFieldInput,
injectDateFieldRootContext,
injectTimeFieldRootContext,
type DateFieldInputProps,
} from "reka-ui";
import { dateSegmentsKey, dateSegmentBaseKey } from "./context";
export default defineComponent({
props: {
kind: { type: String, default: "date" },
segments: {
type: Array as PropType<
{ part: DateFieldInputProps["part"]; value: string }[]
@@ -11,6 +18,14 @@ export default defineComponent({
},
},
setup(props, { slots }) {
const isTime = props.kind === "time";
provide(dateSegmentBaseKey, {
base: isTime
? injectTimeFieldRootContext()!
: injectDateFieldRootContext()!,
input: isTime ? TimeFieldInput : DateFieldInput,
kind: isTime ? "time" : "date",
});
provide(
dateSegmentsKey,
computed(() => props.segments),
@@ -1,5 +1,10 @@
import { inject, type ComputedRef, type InjectionKey } from "vue";
import type { DateValue } from "@internationalized/date";
import {
inject,
type ComputedRef,
type InjectionKey,
type Component,
} from "vue";
import type { DateValue, Time } from "@internationalized/date";
import type { DateFieldInputProps } from "reka-ui";
import type { dateInputGroupVariants } from "@heroui-vue/styles";
export interface DateSegment {
@@ -11,11 +16,12 @@ export interface DateSegment {
isEditable: boolean;
}
export interface DateFieldContext {
value: ComputedRef<DateValue | null>;
value: ComputedRef<DateValue | Time | null>;
disabled: ComputedRef<boolean>;
readOnly: ComputedRef<boolean>;
required: ComputedRef<boolean>;
invalid: ComputedRef<boolean>;
form?: () => HTMLFormElement | null | undefined;
leadingZeros: () => boolean | undefined;
labelledBy: () => string | undefined;
describedBy: () => string | undefined;
@@ -28,10 +34,19 @@ export const dateGroupKey: InjectionKey<
> = Symbol("hv-date-group");
export function useDateField() {
const value = inject(dateFieldKey, undefined);
if (!value) throw new Error("Date input parts require a DateField root.");
if (!value)
throw new Error("Date input parts require a DateField or TimeField root.");
return value;
}
export const dateSegmentsKey: InjectionKey<
ComputedRef<{ part: DateFieldInputProps["part"]; value: string }[]>
> = Symbol("hv-date-segments");
export const dateSegmentBaseKey: InjectionKey<{
base: NonNullable<
ReturnType<typeof import("reka-ui").injectDateFieldRootContext>
>;
input: Component;
kind: "date" | "time";
}> = Symbol("hv-date-segment-base");
@@ -1,5 +1,6 @@
import { defineComponent, watch } from "vue";
import { defineComponent, inject, watch } from "vue";
import { injectDateFieldRootContext } from "reka-ui";
import { dateSegmentBaseKey } from "../date-field/context";
/** Reka does not watch equal primitive null values after a rejected edit.
* Clear its existing segment refs without replacing DOM, focus or IDs. */
@@ -7,7 +8,9 @@ export default defineComponent({
name: "EmptyDateBridge",
props: { revision: { type: Number, required: true } },
setup(props) {
const base = injectDateFieldRootContext();
const base =
inject(dateSegmentBaseKey, undefined)?.base ??
injectDateFieldRootContext()!;
watch(
() => props.revision,
() => {
+10 -8
View File
@@ -1,18 +1,20 @@
import { computed, nextTick, ref } from "vue";
import type { DateValue } from "@internationalized/date";
import type { DateValue, Time } from "@internationalized/date";
import { useChoiceValue } from "../choice/shared";
import { copyDateValue, sameDateValue } from "./value";
/** One accepted model, with a copied wire value to resynchronize editable
* Reka segments after a completed proposal. Partial drafts stay in the base. */
export function useAcceptedDateValue(options: {
value: () => DateValue | null | undefined;
defaultValue: () => DateValue | null | undefined;
onChange: (value: DateValue | null) => void;
export function useAcceptedDateValue<
T extends DateValue | Time = DateValue,
>(options: {
value: () => T | null | undefined;
defaultValue: () => T | null | undefined;
onChange: (value: T | null) => void;
disabled?: () => boolean;
readOnly?: () => boolean;
}) {
const model = useChoiceValue<DateValue | null | undefined>(
const model = useChoiceValue<T | null | undefined>(
() => copyDateValue(options.value()),
() => copyDateValue(options.defaultValue() ?? null),
["modelValue", "model-value", "value"],
@@ -23,7 +25,7 @@ export function useAcceptedDateValue(options: {
let requestId = 0;
const value = computed(() => {
const copy = copyDateValue(model.value.value ?? null);
return copy ? (Object.freeze(copy) as DateValue) : null;
return copy ? (Object.freeze(copy) as T) : null;
});
const wire = computed(() => {
void revision.value;
@@ -36,7 +38,7 @@ export function useAcceptedDateValue(options: {
revision.value++;
});
}
function request(next: DateValue | null | undefined) {
function request(next: T | null | undefined) {
if (
!options.disabled?.() &&
!options.readOnly?.() &&
+16 -5
View File
@@ -1,5 +1,6 @@
import {
DateFormatter,
Time,
createCalendar,
toCalendar,
toCalendarDate,
@@ -8,13 +9,23 @@ import {
} from "@internationalized/date";
/** Private date boundary: preserve calendar/time/zone, never round-trip JS Date. */
export function copyDateValue<T extends DateValue | null | undefined>(
export function copyDateValue<T extends DateValue | Time | null | undefined>(
value: T,
): T {
return (value == null ? value : value.copy()) as T;
}
export function dateValueKey(value: DateValue | null | undefined): string {
export function dateValueKey(
value: DateValue | Time | null | undefined,
): string {
if (value == null) return "empty";
if (!("calendar" in value))
return JSON.stringify([
"time",
value.hour,
value.minute,
value.second,
value.millisecond,
]);
const time =
"hour" in value
? [value.hour, value.minute, value.second, value.millisecond]
@@ -31,8 +42,8 @@ export function dateValueKey(value: DateValue | null | undefined): string {
]);
}
export function sameDateValue(
a: DateValue | null | undefined,
b: DateValue | null | undefined,
a: DateValue | Time | null | undefined,
b: DateValue | Time | null | undefined,
): boolean {
return dateValueKey(a) === dateValueKey(b);
}
@@ -49,7 +60,7 @@ export function copyDateValues<T extends DateValue>(values: readonly T[]): T[] {
}
/** Full ISO boundary; display granularity must not truncate the accepted model. */
export function serializeDateValue(
value: DateValue | null | undefined,
value: DateValue | Time | null | undefined,
): string {
return value?.toString() ?? "";
}
@@ -0,0 +1,404 @@
<!-- Adapted from HeroUI 3.2.6 / ce90ea3 time-field; Apache-2.0, see third-party/HEROUI-LICENSE. -->
<script lang="ts">
import {
computed,
defineComponent,
getCurrentInstance,
h,
nextTick,
onMounted,
provide,
ref,
shallowRef,
watch,
watchEffect,
type PropType,
type SlotsType,
type VNodeChild,
} from "vue";
import { TimeFieldRoot } from "reka-ui";
import {
Time,
parseTime,
parseDateTime,
parseZonedDateTime,
type CalendarDateTime,
type ZonedDateTime,
} from "@internationalized/date";
import { timeFieldVariants } from "@heroui-vue/styles";
import { useConfig } from "../../providers/context";
import { useAcceptedDateValue } from "../date/model";
import { serializeDateValue } from "../date/value";
import EmptyDateBridge from "../date/EmptyDateBridge";
import {
useChoiceField,
useChoiceForm,
validationInput,
} from "../choice/shared";
import { disabledContextKey } from "../field/disabled";
import type { ValidationBehavior, ValidateResult } from "../field/context";
import { dateFieldKey, type DateSegment } from "../date-field/context";
import PrimitiveNode from "../date-field/PrimitiveNode";
import DateSegments from "../date-field/DateSegments";
export type TimeValue = Time | CalendarDateTime | ZonedDateTime;
export interface TimeFieldRenderProps {
value: TimeValue | null;
isDisabled: boolean;
isReadOnly: boolean;
isRequired: boolean;
isInvalid: boolean;
isFocusWithin: boolean;
isFocused: boolean;
isFocusVisible: boolean;
validationErrors: string[];
}
const clock = (value: TimeValue) =>
new Time(value.hour, value.minute, value.second, value.millisecond);
export default defineComponent({
name: "TimeField",
inheritAttrs: false,
slots: Object as SlotsType<{
default?: (state: TimeFieldRenderProps) => VNodeChild;
}>,
props: {
modelValue: {
type: [Object, null] as PropType<TimeValue | null>,
default: undefined,
},
value: {
type: [Object, null] as PropType<TimeValue | null>,
default: undefined,
},
defaultValue: [Object, null] as PropType<TimeValue | null>,
placeholderValue: [Object, null] as PropType<TimeValue | null>,
minValue: [Object, null] as PropType<TimeValue | null>,
maxValue: [Object, null] as PropType<TimeValue | null>,
granularity: String as PropType<"hour" | "minute" | "second">,
hourCycle: Number as PropType<12 | 24>,
hideTimeZone: Boolean,
shouldForceLeadingZeros: { type: Boolean, default: undefined },
locale: String,
dir: String as PropType<"ltr" | "rtl">,
fullWidth: Boolean,
as: { type: String, default: "div" },
id: String,
name: String,
form: String,
isDisabled: Boolean,
disabled: Boolean,
isReadOnly: Boolean,
isRequired: Boolean,
isInvalid: Boolean,
autoFocus: Boolean,
autoComplete: String,
validationBehavior: String as PropType<ValidationBehavior>,
validate: Function as PropType<(value: TimeValue | null) => ValidateResult>,
},
emits: {
"update:modelValue": (_value: TimeValue | null) => true,
change: (_value: TimeValue | null) => true,
},
setup(props, { attrs, slots, emit, expose }) {
const config = useConfig();
const instance = getCurrentInstance()!;
const accepted: ReturnType<typeof useAcceptedDateValue<TimeValue>> =
useAcceptedDateValue<TimeValue>({
value: () =>
["modelValue", "model-value"].some((key) =>
Object.hasOwn(instance.vnode.props ?? {}, key),
)
? props.modelValue
: props.value,
defaultValue: () => props.defaultValue,
onChange: (value) => {
field.edit();
emit("update:modelValue", value);
emit("change", value);
},
disabled: () => field.field.disabled.value,
readOnly: () => field.field.readOnly.value,
});
const field = useChoiceField(props, attrs, {
kind: "group",
value: accepted.value,
satisfied: () => accepted.value.value !== null,
requiredMessage: "请填写此字段。",
validate: (value) => {
if (
value &&
props.minValue &&
clock(value).compare(clock(props.minValue)) < 0
)
return "时间不能早于最早时间。";
if (
value &&
props.maxValue &&
clock(value).compare(clock(props.maxValue)) > 0
)
return "时间不能晚于最晚时间。";
return props.validate?.(value);
},
});
provide(disabledContextKey, field.field.disabled);
provide(dateFieldKey, {
value: accepted.value,
disabled: field.field.disabled,
readOnly: field.field.readOnly,
required: field.field.required,
invalid: field.field.invalid,
form: () => native.value?.form,
leadingZeros: () => props.shouldForceLeadingZeros,
labelledBy: field.labelledBy,
describedBy: field.describedBy,
ariaLabel: () => attrs["aria-label"],
});
const locale = computed(
() => props.locale ?? config?.locale.value ?? "en-US",
);
const hourCycle = computed<12 | 24>(() => {
if (props.hourCycle) return props.hourCycle;
const cycle = new Intl.DateTimeFormat(locale.value, {
hour: "numeric",
}).resolvedOptions().hourCycle;
return cycle === "h11" || cycle === "h12" ? 12 : 24;
});
const initialPlaceholder = (
props.placeholderValue ??
props.defaultValue ??
accepted.value.value ??
new Time()
).copy();
const lastPlaceholder = shallowRef(initialPlaceholder);
watch(accepted.value, (value) => {
if (value) lastPlaceholder.value = value.copy();
});
const placeholder = computed(
() =>
props.placeholderValue ?? accepted.value.value ?? lastPlaceholder.value,
);
const wire = accepted.wire;
const root = ref<HTMLElement>(),
native = ref<HTMLInputElement>(),
proxy = ref<HTMLInputElement>();
const focused = ref(false);
const focusVisible = ref(false);
const focus = () =>
root.value
?.querySelector<HTMLElement>(
'[data-slot="date-input-group-segment"][tabindex="0"]',
)
?.focus();
function request(value: TimeValue | undefined) {
// The base may convert an empty placeholder to Time and omit milliseconds.
// Apply editable clock fields to the accepted/placeholder class, preserving
// its date, calendar, zone and precision that has no visible segment.
const source =
accepted.value.value ??
props.placeholderValue ??
props.defaultValue ??
initialPlaceholder;
accepted.request(
value
? source.set({
hour: value.hour,
minute:
props.granularity === "hour" ? source.minute : value.minute,
second:
props.granularity === "second" ? value.second : source.second,
})
: null,
);
}
function restoreNative() {
if (native.value)
native.value.value = serializeDateValue(accepted.value.value);
}
useChoiceForm(
proxy,
() => {
accepted.reset();
field.reset();
},
restoreNative,
);
watchEffect(() => field.validity(proxy.value), { flush: "post" });
const signature = computed(
() =>
`${props.granularity ?? "minute"}|${hourCycle.value}|${props.hideTimeZone}`,
);
watch(signature, () => {
const old = root.value?.ownerDocument.activeElement as HTMLElement | null;
const part =
old && root.value?.contains(old)
? old.dataset.rekaTimeFieldSegment
: undefined;
if (part)
void nextTick(() => {
const current = root.value?.ownerDocument.activeElement;
if (current === old || current === root.value?.ownerDocument.body)
(
root.value?.querySelector<HTMLElement>(
`[data-reka-time-field-segment="${part}"]`,
) ??
root.value?.querySelector<HTMLElement>(
'[data-slot="date-input-group-segment"][tabindex="0"]',
)
)?.focus();
});
});
onMounted(() => {
if (props.autoFocus) focus();
});
expose({ element: root, focus });
return () => {
const state = {
value: accepted.value.value,
isDisabled: field.field.disabled.value,
isReadOnly: field.field.readOnly.value,
isRequired: field.field.required.value,
isInvalid: field.field.invalid.value,
isFocusWithin: focused.value,
isFocused: focused.value,
isFocusVisible: focusVisible.value,
validationErrors: field.field.errors.value,
};
const raw = slots.default?.(state);
const children = field.prepare(
Array.isArray(raw) ? raw : raw ? [raw] : [],
true,
);
const overrides = {
id: field.field.controlId.value,
role: "group",
class: timeFieldVariants({ fullWidth: props.fullWidth }),
"data-slot": "time-field",
"data-disabled": state.isDisabled || undefined,
"data-readonly": state.isReadOnly || undefined,
"data-invalid": state.isInvalid || undefined,
"data-required": state.isRequired || undefined,
"data-focus-within": focused.value || undefined,
"aria-label": attrs["aria-label"],
"aria-labelledby": field.labelledBy(),
"aria-describedby": field.describedBy(),
"aria-invalid": state.isInvalid || undefined,
"aria-required": state.isRequired || undefined,
ref: (element: unknown) => {
root.value = element as HTMLElement;
},
onFocusin: (event: FocusEvent) => {
focused.value = true;
focusVisible.value = (event.target as HTMLElement).matches(
":focus-visible",
);
},
onFocusout: (event: FocusEvent) => {
if (
!(event.currentTarget as HTMLElement).contains(
event.relatedTarget as Node | null,
)
) {
focused.value = false;
focusVisible.value = false;
}
},
};
return h(
TimeFieldRoot,
{
key: signature.value,
asChild: true,
modelValue: wire.value,
placeholder: placeholder.value,
granularity: props.granularity ?? "minute",
hourCycle: hourCycle.value,
hideTimeZone: props.hideTimeZone,
locale: locale.value,
dir: props.dir ?? config?.dir.value,
disabled: state.isDisabled,
readonly: state.isReadOnly,
// One shared native validator and a full precision named input own
// submission; the underlying Reka input remains nameless.
"onUpdate:modelValue": request,
},
{
default: ({
segments,
}: {
segments: Pick<DateSegment, "part" | "value">[];
}) =>
h(
PrimitiveNode,
{ as: props.as, consumer: attrs, overrides },
{
default: () =>
h(
DateSegments,
{ segments, kind: "time" },
{
default: () => [
...children,
h(EmptyDateBridge, {
revision: accepted.emptyRevision.value,
}),
h("input", {
ref: native,
type: "text",
class: "hv-choice-input",
tabindex: -1,
"aria-hidden": "true",
autoComplete: props.autoComplete ?? "off",
readonly: state.isReadOnly,
onFocus: focus,
onInput: (event: Event) => {
if (
event.defaultPrevented ||
state.isDisabled ||
state.isReadOnly
) {
restoreNative();
return;
}
const text = (event.target as HTMLInputElement)
.value;
try {
accepted.request(
!text
? undefined
: text.includes("[")
? parseZonedDateTime(text)
: text.includes("T")
? parseDateTime(text)
: parseTime(text),
);
} catch {
restoreNative();
}
void nextTick(restoreNative);
},
name: props.name,
form: props.form,
value: serializeDateValue(accepted.value.value),
disabled: state.isDisabled,
"data-slot": "time-field-value",
}),
validationInput(
proxy,
props,
state.isDisabled || state.isReadOnly,
field.behavior.value,
(event) => field.invalidEvent(event, focus),
),
],
},
),
},
),
},
);
};
},
});
</script>
+26
View File
@@ -1111,3 +1111,29 @@ export type {
ColorSwatchStyle,
ColorSwatchStyleFn,
} from "./types";
export {
default as TimeField,
default as TimeFieldRoot,
} from "./components/time-field/TimeField.vue";
export { default as TimeFieldGroup } from "./components/date-field/DateInputGroup.vue";
export { default as TimeFieldInput } from "./components/date-field/DateInputGroupInput.vue";
export { default as TimeFieldSegment } from "./components/date-field/DateInputGroupSegment.vue";
export { default as TimeFieldInputContainer } from "./components/date-field/DateInputGroupInputContainer.vue";
export { default as TimeFieldPrefix } from "./components/date-field/DateInputGroupPrefix.vue";
export { default as TimeFieldSuffix } from "./components/date-field/DateInputGroupSuffix.vue";
export type {
TimeValue,
TimeFieldRenderProps,
} from "./components/time-field/TimeField.vue";
export { timeFieldVariants, type TimeFieldVariants } from "@heroui-vue/styles";
export type {
TimeFieldProps,
TimeFieldRootProps,
TimeFieldGroupProps,
TimeFieldInputProps,
TimeFieldSegmentProps,
TimeFieldInputContainerProps,
TimeFieldPrefixProps,
TimeFieldSuffixProps,
} from "./types";
+11
View File
@@ -879,3 +879,14 @@ export type {
ColorSwatchStyle,
ColorSwatchStyleFn,
} from "./components/color-swatch/types";
export type TimeFieldProps = InstanceType<
(typeof import("./components/time-field/TimeField.vue"))["default"]
>["$props"];
export type TimeFieldRootProps = TimeFieldProps;
export type TimeFieldGroupProps = DateInputGroupProps;
export type TimeFieldInputProps = DateInputGroupInputProps;
export type TimeFieldSegmentProps = DateInputGroupSegmentProps;
export type TimeFieldInputContainerProps = DateInputGroupInputContainerProps;
export type TimeFieldPrefixProps = DateInputGroupPrefixProps;
export type TimeFieldSuffixProps = DateInputGroupSuffixProps;
+1 -1
View File
@@ -31,7 +31,7 @@ pnpm test:related packages/vue/src/components/combo-box/ComboBox.vue
| pnpm build:docs | 库、样式与文档站静态构建,保留文档渲染要求,不视为组件SSR支持 |
| pnpm build:playground | 浏览器验证入口生产构建 |
现有86个测试文件包含1266项客户端用例,默认全部运行;不再维护SSR排除规则或相关命令。逐像素自动对比、完整读屏矩阵、真机矩阵、Nuxt集成暂不投入。
现有91个测试文件包含1322项客户端用例,默认全部运行;不再维护SSR排除规则或相关命令。逐像素自动对比、完整读屏矩阵、真机矩阵、Nuxt集成暂不投入。
不新增普遍服务端、无document运行、ID水合稳定、Teleport服务端、Nuxt服务端适配等验收要求。NodeNext是发布类型解析模式,不代表要求SSR支持。
+10
View File
@@ -40,6 +40,16 @@ for (const id of process.argv.slice(2)) {
.includes("hv-list-box-item__indicator"),
);
}
if (id === "time-field") {
assert(lib.TimeField === lib.TimeFieldRoot);
assert(lib.TimeFieldGroup === lib.DateInputGroup);
assert(lib.TimeFieldInput === lib.DateInputGroupInput);
assert(
lib
.timeFieldVariants({ fullWidth: true })
.includes("hv-time-field--full-width"),
);
}
if (id === "slider")
assert(lib.sliderVariants().thumb().includes("hv-slider__thumb"));
if (id === "select")
+19
View File
@@ -354,5 +354,24 @@
".hv-color-swatch--xl",
"repeating-conic-gradient"
]
},
"time-field": {
"exports": [
"TimeField",
"TimeFieldRoot",
"TimeFieldGroup",
"TimeFieldInput",
"TimeFieldSegment",
"TimeFieldInputContainer",
"TimeFieldPrefix",
"TimeFieldSuffix",
"timeFieldVariants"
],
"css": [
".hv-time-field",
".hv-time-field--full-width",
".hv-date-input-group",
".hv-date-input-group__segment"
]
}
}
+98
View File
@@ -0,0 +1,98 @@
import {
TimeField,
TimeFieldRoot,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
TimeFieldInputContainer,
TimeFieldPrefix,
TimeFieldSuffix,
timeFieldVariants,
type TimeValue,
type TimeFieldProps,
type TimeFieldGroupProps,
type TimeFieldInputProps,
type TimeFieldSegmentProps,
} from "@heroui-vue/components";
import {
Time,
CalendarDateTime,
CalendarDate,
parseZonedDateTime,
} from "@internationalized/date";
const values: TimeValue[] = [
new Time(9, 30),
new CalendarDateTime(2024, 2, 10, 9, 30),
parseZonedDateTime("2024-01-01T09:30+08:00[Asia/Shanghai]"),
];
const props: TimeFieldProps = {
modelValue: values[0],
value: null,
defaultValue: values[1],
placeholderValue: values[2],
minValue: new Time(9),
maxValue: new Time(17),
granularity: "second",
hourCycle: 24,
shouldForceLeadingZeros: true,
form: "appointment",
locale: "zh-CN",
dir: "rtl",
validate: (value) => (value ? null : "Missing"),
"onUpdate:modelValue": (value) => {
const t: TimeValue | null = value;
void t;
},
onChange: (value) => {
const t: TimeValue | null = value;
void t;
},
};
const group: TimeFieldGroupProps = { variant: "secondary", fullWidth: true };
const input: TimeFieldInputProps = { as: "div" };
const segment: TimeFieldSegmentProps = {
segment: {
part: "hour",
type: "hour",
value: "09",
text: "09",
isEditable: true,
isPlaceholder: false,
},
};
// @ts-expect-error values are immutable internationalized time values, not strings
const string: TimeFieldProps = { modelValue: "09:30" };
// @ts-expect-error a plain date has no time
const date: TimeFieldProps = { modelValue: new CalendarDate(2024, 2, 10) };
// @ts-expect-error day granularity belongs to DateField
const day: TimeFieldProps = { granularity: "day" };
// @ts-expect-error no arbitrary visual variant
const variant: TimeFieldGroupProps = { variant: "outline" };
// @ts-expect-error no arbitrary hour cycle
const cycle: TimeFieldProps = { hourCycle: 23 };
// @ts-expect-error TimeField is not a range
const range: TimeFieldProps = { modelValue: values };
// @ts-expect-error real segment object is required
const badSegment: TimeFieldSegmentProps = { segment: "hour" };
void [
TimeField,
TimeFieldRoot,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
TimeFieldInputContainer,
TimeFieldPrefix,
TimeFieldSuffix,
timeFieldVariants({ fullWidth: true }),
props,
group,
input,
segment,
string,
date,
day,
variant,
cycle,
range,
badSegment,
];
+106
View File
@@ -0,0 +1,106 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { readFileSync } from "node:fs";
const demos = import.meta.glob("../apps/docs/demos/time-field-*.vue", {
eager: true,
import: "default",
});
const expected = [
"basic",
"with-prefix-icon",
"with-suffix-icon",
"with-prefix-and-suffix",
"on-surface",
"with-description",
"required",
"disabled",
"full-width",
"invalid",
"controlled",
"form-example",
"with-validation",
"render-function",
"custom-styles",
];
afterEach(() => vi.useRealTimers());
describe("TimeField documentation", () => {
it("retains the fifteen fixed-source previews in the same order", () => {
const md = readFileSync("apps/docs/components/time-field.md", "utf8");
expect(
[...md.matchAll(/name="time-field-([^"]+)"/g)].map((m) => m[1]),
).toEqual(expected);
expect(Object.keys(demos)).toHaveLength(15);
expect(md).not.toContain("@heroui/react");
expect(md).not.toContain("继承 React Aria");
});
it("mounts every real preview without warnings or missing time controls", async () => {
const warnings: string[] = [];
for (const demo of Object.values(demos)) {
const w = mount(demo as never, {
global: { config: { warnHandler: (m) => warnings.push(m) } },
});
try {
await flushPromises();
expect(w.find('[data-slot="time-field"]').exists()).toBe(true);
expect(w.find('[data-type="hour"]').exists()).toBe(true);
expect(w.find('[data-type="year"]').exists()).toBe(false);
} finally {
w.unmount();
}
}
expect(warnings).toEqual([]);
});
it("sets and clears the controlled value through real action buttons", async () => {
const w = mount(
demos["../apps/docs/demos/time-field-controlled.vue"] as never,
);
try {
await w.findAll("button")[0].trigger("click");
await flushPromises();
expect(
(w.get('[data-slot="time-field-value"]').element as HTMLInputElement)
.value,
).toMatch(/^\d{2}:\d{2}:\d{2}/);
expect(w.get('[data-slot="description"]').text()).not.toContain("(空)");
await w.findAll("button")[1].trigger("click");
await flushPromises();
expect(w.get('[data-slot="description"]').text()).toContain("(空)");
expect(w.get('[data-type="hour"]').attributes("data-placeholder")).toBe(
"true",
);
} finally {
w.unmount();
}
});
it("validates business hours and submits the actual value with loading/reset feedback", async () => {
const w = mount(
demos["../apps/docs/demos/time-field-form-example.vue"] as never,
);
try {
const input = w.get('[data-slot="time-field-value"]');
await input.setValue("08:30");
await flushPromises();
expect(w.get('[data-slot="field-error"]').text()).toContain("9:00");
expect((w.get("button").element as HTMLButtonElement).disabled).toBe(
true,
);
await input.setValue("14:30:45");
await flushPromises();
expect(w.find('[data-slot="field-error"]').exists()).toBe(false);
expect((w.get("button").element as HTMLButtonElement).disabled).toBe(
false,
);
vi.useFakeTimers();
await w.get("form").trigger("submit");
expect(w.get("button").text()).toBe("提交中…");
await vi.advanceTimersByTimeAsync(1500);
expect(w.get("output").text()).toBe("已提交:14:30:45");
expect((input.element as HTMLInputElement).value).toBe("");
expect(w.get('[data-type="hour"]').attributes("data-placeholder")).toBe(
"true",
);
} finally {
w.unmount();
}
});
});
+486
View File
@@ -0,0 +1,486 @@
import { afterEach, describe, expect, it } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, ref, shallowRef } from "vue";
import {
Time,
CalendarDateTime,
parseZonedDateTime,
toCalendar,
PersianCalendar,
} from "@internationalized/date";
import {
TimeField,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
TimeFieldPrefix,
TimeFieldInputContainer,
DateInputGroup,
DateInputGroupInput,
Label,
Description,
FieldError,
Fieldset,
Form,
ConfigProvider,
} from "../packages/vue/src";
const components = {
TimeField,
TimeFieldGroup,
TimeFieldInput,
TimeFieldSegment,
TimeFieldPrefix,
TimeFieldInputContainer,
DateInputGroup,
DateInputGroupInput,
Label,
Description,
FieldError,
Fieldset,
Form,
ConfigProvider,
};
const content =
'<Label>Time</Label><TimeFieldGroup><TimeFieldInput v-slot="{segment}"><TimeFieldSegment :segment="segment" /></TimeFieldInput></TimeFieldGroup><Description>Help</Description><FieldError/>';
const initial = new Time(13, 4, 45, 123);
const wrappers: ReturnType<typeof mount>[] = [];
afterEach(() => {
wrappers.splice(0).forEach((w) => w.unmount());
document.body.innerHTML = "";
});
function fixture(template: string, setup = () => ({})) {
const w = mount(defineComponent({ components, template, setup }), {
attachTo: document.body,
});
wrappers.push(w);
return w;
}
const part = (w: ReturnType<typeof mount>, type = "hour") =>
w.get(`[data-type="${type}"]`);
const values = (w: ReturnType<typeof mount>) =>
new FormData(w.get("form").element as HTMLFormElement).getAll("time");
async function up(w: ReturnType<typeof mount>, type = "hour") {
await part(w, type).trigger("keydown", { key: "ArrowUp" });
await flushPromises();
}
describe("TimeField public composition", () => {
it("shares field ids, renders only time and submits one full precision Time", async () => {
const w = fixture(
`<form><TimeField name="time" :default-value="initial" :hour-cycle="24">${content}</TimeField></form>`,
() => ({ initial }),
);
const root = w.get('[data-slot="time-field"]');
expect(root.attributes("aria-labelledby")).toContain(
w.get('[data-slot="label"]').attributes("id"),
);
expect(root.attributes("aria-describedby")).toContain(
w.get('[data-slot="description"]').attributes("id"),
);
expect(w.find('[data-type="year"]').exists()).toBe(false);
expect(w.find('[data-type="second"]').exists()).toBe(false);
expect(values(w)).toEqual(["13:04:45.123"]);
await up(w, "minute");
expect(values(w)).toEqual(["13:05:45.123"]);
expect(w.getComponent(TimeField).emitted("change")![0][0]).toBeInstanceOf(
Time,
);
});
it("restores rejected values, keeps DOM/focus and emits identical retries", async () => {
const w = fixture(
`<form><TimeField name="time" :model-value="initial" :hour-cycle="24">${content}</TimeField></form>`,
() => ({ initial }),
);
const el = part(w).element as HTMLElement;
el.focus();
await up(w);
await up(w);
expect(part(w).text()).toBe("13");
expect(part(w).element).toBe(el);
expect(document.activeElement).toBe(el);
expect(values(w)).toEqual(["13:04:45.123"]);
const events = w.getComponent(TimeField).emitted("change")!;
expect(events).toHaveLength(2);
expect(events.map((e) => (e[0] as Time).toString())).toEqual([
"14:04:45.123",
"14:04:45.123",
]);
});
it("clears rejected completed empty proposals without replacing focused segments", async () => {
const w = fixture(
`<form><TimeField name="time" :model-value="null" :placeholder-value="initial" :hour-cycle="24">${content}</TimeField></form>`,
() => ({ initial }),
);
const el = part(w, "minute").element as HTMLElement;
el.focus();
for (let i = 0; i < 2; i++) {
await up(w);
await up(w, "minute");
expect(part(w).attributes("data-placeholder")).toBe("true");
expect(values(w)).toEqual([""]);
}
expect(document.activeElement).toBe(el);
expect(part(w, "minute").element).toBe(el);
expect(w.getComponent(TimeField).emitted("change")).toHaveLength(2);
});
it("accepts a completed empty edit and preserves DateTime placeholder type", async () => {
const value = shallowRef<CalendarDateTime | null>(null);
const placeholder = new CalendarDateTime(2024, 2, 10, 13, 4, 45, 123);
const w = fixture(
`<form><TimeField v-model="value" name="time" :placeholder-value="placeholder" :hour-cycle="24">${content}</TimeField></form>`,
() => ({ value, placeholder }),
);
await up(w);
await part(w, "minute").trigger("keydown", { key: "4" });
await flushPromises();
expect(value.value).toBeInstanceOf(CalendarDateTime);
expect(value.value?.toString()).toBe("2024-02-10T13:04:45.123");
expect(values(w)).toEqual([value.value!.toString()]);
});
it("preserves named zone, date, calendar and precision when editing only time", async () => {
const value = shallowRef(
parseZonedDateTime("2024-03-10T01:30:45.123-08:00[America/Los_Angeles]"),
);
const w = fixture(
`<form><TimeField v-model="value" name="time" :hour-cycle="24">${content}</TimeField></form>`,
() => ({ value }),
);
expect(part(w, "timeZoneName").attributes("contenteditable")).toBe("false");
await up(w, "minute");
expect(value.value.toString()).toBe(
"2024-03-10T01:31:45.123-08:00[America/Los_Angeles]",
);
expect(values(w)).toEqual([value.value.toString()]);
value.value = toCalendar(value.value, new PersianCalendar());
await flushPromises();
await up(w, "minute");
expect(value.value.calendar.identifier).toBe("persian");
expect(value.value.timeZone).toBe("America/Los_Angeles");
});
it("responds to external updates, clearing, locale and format changes", async () => {
const value = shallowRef<Time | null>(initial);
const locale = ref("en-US");
const cycle = ref<12 | 24>(12);
const granularity = ref<"hour" | "second">("hour");
const w = fixture(
`<form><ConfigProvider :locale="locale"><TimeField v-model="value" name="time" :hour-cycle="cycle" :granularity="granularity" should-force-leading-zeros>${content}</TimeField></ConfigProvider></form>`,
() => ({ value, locale, cycle, granularity }),
);
expect(part(w).text()).toBe("01");
expect(w.find('[data-type="dayPeriod"]').exists()).toBe(true);
part(w).element instanceof HTMLElement &&
(part(w).element as HTMLElement).focus();
cycle.value = 24;
granularity.value = "second";
locale.value = "zh-CN";
await flushPromises();
expect(part(w).text()).toBe("13");
expect(part(w, "second").text()).toBe("45");
expect(document.activeElement).toBe(part(w).element);
expect(w.find('[data-type="dayPeriod"]').exists()).toBe(false);
expect(values(w)).toEqual([initial.toString()]);
value.value = null;
await flushPromises();
expect(part(w).attributes("data-placeholder")).toBe("true");
value.value = new Time(8, 9, 10);
await flushPromises();
expect(part(w).text()).toBe("08");
expect(values(w)).toEqual(["08:09:10"]);
});
it("uses locale hourCycle defaults and toggles dayPeriod", async () => {
const locale = ref("en-US");
const w = fixture(
`<ConfigProvider :locale="locale"><TimeField :default-value="initial">${content}</TimeField></ConfigProvider>`,
() => ({ locale, initial }),
);
expect(w.find('[data-type="dayPeriod"]').exists()).toBe(true);
await up(w, "dayPeriod");
expect(part(w).text()).toBe("1");
locale.value = "en-GB";
await flushPromises();
expect(w.find('[data-type="dayPeriod"]').exists()).toBe(false);
});
it("compares min/max as time of day across different date/zone types", async () => {
const value = shallowRef(new CalendarDateTime(2020, 1, 1, 8, 30));
const min = new Time(9);
const max = new Time(17);
const w = fixture(
`<form><TimeField v-model="value" name="time" :min-value="min" :max-value="max" validation-behavior="aria">${content}</TimeField></form>`,
() => ({ value, min, max }),
);
expect(w.get('[data-slot="field-error"]').text()).toContain("不能早于");
await up(w);
expect(w.find('[data-slot="field-error"]').exists()).toBe(false);
value.value = new CalendarDateTime(2030, 1, 1, 18);
await flushPromises();
expect(w.get('[data-slot="field-error"]').text()).toContain("不能晚于");
});
it("validates required/custom constraints and redirects native invalid focus", async () => {
const w = fixture(
`<form><TimeField name="time" is-required :hour-cycle="24">${content}</TimeField></form>`,
);
expect(
(
w.get(".hv-choice-validation").element as HTMLInputElement
).checkValidity(),
).toBe(false);
await flushPromises();
expect(w.get('[data-slot="field-error"]').text()).toContain("请填写");
expect(document.activeElement).toBe(part(w).element);
const w2 = fixture(
`<form><TimeField name="time" :default-value="initial" :validate="()=> 'Custom error'" validation-behavior="aria">${content}</TimeField></form>`,
() => ({ initial }),
);
expect(w2.get('[data-slot="field-error"]').text()).toBe("Custom error");
expect(
(
w2.get(".hv-choice-validation").element as HTMLInputElement
).checkValidity(),
).toBe(true);
});
it("inherits disabled, submits readonly and responds to dynamic state", async () => {
const disabled = ref(true),
readonly = ref(false);
const w = fixture(
`<form><Fieldset :disabled="disabled"><TimeField name="time" :default-value="initial" :is-read-only="readonly">${content}</TimeField></Fieldset></form>`,
() => ({ initial, disabled, readonly }),
);
expect(values(w)).toEqual([]);
await up(w);
expect(w.getComponent(TimeField).emitted("change")).toBeUndefined();
disabled.value = false;
readonly.value = true;
await flushPromises();
expect(values(w)).toEqual([initial.toString()]);
await up(w);
expect(w.getComponent(TimeField).emitted("change")).toBeUndefined();
expect(part(w).attributes("contenteditable")).toBe("false");
expect(
(w.get(".hv-choice-validation").element as HTMLInputElement).disabled,
).toBe(true);
readonly.value = false;
await flushPromises();
await up(w);
expect(w.getComponent(TimeField).emitted("change")).toHaveLength(1);
});
it("resets uncontrolled edits and empty partial drafts without change events", async () => {
const w = fixture(
`<form><TimeField name="time" :default-value="initial" :hour-cycle="24">${content}</TimeField></form>`,
() => ({ initial }),
);
await up(w);
(w.get("form").element as HTMLFormElement).reset();
await flushPromises();
expect(values(w)).toEqual([initial.toString()]);
expect(w.getComponent(TimeField).emitted("change")).toHaveLength(1);
const empty = fixture(
`<form><TimeField name="time" :hour-cycle="24">${content}</TimeField></form>`,
);
await up(empty);
expect(part(empty).attributes("data-placeholder")).toBeUndefined();
(empty.get("form").element as HTMLFormElement).reset();
await flushPromises();
expect(part(empty).attributes("data-placeholder")).toBe("true");
expect(values(empty)).toEqual([""]);
});
it("preserves controlled reset and canceled reset, supports external form", async () => {
const value = shallowRef(initial),
prevent = ref(false);
const w = fixture(
`<div><form id="external" @reset="prevent && $event.preventDefault()"/><TimeField form="external" name="time" v-model="value">${content}</TimeField></div>`,
() => ({ value, prevent }),
);
await up(w);
(w.get("form").element as HTMLFormElement).reset();
await flushPromises();
expect(values(w)).toEqual([value.value.toString()]);
const uncontrolled = fixture(
`<form @reset.prevent><TimeField name="time" :default-value="initial">${content}</TimeField></form>`,
() => ({ initial }),
);
await up(uncontrolled);
(uncontrolled.get("form").element as HTMLFormElement).reset();
await flushPromises();
expect(values(uncontrolled)).toEqual(["14:04:45.123"]);
});
it("gives explicit modelValue including undefined priority over value/defaultValue", async () => {
const value = shallowRef<Time | undefined>(undefined);
const w = fixture(
`<form><TimeField name="time" :model-value="value" :value="initial" :default-value="initial" :hour-cycle="24">${content}</TimeField></form>`,
() => ({ value, initial }),
);
expect(values(w)).toEqual([""]);
value.value = initial;
await flushPromises();
expect(values(w)).toEqual([initial.toString()]);
const alias = fixture(
`<form><TimeField name="time" :value="initial">${content}</TimeField></form>`,
() => ({ initial }),
);
expect(values(alias)).toEqual([initial.toString()]);
});
it("honors consumer segment key cancellation, IME and navigation direction", async () => {
const w = fixture(
`<form><TimeField name="time" :default-value="initial"><TimeFieldGroup><TimeFieldInput v-slot="{segment}"><TimeFieldSegment :segment="segment" @keydown.stop.prevent /></TimeFieldInput></TimeFieldGroup></TimeField></form>`,
() => ({ initial }),
);
const el = part(w).element as HTMLElement;
el.focus();
await up(w);
await part(w).trigger("keydown", { key: "ArrowRight" });
expect(document.activeElement).toBe(el);
expect(values(w)).toEqual([initial.toString()]);
const rtl = fixture(
`<form><TimeField name="time" :default-value="initial" dir="rtl" :hour-cycle="24">${content}</TimeField></form>`,
() => ({ initial }),
);
(part(rtl).element as HTMLElement).focus();
await part(rtl).trigger("keydown", { key: "ArrowLeft" });
expect(document.activeElement).toBe(part(rtl, "minute").element);
part(rtl).element.dispatchEvent(
new KeyboardEvent("keydown", {
key: "2",
isComposing: true,
bubbles: true,
cancelable: true,
}),
);
await flushPromises();
expect(values(rtl)).toEqual([initial.toString()]);
});
it("accepts native ISO edits, restores rejected or invalid input and keeps one submission", async () => {
const w = fixture(
`<form><TimeField name="time" :model-value="initial">${content}</TimeField></form>`,
() => ({ initial }),
);
const input = w.get('[data-slot="time-field-value"]');
await input.setValue("10:20:30.456");
await flushPromises();
expect(values(w)).toEqual([initial.toString()]);
expect(w.getComponent(TimeField).emitted("change")).toHaveLength(1);
await input.setValue("bad time");
await flushPromises();
expect(values(w)).toEqual([initial.toString()]);
expect(w.getComponent(TimeField).emitted("change")).toHaveLength(1);
});
it("reuses standalone DateInputGroup parts, supports ref focus and slot state", async () => {
const w = fixture(
`<TimeField ref="field" auto-focus is-required v-slot="state" data-custom="foo"><Label>Time</Label><DateInputGroup variant="secondary"><TimeFieldInputContainer><TimeFieldPrefix>At</TimeFieldPrefix><DateInputGroupInput /></TimeFieldInputContainer></DateInputGroup><span data-state>{{state.isRequired}}</span></TimeField>`,
);
await flushPromises();
expect(w.get("[data-state]").text()).toBe("true");
expect(w.get('[data-slot="time-field"]').attributes("data-custom")).toBe(
"foo",
);
expect(document.activeElement).toBe(part(w).element);
expect(
(w.getComponent(TimeField).vm as unknown as { focus: () => void }).focus,
).toBeTypeOf("function");
});
it("dismisses server validation errors on a real edit", async () => {
const w = fixture(
`<Form :validation-errors="{time:'Server error'}" validation-behavior="aria"><TimeField name="time" :default-value="initial">${content}</TimeField></Form>`,
() => ({ initial }),
);
expect(w.get('[data-slot="field-error"]').text()).toBe("Server error");
await up(w);
expect(w.find('[data-slot="field-error"]').exists()).toBe(false);
});
});
it("Enter submits the associated form once; canceled Enter and blur do not duplicate changes", async () => {
const submits = ref(0),
cancel = ref(false);
const w = fixture(
`<div><form id="time-enter" @submit.prevent="submits++"/><TimeField form="time-enter" name="time" :default-value="initial"><TimeFieldGroup><TimeFieldInput v-slot="{segment}"><TimeFieldSegment :segment="segment" @keydown="cancel && $event.preventDefault()"/></TimeFieldInput></TimeFieldGroup></TimeField></div>`,
() => ({ initial, submits, cancel }),
);
await up(w);
const field = w.getComponent(TimeField);
expect(field.emitted("change")).toHaveLength(1);
await part(w).trigger("keydown", { key: "Enter" });
expect(submits.value).toBe(1);
await part(w).trigger("focusout");
await flushPromises();
expect(field.emitted("change")).toHaveLength(1);
cancel.value = true;
await flushPromises();
await part(w).trigger("keydown", { key: "Enter" });
expect(submits.value).toBe(1);
});
it("keeps leading-zero control limited to hour and edits seconds without losing milliseconds", async () => {
const value = shallowRef(new Time(3, 4, 5, 678));
const w = fixture(
`<form><TimeField name="time" v-model="value" :hour-cycle="24" granularity="second" :should-force-leading-zeros="false">${content}</TimeField></form>`,
() => ({ value }),
);
expect(part(w).text()).toBe("3");
expect(part(w, "minute").text()).toBe("04");
expect(part(w, "second").text()).toBe("05");
await up(w, "second");
expect(values(w)).toEqual(["03:04:06.678"]);
});
it("clears an edited segment to null, retains partial drafts and rejects a clear without focus loss", async () => {
const w = fixture(
`<form><TimeField name="time" :default-value="initial" :hour-cycle="24">${content}</TimeField></form>`,
() => ({ initial }),
);
await part(w, "minute").trigger("keydown", { key: "Backspace" });
await flushPromises();
expect(values(w)).toEqual([""]);
expect(part(w, "minute").attributes("data-placeholder")).toBe("true");
const controlled = fixture(
`<form><TimeField name="time" :model-value="initial" :hour-cycle="24">${content}</TimeField></form>`,
() => ({ initial }),
);
const el = part(controlled, "minute").element as HTMLElement;
el.focus();
await part(controlled, "minute").trigger("keydown", { key: "Backspace" });
await flushPromises();
expect(values(controlled)).toEqual([initial.toString()]);
expect(part(controlled, "minute").text()).toBe("04");
expect(document.activeElement).toBe(el);
});
it("updates zone visibility and keeps explicit ARIA and native attrs", async () => {
const hide = ref(false),
zone = parseZonedDateTime("2024-01-01T09:30+08:00[Asia/Shanghai]");
const w = fixture(
`<TimeField :default-value="zone" :hide-time-zone="hide" aria-label="Appointment" aria-describedby="outside" aria-details="details">${content}</TimeField>`,
() => ({ hide, zone }),
);
expect(w.find('[data-type="timeZoneName"]').exists()).toBe(true);
hide.value = true;
await flushPromises();
expect(w.find('[data-type="timeZoneName"]').exists()).toBe(false);
const root = w.get('[data-slot="time-field"]');
expect(root.attributes("aria-details")).toBe("details");
expect(root.attributes("aria-describedby")).toContain("outside");
expect(root.attributes("aria-label")).toBe("Appointment");
});
it("keeps 12-hour spinbutton ARIA ranges consistent with rendered values", async () => {
const w = fixture(
`<TimeField :default-value="initial" locale="en-US">${content}</TimeField>`,
() => ({ initial }),
);
expect(part(w).text()).toBe("1");
expect(part(w).attributes("aria-valuenow")).toBe("1");
expect(part(w).attributes("aria-valuemax")).toBe("12");
expect(part(w, "dayPeriod").attributes("aria-valuenow")).toBe("1");
expect(part(w, "dayPeriod").attributes("aria-valuemax")).toBe("1");
});
it("keeps focus on a valid segment when the focused format part disappears", async () => {
const granularity = ref<"minute" | "second">("second");
const hide = ref(false);
const zone = parseZonedDateTime("2024-01-01T09:30:45+08:00[Asia/Shanghai]");
const w = fixture(
`<TimeField :default-value="zone" :granularity="granularity" :hide-time-zone="hide">${content}</TimeField>`,
() => ({ zone, granularity, hide }),
);
(part(w, "second").element as HTMLElement).focus();
granularity.value = "minute";
await flushPromises();
expect(document.activeElement).toBe(part(w).element);
(part(w, "timeZoneName").element as HTMLElement).focus();
hide.value = true;
await flushPromises();
expect(document.activeElement).toBe(part(w).element);
});