feat: migrate public DateRangePicker with shared range field and calendar owners

This commit is contained in:
maoyingjie
2026-10-26 23:05:36 +08:00
parent aedfe4df78
commit ff7c4ee45a
48 changed files with 4910 additions and 59 deletions
+1 -1
View File
@@ -31,7 +31,7 @@ pnpm test:related packages/vue/src/components/combo-box/ComboBox.vue
| pnpm build:docs | 库、样式与文档站静态构建,保留文档渲染要求,不视为组件SSR支持 |
| pnpm build:playground | 浏览器验证入口生产构建 |
现有91个测试文件包含1322项客户端用例,默认全部运行;不再维护SSR排除规则或相关命令。逐像素自动对比、完整读屏矩阵、真机矩阵、Nuxt集成暂不投入。
现有97个测试文件包含1410项客户端用例,默认全部运行;不再维护SSR排除规则或相关命令。逐像素自动对比、完整读屏矩阵、真机矩阵、Nuxt集成暂不投入。
不新增普遍服务端、无document运行、ID水合稳定、Teleport服务端、Nuxt服务端适配等验收要求。NodeNext是发布类型解析模式,不代表要求SSR支持。
+303
View File
@@ -0,0 +1,303 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { readFileSync } from "node:fs";
import { getLocalTimeZone, today } from "@internationalized/date";
const demos = import.meta.glob("../apps/docs/demos/date-range-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.useRealTimers();
vi.unstubAllGlobals();
document.body.innerHTML = "";
});
function mountDemo(name: string) {
const demo = demos[`../apps/docs/demos/date-range-picker-${name}.vue`];
const w = mount(demo as never, { attachTo: document.body });
wrappers.push(w);
return w;
}
async function open(w: ReturnType<typeof mount>) {
await w.get('[data-slot="date-range-picker-trigger"]').trigger("click");
await flushPromises();
}
function cell(date: string) {
return document.querySelector<HTMLElement>(
`[data-slot="range-calendar-cell"][data-date="${date}"]:not([data-outside-month])`,
);
}
async function pick(date: string) {
const target = cell(date);
expect(target).not.toBeNull();
target!.click();
await flushPromises();
}
function input(
w: ReturnType<typeof mount>,
slot: "start" | "end",
): HTMLInputElement {
return w.get(`[data-slot="date-range-picker-${slot}-value"]`)
.element as HTMLInputElement;
}
describe("DateRangePicker documentation", () => {
it("includes every pinned preview and uses the displayed SFC as its implementation", () => {
const md = readFileSync(
"apps/docs/components/date-range-picker.md",
"utf8",
);
expect(
[
...md.matchAll(/<ComponentPreview name="date-range-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 range 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-range-picker"]').exists()).toBe(true);
expect(w.findAll('[data-slot="date-input-group-input"]')).toHaveLength(2);
expect(w.find('[data-slot="date-range-picker-trigger"]').exists()).toBe(
true,
);
expect(
w.findAll('[data-slot="date-input-group-segment"]').length,
).toBeGreaterThanOrEqual(6);
expect(w.findAll('input[data-part="start"]')).toHaveLength(1);
expect(w.findAll('input[data-part="end"]')).toHaveLength(1);
}
expect(warnings).toEqual([]);
});
it("the controlled example updates and clears the real range", async () => {
const w = mountDemo("controlled");
await flushPromises();
expect(input(w, "start").value).toMatch(/^\d{4}-\d{2}-\d{2}$/);
expect(w.get('[data-slot="description"]').text()).not.toContain("(空)");
await w
.findAll("button")
.find((button) => button.text() === "清空")!
.trigger("click");
await flushPromises();
expect(input(w, "start").value).toBe("");
expect(input(w, "end").value).toBe("");
expect(w.get('[data-slot="description"]').text()).toContain("(空)");
await w
.findAll("button")
.find((button) => button.text() === "设为一周")!
.trigger("click");
await flushPromises();
expect(input(w, "start").value).toMatch(/^\d{4}-\d{2}-\d{2}$/);
expect(w.get('[data-slot="description"]').text()).not.toContain("(空)");
});
it("the disabled example keeps values visible and non-editable", async () => {
const w = mountDemo("disabled");
await flushPromises();
expect(input(w, "start").disabled).toBe(true);
expect(input(w, "end").disabled).toBe(true);
expect(input(w, "start").value).toMatch(/^\d{4}-\d{2}-\d{2}$/);
expect(
w.get('[data-slot="date-range-picker-trigger"]').attributes("disabled"),
).toBeDefined();
expect(w.get('[data-slot="description"]').text()).toContain("已禁用");
});
it("format options keeps one range value while both TimeFields edit independently", async () => {
const w = mountDemo("format-options");
await flushPromises();
expect(input(w, "start").value).toContain("T08:45:00");
expect(input(w, "end").value).toContain("T18:45:00");
await open(w);
const timeFields = document.querySelectorAll('[data-slot="time-field"]');
expect(timeFields).toHaveLength(2);
expect(document.querySelectorAll('[name="startTime"]')).toHaveLength(1);
expect(document.querySelectorAll('[name="endTime"]')).toHaveLength(1);
const hour =
timeFields[0]!.querySelector<HTMLElement>('[data-type="hour"]')!;
hour.focus();
hour.dispatchEvent(
new KeyboardEvent("keydown", {
key: "ArrowUp",
bubbles: true,
cancelable: true,
}),
);
await flushPromises();
expect(input(w, "start").value).toContain("T09:45:00");
expect(input(w, "end").value).toContain("T18:45:00");
expect(document.body.textContent).toContain("已选:");
expect(document.body.textContent).toContain("2026");
expect(document.querySelectorAll('[name="startDate"]')).toHaveLength(1);
expect(document.querySelectorAll('[name="endDate"]')).toHaveLength(1);
});
it("format options switches to day granularity without losing the picker", async () => {
const w = mountDemo("format-options");
await flushPromises();
const trigger = w.get('[data-slot="select-trigger"]');
await trigger.trigger("click");
await flushPromises();
const option = [
...document.querySelectorAll<HTMLElement>("[role=option]"),
].find((node) => node.textContent?.trim() === "日")!;
expect(option).toBeTruthy();
option.click();
await flushPromises();
expect(document.querySelectorAll('[data-slot="time-field"]')).toHaveLength(
0,
);
expect(input(w, "start").value).toMatch(/^\d{4}-\d{2}-\d{2}$/);
expect(input(w, "end").value).toMatch(/^\d{4}-\d{2}-\d{2}$/);
expect(document.querySelectorAll('[name="startDate"]')).toHaveLength(1);
});
it("the form example submits a complete range and clears after success", async () => {
vi.useFakeTimers();
const w = mountDemo("form-example");
await flushPromises();
const submit = () =>
w.findAll("button").find((button) => button.text().includes("提交"))!;
expect(submit().attributes("disabled")).toBeDefined();
expect(w.findAll('[name="tripStartDate"]')).toHaveLength(1);
expect(w.findAll('[name="tripEndDate"]')).toHaveLength(1);
const start = today(getLocalTimeZone());
await open(w);
await pick(start.toString());
await pick(start.toString());
expect(submit().attributes("disabled")).toBeUndefined();
await w.get("form").trigger("submit");
await flushPromises();
expect(submit().text()).toContain("提交中");
vi.advanceTimersByTime(1300);
await flushPromises();
expect(input(w, "start").value).toBe("");
expect(input(w, "end").value).toBe("");
expect(submit().text()).toBe("提交");
});
it("the custom indicator uses the Tabler icon instead of the default SVG", async () => {
const w = mountDemo("with-custom-indicator");
await flushPromises();
const icon = w.get('[data-slot="date-range-picker-trigger-indicator"] svg');
expect(icon.attributes("viewBox")).toBe("0 0 24 24");
expect(
w
.find(
'[data-slot="date-range-picker-trigger-indicator"] svg[viewBox="0 0 13 14"]',
)
.exists(),
).toBe(false);
});
it("the render-function example keeps consumer elements and attributes", async () => {
const w = mountDemo("render-function");
await flushPromises();
expect(w.get('[data-slot="date-range-picker"]').element.tagName).toBe(
"SECTION",
);
expect(
w.get('[data-slot="date-range-picker"]').attributes("data-custom"),
).toBe("date-range-picker");
expect(
w.get('[data-slot="date-input-group"]').attributes("data-custom"),
).toBe("date-field-group");
expect(
w
.get('[data-slot="date-range-picker-trigger"]')
.attributes("data-custom"),
).toBe("date-range-picker-trigger");
});
it("the international calendar displays its locale calendar and keeps values", async () => {
const w = mountDemo("international-calendar");
await flushPromises();
expect(input(w, "start").value).not.toBe("");
await open(w);
const header = document.querySelector(
'[data-slot="range-calendar-header-cell"]',
)?.textContent;
expect(header).toBeTruthy();
expect(header).not.toMatch(/^(Sun|Mon|Tue|Wed|Thu|Fri|Sat)$/);
const selected = document.querySelector(
'[data-slot="range-calendar-cell"][data-selection-start="true"]',
);
expect(selected).not.toBeNull();
});
it("the custom styles example applies consumer classes without component patches", async () => {
const w = mountDemo("custom-styles");
await flushPromises();
const group = w.get('[data-slot="date-input-group"]');
expect(group.classes()).toContain("rounded-xl");
expect(group.classes()).toContain("border");
expect(group.classes()).toContain("hv-date-input-group--secondary");
expect(
w.get('[data-slot="date-range-picker-range-separator"]').classes(),
).toContain("text-muted");
expect(
w.get('[data-slot="date-range-picker-trigger"]').classes(),
).toContain("text-muted");
await open(w);
expect(
document.querySelector('[data-slot="date-range-picker-popover"]')
?.className,
).toContain("border");
expect(
document.querySelector('[data-slot="range-calendar"]')?.className,
).toContain("bg-surface");
});
it("the validation example exposes required and invalid state through the form", async () => {
const w = mountDemo("with-validation");
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(
"请选择从今天起的有效日期范围",
);
const start = today(getLocalTimeZone());
await open(w);
await pick(start.toString());
await pick(start.toString());
expect(validation.checkValidity()).toBe(true);
expect(w.find('[data-slot="field-error"]').exists()).toBe(false);
});
});
File diff suppressed because it is too large Load Diff
+21
View File
@@ -54,6 +54,27 @@ for (const id of process.argv.slice(2)) {
.includes("hv-time-field--full-width"),
);
}
if (id === "date-range-picker") {
assert(lib.DateRangePicker === lib.DateRangePickerRoot);
assert(lib.dateRangePickerVariants().base() === "hv-date-range-picker");
assert(
lib.dateRangePickerVariants().trigger() ===
"hv-date-range-picker__trigger",
);
assert(
lib.dateRangePickerVariants().rangeSeparator() ===
"hv-date-range-picker__range-separator",
);
assert(
lib.dateRangePickerVariants().popover() ===
"hv-date-range-picker__popover",
);
assert(
lib.dateRangePickerVariants().triggerIndicator() ===
"hv-date-range-picker__trigger-indicator",
);
assert(lib.DateFieldInput);
}
if (id === "date-picker") {
assert(lib.DatePicker === lib.DatePickerRoot);
assert(lib.datePickerVariants().base() === "hv-date-picker");
+28
View File
@@ -421,5 +421,33 @@
"data-selection-start",
"data-selection-end"
]
},
"date-range-picker": {
"exports": [
"DateRangePicker",
"DateRangePickerRoot",
"DateRangePickerTrigger",
"DateRangePickerTriggerIndicator",
"DateRangePickerRangeSeparator",
"DateRangePickerPopover",
"dateRangePickerVariants",
"DateFieldGroup",
"DateFieldInput",
"DateFieldInputContainer",
"DateFieldSegment",
"DateFieldSuffix",
"RangeCalendar",
"RangeCalendarCell"
],
"css": [
".hv-date-range-picker",
".hv-date-range-picker__trigger",
".hv-date-range-picker__trigger-indicator",
".hv-date-range-picker__range-separator",
".hv-date-range-picker__popover",
"--reka-popper-transform-origin",
"data-exiting",
"data-endpoint"
]
}
}
+211
View File
@@ -0,0 +1,211 @@
import { h } from "vue";
import {
CalendarDate,
CalendarDateTime,
parseZonedDateTime,
Time,
type DateValue,
} from "@internationalized/date";
import {
DateFieldGroup,
DateFieldInput,
DateFieldInputContainer,
DateFieldSegment,
DateFieldSuffix,
DateRangePicker,
DateRangePickerPopover,
DateRangePickerRangeSeparator,
DateRangePickerRoot,
DateRangePickerTrigger,
DateRangePickerTriggerIndicator,
RangeCalendar,
dateRangePickerVariants,
type DateFieldInputProps,
type DateRangePickerPopoverProps,
type DateRangePickerProps,
type DateRangePickerRangeSeparatorProps,
type DateRangePickerRenderProps,
type DateRangePickerRootProps,
type DateRangePickerState,
type DateRangePickerTimeRange,
type DateRangePickerTimeValue,
type DateRangePickerTriggerIndicatorProps,
type DateRangePickerTriggerProps,
} from "@heroui-vue/components";
type DateRange = { start: DateValue; end: DateValue };
const day = new CalendarDate(2024, 2, 10);
const range: DateRange = {
start: day,
end: new CalendarDate(2024, 2, 15),
};
const dateTime = new CalendarDateTime(2024, 2, 10, 9, 30);
const zoned = parseZonedDateTime("2024-01-01T09:30+08:00[Asia/Shanghai]");
const time: DateRangePickerTimeValue = new Time(9, 30);
const timeRange: DateRangePickerTimeRange = {
start: time,
end: new CalendarDateTime(2024, 1, 1, 18, 30),
};
const values: DateRangePickerProps[] = [
{
modelValue: range,
value: null,
defaultValue: { start: dateTime, end: zoned },
placeholderValue: day,
minValue: day,
maxValue: day.add({ years: 1 }),
isDateUnavailable: (value) => value.day === 20,
allowsNonContiguousRanges: true,
granularity: "second",
hourCycle: 24,
hideTimeZone: true,
shouldForceLeadingZeros: true,
locale: "zh-CN",
firstDayOfWeek: "mon",
pageBehavior: "single",
dir: "rtl",
startName: "startDate",
endName: "endDate",
form: "trip",
isDisabled: false,
isReadOnly: false,
isRequired: true,
isInvalid: false,
shouldCloseOnSelect: false,
validate: (value) =>
value ? (value.end.compare(value.start) < 0 ? "Reversed" : null) : null,
"onUpdate:modelValue": (value) => {
const accepted: DateRange | null = value;
void accepted;
},
onChange: (value) => {
const accepted: DateRange | null = value;
void accepted;
},
"onUpdate:open": (value) => {
const open: boolean = value;
void open;
},
onOpenChange: (value) => {
const open: boolean = value;
void open;
},
},
];
const root: DateRangePickerRootProps = { as: "section" };
const trigger: DateRangePickerTriggerProps = {
as: "button",
asChild: false,
isDisabled: true,
};
const indicator: DateRangePickerTriggerIndicatorProps = { as: "span" };
const separator: DateRangePickerRangeSeparatorProps = {
as: "span",
children: " to ",
};
const popover: DateRangePickerPopoverProps = {
placement: "bottom",
offset: 12,
crossOffset: 4,
shouldFlip: true,
containerPadding: 16,
isDismissable: false,
isKeyboardDismissDisabled: true,
};
const state: DateRangePickerState = {
value: range,
timeRange,
setValue: (value) => {
const next: DateRange | null = value;
void next;
},
setTimeRange: (value) => {
const next: DateRangePickerTimeRange | null = value;
void next;
},
};
const rendered: DateRangePickerRenderProps = {
value: range,
isOpen: true,
isDisabled: false,
isReadOnly: false,
isRequired: false,
isInvalid: false,
isFocusWithin: false,
isFocused: false,
isFocusVisible: false,
validationErrors: [],
timeRange,
state,
open: () => {},
close: () => {},
toggle: () => {},
};
const endpoint: DateFieldInputProps = {
endpoint: "start",
as: "div",
};
const endEndpoint: DateFieldInputProps = { endpoint: "end" };
// @ts-expect-error a range is required, not a single date
const singleDate: DateRangePickerProps = { modelValue: day };
// @ts-expect-error visible granularity has a fixed set
const wrongGranularity: DateRangePickerProps = { granularity: "week" };
// @ts-expect-error hour cycles are 12 or 24
const wrongCycle: DateRangePickerProps = { hourCycle: 23 };
// @ts-expect-error open state is boolean
const wrongOpen: DateRangePickerProps = { open: "yes" };
// @ts-expect-error names are strings
const wrongName: DateRangePickerProps = { startName: 1 };
// @ts-expect-error the non-contiguous policy is boolean
const wrongPolicy: DateRangePickerProps = { allowsNonContiguousRanges: "yes" };
// @ts-expect-error placement is a known logical value
const wrongPlacement: DateRangePickerPopoverProps = { placement: "diagonal" };
// @ts-expect-error endpoints are start or end
const wrongEndpoint: DateFieldInputProps = { endpoint: "middle" };
type Slot = Parameters<
NonNullable<InstanceType<typeof DateRangePicker>["$slots"]["default"]>
>[0];
const slot: Slot = rendered;
const slotTime: DateRangePickerTimeRange | null = slot.state.timeRange;
// @ts-expect-error slot time is not a number
const wrongSlotTime: number = slot.timeRange;
void [
DateRangePicker,
DateRangePickerRoot,
DateRangePickerTrigger,
DateRangePickerTriggerIndicator,
DateRangePickerRangeSeparator,
DateRangePickerPopover,
DateFieldGroup,
DateFieldInput,
DateFieldInputContainer,
DateFieldSegment,
DateFieldSuffix,
RangeCalendar,
dateRangePickerVariants().base(),
dateRangePickerVariants().trigger(),
dateRangePickerVariants().triggerIndicator(),
dateRangePickerVariants().rangeSeparator(),
dateRangePickerVariants().popover(),
values,
root,
trigger,
indicator,
separator,
popover,
state,
rendered,
endpoint,
endEndpoint,
singleDate,
wrongGranularity,
wrongCycle,
wrongOpen,
wrongName,
wrongPolicy,
wrongPlacement,
wrongEndpoint,
slotTime,
wrongSlotTime,
];
h(DateRangePickerPopover, popover);