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

PreviewStreamWebView.tsx

530 lines19.0 KB

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