From 1fbf97e1a574db3b78856bea1e8d46641970d692 Mon Sep 17 00:00:00 2001 From: Owen-Morgan825 Date: Tue, 26 Nov 2024 19:20:58 -0500 Subject: [PATCH] Add timer input type --- src/components/inputs/TimerInput.tsx | 43 ++++++++++++++++++---------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/src/components/inputs/TimerInput.tsx b/src/components/inputs/TimerInput.tsx index fe56d5f..13a2c43 100644 --- a/src/components/inputs/TimerInput.tsx +++ b/src/components/inputs/TimerInput.tsx @@ -1,4 +1,4 @@ -import { Pause, Play, X } from 'lucide-react'; +import { Pause, Play, TimerReset, Undo } from 'lucide-react'; import BaseInputProps from './BaseInputProps'; import { useState, useEffect, useMemo } from 'react'; export interface TimerInputProps extends BaseInputProps { @@ -8,6 +8,9 @@ export interface TimerInputProps extends BaseInputProps { defaultValue?: number; } function getAvg(array: any[]) { + if (array.length === 0) { + return 0; + } let avg = 0; array.forEach((num) => { avg += num; @@ -19,39 +22,42 @@ export default function TimerInput(data: TimerInputProps) { const [isRunning, toggleTimer] = useState(false); const [times, setTimes] = useState([]); - console.log(data.value); + useEffect(() => { + if (data.value === data.defaultValue && times.length > 0) { + clearTimer(); + setTimes([]); + } + }, [data.value, data.defaultValue, times]); function startStop() { toggleTimer(!isRunning); } - function clearTimer() { + + function clearTimer(update: boolean = false) { + if (update) { + updateTimes(time / 100); + } setTime(0); toggleTimer(false); } + function updateTimes(newValue: number) { + data.onChange(getAvg([...times, newValue])) setTimes((old) => ([...old, newValue])); } + useEffect(() => { let intervalId: number; if (isRunning) { intervalId = setInterval(() => setTime(time + (data.step || 1)), 10); } - if (!isRunning && time !== 0) { - updateTimes(time / 100) - } return () => clearInterval(intervalId); }, [isRunning, time]); - const avg = useMemo(() => { - const avg2 = getAvg(times); - data.onChange(avg2); - return avg2; - }, [times]); return (
-

{times.map((t) => { return `${t}` }).join(',')}

-

{avg.toFixed(3)}

+

{`${data.value.toFixed(3)} (${times.length})`}

{(time / 100).toFixed(2)}

+