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

96.15% Statements 75/78
90.51% Branches 124/137
100% Functions 16/16
96.1% Lines 74/77

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 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 33222x                                                           22x         223x           223x     223x   223x 14x         223x 26x           223x 223x 223x 223x 223x   223x 26x           223x 223x 223x             16x 16x 16x           223x 223x 95x                               223x     50x       50x             1x 1x 49x       43x 17x                   17x       9x       8x             43x 6x         4x         34x 34x 34x             8x 8x 8x 8x               1x 1x 1x 1x               2x 2x 2x 2x 2x 2x 2x           6x         6x       4x                                   4x         223x             223x                                                 223x 26x                 223x                 63x                 223x                 89x 89x   89x                       89x   89x       106x    
import React from 'react';
 
import type {DateTime} from '@gravity-ui/date-utils';
import {useControlledState, useLang} from '@gravity-ui/uikit';
 
import type {DateFieldBase} from '../../types/datePicker';
import type {RangeValue} from '../../types/inputs';
import {createPlaceholderRangeValue, isInvalid} from '../../utils/dates';
import {useDefaultTimeZone} from '../../utils/useDefaultTimeZone';
import {IncompleteDate} from '../IncompleteDate.js';
import type {FormatSection} from '../types';
import {
    addSegment,
    adjustDateToFormat,
    getEditableSections,
    getFormatInfo,
    isEditableSectionType,
    parseDateFromString,
    setSegment,
    toEditableSection,
    useFormatSections,
} from '../utils';
 
import type {DateFieldState} from './useBaseDateFieldState';
import {useBaseDateFieldState} from './useBaseDateFieldState';
 
export interface RangeDateFieldStateOptions extends DateFieldBase<RangeValue<DateTime>> {
    delimiter?: string;
}
 
const RANGE_FORMAT_DELIMITER = ' — ';
 
export type RangeDateFieldState = DateFieldState<RangeValue<DateTime>>;
 
