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

DevicePreviewRouteScreen.tsx

428 lines14.8 KB

1import * as Dialog from "../../components/ui/Dialog";
2import {
3 deviceToolVersionLabels,
4 deviceToolUpdateOwnership,
5 deviceToolUpdatePolicy,
6} from "@t3tools/client-runtime/state/device";
7import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
8import { EnvironmentId, ThreadId } from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
11import * as Haptics from "expo-haptics";
12import { Accelerometer } from "expo-sensors";
13import { AppState, BackHandler, Pressable, StatusBar, View } from "react-native";
14import Animated, { FadeIn, FadeOut, ReduceMotion } from "react-native-reanimated";
15import { useSafeAreaInsets } from "react-native-safe-area-context";
16​
17import { SymbolView } from "../../components/ui/AppSymbol";
18import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
19import { AppText } from "../../components/ui/AppText";
20import { ControlPill } from "../../components/ui/ControlPill";
21import { Menu } from "../../components/ui/Menu";
22import { GlassSurface } from "../../components/ui/GlassSurface";
23import {
24 androidHeaderMenuActions,
25 findHeaderMenuAction,
26} from "../../components/ui/headerMenu.android";
27import type { AppBarMenuItem } from "../../components/ui/AppBar.types";
28import { deviceEnvironment, refreshDeviceHubAccess, useDeviceHubAccess } from "../../state/device";
29import { useEnvironmentQuery } from "../../state/query";
30import { useAtomCommand } from "../../state/use-atom-command";
31import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
32import { DeviceStreamWebView, type DeviceStreamRef } from "./DeviceStreamWebView";
33import {
34 selectedThreadDevicePreview,
35 threadDevicePreviews,
36 type ThreadDevicePreview,
37} from "./threadDevicePreviews";
38import { createShakeDetector } from "./shakeDetector";
39​
40const OVERLAY_ENTERING = FadeIn.duration(160).reduceMotion(ReduceMotion.System);
41const OVERLAY_EXITING = FadeOut.duration(120).reduceMotion(ReduceMotion.System);
42​
43type DevicePreviewRouteScreenProps = StaticScreenProps<{
44 readonly environmentId: string;
45 readonly threadId: string;
46}>;
47​
48export function DevicePreviewRouteScreen({ route }: DevicePreviewRouteScreenProps) {
49 const navigation = useNavigation();
50 const onClose = useCallback(() => navigation.goBack(), [navigation]);
51 const { environmentId, threadId } = route.params;
52 const isBlankLink = environmentId.trim().length === 0 || threadId.trim().length === 0;
53 useEffect(() => {
54 if (isBlankLink) onClose();
55 }, [isBlankLink, onClose]);
56 if (isBlankLink) return null;
57 return (
58 <DevicePreviewScreen
59 environmentId={EnvironmentId.make(environmentId)}
60 threadId={ThreadId.make(threadId)}
61 onClose={onClose}
62 />
63 );
65​
66function DevicePreviewScreen({
67 environmentId,
68 threadId,
69 onClose,
70}: {
71 readonly environmentId: EnvironmentId;
72 readonly threadId: ThreadId;
73 readonly onClose: () => void;
74}) {
75 const insets = useSafeAreaInsets();
76 const { themeVariables } = useAppearancePreferences();
77 const focused = useIsFocused();
78 const [foreground, setForeground] = useState(AppState.currentState !== "background");
79 const [selectedKey, setSelectedKey] = useState<string | null>(null);
80 const [inputConnected, setInputConnected] = useState(false);
81 const [streamAttempt, setStreamAttempt] = useState(0);
82 const [shuttingDown, setShuttingDown] = useState(false);
83 const [controlsVisible, setControlsVisible] = useState(true);
84 const retryHost = useAtomCommand(deviceEnvironment.list);
85 const shutdown = useAtomCommand(deviceEnvironment.shutdown, { reportFailure: false });
86 const streamRef = useRef<DeviceStreamRef>(null);
87 const state = useEnvironmentQuery(deviceEnvironment.state({ environmentId, input: {} }));
88 const previews = useMemo(
89 () => threadDevicePreviews(state.data, threadId),
90 [state.data, threadId],
91 );
92 const preview = selectedThreadDevicePreview(previews, selectedKey);
93 const onInputConnected = useCallback(async (connected: boolean) => {
94 setInputConnected(connected);
95 if (connected) setControlsVisible(false);
96 }, []);
97 useEffect(() => {
98 const subscription = AppState.addEventListener("change", (state) =>
99 setForeground(state !== "background"),
100 );
101 return () => subscription.remove();
102 }, []);
103 useEffect(() => {
104 if (focused && state.data !== null && previews.length === 0) onClose();
105 }, [focused, state.data, previews.length, onClose]);
106 useEffect(() => {
107 if (!focused || !foreground) return;
108 const shaken = createShakeDetector();
109 Accelerometer.setUpdateInterval(50);
110 const subscription = Accelerometer.addListener((sample) => {
111 if (!shaken({ ...sample, timestamp: sample.timestamp * 1000 })) return;
112 void Haptics.selectionAsync();
113 setControlsVisible((visible) => !visible);
114 });
115 return () => subscription.remove();
116 }, [focused, foreground]);
117 useEffect(() => {
118 if (controlsVisible) return;
119 const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
120 setControlsVisible(true);
121 return true;
122 });
123 return () => subscription.remove();
124 }, [controlsVisible]);
125​
126 const shutDownDevice = async () => {
127 if (!preview || shuttingDown) return;
128 setShuttingDown(true);
129 try {
130 const result = await shutdown({
131 environmentId,
132 input: {
133 hostId: preview.session.hostId,
134 deviceId: preview.session.deviceId,
135 platform: preview.session.platform,
136 },
137 });
138 if (result._tag === "Failure") {
139 Dialog.alert("Could not shut down device", String(Cause.squash(result.cause)));
140 }
141 } finally {
142 setShuttingDown(false);
143 }
144 };
145​
146 const controls: AppBarMenuItem[] = [
147 ...(state.data?.hosts
148 .filter(
149 (host) =>
150 state.data?.supportsHostRetry && state.data.hostStatuses[host.id]?.status === "failed",
151 )
152 .map((host) => ({
153 id: `retry-${host.id}`,
154 title: `Retry ${host.label}`,
155 icon: "arrow.clockwise" as const,
156 onPress: () => {
157 void retryHost({ environmentId, input: { retryHostId: host.id } });
158 },
159 })) ?? []),
160 ...(state.data?.supportsToolInspection
161 ? [
162 {
163 id: "check-device-tools",
164 title: "Check device tool versions",
165 icon: "arrow.clockwise" as const,
166 onPress: () => {
167 void retryHost({ environmentId, input: { inspectOnly: true } });
168 },
169 },
170 ]
171 : []),
172 {
173 id: "device-tools",
174 title: "Device tool versions",
175 icon: "info.circle",
176 onPress: () =>
177 Dialog.alert(
178 "Device tool versions",
179 deviceToolUpdateOwnership +
180 "\n\n" +
181 deviceToolUpdatePolicy(
182 state.data?.hosts.find((host) => host.id === preview?.session.hostId)?.tools,
183 ) +
184 "\n\n" +
185 deviceToolVersionLabels(
186 state.data?.hosts.find((host) => host.id === preview?.session.hostId)?.tools,
187 ).join("\n") +
188 "\n" +
189 (state.data?.hosts.find((host) => host.id === preview?.session.hostId)
190 ?.toolInspectionError ??
191 state.data?.hostStatuses[preview?.session.hostId ?? ""]?.detail ??
192 ""),
193 ),
194 },
195 {
196 id: "reload",
197 title: "Reload stream",
198 icon: "arrow.clockwise" as const,
199 disabled: !preview || shuttingDown,
200 onPress: () => {
201 setInputConnected(false);
202 setStreamAttempt((attempt) => attempt + 1);
203 },
204 },
205 ...(preview?.session.platform === "android"
206 ? [
207 {
208 id: "back",
209 title: "Back",
210 icon: "arrow.left",
211 disabled: !inputConnected,
212 onPress: () => streamRef.current?.back(),
213 },
214 ]
215 : []),
216 {
217 id: "app-switcher",
218 title: "App switcher",
219 icon: "square.on.square",
220 disabled: !inputConnected,
221 onPress: () => streamRef.current?.appSwitcher(),
222 },
223 ...(preview?.session.platform === "ios"
224 ? [
225 {
226 id: "rotate",
227 title: "Rotate device",
228 icon: "arrow.clockwise" as const,
229 disabled: !inputConnected,
230 onPress: () => streamRef.current?.rotate(),
231 },
232 ]
233 : []),
234 {
235 id: "shutdown",
236 title: shuttingDown ? "Shutting down…" : "Shut down device",
237 icon: "power",
238 disabled: !preview || shuttingDown,
239 onPress: () => void shutDownDevice(),
240 },
241 ];
242 const pressHome = () => streamRef.current?.home();
243 const menuItems: AppBarMenuItem[] = [
244 ...(previews.length > 1
245 ? [
246 {
247 id: "devices",
248 title: "Devices",
249 inline: true,
250 items: previews.map((device) => ({
251 id: device.key,
252 title: device.name,
253 subtitle: device.description,
254 selected: device.key === preview?.key,
255 onPress: () => setSelectedKey(device.key),
256 })),
257 },
258 ]
259 : []),
260 ...controls,
261 ];
262 return (
263 <View className="flex-1" style={{ backgroundColor: themeVariables["--color-sheet-solid"] }}>
264 <StatusBar hidden animated />
265 {preview && focused && foreground ? (
266 <OpenDevicePreview
267 key={`${preview.key}:${streamAttempt}`}
268 environmentId={environmentId}
269 preview={preview}
270 streamRef={streamRef}
271 onInputConnected={onInputConnected}
272 />
273 ) : (
274 <View className="flex-1 items-center justify-center gap-4 px-6">
275 {state.error ? (
276 <>
277 <AppText selectable className="text-center text-sm text-foreground-muted">
278 {state.error}
279 </AppText>
280 <Pressable
281 accessibilityRole="button"
282 className="rounded-full border border-secondary-border bg-secondary px-6 py-3"
283 onPress={state.refresh}
284 >
285 <AppText className="text-secondary-foreground">Retry</AppText>
286 </Pressable>
287 </>
288 ) : focused && foreground ? (
289 <AppActivityIndicator color={themeVariables["--color-icon"]} />
290 ) : null}
291 </View>
292 )}
293 {controlsVisible ? (
294 <Animated.View
295 entering={OVERLAY_ENTERING}
296 exiting={OVERLAY_EXITING}
297 pointerEvents="box-none"
298 className="absolute inset-0"
299 >
300 {inputConnected ? (
301 <Pressable
302 accessibilityLabel="Hide device controls"
303 className="absolute inset-0 bg-black/30"
304 onPress={() => setControlsVisible(false)}
305 />
306 ) : null}
307 <View className="px-3" style={{ paddingTop: Math.max(insets.top, 12) }}>
308 <GlassSurface className="flex-row items-center gap-1 p-1">
309 <ControlPill
310 accessibilityLabel="Close device preview"
311 icon="xmark"
312 onPress={onClose}
313 />
314 <AppText numberOfLines={1} className="flex-1 text-center font-t3-medium text-base">
315 {preview?.name ?? "Devices"}
316 </AppText>
317 <ControlPill
318 accessibilityLabel="Home"
319 icon="house"
320 disabled={!inputConnected}
321 onPress={pressHome}
322 />
323 <DeviceOptionsMenu items={menuItems} />
324 </GlassSurface>
325 </View>
326 </Animated.View>
327 ) : (
328 <Pressable
329 accessibilityRole="button"
330 accessibilityLabel="Show device controls"
331 accessibilityHint="Shaking the phone also shows them"
332 hitSlop={12}
333 className="absolute h-6 w-16 items-center justify-center self-center"
334 style={{ top: Math.max(insets.top - 18, 4) }}
335 onPress={() => setControlsVisible(true)}
336 >
337 <View className="h-1.5 w-10 rounded-full bg-white/40" />
338 </Pressable>
339 )}
340 </View>
341 );
343​
344function DeviceOptionsMenu({ items }: { readonly items: ReadonlyArray<AppBarMenuItem> }) {
345 return (
346 <Menu
347 actions={androidHeaderMenuActions(items)}
348 isAnchoredToRight
349 title="Device options"
350 onPressAction={({ nativeEvent }) => {
351 const action = findHeaderMenuAction(items, nativeEvent.event);
352 if (action && !action.disabled) action.onPress();
353 }}
354 >
355 <Pressable
356 accessibilityLabel="Device options"
357 accessibilityRole="button"
358 className="size-11 items-center justify-center rounded-full bg-subtle"
359 >
360 <SymbolView name="ellipsis" size={18} tintColorClassName="accent-icon" />
361 </Pressable>
362 </Menu>
363 );
365​
366function OpenDevicePreview({
367 environmentId,
368 preview,
369 streamRef,
370 onInputConnected,
371}: {
372 readonly environmentId: EnvironmentId;
373 readonly preview: ThreadDevicePreview;
374 readonly streamRef: RefObject<DeviceStreamRef | null>;
375 readonly onInputConnected: (connected: boolean) => Promise<void>;
376}) {
377 const { session } = preview;
378 const { themeVariables } = useAppearancePreferences();
379 const { access, error, refresh } = useDeviceHubAccess(environmentId, session.hostId);
380 const onUnauthorized = useCallback(
381 async () => refreshDeviceHubAccess(environmentId),
382 [environmentId],
383 );
384 useEffect(() => {
385 refreshDeviceHubAccess(environmentId);
386 return () => void onInputConnected(false);
387 }, [environmentId, onInputConnected]);
388 return access ? (
389 <DeviceStreamWebView
390 ref={streamRef}
391 access={access}
392 platform={session.platform}
393 deviceId={session.deviceId}
394 colors={{
395 background: themeVariables["--color-sheet-solid"],
396 foreground: themeVariables["--color-foreground"],
397 muted: themeVariables["--color-foreground-muted"],
398 buttonBackground: themeVariables["--color-secondary"],
399 buttonForeground: themeVariables["--color-secondary-foreground"],
400 buttonBorder: themeVariables["--color-secondary-border"],
401 }}
402 onUnauthorized={onUnauthorized}
403 onInputConnected={onInputConnected}
404 />
405 ) : (
406 <View className="flex-1 items-center justify-center gap-4 px-6">
407 {error ? (
408 <>
409 <AppText selectable className="text-center text-sm text-foreground-muted">
410 {error}
411 </AppText>
412 <Pressable
413 accessibilityRole="button"
414 className="rounded-full border border-secondary-border bg-secondary px-6 py-3"
415 onPress={refresh}
416 >
417 <AppText className="text-secondary-foreground">Retry</AppText>
418 </Pressable>
419 </>
420 ) : (
421 <>
422 <AppActivityIndicator color={themeVariables["--color-icon"]} />
423 <AppText className="text-sm text-foreground-muted">Connecting to device...</AppText>
424 </>
425 )}
426 </View>
427 );