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

DevicePreviewRouteScreen.tsx

445 lines16.1 KB

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