feat: migrate Calendar and calendar year picker

This commit is contained in:
maoyingjie
2026-10-24 20:59:19 +08:00
parent 1c4ecc3def
commit 835d2e4d90
47 changed files with 4283 additions and 87 deletions
@@ -0,0 +1,533 @@
import {
computed,
defineComponent,
h,
mergeProps,
provide,
ref,
watch,
useId,
type PropType,
type SlotsType,
type VNodeChild,
} from "vue";
import {
DateFormatter,
endOfWeek,
startOfWeek,
isSameDay,
isSameMonth,
isToday,
type DateDuration,
type DateValue,
} from "@internationalized/date";
import {
calendarHeading,
calendarRange,
calendarRows,
calendarWeekdays,
} from "../date/calendar";
import {
calendarGridKey,
useCalendar,
useCalendarGrid,
type CalendarCellState,
} from "./context";
/** Default chevrons ported from ce90ea3 icons.tsx, Apache-2.0. */
export function calendarChevron(
previous = false,
className = "hv-calendar__nav-button-icon",
) {
return h(
"svg",
{
class: className,
"aria-hidden": "true",
role: "presentation",
fill: "none",
width: 16,
height: 16,
viewBox: "0 0 16 16",
},
[
h("path", {
d: previous
? "M10.53 2.97a.75.75 0 0 1 0 1.06L6.56 8l3.97 3.97a.75.75 0 1 1-1.06 1.06l-4.5-4.5a.75.75 0 0 1 0-1.06l4.5-4.5a.75.75 0 0 1 1.06 0"
: "M5.47 2.97a.75.75 0 0 1 1.06 0l4.5 4.5a.75.75 0 0 1 0 1.06l-4.5 4.5a.75.75 0 1 1-1.06-1.06L9.44 8 5.47 4.03a.75.75 0 0 1 0-1.06Z",
fill: "currentColor",
"fill-rule": "evenodd",
"clip-rule": "evenodd",
}),
],
);
}
function staticPart(
name: string,
tag: string,
className: string,
slot: string,
) {
return defineComponent({
name,
inheritAttrs: false,
props: { as: { type: String, default: tag } },
setup(props, { attrs, slots }) {
useCalendar();
return () =>
h(
props.as,
mergeProps(
{
class: className,
"data-slot": slot,
"aria-hidden":
slot === "calendar-cell-indicator" ? "true" : undefined,
},
attrs,
),
slots.default?.(),
);
},
});
}
export const CalendarHeader = staticPart(
"CalendarHeader",
"header",
"hv-calendar__header",
"calendar-header",
);
export const CalendarHeaderCell = staticPart(
"CalendarHeaderCell",
"th",
"hv-calendar__header-cell",
"calendar-header-cell",
);
export const CalendarCellIndicator = staticPart(
"CalendarCellIndicator",
"span",
"hv-calendar__cell-indicator",
"calendar-cell-indicator",
);
export const CalendarHeading = defineComponent({
name: "CalendarHeading",
inheritAttrs: false,
props: {
as: { type: String, default: "h2" },
offset: Object as PropType<DateDuration>,
format: Object as PropType<Intl.DateTimeFormatOptions>,
},
setup(props, { attrs, slots }) {
const ctx = useCalendar(),
id = `hv-calendar-heading-${useId()}`;
return () =>
h(
props.as,
mergeProps(
{
id,
class: "hv-calendar__heading",
"data-slot": "calendar-heading",
"aria-live": "polite",
"aria-atomic": "true",
},
attrs,
),
slots.default?.() ??
calendarHeading(
ctx.anchor.value,
ctx.options.value,
props.offset,
props.format,
),
);
},
});
export const CalendarNavButton = defineComponent({
name: "CalendarNavButton",
inheritAttrs: false,
props: {
slot: { type: String as PropType<"previous" | "next">, default: "next" },
isDisabled: Boolean,
disabled: Boolean,
},
setup(props, { attrs, slots }) {
const ctx = useCalendar();
return () => {
const direction = props.slot === "previous" ? -1 : 1;
const disabled =
props.isDisabled || props.disabled || ctx.pageDisabled(direction);
return h(
"button",
mergeProps(
{
type: "button",
class: "hv-calendar__nav-button",
"aria-label": direction === -1 ? "Previous" : "Next",
},
attrs,
{
"data-slot": "calendar-nav-button",
disabled,
tabindex: ctx.yearOpen.value ? -1 : attrs.tabindex,
"data-disabled": disabled || undefined,
onClick: (event: MouseEvent) => {
if (!event.defaultPrevented && !disabled) ctx.page(direction);
},
},
),
slots.default?.() ?? [calendarChevron(direction === -1)],
);
};
},
});
export const CalendarGrid = defineComponent({
name: "CalendarGrid",
inheritAttrs: false,
props: {
offset: Object as PropType<DateDuration>,
weekdayStyle: {
type: String as PropType<"narrow" | "short" | "long">,
default: "short",
},
},
setup(props, { attrs, slots }) {
const ctx = useCalendar();
const grid = computed(() => ({
...calendarRows(ctx.anchor.value, ctx.options.value, props.offset),
weekdays: calendarWeekdays(
ctx.anchor.value,
ctx.options.value,
props.weekdayStyle,
),
}));
provide(calendarGridKey, grid);
return () =>
h(
"table",
mergeProps(
{
class: "hv-calendar__grid",
role: "grid",
"aria-label": calendarHeading(
ctx.anchor.value,
ctx.options.value,
props.offset,
),
"aria-readonly": ctx.readOnly.value || undefined,
"aria-invalid": ctx.invalid.value || undefined,
"aria-multiselectable": ctx.multiple.value || undefined,
},
attrs,
{
"data-slot": "calendar-grid",
"aria-hidden": ctx.yearOpen.value || undefined,
inert: ctx.yearOpen.value ? "" : undefined,
},
),
slots.default?.(),
);
},
});
export const CalendarGridHeader = defineComponent({
name: "CalendarGridHeader",
inheritAttrs: false,
slots: Object as SlotsType<{
default?: (state: { day: string; index: number }) => VNodeChild;
}>,
setup(_props, { attrs, slots }) {
const grid = useCalendarGrid();
return () =>
h(
"thead",
mergeProps(
{
class: "hv-calendar__grid-header",
"data-slot": "calendar-grid-header",
},
attrs,
),
[
h(
"tr",
grid.value.weekdays.map(
(day, index) =>
slots.default?.({ day, index }) ??
h(CalendarHeaderCell, { key: index }, () => day),
),
),
],
);
},
});
export const CalendarGridBody = defineComponent({
name: "CalendarGridBody",
inheritAttrs: false,
slots: Object as SlotsType<{
default?: (state: { date: DateValue }) => VNodeChild;
}>,
setup(_props, { attrs, slots }) {
const grid = useCalendarGrid();
return () =>
h(
"tbody",
mergeProps(
{
class: "hv-calendar__grid-body",
"data-slot": "calendar-grid-body",
},
attrs,
),
grid.value.rows.map((row, index) =>
h(
"tr",
{ key: index, class: "hv-calendar__grid-row" },
row.map((date, index) =>
date
? (slots.default?.({ date: date.copy() }) ??
h(CalendarCell, { date, key: date.toString() }))
: h("td", { key: `empty-${index}`, "aria-hidden": "true" }),
),
),
),
);
},
});
export const CalendarCell = defineComponent({
name: "CalendarCell",
inheritAttrs: false,
props: { date: { type: Object as PropType<DateValue>, required: true } },
slots: Object as SlotsType<{
default?: (state: CalendarCellState) => VNodeChild;
}>,
setup(props, { attrs, slots, expose }) {
const ctx = useCalendar(),
grid = useCalendarGrid();
const hovered = ref(false),
pressed = ref(false),
focused = ref(false),
focusVisible = ref(false);
let element: HTMLButtonElement | undefined;
expose({
get element() {
return element;
},
focus: () => element?.focus(),
});
const state = computed<CalendarCellState>(() => {
const range = calendarRange(ctx.anchor.value, ctx.options.value);
const outside =
props.date.compare(range.start) < 0 ||
props.date.compare(range.end) > 0;
const outsideMonth =
range.unit === "months" && !isSameMonth(props.date, grid.value.month);
return {
date: props.date.copy(),
formattedDate: props.date.day.toLocaleString(ctx.options.value.locale),
isSelected: ctx.selected(props.date),
isUnavailable: ctx.unavailable(props.date),
isDisabled: outside || outsideMonth || ctx.disabledDay(props.date),
isOutsideMonth: outsideMonth,
isOutsideVisibleRange: outside,
isToday: isToday(props.date, ctx.timeZone.value),
isFocused: focused.value,
isHovered: hovered.value,
isPressed: pressed.value,
isFocusVisible: focusVisible.value,
};
});
watch(
() => state.value.isDisabled || ctx.readOnly.value,
(value) => {
if (value) {
hovered.value = false;
pressed.value = false;
}
},
);
function keydown(event: KeyboardEvent) {
if (
event.defaultPrevented ||
event.isComposing ||
(event.repeat && (event.key === " " || event.key === "Enter")) ||
state.value.isDisabled ||
ctx.yearOpen.value ||
event.metaKey ||
event.ctrlKey ||
event.altKey
)
return;
const date = props.date;
const sign = ctx.dir.value === "rtl" ? -1 : 1;
let target: DateValue;
let step = 1;
switch (event.key) {
case "ArrowLeft":
step = -sign;
target = date.add({ days: step });
break;
case "ArrowRight":
step = sign;
target = date.add({ days: step });
break;
case "ArrowUp":
step = -7;
target = date.add({ days: step });
break;
case "ArrowDown":
step = 7;
target = date.add({ days: step });
break;
case "Home":
target = startOfWeek(
date,
ctx.options.value.locale,
ctx.options.value.firstDayOfWeek,
);
break;
case "End":
target = endOfWeek(
date,
ctx.options.value.locale,
ctx.options.value.firstDayOfWeek,
);
step = -1;
break;
case "PageUp":
step = -1;
target = date.subtract(event.shiftKey ? { years: 1 } : { months: 1 });
break;
case "PageDown":
target = date.add(event.shiftKey ? { years: 1 } : { months: 1 });
break;
case "Enter":
case " ":
event.preventDefault();
pressed.value = true;
ctx.request(date);
return;
default:
return;
}
event.preventDefault();
event.stopPropagation();
if (target.compare(ctx.min.value) < 0) target = ctx.min.value;
if (target.compare(ctx.max.value) > 0) target = ctx.max.value;
// Bounds are finite and calendar arithmetic may saturate at year limits.
while (
target.compare(ctx.min.value) >= 0 &&
target.compare(ctx.max.value) <= 0
) {
if (!ctx.disabledDay(target)) {
ctx.focusDate(target, true);
return;
}
const next = target.add({ days: step });
if (isSameDay(next, target)) return;
target = next;
}
}
return () => {
const value = state.value;
const label = new DateFormatter(ctx.options.value.locale, {
dateStyle: "full",
timeZone: "UTC",
}).format(props.date.toDate("UTC"));
return h(
"td",
{
role: "gridcell",
"aria-selected": value.isSelected,
"aria-hidden": value.isOutsideMonth || undefined,
"aria-disabled": value.isDisabled || value.isUnavailable || undefined,
},
[
h(
"button",
mergeProps(
{
type: "button",
class: "hv-calendar__cell",
tabindex:
!ctx.yearOpen.value &&
!value.isDisabled &&
ctx.tabStop.value &&
isSameDay(props.date, ctx.tabStop.value) &&
!value.isOutsideMonth
? 0
: -1,
"aria-label": label,
},
attrs,
{
ref: (node: unknown) => {
element = node as HTMLButtonElement | undefined;
},
"data-slot": "calendar-cell",
"data-date": props.date.toString(),
disabled: value.isDisabled,
"data-selected": value.isSelected || undefined,
"data-today": value.isToday || undefined,
"data-disabled": value.isDisabled || undefined,
"data-unavailable": value.isUnavailable || undefined,
"data-outside-month": value.isOutsideMonth || undefined,
"aria-disabled":
value.isDisabled || value.isUnavailable || undefined,
onKeydown: keydown,
onClick: (event: MouseEvent) => {
if (
!event.defaultPrevented &&
!ctx.yearOpen.value &&
!value.isDisabled
) {
if (!focused.value) ctx.focusDate(props.date);
ctx.request(props.date);
}
},
"data-focused": focused.value || undefined,
"data-focus-visible": focusVisible.value || undefined,
"data-hovered": hovered.value || undefined,
"data-pressed": pressed.value || undefined,
onPointerenter: () => {
if (!value.isDisabled) hovered.value = true;
},
onPointerleave: () => {
hovered.value = false;
pressed.value = false;
},
onPointerdown: (event: PointerEvent) => {
if (
!event.defaultPrevented &&
!value.isDisabled &&
!ctx.readOnly.value
)
pressed.value = true;
},
onPointerup: () => {
pressed.value = false;
},
onKeyup: () => {
pressed.value = false;
},
onFocus: (event: FocusEvent) => {
focused.value = true;
focusVisible.value = (
event.currentTarget as HTMLElement
).matches(":focus-visible");
if (!value.isDisabled && !ctx.yearOpen.value)
ctx.focusDate(props.date);
},
onBlur: () => {
focused.value = false;
focusVisible.value = false;
pressed.value = false;
},
},
),
slots.default?.(value) ?? value.formattedDate,
),
],
);
};
},
});