Files
heroui-vue/tests/date-range-picker-demos.test.ts
maoyingjie 2e3fdd4800 fix(demos): inherit ConfigProvider locale and restore the format-options popover width
HD-03 scope, all against heroui ce90ea3 cn sources:

- calendar-disabled/read-only: restore the today() default value and the
  baseline description lines (日历已禁用 / 日历为只读) inside the
  flex flex-col items-center wrapper
- calendar-controlled: restore the second button row (设为今天/设为圣诞节/
  清空) and the baseline feedback wording (已选日期:…(未选))
- locale inheritance: add a public useLocale() accessor (the components'
  ConfigProvider → en-US/ltr chain) and use it for startOfWeek in
  calendar-controlled, isWeekend in booking-calendar/unavailable-dates and
  the DateFormatter in date-range-picker-format-options instead of the
  hardcoded 'en-US' / 'zh-CN' literals
- date-range-picker-format-options: restore the pinned w-full popover class;
  the pinned source positions the popover against the initial containing
  block (full viewport width — verified on the reference docs at desktop and
  narrow), while Reka's shrink-to-fit positioning wrapper collapses the same
  class. A scoped adapter rule (.hv-date-range-picker__popover.w-full →
  100vw, layering-safe like the dropdown static-wrapper adapter) restores
  the baseline effect: viewport-wide popover, 252px calendar, stretched
  time rows, identical boundary clamping

- tests: locale dynamic-switching regressions covering zh-CN/en-US for week
  start, weekend rules (with ar-EG flipping the weekend for a observable
  rule change) and range formatting; full suite 110 files / 1627 tests,
  typecheck, build:docs and the date-range-picker / api-root-aliases /
  calendar tarball contracts pass
2026-10-28 16:35:26 +08:00

