@yamada-ui/calendar
Version:
Yamada UI calendar component
502 lines (498 loc) • 21.8 kB
JavaScript
"use client"
;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/use-month.tsx
var use_month_exports = {};
__export(use_month_exports, {
useMonth: () => useMonth
});
module.exports = __toCommonJS(use_month_exports);
var import_utils3 = require("@yamada-ui/utils");
var import_dayjs3 = __toESM(require("dayjs"));
var import_react2 = require("react");
// src/calendar-utils.ts
var import_utils = require("@yamada-ui/utils");
var import_dayjs = __toESM(require("dayjs"));
var getFormattedLabel = (dateOrYear, locale, format) => {
if (dateOrYear == null || dateOrYear === -1) {
return "";
} else if (dateOrYear instanceof Date) {
return (0, import_dayjs.default)(dateOrYear).locale(locale).format(format);
} else {
return (0, import_dayjs.default)(new Date(dateOrYear, 1, 1)).locale(locale).format(format);
}
};
var isSameMonth = (date, comparison) => (date == null ? void 0 : date.getFullYear()) === (comparison == null ? void 0 : comparison.getFullYear()) && (date == null ? void 0 : date.getMonth()) === (comparison == null ? void 0 : comparison.getMonth());
var isSameDate = (date, comparison) => isSameMonth(date, comparison) && (date == null ? void 0 : date.getDate()) === (comparison == null ? void 0 : comparison.getDate());
var isInRange = (date, minDate, maxDate) => {
const hasMinDate = minDate instanceof Date;
const hasMaxDate = maxDate instanceof Date;
if (!hasMaxDate && !hasMinDate) return true;
const minInRange = hasMinDate ? isSomeAfterDate(date, minDate) : true;
const maxInRange = hasMaxDate ? isSomeBeforeDate(date, maxDate) : true;
return maxInRange && minInRange;
};
var isMonthInRange = ({
date,
maxDate,
minDate
}) => {
const hasMinDate = minDate instanceof Date;
const hasMaxDate = maxDate instanceof Date;
if (!hasMaxDate && !hasMinDate) return true;
const firstOfMonth = (0, import_dayjs.default)(date).startOf("month");
const lastOfMonth = (0, import_dayjs.default)(date).endOf("month");
const minInRange = hasMinDate ? lastOfMonth.isAfter(minDate) : true;
const maxInRange = hasMaxDate ? firstOfMonth.isBefore(maxDate) : true;
return maxInRange && minInRange;
};
var sortDates = (dates, type = "asc") => {
if (type === "asc") {
return dates.sort((a, b) => (0, import_dayjs.default)(a).isAfter(b, "day") ? 1 : -1);
} else {
return dates.sort((a, b) => (0, import_dayjs.default)(a).isBefore(b, "day") ? 1 : -1);
}
};
var isSomeAfterDate = (value, date) => (date instanceof Date || date instanceof import_dayjs.default) && ((0, import_dayjs.default)(value).isSame(date) || isAfterDate(value, date));
var isSomeBeforeDate = (value, date) => (date instanceof Date || date instanceof import_dayjs.default) && ((0, import_dayjs.default)(value).isSame(date) || isBeforeDate(value, date));
var isAfterDate = (value, date) => (date instanceof Date || date instanceof import_dayjs.default) && (0, import_dayjs.default)(date).isBefore(value, "day");
var isBeforeDate = (value, date) => (date instanceof Date || date instanceof import_dayjs.default) && (0, import_dayjs.default)(date).isAfter(value, "day");
var onShouldFocus = (refs, validateFunc, isFirst = true) => {
let targetValue;
let targetEl;
for (const value of refs.current.keys()) {
const selected = validateFunc(value);
if (selected) targetValue = value;
}
if (typeof targetValue === "number") {
const ref = refs.current.get(targetValue);
targetEl = ref == null ? void 0 : ref.current;
} else {
const values = [...refs.current.values()];
const firstRef = values[0];
const lastRef = values[values.length - 1];
targetEl = isFirst ? firstRef == null ? void 0 : firstRef.current : lastRef == null ? void 0 : lastRef.current;
}
if (targetEl) {
targetEl.focus();
targetEl.tabIndex = 0;
}
};
var getFocused = (refs) => {
for (const [value, ref] of refs.current.entries()) {
const focused = ref.current ? (0, import_utils.isActiveElement)(ref.current) : false;
if (focused) return value;
}
};
var getRangeFirstDay = (refs) => {
const days = [...refs.current.keys()];
return days[0];
};
var getRangeLastDay = (refs) => {
const days = [...refs.current.keys()];
return days[days.length - 1];
};
var disableAllTabIndex = (refs) => {
for (const ref of refs.current.values()) {
if (ref.current) ref.current.tabIndex = -1;
}
};
var isDisabledDate = ({
disableOutsideDays,
endDate,
excludeDate,
maxDate,
maxTrulySelectStartDate,
maybeEndDate,
maybeStartDate,
minDate,
minTrulySelectStartDate,
outside,
startDate,
value
}) => isAfterDate(value, maxDate) || isBeforeDate(value, minDate) || isAfterDate(value, maybeStartDate) && isBeforeDate(value, maxTrulySelectStartDate) && !endDate || isBeforeDate(value, maybeEndDate) && isAfterDate(value, minTrulySelectStartDate) && !startDate || !!(excludeDate == null ? void 0 : excludeDate(value)) || !!disableOutsideDays && !!outside;
// src/use-calendar.ts
var import_core = require("@yamada-ui/core");
var import_use_controllable_state = require("@yamada-ui/use-controllable-state");
var import_utils2 = require("@yamada-ui/utils");
var import_dayjs2 = __toESM(require("dayjs"));
var import_react = require("react");
var [CalendarProvider, useCalendarContext] = (0, import_utils2.createContext)({
name: "CalendarContext",
errorMessage: `useCalendarContext returned is 'undefined'. Seems you forgot to wrap the components in "<Calendar />"`
});
// src/use-month.tsx
var useMonth = () => {
const {
amountOfMonths,
dateFormat,
dayRefs,
disableOutsideDays,
enableRange,
excludeDate,
hiddenOutsideDays,
holidays,
hoveredValue,
locale,
maxDate,
maxSelectValues,
minDate,
minSelectValues,
month,
nextMonth,
paginateBy,
prevMonth,
setHoveredValue,
setMonth,
setValue,
today,
value: selectedValue,
weekendDays
} = useCalendarContext();
const beforeMonth = (0, import_react2.useRef)(null);
const year = month.getFullYear();
const multi = (0, import_utils3.isArray)(selectedValue);
const range = enableRange && multi;
const rangeSelectedValue = range ? sortDates(selectedValue.filter(Boolean)) : [];
const max = multi && maxSelectValues === selectedValue.length;
const reversed = !!rangeSelectedValue[0] && isAfterDate(rangeSelectedValue[0], hoveredValue);
const startDate = range ? rangeSelectedValue[!reversed ? 0 : 1] : void 0;
const endDate = range ? rangeSelectedValue[!reversed ? 1 : 0] : void 0;
const maybeStartDate = startDate != null ? startDate : hoveredValue;
const maybeEndDate = endDate != null ? endDate : hoveredValue;
const shouldBetween = rangeSelectedValue.length >= 1 && !!maybeEndDate;
const shouldHovered = rangeSelectedValue.length === 1;
const hasAmountOfMonths = amountOfMonths >= 2;
const minSelectEndDate = (0, import_utils3.isNumber)(maxSelectValues) ? (0, import_dayjs3.default)(!reversed ? maybeStartDate : maybeEndDate).subtract(maxSelectValues - 1, "day").toDate() : void 0;
const maxSelectEndDate = (0, import_utils3.isNumber)(maxSelectValues) ? (0, import_dayjs3.default)(!reversed ? maybeStartDate : maybeEndDate).add(maxSelectValues - 1, "day").toDate() : void 0;
const minSelectStartDate = (0, import_utils3.isNumber)(minSelectValues) ? (0, import_dayjs3.default)(!reversed ? maybeStartDate : maybeEndDate).subtract(minSelectValues - 1, "day").toDate() : void 0;
const maxSelectStartDate = (0, import_utils3.isNumber)(minSelectValues) ? (0, import_dayjs3.default)(!reversed ? maybeStartDate : maybeEndDate).add(minSelectValues - 1, "day").toDate() : void 0;
const invalidRangeDates = (0, import_utils3.isNumber)(maxSelectValues) && Math.abs((0, import_dayjs3.default)(startDate).diff(endDate, "day")) >= maxSelectValues;
const minTrulySelectEndDate = shouldHovered || invalidRangeDates ? minSelectEndDate : void 0;
const maxTrulySelectEndDate = shouldHovered || invalidRangeDates ? maxSelectEndDate : void 0;
const minTrulySelectStartDate = shouldHovered || invalidRangeDates ? minSelectStartDate : void 0;
const maxTrulySelectStartDate = shouldHovered || invalidRangeDates ? maxSelectStartDate : void 0;
const onFocusPrev = (0, import_react2.useCallback)(
(targetIndex, targetMonth, targetDay) => {
var _a, _b;
const [firstIndex, , firstDay] = (_b = (_a = getRangeFirstDay(dayRefs)) == null ? void 0 : _a.split("-").map(Number)) != null ? _b : [];
if (firstIndex === targetDay && firstDay && targetDay < firstDay) {
if (!isMonthInRange({ date: prevMonth, maxDate, minDate })) return;
dayRefs.current.clear();
setMonth((prev) => {
beforeMonth.current = prev;
return (0, import_dayjs3.default)(prev).subtract(paginateBy, "months").toDate();
});
} else {
const ref = dayRefs.current.get(
`${targetIndex}-${targetMonth}-${targetDay}`
);
if (ref == null ? void 0 : ref.current) {
if (shouldHovered)
setHoveredValue((0, import_dayjs3.default)(ref.current.dataset.value).toDate());
ref.current.focus();
ref.current.tabIndex = 0;
}
}
},
[
shouldHovered,
dayRefs,
maxDate,
minDate,
paginateBy,
prevMonth,
setMonth,
setHoveredValue
]
);
const onFocusNext = (0, import_react2.useCallback)(
(targetIndex, targetMonth, targetDay) => {
var _a, _b;
const [lastIndex, , lastDay] = (_b = (_a = getRangeLastDay(dayRefs)) == null ? void 0 : _a.split("-").map(Number)) != null ? _b : [];
if (lastIndex === targetIndex && lastDay && lastDay < targetDay) {
if (!isMonthInRange({ date: nextMonth, maxDate, minDate })) return;
dayRefs.current.clear();
setMonth((prev) => {
beforeMonth.current = prev;
return (0, import_dayjs3.default)(prev).add(paginateBy, "months").toDate();
});
} else {
const ref = dayRefs.current.get(
`${targetIndex}-${targetMonth}-${targetDay}`
);
if (ref == null ? void 0 : ref.current) {
if (shouldHovered)
setHoveredValue((0, import_dayjs3.default)(ref.current.dataset.value).toDate());
ref.current.focus();
ref.current.tabIndex = 0;
}
}
},
[
shouldHovered,
dayRefs,
maxDate,
minDate,
nextMonth,
paginateBy,
setMonth,
setHoveredValue
]
);
const onKeyDown = (0, import_react2.useCallback)(
(ev) => {
var _a, _b, _c, _d, _e;
const [focusedIndex, focusedMonth, focusedDay] = ((_a = getFocused(dayRefs)) != null ? _a : "").split("-").map(Number);
const [firstIndex, firstMonth, firstDay] = (_c = (_b = getRangeFirstDay(dayRefs)) == null ? void 0 : _b.split("-").map(Number)) != null ? _c : [];
const [lastIndex, lastMonth, lastDay] = (_e = (_d = getRangeLastDay(dayRefs)) == null ? void 0 : _d.split("-").map(Number)) != null ? _e : [];
const actions = {
ArrowDown: () => {
if (!(0, import_utils3.isNumber)(focusedMonth)) return;
const lastOfMonthDay = (0, import_dayjs3.default)(new Date(year, focusedMonth)).endOf("month").date();
if (focusedDay && focusedDay + 7 <= lastOfMonthDay)
onFocusNext(focusedIndex != null ? focusedIndex : -1, focusedMonth, focusedDay + 7);
},
ArrowLeft: () => {
if (focusedIndex !== firstIndex) {
if (!(0, import_utils3.isNumber)(focusedMonth)) return;
const firstOfMonthDay = (0, import_dayjs3.default)(new Date(year, focusedMonth)).startOf("month").date();
if (focusedDay && firstOfMonthDay < focusedDay) {
onFocusNext(focusedIndex != null ? focusedIndex : -1, focusedMonth, focusedDay - 1);
} else {
const prevLastOfMonthDay = (0, import_dayjs3.default)(new Date(year, focusedMonth)).subtract(1, "month").endOf("month").date();
onFocusNext(
focusedIndex ? focusedIndex - 1 : -1,
focusedMonth - 1,
prevLastOfMonthDay
);
}
} else if ((0, import_utils3.isNumber)(focusedMonth) && (0, import_utils3.isNumber)(focusedDay)) {
onFocusPrev(focusedIndex != null ? focusedIndex : -1, focusedMonth, focusedDay - 1);
}
},
ArrowRight: () => {
if (focusedIndex !== lastIndex) {
if (!(0, import_utils3.isNumber)(focusedMonth)) return;
const lastOfMonthDay = (0, import_dayjs3.default)(new Date(year, focusedMonth)).endOf("month").date();
if (focusedDay && focusedDay < lastOfMonthDay) {
onFocusNext(focusedIndex != null ? focusedIndex : -1, focusedMonth, focusedDay + 1);
} else {
const nextFirstOfMonthDay = (0, import_dayjs3.default)(new Date(year, focusedMonth)).add(1, "month").startOf("month").date();
onFocusNext(
focusedIndex ? focusedIndex + 1 : -1,
focusedMonth + 1,
nextFirstOfMonthDay
);
}
} else if ((0, import_utils3.isNumber)(focusedMonth) && (0, import_utils3.isNumber)(focusedDay)) {
onFocusNext(focusedIndex != null ? focusedIndex : -1, focusedMonth, focusedDay + 1);
}
},
ArrowUp: () => {
if (!(0, import_utils3.isNumber)(focusedMonth)) return;
const firstOfMonthDay = (0, import_dayjs3.default)(new Date(year, focusedMonth)).startOf("month").date();
if (focusedDay && focusedDay - 7 >= firstOfMonthDay)
onFocusNext(focusedIndex != null ? focusedIndex : -1, focusedMonth, focusedDay - 7);
},
End: () => (0, import_utils3.isNumber)(lastMonth) && (0, import_utils3.isNumber)(lastDay) ? onFocusNext(lastIndex != null ? lastIndex : -1, lastMonth, lastDay) : void 0,
Home: () => (0, import_utils3.isNumber)(firstMonth) && (0, import_utils3.isNumber)(firstDay) ? onFocusPrev(firstIndex != null ? firstIndex : -1, firstMonth, firstDay) : void 0
};
const action = actions[ev.key];
if (!action) return;
ev.preventDefault();
ev.stopPropagation();
disableAllTabIndex(dayRefs);
action(ev);
},
[dayRefs, onFocusNext, onFocusPrev, year]
);
const onClick = (0, import_react2.useCallback)(
(ev, newValue) => {
ev.preventDefault();
ev.stopPropagation();
const el = (0, import_utils3.getEventRelatedTarget)(ev);
if (!el || (0, import_utils3.isDisabled)(el)) return;
setValue((prev) => {
if (!(0, import_utils3.isArray)(prev)) {
return newValue;
} else if (range) {
prev = prev.filter(Boolean);
const exceeded = prev.length >= 2;
if (!exceeded) {
const selected = prev.some((value) => isSameDate(value, newValue));
return selected ? [] : sortDates([...prev, newValue]);
} else {
return [newValue];
}
} else {
const selected = prev.some((value) => isSameDate(value, newValue));
if (!selected) {
return [...prev, newValue];
} else {
return prev.filter(
(value) => !isSameDate(value, newValue)
);
}
}
});
},
[setValue, range]
);
const onPointerEnter = (0, import_react2.useCallback)(
(value) => {
if (shouldHovered) setHoveredValue(value);
},
[shouldHovered, setHoveredValue]
);
(0, import_utils3.useUpdateEffect)(() => {
if (!(beforeMonth.current instanceof Date)) return;
onShouldFocus(dayRefs, () => false, beforeMonth.current < month);
beforeMonth.current = null;
}, [month.getMonth()]);
(0, import_utils3.useUnmountEffect)(() => {
dayRefs.current.clear();
});
const getGridProps = (0, import_react2.useCallback)(
({ month: month2, ...props }) => {
const label = getFormattedLabel(month2, locale, dateFormat);
return {
"aria-label": label,
"aria-multiselectable": (0, import_utils3.ariaAttr)(multi),
role: "grid",
...props,
onKeyDown: (0, import_utils3.handlerAll)(onKeyDown, props.onKeyDown)
};
},
[onKeyDown, multi, locale, dateFormat]
);
const getButtonProps = (0, import_react2.useCallback)(
({ index, month: month2, value, ...props }, ref = null) => {
const controlled = beforeMonth.current instanceof Date;
const holiday = holidays.some((holiday2) => isSameDate(holiday2, value));
const outside = !isSameMonth(month2, value);
const weekend = weekendDays.includes(value.getDay());
const hidden = hiddenOutsideDays && outside;
const selected = !multi ? isSameDate(selectedValue, value) : selectedValue.some(
(selectedValue2) => isSameDate(selectedValue2, value)
);
const trulySelected = selected && (!hasAmountOfMonths || !outside);
const selectedMonth = !multi ? isSameMonth(month2, selectedValue) : selectedValue.some(
(selectedValue2) => isSameMonth(month2, selectedValue2)
);
const _today = today && isSameDate(/* @__PURE__ */ new Date(), value);
const disabled = isDisabledDate({
disableOutsideDays,
endDate,
excludeDate,
maxDate: maxTrulySelectEndDate != null ? maxTrulySelectEndDate : maxDate,
maxTrulySelectStartDate,
maybeEndDate,
maybeStartDate,
minDate: minTrulySelectEndDate != null ? minTrulySelectEndDate : minDate,
minTrulySelectStartDate,
outside,
startDate,
value
});
const trulyDisabled = disabled || !selected && max;
const firstDate = value.getDate() === 1;
const shouldFocus = !selectedMonth && !outside && firstDate || selected;
const start = range && isSameDate(maybeStartDate, value) && !isSameDate(maybeEndDate, value);
const end = range && isSameDate(maybeEndDate, value) && !isSameDate(maybeStartDate, value);
const trulyStart = start && (!hasAmountOfMonths || !outside);
const trulyEnd = end && (!hasAmountOfMonths || !outside);
const between = shouldBetween && !isSameDate(maybeStartDate, maybeEndDate) && !hidden && isInRange(value, maybeStartDate, maybeEndDate);
const key = `${index}-${value.getMonth()}-${value.getDate()}`;
if (!outside) dayRefs.current.set(key, (0, import_react2.createRef)());
return {
ref: (0, import_utils3.mergeRefs)(ref, !outside ? dayRefs.current.get(key) : void 0),
between,
end,
hidden,
outside,
selected,
start,
weekend,
...props,
"aria-disabled": (0, import_utils3.ariaAttr)(trulyDisabled),
"aria-selected": (0, import_utils3.ariaAttr)(trulySelected),
"data-between": (0, import_utils3.dataAttr)(between),
"data-disabled": (0, import_utils3.dataAttr)(trulyDisabled),
"data-end": (0, import_utils3.dataAttr)(trulyEnd),
"data-holiday": (0, import_utils3.dataAttr)(holiday),
"data-outside": (0, import_utils3.dataAttr)(outside),
"data-selected": (0, import_utils3.dataAttr)(trulySelected),
"data-start": (0, import_utils3.dataAttr)(trulyStart),
"data-today": (0, import_utils3.dataAttr)(_today),
"data-value": value.getDate(),
"data-weekend": (0, import_utils3.dataAttr)(weekend),
tabIndex: !!index || controlled ? -1 : shouldFocus ? 0 : -1,
onClick: (0, import_utils3.handlerAll)((ev) => onClick(ev, value), props.onClick),
onPointerEnter: (0, import_utils3.handlerAll)(
() => onPointerEnter(value),
props.onPointerEnter
)
};
},
[
holidays,
weekendDays,
hiddenOutsideDays,
multi,
selectedValue,
hasAmountOfMonths,
today,
minDate,
maxDate,
minTrulySelectEndDate,
maxTrulySelectEndDate,
minTrulySelectStartDate,
maxTrulySelectStartDate,
startDate,
endDate,
excludeDate,
disableOutsideDays,
max,
range,
maybeStartDate,
maybeEndDate,
shouldBetween,
dayRefs,
onClick,
onPointerEnter
]
);
return { getButtonProps, getGridProps };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
useMonth
});
//# sourceMappingURL=use-month.js.map