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

DevicePreviewRouteScreen.tsx

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