348 lines
12 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, h, ref } from "vue";
import { readFileSync } from "node:fs";
import {
DateFormatter,
getLocalTimeZone,
parseZonedDateTime,
today,
} from "@internationalized/date";
import { ConfigProvider } from "../packages/vue/src";
const demos = import.meta.glob("../apps/docs/demos/date-range-picker-*.vue", {
eager: true,
import: "default",
});
const expected = [
"basic",
"disabled",
"controlled",
"with-validation",
"format-options",
"form-example",
"with-custom-indicator",
"render-function",
"international-calendar",
"custom-styles",
];
const wrappers: ReturnType<typeof mount>[] = [];
beforeEach(() => {
vi.stubGlobal(
"ResizeObserver",
class {
observe() {}
unobserve() {}
disconnect() {}
},
);
});
afterEach(async () => {
wrappers.splice(0).forEach((w) => w.unmount());
await flushPromises();
vi.useRealTimers();
vi.unstubAllGlobals();
document.body.innerHTML = "";
});
function mountDemo(name: string) {
const demo = demos[`../apps/docs/demos/date-range-picker-${name}.vue`];
const w = mount(demo as never, { attachTo: document.body });
wrappers.push(w);
return w;
}
async function open(w: ReturnType<typeof mount>) {
await w.get('[data-slot="date-range-picker-trigger"]').trigger("click");
await flushPromises();
}
function cell(date: string) {
return document.querySelector<HTMLElement>(
`[data-slot="range-calendar-cell"][data-date="${date}"]:not([data-outside-month])`,
);
}
async function pick(date: string) {
const target = cell(date);
expect(target).not.toBeNull();
target!.click();
await flushPromises();
}
function input(
w: ReturnType<typeof mount>,
slot: "start" | "end",
): HTMLInputElement {
return w.get(`[data-slot="date-range-picker-${slot}-value"]`)
.element as HTMLInputElement;
}
describe("DateRangePicker documentation", () => {
it("includes every pinned preview and uses the displayed SFC as its implementation", () => {
const md = readFileSync(
"apps/docs/components/date-range-picker.md",
"utf8",
);
expect(
[
...md.matchAll(/<ComponentPreview name="date-range-picker-([^"]+)"/g),
].map((match) => match[1]),
).toEqual(expected);
expect(md).not.toContain("[!toc]");
expect(Object.keys(demos)).toHaveLength(10);
});
it("mounts all ten examples without warnings or missing range controls", async () => {
const warnings: string[] = [];
for (const demo of Object.values(demos)) {
const w = mount(demo as never, {
global: {
config: { warnHandler: (message) => warnings.push(message) },
},
});
wrappers.push(w);
await flushPromises();
expect(w.find('[data-slot="date-range-picker"]').exists()).toBe(true);
expect(w.findAll('[data-slot="date-input-group-input"]')).toHaveLength(2);
expect(w.find('[data-slot="date-range-picker-trigger"]').exists()).toBe(
true,
);
expect(
w.findAll('[data-slot="date-input-group-segment"]').length,
).toBeGreaterThanOrEqual(6);
expect(w.findAll('input[data-part="start"]')).toHaveLength(1);
expect(w.findAll('input[data-part="end"]')).toHaveLength(1);
}
expect(warnings).toEqual([]);
});
it("the controlled example updates and clears the real range", async () => {
const w = mountDemo("controlled");
await flushPromises();
expect(input(w, "start").value).toMatch(/^\d{4}-\d{2}-\d{2}$/);
expect(w.get('[data-slot="description"]').text()).not.toContain("(空)");
await w
.findAll("button")
.find((button) => button.text() === "清空")!
.trigger("click");
await flushPromises();
expect(input(w, "start").value).toBe("");
expect(input(w, "end").value).toBe("");
expect(w.get('[data-slot="description"]').text()).toContain("(空)");
await w
.findAll("button")
.find((button) => button.text() === "设为一周")!
.trigger("click");
await flushPromises();
expect(input(w, "start").value).toMatch(/^\d{4}-\d{2}-\d{2}$/);
expect(w.get('[data-slot="description"]').text()).not.toContain("(空)");
});
it("the disabled example keeps values visible and non-editable", async () => {
const w = mountDemo("disabled");
await flushPromises();
expect(input(w, "start").disabled).toBe(true);
expect(input(w, "end").disabled).toBe(true);
expect(input(w, "start").value).toMatch(/^\d{4}-\d{2}-\d{2}$/);
expect(
w.get('[data-slot="date-range-picker-trigger"]').attributes("disabled"),
).toBeDefined();
expect(w.get('[data-slot="description"]').text()).toContain("已禁用");
});
it("format options keeps one range value while both TimeFields edit independently", async () => {
const w = mountDemo("format-options");
await flushPromises();
expect(input(w, "start").value).toContain("T08:45:00");
expect(input(w, "end").value).toContain("T18:45:00");
await open(w);
const timeFields = document.querySelectorAll('[data-slot="time-field"]');
expect(timeFields).toHaveLength(2);
expect(document.querySelectorAll('[name="startTime"]')).toHaveLength(1);
expect(document.querySelectorAll('[name="endTime"]')).toHaveLength(1);
const hour =
timeFields[0]!.querySelector<HTMLElement>('[data-type="hour"]')!;
hour.focus();
hour.dispatchEvent(
new KeyboardEvent("keydown", {
key: "ArrowUp",
bubbles: true,
cancelable: true,
}),
);
await flushPromises();
expect(input(w, "start").value).toContain("T09:45:00");
expect(input(w, "end").value).toContain("T18:45:00");
expect(document.body.textContent).toContain("已选:");
expect(document.body.textContent).toContain("2026");
expect(document.querySelectorAll('[name="startDate"]')).toHaveLength(1);
expect(document.querySelectorAll('[name="endDate"]')).toHaveLength(1);
});
it("format options switches to day granularity without losing the picker", async () => {
const w = mountDemo("format-options");
await flushPromises();
const trigger = w.get('[data-slot="select-trigger"]');
await trigger.trigger("click");
await flushPromises();
const option = [
...document.querySelectorAll<HTMLElement>("[role=option]"),
].find((node) => node.textContent?.trim() === "日")!;
expect(option).toBeTruthy();
option.click();
await flushPromises();
expect(document.querySelectorAll('[data-slot="time-field"]')).toHaveLength(
0,
);
expect(input(w, "start").value).toMatch(/^\d{4}-\d{2}-\d{2}$/);
expect(input(w, "end").value).toMatch(/^\d{4}-\d{2}-\d{2}$/);
expect(document.querySelectorAll('[name="startDate"]')).toHaveLength(1);
});
it("the form example submits a complete range and clears after success", async () => {
vi.useFakeTimers();
const w = mountDemo("form-example");
await flushPromises();
const submit = () =>
w.findAll("button").find((button) => button.text().includes("提交"))!;
expect(submit().attributes("disabled")).toBeDefined();
expect(w.findAll('[name="tripStartDate"]')).toHaveLength(1);
expect(w.findAll('[name="tripEndDate"]')).toHaveLength(1);
const start = today(getLocalTimeZone());
await open(w);
await pick(start.toString());
await pick(start.toString());
expect(submit().attributes("disabled")).toBeUndefined();
await w.get("form").trigger("submit");
await flushPromises();
expect(submit().text()).toContain("提交中");
vi.advanceTimersByTime(1300);
await flushPromises();
expect(input(w, "start").value).toBe("");
expect(input(w, "end").value).toBe("");
expect(submit().text()).toBe("提交");
});
it("the custom indicator uses the Tabler icon instead of the default SVG", async () => {
const w = mountDemo("with-custom-indicator");
await flushPromises();
const icon = w.get('[data-slot="date-range-picker-trigger-indicator"] svg');
expect(icon.attributes("viewBox")).toBe("0 0 24 24");
expect(
w
.find(
'[data-slot="date-range-picker-trigger-indicator"] svg[viewBox="0 0 13 14"]',
)
.exists(),
).toBe(false);
});
it("the render-function example keeps consumer elements and attributes", async () => {
const w = mountDemo("render-function");
await flushPromises();
expect(w.get('[data-slot="date-range-picker"]').element.tagName).toBe(
"SECTION",
);
expect(
w.get('[data-slot="date-range-picker"]').attributes("data-custom"),
).toBe("date-range-picker");
expect(
w.get('[data-slot="date-input-group"]').attributes("data-custom"),
).toBe("date-field-group");
expect(
w
.get('[data-slot="date-range-picker-trigger"]')
.attributes("data-custom"),
).toBe("date-range-picker-trigger");
});
it("the international calendar displays its locale calendar and keeps values", async () => {
const w = mountDemo("international-calendar");
await flushPromises();
expect(input(w, "start").value).not.toBe("");
await open(w);
const header = document.querySelector(
'[data-slot="range-calendar-header-cell"]',
)?.textContent;
expect(header).toBeTruthy();
expect(header).not.toMatch(/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat)$/);
const selected = document.querySelector(
'[data-slot="range-calendar-cell"][data-selection-start="true"]',
);
expect(selected).not.toBeNull();
});
it("the custom styles example applies consumer classes without component patches", async () => {
const w = mountDemo("custom-styles");
await flushPromises();
const group = w.get('[data-slot="date-input-group"]');
expect(group.classes()).toContain("rounded-xl");
expect(group.classes()).toContain("border");
expect(group.classes()).toContain("hv-date-input-group--secondary");
expect(
w.get('[data-slot="date-range-picker-range-separator"]').classes(),
).toContain("text-muted");
expect(
w.get('[data-slot="date-range-picker-trigger"]').classes(),
).toContain("text-muted");
await open(w);
expect(
document.querySelector('[data-slot="date-range-picker-popover"]')
?.className,
).toContain("border");
expect(
document.querySelector('[data-slot="range-calendar"]')?.className,
).toContain("bg-surface");
});
it("the validation example exposes required and invalid state through the form", async () => {
const w = mountDemo("with-validation");
await flushPromises();
const validation = w.get(".hv-choice-validation")
.element as HTMLInputElement;
expect(validation.checkValidity()).toBe(false);
await flushPromises();
expect(w.get('[data-slot="field-error"]').text()).toContain(
"请选择从今天起的有效日期范围",
);
const start = today(getLocalTimeZone());
await open(w);
await pick(start.toString());
await pick(start.toString());
expect(validation.checkValidity()).toBe(true);
expect(w.find('[data-slot="field-error"]').exists()).toBe(false);
});
it("format options formats the range with the active locale and follows runtime switches", async () => {
const tz = getLocalTimeZone();
const start = parseZonedDateTime(`2026-02-03T08:45:00[${tz}]`).toDate();
const end = parseZonedDateTime(`2026-02-10T18:45:00[${tz}]`).toDate();
const formatted = (loc: string) =>
new DateFormatter(loc, {
day: "numeric",
month: "short",
year: "numeric",
}).formatRange(start, end);
expect(formatted("zh-CN")).not.toBe(formatted("en-US"));
const locale = ref("zh-CN");
const demo =
demos["../apps/docs/demos/date-range-picker-format-options.vue"];
const w = mount(
defineComponent({
render: () =>
h(ConfigProvider, { locale: locale.value }, () => h(demo as never)),
}),
{ attachTo: document.body },
);
wrappers.push(w);
await flushPromises();
await open(w);
expect(document.body.textContent).toContain("已选:");
expect(document.body.textContent).toContain(formatted("zh-CN"));
locale.value = "en-US";
await flushPromises();
expect(document.body.textContent).toContain(formatted("en-US"));
expect(document.body.textContent).not.toContain(formatted("zh-CN"));
// The same range renders with the new locale again after a switch back.
locale.value = "zh-CN";
await flushPromises();
expect(document.body.textContent).toContain(formatted("zh-CN"));
expect(document.body.textContent).not.toContain(formatted("en-US"));
});
});