diff --git a/src/components/toolbox/countdown-timer/form/form.tsx b/src/components/toolbox/countdown-timer/form/form.tsx index 066df86..5c4cec7 100644 --- a/src/components/toolbox/countdown-timer/form/form.tsx +++ b/src/components/toolbox/countdown-timer/form/form.tsx @@ -3,6 +3,7 @@ import { useState, useMemo } from 'react'; import { Field } from './field'; import { useCountdownTimers } from '@/stores/countdown-timers'; +import { waitUntil } from '@/helpers/wait'; import styles from './form.module.css'; @@ -19,17 +20,23 @@ export function Form() { const add = useCountdownTimers(state => state.add); - const handleSubmit = (e: React.FormEvent) => { + const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (totalSeconds === 0) return; - add({ + const id = add({ name, total: totalSeconds, }); setName(''); + + await waitUntil(() => !!document.getElementById(`timer-${id}`), 50); + + document + .getElementById(`timer-${id}`) + ?.scrollIntoView({ behavior: 'smooth' }); }; return ( diff --git a/src/components/toolbox/countdown-timer/timers/timer/timer.tsx b/src/components/toolbox/countdown-timer/timers/timer/timer.tsx index 83dd722..c73a6de 100644 --- a/src/components/toolbox/countdown-timer/timers/timer/timer.tsx +++ b/src/components/toolbox/countdown-timer/timers/timer/timer.tsx @@ -139,7 +139,7 @@ export function Timer({ id }: TimerProps) { }, [isRunning, tick, id, spent, total, left]); return ( -
+
boolean, + interval: number, +): Promise { + return new Promise((resolve, reject) => { + const intervalId = setInterval(() => { + try { + const result = func(); + + if (result) { + clearInterval(intervalId); + resolve(); + } + } catch (error) { + clearInterval(intervalId); + reject(error); + } + }, interval); + }); +} diff --git a/src/stores/countdown-timers/index.ts b/src/stores/countdown-timers/index.ts index 0f44edf..dca63d1 100644 --- a/src/stores/countdown-timers/index.ts +++ b/src/stores/countdown-timers/index.ts @@ -16,7 +16,7 @@ interface State { } interface Actions { - add: (timer: { name: string; total: number }) => void; + add: (timer: { name: string; total: number }) => string; delete: (id: string) => void; getTimer: (id: string) => Timer; rename: (id: string, newName: string) => void; @@ -28,10 +28,12 @@ export const useCountdownTimers = create()( persist( (set, get) => ({ add({ name, total }) { + const id = uuid(); + set(state => ({ timers: [ { - id: uuid(), + id, name, spent: 0, total, @@ -39,6 +41,8 @@ export const useCountdownTimers = create()( ...state.timers, ], })); + + return id; }, delete(id) {