All files / src/components/DatePicker/hooks useDatePickerProps.ts

58.49% Statements 31/53
49.01% Branches 25/51
33.33% Functions 3/9
58.49% Lines 31/53

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 2049x   9x                                                               42x   42x         42x   42x 22x       2x 2x   20x 20x 2x 2x 18x           42x       4x 4x 2x         42x   42x   42x   42x 42x 42x               42x 42x   42x   42x 42x   42x                   2x                                                                                                                                                                                                  
import React from 'react';
 
import {isDateTime} from '@gravity-ui/date-utils';
import type {DateTime} from '@gravity-ui/date-utils';
import {useFocusWithin, useForkRef} from '@gravity-ui/uikit';
import type {ButtonButtonProps, PopupProps, TextInputProps} from '@gravity-ui/uikit';
 
import type {CalendarInstance, CalendarProps} from '../../Calendar';
import {useDateFieldProps} from '../../DateField';
import type {DateFieldProps} from '../../DateField';
import type {RangeValue} from '../../types';
import {filterDOMProps} from '../../utils/filterDOMProps';
import {getButtonSizeForInput} from '../../utils/getButtonSizeForInput';
import {mergeProps} from '../../utils/mergeProps';
import type {DatePickerProps} from '../DatePicker';
import {i18n} from '../i18n';
import {getCalendarModes, getDateTimeValue} from '../utils';
 
import type {DatePickerState} from './useDatePickerState';
 
interface InnerDatePickerProps<T = DateTime> {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    groupProps: React.HTMLAttributes<unknown> & {ref: React.Ref<any>};
    fieldProps: TextInputProps;
    calendarButtonProps: ButtonButtonProps & {ref: React.Ref<HTMLButtonElement>};
    popupProps: PopupProps;
    calendarProps: CalendarProps<T> & {ref: React.Ref<CalendarInstance>};
    timeInputProps: DateFieldProps<T>;
}
 
