Open History to see the last commit
1import { createContext, useContext, useEffect, useState } from "react";
2import { type PanelAnimationDurationMs } from "@t3tools/contracts/settings";
3
4import { useMediaQuery } from "./hooks/useMediaQuery";
5import { useClientSettings } from "./hooks/useSettings";
6
7const PanelAnimationSuppressionContext = createContext(false);
8
9export const PanelAnimationSuppressionProvider = PanelAnimationSuppressionContext.Provider;
10
11export function usePanelNavigationSuppression(navigationKey: string): boolean {
12 const [paintedNavigationKey, setPaintedNavigationKey] = useState<string | null>(null);
13 const suppressed = paintedNavigationKey !== navigationKey;
14
15 useEffect(() => {
16 if (!suppressed) return;
17 let releaseFrame = 0;
18 const paintFrame = window.requestAnimationFrame(() => {
19 releaseFrame = window.requestAnimationFrame(() => setPaintedNavigationKey(navigationKey));
20 });
21 return () => {
22 window.cancelAnimationFrame(paintFrame);
23 window.cancelAnimationFrame(releaseFrame);
24 };
25 }, [navigationKey, suppressed]);
26
27 return suppressed;
28}
29
30export function usePanelAnimationSettings(): {
31 active: boolean;
32 durationMs: PanelAnimationDurationMs;
33} {
34 const durationMs = useClientSettings((settings) => settings.panelAnimationDurationMs);
35 const prefersReducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
36 const suppressed = useContext(PanelAnimationSuppressionContext);
37 return { active: durationMs > 0 && !prefersReducedMotion && !suppressed, durationMs };
38}
39
40export function usePanelPresence<T>(
41 open: boolean,
42 value: T | null,
43 animated: boolean,
44 scopeKey: string | null,
45 durationMs: PanelAnimationDurationMs,
46): { present: boolean; value: T | null } {
47 const [present, setPresent] = useState(open);
48 const [retained, setRetained] = useState<{ scopeKey: string | null; value: T | null } | null>(
49 open ? { scopeKey, value } : null,
50 );
51 if (open && (retained?.scopeKey !== scopeKey || retained.value !== value)) {
52 setRetained({ scopeKey, value });
53 }
54
55 if (open && !present) setPresent(true);
56 if (!open && !animated && present) setPresent(false);
57
58 useEffect(() => {
59 if (open || !animated) return;
60 const timeout = window.setTimeout(() => setPresent(false), durationMs);
61 return () => window.clearTimeout(timeout);
62 }, [animated, durationMs, open]);
63
64 const retainedValue = retained?.scopeKey === scopeKey ? retained.value : null;
65 const visible = open || (animated && present && retained?.scopeKey === scopeKey);
66 return { present: visible, value: open ? value : visible ? retainedValue : null };
67}