All files / src/components/TimeSelection/hooks useTimeSelection.ts

45.56% Statements 36/79
42.18% Branches 27/64
61.53% Functions 8/13
46.05% Lines 35/76

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 1811x   1x                                   1x         16x 16x     1x                       17x 16x     17x       17x   17x   17x                                                                     17x                                   17x                       17x   40x 16x 16x 24x 16x 8x 6x 2x 2x             17x                                     17x 17x 1x       17x 16x 9x       17x 16x 16x     17x                  
import React from 'react';
 
import {dateTime} from '@gravity-ui/date-utils';
import type {DateTime} from '@gravity-ui/date-utils';
 
import type {TimeSelectionView, TimeSelectionWheel} from '../TimeSelection.types';
 
interface UseTimeSelectionProps {
    defaultValue?: DateTime;
    value?: DateTime;
    readOnly?: boolean;
    disabled?: boolean;
    timeZone?: string;
    ampm?: boolean;
    views: TimeSelectionView[];
    focusedView?: TimeSelectionView;
    onUpdate?: (value: DateTime) => void;
    onFocusViewUpdate?: (value: TimeSelectionView) => void;
}
 
const getInitialValue = (
    defaultValue?: DateTime,
    controlledValue?: DateTime,
    timeZone?: string,
): DateTime => {
    const initial = defaultValue || controlledValue || dateTime();
    return timeZone ? initial.timeZone(timeZone, true) : initial;
};
 
export const useTimeSelection = ({
    defaultValue,
    value: controlledValue,
    readOnly,
    disabled,
    timeZone,
    ampm,
    views,
    focusedView: controlledFocusedView,
    onUpdate,
    onFocusViewUpdate,
}: UseTimeSelectionProps) => {
    const [internalValue, setInternalValue] = React.useState<DateTime>(() =>
        getInitialValue(defaultValue, controlledValue, timeZone),
    );
 
    const [activeWheel, setActiveWheel] = React.useState<TimeSelectionWheel>(
        controlledFocusedView || views[0] || 'hours',
    );
 
    const currentValue = controlledValue !== undefined ? controlledValue : internalValue;
 
    const order: TimeSelectionWheel[] = ampm ? [...views, 'ampm'] : views;
 
    const updateValue = React.useCallback(
        (prev: DateTime, key: TimeSelectionWheel, val: string): DateTime => {
            let updated = prev;
 
            switch (key) {
                case 'hours':
                    updated = updated.set('hour', Number(val));
                    break;
                case 'minutes':
                    updated = updated.set('minute', Number(val));
                    break;
                case 'seconds':
                    updated = updated.set('second', Number(val));
                    break;
                case 'ampm': {
                    const isPM = val === 'PM';
                    const hour = updated.hour();
                    if (isPM && hour < 12) {
                        updated = updated.set('hour', hour + 12);
                    } else if (!isPM && hour >= 12) {
                        updated = updated.set('hour', hour - 12);
                    }
                    break;
                }
            }
 
            if (timeZone) {
                updated = updated.timeZone(timeZone, true);
            }
 
            return updated;
        },
        [timeZone],
    );
 
    const handleChange = React.useCallback(
        (key: TimeSelectionWheel, val: string) => {
            if (readOnly || disabled) return;
 
            if (controlledValue === undefined) {
                setInternalValue((prev) => {
                    const updated = updateValue(prev, key, val);
                    onUpdate?.(updated);
                    return updated;
                });
            } else {
                const updated = updateValue(currentValue, key, val);
                onUpdate?.(updated);
            }
        },
        [readOnly, disabled, controlledValue, currentValue, updateValue, onUpdate],
    );
 
    const handleActivate = React.useCallback(
        (key: TimeSelectionWheel) => {
            if (controlledFocusedView === undefined) {
                setActiveWheel(key);
            }
            if (key !== 'ampm') {
                onFocusViewUpdate?.(key);
            }
        },
        [controlledFocusedView, onFocusViewUpdate],
    );
 
    const getCurrentValue = React.useCallback(
        (key: TimeSelectionWheel): string => {
            if (key === 'hours') {
                const hour = currentValue.hour();
                return String(ampm ? hour % 12 || 12 : hour).padStart(2, '0');
            } else if (key === 'minutes') {
                return String(currentValue.minute()).padStart(2, '0');
            } else if (key === 'seconds') {
                return String(currentValue.second()).padStart(2, '0');
            E} else if (key === 'ampm') {
                return currentValue.hour() >= 12 ? 'PM' : 'AM';
            }
            return '00';
        },
        [currentValue, ampm],
    );
 
    const handleKeyDown = React.useCallback(
        (e: KeyboardEvent) => {
            if (readOnly || disabled) return;
 
            const idx = order.indexOf(activeWheel);
 
            if (e.key === 'ArrowRight') {
                e.preventDefault();
                const nextWheel = order[(idx + 1) % order.length];
                handleActivate(nextWheel);
            } else if (e.key === 'ArrowLeft') {
                e.preventDefault();
                const prevWheel = order[(idx - 1 + order.length) % order.length];
                handleActivate(prevWheel);
            }
        },
        [activeWheel, order, readOnly, disabled, handleActivate],
    );
 
    React.useEffect(() => {
        if (controlledValue && controlledValue !== internalValue) {
            setInternalValue(controlledValue);
        }
    }, [controlledValue, internalValue]);
 
    React.useEffect(() => {
        if (controlledFocusedView !== undefined) {
            setActiveWheel(controlledFocusedView);
        }
    }, [controlledFocusedView]);
 
    React.useEffect(() => {
        window.addEventListener('keydown', handleKeyDown);
        return () => window.removeEventListener('keydown', handleKeyDown);
    }, [handleKeyDown]);
 
    return {
        currentValue,
        activeWheel,
        order,
        handleChange,
        handleActivate,
        getCurrentValue,
    };
};