493 lines
19 KiB
TypeScript
493 lines
19 KiB
TypeScript
import { afterEach, describe, it, expect, vi } from "vitest";
|
||
import { mount, flushPromises } from "@vue/test-utils";
|
||
import { defineComponent, shallowRef } from "vue";
|
||
import ColorField from "../packages/vue/src/components/color-field/ColorField.vue";
|
||
import ColorInputGroup from "../packages/vue/src/components/color-field/ColorInputGroup.vue";
|
||
import ColorInputGroupInput from "../packages/vue/src/components/color-field/ColorInputGroupInput.vue";
|
||
import Prefix from "../packages/vue/src/components/color-field/ColorInputGroupPrefix.vue";
|
||
import Suffix from "../packages/vue/src/components/color-field/ColorInputGroupSuffix.vue";
|
||
import {
|
||
Label,
|
||
Description,
|
||
FieldError,
|
||
Form,
|
||
TextField,
|
||
Fieldset,
|
||
Button,
|
||
} from "../packages/vue/src/index";
|
||
import Picker from "../packages/vue/tests/fixtures/ColorPickerFoundation.vue";
|
||
import {
|
||
parseColor,
|
||
type Color,
|
||
} from "../packages/vue/src/components/color/value";
|
||
const components = {
|
||
ColorField,
|
||
ColorInputGroup,
|
||
ColorInputGroupInput,
|
||
Prefix,
|
||
Suffix,
|
||
Label,
|
||
Description,
|
||
FieldError,
|
||
Form,
|
||
TextField,
|
||
Fieldset,
|
||
Button,
|
||
Picker,
|
||
};
|
||
const wrappers: ReturnType<typeof mount>[] = [];
|
||
afterEach(() => {
|
||
wrappers.splice(0).forEach((w) => w.unmount());
|
||
document.body.innerHTML = "";
|
||
vi.restoreAllMocks();
|
||
});
|
||
function view(body: string, setup = () => ({})) {
|
||
const w = mount(
|
||
defineComponent({
|
||
components,
|
||
setup,
|
||
template: body.trim().startsWith("<Form") ? body : `<form>${body}</form>`,
|
||
}),
|
||
{ attachTo: document.body },
|
||
);
|
||
wrappers.push(w);
|
||
return w;
|
||
}
|
||
function field(attrs = "", inputAttrs = "", extra = "") {
|
||
return `<ColorField name="color" ${attrs}><Label>Color label</Label><ColorInputGroup><Prefix>#</Prefix><ColorInputGroupInput ${inputAttrs}/><Suffix>${extra}</Suffix></ColorInputGroup><Description>Color description</Description><FieldError/></ColorField>`;
|
||
}
|
||
const input = (w: ReturnType<typeof mount>) =>
|
||
w.get<HTMLInputElement>("[data-slot=color-input-group-input]");
|
||
const changes = (w: ReturnType<typeof mount>) =>
|
||
(w.getComponent(ColorField).emitted("change") ?? []).map(
|
||
([v]) => v as Color | null,
|
||
);
|
||
const data = (w: ReturnType<typeof mount>) =>
|
||
new FormData(w.get("form").element as HTMLFormElement).getAll("color");
|
||
async function edit(w: ReturnType<typeof mount>, value: string) {
|
||
await input(w).setValue(value);
|
||
await input(w).trigger("keydown", { key: "Enter" });
|
||
await flushPromises();
|
||
}
|
||
describe("color field composed protocol", () => {
|
||
it("associates a native label, description and exact input override before rendering", async () => {
|
||
const w = view(field('default-value="#123456"', 'id="leaf"'));
|
||
expect(w.get("label").attributes("for")).toBe("leaf");
|
||
expect(input(w).attributes("id")).toBe("leaf");
|
||
expect(input(w).attributes("aria-describedby")).toBe(
|
||
w.get("[data-slot=description]").attributes("id"),
|
||
);
|
||
expect(w.get("[data-slot=color-input-group]").attributes("role")).toBe(
|
||
"presentation",
|
||
);
|
||
expect(input(w).attributes("aria-label")).toBeUndefined();
|
||
expect(data(w)).toEqual(["#123456"]);
|
||
});
|
||
it("uses localized channel units and the upstream percent submission scale", async () => {
|
||
const w = view(
|
||
field(
|
||
'channel="saturation" color-space="hsb" locale="de-DE" default-value="hsb(270,50%,50%)"',
|
||
),
|
||
);
|
||
expect(input(w).element.value).toBe("50 %");
|
||
expect(data(w)).toEqual(["0.5"]);
|
||
await edit(w, "33,25%");
|
||
expect(input(w).element.value).toBe("33 %");
|
||
expect(data(w)).toEqual(["0.33"]);
|
||
expect(changes(w).at(-1)?.getChannelValue("hue")).toBe(270);
|
||
expect(w.findAll("input[name=color]")).toHaveLength(1);
|
||
});
|
||
it("uses alpha percentage text but fractional submission, and hue degrees", async () => {
|
||
const w = view(
|
||
field('channel="alpha" default-value="hsba(270,0%,50%,.125)"'),
|
||
);
|
||
expect(input(w).element.value).toBe("13%");
|
||
expect(data(w)).toEqual(["0.13"]);
|
||
await edit(w, "25%");
|
||
expect(data(w)).toEqual(["0.25"]);
|
||
expect(changes(w).at(-1)?.getChannelValue("hue")).toBe(270);
|
||
const hue = view(
|
||
field('channel="hue" color-space="hsb" default-value="hsb(270,0%,50%)"'),
|
||
);
|
||
expect(input(hue).element.value).toBe("270°");
|
||
await edit(hue, "271°");
|
||
expect(data(hue)).toEqual(["271"]);
|
||
});
|
||
it("preserves unedited precision despite a rounded localized presentation", async () => {
|
||
const w = view(
|
||
field(
|
||
'channel="alpha" default-value="hsba(270,0%,50%,.123456789012345)"',
|
||
),
|
||
);
|
||
await input(w).trigger("keydown", { key: "Enter" });
|
||
expect(changes(w)).toHaveLength(0);
|
||
expect(data(w)).toEqual(["0.12"]);
|
||
});
|
||
it("restores rejected text and retries identical proposals", async () => {
|
||
const w = view(
|
||
field(
|
||
'channel="saturation" color-space="hsb" model-value="hsb(270,50%,50%)"',
|
||
),
|
||
);
|
||
await edit(w, "70%");
|
||
await edit(w, "70%");
|
||
expect(changes(w)).toHaveLength(2);
|
||
expect(input(w).element.value).toBe("50%");
|
||
expect(data(w)).toEqual(["0.5"]);
|
||
});
|
||
it("keeps native hex drafts out of the accepted color until commit and restores on Escape", async () => {
|
||
const w = view(field('default-value="#123456"'));
|
||
await input(w).setValue("#ab");
|
||
expect(data(w)).toEqual(["#ab"]);
|
||
expect(changes(w)).toHaveLength(0);
|
||
await input(w).trigger("keydown", { key: "Escape" });
|
||
expect(input(w).element.value).toBe("#123456");
|
||
await edit(w, "abc");
|
||
expect(data(w)).toEqual(["#AABBCC"]);
|
||
});
|
||
it("allows native Enter submission after committing while caller cancellation wins", async () => {
|
||
const cancel = shallowRef(true);
|
||
const w = view(
|
||
field(
|
||
'default-value="#123456" @keydown="cancel&&$event.preventDefault()"',
|
||
),
|
||
() => ({ cancel }),
|
||
);
|
||
await input(w).setValue("abc");
|
||
let e = new KeyboardEvent("keydown", {
|
||
key: "Enter",
|
||
bubbles: true,
|
||
cancelable: true,
|
||
});
|
||
input(w).element.dispatchEvent(e);
|
||
await flushPromises();
|
||
expect(changes(w)).toHaveLength(0);
|
||
cancel.value = false;
|
||
await flushPromises();
|
||
e = new KeyboardEvent("keydown", {
|
||
key: "Enter",
|
||
bubbles: true,
|
||
cancelable: true,
|
||
});
|
||
input(w).element.dispatchEvent(e);
|
||
await flushPromises();
|
||
expect(e.defaultPrevented).toBe(false);
|
||
expect(data(w)).toEqual(["#AABBCC"]);
|
||
});
|
||
it("chains root and input native event handlers exactly once before internal behavior", async () => {
|
||
const root = vi.fn(),
|
||
leaf = vi.fn((e: Event) => e.preventDefault());
|
||
const w = view(
|
||
field('default-value="#123456" @keydown="root"', '@keydown="leaf"'),
|
||
() => ({ root, leaf }),
|
||
);
|
||
await edit(w, "abc");
|
||
expect(root).toHaveBeenCalledOnce();
|
||
expect(leaf).toHaveBeenCalledOnce();
|
||
expect(changes(w)).toHaveLength(0);
|
||
});
|
||
it("wheels only a focused enabled field, respects horizontal scroll and isWheelDisabled", async () => {
|
||
const off = shallowRef(false);
|
||
const w = view(
|
||
field('default-value="#123456" :is-wheel-disabled="off"'),
|
||
() => ({ off }),
|
||
);
|
||
await input(w).trigger("wheel", { deltaY: 1, deltaX: 0 });
|
||
expect(changes(w)).toHaveLength(0);
|
||
input(w).element.focus();
|
||
await input(w).trigger("wheel", { deltaY: 1, deltaX: 2 });
|
||
expect(changes(w)).toHaveLength(0);
|
||
await input(w).trigger("wheel", { deltaY: 1, deltaX: 0 });
|
||
expect(data(w)).toEqual(["#123457"]);
|
||
off.value = true;
|
||
await flushPromises();
|
||
await input(w).trigger("wheel", { deltaY: 1, deltaX: 0 });
|
||
expect(changes(w)).toHaveLength(1);
|
||
});
|
||
it("required native/aria validation attaches visible error and resets without emitting", async () => {
|
||
const w = view(field("is-required"));
|
||
expect(input(w).element.required).toBe(true);
|
||
expect(input(w).element.checkValidity()).toBe(false);
|
||
await flushPromises();
|
||
expect(w.get("[data-slot=field-error]").text()).toBe("请选择颜色。");
|
||
const error = w.get("[data-slot=field-error]").attributes("id");
|
||
expect(input(w).attributes("aria-describedby")).toContain(error);
|
||
await edit(w, "abc");
|
||
expect(input(w).element.checkValidity()).toBe(true);
|
||
(w.get("form").element as HTMLFormElement).reset();
|
||
await flushPromises();
|
||
expect(input(w).element.value).toBe("");
|
||
expect(w.find("[data-slot=field-error]").exists()).toBe(false);
|
||
expect(changes(w)).toHaveLength(1);
|
||
const aria = view(field('is-required validation-behavior="aria"'));
|
||
expect(input(aria).element.required).toBe(false);
|
||
expect(input(aria).attributes("aria-required")).toBe("true");
|
||
expect(input(aria).element.checkValidity()).toBe(true);
|
||
expect(input(aria).attributes("aria-invalid")).toBe("true");
|
||
});
|
||
it("uses existing Form server errors and color validation, with generic field isolation", async () => {
|
||
const validate = vi.fn((value: Color | null) =>
|
||
value?.toString("hex") === "#AABBCC" ? "不允许此颜色" : true,
|
||
);
|
||
const w = view(
|
||
`<Form :validation-errors="{color:'服务端错误'}">${field('default-value="#123456" :validate="validate"')}</Form>`,
|
||
() => ({ validate }),
|
||
);
|
||
expect(w.get("[data-slot=field-error]").text()).toBe("服务端错误");
|
||
await edit(w, "abc");
|
||
expect(w.get("[data-slot=field-error]").text()).toBe("不允许此颜色");
|
||
expect(validate.mock.calls.at(-1)?.[0]).toBeInstanceOf(Object);
|
||
expect(input(w).element.checkValidity()).toBe(false);
|
||
});
|
||
it("honors root/leaf and Fieldset disabled, readonly and later programmatic values", async () => {
|
||
const off = shallowRef(true),
|
||
value = shallowRef(parseColor("#123456"));
|
||
const w = view(
|
||
`<Fieldset :disabled="off">${field(':model-value="value"')}</Fieldset>`,
|
||
() => ({ off, value }),
|
||
);
|
||
expect(input(w).element.disabled).toBe(true);
|
||
expect(data(w)).toEqual([]);
|
||
value.value = parseColor("#654321");
|
||
await flushPromises();
|
||
expect(input(w).element.value).toBe("#654321");
|
||
off.value = false;
|
||
await flushPromises();
|
||
expect(data(w)).toEqual(["#654321"]);
|
||
const ro = view(field('default-value="#123456"', "readonly"));
|
||
await edit(ro, "abc");
|
||
expect(changes(ro)).toHaveLength(0);
|
||
expect(input(ro).element.readOnly).toBe(true);
|
||
});
|
||
it("updates native leaf name/form/ID dynamically and respects canceled reset", async () => {
|
||
const external = document.createElement("form");
|
||
external.id = "external";
|
||
document.body.append(external);
|
||
const id = shallowRef("first"),
|
||
name = shallowRef("color");
|
||
const w = view(
|
||
field('default-value="#123456"', ':id="id" :name="name" form="external"'),
|
||
() => ({ id, name }),
|
||
);
|
||
id.value = "second";
|
||
name.value = "other";
|
||
await flushPromises();
|
||
expect(w.get("label").attributes("for")).toBe("second");
|
||
expect(new FormData(external).getAll("other")).toEqual(["#123456"]);
|
||
await edit(w, "abc");
|
||
external.addEventListener("reset", (e) => e.preventDefault(), {
|
||
once: true,
|
||
});
|
||
external.reset();
|
||
await flushPromises();
|
||
expect(input(w).element.value).toBe("#AABBCC");
|
||
external.reset();
|
||
await flushPromises();
|
||
expect(input(w).element.value).toBe("#123456");
|
||
});
|
||
it("shares a Picker owner and does not mutate an enclosing TextField", async () => {
|
||
const outer = shallowRef("outer");
|
||
const w = view(
|
||
`<TextField v-model="outer"><Picker default-value="hsb(270,50%,50%)" v-slot>${field('channel="hue" color-space="hsb"')}</Picker></TextField>`,
|
||
() => ({ outer }),
|
||
);
|
||
await edit(w, "271°");
|
||
expect(w.getComponent(Picker).emitted("change")).toHaveLength(1);
|
||
expect(changes(w)).toHaveLength(0);
|
||
expect(outer.value).toBe("outer");
|
||
});
|
||
it("keeps an independent group a regular text control and respects controlled rejection/reset", async () => {
|
||
const w = view(
|
||
'<ColorInputGroup><Prefix>Text</Prefix><ColorInputGroupInput name="color" model-value="accepted" aria-label="Standalone"/><Suffix>suffix</Suffix></ColorInputGroup>',
|
||
);
|
||
expect(w.get("[data-slot=color-input-group]").attributes("role")).toBe(
|
||
"group",
|
||
);
|
||
await input(w).setValue("rejected");
|
||
await flushPromises();
|
||
expect(input(w).element.value).toBe("accepted");
|
||
expect(data(w)).toEqual(["accepted"]);
|
||
(w.get("form").element as HTMLFormElement).reset();
|
||
await flushPromises();
|
||
expect(input(w).element.value).toBe("accepted");
|
||
});
|
||
it("focuses the input from plain affixes but keeps interactive suffix focus and focus-within state", async () => {
|
||
const w = view(
|
||
field(
|
||
'default-value="#123456"',
|
||
"",
|
||
'<Button type="button">Action</Button>',
|
||
),
|
||
);
|
||
await w.get("[data-slot=color-input-group-prefix]").trigger("click");
|
||
expect(document.activeElement).toBe(input(w).element);
|
||
const button = w.get("button").element;
|
||
button.focus();
|
||
await w.get("button").trigger("click");
|
||
expect(document.activeElement).toBe(button);
|
||
expect(
|
||
w.get("[data-slot=color-input-group]").attributes("data-focus-within"),
|
||
).toBe("true");
|
||
});
|
||
});
|
||
describe("color field ownership and native boundaries", () => {
|
||
it("switches channel/name mode with only one successful named input", async () => {
|
||
const channel = shallowRef<"saturation" | undefined>("saturation");
|
||
const w = view(
|
||
field(
|
||
':channel="channel" color-space="hsb" default-value="hsb(270,50%,50%)"',
|
||
),
|
||
() => ({ channel }),
|
||
);
|
||
expect(data(w)).toEqual(["0.5"]);
|
||
channel.value = undefined;
|
||
await flushPromises();
|
||
expect(data(w)).toEqual(["#604080"]);
|
||
expect(w.findAll("input[name=color]")).toHaveLength(1);
|
||
channel.value = "saturation";
|
||
await flushPromises();
|
||
expect(data(w)).toEqual(["0.5"]);
|
||
});
|
||
it("keeps boolean HTML attributes present, supports autofocus and joins explicit ARIA relationships", async () => {
|
||
const w = view(
|
||
field(
|
||
'default-value="#123456"',
|
||
'autofocus readonly="false" aria-labelledby="external-label" aria-describedby="external-description"',
|
||
),
|
||
);
|
||
expect(document.activeElement).toBe(input(w).element);
|
||
expect(input(w).element.readOnly).toBe(true);
|
||
expect(input(w).attributes("aria-labelledby")).toBe("external-label");
|
||
expect(input(w).attributes("aria-describedby")).toContain(
|
||
"external-description",
|
||
);
|
||
});
|
||
it("restores raw controlled native input after canceled reset and a rejected clear", async () => {
|
||
const w = view(field('model-value="#123456"'));
|
||
await edit(w, "");
|
||
expect(input(w).element.value).toBe("#123456");
|
||
await input(w).setValue("#ab");
|
||
const form = w.get("form").element as HTMLFormElement;
|
||
form.addEventListener("reset", (e) => e.preventDefault(), { once: true });
|
||
form.reset();
|
||
await flushPromises();
|
||
expect(input(w).element.value).toBe("#ab");
|
||
form.reset();
|
||
await flushPromises();
|
||
expect(input(w).element.value).toBe("#123456");
|
||
expect(changes(w)).toHaveLength(1);
|
||
});
|
||
it("does not submit disabled channel fields and still validates channel Color callbacks", async () => {
|
||
const off = shallowRef(false);
|
||
const validate = vi.fn(() => "通道错误");
|
||
const w = view(
|
||
field(
|
||
'channel="saturation" color-space="hsb" default-value="hsb(270,50%,50%)" :is-disabled="off" validation-behavior="aria" :validate="validate"',
|
||
),
|
||
() => ({ off, validate }),
|
||
);
|
||
expect(w.get("[data-slot=field-error]").text()).toBe("通道错误");
|
||
expect(validate.mock.calls.length).toBeGreaterThan(0);
|
||
off.value = true;
|
||
await flushPromises();
|
||
expect(data(w)).toEqual([]);
|
||
expect(input(w).element.disabled).toBe(true);
|
||
expect(w.find("[data-slot=field-error]").exists()).toBe(false);
|
||
});
|
||
it("keeps standalone native attributes and honors canceled input in the shared text control", async () => {
|
||
const w = view(
|
||
'<ColorInputGroup><ColorInputGroupInput name="color" default-value="original" type="password" autocomplete="current-password" inputmode="text" spellcheck="true" @input="$event.preventDefault()"/></ColorInputGroup>',
|
||
);
|
||
expect(input(w).attributes("autocomplete")).toBe("current-password");
|
||
expect(input(w).attributes("type")).toBe("password");
|
||
expect(input(w).attributes("spellcheck")).toBe("true");
|
||
input(w).element.value = "blocked";
|
||
input(w).element.dispatchEvent(
|
||
new Event("input", { bubbles: true, cancelable: true }),
|
||
);
|
||
await flushPromises();
|
||
expect(input(w).element.value).toBe("original");
|
||
expect(
|
||
w.getComponent(ColorInputGroupInput).emitted("update:modelValue"),
|
||
).toBeUndefined();
|
||
});
|
||
it("does not commit during IME and replaces the input without stale ownership", async () => {
|
||
const show = shallowRef(true);
|
||
const w = view(
|
||
field('default-value="#123456"', ":key=\"show?'first':'second'\""),
|
||
() => ({ show }),
|
||
);
|
||
await input(w).trigger("compositionstart");
|
||
await input(w).setValue("abc");
|
||
await input(w).trigger("keydown", { key: "Enter" });
|
||
expect(changes(w)).toHaveLength(0);
|
||
const old = input(w).element;
|
||
show.value = false;
|
||
await flushPromises();
|
||
expect(input(w).element).not.toBe(old);
|
||
expect(input(w).element.value).toBe("#123456");
|
||
await edit(w, "abc");
|
||
expect(data(w)).toEqual(["#AABBCC"]);
|
||
});
|
||
});
|
||
|
||
describe("color field draft validation and step grid", () => {
|
||
it("filters invalid input without discarding the previous partial draft", async () => {
|
||
const w = view(field('default-value="#123456"'));
|
||
await input(w).setValue("#ab");
|
||
await input(w).setValue("#abZ");
|
||
expect(input(w).element.value).toBe("#ab");
|
||
expect(changes(w)).toHaveLength(0);
|
||
await input(w).trigger("compositionstart");
|
||
await input(w).setValue("颜色");
|
||
await input(w).trigger("compositionend");
|
||
await flushPromises();
|
||
expect(input(w).element.value).toBe("#ab");
|
||
const node = input(w).element;
|
||
node.setSelectionRange(3, 3);
|
||
const event = new InputEvent("beforeinput", {
|
||
bubbles: true,
|
||
cancelable: true,
|
||
data: "Z",
|
||
inputType: "insertText",
|
||
});
|
||
node.dispatchEvent(event);
|
||
expect(event.defaultPrevented).toBe(true);
|
||
});
|
||
it("steps from accepted fractions onto the natural grid and starts empty channel values at the boundary", async () => {
|
||
const w = view(
|
||
field('channel="alpha" default-value="hsba(270,0%,50%,.125)"'),
|
||
);
|
||
await input(w).trigger("keydown", { key: "ArrowUp" });
|
||
expect(data(w)).toEqual(["0.14"]);
|
||
await input(w).trigger("keydown", { key: "ArrowDown" });
|
||
expect(data(w)).toEqual(["0.13"]);
|
||
const empty = view(field('channel="saturation" color-space="hsb"'));
|
||
await input(empty).trigger("keydown", { key: "ArrowUp" });
|
||
expect(data(empty)).toEqual(["0"]);
|
||
});
|
||
});
|
||
it("refreshes root ARIA and native listeners even when only fallthrough attrs change", async () => {
|
||
const invalid = shallowRef(false),
|
||
label = shallowRef("first label"),
|
||
handler = shallowRef((event: Event) => event.preventDefault());
|
||
const w = view(
|
||
field(
|
||
'default-value="#123456" :aria-invalid="invalid" :aria-label="label" @keydown="handler"',
|
||
),
|
||
() => ({ invalid, label, handler }),
|
||
);
|
||
expect(input(w).attributes("aria-label")).toBe("first label");
|
||
invalid.value = true;
|
||
label.value = "second label";
|
||
handler.value = () => {};
|
||
await flushPromises();
|
||
expect(input(w).attributes("aria-invalid")).toBe("true");
|
||
expect(input(w).attributes("aria-label")).toBe("second label");
|
||
expect(
|
||
w.get("[data-slot=color-input-group]").attributes("data-invalid"),
|
||
).toBe("true");
|
||
await edit(w, "abc");
|
||
expect(changes(w)).toHaveLength(1);
|
||
});
|