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

DevicePreviewRouteScreen.tsx

418 lines14.6 KB

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