All files / src/components/RangeDateSelection/components/NowLine NowLine.tsx

17.39% Statements 4/23
0% Branches 0/8
0% Functions 0/4
18.18% Lines 4/22

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 511x           1x       1x                                                                           1x    
import React from 'react';
 
import {block} from '../../../../utils/cn';
import {SECOND} from '../../../utils/constants';
import {useViewportDimensions, useViewportInterval} from '../Ruler/Ruler';
 
const MIN_UPDATE_DISTANCE = 4; // in px
 
import './NowLine.scss';
 
const b = block('timeline-now-line');
 
export function NowLine() {
    const viewport = useViewportDimensions();
    const {start: startDate, end: endDate} = useViewportInterval();
    const [, rerender] = React.useState({});
 
    const nowTime = Date.now();
    const needUpdateNow = endDate.valueOf() > nowTime;
    const interval = Math.max(
        SECOND,
        (MIN_UPDATE_DISTANCE * endDate.diff(startDate)) / viewport.width,
        startDate.valueOf() - nowTime,
    );
 
    React.useEffect(() => {
        let timer: number | null = null;
        if (needUpdateNow) {
            timer = window.setInterval(() => {
                rerender({});
            }, interval);
        }
        return () => {
            if (timer) {
                window.clearInterval(timer);
                timer = null;
            }
        };
    }, [needUpdateNow, interval]);
 
    if (nowTime < startDate.valueOf() || endDate.valueOf() < nowTime) {
        return null;
    }
 
    const nowX =
        ((nowTime - startDate.valueOf()) / (endDate.valueOf() - startDate.valueOf())) *
        viewport.width;
 
    return <path d={`M${nowX},0l0,${viewport.height}`} className={b()} />;
}