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

DevicePreviewRouteScreen.tsx

415 lines14.7 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 { deriveBottomControlInsets } from "../../lib/reserved-regions";
31import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
32import { deviceEnvironment, refreshDeviceHubAccess, useDeviceHubAccess } from "../../state/device";
33import { useEnvironmentQuery } from "../../state/query";
34import { useAtomCommand } from "../../state/use-atom-command";
35import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
36import { DeviceStreamWebView, type DeviceStreamRef } from "./DeviceStreamWebView";
37import {
38 selectedThreadDevicePreview,
39 threadDevicePreviews,
40 type ThreadDevicePreview,
41} from "./threadDevicePreviews";
42import { createShakeDetector } from "./shakeDetector";
43​
44const OVERLAY_ENTERING = FadeIn.duration(160).reduceMotion(ReduceMotion.System);
45const OVERLAY_EXITING = FadeOut.duration(120).reduceMotion(ReduceMotion.System);
46​
47type DevicePreviewRouteScreenProps = StaticScreenProps<{
48 readonly environmentId: string;
49 readonly threadId: string;
50}>;
51​
52export function DevicePreviewRouteScreen({ route }: DevicePreviewRouteScreenProps) {
53 const navigation = useNavigation();
54 const onClose = () => navigation.goBack();
55 const { environmentId, threadId } = route.params;
56 const isBlankLink = environmentId.trim().length === 0 || threadId.trim().length === 0;
57 useEffect(() => {
58 if (isBlankLink) onClose();
59 }, [isBlankLink, onClose]);
60 if (isBlankLink) return null;
61 return (
62 <DevicePreviewScreen
63 environmentId={EnvironmentId.make(environmentId)}
64 threadId={ThreadId.make(threadId)}
65 onClose={onClose}
66 />
67 );
69​
70function DevicePreviewScreen({
71 environmentId,
72 threadId,
73 onClose,
74}: {
75 readonly environmentId: EnvironmentId;
76 readonly threadId: ThreadId;
77 readonly onClose: () => void;
78}) {
79 const insets = useSafeAreaInsets();
80 // NativeColumnContent already insets the sides, so only a book fold moves the reveal handle.
81 const handleBounds = deriveBottomControlInsets(useNativeColumnLayoutMetrics());
82 const { themeVariables } = useAppearancePreferences();
83 const focused = useIsFocused();
84 const [foreground, setForeground] = useState(AppState.currentState !== "background");
85 const [selectedKey, setSelectedKey] = useState<string | null>(null);
86 const [inputConnected, setInputConnected] = useState(false);
87 const [streamAttempt, setStreamAttempt] = useState(0);
88 const [shuttingDown, setShuttingDown] = useState(false);
89 const [controlsVisible, setControlsVisible] = useState(true);
90 const retryHost = useAtomCommand(deviceEnvironment.list);
91 const shutdown = useAtomCommand(deviceEnvironment.shutdown, { reportFailure: false });
92 const streamRef = useRef<DeviceStreamRef>(null);
93 const state = useEnvironmentQuery(deviceEnvironment.state({ environmentId, input: {} }));
94 const previews = threadDevicePreviews(state.data, threadId);
95 const preview = selectedThreadDevicePreview(previews, selectedKey);
96 const onInputConnected = async (connected: boolean) => {
97 setInputConnected(connected);
98 if (connected) setControlsVisible(false);
99 };
100 useEffect(() => {
101 const subscription = AppState.addEventListener("change", (state) =>
102 setForeground(state !== "background"),
103 );
104 return () => subscription.remove();
105 }, []);
106 useEffect(() => {
107 if (focused && state.data !== null && previews.length === 0) onClose();
108 }, [focused, state.data, previews.length, onClose]);
109 useEffect(() => {
110 if (!focused || !foreground) return;
111 const shaken = createShakeDetector();
112 Accelerometer.setUpdateInterval(50);
113 const subscription = Accelerometer.addListener((sample) => {
114 if (!shaken({ ...sample, timestamp: sample.timestamp * 1000 })) return;
115 void Haptics.selectionAsync();
116 setControlsVisible((visible) => !visible);
117 });
118 return () => subscription.remove();
119 }, [focused, foreground]);
120 useEffect(() => {
121 if (controlsVisible) return;
122 const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
123 setControlsVisible(true);
124 return true;
125 });
126 return () => subscription.remove();
127 }, [controlsVisible]);
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 <StatusBar hidden animated />
264 {preview && focused && foreground ? (
265 <OpenDevicePreview
266 key={`${preview.key}:${streamAttempt}`}
267 environmentId={environmentId}
268 preview={preview}
269 streamRef={streamRef}
270 onInputConnected={onInputConnected}
271 />
272 ) : (
273 <View className="flex-1 items-center justify-center gap-4 px-6">
274 {state.error ? (
275 <>
276 <AppText selectable className="text-center text-sm text-foreground-muted">
277 {state.error}
278 </AppText>
279 <View className="items-center">
280 <Button label="Retry" tone="secondary" onPress={state.refresh} />
281 </View>
282 </>
283 ) : focused && foreground ? (
284 <AppActivityIndicator color={themeVariables["--color-icon"]} />
285 ) : null}
286 </View>
287 )}
288 {controlsVisible ? (
289 <Animated.View
290 entering={OVERLAY_ENTERING}
291 exiting={OVERLAY_EXITING}
292 pointerEvents="box-none"
293 className="absolute inset-0"
294 >
295 {inputConnected ? (
296 <Pressable
297 accessibilityLabel="Hide device controls"
298 className="absolute inset-0 bg-black/30"
299 onPress={() => setControlsVisible(false)}
300 />
301 ) : null}
302 <View className="px-3" style={{ paddingTop: Math.max(insets.top, 12) }}>
303 <GlassSurface className="flex-row items-center gap-1 p-1">
304 <SheetCloseButton accessibilityLabel="Close device preview" onClose={onClose} />
305 <AppText numberOfLines={1} className="flex-1 text-center font-t3-medium text-base">
306 {preview?.name ?? "Devices"}
307 </AppText>
308 <ControlPill
309 accessibilityLabel="Home"
310 icon="house"
311 disabled={!inputConnected}
312 onPress={pressHome}
313 />
314 <DeviceOptionsMenu items={menuItems} />
315 </GlassSurface>
316 </View>
317 </Animated.View>
318 ) : (
319 <Pressable
320 accessibilityRole="button"
321 accessibilityLabel="Show device controls"
322 accessibilityHint="Shaking the phone also shows them"
323 hitSlop={12}
324 className="absolute h-6 w-16 items-center justify-center self-center"
325 style={{
326 top: Math.max(insets.top - 18, 4),
327 transform: [{ translateX: (handleBounds.left - handleBounds.right) / 2 }],
328 }}
329 onPress={() => setControlsVisible(true)}
330 >
331 <View className="h-1.5 w-10 rounded-full bg-white/40" />
332 </Pressable>
333 )}
334 </View>
335 );
337​
338function DeviceOptionsMenu({ items }: { readonly items: ReadonlyArray<AppBarMenuItem> }) {
339 return (
340 <Menu
341 actions={androidHeaderMenuActions(items)}
342 isAnchoredToRight
343 title="Device options"
344 onPressAction={({ nativeEvent }) => {
345 const action = findHeaderMenuAction(items, nativeEvent.event);
346 if (action && !action.disabled) action.onPress();
347 }}
348 >
349 <Pressable
350 accessibilityLabel="Device options"
351 accessibilityRole="button"
352 className="size-11 items-center justify-center rounded-full bg-subtle"
353 >
354 <SymbolView name="ellipsis" size={18} tintColorClassName="accent-icon" />
355 </Pressable>
356 </Menu>
357 );
359​
360function OpenDevicePreview({
361 environmentId,
362 preview,
363 streamRef,
364 onInputConnected,
365}: {
366 readonly environmentId: EnvironmentId;
367 readonly preview: ThreadDevicePreview;
368 readonly streamRef: RefObject<DeviceStreamRef | null>;
369 readonly onInputConnected: (connected: boolean) => Promise<void>;
370}) {
371 const { session } = preview;
372 const { themeVariables } = useAppearancePreferences();
373 const { access, error, refresh } = useDeviceHubAccess(environmentId, session.hostId);
374 const onUnauthorized = async () => refreshDeviceHubAccess(environmentId);
375 useEffect(() => {
376 refreshDeviceHubAccess(environmentId);
377 return () => void onInputConnected(false);
378 }, [environmentId, onInputConnected]);
379 return access ? (
380 <DeviceStreamWebView
381 ref={streamRef}
382 access={access}
383 platform={session.platform}
384 deviceId={session.deviceId}
385 colors={{
386 background: themeVariables["--color-sheet-solid"],
387 foreground: themeVariables["--color-foreground"],
388 muted: themeVariables["--color-foreground-muted"],
389 buttonBackground: themeVariables["--color-secondary"],
390 buttonForeground: themeVariables["--color-secondary-foreground"],
391 buttonBorder: themeVariables["--color-secondary-border"],
392 }}
393 onUnauthorized={onUnauthorized}
394 onInputConnected={onInputConnected}
395 />
396 ) : (
397 <View className="flex-1 items-center justify-center gap-4 px-6">
398 {error ? (
399 <>
400 <AppText selectable className="text-center text-sm text-foreground-muted">
401 {error}
402 </AppText>
403 <View className="items-center">
404 <Button label="Retry" tone="secondary" onPress={refresh} />
405 </View>
406 </>
407 ) : (
408 <>
409 <AppActivityIndicator color={themeVariables["--color-icon"]} />
410 <AppText className="text-sm text-foreground-muted">Connecting to device...</AppText>
411 </>
412 )}
413 </View>
414 );