Files
heroui-vue/tests/color-input-foundation.test.ts
T

361 lines
15 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, shallowRef } from "vue";
import Input from "../packages/vue/tests/fixtures/ColorInputFoundation.vue";
import Picker from "../packages/vue/tests/fixtures/ColorPickerFoundation.vue";
import Area from "../packages/vue/tests/fixtures/ColorAreaFoundation.vue";
import { Color, parseColor } from "../packages/vue/src/components/color/value";
import { colorChannel } from "../packages/vue/src/components/color/channel";
import { parseColorNumber } from "../packages/vue/src/components/color/text";
import { Form } from "../packages/vue/src/index";
const wrappers: ReturnType<typeof mount>[] = [];
afterEach(() => {
wrappers.splice(0).forEach((w) => w.unmount());
document.body.innerHTML = "";
vi.restoreAllMocks();
});
function fixture(
template = '<Input name="color" default-value="#123456" aria-label="Color"/>',
setup = () => ({}),
) {
const w = mount(
defineComponent({
components: { Input, Picker, Area, Form },
setup,
template: `<form>${template}</form>`,
}),
{ attachTo: document.body },
);
wrappers.push(w);
return w;
}
const input = (w: ReturnType<typeof mount>) =>
w.get<HTMLInputElement>("[data-color-input]");
const changes = (w: ReturnType<typeof mount>, component = Input) =>
(w.getComponent(component).emitted("change") ?? []).map(
([v]) => v as Color | null,
);
async function enter(w: ReturnType<typeof mount>, text: string) {
await input(w).setValue(text);
await input(w).trigger("keydown", { key: "Enter" });
await flushPromises();
}
async function key(w: ReturnType<typeof mount>, key: string, extra = {}) {
await input(w).trigger("keydown", { key, ...extra });
await input(w).trigger("keyup", { key, ...extra });
await flushPromises();
}
const data = (w: ReturnType<typeof mount>) =>
new FormData(w.get("form").element as HTMLFormElement).getAll("color");
describe("color channel boundary", () => {
it("resolves space-specific channels and preserves HSB hue and alpha", () => {
const c = parseColor("hsb(270,0%,50%,.12345)");
expect(colorChannel(c, "hue").color.equals(c)).toBe(true);
expect(colorChannel(c, "red", "hsl").color.getColorSpace()).toBe("rgb");
expect(colorChannel(c, "saturation", "rgb").color.getColorSpace()).toBe(
"hsl",
);
expect(colorChannel(c, "alpha", "rgb").color.equals(c)).toBe(true);
});
it("parses localized channel numbers strictly and uses percent alpha", () => {
expect(parseColorNumber("١٢٫٥", "ar-EG", "alpha")).toBe(0.125);
expect(parseColorNumber("12,5 %", "de-DE", "saturation")).toBe(12.5);
expect(parseColorNumber("270°", "en-US", "hue")).toBe(270);
for (const t of ["1e2", "12junk", "1,234", "NaN", "--1"])
expect(parseColorNumber(t, "en-US", "red")).toBeUndefined();
expect(parseColorNumber("25%", "en-US", "red")).toBeUndefined();
});
});
describe("color text draft protocol", () => {
it("keeps partial drafts out of the model and commits normalized hex once", async () => {
const w = fixture();
await input(w).setValue("#f");
expect(changes(w)).toHaveLength(0);
expect(data(w)).toEqual(["#123456"]);
await enter(w, "abc");
expect(input(w).element.value).toBe("#AABBCC");
expect(changes(w)).toHaveLength(1);
expect(w.getComponent(Input).emitted("changeEnd")).toHaveLength(1);
expect(data(w)).toEqual(["#AABBCC"]);
});
it("rejects incomplete/malformed/alpha hex without changing accepted color", async () => {
const w = fixture();
for (const t of ["#f", "oops", "#12345678", "rgb(1,2,3)"]) {
await enter(w, t);
expect(input(w).element.value).toBe("#123456");
}
expect(changes(w)).toHaveLength(0);
});
it("restores rejected text and allows an identical proposal on the next commit", async () => {
const w = fixture('<Input model-value="#123456" name="color"/>');
await enter(w, "abc");
await enter(w, "abc");
expect(changes(w)).toHaveLength(2);
expect(w.getComponent(Input).emitted("changeEnd")).toHaveLength(2);
expect(input(w).element.value).toBe("#123456");
expect(data(w)).toEqual(["#123456"]);
});
it("preserves a gray hue and alpha when committing an unchanged hex", async () => {
const w = fixture('<Input default-value="hsb(270,0%,50%,.12345)"/>');
await enter(w, "808080");
expect(changes(w)).toHaveLength(0);
expect(
w.getComponent(Input).vm.state.value.value?.getChannelValue("hue"),
).toBe(270);
});
it("clears to null, keeps required validation, and reset restores captured defaults", async () => {
const w = fixture(
'<Input name="color" default-value="#123456" is-required/>',
);
await enter(w, "");
expect(changes(w).at(-1)).toBeNull();
expect(input(w).element.checkValidity()).toBe(false);
await flushPromises();
expect(w.text()).toContain("请选择颜色。");
(w.get("form").element as HTMLFormElement).reset();
await flushPromises();
expect(input(w).element.value).toBe("#123456");
expect(input(w).element.checkValidity()).toBe(true);
expect(changes(w)).toHaveLength(1);
});
it("uses draft numeric values for stepping and clamps channel commits", async () => {
const w = fixture(
'<Input name="color" channel="saturation" color-space="hsb" default-value="hsb(270,50%,50%,.12345)"/>',
);
await input(w).setValue("67");
await key(w, "ArrowUp");
expect(input(w).element.value).toBe("68");
expect(changes(w).at(-1)?.getChannelValue("hue")).toBe(270);
expect(changes(w).at(-1)?.getChannelValue("alpha")).toBe(0.12345);
await enter(w, "200");
expect(input(w).element.value).toBe("100");
await key(w, "Home");
expect(input(w).element.value).toBe("0");
await key(w, "End");
expect(data(w)).toEqual(["100"]);
});
it("formats locale decimal alpha, accepts percent, and submits model scale", async () => {
const w = fixture(
'<Input name="color" locale="de-DE" channel="alpha" default-value="hsb(270,0%,50%,.125)"/>',
);
expect(input(w).element.value).toBe("12,5");
await enter(w, "33,25%");
expect(data(w)).toEqual(["0.3325"]);
await key(w, "ArrowUp");
expect(input(w).element.value).toBe("34,25");
expect(changes(w).at(-1)?.getChannelValue("hue")).toBe(270);
});
it("cancels drafts on escape and external accepted replacement", async () => {
const value = shallowRef<Color | null>(parseColor("#123456"));
const w = fixture('<Input :model-value="value"/>', () => ({ value }));
await input(w).setValue("#abc");
await key(w, "Escape");
expect(input(w).element.value).toBe("#123456");
await input(w).setValue("#def");
value.value = parseColor("#654321");
await flushPromises();
expect(input(w).element.value).toBe("#654321");
expect(changes(w)).toHaveLength(0);
});
it("does not commit the Enter used to finish IME composition", async () => {
const w = fixture();
await input(w).trigger("compositionstart");
await input(w).setValue("abc");
await input(w).trigger("keydown", { key: "Enter" });
expect(changes(w)).toHaveLength(0);
await input(w).trigger("compositionend");
await flushPromises();
await input(w).trigger("keydown", { key: "Enter" });
expect(changes(w)).toHaveLength(1);
});
it("honors canceled events, readonly and disabled", async () => {
const ro = shallowRef(false),
off = shallowRef(false);
const w = fixture(
'<Input :is-read-only="ro" :is-disabled="off" default-value="#123456" @keydown="$event.preventDefault()"/>',
() => ({ ro, off }),
);
await enter(w, "abc");
expect(changes(w)).toHaveLength(0);
ro.value = true;
await flushPromises();
await enter(w, "abc");
expect(changes(w)).toHaveLength(0);
off.value = true;
await flushPromises();
expect(input(w).element.disabled).toBe(true);
});
it("resets actual controlled text even when parent value never changes", async () => {
const w = fixture('<Input model-value="#123456" name="color"/>');
await input(w).setValue("#abc");
(w.get("form").element as HTMLFormElement).reset();
await flushPromises();
expect(input(w).element.value).toBe("#123456");
expect(data(w)).toEqual(["#123456"]);
expect(changes(w)).toHaveLength(0);
});
it("honors canceled reset and external form association", async () => {
const external = document.createElement("form");
external.id = "external";
document.body.append(external);
const w = fixture(
'<Input form="external" name="color" default-value="#123456"/>',
);
await enter(w, "abc");
const form = external;
form.addEventListener("reset", (e) => e.preventDefault(), { once: true });
form.reset();
await flushPromises();
expect(input(w).element.value).toBe("#AABBCC");
form.reset();
await flushPromises();
expect(input(w).element.value).toBe("#123456");
});
});
describe("native channel shared transaction bridge", () => {
it("groups held keys, uses channel page steps and RTL, restores accepted fractions", async () => {
const w = fixture(
'<Input mode="range" channel="alpha" name="color" default-value="hsb(270,0%,50%,.12345)" dir="rtl"/>',
);
await input(w).trigger("keydown", { key: "ArrowLeft" });
await input(w).trigger("keydown", { key: "ArrowLeft", repeat: true });
await input(w).trigger("keyup", { key: "ArrowLeft" });
expect(changes(w)).toHaveLength(2);
expect(w.getComponent(Input).emitted("changeEnd")).toHaveLength(1);
expect(Number(input(w).element.value)).toBeCloseTo(0.14345);
await key(w, "PageUp");
expect(Number(input(w).element.value)).toBeCloseTo(0.24345);
expect(changes(w).at(-1)?.getChannelValue("hue")).toBe(270);
});
it("keeps rejected native input and submission at the accepted value", async () => {
const w = fixture(
'<Input mode="range" channel="hue" name="color" model-value="hsb(270,0%,50%)"/>',
);
await input(w).setValue("120");
await flushPromises();
expect(input(w).element.value).toBe("270");
expect(data(w)).toEqual(["270"]);
await input(w).setValue("120");
await flushPromises();
expect(changes(w)).toHaveLength(2);
});
it("emits final proposal after rejection, and cancel does not emit completion", async () => {
const w = fixture(
'<Input mode="range" channel="hue" model-value="hsb(270,0%,50%)"/>',
);
await input(w).trigger("keydown", { key: "ArrowUp" });
await input(w).trigger("keyup", { key: "ArrowUp" });
expect(
(
w.getComponent(Input).emitted("changeEnd")?.[0]?.[0] as Color
).getChannelValue("hue"),
).toBe(271);
await input(w).trigger("keydown", { key: "ArrowUp" });
await key(w, "Escape");
expect(w.getComponent(Input).emitted("changeEnd")).toHaveLength(1);
});
it("shares one owner across area, native channel and text", async () => {
const w = fixture(
'<Picker name="owner" default-value="hsb(270,0%,50%,.12345)" v-slot><Area/><Input mode="range" channel="hue"/><Input channel="alpha" name="color"/></Picker>',
);
const fields = w.findAll<HTMLInputElement>("[data-color-input]");
await fields[0]!.trigger("keydown", { key: "ArrowUp" });
await fields[0]!.trigger("keyup", { key: "ArrowUp" });
await fields[1]!.setValue("25");
await fields[1]!.trigger("keydown", { key: "Enter" });
const c = changes(w, Picker).at(-1)!;
expect(c.getChannelValue("hue")).toBe(271);
expect(c.getChannelValue("alpha")).toBe(0.25);
expect(
w.getComponent(Area).get('[data-axis="x"]').attributes("aria-valuetext"),
).toContain("0");
expect(changes(w)).toHaveLength(0);
expect(data(w)).toEqual(["0.25"]);
});
});
describe("color input lifecycle integration", () => {
it("does not let inactive input controllers overwrite the current mode", async () => {
const mode = shallowRef<"text" | "range">("text");
const w = fixture(
'<Input :mode="mode" channel="hue" default-value="hsb(270,0%,50%)"/>',
() => ({ mode }),
);
await flushPromises();
expect(input(w).element.value).toBe("270");
mode.value = "range";
await flushPromises();
await key(w, "ArrowUp");
expect(input(w).element.value).toBe("271");
mode.value = "text";
await flushPromises();
expect(input(w).element.value).toBe("271");
});
it("cancels an unfinished native transaction on disable, external replacement and window blur", async () => {
const off = shallowRef(false),
value = shallowRef(parseColor("hsb(270,0%,50%)"));
const w = fixture(
'<Input mode="range" channel="hue" :model-value="value" :is-disabled="off"/>',
() => ({ off, value }),
);
await input(w).trigger("keydown", { key: "ArrowUp" });
off.value = true;
await flushPromises();
await input(w).trigger("keyup", { key: "ArrowUp" });
expect(w.getComponent(Input).emitted("changeEnd")).toBeUndefined();
off.value = false;
await flushPromises();
await input(w).trigger("keydown", { key: "ArrowUp" });
value.value = parseColor("hsb(90,0%,50%)");
await flushPromises();
await input(w).trigger("keyup", { key: "ArrowUp" });
expect(input(w).element.value).toBe("90");
expect(w.getComponent(Input).emitted("changeEnd")).toBeUndefined();
await input(w).trigger("keydown", { key: "ArrowUp" });
window.dispatchEvent(new Event("blur"));
await input(w).trigger("keyup", { key: "ArrowUp" });
expect(w.getComponent(Input).emitted("changeEnd")).toBeUndefined();
});
it("clears unfinished composition on blur and prevents stale drafts after unmount", async () => {
const w = fixture();
await input(w).trigger("compositionstart");
await input(w).setValue("abc");
await input(w).trigger("blur");
expect(input(w).element.value).toBe("#123456");
expect(changes(w)).toHaveLength(0);
});
it("uses existing Form server errors and dismisses them on a text edit", async () => {
const w = mount(
defineComponent({
components: { Input, Form },
template:
'<Form :validation-errors="{color:\'颜色不可用\'}"><Input name="color" default-value="#123456"/></Form>',
}),
{ attachTo: document.body },
);
wrappers.push(w);
expect(w.text()).toContain("颜色不可用");
await input(w).setValue("abc");
expect(w.text()).not.toContain("颜色不可用");
});
it("keeps aria validation out of native form blocking and applies custom validation to accepted values", async () => {
const w = fixture(
'<Input name="color" default-value="#123456" validation-behavior="aria" :validate="()=>\'错误颜色\'"/>',
);
expect(input(w).attributes("aria-invalid")).toBe("true");
expect(input(w).element.checkValidity()).toBe(true);
});
it("preserves separate child owners and leaves sibling transactions alone on unmount", async () => {
const show = shallowRef(true);
const w = fixture(
'<Picker default-value="hsb(270,0%,50%)" v-slot><Input mode="range" channel="hue"/><Input v-if="show" default-value="#123456"/></Picker>',
() => ({ show }),
);
const first = w.findAll("[data-color-input]")[0]!;
await first.trigger("keydown", { key: "ArrowUp" });
show.value = false;
await flushPromises();
await first.trigger("keyup", { key: "ArrowUp" });
expect(w.getComponent(Picker).emitted("changeEnd")).toHaveLength(1);
});
});