All files / src/components/DateField/hooks useDateFieldState.ts

87.32% Statements 62/71
82.14% Branches 69/84
92.85% Functions 13/14
87.14% Lines 61/70

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 23116x                                                                                         176x           176x     176x   176x 9x     176x 176x           176x   33x             176x 176x 176x 176x   176x 33x     176x 176x 176x         11x 11x 11x     176x 176x 82x               176x     38x       38x           38x 29x 14x       14x 4x 4x       29x 9x 5x         25x 25x 25x         4x 4x 4x                       2x 2x 2x 2x 2x           6x         6x 6x       6x         176x       176x                                     176x 33x 33x               176x 49x 49x               176x    
import React from 'react';
 
import type {DateTime} from '@gravity-ui/date-utils';
import {useControlledState, useLang} from '@gravity-ui/uikit';
 
import type {InputBase, Validation, ValueBase} from '../../types';
import {createPlaceholderValue, isInvalid} from '../../utils/dates';
import {useDefaultTimeZone} from '../../utils/useDefaultTimeZone';
import {IncompleteDate} from '../IncompleteDate';
import type {FormatSection} from '../types';
import {
    addSegment,
    adjustDateToFormat,
    getEditableSections,
    getFormatInfo,
    isEditableSectionType,
    parseDateFromString,
    setSegment,
    useFormatSections,
} from '../utils';
 
import {useBaseDateFieldState} from './useBaseDateFieldState';
import type {DateFieldState} from './useBaseDateFieldState';
 
export interface DateFieldStateOptions extends ValueBase<DateTime | null>, InputBase, Validation {
    /** The minimum allowed date that a user may select. */
    minValue?: DateTime;
    /** The maximum allowed date that a user may select. */
    maxValue?: DateTime;
    /** Callback that is called for each date of the calendar. If it returns true, then the date is unavailable. */
    isDateUnavailable?: (date: DateTime) => boolean;
    /** Format of the date when rendered in the input. [Available formats](https://day.js.org/docs/en/display/format) */
    format?: string;
    /** A placeholder date that controls the default values of each segment when the user first interacts with them. Defaults to today's date at midnight. */
    placeholderValue?: DateTime;
    /**
     * Which timezone use to show values. Example: 'default', 'system', 'Europe/Amsterdam'.
     * @default The timezone of the `value` or `defaultValue` or `placeholderValue`, 'default' otherwise.
     */
    timeZone?: string;
    /** Custom parser function for parsing pasted date strings. If not provided, the default parser will be used. */
    parseDateFromString?: (dateStr: string, format: string, timeZone?: string) => DateTime;
}
 
