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

DevicePreviewRouteScreen.tsx

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