7833b94532
- Added reset() method to CountdownTimer class to allow resetting countdown to initial value. - Added initialMs field to CountdownTimer to track original timeout duration. - Integrated countdown reset into HookSelectorComponent to reset timer on user interaction.
47 lines
1.1 KiB
TypeScript
47 lines
1.1 KiB
TypeScript
/**
|
|
* Reusable countdown timer for dialog components.
|
|
*/
|
|
import type { TUI } from "@oh-my-pi/pi-tui";
|
|
|
|
export class CountdownTimer {
|
|
private intervalId: ReturnType<typeof setInterval> | undefined;
|
|
private remainingSeconds: number;
|
|
private readonly initialMs: number;
|
|
|
|
constructor(
|
|
timeoutMs: number,
|
|
private tui: TUI | undefined,
|
|
private onTick: (seconds: number) => void,
|
|
private onExpire: () => void,
|
|
) {
|
|
this.initialMs = timeoutMs;
|
|
this.remainingSeconds = Math.ceil(timeoutMs / 1000);
|
|
this.onTick(this.remainingSeconds);
|
|
|
|
this.intervalId = setInterval(() => {
|
|
this.remainingSeconds--;
|
|
this.onTick(this.remainingSeconds);
|
|
this.tui?.requestRender();
|
|
|
|
if (this.remainingSeconds <= 0) {
|
|
this.dispose();
|
|
this.onExpire();
|
|
}
|
|
}, 1000);
|
|
}
|
|
|
|
/** Reset the countdown to its initial value */
|
|
reset(): void {
|
|
this.remainingSeconds = Math.ceil(this.initialMs / 1000);
|
|
this.onTick(this.remainingSeconds);
|
|
this.tui?.requestRender();
|
|
}
|
|
|
|
dispose(): void {
|
|
if (this.intervalId) {
|
|
clearInterval(this.intervalId);
|
|
this.intervalId = undefined;
|
|
}
|
|
}
|
|
}
|