merge: integrate reviewed ColorSwatch into main

This commit is contained in:
maoyingjie
2026-10-26 18:04:04 +08:00
30 changed files with 1578 additions and 18 deletions
+5
View File
@@ -90,6 +90,11 @@ export const componentItems: DocsItem[] = [
url: "/components/close-button",
category: "buttons",
},
{
title: "ColorSwatch 颜色色块",
url: "/components/color-swatch",
category: "colors",
},
{
title: "ComboBox 组合框",
url: "/components/combo-box",
+4
View File
@@ -11,6 +11,10 @@ description: 浏览已迁移的 Vue 组件,更多组件正在路上。
<DocsComponents category="collections" />
## 颜色
<DocsComponents category="colors" />
## 控件
<DocsComponents category="controls" />
+155
View File
@@ -0,0 +1,155 @@
---
title: ColorSwatch 颜色色块
description: 颜色值的视觉预览,并提供无障碍支持
component: color-swatch
group: 组件
---
## 用法
```vue
<script setup lang="ts">
import { ColorSwatch } from "@heroui-vue/components";
</script>
<template>
<ColorSwatch aria-label="蓝色" color="#0485F7" />
</template>
```
<ComponentPreview name="color-swatch-basic" />
## 示例
### 尺寸
<ComponentPreview name="color-swatch-sizes" />
### 形状
<ComponentPreview name="color-swatch-shapes" />
### 透明度
<ComponentPreview name="color-swatch-transparency" />
### 渲染函数
上游 `render` 用于替换根元素或附加属性;Vue 版通过 `as` 更换元素类型,或通过 `as-child` 将色块属性合并到默认插槽中唯一的自定义根元素。`data-*`、`aria-*` 与事件直接透传。
<ComponentPreview name="color-swatch-render-function" />
### 无障碍
使用 `colorName` 为颜色提供自定义可访问名称,并使用 `aria-label` 补充颜色用途的上下文。
<ComponentPreview name="color-swatch-accessibility" />
## 自定义样式
### Tailwind CSS
<ComponentPreview name="color-swatch-custom-styles" />
### 全局 CSS
可使用 `@layer components` 指令自定义 ColorSwatch 组件类。
[了解更多](https://tailwindcss.com/docs/adding-custom-styles#adding-component-classes)。
```css
@layer components {
.hv-color-swatch {
@apply border-2 border-white;
}
}
```
## 样式参考
HeroUI 遵循 [BEM](https://getbem.com/) 方法论,确保组件变体与状态可复用且易于自定义。类名前缀为 `hv-`。
### CSS 类
ColorSwatch 组件使用以下 CSS 类([查看源码样式](https://github.com/heroui-inc/heroui/blob/v3/packages/styles/components/color-swatch.css)):
#### 基础类 [!toc]
- `.hv-color-swatch` - 基础 swatch 样式,透明区域使用棋盘格背景
#### 形状类 [!toc]
- `.hv-color-swatch--circle` - 圆形(默认)
- `.hv-color-swatch--square` - 圆角方形
#### 尺寸类 [!toc]
- `.hv-color-swatch--xs` - 特小(16px)
- `.hv-color-swatch--sm` - 小(24px)
- `.hv-color-swatch--md` - 中(32px,默认)
- `.hv-color-swatch--lg` - 大(36px)
- `.hv-color-swatch--xl` - 特大(40px)
## API 参考
### ColorSwatch
| Prop | 类型 | 默认值 | 描述 |
| -------------- | --------------------------------------------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `color` | `string \| Color \| null` | - | 要展示的颜色值(hex、rgb、hsl 等),或本库 `Color` 实例。省略时继承最近的共享颜色 owner;显式 `null` 或空字符串清除继承并显示透明 |
| `colorName` | `string` | - | 颜色的可访问名称(会覆盖自动生成的描述) |
| `shape` | `"circle" \| "square"` | `"circle"` | swatch 形状 |
| `size` | `"xs" \| "sm" \| "md" \| "lg" \| "xl"` | `"md"` | swatch 尺寸 |
| `as` | `string` | `"div"` | 自定义根元素标签;对应上游 `render` 的元素替换 |
| `asChild` | `boolean` | `false` | 将色块属性合并到默认插槽中唯一的自定义根元素 |
| `style` | `CSSProperties \| ((renderProps) => CSSProperties)` | - | 行内样式或上游 style render prop;在组件基础样式之后合并 |
| `styleFn` | `(renderProps) => CSSProperties` | - | 模板中的 style 函数别名,接收解析后的 `Color`;在组件基础样式之后合并 |
| `aria-label` | `string` | - | swatch 的无障碍标签,与自动颜色名称合并为可访问名称 |
| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) |
| 默认作用域插槽 | `({ color }) => VNodeChild` | - | 接收解析后的 `Color`;与 `asChild` 组合时可替换根元素 |
`class` 遵循 Vue 的 class 绑定,可接收字符串、数组和对象,并与组件基础类合并;不要使用 React 的 `className`。`color` 省略或为 `undefined` 时继承最近的共享颜色 owner;`null` 与空字符串是显式清空。无效颜色字符串按本库 `parseColor` 边界抛出 `RangeError`。
`style` 与 `styleFn` 可同时使用,合并顺序为组件基础样式 → `style` → `styleFn`;冲突属性由 `styleFn` 覆盖,普通样式不会因函数样式存在而丢失。
组件通过 `defineExpose` 暴露 `element`,指向实际根 DOM 元素;普通 `ref` 仍指向组件实例。`aria-roledescription` 与透明颜色的自动名称随 `ConfigProvider` 的 `locale` 切换;默认 `en-US`。
### Style Render
当使用函数形式时会获得包含颜色对象在内的 render props。Vue 模板保留了 `style` 绑定并会规整函数值,因此模板中通过 `styleFn` 传入;render 函数中可直接使用 `style`,普通对象仍使用标准 `style`:
```vue
<ColorSwatch
color="#0485F7"
:style-fn="
({ color }) => ({
boxShadow: `0 4px 14px ${color.toString('css')}80`,
})
"
/>
```
`color` 对象提供例如:
- `color.toString("css")` - 返回 CSS 颜色字符串
- `color.toString("hex")` - 返回十六进制颜色字符串
- `color.getChannelValue("alpha")` - 返回 alpha 通道数值
### Color 与 parseColor
`Color`、`parseColor`、`ColorValue`、`ColorChannel` 与 `ColorSpace` 从包根导出。当前公开子集实际支持:
| 公共接口 | 类型 / 说明 |
| --------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| `parseColor(value)` | `(value: string) => Color`;支持 hex3/4/6/8、RGB/HSL/HSB(含 alpha)字符串 |
| `ColorInput` | 本库结构化颜色输入:`RGBColor \| HSLColor \| HSBColor`,用于 `new Color(...)` |
| `getColorSpace()` | 返回 `"rgb" \| "hsl" \| "hsb"` |
| `getChannels()` / `getColorChannels()` | 返回当前颜色空间的通道列表 |
| `getChannelValue(channel)` / `withChannelValue(channel, value)` | 读取或返回带新通道值的不可变颜色 |
| `withAlpha(alpha)` / `getChannelRange(channel)` / `formatChannelValue(channel, locale)` | alpha、通道范围与本地化显示 |
| `toFormat(space)` / `toString(format?)` / `clone()` / `equals(other)` | 空间转换、序列化与比较 |
未实现 React Stately `Color` 的感知颜色名、颜色名表与全量通道名称等辅助 API;`ColorSwatch` 在未提供 `colorName` 时使用透明文案或 hex/hexa 作为自动描述,不伪造完整色名表。CSS 命名色、`var()`、Lab/OKLCH 与 CSS Color 4 语法不在当前解析范围。
## 相关组件
本批次仅公开 ColorSwatch。ColorArea、ColorField、ColorPicker、ColorSlider 与 ColorSwatchPicker 仍为私有颜色协议,尚未提供公共页面。
@@ -0,0 +1,11 @@
<script setup lang="ts">
import { ColorSwatch } from "@heroui-vue/components";
</script>
<template>
<div class="flex items-center gap-3">
<ColorSwatch aria-label="主品牌色" color="#0485F7" colorName="海洋蓝" />
<ColorSwatch aria-label="错误状态色" color="#EF4444" colorName="珊瑚红" />
<ColorSwatch aria-label="警告色" color="#F59E0B" colorName="落日橙" />
</div>
</template>
+13
View File
@@ -0,0 +1,13 @@
<script setup lang="ts">
import { ColorSwatch } from "@heroui-vue/components";
</script>
<template>
<div class="flex items-center gap-3">
<ColorSwatch aria-label="蓝色" color="#0485F7" />
<ColorSwatch aria-label="红色" color="#EF4444" />
<ColorSwatch aria-label="琥珀色" color="#F59E0B" />
<ColorSwatch aria-label="绿色" color="#10B981" />
<ColorSwatch aria-label="品红" color="#D946EF" />
</div>
</template>
@@ -0,0 +1,39 @@
<script setup lang="ts">
import { ColorSwatch } from "@heroui-vue/components";
const colors = ["#0485F7", "#EF4444", "#F59E0B", "#10B981", "#D946EF"];
</script>
<template>
<div class="flex flex-col gap-8">
<div class="flex flex-col gap-2">
<span class="text-sm text-muted">发光效果</span>
<div class="flex items-center gap-4">
<ColorSwatch
v-for="color in colors"
:key="color"
:color="color"
size="xl"
:style-fn="() => ({ boxShadow: `0 0 20px 2px ${color}` })"
/>
</div>
</div>
<div class="flex flex-col gap-2">
<span class="text-sm text-muted">渐变</span>
<div class="flex items-center gap-4">
<ColorSwatch
v-for="color in colors"
:key="color"
:color="color"
size="xl"
:style-fn="
({ color: current }) => ({
background: `linear-gradient(135deg, ${current.toString('css')}, white)`,
})
"
/>
</div>
</div>
</div>
</template>
@@ -0,0 +1,25 @@
<script setup lang="ts">
import { ColorSwatch } from "@heroui-vue/components";
const colors = [
{ color: "#0485F7", label: "蓝色", name: "blue" },
{ color: "#EF4444", label: "红色", name: "red" },
{ color: "#F59E0B", label: "琥珀色", name: "amber" },
{ color: "#10B981", label: "绿色", name: "green" },
{ color: "#D946EF", label: "品红", name: "fuchsia" },
];
</script>
<template>
<div class="flex items-center gap-3">
<ColorSwatch
v-for="item in colors"
:key="item.color"
:color="item.color"
:aria-label="item.label"
as-child
>
<div :data-custom="item.name" />
</ColorSwatch>
</div>
</template>
+10
View File
@@ -0,0 +1,10 @@
<script setup lang="ts">
import { ColorSwatch } from "@heroui-vue/components";
</script>
<template>
<div class="flex items-center gap-3">
<ColorSwatch color="#0485F7" shape="circle" />
<ColorSwatch color="#0485F7" shape="square" />
</div>
</template>
+13
View File
@@ -0,0 +1,13 @@
<script setup lang="ts">
import { ColorSwatch } from "@heroui-vue/components";
</script>
<template>
<div class="flex items-center gap-3">
<ColorSwatch color="#0485F7" size="xs" />
<ColorSwatch color="#EF4444" size="sm" />
<ColorSwatch color="#F59E0B" size="md" />
<ColorSwatch color="#10B981" size="lg" />
<ColorSwatch color="#D946EF" size="xl" />
</div>
</template>
@@ -0,0 +1,13 @@
<script setup lang="ts">
import { ColorSwatch } from "@heroui-vue/components";
</script>
<template>
<div class="flex items-center gap-3">
<ColorSwatch aria-label="100% 不透明度" color="rgba(4, 133, 247, 1)" />
<ColorSwatch aria-label="75% 不透明度" color="rgba(4, 133, 247, 0.75)" />
<ColorSwatch aria-label="50% 不透明度" color="rgba(4, 133, 247, 0.5)" />
<ColorSwatch aria-label="25% 不透明度" color="rgba(4, 133, 247, 0.25)" />
<ColorSwatch aria-label="0% 不透明度" color="rgba(4, 133, 247, 0)" />
</div>
</template>
+1 -1
View File
@@ -23,7 +23,7 @@
| color-field | 私有组合协议已验证 | Root/Input及InputGroup前后缀、校验/关联、locale/草稿/IME/reset已验证;未公开包根、variants或正式13例,见COLOR-06。 |
| color-picker | 私有组合协议已验证 | Picker/Trigger/Popover共享owner、字段/轨道联动与单一提交/reset已验证;未公开包根、variants或正式6例,见COLOR-08。 |
| color-slider | 私有轨道已验证 | 自定义轨道、指针捕获/取消、键盘/方向/渐变及共享owner已验证;未公开Slider家族及正式文档,见COLOR-04。 |
| color-swatch | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| color-swatch | 已迁移(客户端) | ColorSwatch/ColorSwatchRoot、circle/square、xs–xl、透明棋盘;7/7 基线例;省略 color 继承最近共享 owner,显式值覆盖;公开 Color/parseColor 子集;render 映射 as/asChild,style 函数映射 styleFn;见 COLOR-SWATCH 结果 |
| color-swatch-picker | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| close-button | 验证中(最小实现) | 专用 CSS/变体、默认基线 CloseIcon、插槽替换图标、isDisabled、aria-label 默认 Close;onPress 由 click 适配 |
| combo-box | 已迁移(有已知差异) | ComboBox 五部件;24/24 基线例;可编辑输入 + 过滤 + 虚拟焦点、form-value key/text、menu-trigger 三态、多选 Value;见 B02 报告 |
+4 -4
View File
@@ -9,14 +9,14 @@
- 展示、按钮、导航、展开、反馈等主要家族已有公共组件与文档。
- 字段/Form、Checkbox/Radio、数值/Slider/OTP、弹层/菜单、集合/ListBox/Select、ComboBox/Autocomplete、Tag、Toast/Table已集成。
- DateField、Calendar与CalendarYearPicker已有公共组件;范围日历内核已验证,公共RangeCalendar尚未迁移。
- 颜色值/状态、Area、Slider、Field/InputGroup、Picker组合协议已有私有实现和回归夹具,尚未作为完整公共颜色家族发布。
- 兼容矩阵目前83条(包含子部件与基础设施),文档有63个组件页面。矩阵中的“验证中”保留其原有限制,不升级为完整兼容。
- ColorSwatch/ColorSwatchRoot及Color/parseColor公共子集已公开;Area、Slider、Field/InputGroup、Picker组合协议仍有私有实现和回归夹具,尚未作为完整公共颜色家族发布。
- 兼容矩阵目前83条(包含子部件与基础设施),文档有64个组件页面。矩阵中的“验证中”保留其原有限制,不升级为完整兼容。
## 尚未完成的公共家族
RangeCalendar、TimeField、DatePicker、DateRangePicker,以及ColorArea、ColorField、ColorSlider、ColorSwatch、ColorSwatchPicker、ColorPicker,共10项;已有私有内核不等于公共迁移完成。ColorInputGroup及Color/parseColor公共边界随相关颜色任务验收,不另计为这里的完整家族。
RangeCalendar、TimeField、DatePicker、DateRangePicker,以及ColorArea、ColorField、ColorSlider、ColorSwatchPicker、ColorPicker,共9项;已有私有内核不等于公共迁移完成。ColorInputGroup仍为私有协议;Color/parseColor公共边界已随COLOR-SWATCH验收。
当前可启动任务卡只有 [COLOR-SWATCH](tasks/COLOR-SWATCH.md) 和 [TIME-FIELD](tasks/TIME-FIELD.md)。一次选择一项,不自动按旧提示词并行推进;其余任务在前置合入后创建卡。
当前可启动任务卡为 [TIME-FIELD](tasks/TIME-FIELD.md);COLOR-SWATCH 已交付到任务分支,结果见 [COLOR-SWATCH](tasks/results/COLOR-SWATCH.md)。一次选择一项,不自动按旧提示词并行推进;其余任务在前置合入后创建卡。
## 当前工程边界
+4 -3
View File
@@ -1,7 +1,8 @@
# 当前工作区交接
- 任务:无进行中任务;MAINTENANCE已交付。
- 任务:无进行中任务;COLOR-SWATCH 已通过复核并合入 main。
- 工作区/分支:heroui-vue / main。
- 起点:52a0bef;结果:docs/tasks/results/MAINTENANCE.md。
- ColorSwatch实施提交:d74ad1b7118ef5ffa9938a83d1f133f09593c263;结果:docs/tasks/results/COLOR-SWATCH.md。
- 另有待单独复核的TimeField:feat/time-field,HEAD 2e2ff53;本次未将其两个提交合入main。该分支的交付入口为docs/tasks/results/TIME-FIELD.md。
这里只记录当前占用和接续入口,不重复任务状态表。单目录串行;新会话先核对git状态,有进行中任务时不切分支覆盖。支持范围统一见AGENTS.md;维护成果已合入本地main,尚未push。下一任务可从当前main新建任务分支。
单目录串行;新会话先核对git状态和任务分支。支持范围统一见AGENTS.md;不要从历史记录自动启动下一任务。
+1 -1
View File
@@ -2,7 +2,7 @@
{
"base": "b129f79366e6a526e047cec917753e1434298fa3",
"upstream": "ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960",
"status": "ready",
"status": "accepted",
"requires": [
"packages/vue/src/components/color/value.ts",
"packages/vue/src/components/color/model.ts",
+75
View File
@@ -0,0 +1,75 @@
# COLOR-SWATCH 交付 / 接续
- 分支:`feat/color-swatch-public`;起点 `60af6ee40b09965630e2b5c869d9347534372da0`(按任务要求从该提交新建,不使用旧 main)。
- 实施SHA:本文件所在提交;准确值可用 `git log -1 --format=%H -- docs/tasks/results/COLOR-SWATCH.md` 查询。
- 范围:仅客户端;未执行或声明 SSR、水合、Nuxt 服务端、逐像素自动对比、完整读屏或真机矩阵。
## 改动
- 新增 `packages/vue/src/components/color-swatch/{ColorSwatch.vue,types.ts}`:Root 与 `ColorSwatchRoot` 别名、`color`/`colorName`/`shape`/`size`/`as`/`asChild`/`style`/`styleFn`、默认作用域插槽、暴露 `element`;样式/ARIA/attrs/事件/ref 归属集中在根元素。
- 新增 `packages/styles/components/color-swatch.css` 与 `colorSwatchVariants`:基线棋盘、边框、circle/square、xs–xl 及默认值,类名改为 `hv-` 前缀;样式入口增量导入。
- 组件复用 `components/color/value.ts` 与 `model.ts`:显式 `color` 覆盖最近的共享颜色 owner,省略或 `undefined` 继承,`null`/空字符串清空;无效字符串沿用 `parseColor` 抛错。
- 公开 `Color`、`parseColor`、`ColorValue`、`ColorChannel`、`ColorSpace`、`ColorInput` 与 `ColorSwatch*` 类型;移除公共声明中的 Reka 具名类型,`Color` 构造参数改为本库结构化 `ColorInput`。
- 新增中文 `apps/docs/components/color-swatch.md`、组件总览的颜色分类与 7 个 SFC 示例(basic/sizes/shapes/transparency/render-function/accessibility/custom-styles),预览、复制、高亮共用同一文件,全部从包根导入;导航、兼容矩阵、状态与上游来源记录增量更新。
- 新增 `tests/color-swatch.test.ts`、`tests/color-swatch-demos.test.ts`、`tests/package/color-swatch-contract.ts`,并扩展现有 `tests/package/client-checks.json` 与共用 `check-client.mjs`;没有新增另一套消费者脚本。
## 验证
| 验收场景 / 复核问题 | 断言或复现步骤 | 实际结果 / 限制 |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| 行为与共享 owner | `pnpm exec vitest run tests/color-swatch.test.ts tests/color-swatch-demos.test.ts tests/color-foundation.test.ts tests/color-picker-composition.test.ts` | 67 项通过;含默认/显式/空值/无效色/透明度/动态更新/灰色hue/精度/attrs/ref/插槽/as/asChild/style/styleFn |
| 颜色协议回归 | 同一命令;另跑 `tests/color-field-protocol`、`color-input-foundation`、`color-picker-protocol`、`color-slider-foundation`、`regressions/color/*` | 10 个颜色套件 150 项通过;`Color` 构造与公共类型调整未改接受值语义 |
| 全量客户端回归 | `pnpm test` | 89 文件 / 1295 项通过,无 skip;覆盖导航/总览新增分类与两条组合回归 |
| 公开类型 | `pnpm typecheck` | 通过;正反例覆盖 shape/size/color/styleFn/ColorChannel/ColorSpace/ColorInput,无 unused `@ts-expect-error` |
| 文档生产构建 | `pnpm build:docs` | 通过;7 例由同一 SFC 进入预览/高亮 |
| 独立tarball | `node scripts/check-package.mjs color-swatch` | 通过:包根导出、`colorSwatchVariants`、CSS/棋盘/变体、`parseColor` alpha;strict NodeNext 与 bundler 契约通过;构建声明无 `reka-ui`/Wire 泄漏 |
| 真实浏览器视觉 | `HEROUI_DOCS_PORT=5185 pnpm dev`,打开 `/components/color-swatch` | 端口 5185 空闲后启动;7 个预览顺序正确;计算尺寸 16/24/32/36/40、圆形半径 8/12/16/24/24、方形 6px;棋盘与内边框存在 |
| 透明度与样式函数 | 浏览器读取实际 `backgroundColor`/`backgroundImage`/`boxShadow` | 0/25/50/75/100% 均对应 `rgba(4, 133, 247, α)`;发光 boxShadow 与渐变背景实际生效;`asChild` 根保留 `data-custom`、`role=img` 与色块类 |
| 浅/深主题 | 浏览器切换 `html.dark` 后重取计算样式 | 两种主题下色块尺寸、颜色、棋盘和边框一致;页面表格宽 732px 等于内容区、无横向溢出;控制台无错误 |
| 可访问性基础 | DOM/ARIA 检查与 `ConfigProvider locale="zh-CN"` 单测 | `role=img`、`aria-roledescription`(en/zh)、`colorName + aria-label` 合并、`aria-labelledby` 前缀、透明名称均通过;未做完整读屏矩阵 |
## 明确差异与遗留
- Vue 模板会规整保留的 `style` 函数值,因此模板中的上游 style render prop 使用 `styleFn`;在 render 代码中 `style` 仍接受函数,普通对象使用标准 `style`。
- 未移植 React Stately 的色名表/`getColorName` 等全量 Color 辅助 API;无 `colorName` 时使用透明文案或 hex/hexa 作为自动描述,并已在文档记录。
- 继承使用本库共享颜色 owner;ColorSwatchPicker 的 `ColorSwatchContext` 与其私有选择家族未迁移,当前公共消费者尚无公开 Picker owner 可组合。
- `ColorSwatchPicker`、ColorArea/ColorField/ColorPicker/ColorSlider 等公共家族仍待后续任务;本提交不自动开始下一任务。
## 集成人复核(2026-10-26,270dea5)
结论:暂不通过,先修下面同一问题表,不安排新组件。本轮未修改实现。
| ID | 来源 | 问题 / 复现 | 当前证据 |
| ---- | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| CS-1 | 原组合契约遗漏 | ColorSwatch asChild,外层aria-labelledby="caption",插槽根id="child-id";Reka保留子元素ID,但组件仍输出自身生成ID作为aria-labelledby前缀,引用不存在的节点。动态更换子ID也须保持关联。 | tests/regressions/color/swatch-composition.test.ts 第一例失败:实际v-0 caption,DOM id为child-id |
| CS-2 | Vue样式适配回归 | 模板同时传:style="{outline:'2px solid red'}"与:style-fn="()=>({opacity:0.5})",styleFn分支直接忽略标准style;两者声明均允许且没有互斥说明,调用方普通样式丢失。普通样式应与计算样式保留,并明确冲突属性优先级。 | 同文件第二例失败:outline为空;预期普通outline和函数opacity都保留 |
原4套/67项通过;新增2项均复现失败。保留这两项作为后续增量复核,不再按返修轮次新增探针或重复全库检查。CS-1修复需使用Vue公开VNode/透传能力,不能通过读取DOM后伪造ARIA或侵入私有ref结构;保留子元素/调用方ID、ref和动态更新。CS-2不需要新增另一种style API。
Color.toWire目前仍出现在公开class声明中,虽然没有泄漏Reka具名类型;它是既有桥接函数。请顺带核对是否应标为内部,而不要将其描述为完整RAC Color接口或为此重写颜色模型。本项为API边界提示,不新增本轮能力要求。
## 返修结果(CS-1 / CS-2)
- 实施:在当前 `feat/color-swatch-public` 分支修复;准确 SHA 见本文件所在提交。
- CS-1:改为一次读取默认作用域插槽的公开 VNode,取唯一有效根元素的 `id` 作为 `aria-labelledby` 前缀;优先级为子元素 `id` → 调用方 `id` → 生成 id,和 Reka Slot 的实际合并规则一致。未读取 DOM 后伪造 ARIA,未访问私有 ref 结构;子元素 id 动态更新、普通 `attrs`、`ref` 仍由公开 VNode/透传路径保留。复核用例 `tests/regressions/color/swatch-composition.test.ts` 第一例通过。
- CS-2:普通 `style` 与 `styleFn` 同时参与渲染,合并顺序为基础样式 → `style` → `styleFn`;冲突属性由 `styleFn` 覆盖。文档已明确该顺序。复核用例第二例通过。
- `Color.toWire` 仍作为既有内部桥接保留在类上并标注 `@internal`;它返回本库 `ColorInput`,不泄漏 Reka 命名类型,也未新增为文档化 RAC API。
| 检查 | 结果 |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| 两条组合回归 | `pnpm exec vitest run tests/regressions/color/swatch-composition.test.ts`:2/2 通过 |
| Swatch 定向套件 | `tests/color-swatch.test.ts`、`tests/color-swatch-demos.test.ts`:27/27 通过;任务卡五文件(含 foundation/picker 与回归)69/69 通过 |
| 全量回归 | `pnpm test`:89 文件 / 1295 项通过,无 skip |
| 类型与文档构建 | `pnpm typecheck`、`pnpm build:docs` 通过 |
| 独立产物 | `node scripts/check-package.mjs color-swatch` 通过;最终声明仍暴露 `element` 且无 Reka/Wire 泄漏 |
| 浏览器复验 | 5185 重新打开 `/components/color-swatch`:7 个预览、尺寸/圆角/透明度/棋盘、styleFn 发光/渐变、asChild `data-custom` 均正常;无控制台错误与横向溢出 |
## 集成人二次复核:通过(2026-10-26)
复核b18949c,原CS-1/CS-2均通过。CS-1仍有动态移除子id的同根因遗漏:Slot的子props.id=undefined会覆盖生成id;本次直接补齐,将最终id通过公开cloneVNode同步到实际Slot根,不操作DOM或私有ref。原组合用例追加id移除及子ref保留断言,不新增另一轮测试文件。CS-1/CS-2现均关闭。
最终5文件/69项定向回归、vue-tsc、独立color-swatch tarball的ESM/CSS及strict NodeNext/bundler正反类型通过。未重复全库/文档构建或逐页浏览器,未增加SSR专项或启动服务。补修提交见本记录所在提交;仍在feat/color-swatch-public,未合main/push。
## 集成(2026-10-26)
用户授权将已验收ColorSwatch合main并推送;实施范围截至d74ad1b。合并只涉及交接文件冲突,代码无冲突;TimeField的97263d8、2e2ff53留在feat/time-field另行复核,没有合入本次main。整合后vitest run:89文件/1295项全部通过,无skip;交接文档格式/diff检查通过。代码与已验收d74ad1b一致,未无理由重复产物构建。
+8
View File
@@ -244,3 +244,11 @@ CSS/tv 仅加 `hv-` 前缀与 Vue 状态适配,保留 Apache-2.0 来源。TagR
## B02c Autocomplete(2026-10-25)
固定 ce90ea3 的 `packages/react/src/components/autocomplete/autocomplete.tsx`、`packages/styles/components/autocomplete.css`、`packages/styles/src/components/autocomplete/autocomplete.styles.ts`、中文 `(pickers)/autocomplete.mdx` 与 `demos/cn/autocomplete` 24 例。CSS/tv 仅加 `hv-` 前缀;默认 chevron 与清除图标沿用基线 `icons.tsx` 路径。Vue 侧把 `SearchFieldInput` 组合成弹层内的 combobox 控件;弹层宽度用本批 `useTriggerWidth`(ResizeObserver)实测,不依赖 Reka 未启用的 size 中间件;未移植 RAC 的 `useFilter`(默认谓词等价)与 `Virtualizer`(用 ListBox 的 items/virtualized)。示例的本地异步源、Value 作用域插槽与虚拟化适配已在报告 12.2 逐项记录,不运行时依赖相邻仓库。
## COLOR-SWATCH ColorSwatch(2026-10-26)
固定 HeroUI 3.2.6 / `ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960`:`packages/react/src/components/color-swatch/{index.ts,color-swatch.tsx}`、`packages/styles/components/color-swatch.css`、`packages/styles/src/components/color-swatch/color-swatch.styles.ts`,中文 `(colors)/color-swatch.mdx` 与 `demos/cn/color-swatch` 全部 7 例(basic/sizes/shapes/transparency/render-function/accessibility/custom-styles)。
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 仓库。
@@ -0,0 +1,62 @@
/* Adapted from HeroUI ce90ea3, Apache-2.0; see third-party/HEROUI-LICENSE. */
/* ==========================================================================
ColorSwatch - visual preview of a color with a transparency checkerboard
========================================================================== */
.hv-color-swatch {
@apply relative box-border size-8 shrink-0;
/* Checkered background pattern for transparency */
background:
linear-gradient(var(--color-swatch-current), var(--color-swatch-current)),
repeating-conic-gradient(#efefef 0% 25%, #f7f7f7 0% 50%) 50% / 16px 16px;
/* Default border for visibility against similar backgrounds */
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.1);
}
/* Shape variants */
.hv-color-swatch--circle {
@apply rounded-2xl;
}
.hv-color-swatch--square {
@apply rounded-md;
}
/* Size variants */
.hv-color-swatch--xs {
@apply size-4;
&.hv-color-swatch--circle {
@apply rounded-lg;
}
}
.hv-color-swatch--sm {
@apply size-6;
&.hv-color-swatch--circle {
@apply rounded-xl;
}
}
.hv-color-swatch--md {
/* No additional styles — default size (32px) uses circle's base rounded-2xl */
}
.hv-color-swatch--lg {
@apply size-9;
&.hv-color-swatch--circle {
@apply rounded-3xl;
}
}
.hv-color-swatch--xl {
@apply size-10;
&.hv-color-swatch--circle {
@apply rounded-3xl;
}
}
+3
View File
@@ -179,3 +179,6 @@
@import "./components/color-input-group.css" layer(components);
@import "./components/color-picker.css" layer(components);
/* Public ColorSwatch (COLOR-SWATCH). */
@import "./components/color-swatch.css" layer(components);
+23
View File
@@ -1782,3 +1782,26 @@ export const autocompleteVariants = tv({
});
export type AutocompleteVariants = VariantProps<typeof autocompleteVariants>;
export const colorSwatchVariants = tv({
base: "hv-color-swatch",
defaultVariants: {
shape: "circle",
size: "md",
},
variants: {
shape: {
circle: "hv-color-swatch--circle",
square: "hv-color-swatch--square",
},
size: {
lg: "hv-color-swatch--lg",
md: "hv-color-swatch--md",
sm: "hv-color-swatch--sm",
xl: "hv-color-swatch--xl",
xs: "hv-color-swatch--xs",
},
},
});
export type ColorSwatchVariants = VariantProps<typeof colorSwatchVariants>;
@@ -0,0 +1,216 @@
<script setup lang="ts">
import {
Comment,
Fragment,
Text,
cloneVNode,
computed,
getCurrentInstance,
h,
isVNode,
onBeforeUpdate,
shallowRef,
useAttrs,
useId,
useSlots,
type CSSProperties,
type StyleValue,
type VNode,
type VNodeChild,
} from "vue";
import { Primitive } from "reka-ui";
import {
colorSwatchVariants,
type ColorSwatchVariants,
} from "@heroui-vue/styles";
import { useColorStateContext } from "../color/model";
import { copyColor, parseColor, type ColorValue } from "../color/value";
import { useConfig } from "../../providers/context";
import type {
ColorSwatchSlots,
ColorSwatchStyle,
ColorSwatchStyleFn,
} from "./types";
defineOptions({ inheritAttrs: false, name: "ColorSwatch" });
const props = withDefaults(
defineProps<{
/** Color string or library Color. Omitted inherits the nearest color owner. */
color?: ColorValue | null;
/** Localized accessible color name; overrides the automatic description. */
colorName?: string;
shape?: ColorSwatchVariants["shape"];
size?: ColorSwatchVariants["size"];
/** Render a different root element; corresponds to the upstream render prop. */
as?: string;
/** Merge swatch attributes onto the single default-slot root. */
asChild?: boolean;
/** Vue style binding or upstream style function, merged after base styles. */
style?: ColorSwatchStyle;
/** Template-friendly alias for the style function; receives the color. */
styleFn?: ColorSwatchStyleFn;
}>(),
{
color: undefined,
colorName: undefined,
shape: "circle",
size: "md",
as: "div",
asChild: false,
style: undefined,
styleFn: undefined,
},
);
defineSlots<ColorSwatchSlots>();
const attrs = useAttrs();
const slots = useSlots();
const instance = getCurrentInstance()!;
const owner = useColorStateContext();
const config = useConfig();
const generatedId = useId();
const element = shallowRef<HTMLElement>();
const TRANSPARENT = parseColor("#fff0");
function meaningfulVNodes(children: unknown): VNode[] {
const out: VNode[] = [];
const walk = (nodes: unknown[]) => {
for (const node of nodes) {
if (node == null || node === false || node === true) continue;
if (Array.isArray(node)) {
walk(node);
continue;
}
if (!isVNode(node)) continue;
if (node.type === Fragment) {
walk(Array.isArray(node.children) ? node.children : []);
continue;
}
if (node.type === Comment) continue;
if (node.type === Text && String(node.children ?? "").trim() === "")
continue;
out.push(node);
}
};
walk([children]);
return out;
}
function presentsColor() {
const raw = instance.vnode.props ?? {};
// `undefined` behaves as omitted so spread bindings can inherit; an explicit
// null or empty string clears the owner and renders the transparent swatch.
return Object.hasOwn(raw, "color") && raw.color !== undefined;
}
const hasOwnColor = shallowRef(presentsColor());
onBeforeUpdate(() => {
hasOwnColor.value = presentsColor();
});
const resolvedColor = computed(() => {
const candidate = hasOwnColor.value ? props.color : owner?.value.value;
return candidate == null || candidate === "" ? null : copyColor(candidate);
});
const displayColor = computed(() => resolvedColor.value ?? TRANSPARENT);
const classes = computed(() =>
colorSwatchVariants({ shape: props.shape, size: props.size }),
);
const locale = computed(() => config?.locale.value ?? "en-US");
const baseStyle = computed<CSSProperties>(() => {
const css = displayColor.value.toString("css");
return {
backgroundColor: css,
forcedColorAdjust: "none",
"--color-swatch-current": css,
} as CSSProperties;
});
const ordinaryStyle = computed<StyleValue | undefined>(() => {
const value = props.style;
return typeof value === "function"
? value({ color: displayColor.value })
: value;
});
const computedStyle = computed<StyleValue | undefined>(() =>
props.styleFn?.({ color: displayColor.value }),
);
function accessibleName() {
if (props.colorName) return props.colorName;
if (displayColor.value.getChannelValue("alpha") === 0)
return locale.value.toLowerCase().startsWith("zh") ? "透明" : "transparent";
return displayColor.value.toString(
displayColor.value.getChannelValue("alpha") === 1 ? "hex" : "hexa",
);
}
function ariaLabel() {
const explicit = attrs["aria-label"];
return [accessibleName(), explicit == null ? "" : String(explicit)]
.filter(Boolean)
.join(", ");
}
function roleDescription() {
return locale.value.toLowerCase().startsWith("zh")
? "颜色色板"
: "color swatch";
}
function setRoot(node: unknown) {
const next =
node instanceof HTMLElement
? node
: ((node as { $el?: HTMLElement } | null)?.$el ?? undefined);
if (element.value !== next) element.value = next;
}
/** Functional render layer so the default slot is read once per render. */
const Render = () => {
let children = slots.default?.({ color: displayColor.value }) as
VNodeChild | undefined;
const childNodes = props.asChild ? meaningfulVNodes(children) : undefined;
const childId = childNodes?.[0]?.props?.id;
const effectiveId =
childId ?? (attrs.id == null ? generatedId : String(attrs.id));
// Slot gives child props precedence, including an explicit undefined ID.
// Put the resolved ID on that VNode too, preserving Vue's ref and key.
if (childNodes?.length) {
childNodes[0] = cloneVNode(childNodes[0]!, { id: effectiveId });
children = childNodes;
}
const labelledBy = attrs["aria-labelledby"];
return h(
Primitive,
{
...attrs,
as: props.as,
asChild: props.asChild,
id: effectiveId,
role: "img",
"aria-roledescription": roleDescription(),
"aria-label": ariaLabel(),
"aria-labelledby": labelledBy
? `${effectiveId} ${String(labelledBy)}`
: undefined,
// Ordinary styles remain; styleFn is the computed override layer.
class: [classes.value, attrs.class],
style: [baseStyle.value, ordinaryStyle.value, computedStyle.value],
"data-slot": "color-swatch",
ref: setRoot,
},
{ default: () => children },
);
};
defineExpose({ element });
</script>
<template>
<component :is="Render" />
</template>
@@ -0,0 +1,24 @@
import type { StyleValue, VNodeChild } from "vue";
import type { Color } from "../color/value";
/** Render values shared by the style function and the default scoped slot. */
export interface ColorSwatchRenderProps {
color: Color;
}
/**
* Function form of the upstream `style` render prop. Vue's template compiler
* reserves `style` and normalizes function values away, so templates pass the
* render function through `styleFn`; render functions may pass it directly.
*/
export type ColorSwatchStyleFn = (
renderProps: ColorSwatchRenderProps,
) => StyleValue | undefined;
/** Vue style binding (object/array/string) or the upstream style function. */
export type ColorSwatchStyle = StyleValue | ColorSwatchStyleFn;
/** Default scoped slot; `asChild` merges swatch semantics onto its root. */
export interface ColorSwatchSlots {
default?: (renderProps: ColorSwatchRenderProps) => VNodeChild;
}
+39 -9
View File
@@ -3,11 +3,41 @@ import {
convertToHsl,
convertToHsb,
parseColor as parseWireColor,
type Color as WireColor,
type ColorSpace,
type ColorChannel,
} from "reka-ui";
export type { ColorSpace, ColorChannel } from "reka-ui";
/** Library color spaces; structurally identical to the Reka boundary. */
export type ColorSpace = "rgb" | "hsl" | "hsb";
export type ColorChannel =
| "red"
| "green"
| "blue"
| "hue"
| "saturation"
| "lightness"
| "brightness"
| "alpha";
export interface RGBColor {
space: "rgb";
r: number;
g: number;
b: number;
alpha: number;
}
export interface HSLColor {
space: "hsl";
h: number;
s: number;
l: number;
alpha: number;
}
export interface HSBColor {
space: "hsb";
h: number;
s: number;
b: number;
alpha: number;
}
/** Structural input accepted by the public Color constructor. */
export type ColorInput = RGBColor | HSLColor | HSBColor;
export type ColorFormat =
ColorSpace | "css" | "hex" | "hexa" | "rgba" | "hsla" | "hsba";
export type ColorAxisChannel = Exclude<ColorChannel, "alpha">;
@@ -36,8 +66,8 @@ const clamp = (value: number, max: number) =>
const round = (value: number) => Math.round(value * 100) / 100;
/** Immutable library color boundary; accepted state is never serialized through hex. */
export class Color {
readonly #value: WireColor;
constructor(value: WireColor) {
readonly #value: ColorInput;
constructor(value: ColorInput) {
const alpha = clamp(value.alpha, 1);
if (value.space === "rgb")
this.#value = {
@@ -98,8 +128,8 @@ export class Color {
: raw,
);
}
/** Internal conversion bridge, omitted from the public Color instance type. */
static toWire(value: Color): WireColor {
/** @internal Conversion bridge for library keying and tests. */
static toWire(value: Color): ColorInput {
return { ...value.#value };
}
toFormat(space: ColorSpace): Color {
@@ -191,7 +221,7 @@ export class Color {
const alpha = this.#value.alpha;
if (format === "hex" || format === "hexa") {
const v = this.toFormat("rgb").#value as Extract<
WireColor,
ColorInput,
{ space: "rgb" }
>;
const hex = (n: number) =>
+28
View File
@@ -1083,3 +1083,31 @@ export {
autocompleteVariants,
type AutocompleteVariants,
} from "@heroui-vue/styles";
export { default as ColorSwatch } from "./components/color-swatch/ColorSwatch.vue";
export { default as ColorSwatchRoot } from "./components/color-swatch/ColorSwatch.vue";
export {
colorSwatchVariants,
type ColorSwatchVariants,
} from "@heroui-vue/styles";
export {
Color,
parseColor,
type ColorAxisChannel,
type ColorChannel,
type ColorFormat,
type ColorInput,
type ColorSpace,
type ColorValue,
type HSLColor,
type HSBColor,
type RGBColor,
} from "./components/color/value";
export type {
ColorSwatchProps,
ColorSwatchRenderProps,
ColorSwatchRootProps,
ColorSwatchSlots,
ColorSwatchStyle,
ColorSwatchStyleFn,
} from "./types";
+10
View File
@@ -869,3 +869,13 @@ import type AutocompleteFilter from "./components/autocomplete/AutocompleteFilte
export type AutocompleteFilterProps = InstanceType<
typeof AutocompleteFilter
>["$props"];
import type ColorSwatch from "./components/color-swatch/ColorSwatch.vue";
export type ColorSwatchProps = InstanceType<typeof ColorSwatch>["$props"];
export type ColorSwatchRootProps = ColorSwatchProps;
export type {
ColorSwatchRenderProps,
ColorSwatchSlots,
ColorSwatchStyle,
ColorSwatchStyleFn,
} from "./components/color-swatch/types";
+194
View File
@@ -0,0 +1,194 @@
import { afterEach, describe, expect, it } from "vitest";
import { mount } from "@vue/test-utils";
import { readFileSync } from "node:fs";
import { ColorSwatch } from "../packages/vue/src";
import Basic from "../apps/docs/demos/color-swatch-basic.vue";
import Sizes from "../apps/docs/demos/color-swatch-sizes.vue";
import Shapes from "../apps/docs/demos/color-swatch-shapes.vue";
import Transparency from "../apps/docs/demos/color-swatch-transparency.vue";
import RenderFunction from "../apps/docs/demos/color-swatch-render-function.vue";
import Accessibility from "../apps/docs/demos/color-swatch-accessibility.vue";
import CustomStyles from "../apps/docs/demos/color-swatch-custom-styles.vue";
const mounted: ReturnType<typeof mount>[] = [];
function render(component: Parameters<typeof mount>[0]) {
const w = mount(component, { attachTo: document.body });
mounted.push(w);
return w;
}
afterEach(() => {
mounted.splice(0).forEach((w) => w.unmount());
document.body.innerHTML = "";
});
const previews = [
"basic",
"sizes",
"shapes",
"transparency",
"render-function",
"accessibility",
"custom-styles",
];
describe("ColorSwatch documentation demos", () => {
it("keeps the seven pinned previews in the upstream order", () => {
const document = readFileSync(
"apps/docs/components/color-swatch.md",
"utf8",
);
const names = [
...document.matchAll(/<ComponentPreview name="color-swatch-([^"]+)"/g),
].map((match) => match[1]);
expect(names).toEqual(previews);
for (const name of previews) {
const source = readFileSync(
`apps/docs/demos/color-swatch-${name}.vue`,
"utf8",
);
expect(source).toContain("<template>");
expect(source).toContain('from "@heroui-vue/components"');
expect(source).not.toContain("className");
}
});
it("renders the basic color set", () => {
const w = render(Basic);
const swatches = w.findAllComponents(ColorSwatch);
expect(swatches).toHaveLength(5);
expect(
swatches.map(
(swatch) => (swatch.element as HTMLElement).style.backgroundColor,
),
).toEqual([
"rgb(4, 133, 247)",
"rgb(239, 68, 68)",
"rgb(245, 158, 11)",
"rgb(16, 185, 129)",
"rgb(217, 70, 239)",
]);
expect(w.findAll<HTMLElement>("[data-slot=color-swatch]")).toHaveLength(5);
});
it("maps every size and both shapes to baseline classes", () => {
const sizes = render(Sizes);
const classes = sizes
.findAll<HTMLElement>("[data-slot=color-swatch]")
.map((node) =>
["xs", "sm", "md", "lg", "xl"].find((size) =>
node.classes().includes(`hv-color-swatch--${size}`),
),
);
expect(classes).toEqual(["xs", "sm", "md", "lg", "xl"]);
const shapes = render(Shapes);
const shapeNodes = shapes.findAll<HTMLElement>("[data-slot=color-swatch]");
expect(shapeNodes).toHaveLength(2);
expect(shapeNodes[0]!.classes()).toContain("hv-color-swatch--circle");
expect(shapeNodes[0]!.classes()).not.toContain("hv-color-swatch--square");
expect(shapeNodes[1]!.classes()).toContain("hv-color-swatch--square");
expect(shapeNodes[1]!.classes()).not.toContain("hv-color-swatch--circle");
});
it("renders transparency alphas on the actual swatch elements", () => {
const w = render(Transparency);
const styles = w
.findAll<HTMLElement>("[data-slot=color-swatch]")
.map((node) => node.element.style.backgroundColor);
expect(styles).toEqual([
"rgb(4, 133, 247)",
"rgba(4, 133, 247, 0.75)",
"rgba(4, 133, 247, 0.5)",
"rgba(4, 133, 247, 0.25)",
"rgba(4, 133, 247, 0)",
]);
expect(
w
.findAll<HTMLElement>("[data-slot=color-swatch]")
.map((node) => node.attributes("aria-label")),
).toEqual([
"#0485F7, 100% 不透明度",
"#0485F7BF, 75% 不透明度",
"#0485F780, 50% 不透明度",
"#0485F740, 25% 不透明度",
"transparent, 0% 不透明度",
]);
});
it("maps the render-function demo to asChild and native attributes", () => {
const w = render(RenderFunction);
const nodes = w.findAll<HTMLElement>("[data-slot=color-swatch]");
expect(nodes).toHaveLength(5);
expect(nodes.map((node) => node.attributes("data-custom"))).toEqual([
"blue",
"red",
"amber",
"green",
"fuchsia",
]);
for (const node of nodes) {
expect(node.element.tagName).toBe("DIV");
expect(node.attributes("role")).toBe("img");
expect(node.classes()).toContain("hv-color-swatch");
expect(node.element.style.backgroundColor).not.toBe("");
}
});
it("merges colorName with the contextual aria-label", () => {
const w = render(Accessibility);
expect(
w
.findAll<HTMLElement>("[data-slot=color-swatch]")
.map((node) => node.attributes("aria-label")),
).toEqual(["海洋蓝, 主品牌色", "珊瑚红, 错误状态色", "落日橙, 警告色"]);
});
it("runs both custom-style effects through the real style function", () => {
const w = render(CustomStyles);
const nodes = w.findAll<HTMLElement>("[data-slot=color-swatch]");
expect(nodes).toHaveLength(10);
expect(nodes[0]!.element.style.boxShadow).toBe("0 0 20px 2px #0485F7");
expect(nodes[4]!.element.style.boxShadow).toBe("0 0 20px 2px #D946EF");
expect(nodes[5]!.element.style.background).toBe(
"linear-gradient(135deg, rgb(4, 133, 247), white)",
);
expect(nodes[9]!.element.style.background).toBe(
"linear-gradient(135deg, rgb(217, 70, 239), white)",
);
for (const node of nodes) {
expect(
node.element.style.getPropertyValue("--color-swatch-current"),
).not.toBe("");
}
});
it("documents the Vue API and style render contract", () => {
const document = readFileSync(
"apps/docs/components/color-swatch.md",
"utf8",
);
expect(document).toContain("title: ColorSwatch 颜色色块");
expect(document).toContain("`color`");
expect(document).toContain("`colorName`");
expect(document).toContain("`shape`");
expect(document).toContain("`size`");
expect(document).toContain("`asChild`");
expect(document).toContain("`class`");
expect(document).toContain("Vue class 绑定");
expect(document).not.toMatch(/\|\s*`className`\s*\|/);
expect(document).toContain("### Style Render");
expect(document).toContain("getChannelValue");
expect(document).toContain("未实现 React Stately");
expect(document).toContain("ColorSwatchPicker");
});
it("adds ColorSwatch to the shared navigation", () => {
const navigation = readFileSync(
"apps/docs/.vitepress/theme/navigation.ts",
"utf8",
);
expect(navigation).toContain("ColorSwatch 颜色色块");
expect(navigation).toContain('url: "/components/color-swatch"');
expect(navigation).toContain('category: "colors"');
});
});
+399
View File
@@ -0,0 +1,399 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { mount } from "@vue/test-utils";
import { defineComponent, h, nextTick, ref, shallowRef } from "vue";
import {
Color,
ColorSwatch,
ColorSwatchRoot,
ConfigProvider,
colorSwatchVariants,
parseColor,
} from "../packages/vue/src";
import type {
ColorSwatchProps,
ColorSwatchRenderProps,
ColorSwatchRootProps,
ColorSwatchSlots,
ColorSwatchStyle,
ColorSwatchStyleFn,
} from "../packages/vue/src";
import ColorPickerFoundation from "../packages/vue/tests/fixtures/ColorPickerFoundation.vue";
const mounted: ReturnType<typeof mount>[] = [];
function render(
component: Parameters<typeof mount>[0],
options: Parameters<typeof mount>[1] = {},
) {
const w = mount(component, { attachTo: document.body, ...options });
mounted.push(w);
return w;
}
afterEach(() => {
mounted.splice(0).forEach((w) => w.unmount());
document.body.innerHTML = "";
vi.restoreAllMocks();
});
describe("ColorSwatch", () => {
it("renders the baseline root, defaults and transparency checker variable", () => {
const w = render(ColorSwatch, { props: { color: "#0485F7" } });
const root = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(root.element.tagName).toBe("DIV");
expect(root.attributes("role")).toBe("img");
expect(root.attributes("aria-roledescription")).toBe("color swatch");
expect(root.classes()).toEqual(
expect.arrayContaining([
"hv-color-swatch",
"hv-color-swatch--circle",
"hv-color-swatch--md",
]),
);
expect(root.element.style.backgroundColor).toBe("rgb(4, 133, 247)");
expect(root.element.style.getPropertyValue("--color-swatch-current")).toBe(
"rgb(4, 133, 247)",
);
expect(root.element.style.getPropertyValue("forced-color-adjust")).toBe(
"none",
);
});
it("falls back to a transparent swatch when color is omitted or cleared", () => {
const omitted = render(ColorSwatch);
const root = omitted.get<HTMLElement>("[data-slot=color-swatch]");
expect(root.element.style.backgroundColor).toBe("rgba(255, 255, 255, 0)");
expect(root.attributes("aria-label")).toBe("transparent");
const cleared = render(ColorSwatch, { props: { color: null } });
const clearedRoot = cleared.get<HTMLElement>("[data-slot=color-swatch]");
expect(clearedRoot.element.style.backgroundColor).toBe(
"rgba(255, 255, 255, 0)",
);
expect(clearedRoot.attributes("aria-label")).toBe("transparent");
const empty = render(ColorSwatch, { props: { color: "" } });
const emptyRoot = empty.get<HTMLElement>("[data-slot=color-swatch]");
expect(emptyRoot.element.style.backgroundColor).toBe(
"rgba(255, 255, 255, 0)",
);
});
it("accepts strings and Color instances, including alpha and fractional precision", () => {
const half = render(ColorSwatch, {
props: { color: "rgba(4, 133, 247, 0.5)" },
});
const halfRoot = half.get<HTMLElement>("[data-slot=color-swatch]");
expect(halfRoot.element.style.backgroundColor).toBe(
"rgba(4, 133, 247, 0.5)",
);
const precise = parseColor("hsb(240, 23.45678%, 70.12345%, 0.4321)");
const w = render(ColorSwatch, {
props: { color: precise },
slots: {
default: ({ color }: ColorSwatchRenderProps) =>
h(
"span",
{ "data-probe": "precision" },
[
color.getColorSpace(),
color.getChannelValue("saturation"),
color.getChannelValue("brightness"),
color.getChannelValue("alpha"),
].join(":"),
),
},
});
expect(w.get("[data-probe=precision]").text()).toBe(
"hsb:23.45678:70.12345:0.4321",
);
expect(precise.getChannelValue("alpha")).toBe(0.4321);
});
it("keeps an owned gray hue in the scoped slot while rendering its CSS color", () => {
const w = render(ColorSwatch, {
props: { color: "hsb(270, 0%, 50%)" },
slots: {
default: ({ color }: ColorSwatchRenderProps) =>
h(
"span",
{ "data-probe": "gray" },
[
color.getColorSpace(),
color.getChannelValue("hue"),
color.getChannelValue("saturation"),
color.toString("css"),
].join("|"),
),
},
});
expect(w.get("[data-probe=gray]").text()).toBe(
"hsb|270|0|rgb(128, 128, 128)",
);
});
it("updates color, styles and accessible name reactively", async () => {
const color = ref<string | Color | null>("#0485F7");
const w = render(
defineComponent({
components: { ColorSwatch },
setup: () => ({ color }),
template: `<ColorSwatch :color="color" aria-label="品牌色" />`,
}),
);
let root = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(root.element.style.backgroundColor).toBe("rgb(4, 133, 247)");
expect(root.attributes("aria-label")).toBe("#0485F7, 品牌色");
color.value = "rgba(239, 68, 68, 0.25)";
await nextTick();
root = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(root.element.style.backgroundColor).toBe("rgba(239, 68, 68, 0.25)");
color.value = null;
await nextTick();
root = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(root.element.style.backgroundColor).toBe("rgba(255, 255, 255, 0)");
expect(root.attributes("aria-label")).toBe("transparent, 品牌色");
});
it("localizes the role description and transparent name through ConfigProvider", () => {
const w = render(
defineComponent({
components: { ConfigProvider, ColorSwatch },
template: `<ConfigProvider locale="zh-CN">
<ColorSwatch color="rgba(4, 133, 247, 0)" />
</ConfigProvider>`,
}),
);
const root = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(root.attributes("aria-roledescription")).toBe("颜色色板");
expect(root.attributes("aria-label")).toBe("透明");
});
it("rejects an invalid explicit color instead of rendering a stale swatch", () => {
expect(() =>
render(ColorSwatch, { props: { color: "rebeccapurple" } }),
).toThrow(RangeError);
});
it("applies shape and size variants from the public variant function", () => {
const w = render(ColorSwatch, {
props: { color: "#EF4444", shape: "square", size: "xl" },
});
const root = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(root.classes()).toContain("hv-color-swatch--square");
expect(root.classes()).toContain("hv-color-swatch--xl");
expect(colorSwatchVariants({ shape: "square", size: "xl" })).toBe(
"hv-color-swatch hv-color-swatch--square hv-color-swatch--xl",
);
});
it("merges class arrays/objects and attrs dynamically", async () => {
const extra = ref<Record<string, unknown>>({});
const classValue = ref<unknown>("base-extra");
const w = render(
defineComponent({
components: { ColorSwatch },
setup: () => ({ extra, classValue }),
template: `<ColorSwatch color="#10B981" v-bind="extra" :class="classValue" />`,
}),
);
let root = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(root.classes()).toContain("hv-color-swatch");
expect(root.classes()).toContain("base-extra");
expect(root.attributes("title")).toBeUndefined();
extra.value = { title: "品牌绿", "data-brand": "green" };
classValue.value = ["array-extra", { "object-extra": true }];
await nextTick();
root = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(root.attributes("title")).toBe("品牌绿");
expect(root.attributes("data-brand")).toBe("green");
expect(root.classes()).toContain("array-extra");
expect(root.classes()).toContain("object-extra");
expect(root.classes()).not.toContain("base-extra");
extra.value = {};
classValue.value = undefined;
await nextTick();
root = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(root.attributes("title")).toBeUndefined();
expect(root.classes()).toContain("hv-color-swatch");
});
it("forwards DOM events and merges aria-label context", async () => {
const clicked = vi.fn();
const w = render(ColorSwatch, {
props: { color: "#F59E0B", colorName: "落日橙" },
attrs: { "aria-label": "警告色", onClick: clicked },
});
const root = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(root.attributes("aria-label")).toBe("落日橙, 警告色");
await root.trigger("click");
expect(clicked).toHaveBeenCalledTimes(1);
});
it("merges the id and aria-labelledby prefix like the baseline", () => {
const w = render(ColorSwatch, {
props: { color: "#D946EF" },
attrs: { id: "swatch-fuchsia", "aria-labelledby": "caption" },
});
const root = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(root.attributes("id")).toBe("swatch-fuchsia");
expect(root.attributes("aria-labelledby")).toBe("swatch-fuchsia caption");
});
it("supports the upstream style render function and scoped slot", () => {
const styleFn = vi.fn(({ color }: ColorSwatchRenderProps) => ({
boxShadow: `0 0 20px 2px ${color.toString("css")}`,
"--probe-color": color.toString("hex"),
}));
const w = render(ColorSwatch, {
props: { color: "#0485F7", size: "xl", styleFn },
slots: {
default: ({ color }: ColorSwatchRenderProps) =>
h("span", { "data-slot-probe": "yes" }, color.toString("hex")),
},
});
const root = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(styleFn).toHaveBeenCalled();
expect(styleFn.mock.calls[0]![0].color).toBeInstanceOf(Color);
expect(root.element.style.boxShadow).toBe("0 0 20px 2px rgb(4, 133, 247)");
expect(root.element.style.getPropertyValue("--probe-color")).toBe(
"#0485F7",
);
expect(w.get("[data-slot-probe=yes]").text()).toBe("#0485F7");
});
it("accepts the upstream style function through style in render code", () => {
const w = render(ColorSwatch, {
props: {
color: "rgba(4, 133, 247, 0.5)",
style: ({ color }: ColorSwatchRenderProps) => ({
outlineColor: color.toString("css"),
}),
},
});
const root = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(root.element.style.outlineColor).toBe("rgba(4, 133, 247, 0.5)");
});
it("merges ordinary style objects after the component style", () => {
const w = render(ColorSwatch, {
props: {
color: "#0485F7",
style: { backgroundColor: "red", outline: "1px solid black" },
},
});
const root = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(root.element.style.backgroundColor).toBe("red");
expect(root.element.style.outline).toBe("1px solid black");
expect(root.element.style.getPropertyValue("--color-swatch-current")).toBe(
"rgb(4, 133, 247)",
);
});
it("supports as, asChild and an exposed element ref", () => {
const span = render(ColorSwatch, {
props: { color: "#0485F7", as: "span" },
});
expect(
span.get<HTMLElement>("[data-slot=color-swatch]").element.tagName,
).toBe("SPAN");
const componentRef = shallowRef<InstanceType<typeof ColorSwatch>>();
const w = render(
defineComponent({
components: { ColorSwatch },
setup: () => ({ componentRef }),
template: `<ColorSwatch ref="componentRef" color="#EF4444" as-child>
<div data-custom="red" />
</ColorSwatch>`,
}),
);
const root = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(root.element.tagName).toBe("DIV");
expect(root.attributes("data-custom")).toBe("red");
expect(root.attributes("role")).toBe("img");
expect(root.classes()).toContain("hv-color-swatch");
expect(root.element.style.backgroundColor).toBe("rgb(239, 68, 68)");
expect(componentRef.value?.element).toBe(root.element);
});
it("aliases ColorSwatchRoot and exposes constrained public types", () => {
expect(ColorSwatchRoot).toBe(ColorSwatch);
const style: ColorSwatchStyle = { background: "#0485F7" };
const styleFn: ColorSwatchStyleFn = ({ color }) => ({
background: color.toString("css"),
});
const props: ColorSwatchProps = {
color: "#0485F7",
colorName: "海洋蓝",
shape: "square",
size: "sm",
as: "div",
asChild: false,
style,
styleFn,
};
const rootProps: ColorSwatchRootProps = props;
const slots: ColorSwatchSlots = {
default: ({ color }) => h("span", color.toString("hex")),
};
void [props, rootProps, slots];
// @ts-expect-error shape is constrained to circle | square
const badShape: ColorSwatchProps = { shape: "pill" };
// @ts-expect-error size is constrained to the baseline set
const badSize: ColorSwatchProps = { size: "xxl" };
// @ts-expect-error color accepts only strings, Color or null
const badColor: ColorSwatchProps = { color: 42 };
void [badShape, badSize, badColor];
});
});
describe("ColorSwatch owner inheritance", () => {
it("inherits the nearest shared owner, supports explicit overrides and dynamic owner updates", async () => {
const color = ref<string | undefined>(undefined);
const owner = ref("#0485F7");
const w = render(
defineComponent({
components: { ColorPickerFoundation, ColorSwatch },
setup: () => ({ color, owner }),
template: `<ColorPickerFoundation :model-value="owner">
<ColorSwatch :color="color" />
</ColorPickerFoundation>`,
}),
);
let root = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(root.element.style.backgroundColor).toBe("rgb(4, 133, 247)");
color.value = "#10B981";
await nextTick();
root = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(root.element.style.backgroundColor).toBe("rgb(16, 185, 129)");
color.value = undefined;
await nextTick();
root = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(root.element.style.backgroundColor).toBe("rgb(4, 133, 247)");
owner.value = "rgba(239, 68, 68, 0.5)";
await nextTick();
root = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(root.element.style.backgroundColor).toBe("rgba(239, 68, 68, 0.5)");
});
it("lets explicit null clear the owner and show transparency", async () => {
const w = render(
defineComponent({
components: { ColorPickerFoundation, ColorSwatch },
template: `<ColorPickerFoundation model-value="#0485F7">
<ColorSwatch :color="null" />
</ColorPickerFoundation>`,
}),
);
const root = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(root.element.style.backgroundColor).toBe("rgba(255, 255, 255, 0)");
expect(root.attributes("aria-label")).toBe("transparent");
});
});
+36
View File
@@ -49,6 +49,42 @@ for (const id of process.argv.slice(2)) {
.base()
.includes("hv-select--secondary"),
);
if (id === "color-swatch") {
assert(lib.ColorSwatch === lib.ColorSwatchRoot);
assert(
lib
.colorSwatchVariants({ shape: "square", size: "xl" })
.includes("hv-color-swatch--square"),
);
assert(
lib
.colorSwatchVariants({ shape: "square", size: "xl" })
.includes("hv-color-swatch--xl"),
);
assert(lib.parseColor("#f008").toString("hexa") === "#FF000088");
assert(
lib.parseColor("rgba(4, 133, 247, 0.5)").getChannelValue("alpha") === 0.5,
);
const valueDts = readFileSync(
new URL(
"./node_modules/@heroui-vue/components/dist/components/color/value.d.ts",
import.meta.url,
),
"utf8",
);
const swatchDts = readFileSync(
new URL(
"./node_modules/@heroui-vue/components/dist/components/color-swatch/ColorSwatch.vue.d.ts",
import.meta.url,
),
"utf8",
);
assert(!valueDts.includes("reka-ui"), "Color declarations leak Reka types");
assert(
!swatchDts.includes("reka-ui"),
"ColorSwatch declarations leak Reka types",
);
}
if (id === "b03-tag-error-message") {
assert(/\.hv-tag-group\s*\[data-slot=["']?error-message/.test(css));
assert(lib.tagVariants({ size: "sm" }).base().includes("hv-tag--sm"));
+17
View File
@@ -337,5 +337,22 @@
"sliderVariants"
],
"css": [".hv-slider__track", "hv-slider__thumb"]
},
"color-swatch": {
"exports": [
"ColorSwatch",
"ColorSwatchRoot",
"colorSwatchVariants",
"Color",
"parseColor"
],
"css": [
".hv-color-swatch",
".hv-color-swatch--circle",
".hv-color-swatch--square",
".hv-color-swatch--xs",
".hv-color-swatch--xl",
"repeating-conic-gradient"
]
}
}
+87
View File
@@ -0,0 +1,87 @@
import {
Color,
ColorSwatch,
ColorSwatchRoot,
colorSwatchVariants,
parseColor,
type ColorChannel,
type ColorInput,
type ColorSpace,
type ColorSwatchProps,
type ColorSwatchRenderProps,
type ColorSwatchRootProps,
type ColorSwatchSlots,
type ColorSwatchStyle,
type ColorSwatchStyleFn,
type ColorValue,
} from "@heroui-vue/components";
const color = parseColor("#0485F7");
const value: ColorValue = color;
const format: ColorSpace = "hsl";
const channel: ColorChannel = "alpha";
const input: ColorInput = { space: "rgb", r: 4, g: 133, b: 247, alpha: 1 };
const constructed = new Color(input);
const style: ColorSwatchStyle = { outline: "1px solid black" };
const styleFn: ColorSwatchStyleFn = ({ color: current }) => ({
background: current.toString("css"),
});
const styleRender: ColorSwatchStyle = ({ color: current }) => ({
background: current.toString("css"),
});
const props: ColorSwatchProps = {
color,
colorName: "海洋蓝",
shape: "square",
size: "xl",
as: "div",
asChild: false,
style,
styleFn,
};
const rootProps: ColorSwatchRootProps = props;
const inlineStyle: ColorSwatchProps = {
color: "#0485F7",
style: ({ color: current }) => ({ background: current.toString("css") }),
};
const slots: ColorSwatchSlots = {
default: ({ color: current }: ColorSwatchRenderProps) =>
current.toString("hex"),
};
// @ts-expect-error shape is constrained to circle | square
const badShape: ColorSwatchProps = { shape: "pill" };
// @ts-expect-error size is constrained to the baseline set
const badSize: ColorSwatchProps = { size: "xxl" };
// @ts-expect-error color accepts strings, Color or null
const badColor: ColorSwatchProps = { color: 42 };
// @ts-expect-error ColorChannel is the public channel union
const badChannel: ColorChannel = "yellow";
// @ts-expect-error ColorSpace is limited to rgb | hsl | hsb
const badSpace: ColorSpace = "lab";
// @ts-expect-error ColorInput requires the space discriminator
const badInput: ColorInput = { r: 1, g: 2, b: 3, alpha: 1 };
// @ts-expect-error withAlpha accepts a number
const badAlpha = color.withAlpha("0.5");
void [
ColorSwatch,
ColorSwatchRoot,
colorSwatchVariants,
value,
format,
channel,
constructed,
props,
rootProps,
styleRender,
inlineStyle,
slots,
badShape,
badSize,
badColor,
badChannel,
badSpace,
badInput,
badAlpha,
];
@@ -0,0 +1,59 @@
import { afterEach, expect, it } from "vitest";
import { mount } from "@vue/test-utils";
import { defineComponent, h, ref, nextTick } from "vue";
import { ColorSwatch } from "../../../packages/vue/src";
const wrappers: ReturnType<typeof mount>[] = [];
afterEach(() => {
wrappers.splice(0).forEach((w) => w.unmount());
document.body.innerHTML = "";
});
it("keeps asChild self-labelledby attached to the actual root ID", async () => {
const id = ref<string | undefined>("child-id");
const childRef = ref<HTMLElement | null>(null);
const w = mount(
defineComponent({
setup: () => () =>
h("div", [
h("span", { id: "caption" }, "Brand"),
h(
ColorSwatch,
{ asChild: true, color: "#0485F7", "aria-labelledby": "caption" },
{
default: () => h("div", { id: id.value, ref: childRef }),
},
),
]),
}),
{ attachTo: document.body },
);
wrappers.push(w);
const root = w.get("[data-slot=color-swatch]");
expect(root.attributes("aria-labelledby")).toBe(
`${root.attributes("id")} caption`,
);
id.value = "next-child-id";
await nextTick();
expect(root.attributes("aria-labelledby")).toBe(
`${root.attributes("id")} caption`,
);
id.value = undefined;
await nextTick();
expect(root.attributes("id")).toBeTruthy();
expect(childRef.value).toBe(root.element);
expect(root.attributes("aria-labelledby")).toBe(
`${root.attributes("id")} caption`,
);
});
it("retains ordinary template styles together with styleFn", () => {
const w = mount(
defineComponent({
components: { ColorSwatch },
template: `<ColorSwatch color="#0485F7" :style="{ outline: '2px solid red' }" :style-fn="() => ({ opacity: 0.5 })" />`,
}),
);
wrappers.push(w);
const style = (w.element as HTMLElement).style;
expect(style.outline).toBe("2px solid red");
expect(style.opacity).toBe("0.5");
});