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

83.95% Statements 68/81
84.09% Branches 74/88
82.35% Functions 14/17
83.75% Lines 67/80

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 262 263 264 265 266 267 268 269 270 27123x                                                                                       201x           201x     201x   201x 10x     201x 201x           201x   35x             201x 201x 201x 201x   201x 35x     201x 201x 201x         12x 12x 12x     201x 201x 94x               201x   201x   201x       119x 57x     62x 12x           50x 50x                             48x       48x           48x 38x 18x       18x 4x 4x       38x 10x 6x         34x 34x 34x         4x 4x 4x                         2x 2x 2x 2x 2x           7x         7x 7x       7x         201x       201x                                                         201x 35x               201x 59x               201x    
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 {DateFieldSectionWithoutPosition} from '../types';
import {
    addSegment,
    adjustDateToFormat,
    getEditableSections,
    getFormatInfo,
    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);
 
    const [selectedSections, setSelectedSections] = React.useState<number | 'all'>(-1);
 
    const selectedSectionIndexes = React.useMemo<{
        startIndex: number;
        endIndex: number;
    } | null>(() => {
        if (selectedSections === -1) {
            return null;
        }
 
        if (selectedSections === 'all') {
            return {
                startIndex: 0,
                endIndex: sectionsState.editableSections.length - 1,
            };
        }
 
        Eif (typeof selectedSections === 'number') {
            return {startIndex: selectedSections, endIndex: selectedSections};
        }
 
        if (typeof selectedSections === 'string') {
            const selectedSectionIndex = sectionsState.editableSections.findIndex(
                (section) => section.type === selectedSections,
            );
 
            return {startIndex: selectedSectionIndex, endIndex: selectedSectionIndex};
        }
 
        return selectedSections;
    }, [selectedSections, sectionsState.editableSections]);
 
    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 getSectionValue(_sectionIndex: number) {
        return displayValue;
    }
 
    function setSectionValue(_sectionIndex: number, newValue: IncompleteDate) {
        setValue(newValue);
    }
 
    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,
        placeholderValue: props.placeholderValue,
        timeZone,
        validationState,
        editableSections: sectionsState.editableSections,
        formatInfo,
        readOnly: props.readOnly,
        disabled: props.disabled,
        selectedSectionIndexes,
        selectedSections,
        isEmpty: displayValue.isCleared(allSegments),
        setSelectedSections,
        setValue,
        adjustSection,
        setSection,
        getSectionValue,
        setSectionValue,
        setValueFromString,
        confirmPlaceholder,
    });
}
 
function useSectionsState(
    sections: DateFieldSectionWithoutPosition[],
    value: IncompleteDate,
    placeholder: DateTime,
) {
    const [state, setState] = React.useState(() => {
        return {
            value,
            sections,
            placeholder,
            editableSections: getEditableSections(sections, value, placeholder),
        };
    });
 
    if (sections !== state.sections || placeholder !== state.placeholder || value !== state.value) {
        setState({
            value,
            sections,
            placeholder,
            editableSections: getEditableSections(sections, value, placeholder),
        });
    }
 
    return state;
}