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

PreviewStreamWebView.tsx

554 lines20.2 KB

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