Files
heroui-vue/tests/color-swatch.test.ts
T
2026-10-26 13:25:21 +08:00

400 lines
15 KiB
TypeScript

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");
});
});