import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { mount, flushPromises } from "@vue/test-utils"; import { defineComponent, nextTick, ref } from "vue"; import { CalendarDate, CalendarDateTime, getLocalTimeZone, parseZonedDateTime, Time, today, type DateValue, } from "@internationalized/date"; import { Calendar, CalendarCell, CalendarGrid, CalendarGridBody, CalendarGridHeader, CalendarHeader, CalendarHeaderCell, CalendarHeading, CalendarNavButton, CalendarYearPickerCell, CalendarYearPickerGrid, CalendarYearPickerGridBody, CalendarYearPickerTrigger, CalendarYearPickerTriggerHeading, CalendarYearPickerTriggerIndicator, DateFieldGroup, DateFieldInput, DateFieldSegment, DateFieldSuffix, DatePicker, DatePickerPopover, DatePickerTrigger, DatePickerTriggerIndicator, Description, FieldError, Form, Label, TimeField, TimeFieldGroup, TimeFieldInput, TimeFieldSegment, } from "../packages/vue/src"; const components = { Calendar, CalendarCell, CalendarGrid, CalendarGridBody, CalendarGridHeader, CalendarHeader, CalendarHeaderCell, CalendarHeading, CalendarNavButton, CalendarYearPickerCell, CalendarYearPickerGrid, CalendarYearPickerGridBody, CalendarYearPickerTrigger, CalendarYearPickerTriggerHeading, CalendarYearPickerTriggerIndicator, DateFieldGroup, DateFieldInput, DateFieldSegment, DateFieldSuffix, DatePicker, DatePickerPopover, DatePickerTrigger, DatePickerTriggerIndicator, Description, FieldError, Form, Label, TimeField, TimeFieldGroup, TimeFieldInput, TimeFieldSegment, }; const calendar = ` {{ day }} `; const content = ` ${calendar}`; const wideCalendar = ` {{ day }} `; const defaultTriggerContent = content.replace(' aria-label="打开日历"', ""); const unlabeledContent = defaultTriggerContent.replace( "", "", ); const initial = new CalendarDate(2024, 2, 10); const wrappers: ReturnType[] = []; beforeEach(() => { vi.stubGlobal( "ResizeObserver", class { observe() {} unobserve() {} disconnect() {} }, ); }); afterEach(async () => { wrappers.splice(0).forEach((w) => w.unmount()); await flushPromises(); vi.unstubAllGlobals(); document.body.innerHTML = ""; }); function view(template: string, setup = () => ({})) { const w = mount(defineComponent({ components, template, setup }), { attachTo: document.body, }); wrappers.push(w); return w; } const native = (w: ReturnType) => w.get('[data-slot="date-picker-value"]').element as HTMLInputElement; const trigger = '[data-slot="date-picker-trigger"]'; async function open(w: ReturnType) { await w.get(trigger).trigger("click"); await flushPromises(); } async function pick(w: ReturnType, date: string) { const cell = document.querySelector( `[data-slot="calendar-cell"][data-date="${date}"]`, ); expect(cell).not.toBeNull(); cell!.click(); await flushPromises(); } describe("DatePicker public composition", () => { it("renders the picker root, trigger and one named date submission", async () => { const w = view( `
${content}
`, () => ({ initial }), ); const root = w.get('[data-slot="date-picker"]'); expect(root.classes()).toContain("hv-date-picker"); expect(root.attributes("role")).toBe("group"); expect(root.attributes("aria-labelledby")).toContain( w.get('[data-slot="label"]').attributes("id"), ); expect( w.get('[data-slot="date-picker-trigger"]').attributes("aria-expanded"), ).toBe("false"); expect(native(w).value).toBe("2024-02-10"); expect( new FormData(w.get("form").element as HTMLFormElement).getAll("date"), ).toEqual(["2024-02-10"]); }); it("opens the real popover and selects a calendar date once", async () => { const w = view( `
${content}
`, () => ({ initial }), ); await w.get('[data-slot="date-picker-trigger"]').trigger("click"); await flushPromises(); expect( document.querySelector('[data-slot="date-picker-popover"]'), ).not.toBeNull(); expect(document.querySelector('[role="dialog"]')).not.toBeNull(); const cell = document.querySelector( '[data-slot="calendar-cell"][data-date="2024-02-15"]', )!; expect(cell).not.toBeNull(); cell.click(); await flushPromises(); expect(native(w).value).toBe("2024-02-15"); expect(w.getComponent(DatePicker).emitted("change")).toHaveLength(1); expect( ( w.getComponent(DatePicker).emitted("change")![0]![0] as CalendarDate ).toString(), ).toBe("2024-02-15"); expect( document.querySelector('[data-slot="date-picker-popover"]'), ).toBeNull(); }); it("toggles the popover through the controlled open model and ignores a cancelled click", async () => { const openModel = ref(false), updates: boolean[] = []; const w = view( `${content}`, () => ({ openModel, initial, updates }), ); await w.get(trigger).trigger("click"); await flushPromises(); expect(updates).toEqual([true]); expect(document.querySelector('[role="dialog"]')).toBeNull(); openModel.value = true; await nextTick(); await flushPromises(); expect(document.querySelector('[role="dialog"]')).not.toBeNull(); expect(w.get(trigger).attributes("aria-expanded")).toBe("true"); window.dispatchEvent( new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true, }), ); await flushPromises(); expect(updates).toEqual([true, false]); expect(document.querySelector('[role="dialog"]')).not.toBeNull(); openModel.value = false; await nextTick(); await flushPromises(); expect(document.querySelector('[role="dialog"]')).toBeNull(); const cancel = ref(true); const cancelled = view( `打开${calendar}`, () => ({ initial, cancel }), ); await cancelled.get(trigger).trigger("click"); await flushPromises(); expect(document.querySelector('[role="dialog"]')).toBeNull(); }); it("inherits picker locale and direction into an unbound calendar", async () => { const w = view( `${content}`, () => ({ initial }), ); expect(w.get('[data-slot="date-picker"]').attributes("dir")).toBe("rtl"); expect( w .findAll('[data-slot="date-input-group-segment"]')[0] .attributes("data-type"), ).toBe("year"); await open(w); const focused = document.activeElement!; const date = focused.getAttribute("data-date"); expect(date).toBe("2024-02-10"); expect( document.querySelector('[data-slot="calendar-header-cell"]')?.textContent, ).toBe("周三"); focused.dispatchEvent( new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true, cancelable: true, }), ); await flushPromises(); expect(document.activeElement?.getAttribute("data-date")).toBe( "2024-02-09", ); }); it("closes from Escape inside a date segment even though the base cancels that key", async () => { const w = view( `${content}`, () => ({ initial }), ); await open(w); const segment = w.get('[data-type="day"]').element as HTMLElement; segment.focus(); segment.dispatchEvent( new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true, }), ); await flushPromises(); expect( document.querySelector('[data-slot="date-picker-popover"]'), ).toBeNull(); }); it("rejects and retries the same controlled value without draft pollution", async () => { const value = ref(initial), accept = ref(false); const w = view( `
${content}
`, () => ({ value, accept, initial }), ); const day = w.get('[data-type="day"]'); await day.trigger("keydown", { key: "ArrowUp" }); await flushPromises(); expect(native(w).value).toBe("2024-02-10"); expect(day.text()).toBe("10"); await day.trigger("keydown", { key: "ArrowUp" }); await flushPromises(); expect(native(w).value).toBe("2024-02-10"); expect( w .getComponent(DatePicker) .emitted("update:modelValue")! .map((args) => (args[0] as CalendarDate).toString()), ).toEqual(["2024-02-11", "2024-02-11"]); accept.value = true; await day.trigger("keydown", { key: "ArrowUp" }); await flushPromises(); expect(value.value?.toString()).toBe("2024-02-11"); expect(native(w).value).toBe("2024-02-11"); value.value = null; await nextTick(); await flushPromises(); expect(native(w).value).toBe(""); expect(w.findAll('[data-placeholder="true"]')).toHaveLength(3); }); it("keeps the accepted value when a controlled calendar proposal is rejected", async () => { const value = ref(initial), accept = ref(false); const w = view( `${content}`, () => ({ value, accept, initial }), ); await open(w); await pick(w, "2024-02-15"); expect(native(w).value).toBe("2024-02-10"); expect( ( w.getComponent(DatePicker).emitted("change")![0]![0] as DateValue ).toString(), ).toBe("2024-02-15"); await open(w); expect( document .querySelector('[data-slot="calendar-cell"][data-date="2024-02-15"]') ?.getAttribute("data-selected"), ).toBeNull(); accept.value = true; await pick(w, "2024-02-15"); expect(value.value?.toString()).toBe("2024-02-15"); expect(native(w).value).toBe("2024-02-15"); }); it("honors shouldCloseOnSelect=false and keeps calendar and field in sync", async () => { const w = view( `${content}`, () => ({ initial }), ); await open(w); await pick(w, "2024-02-15"); expect(document.querySelector('[role="dialog"]')).not.toBeNull(); expect(native(w).value).toBe("2024-02-15"); expect( document .querySelector('[data-slot="calendar-cell"][data-date="2024-02-15"]') ?.getAttribute("data-selected"), ).toBe("true"); await w.get('[data-type="day"]').trigger("keydown", { key: "ArrowUp" }); await flushPromises(); expect(native(w).value).toBe("2024-02-16"); expect( document .querySelector('[data-slot="calendar-cell"][data-date="2024-02-16"]') ?.getAttribute("data-selected"), ).toBe("true"); }); it("preserves date class, time, zone, seconds and calendar when picking a day", async () => { const zoned = parseZonedDateTime( "2024-03-10T01:30:45.123-08:00[America/Los_Angeles]", ); const zonedView = view( `${content}`, () => ({ zoned }), ); await open(zonedView); await pick(zonedView, "2024-03-12"); const zonedValue = zonedView .getComponent(DatePicker) .emitted("change")![0]![0] as typeof zoned; expect(zonedValue.toString()).toBe( "2024-03-12T01:30:45.123-07:00[America/Los_Angeles]", ); expect(zonedValue.timeZone).toBe("America/Los_Angeles"); expect([ zonedValue.hour, zonedValue.minute, zonedValue.second, zonedValue.millisecond, ]).toEqual([1, 30, 45, 123]); expect(native(zonedView).value).toBe(zonedValue.toString()); const dateTime = new CalendarDateTime(2024, 2, 10, 18, 4, 5, 6); const dateTimeView = view( `${content}`, () => ({ dateTime }), ); await open(dateTimeView); await pick(dateTimeView, "2024-02-12"); expect( ( dateTimeView .getComponent(DatePicker) .emitted("change")![0]![0] as CalendarDateTime ).toString(), ).toBe("2024-02-12T18:04:05.006"); }); it("routes slot time operations through the same accepted value", async () => { const initialDateTime = new CalendarDateTime(2024, 2, 10, 1, 2, 3); const w = view( `{{ timeValue?.toString() }}打开${calendar}`, () => ({ initialDateTime, Time }), ); expect(w.get('[data-test="time"]').text()).toBe("01:02:03"); await w.get('[data-test="set-time"]').trigger("click"); await flushPromises(); expect(w.get('[data-test="time"]').text()).toBe("09:08:07"); expect(native(w).value).toBe("2024-02-10T09:08:07"); await open(w); await pick(w, "2024-02-12"); expect(native(w).value).toBe("2024-02-12T09:08:07"); expect( w .getComponent(DatePicker) .emitted("change")! .map((args) => (args[0] as DateValue).toString()), ).toEqual(["2024-02-10T09:08:07", "2024-02-12T09:08:07"]); }); it("keeps an empty picker empty after a time draft and completes it only with a day", async () => { const placeholder = new CalendarDateTime(2024, 2, 10, 0, 0); const w = view( `
打开${calendar}
`, () => ({ placeholder, Time }), ); await w.get('[data-test="set-time"]').trigger("click"); await flushPromises(); expect(native(w).value).toBe(""); expect( new FormData(w.get("form").element as HTMLFormElement).getAll("date"), ).toEqual([""]); await open(w); await pick(w, "2024-02-15"); expect(native(w).value).toBe("2024-02-15T09:08:07"); expect( ( w.getComponent(DatePicker).emitted("change")![0]![0] as CalendarDateTime ).toString(), ).toBe("2024-02-15T09:08:07"); }); it("submits one named date, validates required, accepts a day, and resets to empty", async () => { const w = view( `
${content}
`, () => ({ initial }), ); expect(w.findAll('form [name="date"]')).toHaveLength(1); 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("请填写"); expect(w.get('[data-slot="date-picker"]').attributes("aria-invalid")).toBe( "true", ); await open(w); await pick(w, "2024-02-15"); expect(validation.checkValidity()).toBe(true); expect( new FormData(w.get("form").element as HTMLFormElement).getAll("date"), ).toEqual(["2024-02-15"]); (w.get("form").element as HTMLFormElement).reset(); await flushPromises(); expect(native(w).value).toBe(""); expect( w.get('[data-slot="date-picker"]').attributes("aria-invalid"), ).toBeUndefined(); expect(w.findAll('[data-placeholder="true"]')).toHaveLength(3); await open(w); expect( document.querySelector( '[data-slot="calendar-cell"][data-selected="true"]', ), ).toBeNull(); }); it("applies min/max/unavailable rules to both segments and calendar", async () => { const w = view( `${content}`, () => ({ initial }), ); await flushPromises(); expect(w.get('[data-slot="field-error"]').text()).toContain("不能早于"); await open(w); expect( document .querySelector('[data-slot="calendar-cell"][data-date="2024-02-10"]') ?.getAttribute("data-disabled"), ).toBe("true"); expect( document .querySelector('[data-slot="calendar-cell"][data-date="2024-02-20"]') ?.getAttribute("data-unavailable"), ).toBe("true"); const unavailable = document.querySelector( '[data-slot="calendar-cell"][data-date="2024-02-20"]', )!; unavailable.click(); await flushPromises(); expect(native(w).value).toBe("2024-02-10"); await pick(w, "2024-02-21"); expect(native(w).value).toBe("2024-02-21"); }); it("disables editing and opening, and keeps read-only submission non-editable", async () => { const disabled = view( `
${content}
`, () => ({ initial }), ); expect(disabled.get(trigger).attributes("disabled")).toBeDefined(); expect(native(disabled).disabled).toBe(true); expect( new FormData(disabled.get("form").element as HTMLFormElement).getAll( "date", ), ).toEqual([]); await disabled .get('[data-type="day"]') .trigger("keydown", { key: "ArrowUp" }); expect(disabled.getComponent(DatePicker).emitted("change")).toBeUndefined(); const readOnly = view( `
${content}
`, () => ({ initial }), ); expect(native(readOnly).value).toBe("2024-02-10"); await readOnly .get('[data-type="day"]') .trigger("keydown", { key: "ArrowUp" }); expect(readOnly.getComponent(DatePicker).emitted("change")).toBeUndefined(); expect(readOnly.get(trigger).attributes("disabled")).toBeDefined(); await readOnly.get(trigger).trigger("click"); await flushPromises(); expect(document.querySelector('[role="dialog"]')).toBeNull(); }); it("keeps an explicitly bound child calendar independent from the picker value", async () => { const calendarValue = ref(null); const w = view( `打开{{ day }}`, () => ({ initial, calendarValue }), ); await open(w); await pick(w, "2024-02-15"); expect(calendarValue.value?.toString()).toBe("2024-02-15"); expect(native(w).value).toBe("2024-02-10"); expect(document.querySelector('[role="dialog"]')).not.toBeNull(); }); it("resolves default trigger/dialog labels and restores focus after a mouse selection", async () => { const w = view( `
${defaultTriggerContent}
`, () => ({ initial }), ); const element = w.get(trigger); const label = w.get('[data-slot="label"]'); expect(element.attributes("id")).toBeTruthy(); expect(element.attributes("aria-label")).toBeUndefined(); expect(element.attributes("aria-labelledby")).toContain( label.attributes("id"), ); await open(w); const dialog = document.querySelector('[role="dialog"]')!; const labelledBy = dialog.getAttribute("aria-labelledby")!; expect(document.getElementById(labelledBy)).not.toBeNull(); await pick(w, "2024-02-15"); await flushPromises(); expect(document.activeElement).toBe(element.element); }); it("links custom trigger ids and still names a trigger without a field label", async () => { const custom = view( `${defaultTriggerContent.replace("", '')}`, () => ({ initial }), ); const customTrigger = custom.get(trigger); expect(customTrigger.attributes("id")).toBe("custom-trigger"); await open(custom); expect( document.getElementById( document .querySelector('[role="dialog"]')! .getAttribute("aria-labelledby")!, ), ).toBe(customTrigger.element); custom.unmount(); const unlabeled = view( `${unlabeledContent}`, () => ({ initial }), ); const triggerElement = unlabeled.get(trigger); expect(triggerElement.attributes("aria-labelledby")).toBeUndefined(); expect(triggerElement.attributes("aria-label")).toBe("Calendar"); await open(unlabeled); expect( document.getElementById( document .querySelector('[role="dialog"]')! .getAttribute("aria-labelledby")!, ), ).toBe(triggerElement.element); }); it("reacts to added, replaced and removed unavailable date rules", async () => { const rule = ref<((value: DateValue) => boolean) | undefined>(() => false); const w = view( `${content}`, () => ({ initial, rule }), ); await open(w); const cell = () => document.querySelector( '[data-slot="calendar-cell"][data-date="2024-02-15"]', ); expect(cell()?.getAttribute("data-unavailable")).toBeNull(); rule.value = (value) => value.day === 15; await nextTick(); await flushPromises(); expect(cell()?.getAttribute("data-unavailable")).toBe("true"); rule.value = (value) => value.day === 16; await nextTick(); await flushPromises(); expect(cell()?.getAttribute("data-unavailable")).toBeNull(); expect( document .querySelector('[data-slot="calendar-cell"][data-date="2024-02-16"]') ?.getAttribute("data-unavailable"), ).toBe("true"); rule.value = undefined; await nextTick(); await flushPromises(); expect( document .querySelector('[data-slot="calendar-cell"][data-date="2024-02-16"]') ?.getAttribute("data-unavailable"), ).toBeNull(); }); it("reacts to firstDayOfWeek and pageBehavior changes in the unbound calendar", async () => { const first = ref<"wed" | "mon">("wed"); const behavior = ref<"single" | "visible">("single"); const w = view( `${defaultTriggerContent.replace(`${calendar}`, `${wideCalendar}`)}`, () => ({ initial, first, behavior }), ); await open(w); const firstHeader = () => document.querySelector('[data-slot="calendar-header-cell"]')?.textContent; expect(firstHeader()).toBe("Wed"); first.value = "mon"; await nextTick(); await flushPromises(); expect(firstHeader()).toBe("Mon"); const heading = () => document.querySelector('[data-slot="calendar-heading"]')?.textContent ?? ""; const clickNext = () => { const button = document.querySelector( '[data-slot="calendar-nav-button"][aria-label="Next"]', )!; button.focus(); button.dispatchEvent( new MouseEvent("click", { bubbles: true, cancelable: true }), ); }; clickNext(); await flushPromises(); expect(heading()).toContain("March"); expect(heading()).toContain("April"); behavior.value = "visible"; await nextTick(); await flushPromises(); clickNext(); await flushPromises(); expect(heading()).toContain("May"); expect(heading()).toContain("June"); }); it("honors disabled keyboard dismissal from a date segment", async () => { const disabled = view( `${content.replace("", "")}`, () => ({ initial }), ); await open(disabled); const disabledSegment = disabled.get('[data-type="day"]') .element as HTMLElement; disabledSegment.focus(); disabledSegment.dispatchEvent( new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true, }), ); await flushPromises(); expect( document.querySelector('[data-slot="date-picker-popover"]'), ).not.toBeNull(); expect(disabled.get(trigger).attributes("aria-expanded")).toBe("true"); }); it("honors a cancelled escape-key-down callback from a date segment", async () => { const cancel = ref(true); const w = view( `${content.replace("", '')}`, () => ({ initial, cancel }), ); await open(w); const contentId = w.get(trigger).attributes("aria-controls")!; const segment = w.get('[data-type="day"]').element as HTMLElement; segment.focus(); segment.dispatchEvent( new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true, }), ); await flushPromises(); expect(document.getElementById(contentId)).not.toBeNull(); cancel.value = false; segment.dispatchEvent( new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true, }), ); await flushPromises(); expect(document.getElementById(contentId)).toBeNull(); }); it("honors keyboard dismissal policy from a time segment", async () => { const timeContent = `打开${calendar}`; const initialDateTime = new CalendarDateTime(2024, 2, 10, 9, 8, 7); const dismissDisabled = ref(true); const w = view(timeContent, () => ({ initialDateTime, dismissDisabled })); await open(w); const hour = document.querySelector( '[data-slot="date-picker-popover"] [data-slot="time-field"] [data-type="hour"]', )!; hour.focus(); hour.dispatchEvent( new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true, }), ); await flushPromises(); expect( document.querySelector('[data-slot="date-picker-popover"]'), ).not.toBeNull(); dismissDisabled.value = false; await nextTick(); hour.dispatchEvent( new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true, }), ); await flushPromises(); expect( document.querySelector('[data-slot="date-picker-popover"]'), ).toBeNull(); }); it("clears an empty time draft on reset before a later day is completed", async () => { const placeholder = new CalendarDateTime(2024, 2, 10, 0, 0); const template = `
{{ state.timeValue?.toString() ?? "" }}打开${calendar}
`; const w = view(template, () => ({ placeholder, Time })); await w.get('[data-test="set-time"]').trigger("click"); await flushPromises(); expect(w.get('[data-test="time"]').text()).toBe("09:08:07"); (w.get("form").element as HTMLFormElement).reset(); await flushPromises(); expect(w.get('[data-test="time"]').text()).toBe(""); expect(native(w).value).toBe(""); await open(w); await pick(w, "2024-02-15"); expect(native(w).value).toBe("2024-02-15T00:00:00"); }); it("clears an empty time draft after resetting an externally associated form", async () => { const placeholder = new CalendarDateTime(2024, 2, 10, 0, 0); const template = `
打开${calendar}
`; const w = view(template, () => ({ placeholder, Time })); await w.get('[data-test="set-time"]').trigger("click"); await flushPromises(); (document.getElementById("external") as HTMLFormElement).reset(); await flushPromises(); expect(native(w).value).toBe(""); await open(w); await pick(w, "2024-02-15"); expect(native(w).value).toBe("2024-02-15T00:00:00"); }); it("keeps an empty time draft when reset is cancelled", async () => { const placeholder = new CalendarDateTime(2024, 2, 10, 0, 0); const template = `
{{ state.timeValue?.toString() ?? "" }}打开${calendar}
`; const w = view(template, () => ({ placeholder, Time })); await w.get('[data-test="set-time"]').trigger("click"); await flushPromises(); (w.get("form").element as HTMLFormElement).reset(); await flushPromises(); expect(w.get('[data-test="time"]').text()).toBe("09:08:07"); }); it("keeps field validation and the calendar rule in sync after a rule change", async () => { const value = ref(new CalendarDate(2024, 2, 15)); const rule = ref<(date: DateValue) => boolean>(() => false); const w = view( `
${content}
`, () => ({ value, rule }), ); await flushPromises(); expect(w.find('[data-slot="field-error"]').exists()).toBe(false); rule.value = (date) => date.day === 15; await nextTick(); await flushPromises(); expect(w.get('[data-slot="field-error"]').text()).toContain("此日期不可用"); await open(w); expect( document .querySelector('[data-slot="calendar-cell"][data-date="2024-02-15"]') ?.getAttribute("data-unavailable"), ).toBe("true"); }); });