feat: migrate public DatePicker with shared field and calendar owners

This commit is contained in:
maoyingjie
2026-10-26 22:01:27 +08:00
parent 166a075390
commit 9a69f92233
37 changed files with 3568 additions and 378 deletions
+120
View File
@@ -0,0 +1,120 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { readFileSync } from "node:fs";
const demos = import.meta.glob("../apps/docs/demos/date-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.unstubAllGlobals();
document.body.innerHTML = "";
});
describe("DatePicker documentation", () => {
it("includes every pinned preview and uses the displayed SFC as its implementation", () => {
const md = readFileSync("apps/docs/components/date-picker.md", "utf8");
expect(
[...md.matchAll(/<ComponentPreview name="date-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 date 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-picker"]').exists()).toBe(true);
expect(w.find('[data-slot="date-input-group-segment"]').exists()).toBe(
true,
);
expect(w.find('[data-slot="date-picker-trigger"]').exists()).toBe(true);
expect(w.find('[data-slot="date-picker-value"]').exists()).toBe(true);
}
expect(warnings).toEqual([]);
});
it("the controlled example updates and clears the real date", async () => {
const component = demos["../apps/docs/demos/date-picker-controlled.vue"];
const w = mount(component as never);
wrappers.push(w);
const value = () =>
(w.get('[data-slot="date-picker-value"]').element as HTMLInputElement)
.value;
expect(value()).toMatch(/^\d{4}-\d{2}-\d{2}$/);
const buttons = w.findAll("button");
await buttons.find((button) => button.text() === "清空")!.trigger("click");
await flushPromises();
expect(value()).toBe("");
expect(w.get('[data-slot="description"]').text()).toContain("(空)");
await w
.findAll("button")
.find((button) => button.text() === "设为今天")!
.trigger("click");
await flushPromises();
expect(value()).toMatch(/^\d{4}-\d{2}-\d{2}$/);
expect(w.get('[data-slot="description"]').text()).not.toContain("(空)");
});
it("format options keeps one picker value while TimeField edits its time", async () => {
const component =
demos["../apps/docs/demos/date-picker-format-options.vue"];
const w = mount(component as never, { attachTo: document.body });
wrappers.push(w);
await flushPromises();
expect(
(w.get('[data-slot="date-picker-value"]').element as HTMLInputElement)
.value,
).toContain("T08:45:00");
await w.get('[data-slot="date-picker-trigger"]').trigger("click");
await flushPromises();
const timeField = document.querySelector('[data-slot="time-field"]');
expect(timeField).not.toBeNull();
const hour = timeField!.querySelector<HTMLElement>('[data-type="hour"]')!;
expect(hour.textContent?.trim()).toBe("8");
hour.focus();
hour.dispatchEvent(
new KeyboardEvent("keydown", {
key: "ArrowUp",
bubbles: true,
cancelable: true,
}),
);
await flushPromises();
expect(
(w.get('[data-slot="date-picker-value"]').element as HTMLInputElement)
.value,
).toContain("T09:45:00");
expect(document.querySelectorAll('[name="date"]')).toHaveLength(1);
expect(document.querySelectorAll('[name="time"]')).toHaveLength(1);
});
});
+568
View File
@@ -0,0 +1,568 @@
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,
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,
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 = `<Calendar aria-label="活动日期">
<CalendarHeader>
<CalendarYearPickerTrigger>
<CalendarYearPickerTriggerHeading />
<CalendarYearPickerTriggerIndicator />
</CalendarYearPickerTrigger>
<CalendarNavButton slot="previous" />
<CalendarNavButton slot="next" />
</CalendarHeader>
<CalendarGrid>
<CalendarGridHeader v-slot="{ day }"><CalendarHeaderCell>{{ day }}</CalendarHeaderCell></CalendarGridHeader>
<CalendarGridBody v-slot="{ date }"><CalendarCell :date="date" /></CalendarGridBody>
</CalendarGrid>
<CalendarYearPickerGrid>
<CalendarYearPickerGridBody v-slot="{ year, date }"><CalendarYearPickerCell :year="year" :date="date" /></CalendarYearPickerGridBody>
</CalendarYearPickerGrid>
</Calendar>`;
const content = `<Label>日期</Label>
<DateFieldGroup>
<DateFieldInput v-slot="{ segment }"><DateFieldSegment :segment="segment" /></DateFieldInput>
<DateFieldSuffix>
<DatePickerTrigger aria-label="打开日历"><DatePickerTriggerIndicator /></DatePickerTrigger>
</DateFieldSuffix>
</DateFieldGroup>
<FieldError />
<DatePickerPopover>${calendar}</DatePickerPopover>`;
const initial = new CalendarDate(2024, 2, 10);
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.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<typeof mount>) =>
w.get('[data-slot="date-picker-value"]').element as HTMLInputElement;
const trigger = '[data-slot="date-picker-trigger"]';
async function open(w: ReturnType<typeof mount>) {
await w.get(trigger).trigger("click");
await flushPromises();
}
async function pick(w: ReturnType<typeof mount>, date: string) {
const cell = document.querySelector<HTMLElement>(
`[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(
`<form><DatePicker name="date" :default-value="initial">${content}</DatePicker></form>`,
() => ({ 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(
`<form><DatePicker name="date" :default-value="initial">${content}</DatePicker></form>`,
() => ({ 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<HTMLElement>(
'[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(
`<DatePicker :open="openModel" :default-value="initial" @update:open="updates.push($event)">${content}</DatePicker>`,
() => ({ 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(
`<DatePicker :default-value="initial"><DateFieldGroup><DateFieldInput v-slot="{ segment }"><DateFieldSegment :segment="segment" /></DateFieldInput></DateFieldGroup><DatePickerTrigger @click="cancel && $event.preventDefault()">打开</DatePickerTrigger><DatePickerPopover>${calendar}</DatePickerPopover></DatePicker>`,
() => ({ 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(
`<DatePicker :default-value="initial" locale="zh-CN" dir="rtl" first-day-of-week="wed" page-behavior="single">${content}</DatePicker>`,
() => ({ 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(
`<DatePicker :default-value="initial">${content}</DatePicker>`,
() => ({ 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<CalendarDate | null>(initial),
accept = ref(false);
const w = view(
`<form><DatePicker :model-value="value" name="date" @update:model-value="accept && (value = $event)">${content}</DatePicker></form>`,
() => ({ 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<CalendarDate | null>(initial),
accept = ref(false);
const w = view(
`<DatePicker :model-value="value" @update:model-value="accept && (value = $event)">${content}</DatePicker>`,
() => ({ 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(
`<DatePicker :default-value="initial" :should-close-on-select="false">${content}</DatePicker>`,
() => ({ 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(
`<DatePicker :default-value="zoned">${content}</DatePicker>`,
() => ({ 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(
`<DatePicker :default-value="dateTime">${content}</DatePicker>`,
() => ({ 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(
`<DatePicker :default-value="initialDateTime" granularity="second" v-slot="{ state, timeValue }"><DateFieldGroup><DateFieldInput v-slot="{ segment }"><DateFieldSegment :segment="segment" /></DateFieldInput></DateFieldGroup><button type="button" data-test="set-time" @click="state.setTimeValue(new Time(9, 8, 7))">时间</button><span data-test="time">{{ timeValue?.toString() }}</span><DatePickerTrigger>打开</DatePickerTrigger><DatePickerPopover>${calendar}</DatePickerPopover></DatePicker>`,
() => ({ 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(
`<form><DatePicker name="date" :placeholder-value="placeholder" granularity="second" v-slot="{ state }"><DateFieldGroup><DateFieldInput v-slot="{ segment }"><DateFieldSegment :segment="segment" /></DateFieldInput></DateFieldGroup><button type="button" data-test="set-time" @click="state.setTimeValue(new Time(9, 8, 7))">时间</button><DatePickerTrigger>打开</DatePickerTrigger><DatePickerPopover>${calendar}</DatePickerPopover></DatePicker></form>`,
() => ({ 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(
`<form><DatePicker name="date" is-required :placeholder-value="initial">${content}</DatePicker></form>`,
() => ({ 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(
`<DatePicker :default-value="initial" validation-behavior="aria" :min-value="initial.add({days:1})" :is-date-unavailable="(value) => value.day === 20">${content}</DatePicker>`,
() => ({ 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<HTMLElement>(
'[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(
`<form><DatePicker name="date" is-disabled :default-value="initial">${content}</DatePicker></form>`,
() => ({ 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(
`<form><DatePicker name="date" is-read-only :default-value="initial">${content}</DatePicker></form>`,
() => ({ 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<DateValue | null>(null);
const w = view(
`<DatePicker :default-value="initial"><DateFieldGroup><DateFieldInput v-slot="{ segment }"><DateFieldSegment :segment="segment" /></DateFieldInput></DateFieldGroup><DatePickerTrigger>打开</DatePickerTrigger><DatePickerPopover><Calendar v-model="calendarValue" aria-label="独立日历"><CalendarHeader><CalendarNavButton slot="previous" /><CalendarNavButton slot="next" /></CalendarHeader><CalendarGrid><CalendarGridHeader v-slot="{ day }"><CalendarHeaderCell>{{ day }}</CalendarHeaderCell></CalendarGridHeader><CalendarGridBody v-slot="{ date }"><CalendarCell :date="date" /></CalendarGridBody></CalendarGrid></Calendar></DatePickerPopover></DatePicker>`,
() => ({ 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();
});
});
+6
View File
@@ -54,6 +54,12 @@ for (const id of process.argv.slice(2)) {
.includes("hv-time-field--full-width"),
);
}
if (id === "date-picker") {
assert(lib.DatePicker === lib.DatePickerRoot);
assert(lib.datePickerVariants().base() === "hv-date-picker");
assert(lib.datePickerVariants().trigger() === "hv-date-picker__trigger");
assert(lib.datePickerVariants().popover() === "hv-date-picker__popover");
}
if (id === "slider")
assert(lib.sliderVariants().thumb().includes("hv-slider__thumb"));
if (id === "select")
+24
View File
@@ -198,6 +198,30 @@
"hv-date-input-group--secondary"
]
},
"date-picker": {
"exports": [
"DatePicker",
"DatePickerRoot",
"DatePickerTrigger",
"DatePickerTriggerIndicator",
"DatePickerPopover",
"datePickerVariants",
"DateFieldGroup",
"DateFieldInput",
"DateFieldSegment",
"DateFieldSuffix",
"Calendar",
"CalendarCell"
],
"css": [
".hv-date-picker",
".hv-date-picker__trigger",
".hv-date-picker__trigger-indicator",
".hv-date-picker__popover",
"--reka-popper-transform-origin",
"data-exiting"
]
},
"list-box": {
"exports": [
"ListBox",
+166
View File
@@ -0,0 +1,166 @@
import { h } from "vue";
import {
CalendarDate,
CalendarDateTime,
parseZonedDateTime,
Time,
type DateValue,
} from "@internationalized/date";
import {
DatePicker,
DatePickerRoot,
DatePickerTrigger,
DatePickerTriggerIndicator,
DatePickerPopover,
datePickerVariants,
type DatePickerProps,
type DatePickerTriggerProps,
type DatePickerPopoverProps,
type DatePickerRenderProps,
type DatePickerState,
type DatePickerTimeValue,
} from "@heroui-vue/components";
const day = new CalendarDate(2024, 2, 10);
const dateTime = new CalendarDateTime(2024, 2, 10, 9, 30);
const zoned = parseZonedDateTime("2024-01-01T09:30+08:00[Asia/Shanghai]");
const time: DatePickerTimeValue = new Time(9, 30);
const values: DatePickerProps[] = [
{
modelValue: day,
value: null,
defaultValue: dateTime,
placeholderValue: zoned,
minValue: day,
maxValue: day.add({ years: 1 }),
isDateUnavailable: (value) => value.day === 20,
granularity: "second",
hourCycle: 24,
hideTimeZone: true,
shouldForceLeadingZeros: true,
locale: "zh-CN",
firstDayOfWeek: "mon",
pageBehavior: "single",
dir: "rtl",
name: "date",
form: "appointment",
isDisabled: false,
isReadOnly: false,
isRequired: true,
isInvalid: false,
shouldCloseOnSelect: false,
validate: (value) => (value ? null : "Missing"),
"onUpdate:modelValue": (value) => {
const accepted: DateValue | null = value;
void accepted;
},
onChange: (value) => {
const accepted: DateValue | null = value;
void accepted;
},
"onUpdate:open": (value) => {
const open: boolean = value;
void open;
},
onOpenChange: (value) => {
const open: boolean = value;
void open;
},
},
];
const trigger: DatePickerTriggerProps = {
as: "button",
asChild: false,
isDisabled: true,
};
const indicator = { as: "span" };
const popover: DatePickerPopoverProps = {
placement: "bottom",
offset: 12,
crossOffset: 4,
shouldFlip: true,
containerPadding: 16,
isDismissable: false,
isKeyboardDismissDisabled: true,
};
const state: DatePickerState = {
value: day,
timeValue: time,
setValue: (value) => {
const next: DateValue | null = value;
void next;
},
setTimeValue: (value) => {
const next: DatePickerTimeValue | null = value;
void next;
},
};
const rendered: DatePickerRenderProps = {
value: day,
isOpen: true,
isDisabled: false,
isReadOnly: false,
isRequired: false,
isInvalid: false,
isFocusWithin: false,
isFocused: false,
isFocusVisible: false,
validationErrors: [],
timeValue: time,
state,
open: () => {},
close: () => {},
toggle: () => {},
};
// @ts-expect-error a date model is not a string
const string: DatePickerProps = { modelValue: "2024-02-10" };
// @ts-expect-error visible granularity has a fixed set
const wrongGranularity: DatePickerProps = { granularity: "week" };
// @ts-expect-error page behavior has a fixed set
const wrongPage: DatePickerProps = { pageBehavior: "month" };
// @ts-expect-error hour cycles are 12 or 24
const wrongCycle: DatePickerProps = { hourCycle: 23 };
// @ts-expect-error open state is boolean
const wrongOpen: DatePickerProps = { open: "yes" };
const wrongChange: DatePickerProps = {
// @ts-expect-error no React PressEvent shape
onChange: (event: { key: string }) => event,
};
// @ts-expect-error placement is a known logical value
const wrongPlacement: DatePickerPopoverProps = { placement: "diagonal" };
// @ts-expect-error a DatePicker is not a range model
const range: DatePickerProps = { modelValue: [day] };
type Slot = Parameters<
NonNullable<InstanceType<typeof DatePicker>["$slots"]["default"]>
>[0];
const slot: Slot = rendered;
const slotTime: DatePickerTimeValue | null = slot.state.timeValue;
// @ts-expect-error slot time is not a number
const wrongSlotTime: number = slot.timeValue;
void [
DatePicker,
DatePickerRoot,
DatePickerTrigger,
DatePickerTriggerIndicator,
DatePickerPopover,
datePickerVariants().base(),
datePickerVariants().trigger(),
datePickerVariants().popover(),
values,
trigger,
indicator,
popover,
state,
rendered,
string,
wrongGranularity,
wrongCycle,
wrongPage,
wrongOpen,
wrongChange,
wrongPlacement,
range,
slotTime,
wrongSlotTime,
];
h(DatePickerPopover, popover);