Debian Codegraph @

node/@patternfly/react-core/src/components/CalendarMonth/CalendarMonth.tsx

raw
1 import { useEffect, useMemo, useRef, useState } from 'react';
2 import { TextInput } from '../TextInput';
3 import { Button } from '../Button';
4 import { Select, SelectList, SelectOption } from '../Select';
5 import { MenuToggle, MenuToggleElement } from '../MenuToggle';
6 import { InputGroup, InputGroupItem } from '../InputGroup';
7 import RhMicronsCaretLeftIcon from '@patternfly/react-icons/dist/esm/icons/rh-microns-caret-left-icon';
8 import RhMicronsCaretRightIcon from '@patternfly/react-icons/dist/esm/icons/rh-microns-caret-right-icon';
9 import { css } from '@patternfly/react-styles';
10 import styles from '@patternfly/react-styles/css/components/CalendarMonth/calendar-month';
11 import { useSSRSafeId } from '../../helpers';
12 import { isValidDate } from '../../helpers/datetimeUtils';
13
14 export enum Weekday {
15 Sunday = 0,
16 Monday,
17 Tuesday,
18 Wednesday,
19 Thursday,
20 Friday,
21 Saturday
22 }
23
24 export interface CalendarMonthInlineProps {
25 /** Component wrapping the calendar month when used inline. Recommended to be 'article'. */
26 component?: keyof React.JSX.IntrinsicElements;
27 /** Title of the calendar rendered above the inline calendar month. Recommended to be a 'title' component. */
28 title?: React.ReactNode;
29 /** Id of the accessible label of the calendar month. Recommended to map to the title. */
30 ariaLabelledby?: string;
31 }
32
33 /** Additional properties that extend from and can be passed to the main component. These
34 * properties allow customizing the calendar formatting and aria-labels.
35 */
36
37 export interface CalendarFormat {
38 /** Accessible label for the date cells. */
39 cellAriaLabel?: (date: Date) => string;
40 /** How to format days in buttons in table cells. */
41 dayFormat?: (date: Date) => React.ReactNode;
42 /** If using the default formatters which locale to use. Undefined defaults to current locale.
43 * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation
44 */
45 locale?: string;
46 /** How to format days in header for screen readers. */
47 longWeekdayFormat?: (date: Date) => React.ReactNode;
48 /** How to format months in month select. */
49 monthFormat?: (date: Date) => React.ReactNode;
50 /** Accessible label for the previous month button. */
51 prevMonthAriaLabel?: string;
52 /** Accessible label for the next month button. */
53 nextMonthAriaLabel?: string;
54 /** Which date to start range styles from. */
55 rangeStart?: Date;
56 /** How to format week days in header. */
57 weekdayFormat?: (date: Date) => React.ReactNode;
58 /** Day of week that starts the week. 0 is Sunday, 6 is Saturday. */
59 weekStart?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | Weekday;
60 /** Accessible label for the year input. */
61 yearInputAriaLabel?: string;
62 /** Props used to ensure accessibility when displaying the calendar month inline. */
63 inlineProps?: CalendarMonthInlineProps;
64 }
65
66 export interface CalendarProps extends CalendarFormat, Omit<React.HTMLProps<HTMLDivElement>, 'onChange'> {
67 /** Additional classes to add to the outer div of the calendar month. */
68 className?: string;
69 /** Month/year to base other dates around. */
70 date?: Date;
71 /** Flag to set browser focus on the passed date. **/
72 isDateFocused?: boolean;
73 /** Callback when date is selected. */
74 onChange?: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>, date: Date) => void;
75 /** Callback when month or year is changed. */
76 onMonthChange?: (
77 event?: React.MouseEvent | React.ChangeEvent | React.FormEvent<HTMLInputElement>,
78 newDate?: Date
79 ) => void;
80 /** @hide Internal prop to allow pressing escape in select menu to not close popover. */
81 onSelectToggle?: (open: boolean) => void;
82 /** Functions that returns if a date is valid and selectable. */
83 validators?: ((date: Date) => boolean)[];
84 /** The container to append the month select menu to. Defaults to 'inline'.
85 * If your menu is being cut off you can append it to an element higher up the DOM tree.
86 * Some examples:
87 * monthAppendTo={() => document.body};
88 * monthAppendTo={document.getElementById('target')}
89 */
90 monthAppendTo?: HTMLElement | ((ref?: HTMLElement) => HTMLElement) | 'inline';
91 }
92
93 const buildCalendar = (year: number, month: number, weekStart: number, validators: ((date: Date) => boolean)[]) => {
94 const defaultDate = new Date(year, month);
95
96 const firstDayOfWeek = new Date(defaultDate);
97 firstDayOfWeek.setDate(firstDayOfWeek.getDate() - firstDayOfWeek.getDay() + weekStart);
98
99 // We will show a maximum of 6 weeks like Google calendar
100 // Assume we just want the numbers for now...
101 const calendarWeeks = [];
102
103 if (firstDayOfWeek.getMonth() === defaultDate.getMonth() && firstDayOfWeek.getDate() !== 1) {
104 firstDayOfWeek.setDate(firstDayOfWeek.getDate() - 7);
105 }
106 for (let i = 0; i < 6; i++) {
107 const week = [];
108
109 for (let j = 0; j < 7; j++) {
110 const date = new Date(firstDayOfWeek);
111 week.push({
112 date,
113 isValid: validators.every((validator) => validator(date))
114 });
115 firstDayOfWeek.setDate(firstDayOfWeek.getDate() + 1);
116 }
117 calendarWeeks.push(week);
118 if (firstDayOfWeek.getMonth() !== defaultDate.getMonth()) {
119 break;
120 }
121 }
122
123 return calendarWeeks;
124 };
125
126 const isSameDate = (d1: Date, d2: Date) =>
127 d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth() && d1.getDate() === d2.getDate();
128
129 const today = new Date();
130
131 /** The main calendar month component. */
132
133 export const CalendarMonth = ({
134 date: dateProp,
135 locale = undefined,
136 monthFormat = (date) => date.toLocaleDateString(locale, { month: 'long' }),
137 weekdayFormat = (date) => date.toLocaleDateString(locale, { weekday: 'narrow' }),
138 longWeekdayFormat = (date) => date.toLocaleDateString(locale, { weekday: 'long' }),
139 dayFormat = (date) => date.getDate(),
140 weekStart = 0, // Use the American Sunday as a default
141 onChange = () => {},
142 validators = [() => true],
143 className,
144 onSelectToggle = () => {},
145 onMonthChange = () => {},
146 rangeStart,
147 prevMonthAriaLabel = 'Previous month',
148 nextMonthAriaLabel = 'Next month',
149 yearInputAriaLabel = 'Select year',
150 cellAriaLabel,
151 isDateFocused = false,
152 inlineProps,
153 monthAppendTo = 'inline',
154 ...props
155 }: CalendarProps) => {
156 const longMonths = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
157 .map((monthNum) => new Date(1990, monthNum))
158 .map(monthFormat);
159 const [isSelectOpen, setIsSelectOpen] = useState(false);
160
161 const getInitialDate = () => {
162 if (isValidDate(dateProp)) {
163 return dateProp;
164 }
165 if (isValidDate(rangeStart)) {
166 return rangeStart;
167 }
168 return today;
169 };
170 const initialDate = getInitialDate();
171 const [focusedDate, setFocusedDate] = useState(initialDate);
172
173 // Must be numeric given current header design
174 const yearFormat = (date: Date) => date.getFullYear();
175 //
176 const yearFormatted = yearFormat(focusedDate);
177 const [yearInput, setYearInput] = useState(yearFormatted.toString());
178
179 const [hoveredDate, setHoveredDate] = useState<Date>(undefined);
180 const focusRef = useRef<HTMLButtonElement>(undefined);
181 const hiddenMonthId = useSSRSafeId('hidden-month-span');
182 const [shouldFocus, setShouldFocus] = useState(false);
183
184 const isValidated = (date: Date) => validators.every((validator) => validator(date));
185 const focusedDateValidated = isValidated(focusedDate);
186 useEffect(() => {
187 if (isValidDate(dateProp) && !isSameDate(focusedDate, dateProp)) {
188 setFocusedDate(dateProp);
189 } else if (!dateProp) {
190 setFocusedDate(today);
191 }
192 }, [dateProp]);
193
194 useEffect(() => {
195 // Calendar month should not be focused on page load
196 if ((shouldFocus || isDateFocused) && focusedDateValidated && focusRef.current) {
197 focusRef.current.focus();
198 }
199 }, [focusedDate, isDateFocused, focusedDateValidated, focusRef]);
200
201 const onMonthClick = (ev: React.MouseEvent, newDate: Date) => {
202 setFocusedDate(newDate);
203 setShouldFocus(false);
204 onMonthChange(ev, newDate);
205 setYearInput(yearFormat(newDate).toString());
206 };
207
208 const onKeyDown = (ev: React.KeyboardEvent<HTMLTableSectionElement>) => {
209 const newDate = new Date(focusedDate);
210 if (ev.key === 'ArrowUp') {
211 newDate.setDate(newDate.getDate() - 7);
212 } else if (ev.key === 'ArrowRight') {
213 newDate.setDate(newDate.getDate() + 1);
214 } else if (ev.key === 'ArrowDown') {
215 newDate.setDate(newDate.getDate() + 7);
216 } else if (ev.key === 'ArrowLeft') {
217 newDate.setDate(newDate.getDate() - 1);
218 }
219 if (newDate.getTime() !== focusedDate.getTime() && isValidated(newDate)) {
220 ev.preventDefault();
221 setFocusedDate(newDate);
222 setShouldFocus(true);
223 }
224 };
225
226 const changeYear = (newYear: number) => changeMonth(focusedDate.getMonth(), newYear);
227
228 const changeMonth = (newMonth: number, newYear?: number) =>
229 new Date(newYear ?? focusedDate.getFullYear(), newMonth, 1);
230
231 const MIN_YEAR = 1900;
232 const MAX_YEAR = 2100;
233
234 const handleYearInputChange = (event: React.FormEvent<HTMLInputElement>, yearStr: string) => {
235 if (!/^\d{0,4}$/.test(yearStr)) {
236 return;
237 }
238
239 setYearInput(yearStr);
240
241 if (yearStr.length === 4) {
242 const yearNum = Number(yearStr);
243
244 if (yearNum >= MIN_YEAR && yearNum <= MAX_YEAR) {
245 const newDate = changeYear(yearNum);
246 setFocusedDate(newDate);
247 setShouldFocus(false);
248
249 // We need to manually focus the year input in FireFox when the scroll buttons are clicked, as FireFox doesn't place focus automatically
250 (event.target as HTMLElement).focus();
251 onMonthChange(event, newDate);
252 } else {
253 setYearInput(yearFormatted.toString());
254 }
255 }
256 };
257
258 const addMonth = (toAdd: -1 | 1) => {
259 let newMonth = focusedDate.getMonth() + toAdd;
260 let newYear = focusedDate.getFullYear();
261
262 if (newMonth === -1) {
263 newMonth = 11;
264 newYear--;
265 } else if (newMonth === 12) {
266 newMonth = 0;
267 newYear++;
268 }
269
270 return changeMonth(newMonth, newYear);
271 };
272
273 const prevMonth = addMonth(-1);
274 const nextMonth = addMonth(1);
275 const focusedYear = focusedDate.getFullYear();
276 const focusedMonth = focusedDate.getMonth();
277 const calendar = useMemo(
278 () => buildCalendar(focusedYear, focusedMonth, weekStart, validators),
279 [focusedYear, focusedMonth, weekStart, validators]
280 );
281 if (!focusedDateValidated) {
282 const toFocus = calendar
283 .reduce((acc, cur) => [...acc, ...cur], [])
284 .filter(({ date, isValid }) => isValid && date.getMonth() === focusedMonth)
285 .map(({ date }) => ({ date, days: Math.abs(focusedDate.getTime() - date.getTime()) }))
286 .sort((o1, o2) => o1.days - o2.days)
287 .map(({ date }) => date)[0];
288 if (toFocus) {
289 setFocusedDate(toFocus);
290 }
291 }
292 const isHoveredDateValid = hoveredDate && isValidated(hoveredDate);
293 const monthFormatted = monthFormat(focusedDate);
294
295 const calendarToRender = (
296 <div className={css(styles.calendarMonth, className)} {...props}>
297 <div className={styles.calendarMonthHeader}>
298 <div className={css(styles.calendarMonthHeaderNavControl, 'pf-m-prev-month')}>
299 <Button
300 variant="plain"
301 aria-label={prevMonthAriaLabel}
302 onClick={(ev: React.MouseEvent) => onMonthClick(ev, prevMonth)}
303 icon={<RhMicronsCaretLeftIcon />}
304 />
305 </div>
306 <InputGroup>
307 <InputGroupItem isFill>
308 <div className={styles.calendarMonthHeaderMonth}>
309 <span id={hiddenMonthId} hidden>
310 Month
311 </span>
312 <Select
313 toggle={(toggleRef: React.Ref<MenuToggleElement>) => (
314 <MenuToggle
315 ref={toggleRef}
316 onClick={() => setIsSelectOpen(!isSelectOpen)}
317 isExpanded={isSelectOpen}
318 style={{ width: '140px' } as React.CSSProperties}
319 >
320 {monthFormatted}
321 </MenuToggle>
322 )}
323 aria-labelledby={hiddenMonthId}
324 isOpen={isSelectOpen}
325 onOpenChange={(isOpen) => {
326 setIsSelectOpen(isOpen);
327 onSelectToggle(isOpen);
328 }}
329 onSelect={(ev, monthNum) => {
330 setIsSelectOpen(false);
331 onSelectToggle(false);
332 const newDate = changeMonth(Number(monthNum as string));
333 setFocusedDate(newDate);
334 setShouldFocus(false);
335 onMonthChange(ev, newDate);
336 }}
337 selected={monthFormatted}
338 popperProps={{ appendTo: monthAppendTo }}
339 >
340 <SelectList>
341 {longMonths.map((longMonth, index) => (
342 <SelectOption key={index} value={index} isSelected={longMonth === monthFormatted}>
343 {longMonth}
344 </SelectOption>
345 ))}
346 </SelectList>
347 </Select>
348 </div>
349 </InputGroupItem>
350 <InputGroupItem>
351 <div className={styles.calendarMonthHeaderYear}>
352 <TextInput
353 aria-label={yearInputAriaLabel}
354 type="number"
355 value={yearInput}
356 onChange={handleYearInputChange}
357 />
358 </div>
359 </InputGroupItem>
360 </InputGroup>
361 <div className={css(styles.calendarMonthHeaderNavControl, 'pf-m-next-month')}>
362 <Button
363 variant="plain"
364 aria-label={nextMonthAriaLabel}
365 onClick={(ev: React.MouseEvent) => onMonthClick(ev, nextMonth)}
366 icon={<RhMicronsCaretRightIcon />}
367 />
368 </div>
369 </div>
370 <table className={styles.calendarMonthCalendar} onMouseLeave={() => setHoveredDate(undefined)}>
371 <thead className={styles.calendarMonthDays}>
372 <tr>
373 {calendar[0].map(({ date }, index) => (
374 <th key={index} className={styles.calendarMonthDay} scope="col">
375 <span className="pf-v6-screen-reader">{longWeekdayFormat(date)}</span>
376 <span aria-hidden>{weekdayFormat(date)}</span>
377 </th>
378 ))}
379 </tr>
380 </thead>
381 <tbody onKeyDown={onKeyDown}>
382 {calendar.map((week, index) => (
383 <tr key={index} className={styles.calendarMonthDatesRow}>
384 {week.map(({ date, isValid }, index) => {
385 const dayFormatted = dayFormat(date);
386 const isToday = isSameDate(date, today);
387 const isSelected = isValidDate(dateProp) && isSameDate(date, dateProp);
388 const isFocused = isSameDate(date, focusedDate);
389 const isAdjacentMonth = date.getMonth() !== focusedDate.getMonth();
390 const isRangeStart = isValidDate(rangeStart) && isSameDate(date, rangeStart);
391 let isInRange = false;
392 let isRangeEnd = false;
393 if (isValidDate(rangeStart)) {
394 let rangeEndDate: Date;
395
396 if (isValidDate(dateProp)) {
397 rangeEndDate = dateProp;
398 }
399 if (isHoveredDateValid && (!isValidDate(dateProp) || hoveredDate > dateProp)) {
400 rangeEndDate = hoveredDate;
401 }
402
403 if (rangeEndDate) {
404 isInRange = date >= rangeStart && date <= rangeEndDate;
405 isRangeEnd = isSameDate(date, rangeEndDate);
406 }
407 // Core would likely need new styles for "is selected but disabled"
408 }
409
410 return (
411 <td
412 key={index}
413 className={css(
414 styles.calendarMonthDatesCell,
415 isAdjacentMonth && styles.modifiers.adjacentMonth,
416 isToday && styles.modifiers.current,
417 (isSelected || isRangeStart) && styles.modifiers.selected,
418 !isValid && !(isInRange || isRangeStart || isRangeEnd || isSelected) && styles.modifiers.disabled,
419 isInRange && styles.modifiers.inRange,
420 isRangeStart && styles.modifiers.startRange,
421 isRangeEnd && styles.modifiers.endRange
422 )}
423 >
424 <button
425 className={css(
426 styles.calendarMonthDate,
427 isRangeEnd && styles.modifiers.hover,
428 !isValid && styles.modifiers.disabled
429 )}
430 type="button"
431 onClick={(event) => onChange(event, date)}
432 onMouseOver={() => setHoveredDate(date)}
433 tabIndex={isFocused ? 0 : -1}
434 disabled={!isValid}
435 aria-label={
436 cellAriaLabel
437 ? cellAriaLabel(date)
438 : `${dayFormat(date)} ${monthFormat(date)} ${yearFormat(date)}`
439 }
440 {...(isFocused && { ref: focusRef })}
441 >
442 {dayFormatted}
443 </button>
444 </td>
445 );
446 })}
447 </tr>
448 ))}
449 </tbody>
450 </table>
451 </div>
452 );
453
454 if (inlineProps !== undefined) {
455 const Component = (inlineProps.component ? inlineProps.component : 'article') as any;
456 return (
457 <Component {...(inlineProps.ariaLabelledby && { 'aria-labelledby': inlineProps.ariaLabelledby })}>
458 {inlineProps.title}
459 {calendarToRender}
460 </Component>
461 );
462 }
463 return calendarToRender;
464 };
465 CalendarMonth.displayName = 'CalendarMonth';