export function useDatePickerProps<T extends DateTime | RangeValue<DateTime>>(
    state: DatePickerState<T>,
    {onFocus, onBlur, ...props}: DatePickerProps<T>,
): InnerDatePickerProps<T> {
    const [isActive, setActive] = React.useState(false);
 
    const [focusedDate, setFocusedDate] = React.useState(
        isDateTime(state.dateFieldState.displayValue)
            ? state.dateFieldState.displayValue
            : state.dateFieldState.displayValue.start,
    );
    const [prevDateValue, setPrevDateValue] = React.useState(state.dateFieldState.displayValue);
 
    if (isDateTime(prevDateValue)) {
        if (
            isDateTime(state.dateFieldState.displayValue) &&
            !state.dateFieldState.displayValue.isSame(prevDateValue, 'day')
        ) {
            setPrevDateValue(state.dateFieldState.displayValue);
            setFocusedDate(state.dateFieldState.displayValue);
        }
    E} else if (!isDateTime(state.dateFieldState.displayValue)) {
        if (!state.dateFieldState.displayValue.start.isSame(prevDateValue.start, 'day')) {
            setPrevDateValue(state.dateFieldState.displayValue);
            setFocusedDate(state.dateFieldState.displayValue.start);
        I} else if (!state.dateFieldState.displayValue.end.isSame(prevDateValue.end, 'day')) {
            setPrevDateValue(state.dateFieldState.displayValue);
            setFocusedDate(state.dateFieldState.displayValue.end);
        }
    }
 
    const {focusWithinProps} = useFocusWithin({
        onFocusWithin: onFocus,
        onBlurWithin: onBlur,
        onFocusWithinChange(isFocusWithin) {
            setActive(isFocusWithin);
            if (!isFocusWithin) {
                state.setOpen(false, 'FocusOut');
            }
        },
    });
 
    const {inputProps} = useDateFieldProps(state.dateFieldState, props);
 
    const inputRef = React.useRef<HTMLInputElement>(null);
 
    const handleRef = useForkRef(inputRef, inputProps.controlRef);
 
    const calendarRef = React.useRef<CalendarInstance>(null);
    const calendarButtonRef = React.useRef<HTMLButtonElement>(null);
    const groupRef = React.useRef<HTMLElement>(null);
 
    function focusInput() {
        setTimeout(() => {
            inputRef.current?.focus({preventScroll: true});
        });
    }
 
    const onlyTime = state.formatInfo.hasTime && !state.formatInfo.hasDate;
    const calendarModes = getCalendarModes(state.formatInfo);
 
    const {t} = i18n.useTranslation();
 
    const DOMProps = filterDOMProps(props);
    delete DOMProps.id;
 
    return {
        groupProps: {
            ...DOMProps,
            ref: groupRef,
            tabIndex: -1,
            role: 'group',
            ...focusWithinProps,
            style: props.style,
            'aria-disabled': state.disabled || undefined,
            onKeyDown: (e) => {
                Iif (!onlyTime && e.altKey && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
                    e.preventDefault();
                    e.stopPropagation();
                    state.setOpen(true, 'ShortcutKeyDown');
                }
            },
        },
        fieldProps: mergeProps(
            inputProps,
            state.dateFieldState.isEmpty && !isActive && props.placeholder
                ? {value: ''}
                : undefined,
            {
                controlRef: handleRef,
                controlProps: {role: 'combobox', 'aria-expanded': state.isOpen},
            },
        ),
        calendarButtonProps: {
            ref: calendarButtonRef,
            size: getButtonSizeForInput(props.size),
            disabled: state.disabled,
            'aria-label': t('Calendar'),
            'aria-haspopup': 'dialog',
            'aria-expanded': state.isOpen,
            view: 'flat-secondary',
            onClick: () => {
                setActive(true);
                state.setOpen(!state.isOpen, 'TriggerButtonClick');
            },
        },
        popupProps: {
            open: state.isOpen,
            onOpenChange: (open, e, reason) => {
                if (!open) {
                    if (reason === 'escape-key') {
                        state.setOpen(false, 'EscapeKeyDown');
                        focusInput();
                    } else if (reason === 'outside-press') {
                        if (!e?.target || !calendarButtonRef.current?.contains(e.target as Node)) {
                            state.setOpen(false, 'ClickOutside');
                        }
 
                        if (e?.target && groupRef.current?.contains(e.target as Node)) {
                            focusInput();
                        }
                    }
                }
            },
            onTransitionOutComplete: () => {
                setFocusedDate(
                    isDateTime(state.dateFieldState.displayValue)
                        ? state.dateFieldState.displayValue
                        : state.dateFieldState.displayValue.start,
                );
            },
            modal: !props.disableFocusTrap,
            returnFocus: !props.disableFocusTrap,
            disablePortal: props.disablePortal,
            placement: props.popupPlacement,
            offset: props.popupOffset,
            className: props.popupClassName,
            style: props.popupStyle,
        },
        calendarProps: {
            ref: calendarRef,
            autoFocus: true,
            size: props.size === 's' ? 'm' : props.size,
            disabled: props.disabled,
            readOnly: props.readOnly,
            onUpdate: (d) => {
                state.setDateValue(d);
                if (!state.formatInfo.hasTime) {
                    focusInput();
                }
            },
            value: state.dateFieldState.displayValue,
            minValue: props.minValue,
            maxValue: props.maxValue,
            isDateUnavailable: props.isDateUnavailable,
            timeZone: state.timeZone,
            focusedValue: focusedDate,
            onFocusUpdate: setFocusedDate,
            modes: calendarModes,
        },
        timeInputProps: {
            value: state.timeValue,
            placeholderValue: getDateTimeValue(state.dateFieldState.displayValue),
            onUpdate: state.setTimeValue,
            format: state.timeFormat,
            readOnly: state.readOnly,
            disabled: state.disabled,
            timeZone: state.timeZone,
            hasClear: props.hasClear,
            size: props.size,
        },
    };
}