feat: publish ColorSwatchPicker and shared swatch picker parts

This commit is contained in:
maoyingjie
2026-10-27 14:42:29 +08:00
parent fa4146ee0b
commit 8d9adda8da
38 changed files with 3232 additions and 9 deletions
+223
View File
@@ -0,0 +1,223 @@
import { afterEach, describe, expect, it } from "vitest";
import { mount } from "@vue/test-utils";
import { readFileSync } from "node:fs";
import {
ColorSwatchPicker,
ColorSwatchPickerIndicator,
ColorSwatchPickerItem,
ColorSwatchPickerSwatch,
} from "../packages/vue/src";
import Basic from "../apps/docs/demos/color-swatch-picker-basic.vue";
import Variants from "../apps/docs/demos/color-swatch-picker-variants.vue";
import Sizes from "../apps/docs/demos/color-swatch-picker-sizes.vue";
import Disabled from "../apps/docs/demos/color-swatch-picker-disabled.vue";
import StackLayout from "../apps/docs/demos/color-swatch-picker-stack-layout.vue";
import DefaultValue from "../apps/docs/demos/color-swatch-picker-default-value.vue";
import Controlled from "../apps/docs/demos/color-swatch-picker-controlled.vue";
import CustomIndicator from "../apps/docs/demos/color-swatch-picker-custom-indicator.vue";
import RenderFunction from "../apps/docs/demos/color-swatch-picker-render-function.vue";
import CustomStyles from "../apps/docs/demos/color-swatch-picker-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",
"variants",
"sizes",
"disabled",
"stack-layout",
"default-value",
"controlled",
"custom-indicator",
"render-function",
"custom-styles",
];
const BASELINE = [
"#F43F5E",
"#D946EF",
"#8B5CF6",
"#3B82F6",
"#06B6D4",
"#10B981",
"#84CC16",
];
const items = (w: ReturnType<typeof mount>) =>
w.findAll<HTMLElement>("[data-slot=color-swatch-picker-item]");
describe("ColorSwatchPicker documentation demos", () => {
it("keeps the ten pinned previews in the upstream order", () => {
const document = readFileSync(
"apps/docs/components/color-swatch-picker.md",
"utf8",
);
const names = [
...document.matchAll(
/<ComponentPreview name="color-swatch-picker-([^"]+)"/g,
),
].map((match) => match[1]);
expect(names).toEqual(previews);
for (const name of previews) {
const source = readFileSync(
`apps/docs/demos/color-swatch-picker-${name}.vue`,
"utf8",
);
expect(source).toContain("<template>");
expect(source).toContain('from "@heroui-vue/components"');
expect(source).not.toContain("className");
}
});
it("renders the basic preset palette", () => {
const w = render(Basic);
expect(w.findAllComponents(ColorSwatchPicker)).toHaveLength(1);
expect(w.findAllComponents(ColorSwatchPickerItem)).toHaveLength(7);
expect(w.findAllComponents(ColorSwatchPickerSwatch)).toHaveLength(7);
expect(w.findAllComponents(ColorSwatchPickerIndicator)).toHaveLength(7);
expect(
items(w).map((item) =>
(item.find("[data-slot=color-swatch-picker-swatch]").element as HTMLElement)
.style.backgroundColor,
),
).toEqual([
"rgb(244, 63, 94)",
"rgb(217, 70, 239)",
"rgb(139, 92, 246)",
"rgb(59, 130, 246)",
"rgb(6, 182, 212)",
"rgb(16, 185, 129)",
"rgb(132, 204, 22)",
]);
for (const color of BASELINE) {
expect(items(w).some((item) => item.attributes("aria-label") === color.toUpperCase()))
.toBe(true);
}
});
it("maps variants, sizes, layout and disabled states to baseline classes", () => {
const variants = render(Variants);
const roots = variants
.findAll<HTMLElement>("[data-slot=color-swatch-picker]")
.map((node) => node.classes());
expect(roots[0]).toContain("hv-color-swatch-picker--circle");
expect(roots[1]).toContain("hv-color-swatch-picker--square");
const sizes = render(Sizes);
expect(
sizes
.findAll<HTMLElement>("[data-slot=color-swatch-picker]")
.map((node) =>
["xs", "sm", "md", "lg", "xl"].find((size) =>
node.classes().includes(`hv-color-swatch-picker--${size}`),
),
),
).toEqual(["xs", "sm", "md", "lg", "xl"]);
const stack = render(StackLayout);
expect(
stack
.get<HTMLElement>("[data-slot=color-swatch-picker]")
.classes(),
).toContain("hv-color-swatch-picker--stack");
const disabled = render(Disabled);
expect(items(disabled)).toHaveLength(7);
for (const item of items(disabled)) {
expect(item.attributes("aria-disabled")).toBe("true");
expect(item.attributes("data-disabled")).toBe("true");
}
});
it("keeps the default value, controlled value and real slot state", async () => {
const initial = render(DefaultValue);
expect(
items(initial).map((item) => item.attributes("aria-selected")),
).toEqual([
"false",
"false",
"true",
"false",
"false",
"false",
"false",
]);
const controlled = render(Controlled);
expect(
controlled.get("p span").text(),
).toBe("#F43F5E");
items(controlled)[2]!.trigger("mousedown");
await controlled.vm.$nextTick();
expect(controlled.get("p span").text()).toBe("#8B5CF6");
const slots = render(RenderFunction);
const root = slots.get<HTMLElement>("[data-slot=color-swatch-picker]");
expect(root.attributes("data-custom")).toBe("foo");
expect(items(slots)[2]!.attributes("aria-selected")).toBe("false");
expect(
items(slots)[2]!
.find("[data-slot=color-swatch-picker-swatch]")
.attributes("data-picker-layout"),
).toBe("grid");
});
it("replaces the default checkmark and styles the custom container", () => {
const custom = render(CustomIndicator);
expect(
custom.findAll("[data-slot=color-swatch-picker-checkmark]"),
).toHaveLength(0);
expect(custom.findAll("svg")).toHaveLength(7);
const styled = render(CustomStyles);
const root = styled.get<HTMLElement>("[data-slot=color-swatch-picker]");
expect(root.classes()).toEqual(
expect.arrayContaining([
"rounded-2xl",
"bg-surface",
"hv-color-swatch-picker--square",
]),
);
expect(items(styled)[2]!.attributes("aria-selected")).toBe("true");
});
it("documents the Vue API, slot states and recorded differences", () => {
const document = readFileSync(
"apps/docs/components/color-swatch-picker.md",
"utf8",
);
expect(document).toContain("title: ColorSwatchPicker 颜色色块选择器");
expect(document).toContain("`modelValue`");
expect(document).toContain("`defaultValue`");
expect(document).toContain("`layout`");
expect(document).toContain("`size`");
expect(document).toContain("`variant`");
expect(document).toContain("### Render Props");
expect(document).toContain("isSelected");
expect(document).toContain("listbox");
expect(document).toContain("hexa");
expect(document).toContain("可访问名称差异");
expect(document).toContain("感知色名");
expect(document).toContain("不新增这些字段 API");
expect(document).not.toMatch(/\|\s*`className`\s*\|/);
});
it("adds ColorSwatchPicker to the shared navigation", () => {
const navigation = readFileSync(
"apps/docs/.vitepress/theme/navigation.ts",
"utf8",
);
expect(navigation).toContain("ColorSwatchPicker 颜色色块选择器");
expect(navigation).toContain('url: "/components/color-swatch-picker"');
expect(navigation).toContain('category: "colors"');
});
});
+780
View File
@@ -0,0 +1,780 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { mount } from "@vue/test-utils";
import { defineComponent, shallowRef } from "vue";
import {
Color,
ColorSwatchPicker,
ColorSwatchPickerIndicator,
ColorSwatchPickerItem,
ColorSwatchPickerRoot,
ColorSwatchPickerSwatch,
ConfigProvider,
colorSwatchPickerVariants,
parseColor,
} from "../packages/vue/src";
import { serializeColorValue } from "../packages/vue/src/components/color/submission";
import type {
ColorSwatchPickerExpose,
ColorSwatchPickerRenderProps,
} from "../packages/vue/src";
import Picker from "../packages/vue/src/components/color-picker/ColorPicker.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();
});
const COLORS = ["#F43F5E", "#D946EF", "#8B5CF6"];
function picker(
props: Record<string, unknown> = {},
colors: string[] = COLORS,
itemProps: Record<string, unknown> | ((c: string, i: number) => Record<string, unknown>) = {},
) {
return render(
defineComponent({
components: {
ColorSwatchPicker,
ColorSwatchPickerItem,
ColorSwatchPickerSwatch,
ColorSwatchPickerIndicator,
},
setup: () => ({ attrs: props, colors, itemProps }),
template: `
<ColorSwatchPicker v-bind="attrs">
<ColorSwatchPickerItem
v-for="(c, index) in colors"
:key="index"
:color="c"
v-bind="typeof itemProps === 'function' ? itemProps(c, index) : itemProps"
>
<ColorSwatchPickerSwatch />
<ColorSwatchPickerIndicator />
</ColorSwatchPickerItem>
</ColorSwatchPicker>`,
}),
);
}
function items(w: ReturnType<typeof mount>) {
return w.findAll<HTMLElement>("[data-slot=color-swatch-picker-item]");
}
function press(item: ReturnType<typeof items>[number]) {
item.element.dispatchEvent(
new MouseEvent("mousedown", { bubbles: true, cancelable: true }),
);
}
function keydown(element: Element, key: string, init: KeyboardEventInit = {}) {
const event = new KeyboardEvent("keydown", {
key,
bubbles: true,
cancelable: true,
...init,
});
element.dispatchEvent(event);
return event;
}
/** jsdom has no layout; grid movement needs explicit rects (browser evidence
* in docs/tasks/results/COLOR-SWATCH-PICKER.md is authoritative). */
function withGeometry(w: ReturnType<typeof mount>, columns = 3, size = 32) {
const root = w.get<HTMLElement>("[data-slot=color-swatch-picker]").element;
vi.spyOn(root, "getBoundingClientRect").mockReturnValue({
left: 0,
top: 0,
width: columns * size,
height: 100,
x: 0,
y: 0,
right: columns * size,
bottom: 100,
toJSON: () => ({}),
} as DOMRect);
items(w).forEach((item, index) => {
const x = (index % columns) * size;
const y = Math.floor(index / columns) * size;
vi.spyOn(item.element, "getBoundingClientRect").mockReturnValue({
left: x,
top: y,
width: size,
height: size,
x,
y,
right: x + size,
bottom: y + size,
toJSON: () => ({}),
} as DOMRect);
});
return w;
}
describe("ColorSwatchPicker composition and baseline DOM", () => {
it("exposes the five named exports sharing one root implementation", () => {
expect(ColorSwatchPicker).toBe(ColorSwatchPickerRoot);
const w = picker();
const root = w.get<HTMLElement>("[data-slot=color-swatch-picker]");
expect(root.attributes("role")).toBe("listbox");
expect(root.attributes("aria-orientation")).toBe("vertical");
expect(root.classes()).toEqual(
expect.arrayContaining([
"hv-color-swatch-picker",
"hv-color-swatch-picker--md",
"hv-color-swatch-picker--circle",
"hv-color-swatch-picker--grid",
]),
);
expect(items(w)).toHaveLength(3);
const first = items(w)[0]!;
expect(first.attributes("role")).toBe("option");
expect(first.attributes("aria-selected")).toBe("false");
expect(first.attributes("aria-label")).toBe("#F43F5E");
expect(first.element.style.getPropertyValue("--color-swatch-current")).toBe(
"rgb(244, 63, 94)",
);
expect(first.classes()).toContain("hv-color-swatch-picker__item");
const swatch = w.get<HTMLElement>("[data-slot=color-swatch-picker-swatch]");
expect(swatch.attributes("role")).toBe("img");
expect(swatch.element.style.backgroundColor).toBe("rgb(244, 63, 94)");
const indicator = w.get<HTMLElement>(
"[data-slot=color-swatch-picker-indicator]",
);
expect(indicator.attributes("aria-hidden")).toBe("true");
expect(
indicator.find("[data-slot=color-swatch-picker-checkmark]").exists(),
).toBe(true);
});
it("maps size, shape and layout variants to the ported modifiers", () => {
expect(colorSwatchPickerVariants({ size: "xl" }).base()).toContain(
"hv-color-swatch-picker--xl",
);
expect(colorSwatchPickerVariants({ variant: "square" }).item()).toBe(
"hv-color-swatch-picker__item",
);
const w = picker({ size: "lg", variant: "square", layout: "stack" });
const root = w.get<HTMLElement>("[data-slot=color-swatch-picker]");
expect(root.classes()).toEqual(
expect.arrayContaining([
"hv-color-swatch-picker--lg",
"hv-color-swatch-picker--square",
"hv-color-swatch-picker--stack",
]),
);
});
it("keeps the fixed default accessible names and explicit overrides", () => {
const w = picker();
expect(
w.get("[data-slot=color-swatch-picker]").attributes("aria-label"),
).toBe("Color swatch picker");
const zh = render(
defineComponent({
components: {
ConfigProvider,
ColorSwatchPicker,
ColorSwatchPickerItem,
ColorSwatchPickerSwatch,
ColorSwatchPickerIndicator,
},
template: `
<ConfigProvider locale="zh-CN">
<ColorSwatchPicker>
<ColorSwatchPickerItem color="#fff8">
<ColorSwatchPickerSwatch />
<ColorSwatchPickerIndicator />
</ColorSwatchPickerItem>
</ColorSwatchPicker>
</ConfigProvider>`,
}),
);
expect(
zh.get("[data-slot=color-swatch-picker]").attributes("aria-label"),
).toBe("颜色色块选择器");
expect(items(zh)[0]!.attributes("aria-label")).toBe("#FFFFFF88");
const explicit = picker({ "aria-label": "Color presets" });
expect(
explicit.get("[data-slot=color-swatch-picker]").attributes("aria-label"),
).toBe("Color presets");
const named = render(
defineComponent({
components: {
ColorSwatchPicker,
ColorSwatchPickerItem,
ColorSwatchPickerSwatch,
ColorSwatchPickerIndicator,
},
template: `
<ColorSwatchPicker>
<ColorSwatchPickerItem color="#0000" aria-label="透明色">
<ColorSwatchPickerSwatch />
<ColorSwatchPickerIndicator />
</ColorSwatchPickerItem>
</ColorSwatchPicker>`,
}),
);
expect(items(named)[0]!.attributes("aria-label")).toBe("透明色");
});
it("decides indicator contrast from the item color luminance", () => {
const w = picker({}, ["#FFFFFF", "#000000"]);
const indicators = w.findAll<HTMLElement>(
"[data-slot=color-swatch-picker-indicator]",
);
expect(indicators[0]!.attributes("data-light-color")).toBe("true");
expect(indicators[1]!.attributes("data-light-color")).toBeUndefined();
});
it("requires the parent parts and keeps item identity structural", () => {
expect(() =>
mount(ColorSwatchPickerItem, { props: { color: "#000" } }),
).toThrow(/ColorSwatchPickerItem requires ColorSwatchPicker/);
expect(() => mount(ColorSwatchPickerSwatch)).toThrow(
/require ColorSwatchPickerItem/,
);
const w = picker({}, ["#F43F5E", "#F43F5E"]);
expect(items(w)).toHaveLength(2);
expect(items(w)[0]!.element).not.toBe(items(w)[1]!.element);
const exposed = w.getComponent(ColorSwatchPicker)
.vm as unknown as ColorSwatchPickerExpose;
expect(exposed.element).toBe(
w.get("[data-slot=color-swatch-picker]").element,
);
});
});
describe("ColorSwatchPicker selection", () => {
it("selects on pointer press and emits the candidate color unchanged", async () => {
const w = picker();
const root = w.getComponent(ColorSwatchPicker);
press(items(w)[1]!);
await w.vm.$nextTick();
const emitted = root.emitted("update:modelValue")!;
expect(emitted).toHaveLength(1);
expect((emitted[0]![0] as Color).toString("hex")).toBe("#D946EF");
expect(root.emitted("change")).toHaveLength(1);
expect(items(w)[1]!.attributes("aria-selected")).toBe("true");
expect(items(w)[0]!.attributes("aria-selected")).toBe("false");
expect(items(w)[1]!.attributes("data-selected")).toBe("true");
});
it("keeps the candidate's own color space instead of rewriting it", () => {
const w = picker({}, ["hsl(210, 100%, 50%)"]);
press(items(w)[0]!);
const value = w
.getComponent(ColorSwatchPicker)
.emitted("update:modelValue")![0]![0] as Color;
expect(value.getColorSpace()).toBe("hsl");
expect(value.toString("hex").toLowerCase()).toBe("#007fff");
});
it("never emits when re-selecting the accepted color and honours cancelable presses", async () => {
const w = picker({ defaultValue: COLORS[1] });
const root = w.getComponent(ColorSwatchPicker);
press(items(w)[1]!);
await w.vm.$nextTick();
expect(root.emitted("update:modelValue")).toBeUndefined();
const cancelled = picker(
{ defaultValue: COLORS[1] },
COLORS,
{ onMousedown: (event: MouseEvent) => event.preventDefault() },
);
press(items(cancelled)[0]!);
await cancelled.vm.$nextTick();
expect(
cancelled.getComponent(ColorSwatchPicker).emitted("update:modelValue"),
).toBeUndefined();
expect(items(cancelled)[1]!.attributes("aria-selected")).toBe("true");
});
it("blocks selection from disabled items and a disabled root", () => {
const w = picker({}, COLORS, (_c: string, index: number) => ({
isDisabled: index === 1,
}));
const root = w.getComponent(ColorSwatchPicker);
expect(items(w)[1]!.attributes("aria-disabled")).toBe("true");
expect(items(w)[1]!.attributes("data-disabled")).toBe("true");
expect(items(w)[1]!.attributes("tabindex")).toBeUndefined();
press(items(w)[1]!);
expect(root.emitted("update:modelValue")).toBeUndefined();
const off = picker({ isDisabled: true });
expect(
off.get("[data-slot=color-swatch-picker]").attributes("aria-disabled"),
).toBe("true");
press(items(off)[0]!);
expect(
off.getComponent(ColorSwatchPicker).emitted("update:modelValue"),
).toBeUndefined();
});
it("keeps the accepted state when a controlled parent rejects, then retries", async () => {
const value = shallowRef(parseColor("#F43F5E"));
const w = render(
defineComponent({
components: {
ColorSwatchPicker,
ColorSwatchPickerItem,
ColorSwatchPickerSwatch,
ColorSwatchPickerIndicator,
},
setup: () => ({ value }),
data: () => ({ colors: COLORS }),
template: `
<ColorSwatchPicker :model-value="value">
<ColorSwatchPickerItem
v-for="(c, index) in colors"
:key="index"
:color="c"
>
<ColorSwatchPickerSwatch />
<ColorSwatchPickerIndicator />
</ColorSwatchPickerItem>
</ColorSwatchPicker>`,
}),
);
const root = w.getComponent(ColorSwatchPicker);
press(items(w)[2]!);
await w.vm.$nextTick();
expect(root.emitted("update:modelValue")).toHaveLength(1);
expect(items(w)[2]!.attributes("aria-selected")).toBe("false");
expect(items(w)[0]!.attributes("aria-selected")).toBe("true");
// Same proposal again after the rejection: the change retries.
press(items(w)[2]!);
await w.vm.$nextTick();
expect(root.emitted("update:modelValue")).toHaveLength(2);
value.value = parseColor("#8B5CF6");
await w.vm.$nextTick();
expect(items(w)[2]!.attributes("aria-selected")).toBe("true");
});
it("treats equivalent formats as the fixed hexa key without rewriting values", () => {
const red = parseColor("#8B5CF6");
const hsl = red.toFormat("hsl").toString("hsl");
const w = picker({ defaultValue: "rgb(139, 92, 246)" }, [hsl, "#8B5CF6"]);
expect(items(w)[0]!.attributes("aria-selected")).toBe("true");
expect(items(w)[1]!.attributes("aria-selected")).toBe("true");
// Alpha is compared at the fixed 8-bit scale only for matching.
const alpha = picker({ defaultValue: "rgba(0, 0, 255, 0.5)" }, [
"#0000FF80",
]);
expect(items(alpha)[0]!.attributes("aria-selected")).toBe("true");
// Gray hues collapse through the RGB key while the value keeps its hue.
const gray = picker({ defaultValue: "hsl(120, 0%, 50%)" }, ["#808080"]);
expect(items(gray)[0]!.attributes("aria-selected")).toBe("true");
// Different bytes never match, no matter how close.
const near = picker({ defaultValue: "#8B5CF6" }, ["#8B5CF7"]);
expect(items(near)[0]!.attributes("aria-selected")).toBe("false");
});
it("records the documented empty-value and dynamic candidate behaviour", async () => {
// No initial value: the fixed default is #000000 and nothing is picked.
const w = picker({}, ["#FFFFFF"]);
expect(items(w)[0]!.attributes("aria-selected")).toBe("false");
press(items(w)[0]!);
await w.vm.$nextTick();
expect(items(w)[0]!.attributes("aria-selected")).toBe("true");
const cleared = picker({ modelValue: null });
expect(
items(cleared).every(
(item) => item.attributes("aria-selected") === "false",
),
).toBe(true);
const missing = picker({ defaultValue: "#F43F5E" }, ["#D946EF"]);
expect(items(missing)[0]!.attributes("aria-selected")).toBe("false");
const colors = shallowRef([...COLORS]);
const dyn = render(
defineComponent({
components: {
ColorSwatchPicker,
ColorSwatchPickerItem,
ColorSwatchPickerSwatch,
ColorSwatchPickerIndicator,
},
setup: () => ({ colors }),
template: `
<ColorSwatchPicker default-value="#8B5CF6">
<ColorSwatchPickerItem v-for="c in colors" :key="c" :color="c">
<ColorSwatchPickerSwatch />
<ColorSwatchPickerIndicator />
</ColorSwatchPickerItem>
</ColorSwatchPicker>`,
}),
);
expect(items(dyn)[2]!.attributes("aria-selected")).toBe("true");
// Removing the selected candidate keeps the accepted color.
colors.value = [COLORS[0]!, COLORS[1]!];
await dyn.vm.$nextTick();
expect(items(dyn)).toHaveLength(2);
expect(
items(dyn).every((item) => item.attributes("aria-selected") === "false"),
).toBe(true);
colors.value = [];
await dyn.vm.$nextTick();
expect(items(dyn)).toHaveLength(0);
expect(
dyn.get("[data-slot=color-swatch-picker]").attributes("role"),
).toBe("listbox");
});
});
describe("ColorSwatchPicker focus and keyboard", () => {
it("keeps a single tab stop and marshals the entry focus", async () => {
const w = picker({ defaultValue: COLORS[1] });
const root = w.get<HTMLElement>("[data-slot=color-swatch-picker]");
expect(root.attributes("tabindex")).toBe("0");
expect(items(w).map((item) => item.attributes("tabindex"))).toEqual([
"-1",
"-1",
"-1",
]);
(
w.getComponent(ColorSwatchPicker).vm as unknown as ColorSwatchPickerExpose
).focus();
await w.vm.$nextTick();
expect(document.activeElement).toBe(items(w)[1]!.element);
expect(root.attributes("tabindex")).toBe("-1");
expect(items(w).map((item) => item.attributes("tabindex"))).toEqual([
"-1",
"0",
"-1",
]);
expect(items(w)[1]!.attributes("data-focused")).toBe("true");
expect(root.attributes("data-focused")).toBe("true");
});
it("moves focus without selecting and selects only on Enter/Space", async () => {
const w = picker({ layout: "stack" });
const root = w.getComponent(ColorSwatchPicker);
items(w)[0]!.element.focus();
keydown(items(w)[0]!.element, "ArrowDown");
await w.vm.$nextTick();
expect(document.activeElement).toBe(items(w)[1]!.element);
expect(root.emitted("update:modelValue")).toBeUndefined();
expect(items(w)[1]!.attributes("aria-selected")).toBe("false");
keydown(items(w)[1]!.element, "Enter");
await w.vm.$nextTick();
expect(root.emitted("update:modelValue")).toHaveLength(1);
expect(items(w)[1]!.attributes("aria-selected")).toBe("true");
keydown(items(w)[1]!.element, " ");
await w.vm.$nextTick();
expect(items(w)[1]!.attributes("aria-selected")).toBe("true");
expect(root.emitted("update:modelValue")).toHaveLength(1);
});
it("walks, jumps and stops at the boundaries without wrapping", () => {
const w = picker({ layout: "stack" });
items(w)[0]!.element.focus();
keydown(items(w)[0]!.element, "End");
expect(document.activeElement).toBe(items(w)[2]!.element);
const atEnd = keydown(items(w)[2]!.element, "ArrowDown");
expect(document.activeElement).toBe(items(w)[2]!.element);
expect(atEnd.defaultPrevented).toBe(false);
keydown(items(w)[2]!.element, "Home");
expect(document.activeElement).toBe(items(w)[0]!.element);
});
it("uses order movement horizontally in grid and ignores it in stack", () => {
const grid = withGeometry(picker());
items(grid)[1]!.element.focus();
keydown(items(grid)[1]!.element, "ArrowRight");
expect(document.activeElement).toBe(items(grid)[2]!.element);
keydown(items(grid)[2]!.element, "ArrowLeft");
expect(document.activeElement).toBe(items(grid)[1]!.element);
const stack = picker({ layout: "stack" });
items(stack)[1]!.element.focus();
const event = keydown(items(stack)[1]!.element, "ArrowRight");
expect(document.activeElement).toBe(items(stack)[1]!.element);
expect(event.defaultPrevented).toBe(false);
keydown(items(stack)[1]!.element, "ArrowDown");
expect(document.activeElement).toBe(items(stack)[2]!.element);
});
it("moves across wrapped grid rows by geometry and reverses in RTL", () => {
const w = withGeometry(
picker(
{},
["#F43F5E", "#D946EF", "#8B5CF6", "#3B82F6", "#06B6D4", "#10B981"],
),
);
items(w)[1]!.element.focus();
keydown(items(w)[1]!.element, "ArrowDown");
expect(document.activeElement).toBe(items(w)[4]!.element);
keydown(items(w)[4]!.element, "ArrowUp");
expect(document.activeElement).toBe(items(w)[1]!.element);
// No item shares the column below index 3 in a 3x2 grid.
items(w)[3]!.element.focus();
keydown(items(w)[3]!.element, "ArrowDown");
expect(document.activeElement).toBe(items(w)[3]!.element);
const rtl = picker({ dir: "rtl" });
items(rtl)[1]!.element.focus();
keydown(items(rtl)[1]!.element, "ArrowRight");
expect(document.activeElement).toBe(items(rtl)[0]!.element);
keydown(items(rtl)[0]!.element, "ArrowLeft");
expect(document.activeElement).toBe(items(rtl)[1]!.element);
});
it("skips disabled items, jumps pages and types to focus", () => {
const w = picker({ layout: "stack" }, COLORS, (_c: string, index: number) => ({
isDisabled: index === 1,
}));
items(w)[0]!.element.focus();
keydown(items(w)[0]!.element, "ArrowDown");
expect(document.activeElement).toBe(items(w)[2]!.element);
keydown(items(w)[2]!.element, "PageUp");
expect(document.activeElement).toBe(items(w)[0]!.element);
keydown(items(w)[0]!.element, "PageDown");
expect(document.activeElement).toBe(items(w)[2]!.element);
const typed = picker({ layout: "stack" }, ["#F43F5E", "#D946EF"], (_c: string, index: number) => ({
"aria-label": index === 1 ? "品红" : "珊瑚红",
}));
items(typed)[0]!.element.focus();
keydown(items(typed)[0]!.element, "品");
expect(document.activeElement).toBe(items(typed)[1]!.element);
});
it("returns focus to the listbox when the focused item goes away", async () => {
const colors = shallowRef([...COLORS]);
const w = render(
defineComponent({
components: {
ColorSwatchPicker,
ColorSwatchPickerItem,
ColorSwatchPickerSwatch,
ColorSwatchPickerIndicator,
},
setup: () => ({ colors }),
template: `
<ColorSwatchPicker>
<ColorSwatchPickerItem v-for="c in colors" :key="c" :color="c">
<ColorSwatchPickerSwatch />
<ColorSwatchPickerIndicator />
</ColorSwatchPickerItem>
</ColorSwatchPicker>`,
}),
);
items(w)[1]!.element.focus();
colors.value = [COLORS[0]!, COLORS[2]!];
await w.vm.$nextTick();
expect(
w.get<HTMLElement>("[data-slot=color-swatch-picker]").attributes(
"tabindex",
),
).toBe("0");
});
});
describe("ColorSwatchPicker scoped slots", () => {
it("passes real item state to the item and indicator slots", async () => {
const w = render(
defineComponent({
components: {
ColorSwatchPicker,
ColorSwatchPickerItem,
ColorSwatchPickerSwatch,
ColorSwatchPickerIndicator,
},
data: () => ({ colors: COLORS }),
template: `
<ColorSwatchPicker default-value="#8B5CF6">
<ColorSwatchPickerItem
v-for="(c, index) in colors"
:key="index"
:color="c"
v-slot="state"
>
<ColorSwatchPickerSwatch :data-selected-state="state.isSelected" />
<ColorSwatchPickerIndicator>
<span data-custom-check>{{ state.color.toString('hex') }}</span>
</ColorSwatchPickerIndicator>
</ColorSwatchPickerItem>
</ColorSwatchPicker>`,
}),
);
const states = items(w).map((item) => ({
selected: item
.find("[data-slot=color-swatch-picker-swatch]")
.attributes("data-selected-state"),
check: item.find("[data-custom-check]").text(),
}));
expect(states).toEqual([
{ selected: "false", check: "#F43F5E" },
{ selected: "false", check: "#D946EF" },
{ selected: "true", check: "#8B5CF6" },
]);
});
it("exposes the root render state", async () => {
let seen: ColorSwatchPickerRenderProps | undefined;
const w = render(
defineComponent({
components: {
ColorSwatchPicker,
ColorSwatchPickerItem,
ColorSwatchPickerSwatch,
ColorSwatchPickerIndicator,
},
setup: () => ({ capture: (state: ColorSwatchPickerRenderProps) => { seen = state; } }),
data: () => ({ colors: COLORS }),
template: `
<ColorSwatchPicker v-slot="root" default-value="#8B5CF6" is-disabled>
<span data-probe>{{ capture(root) }}</span>
<ColorSwatchPickerItem v-for="(c, index) in colors" :key="index" :color="c">
<ColorSwatchPickerSwatch />
<ColorSwatchPickerIndicator />
</ColorSwatchPickerItem>
</ColorSwatchPicker>`,
}),
);
await w.vm.$nextTick();
expect(seen).toMatchObject({
isEmpty: false,
isDisabled: true,
isReadOnly: false,
layout: "grid",
});
expect(seen!.color?.toString("hex")).toBe("#8B5CF6");
});
});
describe("ColorSwatchPicker owner composition", () => {
function composition(attrs = "") {
return render(
defineComponent({
components: {
Picker,
ColorSwatchPicker,
ColorSwatchPickerItem,
ColorSwatchPickerSwatch,
ColorSwatchPickerIndicator,
},
data: () => ({ colors: COLORS }),
template: `
<form>
<Picker name="color" default-value="#8B5CF6" ${attrs}>
<ColorSwatchPicker>
<ColorSwatchPickerItem v-for="(c, index) in colors" :key="index" :color="c">
<ColorSwatchPickerSwatch />
<ColorSwatchPickerIndicator />
</ColorSwatchPickerItem>
</ColorSwatchPicker>
</Picker>
</form>`,
}),
);
}
it("inherits the owner color without a second state source", async () => {
const w = composition();
expect(items(w)[2]!.attributes("aria-selected")).toBe("true");
press(items(w)[0]!);
await w.vm.$nextTick();
const values = () =>
new FormData(w.get("form").element as HTMLFormElement).getAll("color");
expect(values()).toEqual([serializeColorValue(parseColor("#F43F5E"))]);
expect(items(w)[0]!.attributes("aria-selected")).toBe("true");
// Exactly one named submission while the picker children are mounted.
expect(w.element.querySelectorAll("input[name=color]")).toHaveLength(1);
});
it("keeps an explicit own value and switches ownership dynamically", async () => {
const own = composition('value="#D946EF"');
expect(items(own)[1]!.attributes("aria-selected")).toBe("true");
const controlled = shallowRef<string | undefined>(undefined);
const w = render(
defineComponent({
components: {
Picker,
ColorSwatchPicker,
ColorSwatchPickerItem,
ColorSwatchPickerSwatch,
ColorSwatchPickerIndicator,
},
setup: () => ({
controlled,
own: () => (controlled.value ? { value: controlled.value } : {}),
}),
data: () => ({ colors: COLORS }),
template: `
<Picker default-value="#8B5CF6">
<ColorSwatchPicker v-bind="own()">
<ColorSwatchPickerItem v-for="(c, index) in colors" :key="index" :color="c">
<ColorSwatchPickerSwatch />
<ColorSwatchPickerIndicator />
</ColorSwatchPickerItem>
</ColorSwatchPicker>
</Picker>`,
}),
);
expect(items(w)[2]!.attributes("aria-selected")).toBe("true");
controlled.value = "#F43F5E";
await w.vm.$nextTick();
expect(items(w)[0]!.attributes("aria-selected")).toBe("true");
controlled.value = undefined;
await w.vm.$nextTick();
expect(items(w)[2]!.attributes("aria-selected")).toBe("true");
});
it("restores the owner DOM after a form reset even when a rejection kept the value", async () => {
const value = shallowRef(parseColor("#8B5CF6"));
const w = render(
defineComponent({
components: {
Picker,
ColorSwatchPicker,
ColorSwatchPickerItem,
ColorSwatchPickerSwatch,
ColorSwatchPickerIndicator,
},
setup: () => ({ value }),
data: () => ({ colors: COLORS }),
template: `
<form>
<Picker name="color" :value="value">
<ColorSwatchPicker>
<ColorSwatchPickerItem v-for="(c, index) in colors" :key="index" :color="c">
<ColorSwatchPickerSwatch />
<ColorSwatchPickerIndicator />
</ColorSwatchPickerItem>
</ColorSwatchPicker>
</Picker>
</form>`,
}),
);
const native = w.get<HTMLInputElement>("input[type=hidden]");
const accepted = serializeColorValue(parseColor("#8B5CF6"));
expect(native.element.value).toBe(accepted);
press(items(w)[0]!);
await w.vm.$nextTick();
// The parent rejects: the accepted value and DOM stay put.
expect(native.element.value).toBe(accepted);
expect(items(w)[2]!.attributes("aria-selected")).toBe("true");
expect(items(w)[0]!.attributes("aria-selected")).toBe("false");
(w.get("form").element as HTMLFormElement).reset();
await new Promise((resolve) => setTimeout(resolve, 0));
expect(native.element.value).toBe(accepted);
expect(items(w)[2]!.attributes("aria-selected")).toBe("true");
});
});
+55
View File
@@ -182,6 +182,61 @@ for (const id of process.argv.slice(2)) {
"ColorSwatch declarations leak Reka types",
);
}
if (id === "color-swatch-picker") {
assert(lib.ColorSwatchPicker === lib.ColorSwatchPickerRoot);
assert(lib.ColorSwatchPickerItem);
assert(lib.ColorSwatchPickerSwatch);
assert(lib.ColorSwatchPickerIndicator);
assert(
lib
.colorSwatchPickerVariants()
.base()
.includes("hv-color-swatch-picker"),
);
assert(
lib
.colorSwatchPickerVariants({ layout: "stack", variant: "square" })
.base()
.includes("hv-color-swatch-picker--stack"),
);
assert(
lib
.colorSwatchPickerVariants({ size: "xs" })
.item() === "hv-color-swatch-picker__item",
);
assert(
lib
.colorSwatchPickerVariants()
.swatch() === "hv-color-swatch-picker__swatch",
);
assert(
lib
.colorSwatchPickerVariants()
.indicator() === "hv-color-swatch-picker__indicator",
);
const pickerDts = readFileSync(
new URL(
"./node_modules/@heroui-vue/components/dist/components/color-swatch-picker/ColorSwatchPicker.vue.d.ts",
import.meta.url,
),
"utf8",
);
const itemDts = readFileSync(
new URL(
"./node_modules/@heroui-vue/components/dist/components/color-swatch-picker/ColorSwatchPickerItem.vue.d.ts",
import.meta.url,
),
"utf8",
);
assert(
!pickerDts.includes("reka-ui"),
"ColorSwatchPicker declarations leak Reka types",
);
assert(
!itemDts.includes("reka-ui"),
"ColorSwatchPickerItem declarations leak Reka types",
);
}
if (id === "color-slider") {
assert(lib.ColorSlider === lib.ColorSliderRoot);
assert(lib.ColorSliderOutput);
+22 -1
View File
@@ -372,6 +372,27 @@
"repeating-conic-gradient"
]
},
"color-swatch-picker": {
"exports": [
"ColorSwatchPicker",
"ColorSwatchPickerRoot",
"ColorSwatchPickerItem",
"ColorSwatchPickerSwatch",
"ColorSwatchPickerIndicator",
"colorSwatchPickerVariants"
],
"css": [
".hv-color-swatch-picker",
".hv-color-swatch-picker--stack",
".hv-color-swatch-picker--square",
".hv-color-swatch-picker--xl",
".hv-color-swatch-picker__item",
".hv-color-swatch-picker__swatch",
".hv-color-swatch-picker__indicator",
"data-light-color",
"repeating-conic-gradient"
]
},
"time-field": {
"exports": [
"TimeField",
@@ -488,6 +509,6 @@
".hv-color-input-group__prefix",
".hv-color-input-group__suffix"
],
"absent": ["ColorPicker", "ColorSwatchPicker"]
"absent": ["ColorPicker"]
}
}
@@ -0,0 +1,137 @@
import { h } from "vue";
import {
ColorSwatchPicker,
ColorSwatchPickerRoot,
ColorSwatchPickerItem,
ColorSwatchPickerSwatch,
ColorSwatchPickerIndicator,
colorSwatchPickerVariants,
parseColor,
type ColorSwatchPickerProps,
type ColorSwatchPickerRootProps,
type ColorSwatchPickerItemProps,
type ColorSwatchPickerSwatchProps,
type ColorSwatchPickerIndicatorProps,
type ColorSwatchPickerExpose,
type ColorSwatchPickerItemExpose,
type ColorSwatchPickerItemRenderProps,
type ColorSwatchPickerItemSlots,
type ColorSwatchPickerIndicatorSlots,
type ColorSwatchPickerLayout,
type ColorSwatchPickerRenderProps,
type ColorSwatchPickerShape,
type ColorSwatchPickerSize,
type ColorSwatchPickerSlots,
type ColorSwatchPickerVariants,
} from "@heroui-vue/components";
const props: ColorSwatchPickerProps = {
modelValue: parseColor("#123456"),
value: "#abcdef",
defaultValue: null,
layout: "stack",
size: "xl",
variant: "square",
isDisabled: false,
disabled: false,
isReadOnly: true,
dir: "rtl",
as: "div",
};
const root: ColorSwatchPickerRootProps = props;
const item: ColorSwatchPickerItemProps = {
color: "hsl(210, 100%, 50%)",
isDisabled: true,
as: "div",
};
const swatch: ColorSwatchPickerSwatchProps = {
color: parseColor("#f008"),
colorName: "海洋蓝",
as: "span",
};
const indicator: ColorSwatchPickerIndicatorProps = { as: "span" };
const slots: ColorSwatchPickerSlots = {
default: (s) => [h("span", {}, [s.color?.toString("hex"), String(s.layout)])],
};
const itemSlots: ColorSwatchPickerItemSlots = {
default: (s: ColorSwatchPickerItemRenderProps) => [
h("span", s.isSelected ? s.color.toString("hexa") : "none"),
],
};
const indicatorSlots: ColorSwatchPickerIndicatorSlots = itemSlots;
const state: ColorSwatchPickerRenderProps = {
color: null,
isEmpty: false,
isDisabled: false,
isReadOnly: false,
isFocused: false,
layout: "grid",
};
const itemState: ColorSwatchPickerItemRenderProps = {
color: parseColor("#8B5CF6"),
isSelected: true,
isDisabled: false,
isFocused: true,
isFocusVisible: true,
isPressed: false,
isHovered: false,
};
const variant: ColorSwatchPickerVariants = {
layout: "grid",
size: "md",
variant: "circle",
};
const layout: ColorSwatchPickerLayout = "stack";
const size: ColorSwatchPickerSize = "xs";
const shape: ColorSwatchPickerShape = "square";
colorSwatchPickerVariants(variant).swatch();
h(ColorSwatchPicker, {
...props,
"onUpdate:modelValue": (value) => value.toString("hex"),
onChange: (value) => value.toString("hexa"),
});
h(ColorSwatchPickerRoot, root);
h(ColorSwatchPickerItem, item);
h(ColorSwatchPickerSwatch, swatch);
h(ColorSwatchPickerIndicator, indicator);
declare const picker: InstanceType<typeof ColorSwatchPicker>;
picker.focus();
picker.element?.focus();
const exposed: ColorSwatchPickerExpose = picker;
declare const row: InstanceType<typeof ColorSwatchPickerItem>;
row.element?.focus();
const itemExposed: ColorSwatchPickerItemExpose = row;
// @ts-expect-error invalid model
const bad: ColorSwatchPickerProps = { modelValue: 123 };
// @ts-expect-error invalid layout
const badLayout: ColorSwatchPickerProps = { layout: "carousel" };
// @ts-expect-error invalid size
const badSize: ColorSwatchPickerProps = { size: "huge" };
// @ts-expect-error invalid variant
h(ColorSwatchPicker, { variant: "pill" });
// @ts-expect-error actual public component rejects invalid model
h(ColorSwatchPicker, { modelValue: 123 });
// @ts-expect-error item color must be a color value
const badColor: ColorSwatchPickerItemProps = { color: 123 };
// @ts-expect-error no public transaction or owner state
picker.state.begin();
// @ts-expect-error item state is exposed through slots only
row.selectedKeys;
void [
slots,
itemSlots,
indicatorSlots,
state,
itemState,
exposed,
itemExposed,
bad,
badLayout,
badSize,
badColor,
layout,
size,
shape,
];