All files / src/components/CalendarView CalendarView.tsx

90.24% Statements 37/41
62.5% Branches 15/24
92.3% Functions 12/13
89.74% Lines 35/39

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261    14x                                     14x                               14x       39x 39x       39x   39x   39x           39x                   14x                                                                       41x   41x 41x     41x           41x 5x 3x   2x       41x   41x                     2x                           46x                               46x 46x   46x     322x                                     46x 46x 46x 46x 46x     276x                           1932x                                                   1932x   1932x                                          
'use client';
 
import React from 'react';
 
import type {DateTime} from '@gravity-ui/date-utils';
import {ChevronLeft, ChevronRight} from '@gravity-ui/icons';
import {ArrowToggle, Button, useLang, useMobile} from '@gravity-ui/uikit';
 
import {block} from '../../utils/cn';
import type {AccessibilityProps, DomProps, FocusEvents, StyleProps} from '../types';
import {formatDateTime} from '../utils/dates';
 
import type {RangeCalendarState} from './hooks/types';
import {useCalendarCellProps} from './hooks/useCalendarCellProps';
import {useCalendarGridProps} from './hooks/useCalendarGridProps';
import {useCalendarProps} from './hooks/useCalendarProps';
import type {CalendarState} from './hooks/useCalendarState';
import {calendarLayouts, getDaysInPeriod, getWeekDays} from './utils';
 
import './Calendar.scss';
 
const b = block('calendar');
 
export type CalendarSize = 'm' | 'l' | 'xl';
 
export interface CalendarInstance {
    focus: () => void;
}
 
export interface CalendarViewProps extends DomProps, StyleProps, FocusEvents, AccessibilityProps {
    state: CalendarState | RangeCalendarState;
    /**
     * The size of the element.
     * @default m
     */
    size?: CalendarSize;
}
export const CalendarView = React.forwardRef<CalendarInstance, CalendarViewProps>(function Calendar(
    props: CalendarViewProps,
    ref,
) {
    const {state} = props;
    const {calendarProps, modeButtonProps, nextButtonProps, previousButtonProps} = useCalendarProps(
        props,
        state,
    );
    const isMobile = useMobile();
 
    const buttonView = isMobile ? 'outlined' : 'flat';
 
    React.useImperativeHandle(ref, () => ({
        focus() {
            state.setFocused(true);
        },
    }));
 
    return (
        <div
            {...calendarProps}
            className={b({size: props.size}, props.className)}
            style={props.style}
        >
            <div className={b('header')}>
                <Button {...modeButtonProps} view={buttonView} size={props.size}>
                    {state.availableModes.indexOf(state.mode) + 1 ===
                    state.availableModes.length ? (
                        <span key="label" className={b('mode-label', b(`years-label`))}>
                            {modeButtonProps.children}
                        </span>
                    ) : (
                        [
                            <span key="label" className={b('mode-label')}>
                                {modeButtonProps.children}
                            </span>,
                            <Button.Icon key="icon">
                                <ArrowToggle direction="bottom" />
                            </Button.Icon>,
                        ]
                    )}
                </Button>
                <div className={b('controls')}>
                    <Button {...previousButtonProps} view={buttonView} size={props.size}>
                        <Button.Icon>
                            <ChevronLeft className={b('control-icon')} />
                        </Button.Icon>
                    </Button>
                    <Button {...nextButtonProps} view={buttonView} size={props.size}>
                        <Button.Icon>
                            <ChevronRight className={b('control-icon')} />
                        </Button.Icon>
                    </Button>
                </div>
            </div>
            <CalendarGrid state={state} />
        </div>
    );
});
 
