refactor(web): replace ProgressProvider context with a self-contained NavigationProgress component driven by TanStack Router lifecycle events

- Remove `ProgressContext`, `useProgress`, and manual `progress.start()` calls from `CommandPalette`, `TitleKeyboardShortcuts`, and `__root.tsx`
- Replace DOM click/popstate listeners with `router.subscribe("onBeforeLoad")` and `router.subscribe("onResolved")` so progress starts/stops automatically on every navigation
- Render `<NavigationProgress />` as a sibling in the root instead of wrapping the tree in a provider
This commit is contained in:
2026-03-19 11:05:33 -04:00
parent 320852b035
commit f4c6b27cd9
4 changed files with 32 additions and 138 deletions
+1 -8
View File
@@ -14,7 +14,6 @@ import { useNavigate } from "@tanstack/react-router";
import { useAtom } from "jotai"; import { useAtom } from "jotai";
import { useCallback, useEffect, useRef, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import { useProgress } from "@/components/navigation-progress";
import { import {
Command, Command,
CommandEmpty, CommandEmpty,
@@ -82,7 +81,6 @@ interface SearchResult {
export function CommandPalette() { export function CommandPalette() {
const { t } = useLingui(); const { t } = useLingui();
const navigate = useNavigate(); const navigate = useNavigate();
const progress = useProgress();
const [commandPaletteOpen, setCommandPaletteOpen] = useAtom(commandPaletteOpenAtom); const [commandPaletteOpen, setCommandPaletteOpen] = useAtom(commandPaletteOpenAtom);
const [helpOpen, setHelpOpen] = useAtom(helpOpenAtom); const [helpOpen, setHelpOpen] = useAtom(helpOpenAtom);
const [recentSearches, setRecentSearches] = useAtom(recentSearchesAtom); const [recentSearches, setRecentSearches] = useAtom(recentSearchesAtom);
@@ -103,7 +101,6 @@ export function CommandPalette() {
useHotkeySequence( useHotkeySequence(
["G", "H"], ["G", "H"],
() => { () => {
progress.start();
void navigate({ to: "/dashboard" }); void navigate({ to: "/dashboard" });
}, },
{ enabled, timeout: 500 }, { enabled, timeout: 500 },
@@ -111,7 +108,6 @@ export function CommandPalette() {
useHotkeySequence( useHotkeySequence(
["G", "E"], ["G", "E"],
() => { () => {
progress.start();
void navigate({ to: "/explore" }); void navigate({ to: "/explore" });
}, },
{ enabled, timeout: 500 }, { enabled, timeout: 500 },
@@ -146,14 +142,13 @@ export function CommandPalette() {
(result: SearchResult) => { (result: SearchResult) => {
if (!result.id) return; if (!result.id) return;
setCommandPaletteOpen(false); setCommandPaletteOpen(false);
progress.start();
if (result.type === "person") { if (result.type === "person") {
void navigate({ to: "/people/$id", params: { id: result.id } }); void navigate({ to: "/people/$id", params: { id: result.id } });
} else { } else {
void navigate({ to: "/titles/$id", params: { id: result.id } }); void navigate({ to: "/titles/$id", params: { id: result.id } });
} }
}, },
[setCommandPaletteOpen, progress, navigate], [setCommandPaletteOpen, navigate],
); );
const handleRecentSearch = useCallback((q: string) => { const handleRecentSearch = useCallback((q: string) => {
@@ -337,7 +332,6 @@ export function CommandPalette() {
<CommandItem <CommandItem
onSelect={() => { onSelect={() => {
setCommandPaletteOpen(false); setCommandPaletteOpen(false);
progress.start();
void navigate({ to: "/dashboard" }); void navigate({ to: "/dashboard" });
}} }}
> >
@@ -348,7 +342,6 @@ export function CommandPalette() {
<CommandItem <CommandItem
onSelect={() => { onSelect={() => {
setCommandPaletteOpen(false); setCommandPaletteOpen(false);
progress.start();
void navigate({ to: "/explore" }); void navigate({ to: "/explore" });
}} }}
> >
+25 -114
View File
@@ -1,29 +1,12 @@
import { useLocation } from "@tanstack/react-router"; import { useRouter } from "@tanstack/react-router";
import { import { useEffect, useEffectEvent, useRef, useState } from "react";
createContext,
type ReactNode,
useContext,
useEffect,
useEffectEvent,
useMemo,
useRef,
useState,
} from "react";
type ProgressApi = {
start: () => void;
done: () => void;
set: (pct: number) => void;
};
const ProgressContext = createContext<ProgressApi | null>(null);
function clamp(n: number, min: number, max: number) { function clamp(n: number, min: number, max: number) {
return Math.max(min, Math.min(max, n)); return Math.max(min, Math.min(max, n));
} }
export function ProgressProvider({ children }: { children: ReactNode }) { export function NavigationProgress() {
const { pathname, searchStr } = useLocation(); const router = useRouter();
const [visible, setVisible] = useState(false); const [visible, setVisible] = useState(false);
const [progress, setProgress] = useState(0); const [progress, setProgress] = useState(0);
@@ -41,7 +24,7 @@ export function ProgressProvider({ children }: { children: ReactNode }) {
clearTimeout(safetyTimerRef.current); clearTimeout(safetyTimerRef.current);
} }
function start() { const start = useEffectEvent(() => {
if (inFlightRef.current) return; if (inFlightRef.current) return;
inFlightRef.current = true; inFlightRef.current = true;
clearTimers(); clearTimers();
@@ -65,10 +48,10 @@ export function ProgressProvider({ children }: { children: ReactNode }) {
clearTimers(); clearTimers();
setVisible(false); setVisible(false);
setProgress(0); setProgress(0);
}, 12000); }, 12_000);
} });
function done() { const done = useEffectEvent(() => {
if (!inFlightRef.current) return; if (!inFlightRef.current) return;
inFlightRef.current = false; inFlightRef.current = false;
clearTimers(); clearTimers();
@@ -80,67 +63,19 @@ export function ProgressProvider({ children }: { children: ReactNode }) {
setVisible(false); setVisible(false);
setTimeout(() => setProgress(0), 200); setTimeout(() => setProgress(0), 200);
}, 200); }, 200);
}
function set(pct: number) {
const next = clamp(pct, 0, 100);
if (next >= 100) {
done();
return;
}
if (!inFlightRef.current) start();
setProgress(next);
}
// Effect events — always see latest closures, don't appear in deps
const onLinkClick = useEffectEvent((e: MouseEvent) => {
if (e.defaultPrevented || e.button !== 0) return;
if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return;
const anchor = (e.target as Element)?.closest?.("a[href]");
if (!(anchor instanceof HTMLAnchorElement)) return;
if (anchor.target && anchor.target !== "_self") return;
if (anchor.hasAttribute("download")) return;
const href = anchor.getAttribute("href");
if (!href || href.startsWith("#")) return;
try {
const url = new URL(href, window.location.href);
if (url.origin !== window.location.origin) return;
} catch {
return;
}
start();
}); });
const onPopState = useEffectEvent(() => start()); // Subscribe to TanStack Router navigation lifecycle events
const onRouteChange = useEffectEvent(() => {
if (inFlightRef.current) done();
});
// Set up listeners once
useEffect(() => { useEffect(() => {
document.addEventListener("click", onLinkClick, true); const unsubBeforeLoad = router.subscribe("onBeforeLoad", (event) => {
window.addEventListener("popstate", onPopState); if (event.pathChanged) start();
});
const unsubResolved = router.subscribe("onResolved", () => done());
return () => { return () => {
document.removeEventListener("click", onLinkClick, true); unsubBeforeLoad();
window.removeEventListener("popstate", onPopState); unsubResolved();
}; };
}, []); }, [router]);
// Finish on route change — routeKey is intentionally a dep to trigger on navigation
const routeKey = pathname + (searchStr ?? "");
const firstRenderRef = useRef(true);
useEffect(() => {
if (firstRenderRef.current) {
firstRenderRef.current = false;
return;
}
onRouteChange();
}, [routeKey]);
// Cleanup timers on unmount // Cleanup timers on unmount
useEffect(() => { useEffect(() => {
@@ -152,40 +87,16 @@ export function ProgressProvider({ children }: { children: ReactNode }) {
}; };
}, []); }, []);
// Stable context API via ref indirection
const apiRef = useRef<ProgressApi>({ start, done, set });
apiRef.current = { start, done, set };
const api = useMemo<ProgressApi>(
() => ({
start: () => apiRef.current.start(),
done: () => apiRef.current.done(),
set: (pct) => apiRef.current.set(pct),
}),
[],
);
return ( return (
<ProgressContext.Provider value={api}> <div
aria-hidden="true"
className="pointer-events-none fixed inset-x-0 top-0 z-[10000] h-0.5 motion-safe:transition-opacity motion-safe:duration-200 motion-safe:ease-out"
style={{ opacity: visible ? 1 : 0 }}
>
<div <div
aria-hidden="true" className={`bg-primary h-full origin-left motion-safe:[box-shadow:0_0_8px_var(--color-primary)] ${progress === 0 ? "" : "motion-safe:transition-transform motion-safe:duration-150 motion-safe:ease-out"}`}
className="pointer-events-none fixed inset-x-0 top-0 z-[10000] h-0.5 motion-safe:transition-opacity motion-safe:duration-200 motion-safe:ease-out" style={{ transform: `scaleX(${clamp(progress, 0, 100) / 100})` }}
style={{ opacity: visible ? 1 : 0 }} />
> </div>
<div
className={`bg-primary h-full origin-left motion-safe:[box-shadow:0_0_8px_var(--color-primary)] ${progress === 0 ? "" : "motion-safe:transition-transform motion-safe:duration-150 motion-safe:ease-out"}`}
style={{ transform: `scaleX(${clamp(progress, 0, 100) / 100})` }}
/>
</div>
{children}
</ProgressContext.Provider>
); );
} }
export function useProgress(): ProgressApi {
const ctx = useContext(ProgressContext);
if (!ctx) {
throw new Error("useProgress must be used inside <ProgressProvider>.");
}
return ctx;
}
@@ -1,14 +1,12 @@
import { useHotkey } from "@tanstack/react-hotkeys"; import { useHotkey } from "@tanstack/react-hotkeys";
import { useAtomValue } from "jotai"; import { useAtomValue } from "jotai";
import { useProgress } from "@/components/navigation-progress";
import { commandPaletteOpenAtom } from "@/lib/atoms/command-palette"; import { commandPaletteOpenAtom } from "@/lib/atoms/command-palette";
import { useTitleContext, useTitleUserInfo } from "./title-context"; import { useTitleContext, useTitleUserInfo } from "./title-context";
import { useTitleActions } from "./use-title-actions"; import { useTitleActions } from "./use-title-actions";
export function TitleKeyboardShortcuts() { export function TitleKeyboardShortcuts() {
const progress = useProgress();
const { titleType } = useTitleContext(); const { titleType } = useTitleContext();
const { userStatus } = useTitleUserInfo(); const { userStatus } = useTitleUserInfo();
const { handleStatusChange, handleRating, handleWatchMovie } = useTitleActions(); const { handleStatusChange, handleRating, handleWatchMovie } = useTitleActions();
@@ -27,14 +25,7 @@ export function TitleKeyboardShortcuts() {
}, },
{ enabled }, { enabled },
); );
useHotkey( useHotkey("Escape", () => window.history.back(), { enabled });
"Escape",
() => {
progress.start();
window.history.back();
},
{ enabled },
);
useHotkey("1", () => handleRating(1), { enabled }); useHotkey("1", () => handleRating(1), { enabled });
useHotkey("2", () => handleRating(2), { enabled }); useHotkey("2", () => handleRating(2), { enabled });
+5 -6
View File
@@ -9,7 +9,7 @@ import { TanStackRouterDevtoolsPanel } from "@tanstack/react-router-devtools";
import { Provider as StoreProvider } from "jotai"; import { Provider as StoreProvider } from "jotai";
import { MotionConfig } from "motion/react"; import { MotionConfig } from "motion/react";
import { ProgressProvider } from "@/components/navigation-progress"; import { NavigationProgress } from "@/components/navigation-progress";
import { SofaLogo } from "@/components/sofa-logo"; import { SofaLogo } from "@/components/sofa-logo";
import { Toaster } from "@/components/ui/sonner"; import { Toaster } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip"; import { TooltipProvider } from "@/components/ui/tooltip";
@@ -54,11 +54,10 @@ function RootComponent() {
<StoreProvider> <StoreProvider>
<I18nProvider i18n={i18n}> <I18nProvider i18n={i18n}>
<MotionConfig reducedMotion="user"> <MotionConfig reducedMotion="user">
<ProgressProvider> <NavigationProgress />
<TooltipProvider> <TooltipProvider>
<Outlet /> <Outlet />
</TooltipProvider> </TooltipProvider>
</ProgressProvider>
<Toaster position="bottom-right" /> <Toaster position="bottom-right" />
</MotionConfig> </MotionConfig>
</I18nProvider> </I18nProvider>