Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DevicePreviewRouteScreen.tsx

311 lines10.4 KB

1import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
2import { createNativeStackNavigator } from "@react-navigation/native-stack";
3import { EnvironmentId, ThreadId } from "@t3tools/contracts";
4import * as Cause from "effect/Cause";
5import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
6import { ActivityIndicator, Alert, AppState, Platform, Pressable, View } from "react-native";
7import { useSafeAreaInsets } from "react-native-safe-area-context";
8​
9import { AppText } from "../../components/AppText";
10import { ScreenHeader, type ScreenHeaderMenuItem } from "../../components/ScreenHeader";
11import { NativeHeaderToolbar } from "../../native/StackHeader";
12import { deviceEnvironment, refreshDeviceHubAccess, useDeviceHubAccess } from "../../state/device";
13import { useEnvironmentQuery } from "../../state/query";
14import { useAtomCommand } from "../../state/use-atom-command";
15import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
16import { DeviceStreamWebView, type DeviceStreamRef } from "./DeviceStreamWebView";
17import {
18 selectedThreadDevicePreview,
19 threadDevicePreviews,
20 type ThreadDevicePreview,
21} from "./threadDevicePreviews";
22​
23const DevicePreviewStack = createNativeStackNavigator<{ DevicePreview: undefined }>();
24​
25type DevicePreviewRouteScreenProps = StaticScreenProps<{
26 readonly environmentId: string;
27 readonly threadId: string;
28}>;
29​
30/** The nested native stack supplies the navigation bar inside the modal. */
31export function DevicePreviewRouteScreen({ route }: DevicePreviewRouteScreenProps) {
32 const navigation = useNavigation();
33 const onClose = useCallback(() => navigation.goBack(), [navigation]);
34 return (
35 <View collapsable={false} className="flex-1 bg-sheet">
36 <DevicePreviewStack.Navigator
37 screenOptions={{
38 headerShown: Platform.OS === "ios",
39 headerBackVisible: false,
40 headerShadowVisible: false,
41 headerTransparent: false,
42 headerTitleStyle: { fontSize: 17, fontWeight: "600" },
43 }}
44 >
45 <DevicePreviewStack.Screen name="DevicePreview">
46 {() => (
47 <DevicePreviewScreen
48 environmentId={EnvironmentId.make(route.params.environmentId)}
49 threadId={ThreadId.make(route.params.threadId)}
50 onClose={onClose}
51 />
52 )}
53 </DevicePreviewStack.Screen>
54 </DevicePreviewStack.Navigator>
55 </View>
56 );
58​
59function DevicePreviewScreen({
60 environmentId,
61 threadId,
62 onClose,
63}: {
64 readonly environmentId: EnvironmentId;
65 readonly threadId: ThreadId;
66 readonly onClose: () => void;
67}) {
68 const insets = useSafeAreaInsets();
69 const { themeVariables } = useAppearancePreferences();
70 const focused = useIsFocused();
71 const [foreground, setForeground] = useState(AppState.currentState === "active");
72 const [selectedKey, setSelectedKey] = useState<string | null>(null);
73 const [inputConnected, setInputConnected] = useState(false);
74 const [streamAttempt, setStreamAttempt] = useState(0);
75 const [shuttingDown, setShuttingDown] = useState(false);
76 const shutdown = useAtomCommand(deviceEnvironment.shutdown, { reportFailure: false });
77 const streamRef = useRef<DeviceStreamRef>(null);
78 const state = useEnvironmentQuery(deviceEnvironment.state({ environmentId, input: {} }));
79 const previews = useMemo(
80 () => threadDevicePreviews(state.data, threadId),
81 [state.data, threadId],
82 );
83 const preview = selectedThreadDevicePreview(previews, selectedKey);
84 const onInputConnected = useCallback(
85 async (connected: boolean) => setInputConnected(connected),
86 [],
87 );
88 useEffect(() => {
89 const subscription = AppState.addEventListener("change", (state) =>
90 setForeground(state === "active"),
91 );
92 return () => subscription.remove();
93 }, []);
94 useEffect(() => {
95 if (focused && state.data !== null && previews.length === 0) onClose();
96 }, [focused, state.data, previews.length, onClose]);
97​
98 const shutDownDevice = async () => {
99 if (!preview || shuttingDown) return;
100 setShuttingDown(true);
101 try {
102 const result = await shutdown({
103 environmentId,
104 input: {
105 hostId: preview.session.hostId,
106 deviceId: preview.session.deviceId,
107 platform: preview.session.platform,
108 },
109 });
110 if (result._tag === "Failure") {
111 Alert.alert("Could not shut down device", String(Cause.squash(result.cause)));
112 }
113 } finally {
114 setShuttingDown(false);
115 }
116 };
117​
118 const controls: ScreenHeaderMenuItem[] = [
119 {
120 id: "reload",
121 title: "Reload stream",
122 icon: "arrow.clockwise",
123 disabled: !preview || shuttingDown,
124 onPress: () => {
125 setInputConnected(false);
126 setStreamAttempt((attempt) => attempt + 1);
127 },
128 },
129 ...(preview?.session.platform === "android"
130 ? [
131 {
132 id: "back",
133 title: "Back",
134 icon: "arrow.left",
135 disabled: !inputConnected,
136 onPress: () => streamRef.current?.back(),
137 },
138 ]
139 : []),
140 {
141 id: "app-switcher",
142 title: "App switcher",
143 icon: "square.on.square",
144 disabled: !inputConnected,
145 onPress: () => streamRef.current?.appSwitcher(),
146 },
147 ...(preview?.session.platform === "ios"
148 ? [
149 {
150 id: "rotate",
151 title: "Rotate device",
152 icon: "arrow.clockwise",
153 disabled: !inputConnected,
154 onPress: () => streamRef.current?.rotate(),
155 },
156 ]
157 : []),
158 {
159 id: "shutdown",
160 title: shuttingDown ? "Shutting down…" : "Shut down device",
161 icon: "power",
162 disabled: !preview || shuttingDown,
163 onPress: () => void shutDownDevice(),
164 },
165 ];
166 return (
167 <View className="flex-1 bg-sheet" style={{ paddingBottom: insets.bottom }}>
168 <ScreenHeader
169 title={preview?.name ?? "Devices"}
170 sidebar={false}
171 onBack={onClose}
172 options={{ headerBackVisible: false }}
173 actions={[
174 {
175 accessibilityLabel: "Home",
176 icon: "house",
177 disabled: !inputConnected,
178 onPress: () => streamRef.current?.home(),
179 },
180 ]}
181 menus={[
182 {
183 title: "Device options",
184 icon: "ellipsis",
185 items: [
186 ...(previews.length > 1
187 ? [
188 {
189 id: "devices",
190 title: "Devices",
191 inline: true,
192 items: previews.map((device) => ({
193 id: device.key,
194 title: device.name,
195 subtitle: device.description,
196 selected: device.key === preview?.key,
197 onPress: () => setSelectedKey(device.key),
198 })),
199 },
200 ]
201 : []),
202 ...controls,
203 ],
204 },
205 ]}
206 />
207 {Platform.OS === "ios" ? (
208 <NativeHeaderToolbar placement="left">
209 <NativeHeaderToolbar.Button
210 icon="xmark"
211 accessibilityLabel="Close device preview"
212 onPress={onClose}
213 separateBackground
214 />
215 </NativeHeaderToolbar>
216 ) : null}
217 {preview && focused && foreground ? (
218 <OpenDevicePreview
219 key={`${preview.key}:${streamAttempt}`}
220 environmentId={environmentId}
221 preview={preview}
222 streamRef={streamRef}
223 onInputConnected={onInputConnected}
224 />
225 ) : (
226 <View className="flex-1 items-center justify-center gap-4 px-6">
227 {state.error ? (
228 <>
229 <AppText selectable className="text-center text-sm text-foreground-muted">
230 {state.error}
231 </AppText>
232 <Pressable
233 accessibilityRole="button"
234 className="rounded-full border border-secondary-border bg-secondary px-6 py-3"
235 onPress={state.refresh}
236 >
237 <AppText className="text-secondary-foreground">Retry</AppText>
238 </Pressable>
239 </>
240 ) : focused && foreground ? (
241 <ActivityIndicator color={themeVariables["--color-icon"]} />
242 ) : null}
243 </View>
244 )}
245 </View>
246 );
248​
249function OpenDevicePreview({
250 environmentId,
251 preview,
252 streamRef,
253 onInputConnected,
254}: {
255 readonly environmentId: EnvironmentId;
256 readonly preview: ThreadDevicePreview;
257 readonly streamRef: RefObject<DeviceStreamRef | null>;
258 readonly onInputConnected: (connected: boolean) => Promise<void>;
259}) {
260 const { session } = preview;
261 const { themeVariables } = useAppearancePreferences();
262 const { access, error, refresh } = useDeviceHubAccess(environmentId, session.hostId);
263 const onUnauthorized = useCallback(
264 async () => refreshDeviceHubAccess(environmentId),
265 [environmentId],
266 );
267 useEffect(() => {
268 refreshDeviceHubAccess(environmentId);
269 return () => void onInputConnected(false);
270 }, [environmentId, onInputConnected]);
271 return access ? (
272 <DeviceStreamWebView
273 ref={streamRef}
274 access={access}
275 platform={session.platform}
276 deviceId={session.deviceId}
277 colors={{
278 background: themeVariables["--color-sheet-solid"],
279 foreground: themeVariables["--color-foreground"],
280 muted: themeVariables["--color-foreground-muted"],
281 buttonBackground: themeVariables["--color-secondary"],
282 buttonForeground: themeVariables["--color-secondary-foreground"],
283 buttonBorder: themeVariables["--color-secondary-border"],
284 }}
285 onUnauthorized={onUnauthorized}
286 onInputConnected={onInputConnected}
287 />
288 ) : (
289 <View className="flex-1 items-center justify-center gap-4 px-6">
290 {error ? (
291 <>
292 <AppText selectable className="text-center text-sm text-foreground-muted">
293 {error}
294 </AppText>
295 <Pressable
296 accessibilityRole="button"
297 className="rounded-full border border-secondary-border bg-secondary px-6 py-3"
298 onPress={refresh}
299 >
300 <AppText className="text-secondary-foreground">Retry</AppText>
301 </Pressable>
302 </>
303 ) : (
304 <>
305 <ActivityIndicator color={themeVariables["--color-icon"]} />
306 <AppText className="text-sm text-foreground-muted">Connecting to device...</AppText>
307 </>
308 )}
309 </View>
310 );