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

DevicePreviewRouteScreen.tsx

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