Skip to content

Commit

Permalink
feat: scroll the new timer into view
Browse files Browse the repository at this point in the history
  • Loading branch information
remvze committed Jun 16, 2024
1 parent 28abc16 commit f4c66e3
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 5 deletions.
11 changes: 9 additions & 2 deletions src/components/toolbox/countdown-timer/form/form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -19,17 +20,23 @@ export function Form() {

const add = useCountdownTimers(state => state.add);

const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
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 (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ export function Timer({ id }: TimerProps) {
}, [isRunning, tick, id, spent, total, left]);

return (
<div className={styles.timer}>
<div className={styles.timer} id={`timer-${id}`}>
<header className={styles.header}>
<div className={styles.bar}>
<div
Expand Down
20 changes: 20 additions & 0 deletions src/helpers/wait.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export function waitUntil(
func: () => boolean,
interval: number,
): Promise<void> {
return new Promise((resolve, reject) => {
const intervalId = setInterval(() => {
try {
const result = func();

if (result) {
clearInterval(intervalId);
resolve();
}
} catch (error) {
clearInterval(intervalId);
reject(error);
}
}, interval);
});
}
8 changes: 6 additions & 2 deletions src/stores/countdown-timers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -28,17 +28,21 @@ export const useCountdownTimers = create<State & Actions>()(
persist(
(set, get) => ({
add({ name, total }) {
const id = uuid();

set(state => ({
timers: [
{
id: uuid(),
id,
name,
spent: 0,
total,
},
...state.timers,
],
}));

return id;
},

delete(id) {
Expand Down

0 comments on commit f4c66e3

Please sign in to comment.