Files
heroui-vue/tests/color-swatch-picker.test.ts
T

888 lines
34 KiB
TypeScript

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");
});
});
describe("ColorSwatchPicker activation lifecycle and dynamic focus", () => {
it("ignores secondary mouse buttons", async () => {
const w = picker();
items(w)[1]!.element.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 2 }));
await w.vm.$nextTick();
expect(w.getComponent(ColorSwatchPicker).emitted("update:modelValue")).toBeUndefined();
// Middle-button counter-example: never a selection gesture either.
items(w)[1]!.element.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 1 }));
await w.vm.$nextTick();
expect(w.getComponent(ColorSwatchPicker).emitted("update:modelValue")).toBeUndefined();
expect(items(w)[1]!.attributes("aria-selected")).toBe("false");
expect(items(w)[1]!.attributes("data-pressed")).toBeUndefined();
});
it("clears pressed state after the primary mouse release", async () => {
const w = picker();
press(items(w)[0]!);
items(w)[0]!.element.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, cancelable: true, button: 0 }));
await w.vm.$nextTick();
expect(items(w)[0]!.attributes("data-pressed")).toBeUndefined();
// A release elsewhere inside the listbox clears the state as well.
press(items(w)[1]!);
w.get("[data-slot=color-swatch-picker]").element.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, cancelable: true, button: 0 }));
await w.vm.$nextTick();
expect(items(w)[1]!.attributes("data-pressed")).toBeUndefined();
// Dragging out cancels the press before any release.
press(items(w)[2]!);
items(w)[2]!.trigger("mouseleave");
await w.vm.$nextTick();
expect(items(w)[2]!.attributes("data-pressed")).toBeUndefined();
// A press that steals focus from another item keeps its own press state.
items(w)[1]!.element.focus();
await w.vm.$nextTick();
press(items(w)[0]!);
await w.vm.$nextTick();
expect(items(w)[0]!.attributes("data-pressed")).toBe("true");
items(w)[0]!.element.dispatchEvent(new MouseEvent("mouseup", { bubbles: true, cancelable: true, button: 0 }));
await w.vm.$nextTick();
expect(items(w)[0]!.attributes("data-pressed")).toBeUndefined();
});
it("keeps an enabled tab entry after dynamically disabling the focused item", async () => {
const off = shallowRef(false);
const w = render(defineComponent({
components: { ColorSwatchPicker, ColorSwatchPickerItem },
setup: () => ({ off }),
template: `<ColorSwatchPicker><ColorSwatchPickerItem color="#F43F5E" :is-disabled="off"/><ColorSwatchPickerItem color="#D946EF"/></ColorSwatchPicker>`,
}));
items(w)[0]!.element.focus();
await w.vm.$nextTick();
off.value = true;
await w.vm.$nextTick();
await w.vm.$nextTick();
const root = w.get("[data-slot=color-swatch-picker]");
const enabledTabEntries = [root, ...items(w)].filter(node => node.attributes("tabindex") === "0" && node.attributes("aria-disabled") !== "true");
expect(enabledTabEntries).toHaveLength(1);
// Focus is not lost to the document while the entry is rebuilt.
expect(document.activeElement).not.toBe(document.body);
// Re-enabling the item keeps a single legal entry again.
off.value = false;
await w.vm.$nextTick();
await w.vm.$nextTick();
expect([root, ...items(w)].filter(node => node.attributes("tabindex") === "0" && node.attributes("aria-disabled") !== "true")).toHaveLength(1);
});
it("keeps legal tab entries for all-disabled items and a disabled root", async () => {
const off = shallowRef(false);
const w = render(defineComponent({
components: { ColorSwatchPicker, ColorSwatchPickerItem },
setup: () => ({ off }),
template: `<ColorSwatchPicker :is-disabled="off"><ColorSwatchPickerItem color="#F43F5E" is-disabled/><ColorSwatchPickerItem color="#D946EF" is-disabled/></ColorSwatchPicker>`,
}));
const root = w.get("[data-slot=color-swatch-picker]");
// Every option disabled: the listbox itself stays the single entry.
expect([root, ...items(w)].filter(node => node.attributes("tabindex") === "0" && node.attributes("aria-disabled") !== "true")).toHaveLength(1);
// A disabled root leaves the tab order entirely, then restores one entry.
off.value = true;
await w.vm.$nextTick();
expect([root, ...items(w)].filter(node => node.attributes("tabindex") === "0")).toHaveLength(0);
off.value = false;
await w.vm.$nextTick();
expect([root, ...items(w)].filter(node => node.attributes("tabindex") === "0" && node.attributes("aria-disabled") !== "true")).toHaveLength(1);
});
it("supports click-only activation used by assistive technology", async () => {
const w = picker();
items(w)[1]!.element.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, detail: 0 }));
await w.vm.$nextTick();
expect(items(w)[1]!.attributes("aria-selected")).toBe("true");
});
it("keeps press ownership so normal clicks never re-propose", async () => {
const w = picker();
const root = w.getComponent(ColorSwatchPicker);
press(items(w)[1]!);
// The compatibility click of the press does not emit a second proposal.
items(w)[1]!.element.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, detail: 1 }));
await w.vm.$nextTick();
expect(root.emitted("update:modelValue")).toHaveLength(1);
// Click-only activation stays cancelable and skips disabled items.
const cancelled = picker({}, COLORS, { onClick: (event: MouseEvent) => event.preventDefault() });
items(cancelled)[0]!.element.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, detail: 0 }));
await cancelled.vm.$nextTick();
expect(cancelled.getComponent(ColorSwatchPicker).emitted("update:modelValue")).toBeUndefined();
const disabled = picker({}, COLORS, (_c: string, index: number) => ({ isDisabled: index === 1 }));
items(disabled)[1]!.element.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, detail: 0 }));
await disabled.vm.$nextTick();
expect(disabled.getComponent(ColorSwatchPicker).emitted("update:modelValue")).toBeUndefined();
});
});