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