export function useDateFieldState(props: DateFieldStateOptions): DateFieldState {
    const [value, setDate] = useControlledState(
        props.value,
        props.defaultValue ?? null,
        props.onUpdate,
    );
 
    const inputTimeZone = useDefaultTimeZone(
        props.value || props.defaultValue || props.placeholderValue,
    );
    const timeZone = props.timeZone || inputTimeZone;
 
    const handleUpdateDate = (v: DateTime | null) => {
        setDate(v ? v.timeZone(inputTimeZone) : v);
    };
 
    const [lastPlaceholder, setLastPlaceholder] = React.useState(props.placeholderValue);
    Iif (
        (props.placeholderValue && !props.placeholderValue.isSame(lastPlaceholder)) ||
        (!props.placeholderValue && lastPlaceholder)
    ) {
        setLastPlaceholder(props.placeholderValue);
    }
    const placeholder = React.useMemo(
        () =>
            createPlaceholderValue({
                placeholderValue: lastPlaceholder,
                timeZone,
            }),
        [lastPlaceholder, timeZone],
    );
 
    const format = props.format || 'L';
    const sections = useFormatSections(format);
    const formatInfo = React.useMemo(() => getFormatInfo(sections), [sections]);
    const allSegments = formatInfo.availableUnits;
 
    const [displayValue, setDisplayValue] = React.useState(() => {
        return new IncompleteDate(value && value.isValid() ? value.timeZone(timeZone) : null);
    });
 
    const [lastValue, setLastValue] = React.useState(value);
    const [lastTimezone, setLastTimezone] = React.useState(timeZone);
    if (
        (value && !value.isSame(lastValue)) ||
        (value && lastTimezone !== timeZone) ||
        (value === null && lastValue !== null)
    ) {
        setLastValue(value);
        setLastTimezone(timeZone);
        setDisplayValue(new IncompleteDate(value?.timeZone(timeZone)));
    }
 
    const {lang} = useLang();
    const dateValue = React.useMemo(() => {
        return displayValue
            .toDateTime(value?.timeZone(timeZone) ?? placeholder, {
                setDate: formatInfo.hasDate,
                setTime: formatInfo.hasTime,
            })
            .locale(lang);
    }, [displayValue, value, placeholder, formatInfo, timeZone, lang]);
 
    const sectionsState = useSectionsState(sections, displayValue, dateValue);
 
    function setValue(newValue: DateTime | IncompleteDate | null) {
        Iif (props.disabled || props.readOnly) {
            return;
        }
 
        Iif (
            newValue === null ||
            (newValue instanceof IncompleteDate && newValue.isCleared(allSegments))
        ) {
            setDate(null);
            setDisplayValue(new IncompleteDate());
        } else if (newValue instanceof IncompleteDate) {
            if (newValue.isComplete(allSegments)) {
                const newDate = newValue.toDateTime(dateValue, {
                    setDate: formatInfo.hasDate,
                    setTime: formatInfo.hasTime,
                });
                if (newValue.validate(newDate, allSegments)) {
                    Eif (!value || !newDate.isSame(value)) {
                        handleUpdateDate(adjustDateToFormat(newDate, formatInfo));
                    }
                }
            }
            setDisplayValue(newValue);
        } else if (!value || !newValue.isSame(value)) {
            handleUpdateDate(newValue);
        }
    }
 
    function setSection(sectionIndex: number, amount: number) {
        const section = sectionsState.editableSections[sectionIndex];
        Eif (section) {
            setValue(setSegment(section, displayValue, amount, dateValue));
        }
    }
 
    function adjustSection(sectionIndex: number, amount: number) {
        const section = sectionsState.editableSections[sectionIndex];
        Eif (section) {
            setValue(addSegment(section, displayValue, amount, dateValue));
        }
    }
 
    function clearSection(sectionIndex: number) {
        const section = sectionsState.editableSections[sectionIndex];
        if (section && isEditableSectionType(section.type)) {
            setValue(displayValue.clear(section.type));
        }
    }
 
    function setValueFromString(str: string) {
        const parseDate = props.parseDateFromString ?? parseDateFromString;
        const date = parseDate(str, format, timeZone);
        Eif (date.isValid()) {
            setValue(date);
            return true;
        }
        return false;
    }
 
    function confirmPlaceholder() {
        Iif (props.disabled || props.readOnly) {
            return;
        }
 
        // If the display value is complete but invalid, we need to constrain it and emit onChange on blur.
        Eif (displayValue.isComplete(allSegments)) {
            const newValue = displayValue.toDateTime(dateValue, {
                setDate: formatInfo.hasDate,
                setTime: formatInfo.hasTime,
            });
            setValue(adjustDateToFormat(newValue, formatInfo, 'startOf'));
        }
    }
 
    const validationState =
        props.validationState ||
        (isInvalid(value, props.minValue, props.maxValue) ? 'invalid' : undefined) ||
        (value && props.isDateUnavailable?.(value) ? 'invalid' : undefined);
 
    return useBaseDateFieldState({
        value,
        displayValue: dateValue,
        validationState,
        editableSections: sectionsState.editableSections,
        formatInfo,
        readOnly: props.readOnly,
        disabled: props.disabled,
        isEmpty: displayValue.isCleared(allSegments),
        setValue,
        adjustSection,
        setSection,
        clearSection,
        setValueFromString,
        confirmPlaceholder,
    });
}
 
function useSectionsState(sections: FormatSection[], value: IncompleteDate, placeholder: DateTime) {
    const [state, setState] = React.useState(() => {
        const editableSections = getEditableSections(sections, value, placeholder);
        return {
            value,
            sections,
            placeholder,
            editableSections,
        };
    });
 
    if (sections !== state.sections || placeholder !== state.placeholder || value !== state.value) {
        const editableSections = getEditableSections(sections, value, placeholder);
        setState({
            value,
            sections,
            placeholder,
            editableSections,
        });
    }
 
    return state;
}