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[] = []; function render( component: Parameters[0], options: Parameters[1] = {}, ) { const w = mount(component, { attachTo: document.body, ...options }); mounted.push(w); return w; } function area( props: Record = {}, template = '', setup: () => Record = () => ({}), ) { 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) => w.get("[data-slot=color-area]"); const thumb = (w: ReturnType) => w.get("[data-slot=color-area-thumb]"); const x = (w: ReturnType) => w.get('[data-axis="x"]'); const y = (w: ReturnType) => w.get('[data-axis="y"]'); const axisValue = (w: ReturnType, axis: "x" | "y") => w.get(`[data-axis="${axis}"]`).element.value; const thumbColor = (w: ReturnType) => thumb(w).element.style.getPropertyValue("--color-area-thumb-color"); const emitted = (w: ReturnType, name: string) => w.findComponent(ColorArea).emitted(name) ?? []; async function key( w: ReturnType, 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, selector = "[data-slot=color-area]", ) { const node = w.get(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: ``, }), ); 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: ` `, }), ); 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( {}, `
`, () => ({ 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( {}, ``, () => ({ 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: ``, }), ); 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( {}, ` `, ); 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( {}, `
`, ); 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( {}, `
`, ); 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>({}); const w = render( defineComponent({ components: { Picker: ColorPickerFoundation, ColorArea, ColorAreaThumb, ColorSwatch, }, setup: () => ({ override }), template: `
`, }), ); const picker = w.findComponent(ColorPickerFoundation); const swatch = () => w.get("[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( {}, ` `, () => ({ 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( {}, ``, ); 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( {}, `
说明
`, ); const roots = labelled.findAll("[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( {}, ``, ); expect(axisValue(both, "x")).toBe("255"); expect(thumbColor(both)).toBe("rgb(255, 0, 0)"); const valueOnly = area( {}, ``, ); 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>({ defaultValue: "hsb(240, 50%, 50%)", colorSpace: "hsb", }); const w = area( {}, ``, () => ({ 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: ``, }), ), ).toThrow(/ColorAreaThumb must be rendered inside ColorArea/); }); });