Open History to see the last commit
1import previewStreamScript from "@t3tools/mobile-preview-stream";
2import {
3 previewStreamControlLabel,
4 previewStreamHostSetupMessage,
5 type PreviewStreamControl,
6 type PreviewStreamDownload,
7 type PreviewStreamFileChooser,
8 type PreviewStreamInput,
9} from "@t3tools/client-runtime/preview/server-browser-stream";
10import type { EnvironmentId, PreviewStreamHostSetup } from "@t3tools/contracts";
11import {
12 useEffect,
13 useEffectEvent,
14 useImperativeHandle,
15 useLayoutEffect,
16 useMemo,
17 useRef,
18 useState,
19 type Ref,
20} from "react";
21import { ActivityIndicator, Alert, Platform, Pressable, TextInput, View } from "react-native";
22import { WebView } from "react-native-webview";
23import * as Clipboard from "expo-clipboard";
24
25import { AppText } from "../../components/AppText";
26import { downloadAndShareAttachment } from "../../lib/attachmentDownload";
27import { beginForegroundHandoff } from "../../lib/foreground-handoff";
28import { usePreviewStreamAccess } from "../../state/preview";
29
30import {
31 previewStreamDocument,
32 previewStreamMessage,
33 type PreviewStreamConfiguration,
34} from "./preview-stream-document";
35
36export interface PreviewStreamRef {
37 /** Navigation requires current control of the browser. */
38 readonly command: (input: PreviewStreamInput) => void;
39 readonly togglePictureInPicture: () => void;
40}
41
42export interface PreviewPictureInPictureState {
43 readonly supported: boolean;
44 readonly active: boolean;
45}
46
47type NativeStreamBridge = {
48 readonly ref?: Ref<PreviewStreamRef>;
49 /** Refresh stream access; new access remounts the document with a fresh ticket. */
50 readonly onUnauthorized: () => void;
51 /** The tab was closed on the server. */
52 readonly onGone?: () => void;
53 readonly onViewport?: (viewport: { readonly width: number; readonly height: number }) => void;
54 readonly onControl?: (control: PreviewStreamControl | null) => void;
55 readonly onPictureInPicture?: (state: PreviewPictureInPictureState, detail?: string) => void;
56 /** True while frames show, so commands reach the page. Pass a stable function. */
57 readonly onStreamingChange?: (streaming: boolean) => void;
58 /** The floating player shows a spinner without text or a reconnect button. */
59 readonly compact?: boolean;
60};
61
62/** Picks files on this device and sends them to the page's open picker; none cancels it. */
63async function sendFilesToPage(chooser: PreviewStreamFileChooser, pick: boolean) {
64 const body = new FormData();
65 if (pick) {
66 const { getDocumentAsync } = await import("expo-document-picker");
67 const endHandoff = beginForegroundHandoff();
68 let result: Awaited<ReturnType<typeof getDocumentAsync>>;
69 try {
70 result = await getDocumentAsync({ multiple: chooser.multiple, copyToCacheDirectory: true });
71 } finally {
72 endHandoff();
73 }
74 for (const asset of result.canceled ? [] : result.assets) {
75 // React Native's FormData uploads a file part from its URI.
76 body.append("file", {
77 uri: asset.uri,
78 name: asset.name,
79 type: asset.mimeType ?? "application/octet-stream",
80 } as unknown as Blob);
81 }
82 }
83 const response = await fetch(chooser.uploadUrl, {
84 method: "POST",
85 body,
86 credentials: chooser.credentials ? "include" : "omit",
87 });
88 if (!response.ok) throw new Error((await response.text()) || "The upload was refused.");
89}
90
91/** The file is on the environment; saving it here goes through the share sheet. */
92function offerDownload(download: PreviewStreamDownload) {
93 Alert.alert(`Downloaded ${download.fileName}`, undefined, [
94 { text: "Not now", style: "cancel" },
95 {
96 text: "Save or share",
97 onPress: () =>
98 void downloadAndShareAttachment({
99 url: download.url,
100 attachment: { name: download.fileName, mimeType: "application/octet-stream" },
101 signal: new AbortController().signal,
102 }).catch((cause: unknown) =>
103 Alert.alert(
104 "Could not save the download",
105 cause instanceof Error ? cause.message : undefined,
106 ),
107 ),
108 },
109 ]);
110}
111
112// Consecutive refused tickets before the view stops and offers Reconnect, e.g. a
113// session without operate scope.
114const MAX_REFUSALS = 3;
115
116export function PreviewStreamWebView(
117 props: Omit<PreviewStreamConfiguration, "access"> &
118 Omit<NativeStreamBridge, "onUnauthorized"> & {
119 readonly environmentId: EnvironmentId;
120 readonly paused?: boolean;
121 },
122) {
123 const { access, error, refresh } = usePreviewStreamAccess(props.environmentId);
124 if (access && !props.paused) {
125 return <AuthorizedPreviewStream {...props} access={access} onUnauthorized={refresh} />;
126 }
127 return (
128 <View
129 className={
130 props.compact
131 ? "flex-1 items-center justify-center"
132 : "flex-1 items-center justify-center gap-4 px-6"
133 }
134 >
135 {props.compact || !error ? <ActivityIndicator colorClassName="accent-icon" /> : null}
136 {!props.compact && (
137 <>
138 <AppText
139 selectable={!!error}
140 className={
141 error ? "text-center text-sm text-foreground-muted" : "text-sm text-foreground-muted"
142 }
143 >
144 {error || "Connecting to browser..."}
145 </AppText>
146 {error && (
147 <Pressable
148 accessibilityRole="button"
149 className="rounded-full border border-secondary-border bg-secondary px-6 py-3"
150 onPress={refresh}
151 >
152 <AppText className="text-secondary-foreground">Retry</AppText>
153 </Pressable>
154 )}
155 </>
156 )}
157 </View>
158 );
159}
160
161function AuthorizedPreviewStream({
162 ref,
163 ...props
164}: PreviewStreamConfiguration & NativeStreamBridge) {
165 const [attempt, setAttempt] = useState(0);
166 const [previousAccess, setPreviousAccess] = useState(props.access);
167 // Wait for refreshed access, including cookie credentials with unchanged JSON.
168 if (props.access !== previousAccess) {
169 setPreviousAccess(props.access);
170 setAttempt((current) => current + 1);
171 }
172 const processRetried = useRef(false);
173 const unauthorized = useRef(0);
174 const refreshTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
175 useEffect(
176 () => () => {
177 if (refreshTimer.current !== null) clearTimeout(refreshTimer.current);
178 },
179 [],
180 );
181 const configuration = JSON.stringify({
182 access: props.access,
183 threadId: props.threadId,
184 tabId: props.tabId,
185 interactive: props.interactive,
186 background: props.background,
187 } satisfies PreviewStreamConfiguration);
188 return (
189 <PreviewStreamDocumentView
190 key={`${attempt}:${configuration}`}
191 {...props}
192 ref={ref}
193 configuration={configuration}
194 onUnauthorized={() => {
195 // The client has stopped. Restart it with a fresh ticket, backing off between refusals.
196 const refusals = ++unauthorized.current;
197 if (refusals >= MAX_REFUSALS) return false;
198 if (refreshTimer.current !== null) clearTimeout(refreshTimer.current);
199 refreshTimer.current = setTimeout(
200 () => {
201 refreshTimer.current = null;
202 props.onUnauthorized();
203 },
204 refusals === 1 ? 0 : 1_000 * 2 ** (refusals - 1),
205 );
206 return true;
207 }}
208 onRetry={() => {
209 processRetried.current = false;
210 unauthorized.current = 0;
211 props.onUnauthorized();
212 }}
213 onStreaming={() => {
214 processRetried.current = false;
215 unauthorized.current = 0;
216 }}
217 onRecoverProcess={() => {
218 if (processRetried.current) return false;
219 processRetried.current = true;
220 setAttempt((current) => current + 1);
221 return true;
222 }}
223 />
224 );
225}
226
227function PreviewStreamDocumentView({
228 ref,
229 configuration,
230 background,
231 compact,
232 onUnauthorized,
233 onGone,
234 onViewport,
235 onControl,
236 onPictureInPicture,
237 onStreamingChange,
238 onRetry,
239 onStreaming,
240 onRecoverProcess,
241}: Omit<NativeStreamBridge, "onUnauthorized"> & {
242 readonly configuration: string;
243 readonly background: string;
244 /** False when the view should stop retrying and fail. */
245 readonly onUnauthorized: () => boolean;
246 readonly onRetry: () => void;
247 readonly onStreaming: () => void;
248 readonly onRecoverProcess: () => boolean;
249}) {
250 const webView = useRef<WebView<object>>(null);
251 const active = useRef(true);
252 const failed = useRef(false);
253 const [status, setStatus] = useState<"connecting" | "streaming" | "error">("connecting");
254 const [error, setError] = useState<string | null>(null);
255 const [gone, setGone] = useState(false);
256 const [hostSetup, setHostSetup] = useState<PreviewStreamHostSetup | null>(null);
257 const [started, setStarted] = useState(false);
258 const [control, setControl] = useState<PreviewStreamControl | null>(null);
259 const [promptText, setPromptText] = useState("");
260 const [fileChooser, setFileChooser] = useState<PreviewStreamFileChooser | null>(null);
261 const answerFileChooser = (pick: boolean) => {
262 const chooser = fileChooser;
263 if (!chooser) return;
264 setFileChooser(null);
265 void sendFilesToPage(chooser, pick).catch((cause: unknown) =>
266 Alert.alert(
267 "Could not send the files to the page",
268 cause instanceof Error ? cause.message : undefined,
269 ),
270 );
271 };
272 const controlChanged = useEffectEvent((next: PreviewStreamControl | null) => onControl?.(next));
273 const command = (input: PreviewStreamInput) =>
274 webView.current?.injectJavaScript(
275 `window.T3PreviewStream?.command(${JSON.stringify(input)}); true;`,
276 );
277 const fail = (message: string) => {
278 if (!active.current || failed.current) return;
279 failed.current = true;
280 webView.current?.injectJavaScript("window.T3PreviewStream?.stop(); true;");
281 onStreamingChange?.(false);
282 setControl(null);
283 setFileChooser(null);
284 onControl?.(null);
285 setError(message);
286 setStatus("error");
287 };
288 // The shared transport owns reconnects once the document acknowledges startup.
289 const bootstrapTimedOut = useEffectEvent(() =>
290 fail("Browser viewer could not start. Reconnect to try again."),
291 );
292 useEffect(() => {
293 if (started) return;
294 const timer = setTimeout(bootstrapTimedOut, 15_000);
295 return () => clearTimeout(timer);
296 }, [started]);
297 const source = useMemo(
298 () => ({
299 html: previewStreamDocument(configuration, previewStreamScript),
300 baseUrl: Platform.OS === "android" ? "https://localhost/" : "file:///",
301 }),
302 [configuration],
303 );
304 useImperativeHandle(ref, () => ({
305 command,
306 togglePictureInPicture: () =>
307 webView.current?.injectJavaScript("window.T3PreviewStream?.pictureInPicture(); true;"),
308 }));
309 useLayoutEffect(() => {
310 active.current = true;
311 const view = webView.current;
312 return () => {
313 active.current = false;
314 view?.injectJavaScript("window.T3PreviewStream?.stop(); true;");
315 };
316 }, []);
317 useEffect(() => () => onStreamingChange?.(false), [onStreamingChange]);
318 useEffect(() => () => controlChanged(null), []);
319 const processTerminated = () => {
320 if (!active.current || failed.current) return;
321 if (!onRecoverProcess()) fail("Browser viewer stopped. Reconnect to try again.");
322 };
323 return (
324 <View className="flex-1" style={{ backgroundColor: background }}>
325 {!compact ? (
326 <View className="flex-row items-center justify-between gap-2 border-b border-secondary-border px-3 py-2">
327 <AppText className="text-xs text-foreground-muted">
328 {previewStreamControlLabel(control)}
329 </AppText>
330 {control?.canOperate ? (
331 <Pressable
332 accessibilityRole="button"
333 disabled={control.controller === "another-viewer"}
334 accessibilityState={{ disabled: control.controller === "another-viewer" }}
335 className="rounded-full border border-secondary-border bg-secondary px-3 py-2"
336 onPress={() =>
337 command({ type: control.controller === "you" ? "releaseControl" : "takeControl" })
338 }
339 >
340 <AppText className="text-xs text-secondary-foreground">
341 {control.controller === "you" ? "Release control" : "Take control"}
342 </AppText>
343 </Pressable>
344 ) : null}
345 </View>
346 ) : null}
347 <WebView<object>
348 ref={webView}
349 source={source}
350 originWhitelist={["*"]}
351 scrollEnabled={false}
352 bounces={false}
353 mixedContentMode="always"
354 allowUniversalAccessFromFileURLs
355 contentInsetAdjustmentBehavior="never"
356 setSupportMultipleWindows={false}
357 // Picture in picture plays the canvas as an inline muted video, started from native chrome.
358 allowsInlineMediaPlayback
359 allowsPictureInPictureMediaPlayback
360 mediaPlaybackRequiresUserAction={false}
361 style={{ flex: 1, backgroundColor: background }}
362 onError={() => fail("Browser viewer could not load. Reconnect to try again.")}
363 onHttpError={() => fail("Browser viewer could not load. Reconnect to try again.")}
364 onContentProcessDidTerminate={processTerminated}
365 onRenderProcessGone={processTerminated}
366 onShouldStartLoadWithRequest={(request) =>
367 request.url === "about:blank" || request.url === source.baseUrl
368 }
369 onMessage={(event) => {
370 if (!active.current || failed.current) return;
371 const message = previewStreamMessage(event.nativeEvent.data);
372 if (message === null) return;
373 switch (message.type) {
374 case "control":
375 setControl(message);
376 setPromptText(message.dialog?.defaultValue ?? "");
377 onControl?.(message);
378 return;
379 case "unauthorized":
380 if (!onUnauthorized()) {
381 fail("This session can't open the browser stream. Reconnect to try again.");
382 }
383 return;
384 case "gone":
385 setGone(true);
386 fail("This tab was closed.");
387 onGone?.();
388 return;
389 case "hostSetup":
390 setHostSetup({ need: message.need, command: message.command });
391 fail(previewStreamHostSetupMessage(message));
392 return;
393 case "viewport":
394 onViewport?.(message);
395 return;
396 case "clipboard":
397 void Clipboard.setStringAsync(message.text).catch(() => undefined);
398 return;
399 case "download":
400 offerDownload(message);
401 return;
402 case "fileChooser":
403 setFileChooser(message.chooser);
404 return;
405 case "pictureInPicture":
406 onPictureInPicture?.(message, message.detail);
407 return;
408 case "status":
409 setStarted(true);
410 if (message.status === "error") {
411 fail(message.detail ?? "Browser stream failed.");
412 return;
413 }
414 setStatus(message.status);
415 if (message.status === "connecting") {
416 setControl(null);
417 onControl?.(null);
418 }
419 onStreamingChange?.(message.status === "streaming");
420 if (message.status === "streaming") onStreaming();
421 }
422 }}
423 />
424 {!compact && fileChooser && control?.controller === "you" ? (
425 <View className="absolute inset-x-3 top-16 gap-3 rounded-xl border border-secondary-border bg-secondary p-4">
426 <AppText className="text-sm text-secondary-foreground">
427 The page asks for {fileChooser.multiple ? "files" : "a file"}.
428 </AppText>
429 <View className="flex-row justify-end gap-3">
430 <Pressable
431 accessibilityRole="button"
432 className="px-3 py-2"
433 onPress={() => answerFileChooser(false)}
434 >
435 <AppText className="text-secondary-foreground">Cancel</AppText>
436 </Pressable>
437 <Pressable
438 accessibilityRole="button"
439 className="px-3 py-2"
440 onPress={() => answerFileChooser(true)}
441 >
442 <AppText className="text-secondary-foreground">
443 Choose {fileChooser.multiple ? "files" : "file"}
444 </AppText>
445 </Pressable>
446 </View>
447 </View>
448 ) : null}
449 {!compact && control?.dialog ? (
450 <View className="absolute inset-x-3 top-16 gap-3 rounded-xl border border-secondary-border bg-secondary p-4">
451 <AppText className="text-sm text-secondary-foreground">{control.dialog.message}</AppText>
452 {control.controller === "you" ? (
453 <>
454 {control.dialog.type === "prompt" ? (
455 <TextInput
456 accessibilityLabel="Dialog response"
457 className="rounded-lg border border-secondary-border bg-background px-3 py-2 text-foreground"
458 value={promptText}
459 onChangeText={setPromptText}
460 />
461 ) : null}
462 <View className="flex-row justify-end gap-3">
463 <Pressable
464 accessibilityRole="button"
465 className="px-3 py-2"
466 onPress={() => command({ type: "dialog", accept: false })}
467 >
468 <AppText className="text-secondary-foreground">Dismiss</AppText>
469 </Pressable>
470 <Pressable
471 accessibilityRole="button"
472 className="px-3 py-2"
473 onPress={() =>
474 command({
475 type: "dialog",
476 accept: true,
477 ...(control.dialog?.type === "prompt" ? { promptText } : {}),
478 })
479 }
480 >
481 <AppText className="text-secondary-foreground">Accept</AppText>
482 </Pressable>
483 </View>
484 </>
485 ) : (
486 <AppText className="text-xs text-foreground-muted">Take control to respond.</AppText>
487 )}
488 </View>
489 ) : null}
490 {status !== "streaming" ? (
491 <View
492 className="absolute inset-0 items-center justify-center gap-4 px-6"
493 style={{ backgroundColor: background }}
494 >
495 {status === "connecting" ? <ActivityIndicator colorClassName="accent-icon" /> : null}
496 {compact ? null : (
497 <AppText
498 accessibilityLiveRegion="polite"
499 className="text-center text-sm text-foreground-muted"
500 >
501 {status === "error" ? error : "Connecting to browser..."}
502 </AppText>
503 )}
504 {status === "error" && hostSetup && !compact ? (
505 <Pressable
506 accessibilityRole="button"
507 accessibilityLabel={`Copy ${hostSetup.command}`}
508 className="w-full flex-row items-center gap-2 rounded-xl border border-secondary-border bg-secondary px-4 py-3"
509 onPress={() => {
510 void Clipboard.setStringAsync(hostSetup.command).catch(() => undefined);
511 }}
512 >
513 <AppText selectable className="flex-1 font-mono text-sm text-secondary-foreground">
514 {hostSetup.command}
515 </AppText>
516 <AppText className="text-xs text-foreground-muted">Copy</AppText>
517 </Pressable>
518 ) : null}
519 {status === "error" && !gone && !compact ? (
520 <Pressable
521 accessibilityRole="button"
522 className="rounded-full border border-secondary-border bg-secondary px-6 py-3"
523 onPress={onRetry}
524 >
525 <AppText className="text-secondary-foreground">
526 {hostSetup ? "Try again" : "Reconnect"}
527 </AppText>
528 </Pressable>
529 ) : null}
530 </View>
531 ) : null}
532 </View>
533 );
534}