Open History to see the last commit
1import { createContext, useContext, useEffect, useRef, 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 retainedRef = useRef<{ scopeKey: string | null; value: T | null } | null>(
49 open ? { scopeKey, value } : null,
50 );
51
52 useEffect(() => {
53 if (open) retainedRef.current = { scopeKey, value };
54 }, [open, scopeKey, value]);
55
56 useEffect(() => {
57 if (open) {
58 setPresent(true);
59 return;
60 }
61 if (!animated) {
62 setPresent(false);
63 return;
64 }
65
66 const timeout = window.setTimeout(() => setPresent(false), durationMs);
67 return () => window.clearTimeout(timeout);
68 }, [animated, durationMs, open]);
69
70 const retainedValue =
71 retainedRef.current?.scopeKey === scopeKey ? retainedRef.current.value : null;
72 const visible = open || (animated && present && retainedRef.current?.scopeKey === scopeKey);
73 return { present: visible, value: open ? value : visible ? retainedValue : null };
74}