fix(demos): inherit ConfigProvider locale and restore the format-options popover width

HD-03 scope, all against heroui ce90ea3 cn sources:

- calendar-disabled/read-only: restore the today() default value and the
  baseline description lines (日历已禁用 / 日历为只读) inside the
  flex flex-col items-center wrapper
- calendar-controlled: restore the second button row (设为今天/设为圣诞节/
  清空) and the baseline feedback wording (已选日期:…(未选))
- locale inheritance: add a public useLocale() accessor (the components'
  ConfigProvider → en-US/ltr chain) and use it for startOfWeek in
  calendar-controlled, isWeekend in booking-calendar/unavailable-dates and
  the DateFormatter in date-range-picker-format-options instead of the
  hardcoded 'en-US' / 'zh-CN' literals
- date-range-picker-format-options: restore the pinned w-full popover class;
  the pinned source positions the popover against the initial containing
  block (full viewport width — verified on the reference docs at desktop and
  narrow), while Reka's shrink-to-fit positioning wrapper collapses the same
  class. A scoped adapter rule (.hv-date-range-picker__popover.w-full →
  100vw, layering-safe like the dropdown static-wrapper adapter) restores
  the baseline effect: viewport-wide popover, 252px calendar, stretched
  time rows, identical boundary clamping

- tests: locale dynamic-switching regressions covering zh-CN/en-US for week
  start, weekend rules (with ar-EG flipping the weekend for a observable
  rule change) and range formatting; full suite 110 files / 1627 tests,
  typecheck, build:docs and the date-range-picker / api-root-aliases /
  calendar tarball contracts pass
