Open History to see the last commit
1import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
2import { KeyboardController } from "react-native-keyboard-controller";
3
4import type { ComposerEditorHandle } from "../../components/ComposerEditor";
5
6type PresentationPhase = "closed" | "opening" | "visible" | "restoring";
7
8/**
9 * The navigator-level UIKit completion event added by the repo's
10 * `@react-navigation/native-stack` patch; absent from upstream event maps.
11 */
12export type NavigationWithFinishTransitioning = {
13 readonly addListener: (type: "finishTransitioning", callback: () => void) => () => void;
14};
15
16const SHEET_DISMISSAL_KEYBOARD_OVERLAP_MS = 300;
17
18/**
19 * A JS-initiated dismissal pops state before its animation runs; a
20 * gesture-driven one animates natively first and pops afterwards, with the
21 * navigator's completion event landing a few dozen milliseconds before the pop.
22 * A completion this fresh at pop time therefore means the sheet is already gone
23 * and the keyboard should return immediately.
24 */
25const NATIVE_DISMISSAL_ECHO_WINDOW_MS = 150;
26
27/**
28 * A plain blur/focus pair costs one keyboard animation each way —
29 * keepFocus-style inputView overrides are avoided because removing them forces
30 * UIKit to reload input views, replaying the keyboard's show as a visible
31 * collapse/re-open.
32 */
33export function useThreadSettingsSheetPresentation(input: {
34 readonly editorRef: RefObject<ComposerEditorHandle | null>;
35 readonly isEditorFocused: boolean;
36}) {
37 const [phase, setPhase] = useState<PresentationPhase>("closed");
38 const isActiveRef = useRef(false);
39 const isMountedRef = useRef(true);
40 const isEditorFocusedRef = useRef(input.isEditorFocused);
41 const openingIdRef = useRef(0);
42 const focusRestoreIdRef = useRef(0);
43 const restoreFocusAfterDismissRef = useRef(false);
44 const restorePendingRef = useRef(false);
45 const lastStackTransitionFinishedAtRef = useRef(0);
46 const dismissRestoreTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
47 const clearDismissRestoreTimer = useCallback(() => {
48 if (dismissRestoreTimerRef.current !== null) {
49 clearTimeout(dismissRestoreTimerRef.current);
50 dismissRestoreTimerRef.current = null;
51 }
52 }, []);
53
54 useEffect(() => {
55 isEditorFocusedRef.current = input.isEditorFocused;
56 }, [input.isEditorFocused]);
57
58 useEffect(() => {
59 // React Strict Mode and Fast Refresh both run an effect cleanup/setup
60 // cycle without recreating refs. Re-arm the mounted guard on every setup.
61 isMountedRef.current = true;
62 return () => {
63 isMountedRef.current = false;
64 isActiveRef.current = false;
65 openingIdRef.current += 1;
66 focusRestoreIdRef.current += 1;
67 clearDismissRestoreTimer();
68 };
69 }, [clearDismissRestoreTimer]);
70
71 const open = useCallback(() => {
72 if (isActiveRef.current) {
73 return;
74 }
75
76 isActiveRef.current = true;
77 focusRestoreIdRef.current += 1;
78 clearDismissRestoreTimer();
79 restorePendingRef.current = false;
80 restoreFocusAfterDismissRef.current =
81 phase === "restoring" || input.isEditorFocused || KeyboardController.isVisible();
82 setPhase("opening");
83
84 const openingId = openingIdRef.current + 1;
85 openingIdRef.current = openingId;
86
87 // Start the keyboard transition before the custom native editor resigns
88 // first responder, then present the sheet on the next frame. The sheet and
89 // keyboard animate together instead of serializing two native transitions.
90 void KeyboardController.dismiss({ animated: true });
91 input.editorRef.current?.blur();
92
93 requestAnimationFrame(() => {
94 if (!isMountedRef.current || !isActiveRef.current || openingIdRef.current !== openingId) {
95 return;
96 }
97 setPhase("visible");
98 });
99 }, [clearDismissRestoreTimer, input.editorRef, input.isEditorFocused, phase]);
100
101 const restoreEditorFocus = useCallback(() => {
102 const focusRestoreId = focusRestoreIdRef.current + 1;
103 focusRestoreIdRef.current = focusRestoreId;
104 let attemptsRemaining = 20;
105
106 // Restoration runs after the dismissal transition, so the first attempt
107 // normally succeeds; the retries are insurance against UIKit briefly
108 // refusing first-responder status right at the transition boundary.
109 const restoreFocus = () => {
110 if (!isMountedRef.current || focusRestoreIdRef.current !== focusRestoreId) {
111 return;
112 }
113 if (isEditorFocusedRef.current || attemptsRemaining <= 0) {
114 setPhase("closed");
115 return;
116 }
117
118 attemptsRemaining -= 1;
119 input.editorRef.current?.focus();
120 setTimeout(restoreFocus, 50);
121 };
122 requestAnimationFrame(restoreFocus);
123 }, [input.editorRef]);
124
125 const runPendingDismissalRestore = useCallback(() => {
126 if (!restorePendingRef.current) {
127 return;
128 }
129 restorePendingRef.current = false;
130 clearDismissRestoreTimer();
131 if (!isMountedRef.current || isActiveRef.current) {
132 return;
133 }
134 restoreEditorFocus();
135 }, [clearDismissRestoreTimer, restoreEditorFocus]);
136
137 const onDismissed = useCallback(() => {
138 isActiveRef.current = false;
139
140 if (!restoreFocusAfterDismissRef.current) {
141 setPhase("closed");
142 return;
143 }
144 // Keep the card expanded across the handoff back to its editor. With a
145 // hardware keyboard there is no software-keyboard travel to hide a collapse
146 // while the sheet dismissal and focus restoration finish.
147 setPhase("restoring");
148 restoreFocusAfterDismissRef.current = false;
149 restorePendingRef.current = true;
150 clearDismissRestoreTimer();
151 if (Date.now() - lastStackTransitionFinishedAtRef.current <= NATIVE_DISMISSAL_ECHO_WINDOW_MS) {
152 runPendingDismissalRestore();
153 return;
154 }
155 dismissRestoreTimerRef.current = setTimeout(() => {
156 dismissRestoreTimerRef.current = null;
157 runPendingDismissalRestore();
158 }, SHEET_DISMISSAL_KEYBOARD_OVERLAP_MS);
159 }, [clearDismissRestoreTimer, runPendingDismissalRestore]);
160
161 const onStackTransitionsFinished = useCallback(() => {
162 lastStackTransitionFinishedAtRef.current = Date.now();
163 runPendingDismissalRestore();
164 }, [runPendingDismissalRestore]);
165
166 return {
167 isActive: phase === "opening" || phase === "visible",
168 keepsComposerExpanded: phase !== "closed",
169 isVisible: phase === "visible",
170 open,
171 onDismissed,
172 onStackTransitionsFinished,
173 } as const;
174}