feat: migrate Calendar and calendar year picker
This commit is contained in:
@@ -0,0 +1,393 @@
|
||||
<script setup lang="ts" generic="M extends CalendarSelectionMode = 'single'">
|
||||
import {
|
||||
computed,
|
||||
getCurrentInstance,
|
||||
nextTick,
|
||||
onMounted,
|
||||
onBeforeUnmount,
|
||||
provide,
|
||||
shallowRef,
|
||||
useAttrs,
|
||||
useId,
|
||||
watch,
|
||||
} from "vue";
|
||||
import {
|
||||
CalendarDate,
|
||||
GregorianCalendar,
|
||||
getLocalTimeZone,
|
||||
today,
|
||||
toCalendar,
|
||||
toCalendarDate,
|
||||
isSameDay,
|
||||
type DateValue,
|
||||
} from "@internationalized/date";
|
||||
import { useChoiceValue } from "../choice/shared";
|
||||
import {
|
||||
copyDateValue,
|
||||
copyDateValues,
|
||||
dateForLocale,
|
||||
dateValueKey,
|
||||
} from "../date/value";
|
||||
import {
|
||||
calendarRange,
|
||||
calendarDuration,
|
||||
calendarHeading,
|
||||
} from "../date/calendar";
|
||||
import { useInheritedDisabled } from "../field/disabled";
|
||||
import { useConfig } from "../../providers/context";
|
||||
import {
|
||||
calendarKey,
|
||||
type CalendarModel,
|
||||
type CalendarOptions,
|
||||
type CalendarSelectionMode,
|
||||
type CalendarContext,
|
||||
} from "./context";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
const props = defineProps<CalendarOptions<M>>();
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [value: CalendarModel<M>];
|
||||
change: [value: CalendarModel<M>];
|
||||
"update:focusedValue": [value: DateValue];
|
||||
focusChange: [value: DateValue];
|
||||
"update:isYearPickerOpen": [value: boolean];
|
||||
yearPickerOpenChange: [value: boolean];
|
||||
}>();
|
||||
defineSlots<{
|
||||
default?: (state: {
|
||||
value: CalendarModel<M>;
|
||||
isDisabled: boolean;
|
||||
isReadOnly: boolean;
|
||||
isInvalid: boolean;
|
||||
focusedValue: DateValue;
|
||||
visibleRange: { start: DateValue; end: DateValue };
|
||||
isYearPickerOpen: boolean;
|
||||
}) => unknown;
|
||||
}>();
|
||||
const attrs = useAttrs(),
|
||||
instance = getCurrentInstance()!,
|
||||
config = useConfig();
|
||||
const root = shallowRef<HTMLElement>(),
|
||||
trigger = shallowRef<HTMLElement>();
|
||||
const headingId = `hv-calendar-${useId()}-heading`;
|
||||
const locale = computed(() => props.locale ?? config?.locale.value ?? "en-US");
|
||||
const dir = computed(() => props.dir ?? config?.dir.value ?? "ltr");
|
||||
const timeZone = computed(() => props.timeZone ?? getLocalTimeZone());
|
||||
const disabled = useInheritedDisabled(() => props.isDisabled || props.disabled);
|
||||
const readOnly = computed(() => !!props.isReadOnly);
|
||||
const multiple = computed(() => props.selectionMode === "multiple");
|
||||
const invalid = computed(() => !!props.isInvalid);
|
||||
const options = computed(() => ({
|
||||
locale: locale.value,
|
||||
firstDayOfWeek: props.firstDayOfWeek,
|
||||
visibleDuration: props.visibleDuration,
|
||||
weeksInMonth: props.weeksInMonth,
|
||||
}));
|
||||
type Value = DateValue | DateValue[] | null;
|
||||
const copy = (value: Value | undefined): Value =>
|
||||
Array.isArray(value) ? copyDateValues(value) : copyDateValue(value ?? null);
|
||||
const has = (key: string) => Object.hasOwn(instance.vnode.props ?? {}, key);
|
||||
const model = useChoiceValue<Value>(
|
||||
() =>
|
||||
copy(
|
||||
has("modelValue") || has("model-value") ? props.modelValue : props.value,
|
||||
),
|
||||
() => copy(props.defaultValue),
|
||||
["modelValue", "model-value", "value"],
|
||||
(value) => {
|
||||
emit("update:modelValue", copy(value) as CalendarModel<M>);
|
||||
emit("change", copy(value) as CalendarModel<M>);
|
||||
},
|
||||
);
|
||||
const selectedValues = computed(() => {
|
||||
const value = model.value.value;
|
||||
return Array.isArray(value) ? value : value ? [value] : [];
|
||||
});
|
||||
const initial = copyDateValue(
|
||||
props.defaultFocusedValue ?? selectedValues.value[0] ?? today(timeZone.value),
|
||||
);
|
||||
const focusModel = useChoiceValue<DateValue>(
|
||||
() => copyDateValue(props.focusedValue ?? initial),
|
||||
() => copyDateValue(initial),
|
||||
["focusedValue", "focused-value"],
|
||||
(value) => {
|
||||
emit("update:focusedValue", value.copy());
|
||||
emit("focusChange", value.copy());
|
||||
},
|
||||
);
|
||||
const focus = computed(() =>
|
||||
toCalendarDate(dateForLocale(focusModel.value.value, locale.value)),
|
||||
);
|
||||
const min = computed(() =>
|
||||
toCalendarDate(
|
||||
dateForLocale(props.minValue ?? new CalendarDate(1900, 1, 1), locale.value),
|
||||
),
|
||||
);
|
||||
const max = computed(() =>
|
||||
toCalendarDate(
|
||||
dateForLocale(
|
||||
props.maxValue ?? new CalendarDate(2099, 12, 31),
|
||||
locale.value,
|
||||
),
|
||||
),
|
||||
);
|
||||
function aligned(date: typeof focus.value) {
|
||||
const { unit, count } = calendarDuration(props.visibleDuration);
|
||||
const alignment = props.selectionAlignment ?? "center";
|
||||
const amount =
|
||||
alignment === "start"
|
||||
? 0
|
||||
: alignment === "end"
|
||||
? count - 1
|
||||
: Math.floor((count - 1) / 2);
|
||||
return date.subtract({ [unit]: amount });
|
||||
}
|
||||
const anchor = shallowRef(aligned(focus.value));
|
||||
const visible = computed(() => calendarRange(anchor.value, options.value));
|
||||
const yearModel = useChoiceValue(
|
||||
() => !!props.isYearPickerOpen,
|
||||
() => !!props.defaultYearPickerOpen,
|
||||
["isYearPickerOpen", "is-year-picker-open"],
|
||||
(value) => {
|
||||
emit("update:isYearPickerOpen", value);
|
||||
emit("yearPickerOpenChange", value);
|
||||
},
|
||||
);
|
||||
const yearOpen = computed(() => yearModel.value.value);
|
||||
function disabledDay(value: DateValue) {
|
||||
return (
|
||||
disabled.value ||
|
||||
toCalendarDate(value).compare(min.value) < 0 ||
|
||||
toCalendarDate(value).compare(max.value) > 0 ||
|
||||
!!props.isDateDisabled?.(value.copy())
|
||||
);
|
||||
}
|
||||
const tabStop = computed(() => {
|
||||
const range = visible.value;
|
||||
if (
|
||||
!disabledDay(focus.value) &&
|
||||
focus.value.compare(range.start) >= 0 &&
|
||||
focus.value.compare(range.end) <= 0
|
||||
)
|
||||
return focus.value;
|
||||
let date = range.start;
|
||||
while (date.compare(range.end) <= 0) {
|
||||
if (!disabledDay(date)) return date;
|
||||
const next = date.add({ days: 1 });
|
||||
if (isSameDay(date, next)) break;
|
||||
date = next;
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
const unavailable = (date: DateValue) =>
|
||||
!!props.isDateUnavailable?.(date.copy());
|
||||
const selected = (date: DateValue) =>
|
||||
selectedValues.value.some((value) => isSameDay(value, date));
|
||||
function request(value: DateValue) {
|
||||
if (disabledDay(value) || unavailable(value) || readOnly.value) return;
|
||||
const fallback = Array.isArray(props.defaultValue)
|
||||
? props.defaultValue[0]
|
||||
: props.defaultValue;
|
||||
const original =
|
||||
selectedValues.value[0] ??
|
||||
fallback ??
|
||||
toCalendarDate(toCalendar(focus.value, new GregorianCalendar()));
|
||||
// Preserve the public model's calendar, date class, time and zone.
|
||||
const day = toCalendar(value, original.calendar);
|
||||
const next = original.set({
|
||||
era: day.era,
|
||||
year: day.year,
|
||||
month: day.month,
|
||||
day: day.day,
|
||||
});
|
||||
if (props.selectionMode === "multiple") {
|
||||
const values = selectedValues.value;
|
||||
model.request(
|
||||
selected(value)
|
||||
? copyDateValues(values.filter((date) => !isSameDay(date, value)))
|
||||
: copyDateValues([...values, next]),
|
||||
);
|
||||
} else if (!selected(value)) model.request(next.copy());
|
||||
}
|
||||
function focusDate(date: DateValue, moveDOM = false) {
|
||||
if (disabledDay(date)) return;
|
||||
const original = focusModel.value.value;
|
||||
const converted = toCalendar(date, original.calendar);
|
||||
if (!isSameDay(original, converted)) focusModel.request(converted.copy());
|
||||
const active = root.value?.ownerDocument.activeElement;
|
||||
const restoreControlledFocus =
|
||||
!!active &&
|
||||
root.value?.contains(active) &&
|
||||
active.getAttribute("data-slot") === "calendar-cell";
|
||||
if (moveDOM || restoreControlledFocus)
|
||||
void nextTick(() => {
|
||||
if (yearOpen.value) return;
|
||||
const iso = (tabStop.value ?? focus.value).toString();
|
||||
root.value
|
||||
?.querySelector<HTMLElement>(
|
||||
`[data-slot="calendar-cell"][data-date="${iso}"]:not([data-outside-month])`,
|
||||
)
|
||||
?.focus();
|
||||
});
|
||||
}
|
||||
watch(
|
||||
() => dateValueKey(focus.value),
|
||||
() => {
|
||||
const active = root.value?.ownerDocument.activeElement;
|
||||
const retainFocus =
|
||||
!!active &&
|
||||
root.value?.contains(active) &&
|
||||
active.getAttribute("data-slot") === "calendar-cell";
|
||||
if (
|
||||
focus.value.compare(visible.value.start) < 0 ||
|
||||
focus.value.compare(visible.value.end) > 0
|
||||
)
|
||||
anchor.value = aligned(focus.value);
|
||||
if (retainFocus)
|
||||
void nextTick(() => {
|
||||
if (!yearOpen.value)
|
||||
root.value
|
||||
?.querySelector<HTMLElement>(
|
||||
`[data-slot="calendar-cell"][tabindex="0"]`,
|
||||
)
|
||||
?.focus();
|
||||
});
|
||||
},
|
||||
{ flush: "sync" },
|
||||
);
|
||||
watch(
|
||||
[locale, () => props.visibleDuration, () => props.firstDayOfWeek],
|
||||
() => {
|
||||
anchor.value = aligned(focus.value);
|
||||
},
|
||||
{ deep: true },
|
||||
);
|
||||
watch(
|
||||
() => selectedValues.value.map(dateValueKey).join("|"),
|
||||
() => {
|
||||
if (
|
||||
!has("focusedValue") &&
|
||||
!has("focused-value") &&
|
||||
selectedValues.value[0]
|
||||
)
|
||||
focusDate(selectedValues.value[0]);
|
||||
},
|
||||
);
|
||||
function pageStep(direction: -1 | 1) {
|
||||
const { unit, count } = calendarDuration(props.visibleDuration);
|
||||
return { [unit]: direction * (props.pageBehavior === "single" ? 1 : count) };
|
||||
}
|
||||
function pageDisabled(direction: -1 | 1) {
|
||||
if (disabled.value || yearOpen.value) return true;
|
||||
const range = calendarRange(
|
||||
anchor.value.add(pageStep(direction)),
|
||||
options.value,
|
||||
);
|
||||
return range.end.compare(min.value) < 0 || range.start.compare(max.value) > 0;
|
||||
}
|
||||
let pageRevision = 0;
|
||||
onBeforeUnmount(() => {
|
||||
pageRevision++;
|
||||
});
|
||||
function page(direction: -1 | 1) {
|
||||
if (pageDisabled(direction)) return;
|
||||
const nextAnchor = anchor.value.add(pageStep(direction));
|
||||
const range = calendarRange(nextAnchor, options.value);
|
||||
let date = focus.value.add(pageStep(direction));
|
||||
if (date.compare(min.value) < 0) date = min.value;
|
||||
if (date.compare(max.value) > 0) date = max.value;
|
||||
// Disabled target days must not make an otherwise navigable month inert.
|
||||
if (disabledDay(date)) {
|
||||
let candidate = range.start;
|
||||
while (candidate.compare(range.end) <= 0 && disabledDay(candidate)) {
|
||||
const next = candidate.add({ days: 1 });
|
||||
if (isSameDay(candidate, next)) return;
|
||||
candidate = next;
|
||||
}
|
||||
if (candidate.compare(range.end) > 0) return;
|
||||
date = candidate;
|
||||
}
|
||||
focusDate(date);
|
||||
const revision = ++pageRevision;
|
||||
void nextTick(() => {
|
||||
if (revision === pageRevision && isSameDay(focus.value, date))
|
||||
anchor.value = nextAnchor;
|
||||
});
|
||||
}
|
||||
function setYearOpen(value: boolean, restore = false) {
|
||||
if (disabled.value) return;
|
||||
yearModel.request(value);
|
||||
if (!value && restore)
|
||||
void nextTick(() => {
|
||||
if (!yearOpen.value) trigger.value?.focus();
|
||||
});
|
||||
}
|
||||
provide(calendarKey, {
|
||||
root,
|
||||
trigger,
|
||||
focus,
|
||||
anchor,
|
||||
options,
|
||||
min,
|
||||
max,
|
||||
disabled,
|
||||
tabStop,
|
||||
readOnly,
|
||||
multiple,
|
||||
invalid,
|
||||
dir,
|
||||
timeZone,
|
||||
yearOpen,
|
||||
headingId,
|
||||
selected,
|
||||
disabledDay,
|
||||
unavailable,
|
||||
request,
|
||||
focusDate,
|
||||
page,
|
||||
pageDisabled,
|
||||
setYearOpen,
|
||||
} satisfies CalendarContext);
|
||||
onMounted(() => {
|
||||
if (props.autoFocus && tabStop.value) focusDate(tabStop.value, true);
|
||||
});
|
||||
defineExpose({
|
||||
get element() {
|
||||
return root.value;
|
||||
},
|
||||
focus: () => {
|
||||
if (tabStop.value) focusDate(tabStop.value, true);
|
||||
},
|
||||
});
|
||||
</script>
|
||||
<template>
|
||||
<component
|
||||
:is="as ?? 'div'"
|
||||
ref="root"
|
||||
v-bind="attrs"
|
||||
class="hv-calendar"
|
||||
:class="{
|
||||
'hv-calendar--week-view': visible.unit === 'weeks',
|
||||
'hv-calendar--day-view': visible.unit === 'days',
|
||||
}"
|
||||
role="group"
|
||||
:aria-label="
|
||||
(attrs['aria-label'] as string | undefined) ??
|
||||
(attrs['aria-labelledby'] ? undefined : calendarHeading(anchor, options))
|
||||
"
|
||||
:dir="dir"
|
||||
:data-slot="'calendar'"
|
||||
:data-disabled="disabled || undefined"
|
||||
:aria-disabled="disabled || undefined"
|
||||
:aria-invalid="isInvalid || undefined"
|
||||
>
|
||||
<slot
|
||||
:value="copy(model.value.value) as CalendarModel<M>"
|
||||
:is-disabled="disabled"
|
||||
:is-read-only="readOnly"
|
||||
:is-invalid="invalid"
|
||||
:focused-value="focus"
|
||||
:visible-range="{ start: visible.start, end: visible.end }"
|
||||
:is-year-picker-open="yearOpen"
|
||||
/>
|
||||
</component>
|
||||
</template>
|
||||
@@ -0,0 +1,122 @@
|
||||
import {
|
||||
inject,
|
||||
type ComputedRef,
|
||||
type InjectionKey,
|
||||
type ShallowRef,
|
||||
} from "vue";
|
||||
import type { CalendarDate, DateValue } from "@internationalized/date";
|
||||
import type {
|
||||
CalendarDuration,
|
||||
CalendarViewOptions,
|
||||
CalendarWeekday,
|
||||
} from "../date/calendar";
|
||||
export type CalendarSelectionMode = "single" | "multiple";
|
||||
export type CalendarModel<M extends CalendarSelectionMode = "single"> =
|
||||
M extends "multiple" ? DateValue[] | null : DateValue | null;
|
||||
export interface CalendarOptions<M extends CalendarSelectionMode = "single"> {
|
||||
modelValue?: CalendarModel<M>;
|
||||
value?: CalendarModel<M>;
|
||||
defaultValue?: CalendarModel<M>;
|
||||
selectionMode?: M;
|
||||
focusedValue?: DateValue;
|
||||
defaultFocusedValue?: DateValue;
|
||||
minValue?: DateValue;
|
||||
maxValue?: DateValue;
|
||||
visibleDuration?: CalendarDuration;
|
||||
firstDayOfWeek?: CalendarWeekday;
|
||||
weeksInMonth?: number;
|
||||
pageBehavior?: "visible" | "single";
|
||||
selectionAlignment?: "start" | "center" | "end";
|
||||
isDateUnavailable?: (date: DateValue) => boolean;
|
||||
isDateDisabled?: (date: DateValue) => boolean;
|
||||
isDisabled?: boolean;
|
||||
disabled?: boolean;
|
||||
isReadOnly?: boolean;
|
||||
isInvalid?: boolean;
|
||||
autoFocus?: boolean;
|
||||
isYearPickerOpen?: boolean;
|
||||
defaultYearPickerOpen?: boolean;
|
||||
locale?: string;
|
||||
dir?: "ltr" | "rtl";
|
||||
timeZone?: string;
|
||||
as?: string;
|
||||
}
|
||||
export interface CalendarCellState {
|
||||
date: DateValue;
|
||||
formattedDate: string;
|
||||
isSelected: boolean;
|
||||
isUnavailable: boolean;
|
||||
isDisabled: boolean;
|
||||
isOutsideMonth: boolean;
|
||||
isOutsideVisibleRange: boolean;
|
||||
isToday: boolean;
|
||||
isFocused: boolean;
|
||||
isFocusVisible: boolean;
|
||||
isHovered: boolean;
|
||||
isPressed: boolean;
|
||||
}
|
||||
export interface CalendarContext {
|
||||
root: ShallowRef<HTMLElement | undefined>;
|
||||
trigger: ShallowRef<HTMLElement | undefined>;
|
||||
focus: ComputedRef<CalendarDate>;
|
||||
anchor: ShallowRef<CalendarDate>;
|
||||
options: ComputedRef<CalendarViewOptions>;
|
||||
min: ComputedRef<CalendarDate>;
|
||||
max: ComputedRef<CalendarDate>;
|
||||
tabStop: ComputedRef<CalendarDate | undefined>;
|
||||
disabled: ComputedRef<boolean>;
|
||||
readOnly: ComputedRef<boolean>;
|
||||
multiple: ComputedRef<boolean>;
|
||||
invalid: ComputedRef<boolean>;
|
||||
dir: ComputedRef<"ltr" | "rtl">;
|
||||
timeZone: ComputedRef<string>;
|
||||
yearOpen: ComputedRef<boolean>;
|
||||
headingId: string;
|
||||
selected: (value: DateValue) => boolean;
|
||||
disabledDay: (value: DateValue) => boolean;
|
||||
unavailable: (value: DateValue) => boolean;
|
||||
request: (value: DateValue) => void;
|
||||
focusDate: (value: DateValue, moveDOM?: boolean) => void;
|
||||
page: (direction: -1 | 1) => void;
|
||||
pageDisabled: (direction: -1 | 1) => boolean;
|
||||
setYearOpen: (value: boolean, restore?: boolean) => void;
|
||||
}
|
||||
export const calendarKey: InjectionKey<CalendarContext> = Symbol("hv-calendar");
|
||||
export function useCalendar() {
|
||||
const value = inject(calendarKey, undefined);
|
||||
if (!value) throw new Error("Calendar parts require Calendar.");
|
||||
return value;
|
||||
}
|
||||
export const calendarGridKey: InjectionKey<
|
||||
ComputedRef<{
|
||||
rows: (CalendarDate | null)[][];
|
||||
month: CalendarDate;
|
||||
weekdays: string[];
|
||||
}>
|
||||
> = Symbol("hv-calendar-grid");
|
||||
export function useCalendarGrid() {
|
||||
const value = inject(calendarGridKey, undefined);
|
||||
if (!value) throw new Error("Calendar grid parts require CalendarGrid.");
|
||||
return value;
|
||||
}
|
||||
export interface CalendarYearState {
|
||||
year: number;
|
||||
date: CalendarDate;
|
||||
formattedYear: string;
|
||||
isSelected: boolean;
|
||||
isCurrentYear: boolean;
|
||||
isOpen: boolean;
|
||||
selectYear: () => void;
|
||||
}
|
||||
export const calendarYearKey: InjectionKey<{
|
||||
entries: ComputedRef<CalendarDate[]>;
|
||||
active: ShallowRef<string>;
|
||||
label: (date: CalendarDate) => string;
|
||||
state: (date: CalendarDate) => CalendarYearState;
|
||||
select: (date: CalendarDate) => void;
|
||||
}> = Symbol("hv-calendar-years");
|
||||
export function useCalendarYears() {
|
||||
const value = inject(calendarYearKey, undefined);
|
||||
if (!value) throw new Error("Year cells require CalendarYearPickerGrid.");
|
||||
return value;
|
||||
}
|
||||
@@ -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,
|
||||
),
|
||||
],
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,422 @@
|
||||
import {
|
||||
computed,
|
||||
defineComponent,
|
||||
h,
|
||||
mergeProps,
|
||||
nextTick,
|
||||
onBeforeUnmount,
|
||||
onMounted,
|
||||
provide,
|
||||
shallowRef,
|
||||
watch,
|
||||
type PropType,
|
||||
type SlotsType,
|
||||
type VNodeChild,
|
||||
} from "vue";
|
||||
import { useResizeObserver } from "@vueuse/core";
|
||||
import {
|
||||
DateFormatter,
|
||||
today,
|
||||
type CalendarDate,
|
||||
type DateDuration,
|
||||
} from "@internationalized/date";
|
||||
import { calendarHeading, calendarYears } from "../date/calendar";
|
||||
import { dateForLocale } from "../date/value";
|
||||
import {
|
||||
calendarYearKey,
|
||||
useCalendar,
|
||||
useCalendarYears,
|
||||
type CalendarYearState,
|
||||
} from "./context";
|
||||
import { calendarChevron } from "./parts";
|
||||
|
||||
export interface CalendarYearPickerTriggerState {
|
||||
isOpen: boolean;
|
||||
monthYear: string;
|
||||
toggle: () => void;
|
||||
}
|
||||
export const CalendarYearPickerTrigger = defineComponent({
|
||||
name: "CalendarYearPickerTrigger",
|
||||
inheritAttrs: false,
|
||||
props: { isDisabled: Boolean, disabled: Boolean },
|
||||
slots: Object as SlotsType<{
|
||||
default?: (state: CalendarYearPickerTriggerState) => VNodeChild;
|
||||
}>,
|
||||
setup(props, { attrs, slots }) {
|
||||
const ctx = useCalendar();
|
||||
const disabled = computed(
|
||||
() => props.isDisabled || props.disabled || ctx.disabled.value,
|
||||
);
|
||||
const toggle = () => {
|
||||
if (!disabled.value) ctx.setYearOpen(!ctx.yearOpen.value);
|
||||
};
|
||||
return () => {
|
||||
const monthYear = calendarHeading(ctx.anchor.value, ctx.options.value);
|
||||
return h(
|
||||
"button",
|
||||
mergeProps(
|
||||
{
|
||||
type: "button",
|
||||
class: "hv-calendar-year-picker__trigger",
|
||||
"aria-label": `${monthYear}, year selector`,
|
||||
},
|
||||
attrs,
|
||||
{
|
||||
ref: (node: unknown) => {
|
||||
ctx.trigger.value = node as HTMLElement | undefined;
|
||||
},
|
||||
disabled: disabled.value,
|
||||
"data-slot": "calendar-year-picker-trigger",
|
||||
"data-open": ctx.yearOpen.value || undefined,
|
||||
"aria-expanded": ctx.yearOpen.value,
|
||||
"aria-controls": ctx.yearOpen.value
|
||||
? `${ctx.headingId}-years`
|
||||
: undefined,
|
||||
onClick: (event: MouseEvent) => {
|
||||
if (!event.defaultPrevented) toggle();
|
||||
},
|
||||
onKeydown: (event: KeyboardEvent) => {
|
||||
if (
|
||||
!event.defaultPrevented &&
|
||||
event.key === "Escape" &&
|
||||
ctx.yearOpen.value
|
||||
) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
ctx.setYearOpen(false, true);
|
||||
}
|
||||
},
|
||||
},
|
||||
),
|
||||
slots.default?.({ isOpen: ctx.yearOpen.value, monthYear, toggle }) ??
|
||||
monthYear,
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
export const CalendarYearPickerTriggerHeading = defineComponent({
|
||||
name: "CalendarYearPickerTriggerHeading",
|
||||
inheritAttrs: false,
|
||||
props: {
|
||||
as: { type: String, default: "span" },
|
||||
offset: Object as PropType<DateDuration>,
|
||||
format: Object as PropType<Intl.DateTimeFormatOptions>,
|
||||
},
|
||||
slots: Object as SlotsType<{
|
||||
default?: (state: CalendarYearPickerTriggerState) => VNodeChild;
|
||||
}>,
|
||||
setup(props, { attrs, slots }) {
|
||||
const ctx = useCalendar();
|
||||
return () => {
|
||||
const monthYear = calendarHeading(
|
||||
ctx.anchor.value,
|
||||
ctx.options.value,
|
||||
props.offset,
|
||||
props.format,
|
||||
);
|
||||
return h(
|
||||
props.as,
|
||||
mergeProps(
|
||||
{
|
||||
class: "hv-calendar-year-picker__trigger-heading",
|
||||
"data-slot": "calendar-year-picker-trigger-heading",
|
||||
},
|
||||
attrs,
|
||||
),
|
||||
slots.default?.({
|
||||
isOpen: ctx.yearOpen.value,
|
||||
monthYear,
|
||||
toggle: () => ctx.setYearOpen(!ctx.yearOpen.value),
|
||||
}) ?? monthYear,
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
export const CalendarYearPickerTriggerIndicator = defineComponent({
|
||||
name: "CalendarYearPickerTriggerIndicator",
|
||||
inheritAttrs: false,
|
||||
setup(_props, { attrs, slots }) {
|
||||
useCalendar();
|
||||
return () =>
|
||||
h(
|
||||
"span",
|
||||
mergeProps(
|
||||
{
|
||||
class: "hv-calendar-year-picker__trigger-indicator",
|
||||
"data-slot": "calendar-year-picker-trigger-indicator",
|
||||
"aria-hidden": "true",
|
||||
},
|
||||
attrs,
|
||||
),
|
||||
slots.default?.() ?? [calendarChevron(false, "")],
|
||||
);
|
||||
},
|
||||
});
|
||||
export const CalendarYearPickerGrid = defineComponent({
|
||||
name: "CalendarYearPickerGrid",
|
||||
inheritAttrs: false,
|
||||
props: {
|
||||
visibleYears: Number,
|
||||
format: Object as PropType<Intl.DateTimeFormatOptions>,
|
||||
},
|
||||
setup(props, { attrs, slots }) {
|
||||
const ctx = useCalendar();
|
||||
const element = shallowRef<HTMLElement>();
|
||||
const top = shallowRef(0),
|
||||
height = shallowRef(0),
|
||||
active = shallowRef("");
|
||||
let revision = 0;
|
||||
const all = computed(() => calendarYears(ctx.min.value, ctx.max.value));
|
||||
const entries = computed(() => {
|
||||
if (props.visibleYears == null) return all.value;
|
||||
const count = props.visibleYears;
|
||||
if (!Number.isSafeInteger(count) || count < 1)
|
||||
throw new RangeError("visibleYears requires a positive integer.");
|
||||
const index = all.value.findIndex(
|
||||
(date) =>
|
||||
date.year === ctx.focus.value.year &&
|
||||
date.era === ctx.focus.value.era,
|
||||
);
|
||||
const start = Math.max(
|
||||
0,
|
||||
Math.min(index - Math.floor(count / 2), all.value.length - count),
|
||||
);
|
||||
return all.value.slice(start, start + count);
|
||||
});
|
||||
const label = (date: CalendarDate) =>
|
||||
new DateFormatter(ctx.options.value.locale, {
|
||||
year: "numeric",
|
||||
...props.format,
|
||||
timeZone: "UTC",
|
||||
}).format(date.toDate("UTC"));
|
||||
function measure() {
|
||||
const grid = ctx.root.value?.querySelector<HTMLElement>(
|
||||
'[data-slot="calendar-grid"]',
|
||||
);
|
||||
if (grid) {
|
||||
top.value = grid.offsetTop;
|
||||
height.value = grid.offsetHeight;
|
||||
}
|
||||
}
|
||||
function focusYear(key: string) {
|
||||
const cell = element.value?.querySelector<HTMLElement>(
|
||||
`[data-year-key="${key}"]`,
|
||||
);
|
||||
cell?.focus({ preventScroll: true });
|
||||
cell?.scrollIntoView?.({ block: "nearest" });
|
||||
}
|
||||
const rootGrid = computed(() =>
|
||||
ctx.root.value?.querySelector<HTMLElement>('[data-slot="calendar-grid"]'),
|
||||
);
|
||||
useResizeObserver(rootGrid, measure);
|
||||
onMounted(measure);
|
||||
watch(
|
||||
() => ctx.yearOpen.value,
|
||||
async (open, old) => {
|
||||
const request = ++revision;
|
||||
await nextTick();
|
||||
if (request !== revision || !element.value) return;
|
||||
measure();
|
||||
if (open) {
|
||||
const date =
|
||||
entries.value.find(
|
||||
(date) =>
|
||||
date.year === ctx.focus.value.year &&
|
||||
date.era === ctx.focus.value.era,
|
||||
) ?? entries.value[0];
|
||||
if (date) {
|
||||
active.value = date.toString();
|
||||
focusYear(active.value);
|
||||
}
|
||||
} else if (
|
||||
old &&
|
||||
element.value.contains(element.value.ownerDocument.activeElement)
|
||||
)
|
||||
ctx.trigger.value?.focus();
|
||||
},
|
||||
{ immediate: true, flush: "post" },
|
||||
);
|
||||
watch(
|
||||
() => entries.value.map((date) => date.toString()).join("|"),
|
||||
() => {
|
||||
if (!entries.value.some((date) => date.toString() === active.value))
|
||||
active.value = entries.value[0]?.toString() ?? "";
|
||||
},
|
||||
);
|
||||
onBeforeUnmount(() => {
|
||||
revision++;
|
||||
});
|
||||
function select(date: CalendarDate) {
|
||||
if (!ctx.yearOpen.value || ctx.disabled.value) return;
|
||||
let target = ctx.focus.value.set({ era: date.era, year: date.year });
|
||||
if (target.compare(ctx.min.value) < 0) target = ctx.min.value;
|
||||
if (target.compare(ctx.max.value) > 0) target = ctx.max.value;
|
||||
ctx.focusDate(target, true);
|
||||
ctx.setYearOpen(false);
|
||||
}
|
||||
function state(date: CalendarDate): CalendarYearState {
|
||||
const current = dateForLocale(
|
||||
today(ctx.timeZone.value),
|
||||
ctx.options.value.locale,
|
||||
);
|
||||
return {
|
||||
year: date.year,
|
||||
date: date.copy(),
|
||||
formattedYear: label(date),
|
||||
isSelected:
|
||||
date.year === ctx.focus.value.year &&
|
||||
date.era === ctx.focus.value.era,
|
||||
isCurrentYear: date.year === current.year && date.era === current.era,
|
||||
isOpen: ctx.yearOpen.value,
|
||||
selectYear: () => select(date),
|
||||
};
|
||||
}
|
||||
provide(calendarYearKey, { entries, active, label, state, select });
|
||||
function keydown(event: KeyboardEvent) {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
event.isComposing ||
|
||||
ctx.disabled.value ||
|
||||
!ctx.yearOpen.value
|
||||
)
|
||||
return;
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
ctx.setYearOpen(false, true);
|
||||
return;
|
||||
}
|
||||
const index = entries.value.findIndex(
|
||||
(date) => date.toString() === active.value,
|
||||
);
|
||||
let next = index;
|
||||
const sign = ctx.dir.value === "rtl" ? -1 : 1;
|
||||
switch (event.key) {
|
||||
case "ArrowRight":
|
||||
next += sign;
|
||||
break;
|
||||
case "ArrowLeft":
|
||||
next -= sign;
|
||||
break;
|
||||
case "ArrowDown":
|
||||
next += 3;
|
||||
break;
|
||||
case "ArrowUp":
|
||||
next -= 3;
|
||||
break;
|
||||
case "Home":
|
||||
next = 0;
|
||||
break;
|
||||
case "End":
|
||||
next = entries.value.length - 1;
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const date =
|
||||
entries.value[Math.max(0, Math.min(next, entries.value.length - 1))];
|
||||
if (date) {
|
||||
active.value = date.toString();
|
||||
focusYear(active.value);
|
||||
}
|
||||
}
|
||||
return () =>
|
||||
h(
|
||||
"div",
|
||||
mergeProps(
|
||||
{
|
||||
id: `${ctx.headingId}-years`,
|
||||
class: "hv-calendar-year-picker__year-grid",
|
||||
role: "listbox",
|
||||
"aria-label": "Year",
|
||||
style: { top: `${top.value}px`, height: `${height.value}px` },
|
||||
},
|
||||
attrs,
|
||||
{
|
||||
ref: element,
|
||||
"data-slot": "calendar-year-picker-grid",
|
||||
"data-open": ctx.yearOpen.value || undefined,
|
||||
"aria-hidden": !ctx.yearOpen.value,
|
||||
inert: !ctx.yearOpen.value ? "" : undefined,
|
||||
onKeydown: keydown,
|
||||
},
|
||||
),
|
||||
slots.default?.(),
|
||||
);
|
||||
},
|
||||
});
|
||||
export const CalendarYearPickerGridBody = defineComponent({
|
||||
name: "CalendarYearPickerGridBody",
|
||||
slots: Object as SlotsType<{
|
||||
default?: (state: CalendarYearState) => VNodeChild;
|
||||
}>,
|
||||
setup(_props, { slots }) {
|
||||
const ctx = useCalendarYears();
|
||||
return () =>
|
||||
ctx.entries.value.map(
|
||||
(date) =>
|
||||
slots.default?.(ctx.state(date)) ??
|
||||
h(CalendarYearPickerCell, {
|
||||
date,
|
||||
year: date.year,
|
||||
key: date.toString(),
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
export const CalendarYearPickerCell = defineComponent({
|
||||
name: "CalendarYearPickerCell",
|
||||
inheritAttrs: false,
|
||||
props: {
|
||||
year: { type: Number, required: true },
|
||||
era: String,
|
||||
date: Object as PropType<CalendarDate>,
|
||||
},
|
||||
slots: Object as SlotsType<{
|
||||
default?: (state: CalendarYearState) => VNodeChild;
|
||||
}>,
|
||||
setup(props, { attrs, slots }) {
|
||||
const ctx = useCalendarYears(),
|
||||
calendar = useCalendar();
|
||||
return () => {
|
||||
const date =
|
||||
props.date ??
|
||||
ctx.entries.value.find(
|
||||
(date) =>
|
||||
date.year === props.year && (!props.era || date.era === props.era),
|
||||
);
|
||||
if (!date) return null;
|
||||
const state = ctx.state(date);
|
||||
return h(
|
||||
"button",
|
||||
mergeProps(
|
||||
{
|
||||
type: "button",
|
||||
role: "option",
|
||||
class: "hv-calendar-year-picker__year-cell",
|
||||
},
|
||||
attrs,
|
||||
{
|
||||
"data-slot": "calendar-year-picker-cell",
|
||||
"data-year": date.year,
|
||||
"data-year-key": date.toString(),
|
||||
"data-selected": state.isSelected || undefined,
|
||||
"aria-selected": state.isSelected,
|
||||
tabindex:
|
||||
state.isOpen && ctx.active.value === date.toString() ? 0 : -1,
|
||||
disabled: calendar.disabled.value,
|
||||
onFocus: () => {
|
||||
ctx.active.value = date.toString();
|
||||
},
|
||||
onClick: (event: MouseEvent) => {
|
||||
if (!event.defaultPrevented) ctx.select(date);
|
||||
},
|
||||
},
|
||||
),
|
||||
slots.default?.(state) ?? state.formattedYear,
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,167 @@
|
||||
import {
|
||||
CalendarDate,
|
||||
DateFormatter,
|
||||
endOfMonth,
|
||||
endOfWeek,
|
||||
startOfMonth,
|
||||
startOfWeek,
|
||||
startOfYear,
|
||||
isSameDay,
|
||||
isSameMonth,
|
||||
toCalendarDate,
|
||||
type DateDuration,
|
||||
type DateValue,
|
||||
} from "@internationalized/date";
|
||||
import { dateForLocale } from "./value";
|
||||
export type CalendarWeekday =
|
||||
"sun" | "mon" | "tue" | "wed" | "thu" | "fri" | "sat";
|
||||
export type CalendarDuration =
|
||||
| { months: number; weeks?: never; days?: never }
|
||||
| { weeks: number; months?: never; days?: never }
|
||||
| { days: number; months?: never; weeks?: never };
|
||||
export interface CalendarViewOptions {
|
||||
locale: string;
|
||||
visibleDuration?: CalendarDuration;
|
||||
firstDayOfWeek?: CalendarWeekday;
|
||||
weeksInMonth?: number;
|
||||
}
|
||||
export function calendarDuration(value: CalendarDuration = { months: 1 }) {
|
||||
const entries = Object.entries(value).filter(([, count]) => count != null);
|
||||
if (
|
||||
entries.length !== 1 ||
|
||||
!["months", "weeks", "days"].includes(entries[0]![0]) ||
|
||||
!Number.isSafeInteger(entries[0]![1]) ||
|
||||
entries[0]![1] <= 0
|
||||
)
|
||||
throw new RangeError(
|
||||
"Calendar visibleDuration requires one positive integer unit.",
|
||||
);
|
||||
return {
|
||||
unit: entries[0]![0] as "months" | "weeks" | "days",
|
||||
count: entries[0]![1] as number,
|
||||
};
|
||||
}
|
||||
export function calendarRange(anchor: DateValue, options: CalendarViewOptions) {
|
||||
const { unit, count } = calendarDuration(options.visibleDuration);
|
||||
const date = toCalendarDate(dateForLocale(anchor, options.locale));
|
||||
const start =
|
||||
unit === "months"
|
||||
? startOfMonth(date)
|
||||
: unit === "weeks"
|
||||
? startOfWeek(date, options.locale, options.firstDayOfWeek)
|
||||
: date;
|
||||
const end =
|
||||
unit === "months"
|
||||
? endOfMonth(start.add({ months: count - 1 }))
|
||||
: start.add({ days: unit === "weeks" ? count * 7 - 1 : count - 1 });
|
||||
return { start, end, unit, count };
|
||||
}
|
||||
/** Source-compatible month/week/day rows. Day views >=7 align weeks, with
|
||||
* disabled leading dates and empty trailing cells; short day views stay compact. */
|
||||
export function calendarRows(
|
||||
anchor: DateValue,
|
||||
options: CalendarViewOptions,
|
||||
offset: DateDuration = {},
|
||||
) {
|
||||
const range = calendarRange(anchor, options);
|
||||
const month = startOfMonth(range.start.add(offset));
|
||||
let start: CalendarDate, end: CalendarDate;
|
||||
if (range.unit === "months") {
|
||||
start = startOfWeek(month, options.locale, options.firstDayOfWeek);
|
||||
end = endOfWeek(endOfMonth(month), options.locale, options.firstDayOfWeek);
|
||||
if (options.weeksInMonth != null) {
|
||||
if (
|
||||
!Number.isSafeInteger(options.weeksInMonth) ||
|
||||
options.weeksInMonth < 1
|
||||
)
|
||||
throw new RangeError(
|
||||
"Calendar weeksInMonth requires a positive integer.",
|
||||
);
|
||||
// Never remove actual month days when a requested minimum is too small.
|
||||
const fixedEnd = start.add({ days: options.weeksInMonth * 7 - 1 });
|
||||
if (fixedEnd.compare(end) > 0) end = fixedEnd;
|
||||
}
|
||||
} else {
|
||||
start =
|
||||
range.unit === "days" && range.count < 7
|
||||
? range.start
|
||||
: startOfWeek(range.start, options.locale, options.firstDayOfWeek);
|
||||
end = range.end;
|
||||
}
|
||||
const rows: (CalendarDate | null)[][] = [];
|
||||
let cursor = start;
|
||||
while (cursor.compare(end) <= 0) {
|
||||
const row: (CalendarDate | null)[] = [];
|
||||
for (let index = 0; index < 7; index++) {
|
||||
row.push(cursor.compare(end) <= 0 ? cursor : null);
|
||||
const next = cursor.add({ days: 1 });
|
||||
if (isSameDay(cursor, next)) {
|
||||
while (row.length < 7) row.push(null);
|
||||
rows.push(row);
|
||||
return { rows, month, range };
|
||||
}
|
||||
cursor = next;
|
||||
}
|
||||
rows.push(row);
|
||||
}
|
||||
return { rows, month, range };
|
||||
}
|
||||
export function calendarWeekdays(
|
||||
anchor: DateValue,
|
||||
options: CalendarViewOptions,
|
||||
style: "narrow" | "short" | "long" = "short",
|
||||
) {
|
||||
const range = calendarRange(anchor, options);
|
||||
const start =
|
||||
range.unit === "days" && range.count < 7
|
||||
? range.start
|
||||
: startOfWeek(range.start, options.locale, options.firstDayOfWeek);
|
||||
const count = range.unit === "days" && range.count < 7 ? range.count : 7;
|
||||
const formatter = new DateFormatter(options.locale, {
|
||||
weekday: style,
|
||||
timeZone: "UTC",
|
||||
});
|
||||
return Array.from({ length: count }, (_, index) =>
|
||||
formatter.format(start.add({ days: index }).toDate("UTC")),
|
||||
);
|
||||
}
|
||||
export function calendarHeading(
|
||||
anchor: DateValue,
|
||||
options: CalendarViewOptions,
|
||||
offset?: DateDuration,
|
||||
format?: Intl.DateTimeFormatOptions,
|
||||
) {
|
||||
const range = calendarRange(anchor, options);
|
||||
const formatter = new DateFormatter(options.locale, {
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
...(range.unit !== "months" ? { day: "numeric" as const } : {}),
|
||||
...format,
|
||||
timeZone: "UTC",
|
||||
});
|
||||
if (offset) return formatter.format(range.start.add(offset).toDate("UTC"));
|
||||
if (
|
||||
isSameDay(range.start, range.end) ||
|
||||
(range.unit === "months" && range.count === 1)
|
||||
)
|
||||
return formatter.format(range.start.toDate("UTC"));
|
||||
return formatter.formatRange(
|
||||
range.start.toDate("UTC"),
|
||||
range.end.toDate("UTC"),
|
||||
);
|
||||
}
|
||||
export function calendarYears(min: DateValue, max: DateValue) {
|
||||
const result: CalendarDate[] = [];
|
||||
let current = startOfYear(toCalendarDate(min));
|
||||
const last = toCalendarDate(max);
|
||||
while (current.compare(last) <= 0) {
|
||||
result.push(current);
|
||||
const next = startOfYear(current.add({ years: 1 }));
|
||||
if (next.compare(current) <= 0) break;
|
||||
current = next;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export function sameCalendarMonth(a: DateValue, b: DateValue) {
|
||||
return isSameMonth(a, b);
|
||||
}
|
||||
Reference in New Issue
Block a user