331 lines
13 KiB
TypeScript
331 lines
13 KiB
TypeScript
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
import { mount, flushPromises } from "@vue/test-utils";
|
|
import { defineComponent, shallowRef, type Component } from "vue";
|
|
import {
|
|
CalendarDate,
|
|
CalendarDateTime,
|
|
parseZonedDateTime,
|
|
PersianCalendar,
|
|
toCalendar,
|
|
} from "@internationalized/date";
|
|
import * as lib from "@heroui-vue/components";
|
|
import type { CalendarRangeModel } from "@heroui-vue/components";
|
|
const initial = new CalendarDate(2024, 2, 10);
|
|
const wrappers: ReturnType<typeof mount>[] = [];
|
|
afterEach(() => {
|
|
wrappers.splice(0).forEach((w) => w.unmount());
|
|
document.body.innerHTML = "";
|
|
vi.restoreAllMocks();
|
|
});
|
|
const grid = `<RangeCalendarGrid><RangeCalendarGridHeader v-slot="{day}"><RangeCalendarHeaderCell>{{day}}</RangeCalendarHeaderCell></RangeCalendarGridHeader><RangeCalendarGridBody v-slot="{date}"><RangeCalendarCell :date="date" class="consumer-cell" @click="onClick" @keydown="onKeydown" v-slot="state"><span>{{state.formattedDate}}</span><RangeCalendarCellIndicator v-if="date.day === 12" /></RangeCalendarCell></RangeCalendarGridBody></RangeCalendarGrid>`;
|
|
const header = `<RangeCalendarHeader><RangeCalendarHeading/><RangeCalendarNavButton slot="previous"/><RangeCalendarNavButton slot="next"/></RangeCalendarHeader>`;
|
|
const years = `<CalendarYearPickerTrigger><CalendarYearPickerTriggerHeading/><CalendarYearPickerTriggerIndicator/></CalendarYearPickerTrigger><CalendarYearPickerGrid :visible-years="12"><CalendarYearPickerGridBody/></CalendarYearPickerGrid>`;
|
|
function fixture(
|
|
attrs = "",
|
|
setup: () => Record<string, unknown> = () => ({}),
|
|
content = header + grid,
|
|
) {
|
|
const w = mount(
|
|
defineComponent({
|
|
components: Object.fromEntries(
|
|
Object.entries(lib).filter(([name]) =>
|
|
/^(RangeCalendar|CalendarYearPicker)/.test(name),
|
|
),
|
|
) as Record<string, Component>,
|
|
setup: () => ({
|
|
initial,
|
|
onClick: () => {},
|
|
onKeydown: () => {},
|
|
...setup(),
|
|
}),
|
|
template: `<RangeCalendar ref="calendar" aria-label="Trip dates" :default-focused-value="initial" ${attrs}>${content}</RangeCalendar>`,
|
|
}),
|
|
{ attachTo: document.body },
|
|
);
|
|
wrappers.push(w);
|
|
return w;
|
|
}
|
|
const cell = (w: ReturnType<typeof mount>, day: number, month = 2) =>
|
|
w.get<HTMLButtonElement>(
|
|
`[data-slot="range-calendar-cell"][data-date="2024-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}"]:not([data-outside-month])`,
|
|
);
|
|
const root = (w: ReturnType<typeof mount>) => w.getComponent(lib.RangeCalendar);
|
|
const changes = (w: ReturnType<typeof mount>) =>
|
|
(root(w).emitted("change") ?? []).map(([v]) => v as CalendarRangeModel);
|
|
async function click(w: ReturnType<typeof mount>, day: number) {
|
|
await cell(w, day).trigger("click");
|
|
await flushPromises();
|
|
}
|
|
async function key(w: ReturnType<typeof mount>, day: number, key: string) {
|
|
cell(w, day).element.focus();
|
|
await cell(w, day).trigger("keydown", { key, code: key });
|
|
await flushPromises();
|
|
}
|
|
async function pointer(
|
|
w: ReturnType<typeof mount>,
|
|
day: number,
|
|
type: string,
|
|
overrides = {},
|
|
) {
|
|
const e = new Event(type, { bubbles: true, cancelable: true });
|
|
Object.assign(e, {
|
|
pointerId: 1,
|
|
pointerType: "mouse",
|
|
button: 0,
|
|
isPrimary: true,
|
|
...overrides,
|
|
});
|
|
cell(w, day).element.dispatchEvent(e);
|
|
await flushPromises();
|
|
}
|
|
describe("RangeCalendar public composition", () => {
|
|
it("exposes the same Root and namespaced parts with actual selection markers and native refs", async () => {
|
|
expect(lib.RangeCalendar).toBe(lib.RangeCalendarRoot);
|
|
const w = fixture('class="consumer-root" as="section"');
|
|
expect(root(w).element.tagName).toBe("SECTION");
|
|
expect(root(w).classes()).toContain("consumer-root");
|
|
await click(w, 15);
|
|
expect(changes(w)).toEqual([]);
|
|
await click(w, 10);
|
|
expect(changes(w)[0]?.start.toString()).toBe("2024-02-10");
|
|
expect(changes(w)[0]?.end.toString()).toBe("2024-02-15");
|
|
expect(cell(w, 10).attributes("data-selection-start")).toBe("true");
|
|
expect(cell(w, 15).attributes("data-selection-end")).toBe("true");
|
|
expect(cell(w, 12).attributes("data-selection-in-range")).toBe("true");
|
|
expect(cell(w, 10).attributes("data-selection-in-range")).toBeUndefined();
|
|
expect(cell(w, 12).classes()).toContain("consumer-cell");
|
|
expect(
|
|
cell(w, 12)
|
|
.get('[data-slot="range-calendar-cell-indicator"]')
|
|
.attributes("aria-hidden"),
|
|
).toBe("true");
|
|
root(w).vm.focus();
|
|
await flushPromises();
|
|
expect(document.activeElement).toBe(cell(w, 10).element);
|
|
expect(root(w).vm.element).toBe(root(w).element);
|
|
const part = w.findComponent(lib.RangeCalendarCell);
|
|
expect(part.vm.element?.tagName).toBe("BUTTON");
|
|
expect(w.find("input[name]").exists()).toBe(false);
|
|
});
|
|
it("orders same-day selection and independently copies change/update payloads", async () => {
|
|
const w = fixture();
|
|
await click(w, 10);
|
|
await click(w, 10);
|
|
expect(changes(w)[0]?.end.toString()).toBe("2024-02-10");
|
|
const value = changes(w)[0]!;
|
|
const update = root(w).emitted(
|
|
"update:modelValue",
|
|
)![0][0] as NonNullable<CalendarRangeModel>;
|
|
expect(value).not.toBe(update);
|
|
expect(value.start).not.toBe(update.start);
|
|
Object.assign(value.start, { day: 2 });
|
|
expect(update.start.day).toBe(10);
|
|
expect(cell(w, 10).attributes("data-selected")).toBe("true");
|
|
});
|
|
it("keeps controlled rejection stable and repeats the same proposal", async () => {
|
|
const accepted = { start: initial, end: initial.add({ days: 2 }) };
|
|
const w = fixture(':model-value="accepted"', () => ({ accepted }));
|
|
for (let n = 0; n < 2; n++) {
|
|
await click(w, 15);
|
|
await click(w, 17);
|
|
expect(cell(w, 10).attributes("data-selected")).toBe("true");
|
|
expect(cell(w, 15).attributes("data-selected")).toBeUndefined();
|
|
}
|
|
expect(changes(w).map((v) => v?.start.day)).toEqual([15, 15]);
|
|
expect(accepted.start.day).toBe(10);
|
|
});
|
|
it("prioritizes explicit empty models and clears drafts on external changes", async () => {
|
|
const value = shallowRef<CalendarRangeModel>(null);
|
|
const w = fixture(
|
|
'v-model="value" :value="accepted" :default-value="accepted"',
|
|
() => ({ value, accepted: { start: initial, end: initial } }),
|
|
);
|
|
expect(w.find("[data-selected]").exists()).toBe(false);
|
|
await click(w, 10);
|
|
value.value = {
|
|
start: initial.add({ days: 5 }),
|
|
end: initial.add({ days: 7 }),
|
|
};
|
|
await flushPromises();
|
|
expect(cell(w, 10).attributes("data-selected")).toBeUndefined();
|
|
expect(changes(w)).toHaveLength(0);
|
|
await click(w, 20);
|
|
expect(changes(w)).toHaveLength(0);
|
|
value.value = null;
|
|
await flushPromises();
|
|
expect(w.find("[data-selected]").exists()).toBe(false);
|
|
});
|
|
it("supports keyboard preview, confirmation, Escape and native cancellation", async () => {
|
|
const w = fixture();
|
|
await key(w, 10, "Enter");
|
|
expect(document.activeElement).toBe(cell(w, 11).element);
|
|
await key(w, 11, "ArrowRight");
|
|
await key(w, 12, "Enter");
|
|
expect(changes(w)[0]?.end.day).toBe(12);
|
|
await key(w, 15, " ");
|
|
await key(w, 16, "Escape");
|
|
expect(cell(w, 15).attributes("data-selected")).toBeUndefined();
|
|
expect(changes(w)).toHaveLength(1);
|
|
const c = fixture("", () => ({
|
|
onClick: (e: Event) => e.preventDefault(),
|
|
onKeydown: (e: Event) => e.preventDefault(),
|
|
}));
|
|
await click(c, 10);
|
|
await click(c, 15);
|
|
await key(c, 10, "Enter");
|
|
expect(changes(c)).toHaveLength(0);
|
|
expect(c.find("[data-selected]").exists()).toBe(false);
|
|
});
|
|
it("retains keyboard focus on unavailable dates, blocks crossings and supports non-contiguous selection", async () => {
|
|
const w = fixture(':is-date-unavailable="unavailable"', () => ({
|
|
unavailable: (d: CalendarDate) => d.day === 12,
|
|
}));
|
|
await key(w, 11, "ArrowRight");
|
|
expect(document.activeElement).toBe(cell(w, 12).element);
|
|
await click(w, 10);
|
|
await click(w, 15);
|
|
expect(changes(w)).toHaveLength(0);
|
|
const n = fixture(
|
|
'allows-non-contiguous-ranges :is-date-unavailable="unavailable"',
|
|
() => ({ unavailable: (d: CalendarDate) => d.day === 12 }),
|
|
);
|
|
await click(n, 10);
|
|
await click(n, 15);
|
|
expect(changes(n)[0]?.end.day).toBe(15);
|
|
expect(cell(n, 12).attributes("data-selected")).toBeUndefined();
|
|
expect(cell(n, 12).attributes("aria-disabled")).toBe("true");
|
|
});
|
|
it("reacts to anchor rules and disabled/readOnly changes without committing drafts", async () => {
|
|
const disabled = shallowRef(false);
|
|
const w = fixture(
|
|
':is-disabled="disabled" :is-date-unavailable="unavailable"',
|
|
() => ({
|
|
disabled,
|
|
unavailable: (d: CalendarDate, a: CalendarDate | null) =>
|
|
!!a && Math.abs(d.compare(a)) > 3,
|
|
}),
|
|
);
|
|
await click(w, 10);
|
|
expect(cell(w, 15).attributes("data-unavailable")).toBe("true");
|
|
disabled.value = true;
|
|
await flushPromises();
|
|
expect(w.find("[data-selected]").exists()).toBe(false);
|
|
expect(changes(w)).toHaveLength(0);
|
|
const r = fixture('is-read-only :default-value="accepted"', () => ({
|
|
accepted: { start: initial, end: initial.add({ days: 2 }) },
|
|
}));
|
|
await click(r, 15);
|
|
await key(r, 10, "Enter");
|
|
expect(changes(r)).toHaveLength(0);
|
|
expect(cell(r, 10).attributes("data-selected")).toBe("true");
|
|
});
|
|
it("commits mouse drag once, rolls back cancellation/outside release and keeps touch pointerdown inert", async () => {
|
|
const w = fixture();
|
|
await pointer(w, 10, "pointerdown");
|
|
await pointer(w, 15, "pointerenter");
|
|
await pointer(w, 15, "pointerup");
|
|
await click(w, 15);
|
|
expect(changes(w)).toHaveLength(1);
|
|
await pointer(w, 20, "pointerdown");
|
|
await pointer(w, 22, "pointerenter");
|
|
document.dispatchEvent(
|
|
Object.assign(new Event("pointercancel"), { pointerId: 1 }),
|
|
);
|
|
await flushPromises();
|
|
expect(cell(w, 20).attributes("data-selected")).toBeUndefined();
|
|
await pointer(w, 20, "pointerdown");
|
|
document.dispatchEvent(
|
|
Object.assign(new Event("pointerup"), { pointerId: 1 }),
|
|
);
|
|
await new Promise((r) => setTimeout(r, 5));
|
|
await flushPromises();
|
|
expect(cell(w, 20).attributes("data-selected")).toBeUndefined();
|
|
await pointer(w, 20, "pointerdown", { pointerType: "touch" });
|
|
expect(cell(w, 20).attributes("data-selected")).toBeUndefined();
|
|
await click(w, 20);
|
|
await click(w, 22);
|
|
expect(changes(w)).toHaveLength(2);
|
|
});
|
|
it("uses shared multi-month, week/day, RTL and year navigation with focus restoration", async () => {
|
|
const w = fixture(
|
|
':visible-duration="{months:2}"',
|
|
() => ({}),
|
|
header +
|
|
grid +
|
|
grid.replace(
|
|
"<RangeCalendarGrid>",
|
|
'<RangeCalendarGrid :offset="{months:1}">',
|
|
) +
|
|
years,
|
|
);
|
|
expect(w.findAll('table[data-slot="range-calendar-grid"]')).toHaveLength(2);
|
|
await w.get('[data-slot="calendar-year-picker-trigger"]').trigger("click");
|
|
await flushPromises();
|
|
expect(w.get('[data-slot="range-calendar-grid"]').attributes("inert")).toBe(
|
|
"",
|
|
);
|
|
await w
|
|
.get('[data-slot="calendar-year-picker-cell"]')
|
|
.trigger("keydown", { key: "Escape" });
|
|
await flushPromises();
|
|
expect(document.activeElement).toBe(
|
|
w.get('[data-slot="calendar-year-picker-trigger"]').element,
|
|
);
|
|
expect(changes(w)).toHaveLength(0);
|
|
const d = fixture(':visible-duration="{days:10}" dir="rtl"');
|
|
expect(
|
|
d.findAll('button[data-slot="range-calendar-cell"]:not([disabled])'),
|
|
).toHaveLength(10);
|
|
await key(d, 10, "ArrowLeft");
|
|
expect(document.activeElement).toBe(cell(d, 11).element);
|
|
const weeks = fixture(':visible-duration="{weeks:2}"');
|
|
expect(weeks.findAll("tbody tr")).toHaveLength(2);
|
|
});
|
|
it("preserves per-endpoint precision and calendar while locale changes only the view", async () => {
|
|
const start = new CalendarDateTime(2024, 2, 10, 8, 9, 45, 123),
|
|
end = parseZonedDateTime(
|
|
"2024-02-12T20:30:15.456-08:00[America/Los_Angeles]",
|
|
);
|
|
const w = fixture(':default-value="accepted"', () => ({
|
|
accepted: { start, end },
|
|
}));
|
|
await click(w, 15);
|
|
await click(w, 17);
|
|
expect(changes(w)[0]?.start.toString()).toBe(
|
|
start.set({ day: 15 }).toString(),
|
|
);
|
|
expect(changes(w)[0]?.end.toString()).toBe(end.set({ day: 17 }).toString());
|
|
const a = toCalendar(initial, new PersianCalendar()),
|
|
b = a.add({ days: 2 });
|
|
const p = fixture(':default-value="accepted" locale="en-US"', () => ({
|
|
accepted: { start: a, end: b },
|
|
}));
|
|
await click(p, 15);
|
|
await click(p, 17);
|
|
expect(changes(p)[0]?.start.calendar.identifier).toBe("persian");
|
|
expect(a.day).not.toBe(changes(p)[0]?.start.day);
|
|
});
|
|
it("exposes copied root snapshots so consumers cannot mutate accepted or draft dates", async () => {
|
|
const snapshots: CalendarRangeModel[] = [];
|
|
const w = fixture(
|
|
':default-value="accepted"',
|
|
() => ({
|
|
accepted: { start: initial, end: initial.add({ days: 2 }) },
|
|
snapshot: (v: CalendarRangeModel) => {
|
|
snapshots.push(v);
|
|
return "";
|
|
},
|
|
}),
|
|
'<template #default="{value,anchorDate,highlightedRange,focusedValue,visibleRange}"><output>{{snapshot(value)}}{{focusedValue.toString()}} / {{visibleRange.start.toString()}}</output>' +
|
|
header +
|
|
grid +
|
|
"</template>",
|
|
);
|
|
Object.assign(snapshots.at(-1)!.start, { day: 3 });
|
|
await click(w, 15);
|
|
await click(w, 17);
|
|
expect(changes(w)[0]?.start.day).toBe(15);
|
|
expect(initial.day).toBe(10);
|
|
});
|
|
});
|