feat: publish ColorField and shared color input parts

This commit is contained in:
maoyingjie
2026-10-27 11:53:02 +08:00
parent 108a120c81
commit 6a7a89be6b
34 changed files with 1511 additions and 39 deletions
+5
View File
@@ -95,6 +95,11 @@ export const componentItems: DocsItem[] = [
url: "/components/color-area",
category: "colors",
},
{
title: "ColorField 颜色输入框",
url: "/components/color-field",
category: "colors",
},
{
title: "ColorSlider 颜色滑块",
url: "/components/color-slider",
+1 -1
View File
@@ -178,4 +178,4 @@ Vue 版写作 `ColorAreaThumb`(对应上游 `ColorArea.Thumb`)。
## 相关组件
本批次公开 ColorArea 与 ColorSwatch。ColorField、ColorInputGroup、ColorPicker、ColorSlider 与 ColorSwatchPicker 仍为私有颜色协议,尚未提供公共页面。
已公开 [ColorField 颜色输入框](/components/color-field)(含 ColorInputGroup)、[ColorArea 颜色区域](/components/color-area)、[ColorSlider 颜色滑块](/components/color-slider) 与 [ColorSwatch 颜色色块](/components/color-swatch)。ColorPicker 与 ColorSwatchPicker 仍未公开。
+288
View File
@@ -0,0 +1,288 @@
---
title: ColorField 颜色输入框
description: 支持 Hex 与颜色通道编辑的颜色输入字段,支持标签、描述与验证
component: color-field
group: 组件
---
## 用法
```vue
<script setup lang="ts">
import {
ColorField,
ColorFieldGroup,
ColorFieldInput,
ColorFieldPrefix,
ColorSwatch,
Label,
Description,
FieldError,
} from "@heroui-vue/components";
</script>
<template>
<ColorField default-value="#0485F7" name="color">
<Label>颜色</Label>
<ColorFieldGroup>
<ColorFieldPrefix>
<ColorSwatch color="#0485F7" size="xs" />
</ColorFieldPrefix>
<ColorFieldInput />
</ColorFieldGroup>
<Description>选择你的颜色</Description>
<FieldError />
</ColorField>
</template>
```
<ComponentPreview name="color-field-basic" />
## 组件结构
```vue
<script setup lang="ts">
import {
ColorField,
ColorFieldGroup,
ColorFieldInput,
ColorFieldPrefix,
ColorSwatch,
Label,
Description,
FieldError,
} from "@heroui-vue/components";
</script>
<template>
<ColorField default-value="#0485F7" name="color">
<Label>颜色</Label>
<ColorFieldGroup>
<ColorFieldPrefix>
<ColorSwatch color="#0485F7" size="xs" />
</ColorFieldPrefix>
<ColorFieldInput />
</ColorFieldGroup>
<Description>选择你的颜色</Description>
<FieldError />
</ColorField>
</template>
```
> **ColorField** 将标签、颜色输入、描述与错误合并为单个无障碍组件。
## 示例
### 变体
ColorFieldGroup 组件支持两种视觉变体:
- **`primary`**(默认)- 标准样式带阴影,适用于大多数场景
- **`secondary`** - 低强调变体无阴影,适用于 Surface 组件内
<ComponentPreview name="color-field-variants" />
### 表面样式
在 [Surface](/components/surface) 组件内使用时,在 ColorFieldGroup 上使用 `variant="secondary"` 以应用适合 Surface 背景的低强调变体。
<ComponentPreview name="color-field-on-surface" />
### 带描述
<ComponentPreview name="color-field-with-description" />
### 必填字段
<ComponentPreview name="color-field-required" />
### 禁用
<ComponentPreview name="color-field-disabled" />
### 宽度充满
<ComponentPreview name="color-field-full-width" />
### 表单校验
将 `isInvalid` 与 `FieldError` 一起使用以显示验证消息。
<ComponentPreview name="color-field-invalid" />
### 分量编辑
ColorField 支持通过设置 `colorSpace` 与 `channel` 属性编辑单个颜色通道(hue、saturation、lightness、red、green、blue、alpha)。
<ComponentPreview name="color-field-channel-editing" />
### 受控组件
控制值以与其他组件或状态管理同步。
<ComponentPreview name="color-field-controlled" />
### 表单示例
包含验证与提交处理的完整表单示例。
<ComponentPreview name="color-field-form-example" />
### 渲染函数
上游 `render` 的元素替换使用 `as` 和透传属性实现;Vue 默认作用域插槽提供实时字段状态,`styleFn` 可依据状态计算样式。
<ComponentPreview name="color-field-render-function" />
## 自定义样式
### Tailwind CSS
<ComponentPreview name="color-field-custom-styles" />
### 全局 CSS
ColorField 默认样式较少。覆盖 `.hv-color-field` 类以自定义容器样式。
```css
@layer components {
.hv-color-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-color-field` – 最小样式的根容器(`flex flex-col gap-1`)
> **Note:** 子组件([Label](/components/label)、[Description](/components/description)、[FieldError](/components/field-error))有各自的 CSS 类与样式。请参阅各自文档了解自定义选项。ColorFieldGroup 样式见下方 API 参考。
### 交互状态
ColorField 根据状态自动管理以下 data 属性:
- **Invalid**:`[data-invalid="true"]` 或 `[aria-invalid="true"]` - 无效时自动隐藏 description slot
- **Required**:`[data-required="true"]` - `isRequired` 为 true 时应用
- **Disabled**:`[data-disabled="true"]` - `isDisabled` 为 true 时应用
- **Focus Within**:`[data-focus-within="true"]` - 任一子 input 聚焦时应用
## API 参考
### ColorField
`ColorFieldRoot` 是 `ColorField` 的别名;Vue 使用具名部件与 `v-model`,颜色复用本库 `Color`。不声明继承全部 React Aria 属性。
| Prop / 事件 | 类型 | 默认值 | 描述 |
| -------------------------------- | ------------------------------------------ | ---------------------- | ----------------------------------------------------------------------------------- |
| `modelValue` / `v-model` | `ColorValue \| null` | - | 受控接受值;ColorValue 为本库 Color 或颜色字符串 |
| `value` | `ColorValue \| null` | - | 低优先级受控别名 |
| `defaultValue` | `ColorValue \| null` | `null` | 非受控初始值,捕获一次 |
| `channel` | `ColorChannel` | - | 未指定时编辑 Hex;否则编辑 hue/saturation/lightness/brightness/red/green/blue/alpha |
| `colorSpace` | `"rgb" \| "hsl" \| "hsb"` | 推断 | 通道使用空间,见下方说明 |
| `fullWidth` | `boolean` | `false` | 根容器占满宽度 |
| `isRequired` | `boolean` | `false` | 必填;原生或 ARIA 校验 |
| `isInvalid` | `boolean` | `false` | 外部错误状态 |
| `validate` | `(value: Color \| null) => ValidateResult` | - | 返回 true/null/undefined 表示有效,false/字符串/字符串数组表示无效 |
| `validationBehavior` | `"native" \| "aria"` | `"native"` / Form | 原生约束阻止提交,或仅提供 ARIA 错误 |
| `isDisabled` / `disabled` | `boolean` | `false` | 禁用;disabled 是本库别名 |
| `isReadOnly` | `boolean` | `false` | 可聚焦、可选中,不能编辑 |
| `isWheelDisabled` | `boolean` | `false` | 禁止滚轮调整 |
| `name` / `form` | `string` | - | 原生提交名 / 外部表单 id |
| `id` | `string` | 自动生成 | 分配给真实 Input;Input 自身 id 优先 |
| `autoFocus` / `autoComplete` | `boolean` / `string` | `false` / `"off"` | 自动聚焦 / 原生自动完成 |
| `locale` | `string` | ConfigProvider / en-US | 通道数字与单位格式 |
| `as` | `string` | `"div"` | 更换根标签;传入 data-*、class、原生属性支持自定义根元素 |
| `style` / `styleFn` | `StyleValue` 或状态函数 / 状态函数 | - | styleFn 在 style 之后合并;class 使用 Vue class 绑定 |
| `@update:modelValue` / `@change` | `(color: Color \| null) => void` | - | 提交颜色提案;父级可以拒绝;不支持 changeEnd |
`modelValue`(包括显式 null)优先于 `value`,受控值优先于 `defaultValue`。全部自身值属性省略时继承最近颜色 owner,这是本库组合扩展;显式 null 清空独立字段。父级拒绝提案后恢复接受值,并允许同一提案再次输入。
无通道时只接受 3/6 位 Hex,可省略 #,显示规范化大写 Hex;解析格式范围不等于字段文本格式范围。颜色解析错误按公共 parseColor 边界抛错。空文本提交 null,非法/不完整草稿失焦后恢复;Enter 提交草稿并保留原生表单提交,Esc 撤销草稿。IME 候选确认期间不提交;此处只有合成 composition 回归与桌面输入检查,不代表完整系统输入法验收。
通道模式使用现有通道解析:RGB 通道用 rgb、lightness 用 hsl、brightness 用 hsb;hue/saturation 在显式 rgb 时转 hsl,其他情况保留指定或接受值的 HSL/HSB 空间,alpha 保留原空间。与固定依赖可能要求显式空间不同,本库保留既有推断/纠正扩展;Props 分别约束 channel 和 colorSpace 的枚举,不额外声明二者判别联合。
通道文本显示本地化数值和单位:hue 带 °,百分比带 %。自然步长为 RGB/hue/百分比 1,alpha 模型步长 .01;输入按自然步长取整并按范围夹限。未编辑的格式化显示不会反写完整颜色精度。上/下方向键单步,Shift 或 PageUp/Down 使用通道页步长,Home/End 到边界;Hex 对应 24 位整数步长 1/10。获得焦点后纵向滚轮向下递增,向上递减;isWheelDisabled、禁用、只读和 preventDefault 阻止调整。
### 表单提交与验证
Hex 使用命名的可见文本 input:直接构造 `FormData` 会读到编辑中的原生草稿;通常 Enter/失焦先提交或恢复草稿,再由表单提交。此行为保留固定字段协议,不能把编辑中 FormData 称为接受颜色。通道模式只命名一个隐藏 input,提交接受通道数值:hue/RGB 为自然数值,saturation/lightness/brightness 和 alpha 为 0–1。通道显示与提交采用自然步长的舍入值,完整颜色对象仍保留未修改精度。
原生必填、validate、Form validationErrors、FieldError、外部 form 和 reset 复用共享字段设施;禁用字段不参与提交,只读保留提交。校验判断颜色接受值;单独读取 FormData 不会主动运行校验。受控 reset 不强制父级改变模型,会把实际 DOM 恢复为当前接受值;非受控 reset 恢复捕获初值。ColorField 不额外提交整个 owner 颜色,Picker 私有组合的完整颜色提交由 owner 负责。
### Composition Components
| Vue 部件 | 对应上游 | 属性与行为 |
| -------------------------------------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ColorFieldGroup` | ColorField.Group | 同 ColorInputGroup/ColorInputGroupRoot;variant primary(默认)/secondary、fullWidth、as、role、style/styleFn;空白点击聚焦 Input,交互前后缀保留焦点 |
| `ColorFieldInput` | ColorField.Input | 同 ColorInputGroupInput;原生 input 属性、事件、class/style;Root 内绑定颜色草稿,不使用另一个文本 v-model |
| `ColorFieldPrefix` | ColorField.Prefix | 同 ColorInputGroupPrefix;as 默认 div,其余原生属性与默认插槽 |
| `ColorFieldSuffix` | ColorField.Suffix | 同 ColorInputGroupSuffix;as 默认 div,其余原生属性与默认插槽 |
| `Label` / `Description` / `FieldError` | 同名组件 | 关联真实输入的 id、描述与错误;无需另建字段状态 |
一个 ColorField 支持一个 Input;重复挂载 Input 抛错。没有 Input 时根和内容仍可渲染,但没有可编辑/可聚焦的字段。普通 DOM/Fragment 和已知 Group 的插槽可预取输入元数据;未知组件包装不执行 setup/render 探测,其 Input 挂载后注册属性,异步包装应显式传入 Root 的 id/name/form 等公共属性。
ColorInputGroup 独立使用时是普通文本组(role=group);Input 可用字符串 v-model/defaultValue。字段内 Group 默认 role=presentation。Root 的 ARIA 和输入事件发给真实 Input,普通 data-*、class/style 发给根;Input 事件与 Root 事件合并,外部取消先于内部行为。原生事件遵循冒泡规则。`aria-label/labelledby/describedby/details`、Label 和动态辅助文本保留关联。可通过 ConfigProvider 的 dir 或 HTML dir 继承 RTL 布局。
### Render Props
| 插槽状态 | 类型 | 含义 |
| -------------------------------------------------------- | --------------- | --------------------------------- |
| `value` | `Color \| null` | 当前接受颜色 |
| `isDisabled` / `isReadOnly` / `isRequired` / `isInvalid` | `boolean` | 实际字段状态 |
| `isFocused` / `isFocusWithin` / `isFocusVisible` | `boolean` | 真实 Input/子元素焦点及焦点可见性 |
| `validationErrors` | `string[]` | 当前可见错误 |
Group 默认插槽与 styleFn 提供 isDisabled/isInvalid/isFocusWithin/isHovered。Root 实例提供 `focus()`、`element`(真实 Input)与 `color`(接受值);Group 提供 element(根 DOM)与 focus(),Input 提供 element、focus()、select()。不暴露私有 owner、事务 token 或整个字段控制器。不提供 asChild;上游 render 换标签由 as/attrs 实现。
### Color Types
```ts
import {
parseColor,
type Color,
type ColorFieldProps,
} from "@heroui-vue/components";
const color: Color = parseColor("#3B82F6");
const props: ColorFieldProps = { defaultValue: color, name: "color" };
color.toString("hex");
color.getChannelValue("red");
```
本页部件和 Props,以及 `ColorFieldRenderProps`、`ColorFieldRenderState`、`ColorFieldSlots`、`ColorFieldExpose`、`colorFieldVariants`、`colorInputGroupVariants`、`ColorFieldVariants`、`ColorInputGroupVariants` 均从包根公开。ColorInputGroup 与 ColorField 的对应部件共享实现。ColorPicker/ColorSwatchPicker 尚未公开。
## ColorField.Group Styling
使用 `.hv-color-input-group`、`__input`、`__prefix`、`__suffix` 定制各节点;primary/secondary/full-width 修饰符与上游视觉数值一致。根容器为 `.hv-color-field`。Group 负责 hover/focus-within/invalid/disabled 的样式,Input 自身去掉默认边框和焦点轮廓;焦点环展示在 Group。状态必须写在实际匹配 CSS 的节点。
```css
@layer components {
.hv-color-input-group {
border-radius: var(--radius-field);
}
.hv-color-input-group__input {
font-variant-numeric: tabular-nums;
}
}
```
## 相关组件
[ColorArea 颜色区域](/components/color-area)、[ColorSlider 颜色滑块](/components/color-slider)、[ColorSwatch 颜色色块](/components/color-swatch)。
+1 -1
View File
@@ -281,4 +281,4 @@ ColorSlider 实现 ARIA slider 模式,提供:
## 相关组件
本批次公开 ColorArea、ColorSwatch 与 ColorSlider。ColorField、ColorInputGroup、ColorPicker 与 ColorSwatchPicker 仍为私有颜色协议,尚未提供公共页面。
已公开 [ColorField 颜色输入框](/components/color-field)(含 ColorInputGroup)、[ColorArea 颜色区域](/components/color-area)、[ColorSlider 颜色滑块](/components/color-slider) 与 [ColorSwatch 颜色色块](/components/color-swatch)。ColorPicker 与 ColorSwatchPicker 仍未公开。
+1 -1
View File
@@ -152,4 +152,4 @@ ColorSwatch 组件使用以下 CSS 类([查看源码样式](https://github.com
## 相关组件
本批次公开 ColorArea 与 ColorSwatch。ColorField、ColorInputGroup、ColorPicker、ColorSlider 与 ColorSwatchPicker 仍为私有颜色协议,尚未提供公共页面。
已公开 [ColorField 颜色输入框](/components/color-field)(含 ColorInputGroup)、[ColorArea 颜色区域](/components/color-area)、[ColorSlider 颜色滑块](/components/color-slider) 与 [ColorSwatch 颜色色块](/components/color-swatch)。ColorPicker 与 ColorSwatchPicker 仍未公开。
+25
View File
@@ -0,0 +1,25 @@
<script setup lang="ts">
import { shallowRef } from "vue";
import type { Color } from "@heroui-vue/components";
import {
ColorField,
ColorFieldGroup,
ColorFieldInput,
ColorFieldPrefix,
ColorSwatch,
Label,
parseColor,
} from "@heroui-vue/components";
const color = shallowRef<Color | null>(parseColor("#0485F7"));
</script>
<template>
<ColorField class="w-[280px]" name="color" v-model="color">
<Label>颜色</Label>
<ColorFieldGroup>
<ColorFieldPrefix>
<ColorSwatch :color="color ?? undefined" size="xs" />
</ColorFieldPrefix>
<ColorFieldInput />
</ColorFieldGroup>
</ColorField>
</template>
@@ -0,0 +1,69 @@
<script setup lang="ts">
import { shallowRef } from "vue";
import type { Color } from "@heroui-vue/components";
import {
ColorField,
ColorFieldGroup,
ColorFieldInput,
ColorFieldSuffix,
ColorSwatch,
Label,
parseColor,
} from "@heroui-vue/components";
const color = shallowRef<Color | null>(parseColor("#7F007F"));
</script>
<template>
<div class="flex flex-col gap-4">
<p class="text-sm text-muted">分别编辑 HSL 通道:</p>
<div class="flex gap-4">
<ColorField
channel="hue"
class="w-[100px]"
color-space="hsl"
name="hue"
v-model="color"
>
<Label>色相</Label>
<ColorFieldGroup>
<ColorFieldInput />
</ColorFieldGroup>
</ColorField>
<ColorField
channel="saturation"
class="w-[100px]"
color-space="hsl"
name="saturation"
v-model="color"
>
<Label>饱和度</Label>
<ColorFieldGroup>
<ColorFieldInput />
<ColorFieldSuffix>
<span class="text-sm text-muted">%</span>
</ColorFieldSuffix>
</ColorFieldGroup>
</ColorField>
<ColorField
channel="lightness"
class="w-[100px]"
color-space="hsl"
name="lightness"
v-model="color"
>
<Label>明度</Label>
<ColorFieldGroup>
<ColorFieldInput />
<ColorFieldSuffix>
<span class="text-sm text-muted">%</span>
</ColorFieldSuffix>
</ColorFieldGroup>
</ColorField>
</div>
<div class="flex items-center gap-2">
<ColorSwatch :color="color ?? undefined" size="md" />
<span class="text-sm">
当前:{{ color ? color.toString("hex") : "(空)" }}
</span>
</div>
</div>
</template>
@@ -0,0 +1,41 @@
<script setup lang="ts">
import { shallowRef } from "vue";
import type { Color } from "@heroui-vue/components";
import {
Button,
ColorField,
ColorFieldGroup,
ColorFieldInput,
ColorFieldPrefix,
ColorSwatch,
Description,
Label,
parseColor,
} from "@heroui-vue/components";
const value = shallowRef<Color | null>(parseColor("#0485F7"));
</script>
<template>
<div class="flex flex-col gap-4">
<ColorField class="w-[280px]" name="color" v-model="value">
<Label>颜色</Label>
<ColorFieldGroup>
<ColorFieldPrefix>
<ColorSwatch :color="value ?? undefined" size="xs" />
</ColorFieldPrefix>
<ColorFieldInput />
</ColorFieldGroup>
<Description>
当前值:{{ value ? value.toString("hex") : "(空)" }}
</Description>
</ColorField>
<div class="flex gap-2">
<Button variant="tertiary" @click="value = parseColor('#EF4444')">
设为红色
</Button>
<Button variant="tertiary" @click="value = parseColor('#10B981')">
设为绿色
</Button>
<Button variant="tertiary" @click="value = null">清空</Button>
</div>
</div>
</template>
@@ -0,0 +1,36 @@
<script setup lang="ts">
import { shallowRef } from "vue";
import type { Color } from "@heroui-vue/components";
import {
ColorField,
ColorFieldGroup,
ColorFieldInput,
ColorFieldPrefix,
ColorSwatch,
Description,
Label,
parseColor,
} from "@heroui-vue/components";
const color = shallowRef<Color | null>(parseColor("#6366F1"));
</script>
<template>
<ColorField
class="w-full max-w-xs gap-1.5"
name="accent-color"
v-model="color"
>
<Label class="font-medium text-foreground">强调色</Label>
<Description>应用于按钮、链接和焦点环。</Description>
<ColorFieldGroup
class="rounded-xl bg-default shadow-none focus-within:ring-2 focus-within:ring-accent/15"
variant="secondary"
>
<ColorFieldPrefix>
<ColorSwatch class="rounded-md" :color="color ?? undefined" size="xs" />
</ColorFieldPrefix>
<ColorFieldInput
class="font-mono text-sm text-foreground placeholder:text-muted"
/>
</ColorFieldGroup>
</ColorField>
</template>
+32
View File
@@ -0,0 +1,32 @@
<script setup lang="ts">
import {
ColorField,
ColorFieldGroup,
ColorFieldInput,
Description,
Label,
} from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-4">
<ColorField
isDisabled
class="w-[280px]"
default-value="#0485F7"
name="color"
>
<Label>颜色</Label>
<ColorFieldGroup>
<ColorFieldInput />
</ColorFieldGroup>
<Description>该颜色字段已禁用</Description>
</ColorField>
<ColorField isDisabled class="w-[280px]" name="color-empty">
<Label>颜色</Label>
<ColorFieldGroup>
<ColorFieldInput placeholder="#000000" />
</ColorFieldGroup>
<Description>该颜色字段已禁用</Description>
</ColorField>
</div>
</template>
@@ -0,0 +1,57 @@
<script setup lang="ts">
import { shallowRef, onBeforeUnmount } from "vue";
import type { Color } from "@heroui-vue/components";
import {
Button,
ColorField,
ColorFieldGroup,
ColorFieldInput,
ColorFieldPrefix,
ColorSwatch,
Description,
Form,
Label,
} from "@heroui-vue/components";
const value = shallowRef<Color | null>(null);
const isSubmitting = shallowRef(false);
let timer: ReturnType<typeof setTimeout> | undefined;
function handleSubmit() {
if (!value.value || isSubmitting.value) return;
isSubmitting.value = true;
timer = setTimeout(() => {
console.log("已提交颜色:", { color: value.value?.toString("hex") });
value.value = null;
isSubmitting.value = false;
}, 1500);
}
onBeforeUnmount(() => clearTimeout(timer));
</script>
<template>
<Form class="flex w-[280px] flex-col gap-4" @submit.prevent="handleSubmit">
<ColorField
fullWidth
isRequired
class="w-full"
name="brand-color"
v-model="value"
>
<Label>品牌色</Label>
<ColorFieldGroup>
<ColorFieldPrefix>
<ColorSwatch :color="value ?? undefined" size="xs" />
</ColorFieldPrefix>
<ColorFieldInput placeholder="#000000" />
</ColorFieldGroup>
<Description>选择品牌主色</Description>
</ColorField>
<Button
class="w-full"
:is-disabled="!value"
:is-pending="isSubmitting"
type="submit"
variant="primary"
>
{{ isSubmitting ? "保存中…" : "保存颜色" }}
</Button>
</Form>
</template>
@@ -0,0 +1,24 @@
<script setup lang="ts">
import {
ColorField,
ColorFieldGroup,
ColorFieldInput,
Label,
} from "@heroui-vue/components";
</script>
<template>
<div class="w-[400px] space-y-4">
<ColorField fullWidth default-value="#10B981" name="color">
<Label>品牌色</Label>
<ColorFieldGroup>
<ColorFieldInput />
</ColorFieldGroup>
</ColorField>
<ColorField fullWidth default-value="#8B5CF6" name="color-with-suffix">
<Label>主题色</Label>
<ColorFieldGroup>
<ColorFieldInput />
</ColorFieldGroup>
</ColorField>
</div>
</template>
+27
View File
@@ -0,0 +1,27 @@
<script setup lang="ts">
import {
ColorField,
ColorFieldGroup,
ColorFieldInput,
FieldError,
Label,
} from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-4">
<ColorField isInvalid isRequired class="w-[280px]" name="color">
<Label>颜色</Label>
<ColorFieldGroup>
<ColorFieldInput placeholder="#000000" />
</ColorFieldGroup>
<FieldError>请输入有效的十六进制颜色</FieldError>
</ColorField>
<ColorField isInvalid class="w-[280px]" name="invalid-color">
<Label>背景色</Label>
<ColorFieldGroup>
<ColorFieldInput default-value="not-a-color" />
</ColorFieldGroup>
<FieldError>颜色格式无效,请使用十六进制(例如 #FF5733)</FieldError>
</ColorField>
</div>
</template>
@@ -0,0 +1,21 @@
<script setup lang="ts">
import {
ColorField,
ColorFieldGroup,
ColorFieldInput,
Description,
Label,
Surface,
} from "@heroui-vue/components";
</script>
<template>
<Surface class="w-[320px] p-4">
<ColorField default-value="#3B82F6" name="color">
<Label>主题色</Label>
<ColorFieldGroup variant="secondary">
<ColorFieldInput />
</ColorFieldGroup>
<Description>选择你的主题色</Description>
</ColorField>
</Surface>
</template>
@@ -0,0 +1,36 @@
<script setup lang="ts">
import { shallowRef } from "vue";
import type { Color } from "@heroui-vue/components";
import {
ColorField,
ColorFieldGroup,
ColorFieldInput,
ColorFieldPrefix,
ColorSwatch,
Label,
parseColor,
} from "@heroui-vue/components";
const color = shallowRef<Color | null>(parseColor("#0485F7"));
</script>
<template>
<ColorField
class="w-[280px]"
name="color"
as="div"
data-custom="foo"
v-slot="{ isFocused }"
v-model="color"
>
<Label>颜色</Label>
<ColorFieldGroup
as="div"
data-custom="foo"
:data-field-focused="isFocused || undefined"
>
<ColorFieldPrefix>
<ColorSwatch :color="color ?? undefined" size="xs" />
</ColorFieldPrefix>
<ColorFieldInput />
</ColorFieldGroup>
</ColorField>
</template>
+26
View File
@@ -0,0 +1,26 @@
<script setup lang="ts">
import {
ColorField,
ColorFieldGroup,
ColorFieldInput,
Description,
Label,
} from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-4">
<ColorField isRequired class="w-[280px]" name="color">
<Label>品牌色</Label>
<ColorFieldGroup>
<ColorFieldInput placeholder="#000000" />
</ColorFieldGroup>
</ColorField>
<ColorField isRequired class="w-[280px]" name="theme-color">
<Label>主题色</Label>
<ColorFieldGroup>
<ColorFieldInput placeholder="#000000" />
</ColorFieldGroup>
<Description>必填项</Description>
</ColorField>
</div>
</template>
+28
View File
@@ -0,0 +1,28 @@
<script setup lang="ts">
import {
ColorField,
ColorFieldGroup,
ColorFieldInput,
Label,
} from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-4">
<ColorField class="w-[280px]" default-value="#0485F7" name="primary-color">
<Label>主要变体</Label>
<ColorFieldGroup variant="primary">
<ColorFieldInput />
</ColorFieldGroup>
</ColorField>
<ColorField
class="w-[280px]"
default-value="#F43F5E"
name="secondary-color"
>
<Label>次要变体</Label>
<ColorFieldGroup variant="secondary">
<ColorFieldInput />
</ColorFieldGroup>
</ColorField>
</div>
</template>
@@ -0,0 +1,27 @@
<script setup lang="ts">
import {
ColorField,
ColorFieldGroup,
ColorFieldInput,
Description,
Label,
} from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-4">
<ColorField class="w-[280px]" default-value="#3B82F6" name="color">
<Label>主色</Label>
<ColorFieldGroup>
<ColorFieldInput />
</ColorFieldGroup>
<Description>输入品牌主色</Description>
</ColorField>
<ColorField class="w-[280px]" default-value="#F59E0B" name="accent-color">
<Label>强调色</Label>
<ColorFieldGroup>
<ColorFieldInput />
</ColorFieldGroup>
<Description>用于高亮与行动按钮</Description>
</ColorField>
</div>
</template>
+35 -9
View File
@@ -1,14 +1,19 @@
<script setup lang="ts">
import { shallowRef } from "vue";
import ColorField from "../../../packages/vue/src/components/color-field/ColorField.vue";
import ColorInputGroup from "../../../packages/vue/src/components/color-field/ColorInputGroup.vue";
import ColorInputGroupInput from "../../../packages/vue/src/components/color-field/ColorInputGroupInput.vue";
import Prefix from "../../../packages/vue/src/components/color-field/ColorInputGroupPrefix.vue";
import Suffix from "../../../packages/vue/src/components/color-field/ColorInputGroupSuffix.vue";
import {
ColorField,
ColorInputGroup,
ColorInputGroupInput,
ColorInputGroupPrefix as Prefix,
ColorInputGroupSuffix as Suffix,
parseColor,
type Color,
} from "@heroui-vue/components";
import Picker from "../../../packages/vue/tests/fixtures/ColorPickerComposition.vue";
import { parseColor } from "../../../packages/vue/src/components/color/value";
import { Label, Description, FieldError, Button } from "@heroui-vue/components";
const value = shallowRef(parseColor("#123456")),
const rtl = shallowRef(false);
const proposals = shallowRef(0);
const value = shallowRef<Color | null>(parseColor("#123456")),
submitted = shallowRef("尚未提交"),
channelSubmitted = shallowRef("尚未提交");
function submit(event: Event, channel = false) {
@@ -20,11 +25,13 @@ function submit(event: Event, channel = false) {
}
</script>
<template>
<main class="color-field-lab">
<main class="color-field-lab" :dir="rtl ? 'rtl' : 'ltr'">
<h1>颜色字段正式协议 · 内部验收</h1>
<p>
组合部件、原生关联、格式化通道、提交和共享颜色;公开导出与正式文档尚未接入。
组合部件、原生关联、格式化通道、提交和共享颜色;本页通过公共导出验证正式字段;Picker
保留内部组合夹具。
</p>
<Button @click="rtl = !rtl">切换 RTL</Button>
<div class="color-field-grid">
<section id="field-native">
<h2>受控 Hex / 原生 Enter</h2>
@@ -49,6 +56,25 @@ function submit(event: Event, channel = false) {
<output>接受值:{{ value?.toString("hex") ?? "empty" }}</output>
</form>
</section>
<section id="field-rejected">
<h2>受控拒绝与重试</h2>
<form @submit.prevent>
<ColorField
name="rejected"
model-value="#123456"
@change="proposals++"
>
<Label>拒绝颜色</Label>
<ColorInputGroup><ColorInputGroupInput /></ColorInputGroup>
</ColorField>
<Button type="reset">重置拒绝字段</Button>
<output>提案次数:{{ proposals }}</output>
</form>
<ColorField is-read-only default-value="#ABCDEF">
<Label>只读颜色</Label>
<ColorInputGroup><ColorInputGroupInput /></ColorInputGroup>
</ColorField>
</section>
<section id="field-channel">
<h2>百分数显示 / 小数提交</h2>
<form @submit.prevent="submit($event, true)">
@@ -53,7 +53,8 @@
========================================================================== */
.hv-color-input-group__input {
@apply flex h-full flex-1 cursor-text items-center rounded-none border-0 bg-transparent px-3 py-2 text-base shadow-none outline-none sm:text-sm;
/* Vue native input has a browser intrinsic minimum width; keep narrow channel inputs and affixes inside the group. */
@apply flex min-w-0 h-full flex-1 cursor-text items-center rounded-none border-0 bg-transparent px-3 py-2 text-base shadow-none outline-none sm:text-sm;
/* Placeholder styling */
&::placeholder {
+30
View File
@@ -1902,3 +1902,33 @@ export const rangeCalendarVariants = tv({
});
export type RangeCalendarVariants = VariantProps<typeof rangeCalendarVariants>;
/** HeroUI 3.2.6 / ce90ea3, Apache-2.0; hv namespace only. */
export const colorFieldVariants = tv({
base: "hv-color-field",
defaultVariants: { fullWidth: false },
variants: { fullWidth: { false: "", true: "hv-color-field--full-width" } },
});
export type ColorFieldVariants = VariantProps<typeof colorFieldVariants>;
export const colorInputGroupVariants = tv({
defaultVariants: { fullWidth: false, variant: "primary" },
slots: {
base: "hv-color-input-group",
input: "hv-color-input-group__input",
prefix: "hv-color-input-group__prefix",
suffix: "hv-color-input-group__suffix",
},
variants: {
fullWidth: {
false: {},
true: { base: "hv-color-input-group--full-width" },
},
variant: {
primary: { base: "hv-color-input-group--primary" },
secondary: { base: "hv-color-input-group--secondary" },
},
},
});
export type ColorInputGroupVariants = VariantProps<
typeof colorInputGroupVariants
>;
@@ -7,6 +7,7 @@ import {
type VNodeChild,
type VNode,
} from "vue";
import { colorFieldVariants } from "@heroui-vue/styles";
import { useColorField } from "./useColorField";
import type { ColorFieldProps, ColorFieldRenderState } from "./context";
import type { Color } from "../color/value";
@@ -45,6 +46,10 @@ const rendered = defineComponent({
props: ["nodes"],
setup: (p) => () => p.nodes as VNodeChild,
});
const ordinaryStyle = computed(() =>
typeof props.style === "function" ? props.style(state.value) : props.style,
);
const computedStyle = computed(() => props.styleFn?.(state.value));
const nativeEvents = new Set([
"aria-label",
"aria-labelledby",
@@ -66,7 +71,9 @@ const nativeEvents = new Set([
]);
const rootAttrs = () =>
Object.fromEntries(
Object.entries(attrs).filter(([key]) => !nativeEvents.has(key)),
Object.entries(attrs).filter(
([key]) => !key.startsWith("aria-") && !nativeEvents.has(key),
),
);
function focusin(event: FocusEvent) {
focusWithin.value = true;
@@ -83,6 +90,7 @@ function focusout(event: FocusEvent) {
defineExpose({
focus: () => control.input.value?.focus(),
element: control.input,
color: control.state.value,
});
</script>
<template>
@@ -90,13 +98,16 @@ defineExpose({
:is="as"
ref="root"
v-bind="rootAttrs()"
class="hv-color-field"
:class="{ 'hv-color-field--full-width': fullWidth }"
:class="colorFieldVariants({ fullWidth })"
:style="[ordinaryStyle, computedStyle]"
data-slot="color-field"
:data-channel="channel ?? 'hex'"
:data-disabled="disabled || undefined"
:data-readonly="readonly || undefined"
:data-required="required || undefined"
:data-focused="focused || undefined"
:data-focus-within="focusWithin || undefined"
:data-focus-visible="focusVisible || undefined"
:data-invalid="invalid || undefined"
@focusin="focusin"
@focusout="focusout"
@@ -1,18 +1,21 @@
<script setup lang="ts">
import { computed, inject, shallowRef, useAttrs } from "vue";
import type {
ColorInputGroupBaseProps,
ColorInputGroupRenderProps,
} from "./types";
import { colorInputGroupVariants } from "@heroui-vue/styles";
import { useColorFieldContext } from "./context";
import { useInheritedDisabled } from "../field/disabled";
import { textFieldContextKey } from "../textfield/context";
defineOptions({ inheritAttrs: false });
const props = withDefaults(
defineProps<{
variant?: "primary" | "secondary";
fullWidth?: boolean;
as?: string;
role?: string;
}>(),
{ variant: "primary", as: "div" },
);
const props = withDefaults(defineProps<ColorInputGroupBaseProps>(), {
variant: "primary",
as: "div",
});
defineSlots<{
default?: (state: ColorInputGroupRenderProps) => import("vue").VNode[];
}>();
const attrs = useAttrs(),
field = useColorFieldContext(),
text = inject(textFieldContextKey, undefined);
@@ -29,6 +32,16 @@ const invalid = computed(
attrs["aria-invalid"] === true ||
attrs["aria-invalid"] === "true",
);
const state = computed(() => ({
isDisabled: disabled.value,
isInvalid: invalid.value,
isFocusWithin: focused.value,
isHovered: hovered.value,
}));
const ordinaryStyle = computed(() =>
typeof props.style === "function" ? props.style(state.value) : props.style,
);
const computedStyle = computed(() => props.styleFn?.(state.value));
function click(event: MouseEvent) {
if (event.defaultPrevented || disabled.value) return;
const target = event.target as HTMLElement;
@@ -44,17 +57,23 @@ function blur(event: FocusEvent) {
if (!root.value?.contains(event.relatedTarget as Node | null))
focused.value = false;
}
defineExpose({
element: root,
focus: () =>
root.value
?.querySelector<HTMLInputElement>(
'input[data-slot="color-input-group-input"]',
)
?.focus(),
});
</script>
<template>
<component
:is="as"
ref="root"
v-bind="attrs"
class="hv-color-input-group"
:class="[
`hv-color-input-group--${variant}`,
{ 'hv-color-input-group--full-width': fullWidth },
]"
:class="colorInputGroupVariants({ variant, fullWidth }).base()"
:style="[ordinaryStyle, computedStyle]"
:role="role ?? (field ? 'presentation' : 'group')"
data-slot="color-input-group"
:data-disabled="disabled || undefined"
@@ -77,10 +77,12 @@ function inputAttrs() {
field.field.field.required.value) ||
undefined,
"aria-describedby": mergeIds(
field.nativeAttrs(attrs)["aria-describedby"] as string | undefined,
attrs["aria-describedby"] as string | undefined,
field.field.describedBy(),
),
"aria-labelledby": mergeIds(
field.nativeAttrs(attrs)["aria-labelledby"] as string | undefined,
attrs["aria-labelledby"] as string | undefined,
field.field.labelledBy(),
),
@@ -12,6 +12,10 @@ import type { ValidateResult } from "../field/context";
export interface ColorFieldProps
extends ColorModelProps, ColorTextOptions, ChoiceFieldProps {
as?: string;
style?:
| import("vue").StyleValue
| ((state: ColorFieldRenderState) => import("vue").StyleValue);
styleFn?: (state: ColorFieldRenderState) => import("vue").StyleValue;
fullWidth?: boolean;
autoFocus?: boolean;
autoComplete?: string;
@@ -0,0 +1,50 @@
import type { StyleValue, VNode } from "vue";
import type ColorField from "./ColorField.vue";
import type ColorInputGroup from "./ColorInputGroup.vue";
import type ColorInputGroupInput from "./ColorInputGroupInput.vue";
import type ColorInputGroupPrefix from "./ColorInputGroupPrefix.vue";
import type ColorInputGroupSuffix from "./ColorInputGroupSuffix.vue";
export type {
ColorFieldProps,
ColorFieldProps as ColorFieldRootProps,
ColorFieldRenderState,
ColorFieldRenderState as ColorFieldRenderProps,
} from "./context";
export interface ColorInputGroupRenderProps {
isDisabled: boolean;
isInvalid: boolean;
isFocusWithin: boolean;
isHovered: boolean;
}
export interface ColorInputGroupBaseProps {
variant?: "primary" | "secondary";
fullWidth?: boolean;
as?: string;
role?: string;
style?: StyleValue | ((state: ColorInputGroupRenderProps) => StyleValue);
styleFn?: (state: ColorInputGroupRenderProps) => StyleValue;
}
export type ColorInputGroupProps = InstanceType<
typeof ColorInputGroup
>["$props"];
export type ColorInputGroupRootProps = ColorInputGroupProps;
export type ColorFieldGroupProps = ColorInputGroupProps;
export type ColorInputGroupInputProps = InstanceType<
typeof ColorInputGroupInput
>["$props"];
export type ColorFieldInputProps = ColorInputGroupInputProps;
export type ColorInputGroupPrefixProps = InstanceType<
typeof ColorInputGroupPrefix
>["$props"];
export type ColorFieldPrefixProps = ColorInputGroupPrefixProps;
export type ColorInputGroupSuffixProps = InstanceType<
typeof ColorInputGroupSuffix
>["$props"];
export type ColorFieldSuffixProps = ColorInputGroupSuffixProps;
export type ColorFieldExpose = Pick<
InstanceType<typeof ColorField>,
"focus" | "element" | "color"
>;
export type ColorFieldSlots = {
default?: (state: import("./context").ColorFieldRenderState) => VNode[];
};
+32
View File
@@ -1290,3 +1290,35 @@ export type {
RangeCalendarCellProps,
RangeCalendarCellIndicatorProps,
} from "./types";
// ColorField and its shared ColorInputGroup parts (HeroUI ce90ea3).
export {
default as ColorField,
default as ColorFieldRoot,
} from "./components/color-field/ColorField.vue";
export {
default as ColorInputGroup,
default as ColorInputGroupRoot,
default as ColorFieldGroup,
} from "./components/color-field/ColorInputGroup.vue";
export {
default as ColorInputGroupInput,
default as ColorFieldInput,
} from "./components/color-field/ColorInputGroupInput.vue";
export {
default as ColorInputGroupPrefix,
default as ColorFieldPrefix,
} from "./components/color-field/ColorInputGroupPrefix.vue";
export {
default as ColorInputGroupSuffix,
default as ColorFieldSuffix,
} from "./components/color-field/ColorInputGroupSuffix.vue";
export type * from "./components/color-field/types";
export {
colorFieldVariants,
colorInputGroupVariants,
} from "@heroui-vue/styles";
export type {
ColorFieldVariants,
ColorInputGroupVariants,
} from "@heroui-vue/styles";
+48
View File
@@ -0,0 +1,48 @@
<script setup lang="ts">
import { shallowRef, useTemplateRef } from "vue";
import {
ColorField,
ColorFieldGroup,
ColorFieldInput,
ColorFieldPrefix,
ColorFieldSuffix,
Label,
parseColor,
type Color,
} from "@heroui-vue/components";
const color = shallowRef<Color | null>(parseColor("#123456"));
const field = useTemplateRef<InstanceType<typeof ColorField>>("field");
const input = useTemplateRef<InstanceType<typeof ColorFieldInput>>("input");
function focus() {
field.value?.focus();
field.value?.color?.toString("hex");
field.value?.element?.select();
input.value?.select();
}
</script>
<template>
<button @click="focus">聚焦</button>
<ColorField
ref="field"
v-model="color"
channel="hue"
color-space="hsl"
v-slot="state"
:style-fn="(s) => ({ opacity: s.isFocused ? 1 : 0.8 })"
>
<Label>颜色</Label>
<ColorFieldGroup variant="secondary" v-slot="group">
<ColorFieldPrefix>{{ state.value?.toString("hex") }}</ColorFieldPrefix>
<ColorFieldInput ref="input" />
<ColorFieldSuffix>{{ group.isHovered }}</ColorFieldSuffix>
</ColorFieldGroup>
</ColorField>
<!-- @vue-expect-error invalid public model -->
<ColorField :model-value="123" />
<!-- @vue-expect-error invalid public color channel -->
<ColorField channel="cyan" />
<!-- @vue-expect-error invalid public color space -->
<ColorField color-space="lab" />
<!-- @vue-expect-error unsupported group variant -->
<ColorFieldGroup variant="tertiary" />
</template>
+154
View File
@@ -0,0 +1,154 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { readFileSync } from "node:fs";
import { ColorField } from "../packages/vue/src";
import Basic from "../apps/docs/demos/color-field-basic.vue";
import Variants from "../apps/docs/demos/color-field-variants.vue";
import OnSurface from "../apps/docs/demos/color-field-on-surface.vue";
import WithDescription from "../apps/docs/demos/color-field-with-description.vue";
import Required from "../apps/docs/demos/color-field-required.vue";
import Disabled from "../apps/docs/demos/color-field-disabled.vue";
import FullWidth from "../apps/docs/demos/color-field-full-width.vue";
import Invalid from "../apps/docs/demos/color-field-invalid.vue";
import ChannelEditing from "../apps/docs/demos/color-field-channel-editing.vue";
import Controlled from "../apps/docs/demos/color-field-controlled.vue";
import FormExample from "../apps/docs/demos/color-field-form-example.vue";
import RenderFunction from "../apps/docs/demos/color-field-render-function.vue";
import CustomStyles from "../apps/docs/demos/color-field-custom-styles.vue";
const demos = {
basic: Basic,
variants: Variants,
"on-surface": OnSurface,
"with-description": WithDescription,
required: Required,
disabled: Disabled,
"full-width": FullWidth,
invalid: Invalid,
"channel-editing": ChannelEditing,
controlled: Controlled,
"form-example": FormExample,
"render-function": RenderFunction,
"custom-styles": CustomStyles,
};
const mounted: ReturnType<typeof mount>[] = [];
afterEach(() => {
mounted.splice(0).forEach((w) => w.unmount());
document.body.innerHTML = "";
vi.useRealTimers();
vi.restoreAllMocks();
});
function render(component: Parameters<typeof mount>[0]) {
const w = mount(component, { attachTo: document.body });
mounted.push(w);
return w;
}
const inputs = (w: ReturnType<typeof mount>) =>
w.findAll<HTMLInputElement>("input[type=text]");
describe("ColorField documentation", () => {
it("keeps all thirteen fixed-source previews in page order", () => {
const doc = readFileSync("apps/docs/components/color-field.md", "utf8");
expect(
[...doc.matchAll(/<ComponentPreview name="color-field-([^"]+)"/g)].map(
(m) => m[1],
),
).toEqual(Object.keys(demos));
});
for (const [name, demo] of Object.entries(demos))
it(`renders ${name} through public parts with a label for every input`, () => {
const w = render(demo);
expect(inputs(w).length).toBeGreaterThan(0);
for (const input of inputs(w))
expect(w.find(`label[for="${input.attributes("id")}"]`).exists()).toBe(
true,
);
expect(
readFileSync(`apps/docs/demos/color-field-${name}.vue`, "utf8"),
).not.toContain("packages/vue");
});
it("synchronizes basic hex editing and preview on blur", async () => {
const w = render(Basic);
expect(inputs(w)[0]!.element.value).toBe("#0485F7");
await inputs(w)[0]!.setValue("22c55e");
await inputs(w)[0]!.trigger("blur");
expect(inputs(w)[0]!.element.value).toBe("#22C55E");
expect(
w.get<HTMLElement>("[data-slot=color-swatch]").element.style
.backgroundColor,
).toBe("rgb(34, 197, 94)");
});
it("renders actual secondary, full width, disabled and invalid states", () => {
expect(
render(Variants)
.find("[data-slot=color-input-group].hv-color-input-group--secondary")
.exists(),
).toBe(true);
expect(
render(OnSurface)
.find(".hv-surface .hv-color-input-group--secondary")
.exists(),
).toBe(true);
expect(
render(FullWidth).findAll(".hv-color-field--full-width"),
).toHaveLength(2);
expect(inputs(render(Disabled)).every((i) => i.element.disabled)).toBe(
true,
);
expect(
inputs(render(Invalid)).every(
(i) => i.attributes("aria-invalid") === "true",
),
).toBe(true);
expect(inputs(render(Required)).every((i) => i.element.required)).toBe(
true,
);
});
it("updates all three HSL fields from one accepted color", async () => {
const w = render(ChannelEditing);
await inputs(w)[0]!.setValue("90");
await inputs(w)[0]!.trigger("blur");
expect(inputs(w)[0]!.element.value).toBe("90°");
expect(inputs(w)[1]!.element.value).toBe("100%");
expect(w.text()).toContain("当前:#407F00");
});
it("controlled buttons replace and clear both input and preview", async () => {
const w = render(Controlled);
await w.findAll("button")[0]!.trigger("click");
expect(inputs(w)[0]!.element.value).toBe("#EF4444");
await w.findAll("button")[1]!.trigger("click");
expect(inputs(w)[0]!.element.value).toBe("#10B981");
await w.findAll("button")[2]!.trigger("click");
expect(inputs(w)[0]!.element.value).toBe("");
expect(w.text()).toContain("(空)");
});
it("uses a live scoped slot in the custom root example", async () => {
const w = render(RenderFunction);
// Let mounted field metadata and child refs settle before exercising native focus.
await flushPromises();
inputs(w)[0]!.element.focus();
await flushPromises();
expect(w.get("[data-slot=color-field]").attributes("data-focused")).toBe(
"true",
);
expect(
w.get("[data-slot=color-input-group]").attributes("data-field-focused"),
).toBe("true");
});
it("submits the accepted form color and restores empty state after saving", async () => {
vi.useFakeTimers();
const log = vi.spyOn(console, "log").mockImplementation(() => {});
const w = render(FormExample);
expect(w.get<HTMLButtonElement>("button").element.disabled).toBe(true);
await inputs(w)[0]!.setValue("abc");
await inputs(w)[0]!.trigger("blur");
expect(w.get<HTMLButtonElement>("button").element.disabled).toBe(false);
expect(new FormData(w.get("form").element).get("brand-color")).toBe(
"#AABBCC",
);
await w.get("form").trigger("submit");
expect(w.text()).toContain("保存中…");
await vi.advanceTimersByTimeAsync(1500);
expect(log).toHaveBeenCalledWith("已提交颜色:", { color: "#AABBCC" });
expect(inputs(w)[0]!.element.value).toBe("");
expect(w.getComponent(ColorField).emitted("change")).toHaveLength(1);
});
});
+7 -5
View File
@@ -1,11 +1,13 @@
import { afterEach, describe, it, expect, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, shallowRef } from "vue";
import ColorField from "../packages/vue/src/components/color-field/ColorField.vue";
import ColorInputGroup from "../packages/vue/src/components/color-field/ColorInputGroup.vue";
import ColorInputGroupInput from "../packages/vue/src/components/color-field/ColorInputGroupInput.vue";
import Prefix from "../packages/vue/src/components/color-field/ColorInputGroupPrefix.vue";
import Suffix from "../packages/vue/src/components/color-field/ColorInputGroupSuffix.vue";
import {
ColorField,
ColorInputGroup,
ColorInputGroupInput,
ColorInputGroupPrefix as Prefix,
ColorInputGroupSuffix as Suffix,
} from "../packages/vue/src/index";
import {
Label,
Description,
+178
View File
@@ -0,0 +1,178 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, shallowRef, h } from "vue";
import * as api from "../packages/vue/src";
const mounted: ReturnType<typeof mount>[] = [];
afterEach(() => {
mounted.splice(0).forEach((w) => w.unmount());
document.body.innerHTML = "";
vi.restoreAllMocks();
});
function view(template: string, setup = () => ({})) {
const w = mount(
defineComponent({
components: {
ColorField: api.ColorField,
ColorFieldGroup: api.ColorFieldGroup,
ColorFieldInput: api.ColorFieldInput,
ColorFieldPrefix: api.ColorFieldPrefix,
ColorFieldSuffix: api.ColorFieldSuffix,
ColorInputGroup: api.ColorInputGroup,
ColorInputGroupInput: api.ColorInputGroupInput,
Label: api.Label,
Description: api.Description,
FieldError: api.FieldError,
},
setup,
template,
}),
{ attachTo: document.body },
);
mounted.push(w);
return w;
}
const control = (w: ReturnType<typeof mount>) =>
w.get<HTMLInputElement>("[data-slot=color-input-group-input]");
const body =
"<Label>颜色</Label><ColorFieldGroup><ColorFieldPrefix>#</ColorFieldPrefix><ColorFieldInput/><ColorFieldSuffix>色</ColorFieldSuffix></ColorFieldGroup><Description>帮助</Description><FieldError/>";
describe("public ColorField", () => {
it("exports aliases without creating separate implementations", () => {
expect(api.ColorFieldRoot).toBe(api.ColorField);
expect(api.ColorInputGroupRoot).toBe(api.ColorFieldGroup);
expect(api.ColorInputGroupInput).toBe(api.ColorFieldInput);
expect(api.ColorInputGroupPrefix).toBe(api.ColorFieldPrefix);
expect(api.ColorInputGroupSuffix).toBe(api.ColorFieldSuffix);
expect(api.colorFieldVariants({ fullWidth: true })).toContain(
"hv-color-field--full-width",
);
expect(
api.colorInputGroupVariants({ variant: "secondary" }).base(),
).toContain("hv-color-input-group--secondary");
});
it("routes every ARIA attribute to the input and updates root attrs reactively", async () => {
const details = shallowRef("details-a");
const w = view(
`<ColorField aria-label="颜色" aria-labelledby="external-label" aria-describedby="external-description" :aria-details="details">${body}</ColorField>`,
() => ({ details }),
);
expect(control(w).attributes("aria-details")).toBe("details-a");
expect(control(w).attributes("aria-labelledby")).toContain(
"external-label",
);
expect(control(w).attributes("aria-describedby")).toContain(
"external-description",
);
expect(
w.get("[data-slot=color-field]").attributes("aria-details"),
).toBeUndefined();
details.value = "details-b";
await flushPromises();
expect(control(w).attributes("aria-details")).toBe("details-b");
});
it("updates scoped slots, styles and focus states from the real input", async () => {
const w = view(
`<ColorField as="section" default-value="#123456" :style-fn="s => ({ opacity: s.isFocused ? '.5' : '1' })" v-slot="s"><ColorFieldGroup :style-fn="g => ({ marginTop: g.isFocusWithin ? '2px' : '0px' })"><ColorFieldInput /></ColorFieldGroup><output>{{s.isFocused}}/{{s.isFocusWithin}}</output></ColorField>`,
);
control(w).element.focus();
await flushPromises();
const root = w.get<HTMLElement>("section");
expect(root.attributes("data-focused")).toBe("true");
expect(root.attributes("data-focus-within")).toBe("true");
expect(root.element.style.opacity).toBe("0.5");
expect(
w.get<HTMLElement>("[data-slot=color-input-group]").element.style
.marginTop,
).toBe("2px");
expect(w.get("output").text()).toBe("true/true");
control(w).element.blur();
await flushPromises();
expect(w.get("output").text()).toBe("false/false");
expect(root.attributes("data-focus-within")).toBeUndefined();
});
it("exposes the actual input and color, with usable focus()", async () => {
const w = view(`<ColorField default-value="#123456">${body}</ColorField>`);
const field = w.getComponent(api.ColorField);
field.vm.focus();
await flushPromises();
expect(document.activeElement).toBe(control(w).element);
expect(field.vm.element).toBe(control(w).element);
expect(field.vm.color?.toString("hex")).toBe("#123456");
});
it("retries a rejected hex, preserves the native draft until commit and resets accepted DOM", async () => {
const w = view(
`<form><ColorField name="color" model-value="#123456">${body}</ColorField></form>`,
);
for (let i = 0; i < 2; i++) {
await control(w).setValue("abc");
expect(new FormData(w.get("form").element).get("color")).toBe("abc");
await control(w).trigger("keydown", { key: "Enter" });
expect(control(w).element.value).toBe("#123456");
}
expect(w.getComponent(api.ColorField).emitted("change")).toHaveLength(2);
await control(w).setValue("#12");
w.get("form").element.reset();
await flushPromises();
expect(control(w).element.value).toBe("#123456");
});
it("modelValue including null takes precedence over value/defaultValue", async () => {
const w = view(
`<ColorField :model-value="null" value="#abcdef" default-value="#123456">${body}</ColorField>`,
);
expect(control(w).element.value).toBe("");
await control(w).setValue("abc");
await control(w).trigger("blur");
expect(control(w).element.value).toBe("");
});
it("switches between standalone and inherited color values without leaking drafts", async () => {
const owns = shallowRef(false);
const w = view(
`<ColorField default-value="hsl(200,50%,50%)"><ColorFieldGroup><ColorFieldInput /></ColorFieldGroup><ColorField v-bind="owns ? { modelValue: '#abcdef' } : {}"><ColorFieldGroup><ColorFieldInput /></ColorFieldGroup></ColorField></ColorField>`,
() => ({ owns }),
);
const inputs = w.findAll<HTMLInputElement>("input[type=text]");
expect(inputs[1]!.element.value).toBe(inputs[0]!.element.value);
await inputs[1]!.setValue("#12");
owns.value = true;
await flushPromises();
expect(inputs[1]!.element.value).toBe("#ABCDEF");
owns.value = false;
await flushPromises();
expect(inputs[1]!.element.value).toBe(inputs[0]!.element.value);
});
it("commits composition only after candidate completion and preserves alpha when text is untouched", async () => {
const w = view(
`<ColorField default-value="hsba(270,0%,50%,.123456789)">${body}</ColorField>`,
);
await control(w).trigger("compositionstart");
await control(w).setValue("abc");
await control(w).trigger("keydown", { key: "Enter" });
expect(w.getComponent(api.ColorField).emitted("change")).toBeUndefined();
await control(w).trigger("compositionend");
await flushPromises();
await control(w).trigger("keydown", { key: "Escape" });
await control(w).trigger("blur");
expect(
w.getComponent(api.ColorField).vm.color?.getChannelValue("alpha"),
).toBe(0.123456789);
});
it("does not run unknown wrappers to discover an input", () => {
const setup = vi.fn(() => () => h(api.ColorFieldInput));
const Unknown = defineComponent({ setup });
const w = mount(api.ColorField, { slots: { default: () => h(Unknown) } });
mounted.push(w);
expect(setup).toHaveBeenCalledOnce();
expect(control(w).element.tagName).toBe("INPUT");
});
it("supports an independent group as a plain v-model text field", async () => {
const value = shallowRef("free text");
const w = view(
'<ColorInputGroup variant="secondary"><ColorInputGroupInput v-model="value" name="plain" /></ColorInputGroup>',
() => ({ value }),
);
await control(w).setValue("anything");
expect(value.value).toBe("anything");
expect(w.get("[data-slot=color-input-group]").attributes("role")).toBe(
"group",
);
});
});
+20
View File
@@ -44,6 +44,26 @@ for (const id of process.argv.slice(2)) {
assert(lib.RangeCalendar === lib.RangeCalendarRoot);
assert(lib.rangeCalendarVariants().cell() === "hv-range-calendar__cell");
}
if (id === "color-field") {
assert(lib.ColorField === lib.ColorFieldRoot);
assert(lib.ColorFieldGroup === lib.ColorInputGroup);
assert(lib.ColorFieldGroup === lib.ColorInputGroupRoot);
assert(lib.ColorFieldInput === lib.ColorInputGroupInput);
assert(lib.ColorFieldPrefix === lib.ColorInputGroupPrefix);
assert(lib.ColorFieldSuffix === lib.ColorInputGroupSuffix);
assert(
lib
.colorFieldVariants({ fullWidth: true })
.includes("hv-color-field--full-width"),
);
const slots = lib.colorInputGroupVariants({
variant: "secondary",
fullWidth: true,
});
assert(slots.base().includes("hv-color-input-group--secondary"));
assert(slots.base().includes("hv-color-input-group--full-width"));
assert(slots.input() === "hv-color-input-group__input");
}
if (id === "time-field") {
assert(lib.TimeField === lib.TimeFieldRoot);
assert(lib.TimeFieldGroup === lib.DateInputGroup);
+31 -4
View File
@@ -137,12 +137,12 @@
".hv-color-input-group__prefix",
".hv-color-input-group__suffix"
],
"absent": ["ColorField", "ColorInputGroup", "ColorPicker"]
"absent": ["ColorPicker"]
},
"color-foundation": {
"exports": [],
"css": [".hv-color-area", ".hv-color-area__thumb"],
"absent": ["ColorField", "ColorInputGroup", "ColorPicker"]
"absent": ["ColorPicker"]
},
"color-picker-protocol": {
"exports": [],
@@ -151,7 +151,7 @@
".hv-color-picker__trigger",
".hv-color-picker__popover"
],
"absent": ["ColorField", "ColorInputGroup", "ColorPicker"]
"absent": ["ColorPicker"]
},
"color-slider-foundation": {
"exports": [],
@@ -165,7 +165,7 @@
"max-height:inherit",
"overscroll-behavior:contain"
],
"absent": ["ColorField", "ColorInputGroup", "ColorPicker"]
"absent": ["ColorPicker"]
},
"date-field": {
"exports": [
@@ -462,5 +462,32 @@
"--track-start-color",
"--track-end-color"
]
},
"color-field": {
"exports": [
"ColorField",
"ColorFieldRoot",
"ColorFieldGroup",
"ColorFieldInput",
"ColorFieldPrefix",
"ColorFieldSuffix",
"ColorInputGroup",
"ColorInputGroupRoot",
"ColorInputGroupInput",
"ColorInputGroupPrefix",
"ColorInputGroupSuffix",
"colorFieldVariants",
"colorInputGroupVariants"
],
"css": [
".hv-color-field",
".hv-color-field--full-width",
".hv-color-input-group",
".hv-color-input-group--secondary",
".hv-color-input-group__input",
".hv-color-input-group__prefix",
".hv-color-input-group__suffix"
],
"absent": ["ColorPicker", "ColorSwatchPicker"]
}
}
+126
View File
@@ -0,0 +1,126 @@
import { h } from "vue";
import {
ColorField,
ColorFieldRoot,
ColorFieldGroup,
ColorFieldInput,
ColorFieldPrefix,
ColorFieldSuffix,
ColorInputGroup,
ColorInputGroupRoot,
ColorInputGroupInput,
ColorInputGroupPrefix,
ColorInputGroupSuffix,
colorFieldVariants,
colorInputGroupVariants,
parseColor,
type ColorFieldProps,
type ColorFieldRootProps,
type ColorFieldGroupProps,
type ColorFieldInputProps,
type ColorFieldPrefixProps,
type ColorFieldSuffixProps,
type ColorFieldRenderProps,
type ColorFieldRenderState,
type ColorFieldSlots,
type ColorFieldExpose,
type ColorFieldVariants,
type ColorInputGroupVariants,
type ColorInputGroupProps,
type ColorInputGroupInputProps,
type ColorInputGroupRootProps,
type ColorInputGroupPrefixProps,
type ColorInputGroupSuffixProps,
type ColorInputGroupRenderProps,
} from "@heroui-vue/components";
const props: ColorFieldProps = {
modelValue: parseColor("#123456"),
value: null,
defaultValue: "#abcdef",
channel: "hue",
colorSpace: "hsb",
name: "hue",
form: "external",
isRequired: true,
isReadOnly: false,
isWheelDisabled: true,
locale: "de-DE",
validate: (color) => (color ? true : "必填"),
styleFn: (s) => ({ opacity: s.isFocused ? 0.5 : 1 }),
};
const root: ColorFieldRootProps = props;
const group: ColorFieldGroupProps = {
variant: "secondary",
styleFn: (s) => ({ opacity: s.isFocusWithin ? 1 : 0.5 }),
};
const ig: ColorInputGroupProps = group;
const igr: ColorInputGroupRootProps = ig;
const input: ColorFieldInputProps = { defaultValue: "abc" };
const ii: ColorInputGroupInputProps = input;
const prefix: ColorFieldPrefixProps = { as: "span" };
const ip: ColorInputGroupPrefixProps = prefix;
const suffix: ColorFieldSuffixProps = { as: "span" };
const is: ColorInputGroupSuffixProps = suffix;
const slots: ColorFieldSlots = {
default: (s) => [h("span", s.value?.toString("hex"))],
};
const state: ColorFieldRenderProps = {
value: null,
isDisabled: false,
isReadOnly: false,
isRequired: false,
isInvalid: false,
isFocused: false,
isFocusWithin: false,
isFocusVisible: false,
validationErrors: [],
};
const renderState: ColorFieldRenderState = state;
const gs: ColorInputGroupRenderProps = {
isDisabled: false,
isInvalid: false,
isFocusWithin: false,
isHovered: false,
};
const variant: ColorFieldVariants = { fullWidth: true };
const iv: ColorInputGroupVariants = { variant: "secondary" };
colorFieldVariants(variant);
colorInputGroupVariants(iv).input();
h(ColorField, {
...props,
"onUpdate:modelValue": (value) => value?.toString("hex"),
});
h(ColorFieldRoot, root);
h(ColorFieldGroup, group);
h(ColorFieldInput, input);
h(ColorFieldPrefix, prefix);
h(ColorFieldSuffix, suffix);
h(ColorInputGroup, ig);
h(ColorInputGroupRoot, igr);
h(ColorInputGroupInput, ii);
h(ColorInputGroupPrefix, ip);
h(ColorInputGroupSuffix, is);
declare const field: InstanceType<typeof ColorField>;
field.focus();
field.element?.select();
field.color?.toString("hex");
const exposed: ColorFieldExpose = field;
declare const control: InstanceType<typeof ColorFieldInput>;
control.focus();
control.select();
control.element?.select();
// @ts-expect-error invalid model
const bad: ColorFieldProps = { modelValue: 123 };
// @ts-expect-error invalid channel
const badChannel: ColorFieldProps = { channel: "cyan" };
// @ts-expect-error invalid color space
h(ColorField, { colorSpace: "oklch" });
// @ts-expect-error actual public component rejects invalid model
h(ColorField, { modelValue: 123 });
// @ts-expect-error variant is primary or secondary
const badGroup: ColorFieldGroupProps = { variant: "tertiary" };
// @ts-expect-error validators receive Color/null
const badValidator: ColorFieldProps = { validate: (v: string) => true };
// @ts-expect-error no public transaction state
field.state.begin();
void [slots, renderState, gs, exposed, bad, badChannel, badGroup, badValidator];