electronでキャプチャーソフトつくってみるpart2

キャプチャーソフトを作成中に、録画経過時間を表示する機能が必要になった。フラグのON/OFFでタイマーの開始・リセット出来るならば、他のアプリにも活かせるかもと思い、タイマーコンポーネントを作ってみた。

要件

  1. タイマーつくる
  2. propsであるisRecordを切り返ると、タイマーが開始・リセットされる

propsTypeの代わりに、flowで型チェックを行っている

// @flow
import * as React from 'react';

type PropType = {
  isRecord: boolean
};

type StateType = {
  time: number,
  timerId: number | null
};

export default class Timer extends React.Component<PropType, StateType> {
  constructor(props: PropType) {
    super(props);
    this.state = {
      time: 0,
      timerId: null,
    };
  }

  shouldComponentUpdate(nextProps: PropType): boolean {
    if (nextProps.isRecord !== this.props.isRecord) {
      (nextProps.isRecord) ? this.clearTimer() : this.setTimer();
    }
    return true;
  }

  setTimer() {
    const timerId = setInterval(() => {
      const { time } = this.state;
      this.setState({ time: time + 1 });
    }, 1000);
    this.setState({ timerId });
  }

  clearTimer() {
    const { timerId } = this.state;
    timerId && clearInterval(timerId);
    this.setState({ time: 0, timerId: null });
  }

  formatTime(time: number): string {
    const zeroPad = (num: number): string | number => {
      if (num < 10) { return `0${num}`; }
      return num;
    };

    const hour = zeroPad(Math.floor(time / 60 / 60));
    const minuite = zeroPad(Math.floor(time / 60));
    const second = zeroPad(time % 60);

    return `${hour}:${minuite}:${second}`;
  }

  render(): React.Node {
    const { time } = this.state;
    return (
        <span>
          {this.formatTime(time)}
        </span>
    );
  }
}

timerIdについて、eslint/flowでエラーが吐かれてしまう。 なんだこれ。あとで調べよう。。。