export function useRangeDateFieldState(props: RangeDateFieldStateOptions): RangeDateFieldState {
    const [value, setRange] = useControlledState(
        props.value,
        props.defaultValue || null,
        props.onUpdate,
    );
 
    const inputTimeZone = useDefaultTimeZone(
        props.value?.start || props.defaultValue?.start || props.placeholderValue,
    );
    const timeZone = props.timeZone || inputTimeZone;
 
    const handleUpdateRange = (v: RangeValue<DateTime> | null) => {
        setRange(
            v ? {start: v.start.timeZone(inputTimeZone), end: v.end.timeZone(inputTimeZone)} : v,
        );
    };
 
    const placeholder = React.useMemo(() => {
        return createPlaceholderRangeValue({
            placeholderValue: props.placeholderValue,
            timeZone,
        });
    }, [props.placeholderValue, timeZone]);
 
    const format = props.format || 'L';
    const delimiter = props.delimiter ?? RANGE_FORMAT_DELIMITER;
    const sections = useFormatSections(format);
    const formatInfo = React.useMemo(() => getFormatInfo(sections), [sections]);
    const allSegments = formatInfo.availableUnits;
 
    const [displayValue, setDisplayValue] = React.useState(() => {
        return {
            start: new IncompleteDate(value ? value.start.timeZone(timeZone) : null),
            end: new IncompleteDate(value ? value.end.timeZone(timeZone) : null),
        };
    });
 
    const [lastValue, setLastValue] = React.useState(value);
    const [lastTimezone, setLastTimezone] = React.useState(timeZone);
    if (
        (value &&
            (!lastValue ||
                !(value.start.isSame(lastValue.start) && value.end.isSame(lastValue.end)))) ||
        (value && lastTimezone !== timeZone) ||
        (value === null && lastValue !== null)
    ) {
        setLastValue(value);
        setLastTimezone(timeZone);
        setDisplayValue({
            start: new IncompleteDate(value ? value.start.timeZone(timeZone) : null),
            end: new IncompleteDate(value ? value.end.timeZone(timeZone) : null),
        });
    }
 
    const {lang} = useLang();
    const rangeValue = React.useMemo(() => {
        return {
            start: displayValue.start
                .toDateTime(value?.start.timeZone(timeZone) ?? placeholder.start, {
                    setDate: formatInfo.hasDate,
                    setTime: formatInfo.hasTime,
                })
                .locale(lang),
            end: displayValue.end
                .toDateTime(value?.end.timeZone(timeZone) ?? placeholder.end, {
                    setDate: formatInfo.hasDate,
                    setTime: formatInfo.hasTime,
                })
                .locale(lang),
        };
    }, [displayValue, value, placeholder, formatInfo, timeZone, lang]);
 
    const sectionsState = useSectionsState(sections, displayValue, rangeValue, delimiter);
 
    function setValue(newValue: RangeValue<DateTime> | RangeValue<IncompleteDate> | null) {
        Iif (props.disabled || props.readOnly) {
            return;
        }
 
        if (
            newValue === null ||
            (newValue.start instanceof IncompleteDate &&
                newValue.start.isCleared(allSegments) &&
                newValue.end instanceof IncompleteDate &&
                newValue.end.isCleared(allSegments))
        ) {
            setRange(null);
            setDisplayValue({start: new IncompleteDate(), end: new IncompleteDate()});
        } else if (
            newValue.start instanceof IncompleteDate &&
            newValue.end instanceof IncompleteDate
        ) {
            if (newValue.start.isComplete(allSegments) && newValue.end.isComplete(allSegments)) {
                const newRange = {
                    start: newValue.start.toDateTime(rangeValue.start, {
                        setDate: formatInfo.hasDate,
                        setTime: formatInfo.hasTime,
                    }),
                    end: newValue.end.toDateTime(rangeValue.end, {
                        setDate: formatInfo.hasDate,
                        setTime: formatInfo.hasTime,
                    }),
                };
                if (
                    newValue.start.validate(newRange.start, allSegments) &&
                    newValue.end.validate(newRange.end, allSegments)
                ) {
                    if (
                        !value ||
                        !(newRange.start.isSame(value.start) && newRange.end.isSame(value.end))
                    ) {
                        handleUpdateRange({
                            start: adjustDateToFormat(newRange.start, formatInfo, 'startOf'),
                            end: adjustDateToFormat(newRange.end, formatInfo, 'endOf'),
                        });
                    }
                }
            }
            setDisplayValue({start: newValue.start, end: newValue.end});
        } else if (
            !(newValue.start instanceof IncompleteDate) &&
            !(newValue.end instanceof IncompleteDate) &&
            (!value || !(value.start.isSame(newValue.start) && value.end.isSame(newValue.end)))
        ) {
            handleUpdateRange({start: newValue.start, end: newValue.end});
        }
    }
 
    function setSection(sectionIndex: number, amount: number) {
        const portion = sectionIndex <= sections.length ? 'start' : 'end';
        const section = sectionsState.editableSections[sectionIndex];
        setValue({
            ...displayValue,
            [portion]: setSegment(section, displayValue[portion], amount, rangeValue[portion]),
        });
    }
 
    function adjustSection(sectionIndex: number, amount: number) {
        const section = sectionsState.editableSections[sectionIndex];
        const portion = sectionIndex <= sections.length ? 'start' : 'end';
        Eif (section) {
            setValue({
                ...displayValue,
                [portion]: addSegment(section, displayValue[portion], amount, rangeValue[portion]),
            });
        }
    }
 
    function clearSection(sectionIndex: number) {
        const section = sectionsState.editableSections[sectionIndex];
        const portion = sectionIndex <= sections.length ? 'start' : 'end';
        Eif (section && isEditableSectionType(section.type)) {
            setValue({
                ...displayValue,
                [portion]: displayValue[portion].clear(section.type),
            });
        }
    }
 
    function setValueFromString(str: string) {
        const [startDate = '', endDate = ''] = str.split(delimiter);
        const parseDate = props.parseDateFromString ?? parseDateFromString;
        const start = parseDate(startDate, format, timeZone);
        const end = parseDate(endDate, format, timeZone);
        Eif (start.isValid() && end.isValid()) {
            handleUpdateRange({start, end});
            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.
        if (
            displayValue.start.isComplete(allSegments) &&
            displayValue.end.isComplete(allSegments)
        ) {
            const newValue = {
                start: adjustDateToFormat(
                    displayValue.start.toDateTime(rangeValue.start, {
                        setDate: formatInfo.hasDate,
                        setTime: formatInfo.hasTime,
                    }),
                    formatInfo,
                    'startOf',
                ),
                end: adjustDateToFormat(
                    displayValue.end.toDateTime(rangeValue.end, {
                        setDate: formatInfo.hasDate,
                        setTime: formatInfo.hasTime,
                    }),
                    formatInfo,
                    'endOf',
                ),
            };
            setValue(newValue);
        }
    }
 
    const validationState =
        props.validationState ||
        (isInvalid(value?.start, props.minValue, props.maxValue) ? 'invalid' : undefined) ||
        (isInvalid(value?.end, props.minValue, props.maxValue) ? 'invalid' : undefined) ||
        (value && !isValidRange(value) ? 'invalid' : undefined) ||
        (value && props.isDateUnavailable?.(value.start) ? 'invalid' : undefined) ||
        (value && props.isDateUnavailable?.(value.end) ? 'invalid' : undefined);
 
    return useBaseDateFieldState<RangeValue<DateTime>, RangeValue<IncompleteDate>>({
        value,
        displayValue: rangeValue,
        validationState,
        editableSections: sectionsState.editableSections,
        formatInfo,
        readOnly: props.readOnly,
        disabled: props.disabled,
        isEmpty:
            displayValue.start.isCleared(allSegments) && displayValue.end.isCleared(allSegments),
        setValue,
        adjustSection,
        setSection,
        clearSection,
        setValueFromString,
        confirmPlaceholder,
    });
}
 
function useSectionsState(
    sections: FormatSection[],
    value: RangeValue<IncompleteDate>,
    placeholder: RangeValue<DateTime>,
    delimiter: string,
) {
    const [state, setState] = React.useState(() => {
        return {
            value,
            sections,
            placeholder,
            delimiter,
            editableSections: getRangeEditableSections(sections, value, placeholder, delimiter),
        };
    });
 
    if (
        sections !== state.sections ||
        value !== state.value ||
        !(
            placeholder.start.isSame(state.placeholder.start) &&
            placeholder.end.isSame(state.placeholder.end)
        ) ||
        delimiter !== state.delimiter
    ) {
        setState({
            value,
            sections,
            placeholder,
            delimiter,
            editableSections: getRangeEditableSections(sections, value, placeholder, delimiter),
        });
    }
 
    return state;
}
 
function getRangeEditableSections(
    sections: FormatSection[],
    value: RangeValue<IncompleteDate>,
    placeholder: RangeValue<DateTime>,
    delimiter: string,
) {
    const start = getEditableSections(sections, value.start, placeholder.start);
    const end = getEditableSections(sections, value.end, placeholder.end);
 
    const delimiterSection = toEditableSection(
        {
            type: 'literal',
            contentType: 'letter',
            format: delimiter,
            placeholder: delimiter,
            hasLeadingZeros: false,
        },
        value.start,
        placeholder.start,
    );
 
    const editableSections = [...start, delimiterSection, ...end];
 
    return editableSections;
}
 
function isValidRange({start, end}: RangeValue<DateTime>): boolean {
    return start.isValid() && end.isValid() && (start.isSame(end) || start.isBefore(end));
}