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);
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import {
|
||||
GregorianCalendar,
|
||||
isSameDay,
|
||||
toCalendar,
|
||||
toCalendarDate,
|
||||
type DateValue,
|
||||
} from "@internationalized/date";
|
||||
import { copyDateValue, dateValueKey } from "./value";
|
||||
|
||||
/** Complete accepted selection. Partial selection belongs to the private draft. */
|
||||
export interface CalendarDateRange<T extends DateValue = DateValue> {
|
||||
start: T;
|
||||
end: T;
|
||||
}
|
||||
export type CalendarRangeModel = CalendarDateRange | null;
|
||||
export const copyCalendarRange = (
|
||||
value: CalendarRangeModel | undefined,
|
||||
): CalendarRangeModel =>
|
||||
value
|
||||
? { start: copyDateValue(value.start), end: copyDateValue(value.end) }
|
||||
: null;
|
||||
export const calendarRangeKey = (value: CalendarRangeModel) =>
|
||||
value ? `${dateValueKey(value.start)}|${dateValueKey(value.end)}` : "empty";
|
||||
export function orderedCalendarRange(
|
||||
a: DateValue,
|
||||
b: DateValue,
|
||||
): CalendarDateRange {
|
||||
const start = toCalendarDate(a),
|
||||
end = toCalendarDate(b);
|
||||
return start.compare(end) <= 0
|
||||
? { start: start.copy(), end: end.copy() }
|
||||
: { start: end.copy(), end: start.copy() };
|
||||
}
|
||||
export function withinCalendarRange(
|
||||
date: DateValue,
|
||||
range: CalendarRangeModel,
|
||||
) {
|
||||
const day = toCalendarDate(date);
|
||||
return (
|
||||
!!range &&
|
||||
day.compare(toCalendarDate(range.start)) >= 0 &&
|
||||
day.compare(toCalendarDate(range.end)) <= 0
|
||||
);
|
||||
}
|
||||
/** Both endpoints preserve their own calendar, time precision and zone. */
|
||||
export function convertCalendarRange(
|
||||
range: CalendarDateRange,
|
||||
original: CalendarRangeModel,
|
||||
): CalendarDateRange {
|
||||
const convert = (day: DateValue, previous?: DateValue) => {
|
||||
const date = toCalendar(day, previous?.calendar ?? new GregorianCalendar());
|
||||
return previous
|
||||
? previous.set({
|
||||
era: date.era,
|
||||
year: date.year,
|
||||
month: date.month,
|
||||
day: date.day,
|
||||
})
|
||||
: toCalendarDate(date);
|
||||
};
|
||||
return {
|
||||
start: convert(range.start, original?.start),
|
||||
end: convert(range.end, original?.end),
|
||||
};
|
||||
}
|
||||
/** First interior barrier, not the endpoint itself: unavailable endpoints stay
|
||||
* focusable. Non-contiguous ranges may cross unavailable, never disabled days. */
|
||||
export function calendarRangeBarrier(
|
||||
anchor: DateValue,
|
||||
target: DateValue,
|
||||
disabled: (date: DateValue) => boolean,
|
||||
unavailable: (date: DateValue) => boolean,
|
||||
allowsNonContiguous = false,
|
||||
): DateValue | undefined {
|
||||
const start = toCalendarDate(anchor),
|
||||
end = toCalendarDate(target);
|
||||
const direction = end.compare(start) < 0 ? -1 : 1;
|
||||
let date = start.add({ days: direction });
|
||||
while (direction * date.compare(end) < 0) {
|
||||
if (disabled(date) || (!allowsNonContiguous && unavailable(date)))
|
||||
return date.copy();
|
||||
const next = date.add({ days: direction });
|
||||
if (isSameDay(next, date)) break;
|
||||
date = next;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -0,0 +1,453 @@
|
||||
import {
|
||||
computed,
|
||||
getCurrentInstance,
|
||||
onBeforeUnmount,
|
||||
shallowRef,
|
||||
watch,
|
||||
type ComputedRef,
|
||||
} from "vue";
|
||||
import {
|
||||
isSameDay,
|
||||
toCalendarDate,
|
||||
type CalendarDate,
|
||||
type DateValue,
|
||||
} from "@internationalized/date";
|
||||
import { useChoiceValue } from "../choice/shared";
|
||||
import { useCalendarView, type CalendarViewProps } from "../calendar/view";
|
||||
import type { CalendarRangeInteraction } from "../calendar/context";
|
||||
import {
|
||||
calendarRangeBarrier,
|
||||
calendarRangeKey,
|
||||
convertCalendarRange,
|
||||
copyCalendarRange,
|
||||
orderedCalendarRange,
|
||||
withinCalendarRange,
|
||||
type CalendarRangeModel,
|
||||
} from "../date/range-selection";
|
||||
import { calendarDayState, dateValueKey } from "../date/value";
|
||||
import { calendarDuration, calendarRange } from "../date/calendar";
|
||||
|
||||
/** Private schema for the next public shell; not exported from the package root. */
|
||||
export interface RangeCalendarOptions extends Omit<
|
||||
CalendarViewProps,
|
||||
"isDateUnavailable"
|
||||
> {
|
||||
modelValue?: CalendarRangeModel;
|
||||
value?: CalendarRangeModel;
|
||||
defaultValue?: CalendarRangeModel;
|
||||
allowsNonContiguousRanges?: boolean;
|
||||
isDateUnavailable?: (
|
||||
date: DateValue,
|
||||
anchorDate: CalendarDate | null,
|
||||
) => boolean;
|
||||
}
|
||||
interface RangeEmit {
|
||||
(event: "update:modelValue", value: CalendarRangeModel): void;
|
||||
(event: "change", value: CalendarRangeModel): void;
|
||||
(event: "update:focusedValue", value: DateValue): void;
|
||||
(event: "focusChange", value: DateValue): void;
|
||||
(event: "update:isYearPickerOpen", value: boolean): void;
|
||||
(event: "yearPickerOpenChange", value: boolean): void;
|
||||
}
|
||||
interface Gesture {
|
||||
id: number;
|
||||
start: DateValue;
|
||||
previousAnchor: CalendarDate | null;
|
||||
previousEnd: CalendarDate | null;
|
||||
hadAnchor: boolean;
|
||||
moved: boolean;
|
||||
}
|
||||
/** Range selection owns only the accepted value and an uncommitted anchor.
|
||||
* All calendar geometry, focus, paging and year navigation have one shared owner. */
|
||||
export function useRangeCalendar(props: RangeCalendarOptions, emit: RangeEmit) {
|
||||
const instance = getCurrentInstance()!;
|
||||
const has = (key: string) => Object.hasOwn(instance.vnode.props ?? {}, key);
|
||||
const fallback = copyCalendarRange(props.defaultValue);
|
||||
const model = useChoiceValue<CalendarRangeModel>(
|
||||
() =>
|
||||
copyCalendarRange(
|
||||
has("modelValue") || has("model-value")
|
||||
? props.modelValue
|
||||
: props.value,
|
||||
),
|
||||
() => copyCalendarRange(fallback),
|
||||
["modelValue", "model-value", "value"],
|
||||
(value) => {
|
||||
emit("update:modelValue", copyCalendarRange(value));
|
||||
emit("change", copyCalendarRange(value));
|
||||
},
|
||||
);
|
||||
const anchorDate = shallowRef<CalendarDate | null>(null);
|
||||
const draftEnd = shallowRef<CalendarDate | null>(null);
|
||||
const dates = computed(() =>
|
||||
model.value.value ? [model.value.value.start, model.value.value.end] : [],
|
||||
);
|
||||
const unavailable = (date: DateValue) =>
|
||||
!!props.isDateUnavailable?.(date.copy(), anchorDate.value?.copy() ?? null);
|
||||
const baseDisabled = (date: DateValue) =>
|
||||
calendarDayState(date, {
|
||||
isDateDisabled: props.isDateDisabled,
|
||||
minValue: props.minValue ?? view.min.value,
|
||||
maxValue: props.maxValue ?? view.max.value,
|
||||
isDisabled: view.disabled.value,
|
||||
}).isDisabled;
|
||||
// Only an active draft constrains cross-barrier navigation. Cache by semantics,
|
||||
// not mutable DateValue identity; invalidated by reactive rules/bounds below.
|
||||
let barriers = new Map<string, ComputedRef<DateValue | undefined>>();
|
||||
function barrier(date: DateValue) {
|
||||
if (
|
||||
!anchorDate.value ||
|
||||
(!props.isDateUnavailable && !props.isDateDisabled)
|
||||
)
|
||||
return undefined;
|
||||
const key = dateValueKey(date);
|
||||
if (!barriers.has(key))
|
||||
barriers.set(
|
||||
key,
|
||||
computed(() =>
|
||||
anchorDate.value
|
||||
? calendarRangeBarrier(
|
||||
anchorDate.value,
|
||||
date,
|
||||
baseDisabled,
|
||||
unavailable,
|
||||
!!props.allowsNonContiguousRanges,
|
||||
)
|
||||
: undefined,
|
||||
),
|
||||
);
|
||||
return barriers.get(key)?.value;
|
||||
}
|
||||
function allowed(date: DateValue) {
|
||||
return (
|
||||
!view.disabled.value &&
|
||||
!view.readOnly.value &&
|
||||
!view.yearOpen.value &&
|
||||
!baseDisabled(date) &&
|
||||
!unavailable(date) &&
|
||||
!barrier(date)
|
||||
);
|
||||
}
|
||||
const highlightedRange = computed(() => {
|
||||
if (anchorDate.value)
|
||||
return orderedCalendarRange(
|
||||
anchorDate.value,
|
||||
draftEnd.value ?? anchorDate.value,
|
||||
);
|
||||
return model.value.value
|
||||
? orderedCalendarRange(model.value.value.start, model.value.value.end)
|
||||
: null;
|
||||
});
|
||||
const invalidSelection = computed(() => {
|
||||
const value = model.value.value;
|
||||
if (anchorDate.value) return false;
|
||||
return (
|
||||
!!value &&
|
||||
(toCalendarDate(value.start).compare(toCalendarDate(value.end)) > 0 ||
|
||||
baseDisabled(value.start) ||
|
||||
baseDisabled(value.end) ||
|
||||
unavailable(value.start) ||
|
||||
unavailable(value.end))
|
||||
);
|
||||
});
|
||||
function selected(date: DateValue) {
|
||||
return (
|
||||
withinCalendarRange(date, highlightedRange.value) &&
|
||||
!baseDisabled(date) &&
|
||||
!unavailable(date)
|
||||
);
|
||||
}
|
||||
function begin(date: DateValue) {
|
||||
draftEnd.value = toCalendarDate(date).copy();
|
||||
anchorDate.value = toCalendarDate(date).copy();
|
||||
barriers.clear();
|
||||
}
|
||||
function complete(date: DateValue) {
|
||||
if (!anchorDate.value || !allowed(date)) return false;
|
||||
if (baseDisabled(anchorDate.value) || unavailable(anchorDate.value)) {
|
||||
cancel();
|
||||
return false;
|
||||
}
|
||||
const range = orderedCalendarRange(anchorDate.value, date);
|
||||
const value = convertCalendarRange(range, model.value.value ?? fallback);
|
||||
anchorDate.value = null;
|
||||
draftEnd.value = null;
|
||||
barriers.clear();
|
||||
model.request(copyCalendarRange(value));
|
||||
return true;
|
||||
}
|
||||
function activate(
|
||||
date: DateValue,
|
||||
source: "keyboard" | "virtual",
|
||||
event?: Event,
|
||||
) {
|
||||
if (event?.defaultPrevented && source !== "keyboard") return;
|
||||
if (!allowed(date)) return;
|
||||
if (anchorDate.value) {
|
||||
complete(date);
|
||||
return;
|
||||
}
|
||||
begin(date);
|
||||
if (source === "keyboard") {
|
||||
// Advancing focus exposes the range preview to keyboard users. Only an
|
||||
// accepted focus is used, so a rejecting parent cannot create a ghost end.
|
||||
for (const direction of [1, -1]) {
|
||||
const next = date.add({ days: direction });
|
||||
if (!isSameDay(next, date) && allowed(next)) {
|
||||
view.focusDate(next, true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let gesture: Gesture | undefined;
|
||||
let pendingClick: Gesture | undefined;
|
||||
let detach = () => {};
|
||||
let ignoreClick = false;
|
||||
let clickTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
function resetClick() {
|
||||
clearTimeout(clickTimer);
|
||||
clickTimer = undefined;
|
||||
pendingClick = undefined;
|
||||
ignoreClick = false;
|
||||
}
|
||||
function restore(previous: Gesture) {
|
||||
anchorDate.value = previous.previousAnchor?.copy() ?? null;
|
||||
draftEnd.value = previous.previousEnd?.copy() ?? null;
|
||||
barriers.clear();
|
||||
}
|
||||
function stopGesture(rollback = false) {
|
||||
if (gesture && rollback) restore(gesture);
|
||||
gesture = undefined;
|
||||
detach();
|
||||
detach = () => {};
|
||||
}
|
||||
function cancel() {
|
||||
const active = !!anchorDate.value || !!gesture || !!pendingClick;
|
||||
stopGesture();
|
||||
resetClick();
|
||||
anchorDate.value = null;
|
||||
draftEnd.value = null;
|
||||
barriers.clear();
|
||||
return active;
|
||||
}
|
||||
function armClickExpiry() {
|
||||
clearTimeout(clickTimer);
|
||||
clickTimer = setTimeout(() => {
|
||||
// A stopped/cancelled native click never leaves a transient draft behind.
|
||||
if (pendingClick) restore(pendingClick);
|
||||
resetClick();
|
||||
}, 0);
|
||||
}
|
||||
const range: CalendarRangeInteraction = {
|
||||
focusTarget(date) {
|
||||
const blocked = barrier(date);
|
||||
if (!blocked || !anchorDate.value) return date;
|
||||
return blocked.add({ days: date.compare(anchorDate.value) < 0 ? 1 : -1 });
|
||||
},
|
||||
state(date) {
|
||||
const highlighted = highlightedRange.value;
|
||||
return {
|
||||
isSelectionStart:
|
||||
selected(date) && !!highlighted && isSameDay(date, highlighted.start),
|
||||
isSelectionEnd:
|
||||
selected(date) && !!highlighted && isSameDay(date, highlighted.end),
|
||||
isInvalid:
|
||||
!anchorDate.value &&
|
||||
view.invalid.value &&
|
||||
withinCalendarRange(date, highlighted),
|
||||
};
|
||||
},
|
||||
activate,
|
||||
cancel,
|
||||
pointerDown(date, event) {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
event.button !== 0 ||
|
||||
event.isPrimary === false ||
|
||||
event.pointerType === "touch" ||
|
||||
!allowed(date)
|
||||
)
|
||||
return;
|
||||
stopGesture(true);
|
||||
resetClick();
|
||||
const previous: Gesture = {
|
||||
id: event.pointerId,
|
||||
start: date.copy(),
|
||||
previousAnchor: anchorDate.value?.copy() ?? null,
|
||||
previousEnd: draftEnd.value?.copy() ?? null,
|
||||
hadAnchor: !!anchorDate.value,
|
||||
moved: false,
|
||||
};
|
||||
gesture = previous;
|
||||
if (!previous.hadAnchor) {
|
||||
const current = model.value.value;
|
||||
const opposite =
|
||||
current &&
|
||||
!invalidSelection.value &&
|
||||
(isSameDay(date, current.start)
|
||||
? current.end
|
||||
: isSameDay(date, current.end)
|
||||
? current.start
|
||||
: undefined);
|
||||
begin(opposite || date);
|
||||
}
|
||||
view.focusDate(date, true);
|
||||
if (anchorDate.value && allowed(view.focus.value))
|
||||
draftEnd.value = view.focus.value.copy();
|
||||
const doc = view.root.value?.ownerDocument;
|
||||
if (!doc) return;
|
||||
// No global queue/capture: these listeners live only for this gesture.
|
||||
// Capture+task also cleans up when consumers stop bubbling pointerup.
|
||||
// Browsers can flush microtasks BETWEEN native event listeners; cleanup
|
||||
// must wait for the whole dispatch, not just the capture callback.
|
||||
let releaseTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const release = (up: PointerEvent) => {
|
||||
if (up.pointerId !== previous.id) return;
|
||||
releaseTimer = setTimeout(() => {
|
||||
if (gesture === previous) stopGesture(true);
|
||||
}, 0);
|
||||
};
|
||||
const abort = (cancelled: PointerEvent) => {
|
||||
if (cancelled.pointerId === previous.id) stopGesture(true);
|
||||
};
|
||||
const blur = () => stopGesture(true);
|
||||
doc.addEventListener("pointerup", release, true);
|
||||
doc.addEventListener("pointercancel", abort, true);
|
||||
doc.defaultView?.addEventListener("blur", blur);
|
||||
detach = () => {
|
||||
clearTimeout(releaseTimer);
|
||||
doc.removeEventListener("pointerup", release, true);
|
||||
doc.removeEventListener("pointercancel", abort, true);
|
||||
doc.defaultView?.removeEventListener("blur", blur);
|
||||
};
|
||||
},
|
||||
pointerEnter(date, event) {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
event.pointerType === "touch" ||
|
||||
!anchorDate.value ||
|
||||
!allowed(date)
|
||||
)
|
||||
return;
|
||||
if (gesture) {
|
||||
if (event.pointerId !== gesture.id) return;
|
||||
if (!isSameDay(date, gesture.start)) gesture.moved = true;
|
||||
}
|
||||
view.focusDate(date, true);
|
||||
},
|
||||
pointerUp(date, event) {
|
||||
if (!gesture || gesture.id !== event.pointerId) return;
|
||||
const previous = gesture;
|
||||
if (event.defaultPrevented || !allowed(date)) {
|
||||
stopGesture(true);
|
||||
return;
|
||||
}
|
||||
if (previous.moved) {
|
||||
complete(date);
|
||||
stopGesture();
|
||||
ignoreClick = true;
|
||||
} else {
|
||||
stopGesture();
|
||||
pendingClick = previous;
|
||||
}
|
||||
armClickExpiry();
|
||||
},
|
||||
click(date, event) {
|
||||
if (event.defaultPrevented) {
|
||||
if (pendingClick) restore(pendingClick);
|
||||
else if (gesture) stopGesture(true);
|
||||
resetClick();
|
||||
return;
|
||||
}
|
||||
if (ignoreClick && event.detail > 0) {
|
||||
resetClick();
|
||||
return;
|
||||
}
|
||||
const pending = pendingClick;
|
||||
resetClick();
|
||||
if (!allowed(date)) return;
|
||||
if (pending && !pending.hadAnchor) begin(date);
|
||||
else activate(date, "virtual", event);
|
||||
view.focusDate(date);
|
||||
},
|
||||
};
|
||||
const view = useCalendarView(
|
||||
props,
|
||||
{
|
||||
dates,
|
||||
followSelected: false,
|
||||
alignment(date, options) {
|
||||
const { unit, count } = calendarDuration(options.visibleDuration);
|
||||
const centered = calendarRange(
|
||||
date.subtract({ [unit]: Math.floor((count - 1) / 2) }),
|
||||
options,
|
||||
);
|
||||
return model.value.value &&
|
||||
toCalendarDate(model.value.value.end).compare(centered.end) > 0
|
||||
? "start"
|
||||
: "center";
|
||||
},
|
||||
selected,
|
||||
request: (date) => activate(date, "virtual"),
|
||||
unavailable,
|
||||
multiple: () => true,
|
||||
invalid: () => invalidSelection.value,
|
||||
disabledDay: (date) => !!barrier(date),
|
||||
range,
|
||||
},
|
||||
emit,
|
||||
"range-calendar",
|
||||
);
|
||||
watch(
|
||||
() => dateValueKey(view.focus.value),
|
||||
() => {
|
||||
if (!anchorDate.value) return;
|
||||
const date = view.focus.value;
|
||||
if (!baseDisabled(date) && !unavailable(date) && !barrier(date))
|
||||
draftEnd.value = date.copy();
|
||||
},
|
||||
{ flush: "sync" },
|
||||
);
|
||||
watch(
|
||||
() => calendarRangeKey(model.value.value),
|
||||
() => cancel(),
|
||||
{ flush: "sync" },
|
||||
);
|
||||
watch(
|
||||
[
|
||||
anchorDate,
|
||||
() => props.isDateUnavailable,
|
||||
() => props.isDateDisabled,
|
||||
() => props.allowsNonContiguousRanges,
|
||||
() => dateValueKey(props.minValue),
|
||||
() => dateValueKey(props.maxValue),
|
||||
() => view.options.value.locale,
|
||||
],
|
||||
() => {
|
||||
barriers = new Map();
|
||||
},
|
||||
{ flush: "sync" },
|
||||
);
|
||||
watch(
|
||||
[view.disabled, view.readOnly, view.yearOpen],
|
||||
([disabled, readonly, yearOpen]) => {
|
||||
if (disabled || readonly || yearOpen) cancel();
|
||||
},
|
||||
{ flush: "sync" },
|
||||
);
|
||||
watch(
|
||||
() =>
|
||||
!!anchorDate.value &&
|
||||
(baseDisabled(anchorDate.value) || unavailable(anchorDate.value)),
|
||||
(invalid) => {
|
||||
if (invalid) cancel();
|
||||
},
|
||||
{ flush: "sync" },
|
||||
);
|
||||
onBeforeUnmount(() => {
|
||||
stopGesture();
|
||||
resetClick();
|
||||
});
|
||||
return { ...view, model, anchorDate, highlightedRange, cancel };
|
||||
}
|
||||
Reference in New Issue
Block a user