This commit is contained in:
maoyingjie
2026-10-28 16:35:26 +08:00
parent 0b89f02745
commit 2e3fdd4800
15 changed files with 382 additions and 147 deletions
+2 -2
View File
@@ -288,8 +288,8 @@ Calendar 保留固定基线的主要属性与部件,以 Vue 模型、具名部
### Related packages ### Related packages
- [`@internationalized/date`](https://react-aria.adobe.com/internationalized/date/) — 所有日期组件使用的日期类型(`CalendarDate`、`CalendarDateTime`、`ZonedDateTime`)与工具 - [`@internationalized/date`](https://react-aria.adobe.com/internationalized/date/) — 所有日期组件使用的日期类型(`CalendarDate`、`CalendarDateTime`、`ZonedDateTime`)与工具
- 本库 `ConfigProvider` — 覆盖子树的 locale - 本库 `ConfigProvider` — 覆盖子树的 locale 与布局方向
- 本库 `ConfigProvider` — 统一 locale 与布局方向 - 本库 `useLocale()` — 读取当前 `ConfigProvider` 的 `locale` / `dir`(未包裹时回退 `en-US` / `ltr`,与组件继承链一致),供 `startOfWeek`、`isWeekend`、`DateFormatter` 等本地化计算使用
## Vue 模型、DOM 与当前差异 ## Vue 模型、DOM 与当前差异
@@ -348,6 +348,7 @@ DateRangePicker 继承固定基线的双端点日期字段、范围日历与弹
- [`@internationalized/date`](https://react-aria.adobe.com/internationalized/date/) — 所有日期组件使用的日期类型(`CalendarDate`、`CalendarDateTime`、`ZonedDateTime`)与工具 - [`@internationalized/date`](https://react-aria.adobe.com/internationalized/date/) — 所有日期组件使用的日期类型(`CalendarDate`、`CalendarDateTime`、`ZonedDateTime`)与工具
- 本库 `ConfigProvider` — 为子树覆盖 locale、书写方向与 Portal 目标 - 本库 `ConfigProvider` — 为子树覆盖 locale、书写方向与 Portal 目标
- 本库 `useLocale()` — 读取当前 `ConfigProvider` 的 `locale` / `dir`(未包裹时回退 `en-US` / `ltr`),供 `DateFormatter`、`startOfWeek`、`isWeekend` 等本地化计算使用
## 相关组件 ## 相关组件
@@ -12,6 +12,7 @@ import {
CalendarCellIndicator, CalendarCellIndicator,
Button, Button,
Description, Description,
useLocale,
} from "@heroui-vue/components"; } from "@heroui-vue/components";
import { shallowRef, ref } from "vue"; import { shallowRef, ref } from "vue";
import { import {
@@ -24,8 +25,9 @@ const selectedDate = shallowRef<DateValue | null>(null);
const booking = ref(""); const booking = ref("");
const now = today(getLocalTimeZone()); const now = today(getLocalTimeZone());
const bookedDates = [5, 6, 12, 13, 14, 20]; const bookedDates = [5, 6, 12, 13, 14, 20];
const { locale } = useLocale();
const isDateUnavailable = (date: DateValue) => const isDateUnavailable = (date: DateValue) =>
isWeekend(date, "en-US") || bookedDates.includes(date.day); isWeekend(date, locale.value) || bookedDates.includes(date.day);
</script> </script>
<template> <template>
<div class="flex flex-col items-center gap-4"> <div class="flex flex-col items-center gap-4">
+21 -2
View File
@@ -12,6 +12,7 @@ import {
Button, Button,
ButtonGroup, ButtonGroup,
Description, Description,
useLocale,
} from "@heroui-vue/components"; } from "@heroui-vue/components";
import { shallowRef } from "vue"; import { shallowRef } from "vue";
import { import {
@@ -24,6 +25,7 @@ import {
} from "@internationalized/date"; } from "@internationalized/date";
const value = shallowRef<DateValue | null>(null); const value = shallowRef<DateValue | null>(null);
const focusedDate = shallowRef<DateValue>(parseDate("2025-12-25")); const focusedDate = shallowRef<DateValue>(parseDate("2025-12-25"));
const { locale } = useLocale();
function jump(date: DateValue) { function jump(date: DateValue) {
value.value = date; value.value = date;
focusedDate.value = date; focusedDate.value = date;
@@ -33,7 +35,7 @@ function jump(date: DateValue) {
<div class="flex flex-col items-center gap-4"> <div class="flex flex-col items-center gap-4">
<ButtonGroup full-width size="sm" variant="tertiary"> <ButtonGroup full-width size="sm" variant="tertiary">
<Button @click="jump(today(getLocalTimeZone()))">今天</Button> <Button @click="jump(today(getLocalTimeZone()))">今天</Button>
<Button @click="jump(startOfWeek(today(getLocalTimeZone()), 'en-US'))"> <Button @click="jump(startOfWeek(today(getLocalTimeZone()), locale))">
本周 本周
</Button> </Button>
<Button @click="jump(startOfMonth(today(getLocalTimeZone())))"> <Button @click="jump(startOfMonth(today(getLocalTimeZone())))">
@@ -60,7 +62,24 @@ function jump(date: DateValue) {
</CalendarGrid> </CalendarGrid>
</Calendar> </Calendar>
<Description class="text-center"> <Description class="text-center">
{{ value ? `已选择:${value.toString()}` : "未选择日期" }} 已选日期:{{ value ? value.toString() : "(未选)" }}
</Description> </Description>
<div class="flex gap-2">
<Button
size="sm"
variant="secondary"
@click="jump(today(getLocalTimeZone()))"
>
设为今天
</Button>
<Button
size="sm"
variant="secondary"
@click="jump(parseDate('2025-12-25'))"
>
设为圣诞节
</Button>
<Button size="sm" variant="tertiary" @click="value = null">清空</Button>
</div>
</div> </div>
</template> </template>
+10 -1
View File
@@ -9,10 +9,17 @@ import {
CalendarGridBody, CalendarGridBody,
CalendarHeaderCell, CalendarHeaderCell,
CalendarCell, CalendarCell,
Description,
} from "@heroui-vue/components"; } from "@heroui-vue/components";
import { getLocalTimeZone, today } from "@internationalized/date";
</script> </script>
<template> <template>
<Calendar aria-label="活动日期" is-disabled> <div class="flex flex-col items-center gap-4">
<Calendar
aria-label="活动日期"
is-disabled
:default-value="today(getLocalTimeZone())"
>
<CalendarHeader> <CalendarHeader>
<CalendarHeading /> <CalendarHeading />
<CalendarNavButton slot="previous" /> <CalendarNavButton slot="previous" />
@@ -27,4 +34,6 @@ import {
</CalendarGridBody> </CalendarGridBody>
</CalendarGrid> </CalendarGrid>
</Calendar> </Calendar>
<Description class="text-center">日历已禁用</Description>
</div>
</template> </template>
+6 -2
View File
@@ -9,14 +9,16 @@ import {
CalendarGridBody, CalendarGridBody,
CalendarHeaderCell, CalendarHeaderCell,
CalendarCell, CalendarCell,
Description,
} from "@heroui-vue/components"; } from "@heroui-vue/components";
import { parseDate } from "@internationalized/date"; import { getLocalTimeZone, today } from "@internationalized/date";
</script> </script>
<template> <template>
<div class="flex flex-col items-center gap-4">
<Calendar <Calendar
aria-label="活动日期" aria-label="活动日期"
is-read-only is-read-only
:default-value="parseDate('2025-02-14')" :default-value="today(getLocalTimeZone())"
> >
<CalendarHeader> <CalendarHeader>
<CalendarHeading /> <CalendarHeading />
@@ -32,4 +34,6 @@ import { parseDate } from "@internationalized/date";
</CalendarGridBody> </CalendarGridBody>
</CalendarGrid> </CalendarGrid>
</Calendar> </Calendar>
<Description class="text-center">日历为只读</Description>
</div>
</template> </template>
@@ -10,9 +10,11 @@ import {
CalendarHeaderCell, CalendarHeaderCell,
CalendarCell, CalendarCell,
Description, Description,
useLocale,
} from "@heroui-vue/components"; } from "@heroui-vue/components";
import { isWeekend, type DateValue } from "@internationalized/date"; import { isWeekend, type DateValue } from "@internationalized/date";
const isDateUnavailable = (date: DateValue) => isWeekend(date, "en-US"); const { locale } = useLocale();
const isDateUnavailable = (date: DateValue) => isWeekend(date, locale.value);
</script> </script>
<template> <template>
<div class="flex flex-col items-center gap-4"> <div class="flex flex-col items-center gap-4">
@@ -43,6 +43,7 @@ import {
TimeFieldGroup, TimeFieldGroup,
TimeFieldInput, TimeFieldInput,
TimeFieldSegment, TimeFieldSegment,
useLocale,
} from "@heroui-vue/components"; } from "@heroui-vue/components";
import { import {
DateFormatter, DateFormatter,
@@ -61,6 +62,7 @@ const granularity = ref<Granularity>("minute");
const hourCycle = ref<HourCycle>(12); const hourCycle = ref<HourCycle>(12);
const hideTimeZone = ref(false); const hideTimeZone = ref(false);
const shouldForceLeadingZeros = ref(false); const shouldForceLeadingZeros = ref(false);
const { locale } = useLocale();
const cycle = computed(() => (hourCycle.value === 24 ? 24 : 12) as 12 | 24); const cycle = computed(() => (hourCycle.value === 24 ? 24 : 12) as 12 | 24);
const timeGranularity = computed(() => const timeGranularity = computed(() =>
granularity.value !== "day" ? granularity.value : undefined, granularity.value !== "day" ? granularity.value : undefined,
@@ -78,14 +80,17 @@ const defaultValue = computed<DateRange>(() => {
start: parseZonedDateTime(`2026-02-03T08:45:00[${localTimeZone}]`), start: parseZonedDateTime(`2026-02-03T08:45:00[${localTimeZone}]`),
}; };
}); });
const dateFormatter = new DateFormatter("zh-CN", { const dateFormatter = computed(
() =>
new DateFormatter(locale.value, {
day: "numeric", day: "numeric",
month: "short", month: "short",
year: "numeric", year: "numeric",
}); }),
);
function formatDate(range: DateRange) { function formatDate(range: DateRange) {
const localTimeZone = getLocalTimeZone(); const localTimeZone = getLocalTimeZone();
return dateFormatter.formatRange( return dateFormatter.value.formatRange(
range.start.toDate(localTimeZone), range.start.toDate(localTimeZone),
range.end.toDate(localTimeZone), range.end.toDate(localTimeZone),
); );
@@ -133,8 +138,10 @@ const hourCycleOptions: { label: string; value: HourCycle }[] = [
</DateFieldSuffix> </DateFieldSuffix>
</DateFieldGroup> </DateFieldGroup>
<!-- Portaled content keeps an auto-sized wrapper; the pinned example's <!-- Portaled content keeps an auto-sized wrapper; the pinned example's
w-full maps to the 252px calendar plus the popover's 24px padding. --> w-full fills the popover's positioning container — see the
<DateRangePickerPopover class="flex w-[276px] flex-col gap-3"> .hv-date-range-picker__popover.w-full adapter in date-range-picker.css,
which maps it to the same viewport width as the upstream chain. -->
<DateRangePickerPopover class="flex w-full flex-col gap-3">
<RangeCalendar aria-label="出行日期" class="w-full"> <RangeCalendar aria-label="出行日期" class="w-full">
<RangeCalendarHeader> <RangeCalendarHeader>
<CalendarYearPickerTrigger> <CalendarYearPickerTrigger>
+2 -2
View File
@@ -5,7 +5,7 @@
固定上游公共组件清单;状态、差异和验证范围逐组件记录,不以单项测试通过声明整库完整兼容。 固定上游公共组件清单;状态、差异和验证范围逐组件记录,不以单项测试通过声明整库完整兼容。
| 组件 | 状态 | 当前能力 / 差异 | | 组件 | 状态 | 当前能力 / 差异 |
| -------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | -------------------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| accordion | 验证中(M23) | Accordion/Item/Heading/Trigger/Panel/Body/Indicator;10/10 基线例;surface/hideSeparator;复用组键协议 | | accordion | 验证中(M23) | Accordion/Item/Heading/Trigger/Panel/Body/Indicator;10/10 基线例;surface/hideSeparator;复用组键协议 |
| alert-dialog | 验证中(M33) | 11 部件;role=alertdialog;默认不误关;14/14 基线例;Reka Dialog 底座 | | alert-dialog | 验证中(M33) | 11 部件;role=alertdialog;默认不误关;14/14 基线例;Reka Dialog 底座 |
| autocomplete | 已迁移(有已知差异) | Autocomplete 七部件;24/24 基线例;触发器单一 Tab 入口 + 弹层内搜索框虚拟焦点、受控开关/文本、多选 Value 用作用域插槽;见 B02 报告 | | autocomplete | 已迁移(有已知差异) | Autocomplete 七部件;24/24 基线例;触发器单一 Tab 入口 + 弹层内搜索框虚拟焦点、受控开关/文本、多选 Value 用作用域插槽;见 B02 报告 |
@@ -279,7 +279,7 @@ ComboBox/Autocomplete的正式组合、原30项返修和本轮定位/ref/ARIA/lo
公开 DateRangePicker/Root、Trigger、TriggerIndicator、RangeSeparator、Popover、dateRangePickerVariants 及 Props/RenderProps/state/time 类型;起止输入复用 DateFieldGroup/Input/InputContainer/Segment/Suffix,端点为可类型检查的 `endpoint` prop;日历复用 RangeCalendar 与 CalendarYearPicker 具名部件。固定源中文 10 个预览、API/插槽/状态表与导航已接入;Picker 拥有唯一完整范围接受值、双端点字段校验、两个命名提交值和 reset,未显式绑定的内嵌 RangeCalendar 继承范围、上下界、不可用、禁用/只读/无效、locale/dir 与非连续策略。 公开 DateRangePicker/Root、Trigger、TriggerIndicator、RangeSeparator、Popover、dateRangePickerVariants 及 Props/RenderProps/state/time 类型;起止输入复用 DateFieldGroup/Input/InputContainer/Segment/Suffix,端点为可类型检查的 `endpoint` prop;日历复用 RangeCalendar 与 CalendarYearPicker 具名部件。固定源中文 10 个预览、API/插槽/状态表与导航已接入;Picker 拥有唯一完整范围接受值、双端点字段校验、两个命名提交值和 reset,未显式绑定的内嵌 RangeCalendar 继承范围、上下界、不可用、禁用/只读/无效、locale/dir 与非连续策略。
不完整范围、第一下日历点击和空值时间草稿都不提交;清空两端提交 null,清空一端在关闭/外部替换/reset 时回到接受状态。受控拒绝后可重试,日历修改保留两端各自的日期类、时间、时区与历法,字段编辑保留不可显示精度。固定源 `slot="start"/"end"` 映射为 `endpoint` prop;格式选项的 `w-full` 弹层宽度映射为 252px 日历加 24px 内边距。真实浏览器、定向回归和最终 tarball 验证见 [任务结果](tasks/results/DATE-RANGE-PICKER.md)。 不完整范围、第一下日历点击和空值时间草稿都不提交;清空两端提交 null,清空一端在关闭/外部替换/reset 时回到接受状态。受控拒绝后可重试,日历修改保留两端各自的日期类、时间、时区与历法,字段编辑保留不可显示精度。固定源 `slot="start"/"end"` 映射为 `endpoint` prop;格式选项弹层沿用基线 `w-full`:上游把弹层自身以 `position: absolute` 定位到初始包含块,`w-full` 即视口宽(官方文档桌面/窄屏实测),Vue/Reka 的定位包裹层按内容收缩,`date-range-picker.css` 的 `.hv-date-range-picker__popover.w-full` 适配规则把该类映射到同一视口宽,锚点贴靠、边界钳制与内容布局(252px 日历 + 拉伸的时间行)随之一致。真实浏览器、定向回归和最终 tarball 验证见 [任务结果](tasks/results/DATE-RANGE-PICKER.md)。
## FORM 正式迁移(2026-10-27) ## FORM 正式迁移(2026-10-27)
@@ -91,3 +91,15 @@
.hv-date-range-picker__popover .hv-calendar__nav-button-icon { .hv-date-range-picker__popover .hv-calendar__nav-button-icon {
@apply rotate-0; @apply rotate-0;
} }
/* Vue/Reka adapter: the pinned source positions the popover itself with
* `position: absolute` against the initial containing block, where a consumer's
* `w-full` (e.g. the cn format-options demo) resolves to the viewport width.
* Reka sizes its positioning wrapper to the content instead, so the same class
* would collapse; map it to the identical viewport width so the anchor
* placement, boundary clamping and content layout match the baseline.
* `!important` is required to out-rank the `w-full` utility layer (same
* layering constraint as the dropdown static-wrapper adapter). */
.hv-date-range-picker__popover.w-full {
width: 100vw !important;
}
+4 -9
View File
@@ -438,6 +438,7 @@ export {
type UseOverlayStateOptions, type UseOverlayStateOptions,
} from "./composables/useOverlayState"; } from "./composables/useOverlayState";
export { default as ConfigProvider } from "./providers/ConfigProvider.vue"; export { default as ConfigProvider } from "./providers/ConfigProvider.vue";
export { useLocale } from "./providers/context";
export type { ConfigProviderProps } from "./types"; export type { ConfigProviderProps } from "./types";
export { default as Modal } from "./components/modal/Modal"; export { default as Modal } from "./components/modal/Modal";
@@ -817,9 +818,7 @@ export {
default as DateInputGroup, default as DateInputGroup,
default as DateFieldGroup, default as DateFieldGroup,
} from "./components/date-field/DateInputGroup.vue"; } from "./components/date-field/DateInputGroup.vue";
export { export { default as DateInputGroupRoot } from "./components/date-field/DateInputGroup.vue";
default as DateInputGroupRoot,
} from "./components/date-field/DateInputGroup.vue";
export { export {
default as DateInputGroupInput, default as DateInputGroupInput,
default as DateFieldInput, default as DateFieldInput,
@@ -1437,12 +1436,8 @@ export {
default as ColorPicker, default as ColorPicker,
default as ColorPickerRoot, default as ColorPickerRoot,
} from "./components/color-picker/ColorPicker.vue"; } from "./components/color-picker/ColorPicker.vue";
export { export { default as ColorPickerTrigger } from "./components/color-picker/ColorPickerTrigger.vue";
default as ColorPickerTrigger, export { default as ColorPickerPopover } from "./components/color-picker/ColorPickerPopover.vue";
} from "./components/color-picker/ColorPickerTrigger.vue";
export {
default as ColorPickerPopover,
} from "./components/color-picker/ColorPickerPopover.vue";
export type * from "./components/color-picker/types"; export type * from "./components/color-picker/types";
export { colorPickerVariants } from "@heroui-vue/styles"; export { colorPickerVariants } from "@heroui-vue/styles";
export type { ColorPickerVariants } from "@heroui-vue/styles"; export type { ColorPickerVariants } from "@heroui-vue/styles";
+15 -1
View File
@@ -1,4 +1,4 @@
import { inject, type ComputedRef, type InjectionKey } from "vue"; import { computed, inject, type ComputedRef, type InjectionKey } from "vue";
export interface ConfigContext { export interface ConfigContext {
dir: ComputedRef<"ltr" | "rtl">; dir: ComputedRef<"ltr" | "rtl">;
@@ -9,3 +9,17 @@ export const configContextKey: InjectionKey<ConfigContext> =
export function useConfig() { export function useConfig() {
return inject(configContextKey, undefined); return inject(configContextKey, undefined);
} }
/**
* Locale/direction of the active `ConfigProvider`, mirroring the components'
* inheritance chain (`ConfigProvider` → `en-US` / `ltr`). Consumers use it for
* locale-dependent computations outside the components, such as
* `startOfWeek`/`isWeekend` or a `DateFormatter`, the way upstream demos use
* react-aria-components' `useLocale()`.
*/
export function useLocale() {
const config = useConfig();
return {
locale: computed(() => config?.locale.value ?? "en-US"),
dir: computed(() => config?.dir.value ?? "ltr"),
};
}
+125 -1
View File
@@ -1,11 +1,31 @@
import { afterEach, expect, it, vi } from "vitest"; import { afterEach, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils"; import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, h, type Component } from "vue"; import { defineComponent, h, ref, type Component, type Ref } from "vue";
import {
getDayOfWeek,
getLocalTimeZone,
isWeekend,
startOfMonth,
startOfWeek,
today,
} from "@internationalized/date";
import { ConfigProvider } from "../packages/vue/src";
const demos = import.meta.glob("../apps/docs/demos/calendar-*.vue", { const demos = import.meta.glob("../apps/docs/demos/calendar-*.vue", {
eager: true, eager: true,
import: "default", import: "default",
}) as Record<string, Component>; }) as Record<string, Component>;
const wrappers: ReturnType<typeof mount>[] = []; const wrappers: ReturnType<typeof mount>[] = [];
function mountInLocale(locale: Ref<string>, name: string) {
const demo = demos[`../apps/docs/demos/${name}.vue`];
const w = mount(
defineComponent({
render: () => h(ConfigProvider, { locale: locale.value }, () => h(demo!)),
}),
{ attachTo: document.body },
);
wrappers.push(w);
return w;
}
afterEach(() => { afterEach(() => {
wrappers.splice(0).forEach((w) => w.unmount()); wrappers.splice(0).forEach((w) => w.unmount());
document.body.innerHTML = ""; document.body.innerHTML = "";
@@ -30,3 +50,107 @@ it("mounts all nineteen baseline demos together without duplicate IDs or Vue war
expect(new Set(ids).size).toBe(ids.length); expect(new Set(ids).size).toBe(ids.length);
expect(warn).not.toHaveBeenCalled(); expect(warn).not.toHaveBeenCalled();
}); });
it("the 本周 jump uses the active ConfigProvider locale and follows runtime switches", async () => {
const locale = ref("en-US");
mountInLocale(locale, "calendar-controlled");
await flushPromises();
const weekButton = () =>
[...document.querySelectorAll("button")].find(
(b) => b.textContent?.trim() === "本周",
)!;
const picked = () =>
document.body.textContent!.match(/已选日期:(\d{4}-\d{2}-\d{2})/)?.[1];
weekButton().click();
await flushPromises();
const enStart = startOfWeek(today(getLocalTimeZone()), "en-US").toString();
expect(enStart).toBe(
startOfWeek(today(getLocalTimeZone()), "en-US").toString(),
);
expect(picked()).toBe(enStart);
locale.value = "zh-CN";
await flushPromises();
weekButton().click();
await flushPromises();
const zhStart = startOfWeek(today(getLocalTimeZone()), "zh-CN").toString();
// The two locales disagree on the first day of the week (Sunday vs Monday),
// so the same action must land on different days after the switch.
expect(zhStart).not.toBe(enStart);
expect(picked()).toBe(zhStart);
});
it("weekend disabling follows the active locale, including weekend-rule changes", async () => {
const base = startOfWeek(today(getLocalTimeZone()), "en-US");
const day = (offset: number) => base.add({ days: offset }).toString();
const friday = day(5),
saturday = day(6),
sunday = day(0);
const flags = () =>
Object.fromEntries(
[friday, saturday, sunday].map((date) => [
date,
!!document
.querySelector(`[data-date="${date}"]`)
?.getAttribute("data-unavailable"),
]),
);
const locale = ref("en-US");
mountInLocale(locale, "calendar-unavailable-dates");
await flushPromises();
// en-US/zh-CN share the Sat–Sun weekend (CLDR); the flags must equal the
// locale rule either way.
expect(flags()).toEqual({
[friday]: isWeekend(base.add({ days: 5 }), "en-US"),
[saturday]: isWeekend(base.add({ days: 6 }), "en-US"),
[sunday]: isWeekend(base.add({ days: 0 }), "en-US"),
});
expect(flags()[saturday]).toBe(true);
expect(flags()[sunday]).toBe(true);
expect(flags()[friday]).toBe(false);
locale.value = "zh-CN";
await flushPromises();
expect(flags()).toEqual({
[friday]: isWeekend(base.add({ days: 5 }), "zh-CN"),
[saturday]: isWeekend(base.add({ days: 6 }), "zh-CN"),
[sunday]: isWeekend(base.add({ days: 0 }), "zh-CN"),
});
// ar-EG has a Friday–Saturday weekend: the same cells must flip.
locale.value = "ar-EG";
await flushPromises();
expect(flags()).toEqual({
[friday]: true,
[saturday]: true,
[sunday]: false,
});
});
it("the booking calendar combines locale weekends with the booked days", async () => {
const booked = [5, 6, 12, 13, 14, 20];
const monthStart = startOfMonth(today(getLocalTimeZone()));
const days = Array.from({ length: 31 }, (_, i) =>
monthStart.add({ days: i }),
).filter((d) => d.month === monthStart.month);
const iso = (d: (typeof days)[number]) => d.toString();
const unavailable = (d: (typeof days)[number]) =>
!!document
.querySelector(`[data-date="${iso(d)}"]`)
?.getAttribute("data-unavailable");
const sunday = days.find(
(d) => !booked.includes(d.day) && getDayOfWeek(d, "en-US", "sun") === 0,
)!;
const arWorkingDay = days.find(
(d) => booked.includes(d.day) && !isWeekend(d, "ar-EG"),
)!;
const locale = ref("en-US");
mountInLocale(locale, "calendar-booking-calendar");
await flushPromises();
// Booked days stay unavailable whatever the weekend rule is.
expect(unavailable(arWorkingDay)).toBe(true);
// The locale weekend applies on top of the booked days.
expect(unavailable(sunday)).toBe(true);
locale.value = "ar-EG";
await flushPromises();
// Sunday becomes a working day under ar-EG and is not booked here.
expect(unavailable(sunday)).toBe(false);
expect(unavailable(arWorkingDay)).toBe(true);
});
+45 -1
View File
@@ -1,7 +1,14 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils"; import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, h, ref } from "vue";
import { readFileSync } from "node:fs"; import { readFileSync } from "node:fs";
import { getLocalTimeZone, today } from "@internationalized/date"; import {
DateFormatter,
getLocalTimeZone,
parseZonedDateTime,
today,
} from "@internationalized/date";
import { ConfigProvider } from "../packages/vue/src";
const demos = import.meta.glob("../apps/docs/demos/date-range-picker-*.vue", { const demos = import.meta.glob("../apps/docs/demos/date-range-picker-*.vue", {
eager: true, eager: true,
import: "default", import: "default",
@@ -300,4 +307,41 @@ describe("DateRangePicker documentation", () => {
expect(validation.checkValidity()).toBe(true); expect(validation.checkValidity()).toBe(true);
expect(w.find('[data-slot="field-error"]').exists()).toBe(false); expect(w.find('[data-slot="field-error"]').exists()).toBe(false);
}); });
it("format options formats the range with the active locale and follows runtime switches", async () => {
const tz = getLocalTimeZone();
const start = parseZonedDateTime(`2026-02-03T08:45:00[${tz}]`).toDate();
const end = parseZonedDateTime(`2026-02-10T18:45:00[${tz}]`).toDate();
const formatted = (loc: string) =>
new DateFormatter(loc, {
day: "numeric",
month: "short",
year: "numeric",
}).formatRange(start, end);
expect(formatted("zh-CN")).not.toBe(formatted("en-US"));
const locale = ref("zh-CN");
const demo =
demos["../apps/docs/demos/date-range-picker-format-options.vue"];
const w = mount(
defineComponent({
render: () =>
h(ConfigProvider, { locale: locale.value }, () => h(demo as never)),
}),
{ attachTo: document.body },
);
wrappers.push(w);
await flushPromises();
await open(w);
expect(document.body.textContent).toContain("已选:");
expect(document.body.textContent).toContain(formatted("zh-CN"));
locale.value = "en-US";
await flushPromises();
expect(document.body.textContent).toContain(formatted("en-US"));
expect(document.body.textContent).not.toContain(formatted("zh-CN"));
// The same range renders with the new locale again after a switch back.
locale.value = "zh-CN";
await flushPromises();
expect(document.body.textContent).toContain(formatted("zh-CN"));
expect(document.body.textContent).not.toContain(formatted("en-US"));
});
}); });
+2
View File
@@ -481,6 +481,7 @@
".hv-date-range-picker__trigger-indicator", ".hv-date-range-picker__trigger-indicator",
".hv-date-range-picker__range-separator", ".hv-date-range-picker__range-separator",
".hv-date-range-picker__popover", ".hv-date-range-picker__popover",
".hv-date-range-picker__popover.w-full",
"--reka-popper-transform-origin", "--reka-popper-transform-origin",
"data-exiting", "data-exiting",
"data-endpoint" "data-endpoint"
@@ -584,6 +585,7 @@
}, },
"api-root-aliases": { "api-root-aliases": {
"exports": [ "exports": [
"useLocale",
"Accordion", "Accordion",
"AccordionRoot", "AccordionRoot",
"Alert", "Alert",