Debian Codegraph @

node/@patternfly/react-core/dist/esm/components/CalendarMonth/CalendarMonth.js

raw
1 import { __rest } from "tslib";
2 import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3 import { useEffect, useMemo, useRef, useState } from 'react';
4 import { TextInput } from '../TextInput';
5 import { Button } from '../Button';
6 import { Select, SelectList, SelectOption } from '../Select';
7 import { MenuToggle } from '../MenuToggle';
8 import { InputGroup, InputGroupItem } from '../InputGroup';
9 import RhMicronsCaretLeftIcon from '@patternfly/react-icons/dist/esm/icons/rh-microns-caret-left-icon';
10 import RhMicronsCaretRightIcon from '@patternfly/react-icons/dist/esm/icons/rh-microns-caret-right-icon';
11 import { css } from '@patternfly/react-styles';
12 import styles from '@patternfly/react-styles/css/components/CalendarMonth/calendar-month.mjs';
13 import { useSSRSafeId } from '../../helpers';
14 import { isValidDate } from '../../helpers/datetimeUtils';
15 export var Weekday;
16 (function (Weekday) {
17 Weekday[Weekday["Sunday"] = 0] = "Sunday";
18 Weekday[Weekday["Monday"] = 1] = "Monday";
19 Weekday[Weekday["Tuesday"] = 2] = "Tuesday";
20 Weekday[Weekday["Wednesday"] = 3] = "Wednesday";
21 Weekday[Weekday["Thursday"] = 4] = "Thursday";
22 Weekday[Weekday["Friday"] = 5] = "Friday";
23 Weekday[Weekday["Saturday"] = 6] = "Saturday";
24 })(Weekday || (Weekday = {}));
25 const buildCalendar = (year, month, weekStart, validators) => {
26 const defaultDate = new Date(year, month);
27 const firstDayOfWeek = new Date(defaultDate);
28 firstDayOfWeek.setDate(firstDayOfWeek.getDate() - firstDayOfWeek.getDay() + weekStart);
29 // We will show a maximum of 6 weeks like Google calendar
30 // Assume we just want the numbers for now...
31 const calendarWeeks = [];
32 if (firstDayOfWeek.getMonth() === defaultDate.getMonth() && firstDayOfWeek.getDate() !== 1) {
33 firstDayOfWeek.setDate(firstDayOfWeek.getDate() - 7);
34 }
35 for (let i = 0; i < 6; i++) {
36 const week = [];
37 for (let j = 0; j < 7; j++) {
38 const date = new Date(firstDayOfWeek);
39 week.push({
40 date,
41 isValid: validators.every((validator) => validator(date))
42 });
43 firstDayOfWeek.setDate(firstDayOfWeek.getDate() + 1);
44 }
45 calendarWeeks.push(week);
46 if (firstDayOfWeek.getMonth() !== defaultDate.getMonth()) {
47 break;
48 }
49 }
50 return calendarWeeks;
51 };
52 const isSameDate = (d1, d2) => d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth() && d1.getDate() === d2.getDate();
53 const today = new Date();
54 /** The main calendar month component. */
55 export const CalendarMonth = (_a) => {
56 var { date: dateProp, locale = undefined, monthFormat = (date) => date.toLocaleDateString(locale, { month: 'long' }), weekdayFormat = (date) => date.toLocaleDateString(locale, { weekday: 'narrow' }), longWeekdayFormat = (date) => date.toLocaleDateString(locale, { weekday: 'long' }), dayFormat = (date) => date.getDate(), weekStart = 0, // Use the American Sunday as a default
57 onChange = () => { }, validators = [() => true], className, onSelectToggle = () => { }, onMonthChange = () => { }, rangeStart, prevMonthAriaLabel = 'Previous month', nextMonthAriaLabel = 'Next month', yearInputAriaLabel = 'Select year', cellAriaLabel, isDateFocused = false, inlineProps, monthAppendTo = 'inline' } = _a, props = __rest(_a, ["date", "locale", "monthFormat", "weekdayFormat", "longWeekdayFormat", "dayFormat", "weekStart", "onChange", "validators", "className", "onSelectToggle", "onMonthChange", "rangeStart", "prevMonthAriaLabel", "nextMonthAriaLabel", "yearInputAriaLabel", "cellAriaLabel", "isDateFocused", "inlineProps", "monthAppendTo"]);
58 const longMonths = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
59 .map((monthNum) => new Date(1990, monthNum))
60 .map(monthFormat);
61 const [isSelectOpen, setIsSelectOpen] = useState(false);
62 const getInitialDate = () => {
63 if (isValidDate(dateProp)) {
64 return dateProp;
65 }
66 if (isValidDate(rangeStart)) {
67 return rangeStart;
68 }
69 return today;
70 };
71 const initialDate = getInitialDate();
72 const [focusedDate, setFocusedDate] = useState(initialDate);
73 // Must be numeric given current header design
74 const yearFormat = (date) => date.getFullYear();
75 //
76 const yearFormatted = yearFormat(focusedDate);
77 const [yearInput, setYearInput] = useState(yearFormatted.toString());
78 const [hoveredDate, setHoveredDate] = useState(undefined);
79 const focusRef = useRef(undefined);
80 const hiddenMonthId = useSSRSafeId('hidden-month-span');
81 const [shouldFocus, setShouldFocus] = useState(false);
82 const isValidated = (date) => validators.every((validator) => validator(date));
83 const focusedDateValidated = isValidated(focusedDate);
84 useEffect(() => {
85 if (isValidDate(dateProp) && !isSameDate(focusedDate, dateProp)) {
86 setFocusedDate(dateProp);
87 }
88 else if (!dateProp) {
89 setFocusedDate(today);
90 }
91 }, [dateProp]);
92 useEffect(() => {
93 // Calendar month should not be focused on page load
94 if ((shouldFocus || isDateFocused) && focusedDateValidated && focusRef.current) {
95 focusRef.current.focus();
96 }
97 }, [focusedDate, isDateFocused, focusedDateValidated, focusRef]);
98 const onMonthClick = (ev, newDate) => {
99 setFocusedDate(newDate);
100 setShouldFocus(false);
101 onMonthChange(ev, newDate);
102 setYearInput(yearFormat(newDate).toString());
103 };
104 const onKeyDown = (ev) => {
105 const newDate = new Date(focusedDate);
106 if (ev.key === 'ArrowUp') {
107 newDate.setDate(newDate.getDate() - 7);
108 }
109 else if (ev.key === 'ArrowRight') {
110 newDate.setDate(newDate.getDate() + 1);
111 }
112 else if (ev.key === 'ArrowDown') {
113 newDate.setDate(newDate.getDate() + 7);
114 }
115 else if (ev.key === 'ArrowLeft') {
116 newDate.setDate(newDate.getDate() - 1);
117 }
118 if (newDate.getTime() !== focusedDate.getTime() && isValidated(newDate)) {
119 ev.preventDefault();
120 setFocusedDate(newDate);
121 setShouldFocus(true);
122 }
123 };
124 const changeYear = (newYear) => changeMonth(focusedDate.getMonth(), newYear);
125 const changeMonth = (newMonth, newYear) => new Date(newYear !== null && newYear !== void 0 ? newYear : focusedDate.getFullYear(), newMonth, 1);
126 const MIN_YEAR = 1900;
127 const MAX_YEAR = 2100;
128 const handleYearInputChange = (event, yearStr) => {
129 if (!/^\d{0,4}$/.test(yearStr)) {
130 return;
131 }
132 setYearInput(yearStr);
133 if (yearStr.length === 4) {
134 const yearNum = Number(yearStr);
135 if (yearNum >= MIN_YEAR && yearNum <= MAX_YEAR) {
136 const newDate = changeYear(yearNum);
137 setFocusedDate(newDate);
138 setShouldFocus(false);
139 // We need to manually focus the year input in FireFox when the scroll buttons are clicked, as FireFox doesn't place focus automatically
140 event.target.focus();
141 onMonthChange(event, newDate);
142 }
143 else {
144 setYearInput(yearFormatted.toString());
145 }
146 }
147 };
148 const addMonth = (toAdd) => {
149 let newMonth = focusedDate.getMonth() + toAdd;
150 let newYear = focusedDate.getFullYear();
151 if (newMonth === -1) {
152 newMonth = 11;
153 newYear--;
154 }
155 else if (newMonth === 12) {
156 newMonth = 0;
157 newYear++;
158 }
159 return changeMonth(newMonth, newYear);
160 };
161 const prevMonth = addMonth(-1);
162 const nextMonth = addMonth(1);
163 const focusedYear = focusedDate.getFullYear();
164 const focusedMonth = focusedDate.getMonth();
165 const calendar = useMemo(() => buildCalendar(focusedYear, focusedMonth, weekStart, validators), [focusedYear, focusedMonth, weekStart, validators]);
166 if (!focusedDateValidated) {
167 const toFocus = calendar
168 .reduce((acc, cur) => [...acc, ...cur], [])
169 .filter(({ date, isValid }) => isValid && date.getMonth() === focusedMonth)
170 .map(({ date }) => ({ date, days: Math.abs(focusedDate.getTime() - date.getTime()) }))
171 .sort((o1, o2) => o1.days - o2.days)
172 .map(({ date }) => date)[0];
173 if (toFocus) {
174 setFocusedDate(toFocus);
175 }
176 }
177 const isHoveredDateValid = hoveredDate && isValidated(hoveredDate);
178 const monthFormatted = monthFormat(focusedDate);
179 const calendarToRender = (_jsxs("div", Object.assign({ className: css(styles.calendarMonth, className) }, props, { children: [_jsxs("div", { className: styles.calendarMonthHeader, children: [_jsx("div", { className: css(styles.calendarMonthHeaderNavControl, 'pf-m-prev-month'), children: _jsx(Button, { variant: "plain", "aria-label": prevMonthAriaLabel, onClick: (ev) => onMonthClick(ev, prevMonth), icon: _jsx(RhMicronsCaretLeftIcon, {}) }) }), _jsxs(InputGroup, { children: [_jsx(InputGroupItem, { isFill: true, children: _jsxs("div", { className: styles.calendarMonthHeaderMonth, children: [_jsx("span", { id: hiddenMonthId, hidden: true, children: "Month" }), _jsx(Select, { toggle: (toggleRef) => (_jsx(MenuToggle, { ref: toggleRef, onClick: () => setIsSelectOpen(!isSelectOpen), isExpanded: isSelectOpen, style: { width: '140px' }, children: monthFormatted })), "aria-labelledby": hiddenMonthId, isOpen: isSelectOpen, onOpenChange: (isOpen) => {
180 setIsSelectOpen(isOpen);
181 onSelectToggle(isOpen);
182 }, onSelect: (ev, monthNum) => {
183 setIsSelectOpen(false);
184 onSelectToggle(false);
185 const newDate = changeMonth(Number(monthNum));
186 setFocusedDate(newDate);
187 setShouldFocus(false);
188 onMonthChange(ev, newDate);
189 }, selected: monthFormatted, popperProps: { appendTo: monthAppendTo }, children: _jsx(SelectList, { children: longMonths.map((longMonth, index) => (_jsx(SelectOption, { value: index, isSelected: longMonth === monthFormatted, children: longMonth }, index))) }) })] }) }), _jsx(InputGroupItem, { children: _jsx("div", { className: styles.calendarMonthHeaderYear, children: _jsx(TextInput, { "aria-label": yearInputAriaLabel, type: "number", value: yearInput, onChange: handleYearInputChange }) }) })] }), _jsx("div", { className: css(styles.calendarMonthHeaderNavControl, 'pf-m-next-month'), children: _jsx(Button, { variant: "plain", "aria-label": nextMonthAriaLabel, onClick: (ev) => onMonthClick(ev, nextMonth), icon: _jsx(RhMicronsCaretRightIcon, {}) }) })] }), _jsxs("table", { className: styles.calendarMonthCalendar, onMouseLeave: () => setHoveredDate(undefined), children: [_jsx("thead", { className: styles.calendarMonthDays, children: _jsx("tr", { children: calendar[0].map(({ date }, index) => (_jsxs("th", { className: styles.calendarMonthDay, scope: "col", children: [_jsx("span", { className: "pf-v6-screen-reader", children: longWeekdayFormat(date) }), _jsx("span", { "aria-hidden": true, children: weekdayFormat(date) })] }, index))) }) }), _jsx("tbody", { onKeyDown: onKeyDown, children: calendar.map((week, index) => (_jsx("tr", { className: styles.calendarMonthDatesRow, children: week.map(({ date, isValid }, index) => {
190 const dayFormatted = dayFormat(date);
191 const isToday = isSameDate(date, today);
192 const isSelected = isValidDate(dateProp) && isSameDate(date, dateProp);
193 const isFocused = isSameDate(date, focusedDate);
194 const isAdjacentMonth = date.getMonth() !== focusedDate.getMonth();
195 const isRangeStart = isValidDate(rangeStart) && isSameDate(date, rangeStart);
196 let isInRange = false;
197 let isRangeEnd = false;
198 if (isValidDate(rangeStart)) {
199 let rangeEndDate;
200 if (isValidDate(dateProp)) {
201 rangeEndDate = dateProp;
202 }
203 if (isHoveredDateValid && (!isValidDate(dateProp) || hoveredDate > dateProp)) {
204 rangeEndDate = hoveredDate;
205 }
206 if (rangeEndDate) {
207 isInRange = date >= rangeStart && date <= rangeEndDate;
208 isRangeEnd = isSameDate(date, rangeEndDate);
209 }
210 // Core would likely need new styles for "is selected but disabled"
211 }
212 return (_jsx("td", { className: css(styles.calendarMonthDatesCell, isAdjacentMonth && styles.modifiers.adjacentMonth, isToday && styles.modifiers.current, (isSelected || isRangeStart) && styles.modifiers.selected, !isValid && !(isInRange || isRangeStart || isRangeEnd || isSelected) && styles.modifiers.disabled, isInRange && styles.modifiers.inRange, isRangeStart && styles.modifiers.startRange, isRangeEnd && styles.modifiers.endRange), children: _jsx("button", Object.assign({ className: css(styles.calendarMonthDate, isRangeEnd && styles.modifiers.hover, !isValid && styles.modifiers.disabled), type: "button", onClick: (event) => onChange(event, date), onMouseOver: () => setHoveredDate(date), tabIndex: isFocused ? 0 : -1, disabled: !isValid, "aria-label": cellAriaLabel
213 ? cellAriaLabel(date)
214 : `${dayFormat(date)} ${monthFormat(date)} ${yearFormat(date)}` }, (isFocused && { ref: focusRef }), { children: dayFormatted })) }, index));
215 }) }, index))) })] })] })));
216 if (inlineProps !== undefined) {
217 const Component = (inlineProps.component ? inlineProps.component : 'article');
218 return (_jsxs(Component, Object.assign({}, (inlineProps.ariaLabelledby && { 'aria-labelledby': inlineProps.ariaLabelledby }), { children: [inlineProps.title, calendarToRender] })));
219 }
220 return calendarToRender;
221 };
222 CalendarMonth.displayName = 'CalendarMonth';
223 //# sourceMappingURL=CalendarMonth.js.map