feat: establish shared calendar range selection foundation
This commit is contained in:
@@ -1,46 +1,20 @@
|
||||
<script setup lang="ts" generic="M extends CalendarSelectionMode = 'single'">
|
||||
import { computed, getCurrentInstance, useAttrs } from "vue";
|
||||
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,
|
||||
import { copyDateValue, copyDateValues } from "../date/value";
|
||||
import { calendarHeading } from "../date/calendar";
|
||||
import { useCalendarView } from "./view";
|
||||
import type {
|
||||
CalendarModel,
|
||||
CalendarOptions,
|
||||
CalendarSelectionMode,
|
||||
} from "./context";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
const props = defineProps<CalendarOptions<M>>();
|
||||
@@ -64,24 +38,7 @@ defineSlots<{
|
||||
}) => 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,
|
||||
}));
|
||||
instance = getCurrentInstance()!;
|
||||
type Value = DateValue | DateValue[] | null;
|
||||
const copy = (value: Value | undefined): Value =>
|
||||
Array.isArray(value) ? copyDateValues(value) : copyDateValue(value ?? null);
|
||||
@@ -102,95 +59,43 @@ 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));
|
||||
const view = useCalendarView(
|
||||
props,
|
||||
{
|
||||
dates: selectedValues,
|
||||
selected,
|
||||
request,
|
||||
unavailable: (date) => !!props.isDateUnavailable?.(date.copy()),
|
||||
multiple: () => props.selectionMode === "multiple",
|
||||
},
|
||||
emit,
|
||||
);
|
||||
const {
|
||||
root,
|
||||
focus,
|
||||
anchor,
|
||||
options,
|
||||
disabled,
|
||||
readOnly,
|
||||
invalid,
|
||||
dir,
|
||||
yearOpen,
|
||||
visible,
|
||||
tabStop,
|
||||
focusDate,
|
||||
} = view;
|
||||
function request(value: DateValue) {
|
||||
if (disabledDay(value) || unavailable(value) || readOnly.value) return;
|
||||
if (view.disabledDay(value) || view.unavailable(value) || view.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()));
|
||||
toCalendarDate(toCalendar(view.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({
|
||||
@@ -208,148 +113,6 @@ function request(value: DateValue) {
|
||||
);
|
||||
} 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;
|
||||
|
||||
@@ -54,8 +54,32 @@ export interface CalendarCellState {
|
||||
isFocusVisible: boolean;
|
||||
isHovered: boolean;
|
||||
isPressed: boolean;
|
||||
isSelectionStart: boolean;
|
||||
isSelectionEnd: boolean;
|
||||
isInvalid: boolean;
|
||||
}
|
||||
/** Private gesture bridge. The selection owner, not individual cells, owns drafts. */
|
||||
export interface CalendarRangeInteraction {
|
||||
focusTarget: (date: DateValue) => DateValue;
|
||||
state: (
|
||||
date: DateValue,
|
||||
) => Pick<
|
||||
CalendarCellState,
|
||||
"isSelectionStart" | "isSelectionEnd" | "isInvalid"
|
||||
>;
|
||||
activate: (
|
||||
date: DateValue,
|
||||
source: "keyboard" | "virtual",
|
||||
event?: Event,
|
||||
) => void;
|
||||
pointerDown: (date: DateValue, event: PointerEvent) => void;
|
||||
pointerEnter: (date: DateValue, event: PointerEvent) => void;
|
||||
pointerUp: (date: DateValue, event: PointerEvent) => void;
|
||||
click: (date: DateValue, event: MouseEvent) => void;
|
||||
cancel: () => boolean;
|
||||
}
|
||||
export interface CalendarContext {
|
||||
prefix: "calendar" | "range-calendar";
|
||||
root: ShallowRef<HTMLElement | undefined>;
|
||||
trigger: ShallowRef<HTMLElement | undefined>;
|
||||
focus: ComputedRef<CalendarDate>;
|
||||
@@ -80,6 +104,7 @@ export interface CalendarContext {
|
||||
page: (direction: -1 | 1) => void;
|
||||
pageDisabled: (direction: -1 | 1) => boolean;
|
||||
setYearOpen: (value: boolean, restore?: boolean) => void;
|
||||
range?: CalendarRangeInteraction;
|
||||
}
|
||||
export const calendarKey: InjectionKey<CalendarContext> = Symbol("hv-calendar");
|
||||
export function useCalendar() {
|
||||
|
||||
@@ -73,14 +73,14 @@ function staticPart(
|
||||
inheritAttrs: false,
|
||||
props: { as: { type: String, default: tag } },
|
||||
setup(props, { attrs, slots }) {
|
||||
useCalendar();
|
||||
const ctx = useCalendar();
|
||||
return () =>
|
||||
h(
|
||||
props.as,
|
||||
mergeProps(
|
||||
{
|
||||
class: className,
|
||||
"data-slot": slot,
|
||||
class: className.replace("hv-calendar__", `hv-${ctx.prefix}__`),
|
||||
"data-slot": slot.replace("calendar-", `${ctx.prefix}-`),
|
||||
"aria-hidden":
|
||||
slot === "calendar-cell-indicator" ? "true" : undefined,
|
||||
},
|
||||
@@ -126,8 +126,8 @@ export const CalendarHeading = defineComponent({
|
||||
mergeProps(
|
||||
{
|
||||
id,
|
||||
class: "hv-calendar__heading",
|
||||
"data-slot": "calendar-heading",
|
||||
class: `hv-${ctx.prefix}__heading`,
|
||||
"data-slot": `${ctx.prefix}-heading`,
|
||||
"aria-live": "polite",
|
||||
"aria-atomic": "true",
|
||||
},
|
||||
@@ -162,12 +162,12 @@ export const CalendarNavButton = defineComponent({
|
||||
mergeProps(
|
||||
{
|
||||
type: "button",
|
||||
class: "hv-calendar__nav-button",
|
||||
class: `hv-${ctx.prefix}__nav-button`,
|
||||
"aria-label": direction === -1 ? "Previous" : "Next",
|
||||
},
|
||||
attrs,
|
||||
{
|
||||
"data-slot": "calendar-nav-button",
|
||||
"data-slot": `${ctx.prefix}-nav-button`,
|
||||
disabled,
|
||||
tabindex: ctx.yearOpen.value ? -1 : attrs.tabindex,
|
||||
"data-disabled": disabled || undefined,
|
||||
@@ -176,7 +176,12 @@ export const CalendarNavButton = defineComponent({
|
||||
},
|
||||
},
|
||||
),
|
||||
slots.default?.() ?? [calendarChevron(direction === -1)],
|
||||
slots.default?.() ?? [
|
||||
calendarChevron(
|
||||
direction === -1,
|
||||
`hv-${ctx.prefix}__nav-button-icon`,
|
||||
),
|
||||
],
|
||||
);
|
||||
};
|
||||
},
|
||||
@@ -207,7 +212,7 @@ export const CalendarGrid = defineComponent({
|
||||
"table",
|
||||
mergeProps(
|
||||
{
|
||||
class: "hv-calendar__grid",
|
||||
class: `hv-${ctx.prefix}__grid`,
|
||||
role: "grid",
|
||||
"aria-label": calendarHeading(
|
||||
ctx.anchor.value,
|
||||
@@ -220,7 +225,7 @@ export const CalendarGrid = defineComponent({
|
||||
},
|
||||
attrs,
|
||||
{
|
||||
"data-slot": "calendar-grid",
|
||||
"data-slot": `${ctx.prefix}-grid`,
|
||||
"aria-hidden": ctx.yearOpen.value || undefined,
|
||||
inert: ctx.yearOpen.value ? "" : undefined,
|
||||
},
|
||||
@@ -236,14 +241,15 @@ export const CalendarGridHeader = defineComponent({
|
||||
default?: (state: { day: string; index: number }) => VNodeChild;
|
||||
}>,
|
||||
setup(_props, { attrs, slots }) {
|
||||
const ctx = useCalendar();
|
||||
const grid = useCalendarGrid();
|
||||
return () =>
|
||||
h(
|
||||
"thead",
|
||||
mergeProps(
|
||||
{
|
||||
class: "hv-calendar__grid-header",
|
||||
"data-slot": "calendar-grid-header",
|
||||
class: `hv-${ctx.prefix}__grid-header`,
|
||||
"data-slot": `${ctx.prefix}-grid-header`,
|
||||
},
|
||||
attrs,
|
||||
),
|
||||
@@ -267,21 +273,22 @@ export const CalendarGridBody = defineComponent({
|
||||
default?: (state: { date: DateValue }) => VNodeChild;
|
||||
}>,
|
||||
setup(_props, { attrs, slots }) {
|
||||
const ctx = useCalendar();
|
||||
const grid = useCalendarGrid();
|
||||
return () =>
|
||||
h(
|
||||
"tbody",
|
||||
mergeProps(
|
||||
{
|
||||
class: "hv-calendar__grid-body",
|
||||
"data-slot": "calendar-grid-body",
|
||||
class: `hv-${ctx.prefix}__grid-body`,
|
||||
"data-slot": `${ctx.prefix}-grid-body`,
|
||||
},
|
||||
attrs,
|
||||
),
|
||||
grid.value.rows.map((row, index) =>
|
||||
h(
|
||||
"tr",
|
||||
{ key: index, class: "hv-calendar__grid-row" },
|
||||
{ key: index, class: `hv-${ctx.prefix}__grid-row` },
|
||||
row.map((date, index) =>
|
||||
date
|
||||
? (slots.default?.({ date: date.copy() }) ??
|
||||
@@ -334,6 +341,10 @@ export const CalendarCell = defineComponent({
|
||||
isHovered: hovered.value,
|
||||
isPressed: pressed.value,
|
||||
isFocusVisible: focusVisible.value,
|
||||
isSelectionStart: false,
|
||||
isSelectionEnd: false,
|
||||
isInvalid: ctx.invalid.value && ctx.selected(props.date),
|
||||
...ctx.range?.state(props.date),
|
||||
};
|
||||
});
|
||||
watch(
|
||||
@@ -357,6 +368,11 @@ export const CalendarCell = defineComponent({
|
||||
event.altKey
|
||||
)
|
||||
return;
|
||||
if (event.key === "Escape" && ctx.range?.cancel()) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
return;
|
||||
}
|
||||
const date = props.date;
|
||||
const sign = ctx.dir.value === "rtl" ? -1 : 1;
|
||||
let target: DateValue;
|
||||
@@ -404,7 +420,8 @@ export const CalendarCell = defineComponent({
|
||||
case " ":
|
||||
event.preventDefault();
|
||||
pressed.value = true;
|
||||
ctx.request(date);
|
||||
if (ctx.range) ctx.range.activate(date, "keyboard", event);
|
||||
else ctx.request(date);
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
@@ -413,6 +430,7 @@ export const CalendarCell = defineComponent({
|
||||
event.stopPropagation();
|
||||
if (target.compare(ctx.min.value) < 0) target = ctx.min.value;
|
||||
if (target.compare(ctx.max.value) > 0) target = ctx.max.value;
|
||||
target = ctx.range?.focusTarget(target) ?? target;
|
||||
// Bounds are finite and calendar arithmetic may saturate at year limits.
|
||||
while (
|
||||
target.compare(ctx.min.value) >= 0 &&
|
||||
@@ -422,7 +440,8 @@ export const CalendarCell = defineComponent({
|
||||
ctx.focusDate(target, true);
|
||||
return;
|
||||
}
|
||||
const next = target.add({ days: step });
|
||||
const candidate = target.add({ days: step });
|
||||
const next = ctx.range?.focusTarget(candidate) ?? candidate;
|
||||
if (isSameDay(next, target)) return;
|
||||
target = next;
|
||||
}
|
||||
@@ -438,6 +457,7 @@ export const CalendarCell = defineComponent({
|
||||
{
|
||||
role: "gridcell",
|
||||
"aria-selected": value.isSelected,
|
||||
"aria-invalid": value.isInvalid || undefined,
|
||||
"aria-hidden": value.isOutsideMonth || undefined,
|
||||
"aria-disabled": value.isDisabled || value.isUnavailable || undefined,
|
||||
},
|
||||
@@ -447,7 +467,7 @@ export const CalendarCell = defineComponent({
|
||||
mergeProps(
|
||||
{
|
||||
type: "button",
|
||||
class: "hv-calendar__cell",
|
||||
class: `hv-${ctx.prefix}__cell`,
|
||||
tabindex:
|
||||
!ctx.yearOpen.value &&
|
||||
!value.isDisabled &&
|
||||
@@ -463,10 +483,14 @@ export const CalendarCell = defineComponent({
|
||||
ref: (node: unknown) => {
|
||||
element = node as HTMLButtonElement | undefined;
|
||||
},
|
||||
"data-slot": "calendar-cell",
|
||||
"data-slot": `${ctx.prefix}-cell`,
|
||||
"data-date": props.date.toString(),
|
||||
disabled: value.isDisabled,
|
||||
"data-selected": value.isSelected || undefined,
|
||||
"data-selection-start": value.isSelectionStart || undefined,
|
||||
"data-selection-end": value.isSelectionEnd || undefined,
|
||||
"data-invalid": value.isInvalid || undefined,
|
||||
"aria-invalid": value.isInvalid || undefined,
|
||||
"data-today": value.isToday || undefined,
|
||||
"data-disabled": value.isDisabled || undefined,
|
||||
"data-unavailable": value.isUnavailable || undefined,
|
||||
@@ -475,6 +499,11 @@ export const CalendarCell = defineComponent({
|
||||
value.isDisabled || value.isUnavailable || undefined,
|
||||
onKeydown: keydown,
|
||||
onClick: (event: MouseEvent) => {
|
||||
if (ctx.range) {
|
||||
if (value.isDisabled || ctx.yearOpen.value) return;
|
||||
ctx.range.click(props.date, event);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!event.defaultPrevented &&
|
||||
!ctx.yearOpen.value &&
|
||||
@@ -488,14 +517,19 @@ export const CalendarCell = defineComponent({
|
||||
"data-focus-visible": focusVisible.value || undefined,
|
||||
"data-hovered": hovered.value || undefined,
|
||||
"data-pressed": pressed.value || undefined,
|
||||
onPointerenter: () => {
|
||||
if (!value.isDisabled) hovered.value = true;
|
||||
onPointerenter: (event: PointerEvent) => {
|
||||
if (!event.defaultPrevented && !value.isDisabled)
|
||||
hovered.value = true;
|
||||
if (!value.isDisabled && !ctx.yearOpen.value)
|
||||
ctx.range?.pointerEnter(props.date, event);
|
||||
},
|
||||
onPointerleave: () => {
|
||||
hovered.value = false;
|
||||
pressed.value = false;
|
||||
},
|
||||
onPointerdown: (event: PointerEvent) => {
|
||||
if (!value.isDisabled && !ctx.yearOpen.value)
|
||||
ctx.range?.pointerDown(props.date, event);
|
||||
if (
|
||||
!event.defaultPrevented &&
|
||||
!value.isDisabled &&
|
||||
@@ -503,7 +537,9 @@ export const CalendarCell = defineComponent({
|
||||
)
|
||||
pressed.value = true;
|
||||
},
|
||||
onPointerup: () => {
|
||||
onPointerup: (event: PointerEvent) => {
|
||||
if (!value.isDisabled && !ctx.yearOpen.value)
|
||||
ctx.range?.pointerUp(props.date, event);
|
||||
pressed.value = false;
|
||||
},
|
||||
onKeyup: () => {
|
||||
@@ -524,7 +560,20 @@ export const CalendarCell = defineComponent({
|
||||
},
|
||||
},
|
||||
),
|
||||
slots.default?.(value) ?? value.formattedDate,
|
||||
ctx.range
|
||||
? h(
|
||||
"span",
|
||||
{
|
||||
class: `hv-${ctx.prefix}__cell-button`,
|
||||
"data-slot": `${ctx.prefix}-cell-button`,
|
||||
"data-selected":
|
||||
value.isSelectionStart ||
|
||||
value.isSelectionEnd ||
|
||||
undefined,
|
||||
},
|
||||
slots.default?.(value) ?? value.formattedDate,
|
||||
)
|
||||
: (slots.default?.(value) ?? value.formattedDate),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
import {
|
||||
computed,
|
||||
getCurrentInstance,
|
||||
nextTick,
|
||||
onMounted,
|
||||
onBeforeUnmount,
|
||||
provide,
|
||||
shallowRef,
|
||||
useId,
|
||||
watch,
|
||||
type ComputedRef,
|
||||
} from "vue";
|
||||
import {
|
||||
CalendarDate,
|
||||
getLocalTimeZone,
|
||||
today,
|
||||
toCalendarDate,
|
||||
toCalendar,
|
||||
isSameDay,
|
||||
type DateValue,
|
||||
} from "@internationalized/date";
|
||||
import { useChoiceValue } from "../choice/shared";
|
||||
import { copyDateValue, dateForLocale, dateValueKey } from "../date/value";
|
||||
import {
|
||||
calendarRange,
|
||||
calendarDuration,
|
||||
type CalendarViewOptions,
|
||||
} from "../date/calendar";
|
||||
import { useInheritedDisabled } from "../field/disabled";
|
||||
import { useConfig } from "../../providers/context";
|
||||
import {
|
||||
calendarKey,
|
||||
type CalendarContext,
|
||||
type CalendarOptions,
|
||||
type CalendarRangeInteraction,
|
||||
} from "./context";
|
||||
|
||||
export type CalendarViewProps = Omit<
|
||||
CalendarOptions<"single">,
|
||||
| "modelValue"
|
||||
| "value"
|
||||
| "defaultValue"
|
||||
| "selectionMode"
|
||||
| "isDateUnavailable"
|
||||
>;
|
||||
export interface CalendarSelectionAdapter {
|
||||
dates: ComputedRef<DateValue[]>;
|
||||
selected: (date: DateValue) => boolean;
|
||||
request: (date: DateValue) => void;
|
||||
unavailable?: (date: DateValue) => boolean;
|
||||
multiple?: () => boolean;
|
||||
invalid?: () => boolean;
|
||||
disabledDay?: (date: DateValue) => boolean;
|
||||
range?: CalendarRangeInteraction;
|
||||
followSelected?: boolean;
|
||||
alignment?: (
|
||||
date: CalendarDate,
|
||||
options: CalendarViewOptions,
|
||||
) => "start" | "center" | "end";
|
||||
}
|
||||
type ViewEmit = {
|
||||
(event: "yearPickerOpenChange", value: boolean): void;
|
||||
(event: "update:focusedValue", value: DateValue): void;
|
||||
(event: "focusChange", value: DateValue): void;
|
||||
(event: "update:isYearPickerOpen", value: boolean): void;
|
||||
};
|
||||
/** One view/focus/year owner for Calendar and RangeCalendar. Private implementation API. */
|
||||
export function useCalendarView(
|
||||
props: CalendarViewProps,
|
||||
selection: CalendarSelectionAdapter,
|
||||
emit: ViewEmit,
|
||||
prefix: "calendar" | "range-calendar" = "calendar",
|
||||
) {
|
||||
const instance = getCurrentInstance()!,
|
||||
config = useConfig();
|
||||
const has = (key: string) => Object.hasOwn(instance.vnode.props ?? {}, key);
|
||||
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(() => selection.multiple?.() ?? false);
|
||||
const invalid = computed(() => !!props.isInvalid || !!selection.invalid?.());
|
||||
const options = computed(() => ({
|
||||
locale: locale.value,
|
||||
firstDayOfWeek: props.firstDayOfWeek,
|
||||
visibleDuration: props.visibleDuration,
|
||||
weeksInMonth: props.weeksInMonth,
|
||||
}));
|
||||
const initial = copyDateValue(
|
||||
props.defaultFocusedValue ??
|
||||
selection.dates.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 ??
|
||||
selection.alignment?.(date, options.value) ??
|
||||
"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()) ||
|
||||
!!selection.disabledDay?.(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;
|
||||
});
|
||||
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") === `${prefix}-cell`;
|
||||
if (moveDOM || restoreControlledFocus)
|
||||
void nextTick(() => {
|
||||
if (yearOpen.value) return;
|
||||
const iso = (tabStop.value ?? focus.value).toString();
|
||||
root.value
|
||||
?.querySelector<HTMLElement>(
|
||||
`[data-slot="${prefix}-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") === `${prefix}-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="${prefix}-cell"][tabindex="0"]`,
|
||||
)
|
||||
?.focus();
|
||||
});
|
||||
},
|
||||
{ flush: "sync" },
|
||||
);
|
||||
watch(
|
||||
[locale, () => props.visibleDuration, () => props.firstDayOfWeek],
|
||||
() => {
|
||||
anchor.value = aligned(focus.value);
|
||||
},
|
||||
{ deep: true },
|
||||
);
|
||||
watch(
|
||||
() => selection.dates.value.map(dateValueKey).join("|"),
|
||||
() => {
|
||||
if (
|
||||
selection.followSelected !== false &&
|
||||
!has("focusedValue") &&
|
||||
!has("focused-value") &&
|
||||
selection.dates.value[0]
|
||||
)
|
||||
focusDate(selection.dates.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();
|
||||
});
|
||||
}
|
||||
const context = {
|
||||
prefix,
|
||||
root,
|
||||
trigger,
|
||||
focus,
|
||||
anchor,
|
||||
options,
|
||||
min,
|
||||
max,
|
||||
disabled,
|
||||
tabStop,
|
||||
readOnly,
|
||||
multiple,
|
||||
invalid,
|
||||
dir,
|
||||
timeZone,
|
||||
yearOpen,
|
||||
headingId,
|
||||
selected: selection.selected,
|
||||
disabledDay,
|
||||
unavailable: selection.unavailable ?? (() => false),
|
||||
request: selection.request,
|
||||
range: selection.range,
|
||||
focusDate,
|
||||
page,
|
||||
pageDisabled,
|
||||
setYearOpen,
|
||||
} satisfies CalendarContext;
|
||||
provide(calendarKey, context);
|
||||
onMounted(() => {
|
||||
if (props.autoFocus && tabStop.value) focusDate(tabStop.value, true);
|
||||
});
|
||||
|
||||
return { ...context, visible };
|
||||
}
|
||||
@@ -191,7 +191,7 @@ export const CalendarYearPickerGrid = defineComponent({
|
||||
}).format(date.toDate("UTC"));
|
||||
function measure() {
|
||||
const grid = ctx.root.value?.querySelector<HTMLElement>(
|
||||
'[data-slot="calendar-grid"]',
|
||||
`[data-slot="${ctx.prefix}-grid"]`,
|
||||
);
|
||||
if (grid) {
|
||||
top.value = grid.offsetTop;
|
||||
@@ -206,7 +206,9 @@ export const CalendarYearPickerGrid = defineComponent({
|
||||
cell?.scrollIntoView?.({ block: "nearest" });
|
||||
}
|
||||
const rootGrid = computed(() =>
|
||||
ctx.root.value?.querySelector<HTMLElement>('[data-slot="calendar-grid"]'),
|
||||
ctx.root.value?.querySelector<HTMLElement>(
|
||||
`[data-slot="${ctx.prefix}-grid"]`,
|
||||
),
|
||||
);
|
||||
useResizeObserver(rootGrid, measure);
|
||||
onMounted(measure);
|
||||
|
||||
Reference in New Issue
Block a user