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

PreviewStreamWebView.tsx

531 lines19.1 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 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts the bootstrap timeout and stops the WebView stream when this view unmounts
299 useLayoutEffect(() => {
300 active.current = true;
301 const view = webView.current;
302 bootstrapTimer.current = setTimeout(bootstrapTimedOut, 15_000);
303 return () => {
304 if (bootstrapTimer.current !== null) clearTimeout(bootstrapTimer.current);
305 bootstrapTimer.current = null;
306 active.current = false;
307 view?.injectJavaScript("window.T3PreviewStream?.stop(); true;");
308 streamEnded();
309 };
310 }, []);
311 const source = useMemo(
312 () => ({
313 html: previewStreamDocument(configuration, previewStreamScript),
314 baseUrl: Platform.OS === "android" ? "https://localhost/" : "file:///",
315 }),
316 [configuration],
317 );
318 useImperativeHandle(ref, () => ({
319 command,
320 paste,
321 togglePictureInPicture: () =>
322 webView.current?.injectJavaScript("window.T3PreviewStream?.pictureInPicture(); true;"),
323 }));
324 const processTerminated = () => {
325 if (!active.current || failed.current) return;
326 if (!onRecoverProcess()) fail("Browser viewer stopped. Reconnect to try again.");
327 };
328 return (
329 <View className="flex-1" style={{ backgroundColor: background }}>
330 {!compact ? (
331 <View className="flex-row items-center justify-between gap-2 border-b border-secondary-border px-3 py-2">
332 <AppText className="text-xs text-foreground-muted">
333 {previewStreamControlLabel(control)}
334 </AppText>
335 {control?.canOperate ? (
336 <Button
337 label={control.controller === "you" ? "Release control" : "Take control"}
338 tone="secondary"
339 disabled={control.controller === "another-viewer"}
340 onPress={() =>
341 command({ type: control.controller === "you" ? "releaseControl" : "takeControl" })
342 }
343 />
344 ) : null}
345 </View>
346 ) : null}
347 <View className="relative flex-1">
348 <WebView<object>
349 ref={webView}
350 source={source}
351 originWhitelist={["*"]}
352 scrollEnabled={false}
353 bounces={false}
354 mixedContentMode="always"
355 allowUniversalAccessFromFileURLs
356 contentInsetAdjustmentBehavior="never"
357 setSupportMultipleWindows={false}
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 const previousDialog = dialogRef.current;
377 dialogRef.current = message.dialog;
378 setPromptText((draft) => previewPromptText(previousDialog, message.dialog, draft));
379 onControl?.(message);
380 return;
381 }
382 case "unauthorized":
383 if (!onUnauthorized()) {
384 fail("This session can't open the browser stream. Reconnect to try again.");
385 }
386 return;
387 case "gone":
388 setGone(true);
389 fail("This tab was closed.");
390 onGone?.();
391 return;
392 case "hostSetup":
393 setHostSetup({ need: message.need, command: message.command });
394 fail(previewStreamHostSetupMessage(message));
395 return;
396 case "viewport":
397 onViewport?.(message);
398 return;
399 case "clipboard":
400 void Clipboard.setStringAsync(message.text).catch(() => undefined);
401 return;
402 case "download":
403 offerDownload(message);
404 return;
405 case "fileChooser":
406 setFileChooser(message.chooser);
407 return;
408 case "pictureInPicture":
409 onPictureInPicture?.(message, message.detail);
410 return;
411 case "status":
412 clearBootstrapTimer();
413 if (message.status === "error") {
414 fail(message.detail ?? "Browser stream failed.");
415 return;
416 }
417 setStatus(message.status);
418 if (message.status === "connecting") {
419 // Dialogs may have closed and reopened while this viewer was disconnected.
420 dialogRef.current = null;
421 setControl(null);
422 onControl?.(null);
423 }
424 onStreamingChange?.(message.status === "streaming");
425 if (message.status === "streaming") onStreaming();
426 }
427 }}
428 />
429 {pdfUri ? (
430 <View className="absolute inset-0">
431 <PdfPreview key={pdfUri} uri={pdfUri} />
432 </View>
433 ) : null}
434 </View>
435 {!compact && fileChooser && control?.controller === "you" ? (
436 <View className="absolute inset-x-3 top-16 gap-3 rounded-xl border border-secondary-border bg-secondary p-4">
437 <AppText className="text-sm text-secondary-foreground">
438 The page asks for {fileChooser.multiple ? "files" : "a file"}.
439 </AppText>
440 <View className="flex-row justify-end gap-3">
441 <Button label="Cancel" tone="text" onPress={() => answerFileChooser(false)} />
442 <Button
443 label={`Choose ${fileChooser.multiple ? "files" : "file"}`}
444 tone="secondary"
445 onPress={() => answerFileChooser(true)}
446 />
447 </View>
448 </View>
449 ) : null}
450 {!compact && control?.dialog ? (
451 <View className="absolute inset-x-3 top-16 gap-3 rounded-xl border border-secondary-border bg-secondary p-4">
452 <AppText className="text-sm text-secondary-foreground">{control.dialog.message}</AppText>
453 {control.controller === "you" ? (
454 <>
455 {control.dialog.type === "prompt" ? (
456 <TextInput
457 accessibilityLabel="Dialog response"
458 className="rounded-lg border border-input-border bg-input px-3 py-2 text-foreground"
459 placeholderTextColorClassName="accent-placeholder"
460 selectionColorClassName="accent-focus/32"
461 value={promptText}
462 onChangeText={setPromptText}
463 />
464 ) : null}
465 <View className="flex-row justify-end gap-3">
466 <Button
467 label="Dismiss"
468 tone="text"
469 onPress={() => command({ type: "dialog", accept: false })}
470 />
471 <Button
472 label="Accept"
473 tone="secondary"
474 onPress={() =>
475 command({
476 type: "dialog",
477 accept: true,
478 ...(control.dialog?.type === "prompt" ? { promptText } : {}),
479 })
480 }
481 />
482 </View>
483 </>
484 ) : (
485 <AppText className="text-xs text-foreground-muted">Take control to respond.</AppText>
486 )}
487 </View>
488 ) : null}
489 {status !== "streaming" ? (
490 <View
491 className="absolute inset-0 items-center justify-center gap-4 px-6"
492 style={{ backgroundColor: background }}
493 >
494 {status === "connecting" ? <AppActivityIndicator colorClassName="accent-icon" /> : null}
495 {compact ? null : (
496 <AppText
497 accessibilityLiveRegion="polite"
498 className="text-center text-sm text-foreground-muted"
499 >
500 {status === "error" ? error : "Connecting to browser..."}
501 </AppText>
502 )}
503 {status === "error" && hostSetup && !compact ? (
504 <Pressable
505 accessibilityRole="button"
506 accessibilityLabel={`Copy ${hostSetup.command}`}
507 className="w-full flex-row items-center gap-2 rounded-xl border border-secondary-border bg-secondary px-4 py-3"
508 onPress={() => {
509 void Clipboard.setStringAsync(hostSetup.command).catch(() => undefined);
510 }}
511 >
512 <AppText selectable className="flex-1 font-mono text-sm text-secondary-foreground">
513 {hostSetup.command}
514 </AppText>
515 <AppText className="text-xs text-foreground-muted">Copy</AppText>
516 </Pressable>
517 ) : null}
518 {status === "error" && !gone && !compact ? (
519 <View className="items-center">
520 <Button
521 label={hostSetup ? "Try again" : "Reconnect"}
522 tone="secondary"
523 onPress={onRetry}
524 />
525 </View>
526 ) : null}
527 </View>
528 ) : null}
529 </View>
530 );