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

PreviewStreamWebView.tsx

530 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 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;
46​
47export interface PreviewPictureInPictureState {
48 readonly supported: boolean;
49 readonly active: boolean;
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 // React Native's FormData uploads a file part from its URI.
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"> & {
118 readonly environmentId: EnvironmentId;
119 readonly paused?: boolean;
120 },
121) {
122 const { access, error, refresh } = usePreviewStreamAccess(props.environmentId);
123 if (access && !props.paused) {
124 return <AuthorizedPreviewStream {...props} access={access} onUnauthorized={refresh} />;
125 }
126 return (
127 <View
128 className={
129 props.compact
130 ? "flex-1 items-center justify-center"
131 : "flex-1 items-center justify-center gap-4 px-6"
132 }
133 >
134 {props.compact || !error ? <AppActivityIndicator colorClassName="accent-icon" /> : null}
135 {!props.compact && (
136 <>
137 <AppText
138 selectable={!!error}
139 className={
140 error ? "text-center text-sm text-foreground-muted" : "text-sm text-foreground-muted"
141 }
142 >
143 {error || "Connecting to browser..."}
144 </AppText>
145 {error && (
146 <View className="items-center">
147 <Button label="Retry" tone="secondary" onPress={refresh} />
148 </View>
149 )}
150 </>
151 )}
152 </View>
153 );
155​
156function AuthorizedPreviewStream({
157 ref,
158 ...props
159}: PreviewStreamConfiguration & NativeStreamBridge) {
160 const [attempt, setAttempt] = useState(0);
161 const [previousAccess, setPreviousAccess] = useState(props.access);
162 // Wait for refreshed access, including cookie credentials with unchanged JSON.
163 if (props.access !== previousAccess) {
164 setPreviousAccess(props.access);
165 setAttempt((current) => current + 1);
166 }
167 const processRetried = useRef(false);
168 const unauthorized = useRef(0);
169 const refreshTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
170 useEffect(
171 () => () => {
172 if (refreshTimer.current !== null) clearTimeout(refreshTimer.current);
173 },
174 [],
175 );
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 if (refreshTimer.current !== null) clearTimeout(refreshTimer.current);
193 refreshTimer.current = setTimeout(
194 () => {
195 refreshTimer.current = null;
196 props.onUnauthorized();
197 },
198 refusals === 1 ? 0 : 1_000 * 2 ** (refusals - 1),
199 );
200 return true;
201 }}
202 onRetry={() => {
203 processRetried.current = false;
204 unauthorized.current = 0;
205 props.onUnauthorized();
206 }}
207 onStreaming={() => {
208 processRetried.current = false;
209 unauthorized.current = 0;
210 }}
211 onRecoverProcess={() => {
212 if (processRetried.current) return false;
213 processRetried.current = true;
214 setAttempt((current) => current + 1);
215 return true;
216 }}
217 />
218 );
220​
221function PreviewStreamDocumentView({
222 ref,
223 configuration,
224 background,
225 compact,
226 pdfUri,
227 onUnauthorized,
228 onGone,
229 onViewport,
230 onControl,
231 onPictureInPicture,
232 onStreamingChange,
233 onRetry,
234 onStreaming,
235 onRecoverProcess,
236}: Omit<NativeStreamBridge, "onUnauthorized"> & {
237 readonly configuration: string;
238 readonly background: string;
239 readonly onUnauthorized: () => boolean;
240 readonly onRetry: () => void;
241 readonly onStreaming: () => void;
242 readonly onRecoverProcess: () => boolean;
243}) {
244 const webView = useRef<WebView<object>>(null);
245 const active = useRef(true);
246 const failed = useRef(false);
247 const [status, setStatus] = useState<"connecting" | "streaming" | "error">("connecting");
248 const [error, setError] = useState<string | null>(null);
249 const [gone, setGone] = useState(false);
250 const [hostSetup, setHostSetup] = useState<PreviewStreamHostSetup | null>(null);
251 const [started, setStarted] = useState(false);
252 const [control, setControl] = useState<PreviewStreamControl | null>(null);
253 const dialogRef = useRef<PreviewStreamControl["dialog"]>(null);
254 const [promptText, setPromptText] = useState("");
255 const [fileChooser, setFileChooser] = useState<PreviewStreamFileChooser | null>(null);
256 const answerFileChooser = (pick: boolean) => {
257 const chooser = fileChooser;
258 if (!chooser) return;
259 setFileChooser(null);
260 void sendFilesToPage(chooser, pick).catch((cause: unknown) =>
261 Dialog.alert(
262 "Could not send the files to the page",
263 cause instanceof Error ? cause.message : undefined,
264 ),
265 );
266 };
267 const controlChanged = useEffectEvent((next: PreviewStreamControl | null) => onControl?.(next));
268 const command = (input: PreviewStreamInput) =>
269 webView.current?.injectJavaScript(
270 `window.T3PreviewStream?.command(${JSON.stringify(input)}); true;`,
271 );
272 // Reads here rather than in the screen: a tab switch during the iOS paste prompt unmounts
273 // this view and nulls its WebView ref, so the text can never type into another tab.
274 const paste = () =>
275 void Clipboard.getStringAsync().then(
276 (text) => {
277 if (text) command({ type: "text", text });
278 },
279 () => Dialog.alert("Could not read the clipboard"),
280 );
281 const fail = (message: string) => {
282 if (!active.current || failed.current) return;
283 failed.current = true;
284 webView.current?.injectJavaScript("window.T3PreviewStream?.stop(); true;");
285 onStreamingChange?.(false);
286 setControl(null);
287 setFileChooser(null);
288 onControl?.(null);
289 setError(message);
290 setStatus("error");
291 };
292 const bootstrapTimedOut = useEffectEvent(() =>
293 fail("Browser viewer could not start. Reconnect to try again."),
294 );
295 useEffect(() => {
296 if (started) return;
297 const timer = setTimeout(bootstrapTimedOut, 15_000);
298 return () => clearTimeout(timer);
299 }, [started]);
300 const source = useMemo(
301 () => ({
302 html: previewStreamDocument(configuration, previewStreamScript),
303 baseUrl: Platform.OS === "android" ? "https://localhost/" : "file:///",
304 }),
305 [configuration],
306 );
307 useImperativeHandle(ref, () => ({
308 command,
309 paste,
310 togglePictureInPicture: () =>
311 webView.current?.injectJavaScript("window.T3PreviewStream?.pictureInPicture(); true;"),
312 }));
313 useLayoutEffect(() => {
314 active.current = true;
315 const view = webView.current;
316 return () => {
317 active.current = false;
318 view?.injectJavaScript("window.T3PreviewStream?.stop(); true;");
319 };
320 }, []);
321 useEffect(() => () => onStreamingChange?.(false), [onStreamingChange]);
322 useEffect(() => () => controlChanged(null), []);
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 setStarted(true);
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 );