Files
heroui-vue/tests/progress-meter.test.ts
maoyingjie 8f51b0e097 feat: align public Root aliases and rework progress-bar custom-value demo
- 包根补齐固定上游 82 对 Xxx/XxxRoot 同对象别名(55 个缺失 Root 别名 + Dropdown 反向别名)与 59 个 RootProps/Menu/Dropdown 类型别名;不杜撰上游没有的名称(如 CheckboxGroupRoot、ToastRootProps)
- tests/package 新增 api-root-aliases 契约:完整别名清单、82 对身份等价断言与 strict NodeNext/bundler 类型正反例
- progress-bar custom-value 演示回填公共 NumberField/Select,保持固定源文案/布局/范围/四格式与边界处理
- 修复 NumberFieldInput keydown 无条件 restore 还原同任务键入字符的缺陷,并入 number-field 回归
- 文档导航 dropdown 归位固定 meta.json 顺序并补顺序断言;修正“原生临时控件”陈述
2026-10-27 19:48:35 +08:00

954 lines
32 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { componentItems } from "../apps/docs/.vitepress/theme/navigation";
import { describe, it, expect, afterEach } from "vitest";
import { readFileSync } from "node:fs";
import { flushPromises, mount } from "@vue/test-utils";
import { defineComponent, h, nextTick, ref } from "vue";
import {
Label,
TextField,
Input,
Meter,
MeterFill,
MeterOutput,
MeterTrack,
ProgressBar,
ProgressBarFill,
ProgressBarOutput,
ProgressBarTrack,
ProgressCircle,
ProgressCircleFillCircle,
ProgressCircleTrack,
ProgressCircleTrackCircle,
} from "../packages/vue/src";
afterEach(() => {
document.body.innerHTML = "";
});
describe("ProgressBar", () => {
it("renders with progressbar role and Label accessible name", async () => {
const w = mount(
defineComponent({
components: {
Label,
ProgressBar,
ProgressBarOutput,
ProgressBarTrack,
ProgressBarFill,
},
template: `
<ProgressBar :value="60">
<Label>Loading</Label>
<ProgressBarOutput />
<ProgressBarTrack>
<ProgressBarFill />
</ProgressBarTrack>
</ProgressBar>
`,
}),
);
const root = w.get("[data-slot=progress-bar]");
expect(root.attributes("role")).toBe("progressbar");
expect(root.attributes("aria-valuenow")).toBe("60");
expect(root.attributes("aria-valuemin")).toBe("0");
expect(root.attributes("aria-valuemax")).toBe("100");
await nextTick();
const label = w.get("[data-slot=label]");
expect(root.attributes("aria-labelledby")).toBe(label.attributes("id"));
expect(label.attributes("id")).toBeTruthy();
});
it("exposes BEM block, color/size modifiers and data-slots", () => {
const w = mount(ProgressBar, {
props: { color: "success", size: "lg", value: 50 },
attrs: { "aria-label": "Loading", "data-foo": "bar" },
slots: {
default: () => [
h(ProgressBarOutput),
h(ProgressBarTrack, null, { default: () => h(ProgressBarFill) }),
],
},
});
const root = w.get("[data-slot=progress-bar]");
expect(root.attributes("data-foo")).toBe("bar");
expect(root.attributes("aria-label")).toBe("Loading");
expect(root.classes()).toContain("hv-progress-bar");
expect(root.classes()).toContain("hv-progress-bar--success");
expect(root.classes()).toContain("hv-progress-bar--lg");
expect(w.find("[data-slot=progress-bar-output]").exists()).toBe(true);
expect(w.find("[data-slot=progress-bar-track]").exists()).toBe(true);
expect(w.find("[data-slot=progress-bar-fill]").exists()).toBe(true);
});
it("omits aria-valuenow and width when indeterminate", () => {
const w = mount(ProgressBar, {
props: { isIndeterminate: true },
attrs: { "aria-label": "Loading" },
slots: {
default: () =>
h(ProgressBarTrack, null, {
default: () => h(ProgressBarFill, { "data-testid": "fill" }),
}),
},
});
const root = w.get("[data-slot=progress-bar]");
expect(root.attributes("aria-valuenow")).toBeUndefined();
expect(root.attributes("aria-valuetext")).toBeUndefined();
const fill = w.get("[data-slot=progress-bar-fill]");
expect((fill.element as HTMLElement).style.width).toBe("");
});
it("formats percent text and custom ranges", async () => {
const percent = mount(ProgressBar, {
props: { value: 60 },
attrs: { "aria-label": "p" },
slots: { default: () => h(ProgressBarOutput) },
});
expect(percent.get("[data-slot=progress-bar-output]").text()).toBe("60%");
const currency = mount(ProgressBar, {
props: {
value: 750,
minValue: 0,
maxValue: 1000,
formatOptions: { style: "currency", currency: "USD" },
},
attrs: { "aria-label": "p" },
slots: {
default: () => [
h(ProgressBarOutput),
h(ProgressBarFill, { "data-testid": "fill" }),
],
},
});
expect(currency.get("[data-slot=progress-bar-output]").text()).toBe(
"$750.00",
);
expect(
(currency.get("[data-slot=progress-bar-fill]").element as HTMLElement)
.style.width,
).toBe("75%");
});
it("clamps value and supports valueLabel override", () => {
const w = mount(ProgressBar, {
props: { value: 150, minValue: 0, maxValue: 100, valueLabel: "自定义" },
attrs: { "aria-label": "p" },
slots: {
default: () => [
h(ProgressBarOutput),
h(ProgressBarFill, { "data-testid": "fill" }),
],
},
});
const root = w.get("[data-slot=progress-bar]");
expect(root.attributes("aria-valuenow")).toBe("100");
expect(root.attributes("aria-valuetext")).toBe("自定义");
expect(w.get("[data-slot=progress-bar-output]").text()).toBe("自定义");
expect(
(w.get("[data-slot=progress-bar-fill]").element as HTMLElement).style
.width,
).toBe("100%");
});
it("updates DOM when value and indeterminate toggle", async () => {
const value = ref(20);
const indeterminate = ref(false);
const w = mount(
defineComponent({
components: {
ProgressBar,
ProgressBarOutput,
ProgressBarTrack,
ProgressBarFill,
},
setup: () => ({ value, indeterminate }),
template: `
<ProgressBar
:value="value"
:is-indeterminate="indeterminate"
aria-label="动态"
>
<ProgressBarOutput />
<ProgressBarTrack>
<ProgressBarFill data-testid="fill" />
</ProgressBarTrack>
</ProgressBar>
`,
}),
);
const root = w.get("[data-slot=progress-bar]");
const fill = w.get("[data-slot=progress-bar-fill]");
expect(root.attributes("aria-valuenow")).toBe("20");
expect((fill.element as HTMLElement).style.width).toBe("20%");
value.value = 80;
await nextTick();
expect(root.attributes("aria-valuenow")).toBe("80");
expect((fill.element as HTMLElement).style.width).toBe("80%");
indeterminate.value = true;
await nextTick();
expect(root.attributes("aria-valuenow")).toBeUndefined();
expect((fill.element as HTMLElement).style.width).toBe("");
indeterminate.value = false;
value.value = 45;
await nextTick();
expect(root.attributes("aria-valuenow")).toBe("45");
expect((fill.element as HTMLElement).style.width).toBe("45%");
});
it("merges caller class arrays/objects and supports scoped default slot", () => {
const w = mount(ProgressBar, {
props: { value: 30, size: "sm" },
attrs: {
"aria-label": "p",
class: ["custom-a", { "custom-b": true }],
},
slots: {
default: (scope: {
percentage: number | undefined;
valueText: string | undefined;
isIndeterminate: boolean;
}) =>
h("span", { "data-testid": "scoped" }, [
`${scope.percentage}|${scope.valueText}|${scope.isIndeterminate}`,
]),
},
});
const root = w.get("[data-slot=progress-bar]");
expect(root.classes()).toContain("hv-progress-bar");
expect(root.classes()).toContain("hv-progress-bar--sm");
expect(root.classes()).toContain("custom-a");
expect(root.classes()).toContain("custom-b");
expect(w.get("[data-testid=scoped]").text()).toBe("30|30%|false");
});
});
describe("ProgressCircle", () => {
it("renders circle geometry and indeterminate dash offset", () => {
const w = mount(
defineComponent({
components: {
ProgressCircle,
ProgressCircleTrack,
ProgressCircleTrackCircle,
ProgressCircleFillCircle,
},
template: `
<ProgressCircle aria-label="加载中" :value="60">
<ProgressCircleTrack>
<ProgressCircleTrackCircle />
<ProgressCircleFillCircle />
</ProgressCircleTrack>
</ProgressCircle>
`,
}),
);
const root = w.get("[data-slot=progress-circle]");
expect(root.attributes("role")).toBe("progressbar");
expect(root.attributes("aria-valuenow")).toBe("60");
const track = w.get("svg[data-slot=progress-circle-track]");
expect(track.attributes("viewBox")).toBe("0 0 36 36");
expect(track.attributes("fill")).toBe("none");
const trackCircle = w.get("[data-slot=progress-circle-track-circle]");
expect(trackCircle.attributes("cx")).toBe("18");
expect(trackCircle.attributes("cy")).toBe("18");
expect(trackCircle.attributes("r")).toBe("16");
expect(trackCircle.attributes("stroke-width")).toBe("4");
const fillCircle = w.get("[data-slot=progress-circle-fill-circle]");
const circumference = 2 * Math.PI * 16;
expect(Number(fillCircle.attributes("stroke-dasharray"))).toBeCloseTo(
circumference,
5,
);
// 60% → offset = C * 0.4
expect(Number(fillCircle.attributes("stroke-dashoffset"))).toBeCloseTo(
circumference * 0.4,
5,
);
expect(fillCircle.attributes("stroke-linecap")).toBe("round");
expect(fillCircle.attributes("transform")).toBe("rotate(-90 18 18)");
});
it("supports custom SVG geometry overrides", () => {
const w = mount(
defineComponent({
components: {
ProgressCircle,
ProgressCircleTrack,
ProgressCircleTrackCircle,
ProgressCircleFillCircle,
},
template: `
<ProgressCircle aria-label="细" :value="60">
<ProgressCircleTrack stroke-width="2" view-box="0 0 36 36">
<ProgressCircleTrackCircle :cx="18" :cy="18" :r="17" :stroke-width="2" />
<ProgressCircleFillCircle :cx="18" :cy="18" :r="17" :stroke-width="2" />
</ProgressCircleTrack>
</ProgressCircle>
`,
}),
);
expect(
w.get("[data-slot=progress-circle-track-circle]").attributes("r"),
).toBe("17");
expect(
w
.get("[data-slot=progress-circle-track-circle]")
.attributes("stroke-width"),
).toBe("2");
});
it("omits aria-valuenow when indeterminate and spins track via CSS hook", () => {
const w = mount(
defineComponent({
components: {
ProgressCircle,
ProgressCircleTrack,
ProgressCircleTrackCircle,
ProgressCircleFillCircle,
},
template: `
<ProgressCircle is-indeterminate aria-label="加载中">
<ProgressCircleTrack>
<ProgressCircleTrackCircle />
<ProgressCircleFillCircle />
</ProgressCircleTrack>
</ProgressCircle>
`,
}),
);
expect(
w.get("[data-slot=progress-circle]").attributes("aria-valuenow"),
).toBeUndefined();
});
});
describe("Meter", () => {
it("renders meter role with Label name and percent output", async () => {
const w = mount(
defineComponent({
components: {
Label,
Meter,
MeterOutput,
MeterTrack,
MeterFill,
},
template: `
<Meter :value="60">
<Label>Storage</Label>
<MeterOutput />
<MeterTrack>
<MeterFill />
</MeterTrack>
</Meter>
`,
}),
);
const root = w.get("[data-slot=meter]");
expect(root.attributes("role")).toBe("meter progressbar");
expect(root.attributes("aria-valuenow")).toBe("60");
expect(root.attributes("aria-valuetext")).toBe("60%");
await nextTick();
const label = w.get("[data-slot=label]");
expect(root.attributes("aria-labelledby")).toBe(label.attributes("id"));
expect(w.get("[data-slot=meter-output]").text()).toBe("60%");
});
it("always reports a value (no indeterminate) and uses BEM color", () => {
const w = mount(Meter, {
props: { value: 50, color: "danger" },
attrs: { "aria-label": "Storage", "data-foo": "bar" },
slots: {
default: () => [
h(MeterOutput),
h(MeterTrack, null, { default: () => h(MeterFill) }),
],
},
});
const root = w.get("[data-slot=meter]");
expect(root.attributes("data-foo")).toBe("bar");
expect(root.attributes("aria-valuenow")).toBe("50");
expect(root.classes()).toContain("hv-meter--danger");
expect(root.attributes("role")).toBe("meter progressbar");
});
it("formats custom value ranges", () => {
const w = mount(Meter, {
props: {
value: 750,
maxValue: 1000,
minValue: 0,
formatOptions: { style: "currency", currency: "USD" },
},
attrs: { "aria-label": "Revenue" },
slots: {
default: () => [h(MeterOutput), h(MeterFill)],
},
});
expect(w.get("[data-slot=meter-output]").text()).toBe("$750.00");
expect(
(w.get("[data-slot=meter-fill]").element as HTMLElement).style.width,
).toBe("75%");
expect(w.get("[data-slot=meter]").attributes("aria-valuenow")).toBe("750");
expect(w.get("[data-slot=meter]").attributes("aria-valuemin")).toBe("0");
expect(w.get("[data-slot=meter]").attributes("aria-valuemax")).toBe("1000");
});
it("prefers explicit aria-label over Label association", () => {
const w = mount(
defineComponent({
components: { Label, Meter },
template: `
<Meter :value="40" aria-label="显式名称">
<Label>内部标签</Label>
</Meter>
`,
}),
);
const root = w.get("[data-slot=meter]");
expect(root.attributes("aria-label")).toBe("显式名称");
expect(root.attributes("aria-labelledby")).toBeUndefined();
});
});
describe("M18–M20 demos", () => {
const demoModules = import.meta.glob<{ default: unknown }>(
"../apps/docs/demos/{progress-bar,progress-circle,meter}-*.vue",
{ eager: true },
);
it("mounts all 20 baseline demos without console errors", async () => {
const names = Object.keys(demoModules).sort();
expect(names).toHaveLength(20);
expect(names.map((n) => n.split("/").pop())).toEqual([
"meter-basic.vue",
"meter-colors.vue",
"meter-custom-styles.vue",
"meter-custom-value.vue",
"meter-sizes.vue",
"meter-without-label.vue",
"progress-bar-basic.vue",
"progress-bar-colors.vue",
"progress-bar-custom-styles.vue",
"progress-bar-custom-value.vue",
"progress-bar-indeterminate.vue",
"progress-bar-sizes.vue",
"progress-bar-without-label.vue",
"progress-circle-basic.vue",
"progress-circle-colors.vue",
"progress-circle-custom-styles.vue",
"progress-circle-custom-svg.vue",
"progress-circle-indeterminate.vue",
"progress-circle-sizes.vue",
"progress-circle-with-label.vue",
]);
const errors: unknown[] = [];
const warn = console.warn;
const error = console.error;
console.warn = (...args: unknown[]) => {
errors.push(args);
warn(...args);
};
console.error = (...args: unknown[]) => {
errors.push(args);
error(...args);
};
try {
for (const [path, mod] of Object.entries(demoModules)) {
const w = mount(mod.default as never, { attachTo: document.body });
expect(w.html().length).toBeGreaterThan(20);
w.unmount();
document.body.innerHTML = "";
void path;
}
} finally {
console.warn = warn;
console.error = error;
}
expect(errors).toEqual([]);
});
it("extracts, compiles and mounts documentation body SFC examples", async () => {
const docs = [
"apps/docs/components/progress-bar.md",
"apps/docs/components/progress-circle.md",
"apps/docs/components/meter.md",
];
const fixturePaths = [
"tests/fixtures/m18m20-progress-bar-doc-0.vue",
"tests/fixtures/m18m20-progress-bar-doc-1.vue",
"tests/fixtures/m18m20-progress-circle-doc-0.vue",
"tests/fixtures/m18m20-progress-circle-doc-1.vue",
"tests/fixtures/m18m20-meter-doc-0.vue",
"tests/fixtures/m18m20-meter-doc-1.vue",
];
const fixtures = await Promise.all(
fixturePaths.map(async (path) => ({
path,
mod: (await import("./" + path.replace("tests/", ""))).default,
})),
);
let index = 0;
for (const file of docs) {
const source = readFileSync(file, "utf8");
const blocks = [...source.matchAll(/```vue\n([\s\S]*?)```/g)].map(
(m) => m[1],
);
expect(blocks.length).toBeGreaterThanOrEqual(2);
for (const block of blocks) {
const fixture = fixtures[index];
expect(fixture).toBeTruthy();
expect(readFileSync(fixture.path, "utf8")).toBe(block);
const w = mount(fixture.mod as never, { attachTo: document.body });
expect(w.html().length).toBeGreaterThan(20);
w.unmount();
document.body.innerHTML = "";
index += 1;
}
}
expect(index).toBe(6);
});
});
describe("M18–M20 review regressions", () => {
it("keeps explicit aria-labelledby on all three roots", () => {
const cases = [
{ Comp: ProgressBar, slot: "progress-bar" },
{ Comp: ProgressCircle, slot: "progress-circle" },
{ Comp: Meter, slot: "meter" },
] as const;
for (const { Comp, slot } of cases) {
const w = mount(Comp, {
props: { value: 40 },
attrs: { "aria-labelledby": "external-label" },
});
expect(w.get(`[data-slot=${slot}]`).attributes("aria-labelledby")).toBe(
"external-label",
);
w.unmount();
}
});
it("keeps dynamic aria-labelledby updates and removals", async () => {
const labelledby = ref<string | undefined>("external-label");
const w = mount(ProgressBar, {
props: { value: 10 },
attrs: {
get "aria-labelledby"() {
return labelledby.value;
},
},
// re-render when ref changes
});
// attrs object getters need a reactive wrapper component instead
w.unmount();
const wrapper = mount(
defineComponent({
components: { ProgressBar },
setup: () => ({ labelledby }),
template: `
<ProgressBar
:value="10"
:aria-labelledby="labelledby"
data-testid="root"
/>
`,
}),
);
const root = wrapper.get("[data-testid=root]");
expect(root.attributes("aria-labelledby")).toBe("external-label");
labelledby.value = "other-label";
await nextTick();
expect(root.attributes("aria-labelledby")).toBe("other-label");
labelledby.value = undefined;
await nextTick();
expect(root.attributes("aria-labelledby")).toBeUndefined();
labelledby.value = "external-label";
await nextTick();
expect(root.attributes("aria-labelledby")).toBe("external-label");
});
it("preserves explicit Label id and unique auto ids for multiple labels", async () => {
const w = mount(
defineComponent({
components: { Label, ProgressBar },
template: `
<ProgressBar :value="50">
<Label id="my-label">自定义</Label>
<Label>自动甲</Label>
<Label>自动乙</Label>
</ProgressBar>
`,
}),
);
await nextTick();
const labels = w.findAll("[data-slot=label]");
expect(labels).toHaveLength(3);
const ids = labels.map((l) => l.attributes("id"));
expect(ids[0]).toBe("my-label");
expect(ids[1]).toBeTruthy();
expect(ids[2]).toBeTruthy();
expect(new Set(ids).size).toBe(3);
const root = w.get("[data-slot=progress-bar]");
const labelledby = root.attributes("aria-labelledby")!.split(/\s+/);
expect(labelledby).toContain("my-label");
expect(labelledby).toContain(ids[1]);
expect(labelledby).toContain(ids[2]);
expect(labelledby).toHaveLength(3);
// Every referenced id exists in the mounted tree
for (const id of labelledby) {
expect(w.find(`[id="${id}"]`).exists()).toBe(true);
}
});
it("restores native label when for is added dynamically and removes it again", async () => {
const forAttr = ref<string | undefined>(undefined);
const w = mount(
defineComponent({
components: { Label, ProgressBar },
setup: () => ({ forAttr }),
template: `
<ProgressBar :value="50">
<Label :for="forAttr">动态标签</Label>
</ProgressBar>
`,
}),
);
await nextTick();
expect(w.get("[data-slot=label]").element.tagName).toBe("SPAN");
forAttr.value = "target-input";
await nextTick();
const asLabel = w.get("[data-slot=label]");
expect(asLabel.element.tagName).toBe("LABEL");
expect(asLabel.attributes("for")).toBe("target-input");
forAttr.value = "other-input";
await nextTick();
expect(w.get("[data-slot=label]").attributes("for")).toBe("other-input");
forAttr.value = undefined;
await nextTick();
expect(w.get("[data-slot=label]").element.tagName).toBe("SPAN");
forAttr.value = "target-input";
await nextTick();
expect(w.get("[data-slot=label]").element.tagName).toBe("LABEL");
});
it("keeps field labels working when for is present without indicator span override", async () => {
// No indicator context: default remains native label without for
const w = mount(Label, { slots: { default: "独立标签" } });
expect(w.get("[data-slot=label]").element.tagName).toBe("LABEL");
const withFor = mount(Label, {
attrs: { for: "x" },
slots: { default: "关联标签" },
});
expect(withFor.get("[data-slot=label]").element.tagName).toBe("LABEL");
expect(withFor.get("[data-slot=label]").attributes("for")).toBe("x");
});
});
describe("M18–M20 docs navigation", () => {
it("preserves the three pages in the shared sidebar/previous-next model", () => {
const urls = componentItems.map((item) => item.url);
for (const slug of ["meter", "progress-bar", "progress-circle"])
expect(urls).toContain("/components/" + slug);
expect(urls.indexOf("/components/meter")).toBeGreaterThan(
urls.indexOf("/components/link"),
);
expect(urls.indexOf("/components/progress-circle")).toBeGreaterThan(
urls.indexOf("/components/progress-bar"),
);
expect(urls.indexOf("/components/radio-group")).toBeGreaterThan(
urls.indexOf("/components/progress-circle"),
);
});
});
it("removes stale label IDs and keeps associations correct after id removal and reordering", async () => {
const rows = ref(["a", "b"]);
const ids = ref<Record<string, string>>({ a: "first-label" });
const w = mount({
render: () =>
h(ProgressBar, {}, () =>
rows.value.map((key) =>
h(
Label,
{ key, ...(ids.value[key] ? { id: ids.value[key] } : {}) },
() => key,
),
),
),
});
for (const step of [
() => {
ids.value = { a: "new-first" };
},
() => {
ids.value = {};
},
() => {
rows.value = ["b", "a"];
},
() => {
rows.value = ["a"];
},
() => {
rows.value = [];
},
() => {
rows.value = ["b"];
},
]) {
step();
await nextTick();
await nextTick();
const labelIds = w
.findAll("[data-slot=label]")
.map((n) => n.attributes("id"));
const refs = (w.attributes("aria-labelledby") ?? "")
.split(" ")
.filter(Boolean);
expect([...refs].sort()).toEqual([...labelIds].sort());
expect(new Set(labelIds).size).toBe(labelIds.length);
}
w.unmount();
});
it("isolates indicator labels from both surrounding and nested field scopes", async () => {
const w = mount({
render: () =>
h(TextField, {}, () => [
h(Label, { id: "outer-field" }, () => "Outer"),
h(Input),
h(ProgressBar, {}, () => [
h(Label, { id: "progress-title" }, () => "Progress"),
h(TextField, {}, () => [
h(Label, { id: "inner-field" }, () => "Inner"),
h(Input),
]),
]),
]),
});
await nextTick();
await nextTick();
const indicator = w.get("[data-slot=progress-bar]");
expect(indicator.attributes("aria-labelledby")).toBe("progress-title");
const label = w.get("#progress-title");
expect(label.element.tagName).toBe("SPAN");
expect(label.attributes("for")).toBeUndefined();
const inputs = w.findAll("[data-slot=input]");
expect(w.get("#outer-field").attributes("for")).toBe(
inputs[0].attributes("id"),
);
expect(w.get("#inner-field").attributes("for")).toBe(
inputs[1].attributes("id"),
);
w.unmount();
});
describe("progress-bar custom-value demo with public NumberField/Select", () => {
async function setup() {
const mod = await import("../apps/docs/demos/progress-bar-custom-value.vue");
const w = mount(mod.default as never, { attachTo: document.body });
await flushPromises();
return w;
}
const field = (w: ReturnType<typeof mount>, index: number) =>
w.findAll('[data-slot="number-field"]')[index];
const inputOf = (w: ReturnType<typeof mount>, index: number) =>
field(w, index).get("input[role=spinbutton]");
const progress = (w: ReturnType<typeof mount>) =>
w.get("[data-slot=progress-bar]");
const output = (w: ReturnType<typeof mount>) =>
w.get("[data-slot=progress-bar-output]");
const fill = (w: ReturnType<typeof mount>) =>
w.get("[data-slot=progress-bar-fill]").element as HTMLElement;
const text = (options: Intl.NumberFormatOptions, value: number) =>
new Intl.NumberFormat(undefined, options).format(value);
const percent = (value: number, min: number, max: number) =>
text({ style: "percent" }, (value - min) / (max - min));
it("keeps the fixed source values and renders NumberField/Select parts", async () => {
const w = await setup();
expect(w.findAll('[data-slot="number-field"]')).toHaveLength(3);
expect(w.findAll("input[role=spinbutton]")).toHaveLength(3);
expect(w.findAll('[data-slot="select-trigger"]')).toHaveLength(1);
expect(
w.findAll('[data-slot="number-field-increment-button"]'),
).toHaveLength(3);
const bar = progress(w);
expect(bar.attributes("aria-label")).toBe("收入");
expect(bar.attributes("aria-valuenow")).toBe("750");
expect(bar.attributes("aria-valuemin")).toBe("0");
expect(bar.attributes("aria-valuemax")).toBe("1000");
expect(output(w).text()).toBe("75%");
expect(fill(w).style.width).toBe("75%");
const labels = w.findAll("[data-slot=label]").map((n) => n.text());
expect(labels).toEqual(["进度", "选项", "值", "最小值", "最大值", "格式"]);
w.unmount();
});
it("synchronizes typed input, stepping and bounds with progress text and fill", async () => {
const w = await setup();
const valueInput = inputOf(w, 0);
await valueInput.setValue("500");
await valueInput.trigger("blur");
await flushPromises();
expect(progress(w).attributes("aria-valuenow")).toBe("500");
expect(output(w).text()).toBe("50%");
expect(fill(w).style.width).toBe("50%");
await field(w, 0)
.get('[data-slot="number-field-increment-button"]')
.trigger("click");
await flushPromises();
expect(progress(w).attributes("aria-valuenow")).toBe("501");
expect(output(w).text()).toBe(percent(501, 0, 1000));
expect(fill(w).style.width).toBe("50.1%");
await field(w, 0)
.get('[data-slot="number-field-decrement-button"]')
.trigger("click");
await flushPromises();
expect(progress(w).attributes("aria-valuenow")).toBe("500");
await valueInput.setValue("1000");
await valueInput.trigger("blur");
await flushPromises();
expect(
(
field(w, 0)
.get('[data-slot="number-field-increment-button"]')
.element as HTMLButtonElement
).disabled,
).toBe(true);
expect(output(w).text()).toBe("100%");
w.unmount();
});
it("rejects cleared and invalid drafts without NaN or display mismatch", async () => {
const w = await setup();
const valueInput = inputOf(w, 0);
for (const draft of ["", "abc", "-"]) {
await valueInput.setValue(draft);
await valueInput.trigger("blur");
await flushPromises();
expect(progress(w).attributes("aria-valuenow")).toBe("750");
expect(output(w).text()).toBe("75%");
expect(fill(w).style.width).toBe("75%");
expect((valueInput.element as HTMLInputElement).value).not.toBe("");
expect(w.text()).not.toContain("NaN");
}
w.unmount();
});
it("clamps out-of-range commits into the current range", async () => {
const w = await setup();
const valueInput = inputOf(w, 0);
await valueInput.setValue("5000");
await valueInput.trigger("blur");
await flushPromises();
expect(progress(w).attributes("aria-valuenow")).toBe("1000");
expect(output(w).text()).toBe("100%");
expect(fill(w).style.width).toBe("100%");
await valueInput.setValue("-20");
await valueInput.trigger("blur");
await flushPromises();
expect(progress(w).attributes("aria-valuenow")).toBe("0");
expect(output(w).text()).toBe("0%");
expect(fill(w).style.width).toBe("0%");
w.unmount();
});
it("re-syncs value when the dynamic bounds change", async () => {
const w = await setup();
const minInput = inputOf(w, 1);
await minInput.setValue("800");
await minInput.trigger("blur");
await flushPromises();
expect(progress(w).attributes("aria-valuemin")).toBe("800");
expect(progress(w).attributes("aria-valuenow")).toBe("800");
expect(output(w).text()).toBe("0%");
await minInput.setValue("2000");
await minInput.trigger("blur");
await flushPromises();
expect(progress(w).attributes("aria-valuemin")).toBe("999");
expect(progress(w).attributes("aria-valuenow")).toBe("999");
const maxInput = inputOf(w, 2);
await maxInput.setValue("400");
await maxInput.trigger("blur");
await flushPromises();
expect(progress(w).attributes("aria-valuemax")).toBe("1000");
expect(progress(w).attributes("aria-valuenow")).toBe("999");
w.unmount();
const fresh = await setup();
const freshMax = inputOf(fresh, 2);
await freshMax.setValue("600");
await freshMax.trigger("blur");
await flushPromises();
expect(progress(fresh).attributes("aria-valuemax")).toBe("600");
expect(progress(fresh).attributes("aria-valuenow")).toBe("600");
expect(output(fresh).text()).toBe("100%");
await freshMax.setValue("0");
await freshMax.trigger("blur");
await flushPromises();
expect(progress(fresh).attributes("aria-valuemax")).toBe("1");
expect(progress(fresh).attributes("aria-valuenow")).toBe("1");
fresh.unmount();
});
it("switches all four formats through the Select panel", async () => {
const w = await setup();
const cases: [string, Intl.NumberFormatOptions, number, number][] = [
["货币", { currency: "USD", style: "currency" }, 750, 1000],
["小数", { style: "decimal" }, 750, 1000],
["单位", { style: "unit", unit: "mile" }, 750, 1000],
["百分比", { style: "percent" }, 750, 1000],
];
for (const [label, options, value, max] of cases) {
await w.get('[data-slot="select-trigger"]').trigger("keydown", {
key: "ArrowDown",
});
await flushPromises();
const panelOptions = [
...document.querySelectorAll<HTMLElement>('[role="option"]'),
];
expect(panelOptions.map((n) => n.textContent?.trim())).toEqual([
"货币",
"百分比",
"小数",
"单位",
]);
const target = panelOptions.find((n) => n.textContent?.trim() === label)!;
target.click();
await flushPromises();
expect(document.querySelector('[role="listbox"]')).toBeNull();
expect(w.get('[data-slot="select-value"]').text()).toContain(label);
const expected =
options.style === "percent"
? percent(value, 0, max)
: text(options, value);
expect(output(w).text()).toBe(expected);
}
w.unmount();
});
});