Files
heroui-vue/packages/vue/src/components/range-calendar/use-range-calendar.ts
T

454 lines
14 KiB
TypeScript

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 };
}