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

DevicePreviewRouteScreen.tsx

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