The best way to control Claude Code, Codex and more from any computer or phone

main
ts 66 lines 1.93 KB
Raw
1 import { StackActions, useNavigation } from "@react-navigation/native";
2 import { useEffect, useEffectEvent, useRef } from "react";
3
4 /**
5 * Leaves a terminal screen whose shell exited: to another live terminal of the
6 * thread, else back. Screen navigation acts on the top route of the stack, so
7 * a shell that exits while another screen is on top waits until its own screen
8 * is focused again.
9 */
10 export function useTerminalExitNavigation(target: {
11 readonly environmentId: string;
12 readonly threadId: string;
13 readonly readFallbackTerminalId: () => string | null;
14 }) {
15 const navigation = useNavigation();
16 const pendingRef = useRef(false);
17
18 const navigateAway = useEffectEvent(() => {
19 const fallbackTerminalId = target.readFallbackTerminalId();
20 if (fallbackTerminalId !== null) {
21 navigation.dispatch(
22 StackActions.replace("ThreadTerminal", {
23 environmentId: target.environmentId,
24 threadId: target.threadId,
25 terminalId: fallbackTerminalId,
26 }),
27 );
28 return;
29 }
30 if (navigation.canGoBack()) {
31 navigation.goBack();
32 return;
33 }
34 navigation.dispatch(
35 StackActions.replace("Thread", {
36 environmentId: target.environmentId,
37 threadId: target.threadId,
38 }),
39 );
40 });
41
42 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- focus subscription for the screen's lifetime; an exit behind another screen navigates when the user returns
43 useEffect(
44 () =>
45 navigation.addListener("focus", () => {
46 if (!pendingRef.current) return;
47 pendingRef.current = false;
48 navigateAway();
49 }),
50 [navigation],
51 );
52
53 return {
54 exited: () => {
55 if (navigation.isFocused()) {
56 navigateAway();
57 return;
58 }
59 pendingRef.current = true;
60 },
61 /** A shell that runs again before the screen regains focus keeps the screen. */
62 restarted: () => {
63 pendingRef.current = false;
64 },
65 };
66 }