aboutsummaryrefslogtreecommitdiffstats
path: root/packages/instant/src/components/time_counter.tsx
blob: c98fd2550dd3e634f956c0deb1845d57734b3a3a (plain) (blame)
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
import * as React from 'react';

import { ONE_SECOND_MS } from '../constants';
import { timeUtil } from '../util/time';

import { Flex } from './ui/flex';
import { Text } from './ui/text';

export interface TimeCounterProps {
    estimatedTimeMs: number;
    hasEnded: boolean;
}
interface TimeCounterState {
    elapsedSeconds: number;
}

export class TimeCounter extends React.Component<TimeCounterProps, TimeCounterState> {
    public state = {
        elapsedSeconds: 0,
    };
    private _timerId?: number;

    public componentDidMount(): void {
        this._setupTimerBasedOnProps();
    }

    public componentWillUnmount(): void {
        this._clearTimer();
    }

    public componentDidUpdate(prevProps: TimeCounterProps): void {
        if (prevProps.hasEnded !== this.props.hasEnded) {
            this._setupTimerBasedOnProps();
        }
    }

    public render(): React.ReactNode {
        const estimatedTimeSeconds = this.props.estimatedTimeMs / ONE_SECOND_MS;
        return (
            <Flex justify="space-between">
                <Text>Est. Time ({timeUtil.secondsToHumanDescription(estimatedTimeSeconds)})</Text>
                <Text>Time: {timeUtil.secondsToStopwatchTime(this.state.elapsedSeconds)}</Text>
            </Flex>
        );
    }

    private _setupTimerBasedOnProps(): void {
        this.props.hasEnded ? this._clearTimer() : this._newTimer();
    }

    private _newTimer(): void {
        this._clearTimer();
        this._timerId = window.setInterval(() => {
            this.setState({
                elapsedSeconds: this.state.elapsedSeconds + 1,
            });
        }, ONE_SECOND_MS);
    }

    private _clearTimer(): void {
        if (this._timerId) {
            window.clearInterval(this._timerId);
        }
    }
}