Open History to see the last commit
1import { useEffect, useRef, useState } from "react";
2
3const TICK_INTERVAL_MS = 120;
4const FADE_OUT_DELAY_MS = 220;
5const SEED_PERCENT = 4;
6const ASYMPTOTE_PERCENT = 90;
7const APPROACH_FACTOR = 0.08;
8const MIN_INCREMENT = 0.5;
9
10/**
11 * Indeterminate progress simulator for the preview chrome's loading bar.
12 * Animates 0 → 90% asymptotically while `loading` is true, snaps to 100%
13 * on release, then resets after a short pause.
14 *
15 * Uses a ref to thread the latest progress through interval ticks without
16 * needing `loading` to retrigger the effect, which sidesteps the stale-
17 * closure pitfalls of reading `progress` directly.
18 */
19export function useLoadingProgress(loading: boolean): number {
20 const [progress, setProgress] = useState(0);
21 const progressRef = useRef(0);
22 progressRef.current = progress;
23
24 useEffect(() => {
25 if (!loading) {
26 if (progressRef.current === 0) return;
27 setProgress(100);
28 const timer = window.setTimeout(() => setProgress(0), FADE_OUT_DELAY_MS);
29 return () => window.clearTimeout(timer);
30 }
31
32 setProgress((value) => (value > 0 && value < 95 ? value : SEED_PERCENT));
33 const interval = window.setInterval(() => {
34 const current = progressRef.current;
35 if (current >= ASYMPTOTE_PERCENT) return;
36 const remaining = ASYMPTOTE_PERCENT - current;
37 const increment = Math.max(MIN_INCREMENT, remaining * APPROACH_FACTOR);
38 setProgress(Math.min(ASYMPTOTE_PERCENT, current + increment));
39 }, TICK_INTERVAL_MS);
40
41 return () => window.clearInterval(interval);
42 }, [loading]);
43
44 return progress;
45}