|
1 | | -import { createContext, useContext, useEffect, useRef, useState } from "react"; |
| 1 | +import { createContext, useContext, useEffect, useState } from "react"; |
2 | 2 | import { type PanelAnimationDurationMs } from "@t3tools/contracts/settings"; |
3 | 3 |
|
4 | 4 | import { useMediaQuery } from "./hooks/useMediaQuery"; |
@@ -45,30 +45,23 @@ export function usePanelPresence<T>( |
45 | 45 | durationMs: PanelAnimationDurationMs, |
46 | 46 | ): { present: boolean; value: T | null } { |
47 | 47 | const [present, setPresent] = useState(open); |
48 | | - const retainedRef = useRef<{ scopeKey: string | null; value: T | null } | null>( |
| 48 | + const [retained, setRetained] = useState<{ scopeKey: string | null; value: T | null } | null>( |
49 | 49 | open ? { scopeKey, value } : null, |
50 | 50 | ); |
| 51 | + if (open && (retained?.scopeKey !== scopeKey || retained.value !== value)) { |
| 52 | + setRetained({ scopeKey, value }); |
| 53 | + } |
51 | 54 |
|
52 | | - useEffect(() => { |
53 | | - if (open) retainedRef.current = { scopeKey, value }; |
54 | | - }, [open, scopeKey, value]); |
| 55 | + if (open && !present) setPresent(true); |
| 56 | + if (!open && !animated && present) setPresent(false); |
55 | 57 |
|
56 | 58 | useEffect(() => { |
57 | | - if (open) { |
58 | | - setPresent(true); |
59 | | - return; |
60 | | - } |
61 | | - if (!animated) { |
62 | | - setPresent(false); |
63 | | - return; |
64 | | - } |
65 | | - |
| 59 | + if (open || !animated) return; |
66 | 60 | const timeout = window.setTimeout(() => setPresent(false), durationMs); |
67 | 61 | return () => window.clearTimeout(timeout); |
68 | 62 | }, [animated, durationMs, open]); |
69 | 63 |
|
70 | | - const retainedValue = |
71 | | - retainedRef.current?.scopeKey === scopeKey ? retainedRef.current.value : null; |
72 | | - const visible = open || (animated && present && retainedRef.current?.scopeKey === scopeKey); |
| 64 | + const retainedValue = retained?.scopeKey === scopeKey ? retained.value : null; |
| 65 | + const visible = open || (animated && present && retained?.scopeKey === scopeKey); |
73 | 66 | return { present: visible, value: open ? value : visible ? retainedValue : null }; |
74 | 67 | } |
0 commit comments