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