interface CalendarGridProps {
    state: CalendarState | RangeCalendarState;
}
function CalendarGrid({state}: CalendarGridProps) {
    const [prevState, setPrevState] = React.useState(() => ({...state, isFocused: false}));
 
    const modeChanged = state.mode !== prevState.mode;
    const startDateChanged = !state.startDate.isSame(prevState.startDate, 'days');
 
    let animation;
    Iif (modeChanged) {
        if (calendarLayouts.indexOf(prevState.mode) > calendarLayouts.indexOf(state.mode)) {
            animation = 'zoom-out';
        } else {
            animation = 'zoom-in';
        }
    } else if (startDateChanged) {
        if (state.startDate.isBefore(prevState.startDate)) {
            animation = 'forward';
        } else {
            animation = 'backward';
        }
    }
 
    const {gridProps} = useCalendarGridProps(state);
 
    return (
        <div className={b('grid')} {...gridProps}>
            {animation && (
                <Content className={b('previous-state')} state={prevState} animation={animation} />
            )}
            <Content
                key="current"
                className={b('current-state')}
                state={state}
                animation={animation}
                onAnimationEnd={() => {
                    setPrevState({...state, isFocused: false});
                }}
            />
        </div>
    );
}
 
interface ContentProps {
    className?: string;
    animation?: string;
    onAnimationEnd?: () => void;
    state: CalendarState | RangeCalendarState;
}
function Content({className, state, animation, onAnimationEnd}: ContentProps) {
    return (
        <div
            className={b('content', {animation}, className)}
            onAnimationEnd={onAnimationEnd}
            role="presentation"
        >
            {state.mode === 'days' && <Weekdays state={state} />}
            <CalendarGridCells state={state} />
        </div>
    );
}
 
interface WeekdaysProps {
    state: CalendarState | RangeCalendarState;
}
function Weekdays({state}: WeekdaysProps) {
    const weekdays = getWeekDays(state);
    const {lang} = useLang();
 
    return (
        <div className={b('grid-row')} role="row">
            {weekdays.map((date) => {
                return (
                    <div
                        key={date.day()}
                        className={b('weekday', {weekend: state.isWeekend(date)})}
                        role="columnheader"
                        aria-label={formatDateTime(date, 'dddd', state.timeZone, lang)}
                    >
                        {formatDateTime(date, 'dd', state.timeZone, lang)}
                    </div>
                );
            })}
        </div>
    );
}
 
interface CalendarGridProps {
    state: CalendarState | RangeCalendarState;
}
function CalendarGridCells({state}: CalendarGridProps) {
    const rowsInPeriod = state.mode === 'days' ? 6 : 4;
    const columnsInRow = state.mode === 'days' ? 7 : 3 + (state.mode === 'quarters' ? 1 : 0);
    const days = getDaysInPeriod(state);
    const {lang} = useLang();
    return (
        <div className={b('grid-rowgroup', {mode: state.mode})} role="rowgroup">
            {[...new Array(rowsInPeriod).keys()].map((rowIndex) => (
                <div key={rowIndex} className={b('grid-row')} role="row">
                    {state.mode === 'quarters' ? (
                        <span role="rowheader" className={b('grid-rowgroup-header')}>
                            {formatDateTime(
                                days[rowIndex * columnsInRow],
                                'YYYY',
                                state.timeZone,
                                lang,
                            )}
                        </span>
                    ) : null}
                    {days
                        .slice(rowIndex * columnsInRow, (rowIndex + 1) * columnsInRow)
                        .map((date) => {
                            return <CalendarCell key={date.unix()} date={date} state={state} />;
                        })}
                </div>
            ))}
        </div>
    );
}
 
interface CalendarCellProps {
    date: DateTime;
    state: CalendarState | RangeCalendarState;
}
function CalendarCell({date, state}: CalendarCellProps) {
    const {
        cellProps,
        buttonProps,
        formattedDate,
        isDisabled,
        isSelected,
        isRangeSelection,
        isSelectionStart,
        isSelectionEnd,
        isOutsideCurrentRange,
        isUnavailable,
        isCurrent,
        isWeekend,
    } = useCalendarCellProps(date, state);
 
    return (
        <div {...cellProps}>
            <div
                {...buttonProps}
                className={b('button', {
                    disabled: isDisabled,
                    selected: isSelected,
                    'range-selection': isRangeSelection,
                    'selection-start': isSelectionStart,
                    'selection-end': isSelectionEnd,
                    'out-of-boundary': isOutsideCurrentRange,
                    unavailable: isUnavailable,
                    current: isCurrent,
                    weekend: isWeekend,
                })}
            >
                {formattedDate}
            </div>
        </div>
    );
}