feat: add public ColorArea components, docs, and package contract

This commit is contained in:
maoyingjie
2026-10-26 23:51:31 +08:00
parent 01882160e6
commit ae364578ce
33 changed files with 2201 additions and 151 deletions
+197
View File
@@ -0,0 +1,197 @@
import { afterEach, describe, expect, it } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { readFileSync } from "node:fs";
import { ColorArea, Select, parseColor } from "../packages/vue/src";
import Basic from "../apps/docs/demos/color-area-basic.vue";
import WithDots from "../apps/docs/demos/color-area-with-dots.vue";
import SpaceAndChannels from "../apps/docs/demos/color-area-space-and-channels.vue";
import Disabled from "../apps/docs/demos/color-area-disabled.vue";
import Controlled from "../apps/docs/demos/color-area-controlled.vue";
import RenderFunction from "../apps/docs/demos/color-area-render-function.vue";
import CustomStyles from "../apps/docs/demos/color-area-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 root = (w: ReturnType<typeof mount>) =>
w.get<HTMLElement>("[data-slot=color-area]");
const thumb = (w: ReturnType<typeof mount>) =>
w.get<HTMLElement>("[data-slot=color-area-thumb]");
const axis = (w: ReturnType<typeof mount>, name: "x" | "y") =>
w.get<HTMLInputElement>(`[data-axis="${name}"]`);
const previews = [
"basic",
"with-dots",
"space-and-channels",
"disabled",
"controlled",
"render-function",
"custom-styles",
];
describe("ColorArea documentation demos", () => {
it("keeps the seven pinned previews in the upstream order", () => {
const document = readFileSync("apps/docs/components/color-area.md", "utf8");
const names = [
...document.matchAll(/<ComponentPreview name="color-area-([^"]+)"/g),
].map((match) => match[1]);
expect(names).toEqual(previews);
for (const name of previews) {
const source = readFileSync(
`apps/docs/demos/color-area-${name}.vue`,
"utf8",
);
expect(source).toContain("<template>");
expect(source).toContain('from "@heroui-vue/components"');
expect(source).not.toContain("className");
}
});
it("renders the basic color area from the baseline default value", () => {
const w = render(Basic);
expect(root(w).classes()).toContain("hv-color-area");
expect(axis(w, "x").element.value).toBe("116");
expect(axis(w, "y").element.value).toBe("52");
expect(axis(w, "x").attributes("aria-label")).toBe("Red");
expect(axis(w, "y").attributes("aria-label")).toBe("Green");
expect(thumb(w).element.style.left).toBe(`${(116 / 255) * 100}%`);
expect(
root(w).element.style.getPropertyValue("--color-area-background"),
).toContain("linear-gradient");
});
it("applies the dots overlay variant", () => {
const w = render(WithDots);
expect(root(w).classes()).toContain("hv-color-area--show-dots");
expect(axis(w, "x").element.value).toBe("200");
expect(axis(w, "y").element.value).toBe("100");
});
it("switches color space and axes in the space-and-channels example", async () => {
const w = render(SpaceAndChannels);
const selects = w.findAllComponents(Select);
expect(selects).toHaveLength(3);
expect(w.findAll("[data-slot=color-area]")).toHaveLength(1);
expect(axis(w, "x").attributes("aria-label")).toBe("Saturation");
expect(axis(w, "y").attributes("aria-label")).toBe("Brightness");
expect(axis(w, "x").element.value).toBe("58");
expect(axis(w, "y").element.value).toBe("93");
expect(w.text()).toContain("hsb(219, 58%, 93%)");
await selects[0]!.vm.$emit("update:modelValue", "rgb");
await flushPromises();
expect(axis(w, "x").attributes("aria-label")).toBe("Blue");
expect(axis(w, "y").attributes("aria-label")).toBe("Green");
expect(w.text()).toMatch(/rgb\(/);
await w.findAllComponents(Select)[1]!.vm.$emit("update:modelValue", "red");
await flushPromises();
expect(axis(w, "x").attributes("aria-label")).toBe("Red");
expect(axis(w, "x").attributes("max")).toBe("255");
});
it("disables both axes and pointer interaction", async () => {
const w = render(Disabled);
expect(root(w).attributes("data-disabled")).toBe("true");
expect(axis(w, "x").element.disabled).toBe(true);
expect(axis(w, "y").element.disabled).toBe(true);
await axis(w, "x").trigger("keydown", { key: "ArrowRight" });
expect(w.findComponent(ColorArea).emitted("change")).toBeUndefined();
});
it("keeps the controlled swatch and hex output in sync", async () => {
const w = render(Controlled);
const swatch = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(swatch.element.style.backgroundColor).toBe(
parseColor("#9B80FF").toString("css"),
);
expect(axis(w, "x").element.value).toBe("155");
expect(axis(w, "y").element.value).toBe("128");
await axis(w, "x").trigger("keydown", { key: "ArrowRight" });
await axis(w, "x").trigger("keyup", { key: "ArrowRight" });
await flushPromises();
expect(w.text()).toContain("#9C80FF");
expect(swatch.element.style.backgroundColor).toBe(
parseColor("#9C80FF").toString("css"),
);
});
it("maps the render-function demo to asChild, as and native attributes", async () => {
const w = render(RenderFunction);
const area = root(w);
expect(area.attributes("data-custom")).toBe("slider");
expect(area.element.tagName).toBe("DIV");
expect(area.classes()).toContain("hv-color-area");
expect(area.attributes("role")).toBe("group");
const handle = thumb(w);
expect(handle.attributes("data-custom")).toBe("thumb");
expect(handle.element.tagName).toBe("SPAN");
expect(handle.classes()).toContain("hv-color-area__thumb");
expect(axis(w, "x").element.value).toBe("116");
await axis(w, "x").trigger("keydown", { key: "ArrowRight" });
await axis(w, "x").trigger("keyup", { key: "ArrowRight" });
await flushPromises();
expect(axis(w, "x").element.value).toBe("117");
});
it("merges the custom style classes onto the real parts", () => {
const w = render(CustomStyles);
const area = root(w);
const handle = thumb(w);
for (const name of ["size-44", "rounded-3xl", "hv-color-area"]) {
expect(area.classes()).toContain(name);
}
for (const name of [
"size-5",
"rounded-full",
"border-4",
"border-white",
"hv-color-area__thumb",
]) {
expect(handle.classes()).toContain(name);
}
});
it("documents the Vue API, adaptation range and related state", () => {
const document = readFileSync("apps/docs/components/color-area.md", "utf8");
expect(document).toContain("title: ColorArea 颜色区域");
expect(document).toContain("ColorAreaThumb");
expect(document).toContain("`colorSpace`");
expect(document).toContain("`xChannel`");
expect(document).toContain("`yChannel`");
expect(document).toContain("`showDots`");
expect(document).toContain("`asChild`");
expect(document).toContain("`styleFn`");
expect(document).toContain("`isReadOnly`");
expect(document).toContain("`xName` / `yName`");
expect(document).toContain("ColorAreaRenderProps");
expect(document).toContain("changeEnd");
expect(document).not.toMatch(/\|\s*`className`\s*\|/);
expect(document).not.toContain("### ColorArea.Thumb");
expect(document).toContain("ColorField");
expect(document).toContain("仍为私有颜色协议");
});
it("adds ColorArea to the shared navigation before ColorSwatch", () => {
const navigation = readFileSync(
"apps/docs/.vitepress/theme/navigation.ts",
"utf8",
);
const area = navigation.indexOf("ColorArea 颜色区域");
const swatch = navigation.indexOf("ColorSwatch 颜色色块");
expect(area).toBeGreaterThan(-1);
expect(swatch).toBeGreaterThan(area);
expect(navigation).toContain('url: "/components/color-area"');
expect(navigation).toContain('category: "colors"');
});
});
+620
View File
@@ -0,0 +1,620 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, ref, shallowRef } from "vue";
import {
ColorArea,
ColorAreaRoot,
ColorAreaThumb,
ColorSwatch,
ConfigProvider,
colorAreaVariants,
parseColor,
type Color,
} 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;
}
function area(
props: Record<string, unknown> = {},
template = '<ColorArea v-bind="props"><ColorAreaThumb /></ColorArea>',
setup: () => Record<string, unknown> = () => ({}),
) {
return render(
defineComponent({
components: { ColorArea, ColorAreaThumb },
setup: () => ({ props, ...setup() }),
template,
}),
);
}
afterEach(() => {
mounted.splice(0).forEach((w) => w.unmount());
document.body.innerHTML = "";
vi.restoreAllMocks();
});
const root = (w: ReturnType<typeof mount>) =>
w.get<HTMLElement>("[data-slot=color-area]");
const thumb = (w: ReturnType<typeof mount>) =>
w.get<HTMLElement>("[data-slot=color-area-thumb]");
const x = (w: ReturnType<typeof mount>) =>
w.get<HTMLInputElement>('[data-axis="x"]');
const y = (w: ReturnType<typeof mount>) =>
w.get<HTMLInputElement>('[data-axis="y"]');
const axisValue = (w: ReturnType<typeof mount>, axis: "x" | "y") =>
w.get<HTMLInputElement>(`[data-axis="${axis}"]`).element.value;
const thumbColor = (w: ReturnType<typeof mount>) =>
thumb(w).element.style.getPropertyValue("--color-area-thumb-color");
const emitted = (w: ReturnType<typeof mount>, name: string) =>
w.findComponent(ColorArea).emitted(name) ?? [];
async function key(
w: ReturnType<typeof mount>,
name: string,
up = true,
extra = {},
axis: "x" | "y" = "x",
) {
const input = w.get(`[data-axis="${axis}"]`);
await input.trigger("keydown", { key: name, ...extra });
if (up) await input.trigger("keyup", { key: name, ...extra });
await flushPromises();
}
function geometry(
w: ReturnType<typeof mount>,
selector = "[data-slot=color-area]",
) {
const node = w.get<HTMLElement>(selector).element;
let captured: number | undefined;
Object.defineProperties(node, {
offsetWidth: { get: () => 224, configurable: true },
offsetHeight: { get: () => 224, configurable: true },
});
vi.spyOn(node, "getBoundingClientRect").mockReturnValue({
left: 0,
top: 0,
width: 224,
height: 224,
right: 224,
bottom: 224,
x: 0,
y: 0,
toJSON: () => ({}),
});
node.setPointerCapture = vi.fn((id) => {
captured = id;
});
node.hasPointerCapture = vi.fn((id) => captured === id);
node.releasePointerCapture = vi.fn(() => {
captured = undefined;
});
return node;
}
async function pointer(node: Element, type: string, extra = {}) {
const event = new Event(type, { bubbles: true, cancelable: true });
Object.assign(event, {
pointerId: 1,
pointerType: "mouse",
isPrimary: true,
button: 0,
clientX: 112,
clientY: 112,
...extra,
});
node.dispatchEvent(event);
await flushPromises();
return event;
}
describe("ColorArea public contract", () => {
it("renders the baseline root, thumb, two axes and background variable", () => {
const w = area({ defaultValue: "hsl(200, 100%, 50%)" });
expect(ColorAreaRoot).toBe(ColorArea);
const node = root(w);
expect(node.attributes("role")).toBe("group");
expect(node.attributes("dir")).toBe("ltr");
expect(node.classes()).toEqual(expect.arrayContaining(["hv-color-area"]));
expect(node.classes()).not.toContain("hv-color-area--show-dots");
expect(
node.element.style.getPropertyValue("--color-area-background"),
).toContain("linear-gradient");
expect(node.element.style.backgroundBlendMode).toBe("normal");
const handle = thumb(w);
expect(handle.classes()).toContain("hv-color-area__thumb");
expect(handle.element.tagName).toBe("DIV");
expect(parseFloat(handle.element.style.left)).toBeCloseTo(
(200 / 360) * 100,
);
expect(handle.element.style.top).toBe("0%");
expect(handle.element.style.transform).toBe("translate(-50%, -50%)");
expect(
handle.element.style.getPropertyValue("--color-area-thumb-color"),
).toBe(parseColor("hsl(200, 100%, 50%)").toString("css"));
expect(x(w).attributes("type")).toBe("range");
expect(x(w).attributes("step")).toBe("any");
expect(x(w).attributes("aria-label")).toBe("Hue");
expect(x(w).attributes("aria-valuetext")).toBe("200°");
expect(x(w).attributes("min")).toBe("0");
expect(x(w).attributes("max")).toBe("360");
expect(x(w).attributes("tabindex")).toBe("0");
expect(y(w).attributes("aria-label")).toBe("Saturation");
expect(y(w).attributes("aria-orientation")).toBe("vertical");
expect(y(w).attributes("tabindex")).toBe("-1");
expect(x(w).element.value).toBe("200");
expect(y(w).element.value).toBe("100");
});
it("maps showDots to the variant classes", () => {
const w = area({ defaultValue: "#ff0000", showDots: true });
expect(root(w).classes()).toContain("hv-color-area--show-dots");
expect(colorAreaVariants({ showDots: true }).base()).toContain(
"hv-color-area--show-dots",
);
expect(colorAreaVariants().thumb()).toBe("hv-color-area__thumb");
});
it("updates an uncontrolled area through the native axes and commits once", async () => {
const w = area({
defaultValue: "hsb(240, 50%, 50%)",
xChannel: "saturation",
yChannel: "brightness",
});
await key(w, "ArrowRight", false);
expect(x(w).element.value).toBe("51");
expect(thumb(w).element.style.left).toBe("51%");
expect(emitted(w, "update:modelValue")).toHaveLength(1);
expect(emitted(w, "change")).toHaveLength(1);
expect(emitted(w, "changeEnd")).toHaveLength(0);
await x(w).trigger("keyup", { key: "ArrowRight" });
expect(emitted(w, "changeEnd")).toHaveLength(1);
const value = emitted(w, "changeEnd")[0]![0] as Color;
expect(value.getChannelValue("saturation")).toBe(51);
expect(value.getChannelValue("alpha")).toBe(1);
await key(w, "ArrowUp", true, {}, "y");
expect(y(w).element.value).toBe("51");
expect(x(w).attributes("tabindex")).toBe("-1");
expect(y(w).attributes("tabindex")).toBe("0");
expect(document.activeElement).toBe(y(w).element);
});
it("keeps the accepted value on controlled rejection and allows retries", async () => {
const value = shallowRef(parseColor("hsb(240,50%,50%)"));
const w = render(
defineComponent({
components: { ColorArea, ColorAreaThumb },
setup: () => ({ value }),
template: `<ColorArea :model-value="value" x-channel="saturation" y-channel="brightness"><ColorAreaThumb /></ColorArea>`,
}),
);
for (let i = 0; i < 2; i++) await key(w, "ArrowRight");
expect(emitted(w, "change")).toHaveLength(2);
expect(
(emitted(w, "change")[1]![0] as Color).getChannelValue("saturation"),
).toBe(51);
expect(x(w).element.value).toBe("50");
expect(thumb(w).element.style.left).toBe("50%");
value.value = parseColor("hsb(240,80%,70%)");
await flushPromises();
expect(x(w).element.value).toBe("80");
expect(y(w).element.value).toBe("70");
expect(thumb(w).element.style.left).toBe("80%");
expect(parseFloat(thumb(w).element.style.top)).toBeCloseTo(30);
});
it("commits pointer drags once and cleans up cancellations", async () => {
const w = area({
defaultValue: "hsb(240, 50%, 50%)",
xChannel: "saturation",
yChannel: "brightness",
});
const node = geometry(w);
await pointer(node, "pointerdown", { clientX: 112, clientY: 112 });
await pointer(node, "pointermove", { clientX: 168, clientY: 112 });
await pointer(node, "pointerup", { clientX: 168, clientY: 112 });
expect(node.setPointerCapture).toHaveBeenCalledWith(1);
expect(node.releasePointerCapture).toHaveBeenCalledWith(1);
expect(emitted(w, "change")).toHaveLength(1);
expect(emitted(w, "changeEnd")).toHaveLength(1);
expect(
(emitted(w, "changeEnd")[0]![0] as Color).getChannelValue("saturation"),
).toBe(75);
const cancel = area({
colorSpace: "hsb",
xChannel: "saturation",
yChannel: "brightness",
});
const cancelled = geometry(cancel);
await pointer(cancelled, "pointerdown");
await pointer(cancelled, "pointermove", { clientX: 168 });
await pointer(cancelled, "pointercancel");
expect(emitted(cancel, "changeEnd")).toHaveLength(0);
expect(cancelled.releasePointerCapture).toHaveBeenCalledWith(1);
});
it("honors disabled and read-only permissions", async () => {
const disabled = area({ isDisabled: true, defaultValue: "#ff0000" });
expect(root(disabled).attributes("data-disabled")).toBe("true");
expect(thumb(disabled).attributes("data-disabled")).toBe("true");
expect(x(disabled).attributes()).toHaveProperty("disabled");
const node = geometry(disabled);
await pointer(node, "pointerdown");
await key(disabled, "ArrowRight");
expect(emitted(disabled, "change")).toHaveLength(0);
expect(node.setPointerCapture).not.toHaveBeenCalled();
const readOnly = area({ isReadOnly: true, defaultValue: "#ff0000" });
expect(root(readOnly).attributes("data-readonly")).toBe("true");
expect(x(readOnly).attributes("aria-readonly")).toBe("true");
expect(x(readOnly).attributes()).not.toHaveProperty("disabled");
await key(readOnly, "ArrowRight");
expect(emitted(readOnly, "change")).toHaveLength(0);
});
it("supports channels, color spaces and locale-aware labels", () => {
const rgb = area({
colorSpace: "rgb",
defaultValue: "rgb(10, 20, 30)",
});
expect(x(rgb).attributes("aria-label")).toBe("Red");
expect(y(rgb).attributes("aria-label")).toBe("Green");
expect(x(rgb).attributes("max")).toBe("255");
expect(x(rgb).element.value).toBe("10");
expect(thumb(rgb).element.style.left).toBe(`${(10 / 255) * 100}%`);
const zh = render(
defineComponent({
components: { ConfigProvider, ColorArea, ColorAreaThumb },
template: `<ConfigProvider locale="zh-CN" dir="rtl">
<ColorArea default-value="hsb(240,25%,50%)" x-channel="saturation" y-channel="brightness">
<ColorAreaThumb />
</ColorArea>
</ConfigProvider>`,
}),
);
expect(root(zh).attributes("aria-label")).toBe("颜色区域");
expect(root(zh).attributes("dir")).toBe("rtl");
expect(x(zh).attributes("aria-label")).toBe("饱和度");
expect(y(zh).attributes("aria-label")).toBe("明度");
expect(x(zh).attributes("aria-valuetext")).toBe("25%");
expect(thumb(zh).element.style.left).toBe("75%");
expect(
root(zh).element.style.getPropertyValue("--color-area-background"),
).toContain("to left");
});
it("supports as, asChild, class, style, styleFn and exposed state", () => {
const styleFn = vi.fn(({ color }: { color: Color }) => ({
outline: `1px solid ${color.toString("hex")}`,
}));
const w = area(
{},
`<ColorArea as-child default-value="#ff0000" :style="{ opacity: 0.9 }" :style-fn="styleFn" ref="areaRef">
<div data-custom="area"><ColorAreaThumb as="span" data-custom="thumb" /></div>
</ColorArea>`,
() => ({ styleFn }),
);
const node = root(w);
expect(node.element.tagName).toBe("DIV");
expect(node.attributes("data-custom")).toBe("area");
expect(node.attributes("role")).toBe("group");
expect(node.classes()).toContain("hv-color-area");
expect(node.element.style.opacity).toBe("0.9");
expect(node.element.style.outline).toBe("1px solid #FF0000");
expect(styleFn).toHaveBeenCalled();
expect(thumb(w).element.tagName).toBe("SPAN");
expect(thumb(w).attributes("data-custom")).toBe("thumb");
const exposed = w.vm.$refs.areaRef as {
element: HTMLElement;
color: Color;
};
expect(exposed.element).toBe(node.element);
expect(exposed.color.toString("hex")).toBe("#FF0000");
});
it("keeps one Tab entry and restores focused axes", async () => {
const w = area({ defaultValue: "hsb(240,50%,50%)" });
expect(x(w).attributes("tabindex")).toBe("0");
expect(y(w).attributes("tabindex")).toBe("-1");
await key(w, "ArrowUp", true, {}, "x");
expect(document.activeElement).toBe(y(w).element);
expect(y(w).attributes("tabindex")).toBe("0");
expect(x(w).attributes("tabindex")).toBe("-1");
await key(w, "ArrowRight", true, {}, "y");
expect(document.activeElement).toBe(x(w).element);
expect(x(w).attributes("tabindex")).toBe("0");
});
it("keeps the thumb grab offset and cleans up when disabled mid-drag", async () => {
const disabled = ref(false);
const w = area(
{},
`<ColorArea :is-disabled="disabled" default-value="hsb(240,50%,50%)" x-channel="saturation" y-channel="brightness"><ColorAreaThumb /></ColorArea>`,
() => ({ disabled }),
);
const node = geometry(w);
await pointer(thumb(w).element, "pointerdown", {
clientX: 115,
clientY: 112,
});
expect(thumb(w).attributes("data-dragging")).toBe("true");
await pointer(node, "pointermove", { clientX: 137.4, clientY: 112 });
expect(
(emitted(w, "change")[0]![0] as Color).getChannelValue("saturation"),
).toBeCloseTo(60);
disabled.value = true;
await flushPromises();
await pointer(node, "pointerup", { clientX: 137.4 });
expect(emitted(w, "changeEnd")).toHaveLength(0);
expect(node.releasePointerCapture).toHaveBeenCalledWith(1);
expect(thumb(w).attributes("data-dragging")).toBeUndefined();
});
it("cancels stale keyboard transactions after an external replacement", async () => {
const value = shallowRef(parseColor("hsb(240,50%,50%)"));
const w = render(
defineComponent({
components: { ColorArea, ColorAreaThumb },
setup: () => ({ value }),
template: `<ColorArea :model-value="value" x-channel="saturation" y-channel="brightness"><ColorAreaThumb /></ColorArea>`,
}),
);
await key(w, "ArrowRight", false);
value.value = parseColor("hsb(90,25%,75%)");
await flushPromises();
await x(w).trigger("keyup", { key: "ArrowRight" });
expect(emitted(w, "changeEnd")).toHaveLength(0);
expect(x(w).element.value).toBe("25");
});
it("honors consumer cancellation of keyboard and pointer defaults", async () => {
const w = area(
{},
`<ColorArea default-value="#ff0000" @keydown.prevent @pointerdown.prevent>
<ColorAreaThumb />
</ColorArea>`,
);
const node = geometry(w);
await key(w, "ArrowRight");
await pointer(node, "pointerdown");
expect(emitted(w, "change")).toHaveLength(0);
expect(node.setPointerCapture).not.toHaveBeenCalled();
});
it("submits and resets the two named axes, including an external form", async () => {
const w = area(
{},
`<form><ColorArea default-value="hsb(240,50%,50%)" x-channel="saturation" y-channel="brightness" x-name="s" y-name="b">
<ColorAreaThumb />
</ColorArea></form>`,
);
await key(w, "ArrowUp", true, {}, "y");
const form = w.get("form").element as HTMLFormElement;
expect(new FormData(form).get("s")).toBe("50");
expect(new FormData(form).get("b")).toBe("51");
form.reset();
await flushPromises();
expect(x(w).element.value).toBe("50");
expect(y(w).element.value).toBe("50");
const external = area(
{},
`<form id="external-area"></form>
<ColorArea form="external-area" default-value="hsb(240,50%,50%)" x-channel="saturation" y-channel="brightness" x-name="s" y-name="b">
<ColorAreaThumb />
</ColorArea>`,
);
const outside = external.get("#external-area").element as HTMLFormElement;
await key(external, "ArrowRight");
expect(new FormData(outside).get("s")).toBe("51");
outside.reset();
await flushPromises();
expect(x(external).element.value).toBe("50");
});
it("shares the nearest color owner, supports overrides and restores inheritance", async () => {
const override = shallowRef<Record<string, unknown>>({});
const w = render(
defineComponent({
components: {
Picker: ColorPickerFoundation,
ColorArea,
ColorAreaThumb,
ColorSwatch,
},
setup: () => ({ override }),
template: `<form><Picker name="color" default-value="hsb(240,50%,50%)">
<ColorArea v-bind="override" color-space="hsb" x-channel="saturation" y-channel="brightness"><ColorAreaThumb /></ColorArea>
<ColorSwatch data-owner-swatch />
</Picker></form>`,
}),
);
const picker = w.findComponent(ColorPickerFoundation);
const swatch = () =>
w.get<HTMLElement>("[data-owner-swatch]").element.style.backgroundColor;
expect(x(w).element.value).toBe("50");
expect(swatch()).toBe(parseColor("hsb(240,50%,50%)").toString("css"));
await key(w, "ArrowRight");
expect(picker.emitted("change")).toHaveLength(1);
expect(x(w).element.value).toBe("51");
expect(swatch()).toBe(parseColor("hsb(240,51%,50%)").toString("css"));
override.value = { modelValue: "hsb(10,20%,30%)" };
await flushPromises();
expect(x(w).element.value).toBe("20");
await key(w, "ArrowRight");
expect(picker.emitted("change")).toHaveLength(1);
expect(x(w).element.value).toBe("20");
override.value = {};
await flushPromises();
expect(x(w).element.value).toBe("51");
await key(w, "ArrowRight");
expect(picker.emitted("change")).toHaveLength(2);
expect(
new FormData(w.get("form").element as HTMLFormElement).getAll("color"),
).toHaveLength(1);
});
it("supports thumb style functions and preserves ordinary styles", () => {
const styleFn = vi.fn(
({ percent }: { percent: { x: number; y: number } }) => ({
opacity: percent.x,
}),
);
const w = area(
{},
`<ColorArea default-value="hsb(240,25%,50%)" x-channel="saturation" y-channel="brightness">
<ColorAreaThumb :style="{ borderColor: 'black' }" :style-fn="styleFn" data-custom="thumb" />
</ColorArea>`,
() => ({ styleFn }),
);
const handle = thumb(w);
expect(handle.attributes("data-custom")).toBe("thumb");
expect(handle.element.style.borderColor).toBe("black");
expect(handle.element.style.opacity).toBe("0.25");
expect(styleFn).toHaveBeenCalledWith(
expect.objectContaining({
percent: { x: 0.25, y: 0.5 },
isDragging: false,
isDisabled: false,
isReadOnly: false,
}),
);
});
it("uses the documented default, explicit null and root label fallbacks", async () => {
const fallback = area();
expect(x(fallback).element.value).toBe("255");
expect(y(fallback).element.value).toBe("255");
expect(thumb(fallback).element.style.left).toBe("100%");
expect(thumb(fallback).element.style.top).toBe("0%");
const cleared = area(
{},
`<ColorArea :model-value="null"><ColorAreaThumb /></ColorArea>`,
);
expect(x(cleared).element.value).toBe("255");
expect(y(cleared).element.value).toBe("255");
expect(thumb(cleared).element.style.left).toBe("100%");
expect(thumb(cleared).element.style.top).toBe("0%");
await key(cleared, "ArrowLeft");
expect(emitted(cleared, "change")).toHaveLength(1);
const labelled = area(
{},
`<div>
<ColorArea aria-label="主题色"><ColorAreaThumb /></ColorArea>
<ColorArea aria-labelledby="area-caption"><ColorAreaThumb /></ColorArea>
<span id="area-caption">说明</span>
</div>`,
);
const roots = labelled.findAll<HTMLElement>("[data-slot=color-area]");
expect(roots[0]!.attributes("aria-label")).toBe("主题色");
expect(roots[1]!.attributes("aria-label")).toBeUndefined();
expect(roots[1]!.attributes("aria-labelledby")).toBe("area-caption");
});
it("honors modelValue over value over defaultValue and the disabled alias", async () => {
const both = area(
{},
`<ColorArea model-value="#ff0000" value="#00ff00" default-value="#0000ff"><ColorAreaThumb /></ColorArea>`,
);
expect(axisValue(both, "x")).toBe("255");
expect(thumbColor(both)).toBe("rgb(255, 0, 0)");
const valueOnly = area(
{},
`<ColorArea value="#00ff00" default-value="#0000ff"><ColorAreaThumb /></ColorArea>`,
);
expect(thumbColor(valueOnly)).toBe("rgb(0, 255, 0)");
const disabled = area({ disabled: true, defaultValue: "#ff0000" });
expect(root(disabled).attributes("data-disabled")).toBe("true");
expect(x(disabled).element.disabled).toBe(true);
});
it("re-infer axes when colorSpace and channel props change dynamically", async () => {
const props = shallowRef<Record<string, unknown>>({
defaultValue: "hsb(240, 50%, 50%)",
colorSpace: "hsb",
});
const w = area(
{},
`<ColorArea v-bind="props"><ColorAreaThumb /></ColorArea>`,
() => ({
props,
}),
);
expect(x(w).attributes("aria-label")).toBe("Hue");
expect(y(w).attributes("aria-label")).toBe("Saturation");
expect(x(w).element.value).toBe("240");
props.value = {
defaultValue: "hsb(240, 50%, 50%)",
colorSpace: "rgb",
};
await flushPromises();
expect(x(w).attributes("aria-label")).toBe("Red");
expect(y(w).attributes("aria-label")).toBe("Green");
expect(x(w).attributes("max")).toBe("255");
props.value = {
defaultValue: "hsb(240, 50%, 50%)",
colorSpace: "rgb",
xChannel: "green",
yChannel: "blue",
};
await flushPromises();
expect(x(w).attributes("aria-label")).toBe("Green");
expect(y(w).attributes("aria-label")).toBe("Blue");
expect(thumb(w).element.style.left).not.toBe("");
props.value = {
defaultValue: "hsl(200, 50%, 50%)",
colorSpace: "hsl",
};
await flushPromises();
expect(x(w).attributes("aria-label")).toBe("Hue");
expect(y(w).attributes("aria-label")).toBe("Saturation");
expect(x(w).attributes("max")).toBe("360");
});
it("keeps accepted alpha and fractional channel precision through keyboard changes", async () => {
const value = parseColor("hsb(240,50.123%,50.567%,.321)");
const w = area({
defaultValue: value,
xChannel: "saturation",
yChannel: "brightness",
});
expect(x(w).element.value).toBe("50.123");
await key(w, "ArrowUp", true, {}, "y");
const proposal = emitted(w, "change")[0]![0] as Color;
expect(proposal.getChannelValue("alpha")).toBe(0.321);
expect(proposal.getChannelValue("saturation")).toBe(50.123);
expect(proposal.getChannelValue("brightness")).toBeCloseTo(51.567);
});
it("requires the thumb to be rendered inside the root", () => {
expect(() =>
render(
defineComponent({
components: { ColorAreaThumb },
template: `<ColorAreaThumb />`,
}),
),
).toThrow(/ColorAreaThumb must be rendered inside ColorArea/);
});
});
+12 -2
View File
@@ -171,9 +171,19 @@ describe("immutable private color value boundary", () => {
});
it("resolves legal space defaults and rejects duplicate/mismatched axes", () => {
expect(colorAxes(parseColor("#f00"))).toMatchObject({
space: "rgb",
x: "red",
y: "green",
});
expect(colorAxes(parseColor("hsl(200, 50%, 50%)"))).toMatchObject({
space: "hsl",
x: "hue",
y: "saturation",
});
expect(colorAxes(parseColor("hsb(240, 50%, 50%)"))).toMatchObject({
space: "hsb",
x: "saturation",
y: "brightness",
x: "hue",
y: "saturation",
});
expect(colorAxes(parseColor("#f00"), "rgb")).toMatchObject({
x: "red",
+36
View File
@@ -90,6 +90,42 @@ for (const id of process.argv.slice(2)) {
.base()
.includes("hv-select--secondary"),
);
if (id === "color-area") {
assert(lib.ColorArea === lib.ColorAreaRoot);
assert(lib.ColorAreaThumb);
assert(
lib
.colorAreaVariants({ showDots: true })
.base()
.includes("hv-color-area--show-dots"),
);
assert(
lib.colorAreaVariants().thumb() === "hv-color-area__thumb",
"ColorArea thumb class must stay in the baseline namespace",
);
const areaDts = readFileSync(
new URL(
"./node_modules/@heroui-vue/components/dist/components/color-area/ColorArea.vue.d.ts",
import.meta.url,
),
"utf8",
);
const thumbDts = readFileSync(
new URL(
"./node_modules/@heroui-vue/components/dist/components/color-area/ColorAreaThumb.vue.d.ts",
import.meta.url,
),
"utf8",
);
assert(
!areaDts.includes("reka-ui"),
"ColorArea declarations leak Reka types",
);
assert(
!thumbDts.includes("reka-ui"),
"ColorAreaThumb declarations leak Reka types",
);
}
if (id === "color-swatch") {
assert(lib.ColorSwatch === lib.ColorSwatchRoot);
assert(
+21 -28
View File
@@ -110,6 +110,23 @@
".hv-calendar-year-picker__year-cell"
]
},
"color-area": {
"exports": [
"ColorArea",
"ColorAreaRoot",
"ColorAreaThumb",
"colorAreaVariants",
"Color",
"parseColor"
],
"css": [
".hv-color-area",
".hv-color-area--show-dots",
".hv-color-area__thumb",
"--color-area-background",
"--color-area-thumb-color"
]
},
"color-field-protocol": {
"exports": [],
"css": [
@@ -120,24 +137,12 @@
".hv-color-input-group__prefix",
".hv-color-input-group__suffix"
],
"absent": [
"ColorArea",
"ColorSlider",
"ColorField",
"ColorInputGroup",
"ColorPicker"
]
"absent": ["ColorSlider", "ColorField", "ColorInputGroup", "ColorPicker"]
},
"color-foundation": {
"exports": [],
"css": [".hv-color-area", ".hv-color-area__thumb"],
"absent": [
"ColorArea",
"ColorSlider",
"ColorField",
"ColorInputGroup",
"ColorPicker"
]
"absent": ["ColorSlider", "ColorField", "ColorInputGroup", "ColorPicker"]
},
"color-picker-protocol": {
"exports": [],
@@ -146,13 +151,7 @@
".hv-color-picker__trigger",
".hv-color-picker__popover"
],
"absent": [
"ColorArea",
"ColorSlider",
"ColorField",
"ColorInputGroup",
"ColorPicker"
]
"absent": ["ColorSlider", "ColorField", "ColorInputGroup", "ColorPicker"]
},
"color-slider-foundation": {
"exports": [],
@@ -166,13 +165,7 @@
"max-height:inherit",
"overscroll-behavior:contain"
],
"absent": [
"ColorArea",
"ColorSlider",
"ColorField",
"ColorInputGroup",
"ColorPicker"
]
"absent": ["ColorSlider", "ColorField", "ColorInputGroup", "ColorPicker"]
},
"date-field": {
"exports": [
+135
View File
@@ -0,0 +1,135 @@
import {
ColorArea,
ColorAreaRoot,
ColorAreaThumb,
colorAreaVariants,
parseColor,
type Color,
type ColorAreaExpose,
type ColorAreaProps,
type ColorAreaRenderProps,
type ColorAreaRootProps,
type ColorAreaSlots,
type ColorAreaStyle,
type ColorAreaStyleFn,
type ColorAreaThumbProps,
type ColorAreaThumbRenderProps,
type ColorAreaThumbStyle,
type ColorAreaThumbStyleFn,
type ColorAreaVariants,
type ColorAxisChannel,
type ColorSpace,
type ColorValue,
} from "@heroui-vue/components";
const color = parseColor("#9B80FF");
const value: ColorValue = color;
const axis: ColorAxisChannel = "saturation";
const space: ColorSpace = "hsb";
const style: ColorAreaStyle = { outline: "1px solid black" };
const styleFn: ColorAreaStyleFn = ({ color: current }) => ({
outline: `1px solid ${current.toString("hex")}`,
});
const styleRender: ColorAreaStyle = ({ color: current }) => ({
background: current.toString("css"),
});
const thumbStyle: ColorAreaThumbStyle = ({ percent }) => ({
opacity: percent.x,
});
const thumbStyleFn: ColorAreaThumbStyleFn = ({ isDragging }) => ({
width: isDragging ? "20px" : "16px",
});
const props: ColorAreaProps = {
modelValue: color,
value,
defaultValue: "hsb(240, 50%, 50%)",
colorSpace: space,
xChannel: "hue",
yChannel: axis,
xName: "hue",
yName: "saturation",
form: "color-form",
isDisabled: false,
disabled: false,
isReadOnly: false,
showDots: true,
locale: "zh-CN",
dir: "rtl",
as: "div",
asChild: false,
style,
styleFn,
};
const rootProps: ColorAreaRootProps = props;
const thumbProps: ColorAreaThumbProps = {
as: "span",
style: thumbStyle,
styleFn: thumbStyleFn,
};
const slots: ColorAreaSlots = { default: () => null };
const variants: ColorAreaVariants = { showDots: true };
const render: ColorAreaRenderProps = {
color,
space: "hsb",
x: "hue",
y: "saturation",
};
const thumbRender: ColorAreaThumbRenderProps = {
...render,
percent: { x: 1, y: 0 },
isDragging: false,
isDisabled: false,
isReadOnly: false,
};
const exposed: ColorAreaExpose = { element: null, color: null };
const typedColor: Color = parseColor("rgb(1, 2, 3)");
// @ts-expect-error alpha is not a two-dimensional axis
const badAxis: ColorAxisChannel = "alpha";
// @ts-expect-error the public space set is rgb | hsl | hsb
const badSpace: ColorSpace = "lab";
// @ts-expect-error showDots only accepts a boolean
const badVariant: ColorAreaVariants = { showDots: "yes" };
// @ts-expect-error xChannel is a channel name, not an index
const badProps: ColorAreaProps = { xChannel: 1 };
const badRender: ColorAreaRenderProps = {
// @ts-expect-error render props require a Color instance
color: "#fff",
space: "rgb",
x: "red",
y: "green",
};
const badThumb: ColorAreaThumbRenderProps = {
...render,
// @ts-expect-error the thumb exposes percent, not raw pixel coordinates
percent: 1,
isDragging: false,
isDisabled: false,
isReadOnly: false,
};
void [
ColorArea,
ColorAreaRoot,
ColorAreaThumb,
colorAreaVariants,
value,
axis,
space,
styleRender,
props,
rootProps,
thumbProps,
slots,
variants,
render,
thumbRender,
exposed,
typedColor,
badAxis,
badSpace,
badVariant,
badProps,
badRender,
badThumb,
];