Files
heroui-vue/tests/range-calendar-foundation.test.ts

541 lines
21 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 { afterEach, describe, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, shallowRef, type Component } from "vue";
import {
CalendarDate,
CalendarDateTime,
PersianCalendar,
toCalendar,
parseZonedDateTime,
type DateValue,
} from "@internationalized/date";
import Range from "../packages/vue/tests/fixtures/RangeCalendarFoundation.vue";
import * as library from "../packages/vue/src/index";
import {
calendarRangeBarrier,
convertCalendarRange,
orderedCalendarRange,
type CalendarRangeModel,
} from "../packages/vue/src/components/date/range-selection";
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();
});
function fixture(attrs = "", setup = () => ({}), children = "") {
const w = mount(
defineComponent({
components: {
Range,
...(Object.fromEntries(
Object.entries(library).filter(([name]) =>
name.startsWith("Calendar"),
),
) as Record<string, Component>),
},
setup: () => ({ initial, ...setup() }),
template: `<Range aria-label="Trip dates" :default-focused-value="initial" ${attrs}>${children}</Range>`,
}),
{ attachTo: document.body },
);
wrappers.push(w);
return w;
}
const cell = (w: ReturnType<typeof mount>, day: number, month = 2) =>
w.get<HTMLElement>(
`[data-slot="range-calendar-cell"][data-date="2024-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}"]:not([data-outside-month])`,
);
const changes = (w: ReturnType<typeof mount>) =>
(w.getComponent(Range).emitted("change") ?? []).map(
([value]) => value as CalendarRangeModel,
);
const values = (w: ReturnType<typeof mount>) =>
changes(w).map((v) => v && [v.start.toString(), v.end.toString()]);
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,
other = {},
) {
cell(w, day).element.focus();
await cell(w, day).trigger("keydown", { key, code: key, ...other });
await flushPromises();
}
async function pointer(
w: ReturnType<typeof mount>,
day: number,
type: string,
other: { click?: boolean; [key: string]: unknown } = {},
) {
const event = new Event(type, { bubbles: true, cancelable: true });
Object.assign(event, {
pointerId: 1,
pointerType: "mouse",
button: 0,
isPrimary: true,
...other,
});
cell(w, day).element.dispatchEvent(event);
if (other.click)
cell(w, day).element.dispatchEvent(
new MouseEvent("click", { bubbles: true, cancelable: true, detail: 1 }),
);
await flushPromises();
return event;
}
const gridChildren =
'<CalendarGrid><CalendarGridHeader/><CalendarGridBody v-slot="{date}"><CalendarCell :date="date"/></CalendarGridBody></CalendarGrid>';
describe("private range selection and shared calendar integration", () => {
it("keeps partial drafts out of the accepted value and orders reverse/same-day selection", async () => {
const w = fixture();
await click(w, 15);
expect(changes(w)).toHaveLength(0);
expect(cell(w, 15).attributes("data-selection-start")).toBe("true");
await click(w, 10);
expect(values(w)).toEqual([["2024-02-10", "2024-02-15"]]);
expect(cell(w, 12).attributes("data-selected")).toBe("true");
expect(cell(w, 10).attributes("data-selection-start")).toBe("true");
expect(cell(w, 15).attributes("data-selection-end")).toBe("true");
await click(w, 20);
await click(w, 20);
expect(values(w)[1]).toEqual(["2024-02-20", "2024-02-20"]);
expect(w.find("input[name]").exists()).toBe(false);
expect(w.get("table").attributes("aria-multiselectable")).toBe("true");
});
it("reverts controlled rejection and retries the same complete proposal", async () => {
const value = { start: initial, end: initial.add({ days: 2 }) };
const w = fixture(':model-value="value"', () => ({ value }));
for (let n = 0; n < 2; n++) {
await click(w, 15);
await click(w, 17);
}
expect(values(w)).toEqual([
["2024-02-15", "2024-02-17"],
["2024-02-15", "2024-02-17"],
]);
expect(cell(w, 10).attributes("data-selected")).toBe("true");
expect(cell(w, 15).attributes("data-selected")).toBeUndefined();
expect(value.start.day).toBe(10);
});
it("gives explicit modelValue null priority over value/defaultValue", async () => {
const value = { start: initial, end: initial.add({ days: 2 }) };
const w = fixture(
':model-value="null" :value="value" :default-value="value"',
() => ({ value }),
);
expect(
w.find('[data-slot="range-calendar-cell"][data-selected]').exists(),
).toBe(false);
await click(w, 15);
await click(w, 17);
expect(
w.find('[data-slot="range-calendar-cell"][data-selected]').exists(),
).toBe(false);
expect(changes(w)).toHaveLength(1);
});
it("captures defaults once, copies endpoints and keeps separate endpoint precision/zone", async () => {
const start = new CalendarDateTime(2024, 2, 10, 8, 9, 45, 123);
const end = parseZonedDateTime(
"2024-02-12T20:30:15.456-08:00[America/Los_Angeles]",
);
const value = shallowRef<NonNullable<CalendarRangeModel>>({ start, end });
const w = fixture(':default-value="value"', () => ({ value }));
value.value = { start: initial, end: initial };
await flushPromises();
await click(w, 15);
await click(w, 17);
const v = changes(w)[0]!;
expect(v.start.toString()).toBe(start.set({ day: 15 }).toString());
expect(v.end.toString()).toBe(end.set({ day: 17 }).toString());
expect(start.day).toBe(10);
expect(end.day).toBe(12);
});
it("cancels a draft on external selection replacement without synthesizing change", async () => {
const value = shallowRef<CalendarRangeModel>(null);
const w = fixture('v-model="value"', () => ({ value }));
await click(w, 15);
value.value = { start: initial, end: initial.add({ days: 2 }) };
await flushPromises();
expect(cell(w, 15).attributes("data-selected")).toBeUndefined();
expect(cell(w, 10).attributes("data-selection-start")).toBe("true");
expect(changes(w)).toHaveLength(0);
await click(w, 20);
expect(changes(w)).toHaveLength(0);
});
it("advances keyboard focus, previews accepted focus, commits once and cancels drafts with Escape", async () => {
const w = fixture();
await key(w, 10, "Enter");
expect(changes(w)).toHaveLength(0);
expect(document.activeElement).toBe(cell(w, 11).element);
await key(w, 11, "ArrowRight");
expect(cell(w, 12).attributes("data-selection-end")).toBe("true");
await key(w, 12, "Enter");
expect(values(w)).toEqual([["2024-02-10", "2024-02-12"]]);
expect(document.activeElement).toBe(cell(w, 12).element);
await key(w, 15, " ");
await key(w, 16, "Escape");
expect(cell(w, 10).attributes("data-selection-start")).toBe("true");
await key(w, 16, "Enter", { repeat: true });
expect(changes(w)).toHaveLength(1);
});
it("does not turn rejected controlled focus into a ghost preview", async () => {
const w = fixture(':focused-value="initial"');
await key(w, 10, "Enter");
expect(document.activeElement).toBe(cell(w, 10).element);
expect(cell(w, 11).attributes("data-selected")).toBeUndefined();
await key(w, 10, "ArrowRight");
expect(cell(w, 11).attributes("data-selected")).toBeUndefined();
await key(w, 10, "Enter");
expect(values(w)).toEqual([["2024-02-10", "2024-02-10"]]);
});
it("keeps unavailable dates focusable, blocks crossing barriers and terminates keyboard navigation", async () => {
const w = fixture(':is-date-unavailable="d=>d.day===12"');
await click(w, 10);
expect(cell(w, 12).attributes("disabled")).toBeUndefined();
expect(cell(w, 13).attributes("disabled")).toBeDefined();
await key(w, 11, "ArrowRight");
expect(document.activeElement).toBe(cell(w, 12).element);
await key(w, 12, "ArrowRight");
expect(document.activeElement).toBe(cell(w, 11).element);
await click(w, 13);
expect(changes(w)).toHaveLength(0);
await click(w, 11);
expect(values(w)).toEqual([["2024-02-10", "2024-02-11"]]);
});
it("allows unavailable interiors but never endpoints, and never crosses disabled interiors", async () => {
const w = fixture(
'allows-non-contiguous-ranges :is-date-unavailable="d=>d.day===12"',
);
await click(w, 10);
await click(w, 12);
expect(changes(w)).toHaveLength(0);
await click(w, 15);
expect(values(w)).toEqual([["2024-02-10", "2024-02-15"]]);
expect(cell(w, 12).attributes("data-selected")).toBeUndefined();
const blocked = fixture(
'allows-non-contiguous-ranges :is-date-disabled="d=>d.day===12"',
);
await click(blocked, 10);
await click(blocked, 15);
expect(changes(blocked)).toHaveLength(0);
});
it("passes a copied anchor and reacts to captured reactive availability rules", async () => {
const max = shallowRef(7);
const seen: (string | null)[] = [];
const unavailable = (date: DateValue, anchor: CalendarDate | null) => {
seen.push(anchor?.toString() ?? null);
return !!anchor && Math.abs(date.compare(anchor)) > max.value;
};
const w = fixture(':is-date-unavailable="unavailable"', () => ({
unavailable,
}));
await click(w, 10);
expect(cell(w, 15).attributes("aria-disabled")).toBeUndefined();
max.value = 2;
await flushPromises();
expect(cell(w, 15).attributes("aria-disabled")).toBe("true");
expect(seen).toContain("2024-02-10");
await click(w, 12);
expect(values(w)).toEqual([["2024-02-10", "2024-02-12"]]);
});
it("honors readonly, inherited Fieldset disabled, min/max and invalid accepted ranges", async () => {
const ro = fixture("is-read-only");
await key(ro, 10, "ArrowRight");
expect(document.activeElement).toBe(cell(ro, 11).element);
await click(ro, 11);
expect(changes(ro)).toHaveLength(0);
const w = fixture(
':min-value="initial" :max-value="initial.add({days:5})" :model-value="{start:initial,end:initial.add({days:10})}"',
);
expect(cell(w, 9).attributes("disabled")).toBeDefined();
expect(cell(w, 16).attributes("disabled")).toBeDefined();
expect(
w.get('[data-slot="range-calendar"]').attributes("aria-invalid"),
).toBe("true");
const inherited = mount(
defineComponent({
components: { Fieldset: library.Fieldset, Range },
setup: () => ({ initial }),
template:
'<Fieldset disabled><Range :default-focused-value="initial"/></Fieldset>',
}),
{ attachTo: document.body },
);
wrappers.push(inherited);
expect(cell(inherited, 10).attributes("disabled")).toBeDefined();
});
it("honors actual consumer click, keyboard and pointer cancellation", async () => {
const w = fixture(
"",
() => ({}),
gridChildren.replace(
'<CalendarCell :date="date"/>',
'<CalendarCell :date="date" @click.prevent @keydown.prevent @pointerdown.prevent/>',
),
);
await click(w, 10);
await key(w, 10, "Enter");
await pointer(w, 10, "pointerdown");
await pointer(w, 15, "pointerenter");
await pointer(w, 15, "pointerup");
expect(
w.find('[data-slot="range-calendar-cell"][data-selected]').exists(),
).toBe(false);
expect(changes(w)).toHaveLength(0);
});
it("commits mouse drag once and suppresses its compatibility click", async () => {
const w = fixture();
await pointer(w, 10, "pointerdown");
await pointer(w, 15, "pointerenter");
expect(cell(w, 13).attributes("data-selected")).toBe("true");
await pointer(w, 15, "pointerup", { click: true });
expect(values(w)).toEqual([["2024-02-10", "2024-02-15"]]);
expect(cell(w, 10).attributes("data-selection-start")).toBe("true");
});
it("supports native two-click gestures without emitting a one-day range on first release", async () => {
const w = fixture();
for (const d of [10, 15]) {
await pointer(w, d, "pointerdown");
await pointer(w, d, "pointerup", { click: true });
}
expect(values(w)).toEqual([["2024-02-10", "2024-02-15"]]);
});
it("adjusts a selected boundary by dragging, but a stationary boundary click starts a new range", async () => {
const w = fixture(
':default-value="{start:initial,end:initial.add({days:5})}"',
);
await pointer(w, 10, "pointerdown");
await pointer(w, 8, "pointerenter");
await pointer(w, 8, "pointerup");
expect(values(w)).toEqual([["2024-02-08", "2024-02-15"]]);
await pointer(w, 8, "pointerdown");
await pointer(w, 8, "pointerup", { click: true });
await click(w, 9);
expect(values(w)[1]).toEqual(["2024-02-08", "2024-02-09"]);
});
it("rolls back cancelled gestures, outside releases and right/non-primary pointers", async () => {
const w = fixture(
':default-value="{start:initial,end:initial.add({days:2})}"',
);
await pointer(w, 15, "pointerdown");
await pointer(w, 17, "pointerenter");
const cancel = new Event("pointercancel", { bubbles: true });
Object.assign(cancel, { pointerId: 1 });
document.dispatchEvent(cancel);
await flushPromises();
expect(cell(w, 10).attributes("data-selection-start")).toBe("true");
await pointer(w, 15, "pointerdown");
const up = new Event("pointerup", { bubbles: true });
Object.assign(up, { pointerId: 1 });
document.body.dispatchEvent(up);
await new Promise((resolve) => setTimeout(resolve, 1));
await flushPromises();
expect(cell(w, 15).attributes("data-selected")).toBeUndefined();
await pointer(w, 15, "pointerdown", { button: 2 });
await pointer(w, 17, "pointerenter");
await pointer(w, 17, "pointerup");
expect(changes(w)).toHaveLength(0);
});
it("cleans gesture listeners and draft state when disabled/opening year picker/unmounting", async () => {
const disabled = shallowRef(false);
const w = fixture(':is-disabled="disabled"', () => ({ disabled }));
await click(w, 10);
disabled.value = true;
await flushPromises();
disabled.value = false;
await flushPromises();
await click(w, 15);
expect(changes(w)).toHaveLength(0);
await w.get('[data-slot="calendar-year-picker-trigger"]').trigger("click");
await flushPromises();
expect(
w
.get('[data-slot="calendar-year-picker-grid"]')
.attributes("aria-hidden"),
).toBe("false");
const fresh = fixture();
const remove = vi.spyOn(document, "removeEventListener");
await pointer(fresh, 10, "pointerdown");
fresh.unmount();
expect(remove.mock.calls.some(([name]) => name === "pointerup")).toBe(true);
expect(remove.mock.calls.some(([name]) => name === "pointercancel")).toBe(
true,
);
});
it("keeps touch scroll free of pointer-down drafts and permits click-based touch selection", async () => {
const w = fixture();
await pointer(w, 10, "pointerdown", { pointerType: "touch" });
expect(
w.find('[data-slot="range-calendar-cell"][data-selected]').exists(),
).toBe(false);
await click(w, 10);
await click(w, 15);
expect(changes(w)).toHaveLength(1);
});
it("reuses week/day/RTL and year geometry contracts without another view owner", async () => {
const w = fixture(':visible-duration="{weeks:2}" dir="rtl"');
expect(w.findAll("tbody tr")).toHaveLength(2);
await key(w, 10, "ArrowLeft");
expect(document.activeElement).toBe(cell(w, 11).element);
const d = fixture(':visible-duration="{days:10}"');
expect(
d.findAll('[data-slot="range-calendar-cell"]:not([disabled])'),
).toHaveLength(10);
});
it("preserves public calendar endpoints while locale affects only the view", () => {
const start = toCalendar(initial, new PersianCalendar()),
end = toCalendar(initial.add({ days: 2 }), new PersianCalendar());
const range = convertCalendarRange(
orderedCalendarRange(initial.add({ days: 3 }), initial.add({ days: 5 })),
{ start, end },
);
expect(range.start.calendar.identifier).toBe("persian");
expect(range.end.calendar.identifier).toBe("persian");
const empty = convertCalendarRange(orderedCalendarRange(start, end), null);
expect(empty.start.calendar.identifier).toBe("gregory");
expect(
calendarRangeBarrier(
initial,
initial.add({ days: 5 }),
() => false,
(d) => d.day === 12,
)?.day,
).toBe(12);
});
it("reverts the pointer draft when the actual compatibility click is cancelled", async () => {
const w = fixture(
"",
() => ({}),
gridChildren.replace(
'<CalendarCell :date="date"/>',
'<CalendarCell :date="date" @click.prevent/>',
),
);
await pointer(w, 10, "pointerdown");
await pointer(w, 10, "pointerup", { click: true });
expect(
w.find('[data-slot="range-calendar-cell"][data-selected]').exists(),
).toBe(false);
expect(changes(w)).toHaveLength(0);
});
it("cancels an anchor invalidated by new bounds or a captured rule", async () => {
const min = shallowRef(initial),
blocked = shallowRef(false);
const w = fixture(
':min-value="min" :is-date-unavailable="d=>blocked && d.day===10"',
() => ({ min, blocked }),
);
await click(w, 10);
min.value = initial.add({ days: 1 });
await flushPromises();
await click(w, 15);
expect(changes(w)).toHaveLength(0);
await key(w, 15, "Escape");
min.value = initial;
await flushPromises();
await click(w, 10);
blocked.value = true;
await flushPromises();
await click(w, 15);
expect(changes(w)).toHaveLength(0);
});
it("keeps separate grids in a multi-month range and skips duplicate filler dates", async () => {
const w = fixture(
':visible-duration="{months:2}" selection-alignment="start"',
() => ({}),
'<CalendarGrid><CalendarGridHeader/><CalendarGridBody/></CalendarGrid><CalendarGrid :offset="{months:1}"><CalendarGridHeader/><CalendarGridBody/></CalendarGrid>',
);
await click(w, 28);
await cell(w, 2, 3).trigger("click");
await flushPromises();
expect(values(w)).toEqual([["2024-02-28", "2024-03-02"]]);
expect(w.findAll('[data-date="2024-03-01"]:not([disabled])')).toHaveLength(
1,
);
expect(
w.findAll('[data-slot="range-calendar-cell"][tabindex="0"]'),
).toHaveLength(1);
});
it("keeps a rejected drag at the parent's value and permits an identical repeated drag", async () => {
const w = fixture(
':model-value="{start:initial,end:initial.add({days:5})}"',
);
for (let n = 0; n < 2; n++) {
await pointer(w, 10, "pointerdown");
await pointer(w, 8, "pointerenter");
await pointer(w, 8, "pointerup", { click: true });
}
expect(values(w)).toEqual([
["2024-02-08", "2024-02-15"],
["2024-02-08", "2024-02-15"],
]);
expect(cell(w, 10).attributes("data-selection-start")).toBe("true");
expect(cell(w, 8).attributes("data-selected")).toBeUndefined();
});
it("ignores foreign pointer releases and rolls back a consumer-cancelled pointerup", async () => {
const w = fixture(
"",
() => ({}),
gridChildren.replace(
'<CalendarCell :date="date"/>',
'<CalendarCell :date="date" @pointerup.prevent/>',
),
);
await pointer(w, 10, "pointerdown");
await pointer(w, 15, "pointerenter");
await pointer(w, 15, "pointerup", { pointerId: 2 });
expect(changes(w)).toHaveLength(0);
await pointer(w, 15, "pointerup");
expect(changes(w)).toHaveLength(0);
expect(
w.find('[data-slot="range-calendar-cell"][data-selected]').exists(),
).toBe(false);
});
it("does not navigate or commit when a mouse drag crosses a disabled outside-month filler", async () => {
const w = fixture();
await pointer(w, 28, "pointerdown");
const outside = w.get(
'[data-slot="range-calendar-cell"][data-date="2024-03-01"][data-outside-month]',
);
for (const type of ["pointerenter", "pointerup"]) {
const event = new Event(type, { bubbles: true, cancelable: true });
Object.assign(event, { pointerId: 1, pointerType: "mouse", button: 0 });
outside.element.dispatchEvent(event);
}
await new Promise((resolve) => setTimeout(resolve, 1));
await flushPromises();
expect(
w.get('[data-slot="calendar-year-picker-trigger"]').text(),
).toContain("February");
expect(changes(w)).toHaveLength(0);
expect(cell(w, 28).attributes("data-selected")).toBeUndefined();
});
it("aligns long accepted ranges at the start and keeps an explicit alignment override", () => {
const children =
"<CalendarHeader><CalendarHeading/></CalendarHeader><CalendarGrid><CalendarGridHeader/><CalendarGridBody/></CalendarGrid>";
const props =
':default-value="{start:initial,end:initial.add({months:4})}" :visible-duration="{months:3}"';
const w = fixture(props, () => ({}), children);
expect(
w.get('[data-slot="range-calendar-heading"]').text().replace(/\s+/g, " "),
).toBe("February – April 2024");
const explicit = fixture(
props + ' selection-alignment="center"',
() => ({}),
children,
);
expect(
explicit
.get('[data-slot="range-calendar-heading"]')
.text()
.replace(/\s+/g, " "),
).toBe("January – March 2024");
});
});