import _ from "lodash" import React from "react" import * as formUtils from "./formUtils" import { InnerFormContext } from "./formContext" import { Timer } from "./formDesign" function now() { return new Date().getTime() } function toTicks(seconds: any) { if (seconds != null) { return seconds * 1000 } else { return null } } function integerDiv(dividend: any, divisor: any) { return [Math.floor(dividend / divisor), dividend % divisor] } function zeroPad(val: any, length: any) { val += "" const numPads = length - val.length if (numPads > 0) { return new Array(numPads + 1).join("0") + val } else { return val } } function getDisplayValue(ticks: any) { if (ticks != null) { let seconds let [minutes, remainder] = integerDiv(ticks, 60000) ;[seconds, remainder] = integerDiv(remainder, 1000) minutes = zeroPad(minutes, 2) seconds = zeroPad(seconds, 2) return minutes + ":" + seconds } else { return "--:--" } } export interface TimerComponentProps { timer: Timer formCtx: InnerFormContext } interface TimerComponentState { timerId: any elapsedTicks: any } export default class TimerComponent extends React.Component { constructor(props: TimerComponentProps) { super(props) this.state = { elapsedTicks: null, timerId: null } } componentDidUpdate(prevProps: TimerComponentProps) { if ((prevProps as any).value !== (this.props as any).value && this.state.timerId === null) { // Don't update elapsedTicks if timer is active return this.setState({ elapsedTicks: toTicks((this.props as any).value) }) } } // Starts a timer to update @elapsedTicks every 10 ms handleStartClick = () => { const startTime = now() - (this.state.elapsedTicks || 0) // for restarts we need to fudge the startTime const update = () => this.setState({ elapsedTicks: now() - startTime }) return this.setState({ timerId: setInterval(update, 10) }) // create a timer and store its id\ } // Stops the timer handleStopClick = () => { clearInterval(this.state.timerId) // stop the running timer return this.setState({ timerId: null }) } // Stops timer and resets @elapsedTicks to 0 handleResetClick = () => { clearInterval(this.state.timerId) return this.setState({ elapsedTicks: null, timerId: null }) } render() { const isRunning = this.state.timerId != null let timeLeft: number | null = this.props.timer.duration - this.state.elapsedTicks if (timeLeft < 0) { timeLeft = null // To display -- : -- } return (
{formUtils.localizeString(this.props.timer.text, this.props.formCtx.locale)}
{this.props.timer.hint ? (
{formUtils.localizeString(this.props.timer.hint, this.props.formCtx.locale)}
) : undefined}

{getDisplayValue(timeLeft)}

) } }