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

PreviewStreamWebView.tsx

533 lines19.3 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 { downloadAndShareAttachment } from "../../lib/attachmentDownload";
29import { beginForegroundHandoff } from "../../lib/foreground-handoff";
30import { usePreviewStreamAccess } from "../../state/preview";
31import { previewPromptText } from "./previewPromptText";
32​
33import {
34 previewStreamDocument,
35 previewStreamMessage,
36 type PreviewStreamConfiguration,
37} from "./preview-stream-document";
38​
39export interface PreviewStreamRef {
40 readonly command: (input: PreviewStreamInput) => void;
41 readonly togglePictureInPicture: () => void;
43​
44export interface PreviewPictureInPictureState {
45 readonly supported: boolean;
46 readonly active: boolean;
48​
49type NativeStreamBridge = {
50 readonly ref?: Ref<PreviewStreamRef>;
51 readonly onUnauthorized: () => void;
52 readonly onGone?: () => void;
53 readonly onViewport?: (viewport: { readonly width: number; readonly height: number }) => void;
54 readonly onControl?: (control: PreviewStreamControl | null) => void;
55 readonly onPictureInPicture?: (state: PreviewPictureInPictureState, detail?: string) => void;
56 /** True while frames show, so commands reach the page. Pass a stable function. */
57 readonly onStreamingChange?: (streaming: boolean) => void;
58 readonly compact?: boolean;
59};
60​
61async function sendFilesToPage(chooser: PreviewStreamFileChooser, pick: boolean) {
62 const body = new FormData();
63 if (pick) {
64 const { getDocumentAsync } = await import("expo-document-picker");
65 const endHandoff = beginForegroundHandoff();
66 let result: Awaited<ReturnType<typeof getDocumentAsync>>;
67 try {
68 result = await getDocumentAsync({ multiple: chooser.multiple, copyToCacheDirectory: true });
69 } finally {
70 endHandoff();
71 }
72 for (const asset of result.canceled ? [] : result.assets) {
73 // React Native's FormData uploads a file part from its URI.
74 body.append("file", {
75 uri: asset.uri,
76 name: asset.name,
77 type: asset.mimeType ?? "application/octet-stream",
78 } as unknown as Blob);
79 }
80 }
81 const response = await fetch(chooser.uploadUrl, {
82 method: "POST",
83 body,
84 credentials: chooser.credentials ? "include" : "omit",
85 });
86 if (!response.ok) throw new Error((await response.text()) || "The upload was refused.");
88​
89function offerDownload(download: PreviewStreamDownload) {
90 Dialog.alert(`Downloaded ${download.fileName}`, undefined, [
91 { text: "Not now", style: "cancel" },
92 {
93 text: "Save or share",
94 onPress: () =>
95 void downloadAndShareAttachment({
96 url: download.url,
97 attachment: { name: download.fileName, mimeType: "application/octet-stream" },
98 signal: new AbortController().signal,
99 }).catch((cause: unknown) =>
100 Dialog.alert(
101 "Could not save the download",
102 cause instanceof Error ? cause.message : undefined,
103 ),
104 ),
105 },
106 ]);
108​
109const MAX_REFUSALS = 3;
110​
111export function PreviewStreamWebView(
112 props: Omit<PreviewStreamConfiguration, "access"> &
113 Omit<NativeStreamBridge, "onUnauthorized"> & {
114 readonly environmentId: EnvironmentId;
115 readonly paused?: boolean;
116 },
117) {
118 const { access, error, refresh } = usePreviewStreamAccess(props.environmentId);
119 if (access && !props.paused) {
120 return <AuthorizedPreviewStream {...props} access={access} onUnauthorized={refresh} />;
121 }
122 return (
123 <View
124 className={
125 props.compact
126 ? "flex-1 items-center justify-center"
127 : "flex-1 items-center justify-center gap-4 px-6"
128 }
129 >
130 {props.compact || !error ? <AppActivityIndicator colorClassName="accent-icon" /> : null}
131 {!props.compact && (
132 <>
133 <AppText
134 selectable={!!error}
135 className={
136 error ? "text-center text-sm text-foreground-muted" : "text-sm text-foreground-muted"
137 }
138 >
139 {error || "Connecting to browser..."}
140 </AppText>
141 {error && (
142 <Pressable
143 accessibilityRole="button"
144 className="rounded-full border border-secondary-border bg-secondary px-6 py-3"
145 onPress={refresh}
146 >
147 <AppText className="text-secondary-foreground">Retry</AppText>
148 </Pressable>
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 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 const fail = (message: string) => {
272 if (!active.current || failed.current) return;
273 failed.current = true;
274 webView.current?.injectJavaScript("window.T3PreviewStream?.stop(); true;");
275 onStreamingChange?.(false);
276 setControl(null);
277 setFileChooser(null);
278 onControl?.(null);
279 setError(message);
280 setStatus("error");
281 };
282 const bootstrapTimedOut = useEffectEvent(() =>
283 fail("Browser viewer could not start. Reconnect to try again."),
284 );
285 useEffect(() => {
286 if (started) return;
287 const timer = setTimeout(bootstrapTimedOut, 15_000);
288 return () => clearTimeout(timer);
289 }, [started]);
290 const source = useMemo(
291 () => ({
292 html: previewStreamDocument(configuration, previewStreamScript),
293 baseUrl: Platform.OS === "android" ? "https://localhost/" : "file:///",
294 }),
295 [configuration],
296 );
297 useImperativeHandle(ref, () => ({
298 command,
299 togglePictureInPicture: () =>
300 webView.current?.injectJavaScript("window.T3PreviewStream?.pictureInPicture(); true;"),
301 }));
302 useLayoutEffect(() => {
303 active.current = true;
304 const view = webView.current;
305 return () => {
306 active.current = false;
307 view?.injectJavaScript("window.T3PreviewStream?.stop(); true;");
308 };
309 }, []);
310 useEffect(() => () => onStreamingChange?.(false), [onStreamingChange]);
311 useEffect(() => () => controlChanged(null), []);
312 const processTerminated = () => {
313 if (!active.current || failed.current) return;
314 if (!onRecoverProcess()) fail("Browser viewer stopped. Reconnect to try again.");
315 };
316 return (
317 <View className="flex-1" style={{ backgroundColor: background }}>
318 {!compact ? (
319 <View className="flex-row items-center justify-between gap-2 border-b border-secondary-border px-3 py-2">
320 <AppText className="text-xs text-foreground-muted">
321 {previewStreamControlLabel(control)}
322 </AppText>
323 {control?.canOperate ? (
324 <Pressable
325 accessibilityRole="button"
326 disabled={control.controller === "another-viewer"}
327 accessibilityState={{ disabled: control.controller === "another-viewer" }}
328 className="rounded-full border border-secondary-border bg-secondary px-3 py-2"
329 onPress={() =>
330 command({ type: control.controller === "you" ? "releaseControl" : "takeControl" })
331 }
332 >
333 <AppText className="text-xs text-secondary-foreground">
334 {control.controller === "you" ? "Release control" : "Take control"}
335 </AppText>
336 </Pressable>
337 ) : null}
338 </View>
339 ) : null}
340 <WebView<object>
341 ref={webView}
342 source={source}
343 originWhitelist={["*"]}
344 scrollEnabled={false}
345 bounces={false}
346 mixedContentMode="always"
347 allowUniversalAccessFromFileURLs
348 contentInsetAdjustmentBehavior="never"
349 setSupportMultipleWindows={false}
350 allowsInlineMediaPlayback
351 allowsPictureInPictureMediaPlayback
352 mediaPlaybackRequiresUserAction={false}
353 style={{ flex: 1, backgroundColor: background }}
354 onError={() => fail("Browser viewer could not load. Reconnect to try again.")}
355 onHttpError={() => fail("Browser viewer could not load. Reconnect to try again.")}
356 onContentProcessDidTerminate={processTerminated}
357 onRenderProcessGone={processTerminated}
358 onShouldStartLoadWithRequest={(request) =>
359 request.url === "about:blank" || request.url === source.baseUrl
360 }
361 onMessage={(event) => {
362 if (!active.current || failed.current) return;
363 const message = previewStreamMessage(event.nativeEvent.data);
364 if (message === null) return;
365 switch (message.type) {
366 case "control": {
367 setControl(message);
368 const previousDialog = dialogRef.current;
369 dialogRef.current = message.dialog;
370 setPromptText((draft) => previewPromptText(previousDialog, message.dialog, draft));
371 onControl?.(message);
372 return;
373 }
374 case "unauthorized":
375 if (!onUnauthorized()) {
376 fail("This session can't open the browser stream. Reconnect to try again.");
377 }
378 return;
379 case "gone":
380 setGone(true);
381 fail("This tab was closed.");
382 onGone?.();
383 return;
384 case "hostSetup":
385 setHostSetup({ need: message.need, command: message.command });
386 fail(previewStreamHostSetupMessage(message));
387 return;
388 case "viewport":
389 onViewport?.(message);
390 return;
391 case "clipboard":
392 void Clipboard.setStringAsync(message.text).catch(() => undefined);
393 return;
394 case "download":
395 offerDownload(message);
396 return;
397 case "fileChooser":
398 setFileChooser(message.chooser);
399 return;
400 case "pictureInPicture":
401 onPictureInPicture?.(message, message.detail);
402 return;
403 case "status":
404 setStarted(true);
405 if (message.status === "error") {
406 fail(message.detail ?? "Browser stream failed.");
407 return;
408 }
409 setStatus(message.status);
410 if (message.status === "connecting") {
411 // Dialogs may have closed and reopened while this viewer was disconnected.
412 dialogRef.current = null;
413 setControl(null);
414 onControl?.(null);
415 }
416 onStreamingChange?.(message.status === "streaming");
417 if (message.status === "streaming") onStreaming();
418 }
419 }}
420 />
421 {!compact && fileChooser && control?.controller === "you" ? (
422 <View className="absolute inset-x-3 top-16 gap-3 rounded-xl border border-secondary-border bg-secondary p-4">
423 <AppText className="text-sm text-secondary-foreground">
424 The page asks for {fileChooser.multiple ? "files" : "a file"}.
425 </AppText>
426 <View className="flex-row justify-end gap-3">
427 <Pressable
428 accessibilityRole="button"
429 className="px-3 py-2"
430 onPress={() => answerFileChooser(false)}
431 >
432 <AppText className="text-secondary-foreground">Cancel</AppText>
433 </Pressable>
434 <Pressable
435 accessibilityRole="button"
436 className="px-3 py-2"
437 onPress={() => answerFileChooser(true)}
438 >
439 <AppText className="text-secondary-foreground">
440 Choose {fileChooser.multiple ? "files" : "file"}
441 </AppText>
442 </Pressable>
443 </View>
444 </View>
445 ) : null}
446 {!compact && control?.dialog ? (
447 <View className="absolute inset-x-3 top-16 gap-3 rounded-xl border border-secondary-border bg-secondary p-4">
448 <AppText className="text-sm text-secondary-foreground">{control.dialog.message}</AppText>
449 {control.controller === "you" ? (
450 <>
451 {control.dialog.type === "prompt" ? (
452 <TextInput
453 accessibilityLabel="Dialog response"
454 className="rounded-lg border border-input-border bg-input px-3 py-2 text-foreground"
455 placeholderTextColorClassName="accent-placeholder"
456 selectionColorClassName="accent-focus/32"
457 value={promptText}
458 onChangeText={setPromptText}
459 />
460 ) : null}
461 <View className="flex-row justify-end gap-3">
462 <Pressable
463 accessibilityRole="button"
464 className="px-3 py-2"
465 onPress={() => command({ type: "dialog", accept: false })}
466 >
467 <AppText className="text-secondary-foreground">Dismiss</AppText>
468 </Pressable>
469 <Pressable
470 accessibilityRole="button"
471 className="px-3 py-2"
472 onPress={() =>
473 command({
474 type: "dialog",
475 accept: true,
476 ...(control.dialog?.type === "prompt" ? { promptText } : {}),
477 })
478 }
479 >
480 <AppText className="text-secondary-foreground">Accept</AppText>
481 </Pressable>
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 <Pressable
520 accessibilityRole="button"
521 className="rounded-full border border-secondary-border bg-secondary px-6 py-3"
522 onPress={onRetry}
523 >
524 <AppText className="text-secondary-foreground">
525 {hostSetup ? "Try again" : "Reconnect"}
526 </AppText>
527 </Pressable>
528 ) : null}
529 </View>
530 ) : null}
531 </View>
532 );