feat: migrate RangeCalendar public components and demos

This commit is contained in:
maoyingjie
2026-10-26 21:25:25 +08:00
parent ebe81f28c7
commit 07f6aeadb6
43 changed files with 2420 additions and 53 deletions
+4
View File
@@ -40,6 +40,10 @@ for (const id of process.argv.slice(2)) {
.includes("hv-list-box-item__indicator"),
);
}
if (id === "range-calendar") {
assert(lib.RangeCalendar === lib.RangeCalendarRoot);
assert(lib.rangeCalendarVariants().cell() === "hv-range-calendar__cell");
}
if (id === "time-field") {
assert(lib.TimeField === lib.TimeFieldRoot);
assert(lib.TimeFieldGroup === lib.DateInputGroup);
+24
View File
@@ -373,5 +373,29 @@
".hv-date-input-group",
".hv-date-input-group__segment"
]
},
"range-calendar": {
"exports": [
"RangeCalendar",
"RangeCalendarRoot",
"RangeCalendarHeader",
"RangeCalendarHeading",
"RangeCalendarNavButton",
"RangeCalendarGrid",
"RangeCalendarGridHeader",
"RangeCalendarGridBody",
"RangeCalendarHeaderCell",
"RangeCalendarCell",
"RangeCalendarCellIndicator",
"rangeCalendarVariants"
],
"css": [
".hv-range-calendar__cell",
".hv-range-calendar__cell-button",
".hv-range-calendar--week-view",
".hv-range-calendar--day-view",
"data-selection-start",
"data-selection-end"
]
}
}
+137
View File
@@ -0,0 +1,137 @@
import { h } from "vue";
import {
CalendarDate,
CalendarDateTime,
type DateValue,
} from "@internationalized/date";
import {
RangeCalendar,
RangeCalendarRoot,
RangeCalendarCell,
RangeCalendarGrid,
CalendarYearPickerCell,
rangeCalendarVariants,
type RangeCalendarProps,
type RangeCalendarRootProps,
type RangeCalendarCellProps,
type RangeCalendarGridProps,
type RangeCalendarCellRenderProps,
type CalendarDateRange,
type CalendarRangeModel,
type RangeCalendarVariants,
} from "@heroui-vue/components";
const day = new CalendarDate(2024, 2, 10);
const range: CalendarDateRange<CalendarDate> = {
start: day,
end: day.add({ days: 2 }),
};
const mixed: CalendarDateRange = {
start: new CalendarDateTime(2024, 2, 10, 9),
end: day,
};
const props: RangeCalendarProps = {
modelValue: range,
defaultValue: null,
focusedValue: day,
allowsNonContiguousRanges: true,
firstDayOfWeek: "mon",
visibleDuration: { weeks: 2 },
isDateUnavailable: (date, anchor) => {
const value: DateValue = date;
const original: CalendarDate | null = anchor;
// @ts-expect-error anchor has calendar semantics, not a JS Date
const invalid: Date | null = anchor;
void [value, original, invalid];
return false;
},
"onUpdate:modelValue": (value) => {
const model: CalendarRangeModel = value;
// @ts-expect-error proposal is a range or null
const invalid: string = value;
void [model, invalid];
},
"onUpdate:focusedValue": (date) => {
const value: DateValue = date;
void value;
},
"onUpdate:isYearPickerOpen": (open) => {
const value: boolean = open;
void value;
},
};
const root: RangeCalendarRootProps = props;
const cell: RangeCalendarCellProps = { date: day };
const grid: RangeCalendarGridProps = {
offset: { months: 1 },
weekdayStyle: "long",
};
// @ts-expect-error a scalar DateValue is not a range
const scalar: RangeCalendarProps = { modelValue: day };
// @ts-expect-error ranges require both endpoints
const partial: RangeCalendarProps = { modelValue: { start: day } };
// @ts-expect-error a range is not an array
const array: RangeCalendarProps = { modelValue: [day, day] };
// @ts-expect-error dates must retain DateValue semantics
const native: RangeCalendarCellProps = { date: new Date() };
// @ts-expect-error no extra selection mode
const mode: RangeCalendarProps = { selectionMode: "multiple" };
const duration: RangeCalendarProps = {
// @ts-expect-error visible duration takes exactly one unit
visibleDuration: { months: 1, weeks: 1 },
};
type ActualRoot = InstanceType<typeof RangeCalendar>["$props"];
// @ts-expect-error actual component rejects partial values too
const actual: ActualRoot = { modelValue: { end: day } };
type RootSlot = Parameters<
NonNullable<InstanceType<typeof RangeCalendar>["$slots"]["default"]>
>[0];
const snapshot = {} as RootSlot;
const value: CalendarRangeModel = snapshot.value;
const anchor: CalendarDate | null = snapshot.anchorDate;
const focused: DateValue = snapshot.focusedValue;
// @ts-expect-error slot value is not any or a scalar
const badValue: DateValue = snapshot.value;
type CellSlot = Parameters<
NonNullable<InstanceType<typeof RangeCalendarCell>["$slots"]["default"]>
>[0];
const state = {} as CellSlot;
const renderProps: RangeCalendarCellRenderProps = state;
const start: boolean = state.isSelectionStart;
// @ts-expect-error cell states remain typed
const badStart: string = state.isSelectionStart;
const variants: RangeCalendarVariants = {};
const classes: string = rangeCalendarVariants(variants).cell();
h(RangeCalendarRoot, props);
h(RangeCalendarGrid, grid);
h(CalendarYearPickerCell, { year: 2024 });
void [
range,
mixed,
root,
cell,
scalar,
partial,
array,
native,
mode,
duration,
actual,
value,
anchor,
focused,
badValue,
renderProps,
start,
badStart,
classes,
];
const instance = {} as InstanceType<typeof RangeCalendar>;
instance.focus();
const element: HTMLElement | undefined = instance.element;
const cellInstance = {} as InstanceType<typeof RangeCalendarCell>;
cellInstance.focus();
const button: HTMLButtonElement | undefined = cellInstance.element;
// @ts-expect-error a button ref is not an input
const input: HTMLInputElement | undefined = cellInstance.element;
void [element, button, input];
+150
View File
@@ -0,0 +1,150 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, h, type Component } from "vue";
import { readFileSync } from "node:fs";
const demos = import.meta.glob("../apps/docs/demos/range-calendar-*.vue", {
eager: true,
import: "default",
}) as Record<string, Component>;
const expected = [
"basic",
"disabled",
"year-picker",
"default-value",
"controlled",
"min-max-dates",
"unavailable-dates",
"anchor-unavailable-dates",
"weeks-in-month",
"week-view",
"day-view",
"allows-non-contiguous-ranges",
"read-only",
"invalid",
"focused-value",
"with-indicators",
"booking-calendar",
"multiple-months",
"international-calendar",
"custom-styles",
];
const wrappers: ReturnType<typeof mount>[] = [];
afterEach(() => {
wrappers.splice(0).forEach((w) => w.unmount());
document.body.innerHTML = "";
vi.restoreAllMocks();
});
function demo(name: string) {
const w = mount(demos[`../apps/docs/demos/range-calendar-${name}.vue`], {
attachTo: document.body,
});
wrappers.push(w);
return w;
}
describe("RangeCalendar fixed-source documentation", () => {
it("retains all twenty previews in baseline order with public-only demo imports", () => {
const md = readFileSync("apps/docs/components/range-calendar.md", "utf8");
expect(
[...md.matchAll(/name="range-calendar-([^"]+)"/g)].map((m) => m[1]),
).toEqual(expected);
expect(Object.keys(demos)).toHaveLength(20);
for (const key of Object.keys(demos)) {
const source = readFileSync(key.replace("../", ""), "utf8");
expect(source).not.toContain("packages/vue");
expect(source).not.toContain("@heroui/react");
}
});
it("mounts all real compositions together with unique IDs and no warnings", async () => {
const warnings: string[] = [];
const warn = vi
.spyOn(console, "warn")
.mockImplementation((...args) => warnings.push(args.join(" ")));
const w = mount(
defineComponent({
render: () =>
h(
"div",
Object.entries(demos).map(([key, d]) => h(d, { key })),
),
}),
{ attachTo: document.body },
);
wrappers.push(w);
await flushPromises();
expect(w.findAll('[data-slot="range-calendar"]')).toHaveLength(20);
const ids = Array.from(document.querySelectorAll("[id]")).map((e) => e.id);
expect(new Set(ids).size).toBe(ids.length);
expect(warnings).toEqual([]);
expect(warn).not.toHaveBeenCalled();
});
it("sets a full holiday range and clears the controlled value through real actions", async () => {
const w = demo("controlled");
await w
.findAll("button")
.find((b) => b.text() === "设为节假日")!
.trigger("click");
await flushPromises();
expect(w.get('[data-slot="description"]').text()).toContain(
"2025-12-20 -> 2025-12-31",
);
expect(
w.findAll(
'[data-slot="range-calendar-cell"][data-selected]:not([data-outside-month])',
),
).toHaveLength(12);
await w
.findAll("button")
.find((b) => b.text() === "清空")!
.trigger("click");
await flushPromises();
expect(w.get('[data-slot="description"]').text()).toContain("(无)");
expect(w.find("[data-selected]").exists()).toBe(false);
});
it("changes focused month and retains exact baseline default/custom selections", async () => {
const w = demo("focused-value");
await w
.findAll("button")
.find((b) => b.text() === "跳转到圣诞节")!
.trigger("click");
await flushPromises();
expect(w.get('[data-slot="description"]').text()).toContain("2025-12-25");
const d = demo("default-value");
expect(d.get("[data-selection-start]").attributes("data-date")).toBe(
"2025-02-03",
);
expect(d.get("[data-selection-end]").attributes("data-date")).toBe(
"2025-02-12",
);
const c = demo("custom-styles");
expect(c.get("[data-selection-start]").attributes("data-date")).toBe(
"2025-02-08",
);
expect(c.get("[data-selection-end]").attributes("data-date")).toBe(
"2025-02-14",
);
expect(c.get("[data-selection-start]").classes()).toContain(
"data-[selected=true]:bg-success-soft",
);
});
it("shows two offset months, day/week layouts, indicators and the international year trigger", () => {
expect(
demo("multiple-months").findAll('table[data-slot="range-calendar-grid"]'),
).toHaveLength(2);
expect(demo("week-view").findAll("tbody tr")).toHaveLength(1);
expect(
demo("day-view").findAll(
'[data-slot="range-calendar-cell"]:not([disabled])',
),
).toHaveLength(5);
expect(
demo("with-indicators")
.find('[data-slot="range-calendar-cell-indicator"]')
.exists(),
).toBe(true);
expect(
demo("international-calendar")
.get('[data-slot="calendar-year-picker-trigger"]')
.text(),
).toMatch(/[\u0900-\u097f]/);
});
});
+330
View File
@@ -0,0 +1,330 @@
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);
});
});