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

DevicePreviewRouteScreen.tsx

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