Open History to see the last commit
1import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2import { Button } from "../../components/ui/Button";
3import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
4import * as Dialog from "../../components/ui/Dialog";
5import previewStreamScript from "@t3tools/mobile-preview-stream";
6import {
7 previewStreamControlLabel,
8 previewStreamHostSetupMessage,
9 type PreviewStreamControl,
10 type PreviewStreamDownload,
11 type PreviewStreamFileChooser,
12 type PreviewStreamInput,
13 type PreviewStreamSelectMenu,
14} from "@t3tools/client-runtime/preview/server-browser-stream";
15import type { EnvironmentId, PreviewStreamHostSetup } from "@t3tools/contracts";
16import {
17 useEffectEvent,
18 useImperativeHandle,
19 useLayoutEffect,
20 useRef,
21 useState,
22 type Ref,
23} from "react";
24import { msg, useGT, useMessages } from "gt-react-native";
25import { Platform, Pressable, TextInput, View } from "react-native";
26import { LegendList } from "@legendapp/list/react-native";
27import { WebView } from "react-native-webview";
28import * as Clipboard from "expo-clipboard";
29
30import { AppText } from "../../components/ui/AppText";
31import { ListChoiceRow } from "../../components/ui/ListChoiceRow";
32import { Sheet } from "../../components/ui/Sheet";
33import { PdfPreview } from "../../components/PdfPreview";
34import { m } from "../../i18n/messages";
35import { downloadAndShareAttachment } from "../../lib/attachmentDownload";
36import { beginForegroundHandoff } from "../../lib/foreground-handoff";
37import { usePreviewStreamAccess } from "../../state/preview";
38import { previewPromptText } from "./previewPromptText";
39
40import {
41 previewStreamDocument,
42 previewStreamMessage,
43 type PreviewStreamConfiguration,
44} from "./preview-stream-document";
45
46export interface PreviewStreamRef {
47 readonly command: (input: PreviewStreamInput) => void;
48 readonly paste: () => void;
49 readonly togglePictureInPicture: () => void;
50}
51
52export interface PreviewPictureInPictureState {
53 readonly supported: boolean;
54 readonly active: boolean;
55}
56
57type NativeStreamBridge = {
58 readonly ref?: Ref<PreviewStreamRef>;
59 readonly onUnauthorized: () => void;
60 /** Asks for fresh access after a refusal, once `delayMs` has passed. */
61 readonly onRefused: (delayMs: number) => void;
62 readonly onGone?: () => void;
63 readonly onViewport?: (viewport: { readonly width: number; readonly height: number }) => void;
64 /** The direction a drag scrolls the page, every few dozen pixels of it. */
65 readonly onScrollDirection?: (direction: "up" | "down") => void;
66 readonly onControl?: (control: PreviewStreamControl | null) => void;
67 readonly onPictureInPicture?: (state: PreviewPictureInPictureState, detail?: string) => void;
68 /** True while frames show, so commands reach the page. */
69 readonly onStreamingChange?: (streaming: boolean) => void;
70 readonly compact?: boolean;
71 readonly pdfUri?: string | null;
72};
73
74async function sendFilesToPage(chooser: PreviewStreamFileChooser, pick: boolean) {
75 const body = new FormData();
76 if (pick) {
77 const { getDocumentAsync } = await import("expo-document-picker");
78 const endHandoff = beginForegroundHandoff();
79 let result: Awaited<ReturnType<typeof getDocumentAsync>>;
80 try {
81 result = await getDocumentAsync({ multiple: chooser.multiple, copyToCacheDirectory: true });
82 } finally {
83 endHandoff();
84 }
85 for (const asset of result.canceled ? [] : result.assets) {
86 body.append("file", {
87 uri: asset.uri,
88 name: asset.name,
89 type: asset.mimeType ?? "application/octet-stream",
90 } as unknown as Blob);
91 }
92 }
93 const response = await fetch(chooser.uploadUrl, {
94 method: "POST",
95 body,
96 credentials: chooser.credentials ? "include" : "omit",
97 });
98 if (!response.ok) throw new Error((await response.text()) || m(msg("The upload was refused.")));
99}
100
101function offerDownload(download: PreviewStreamDownload) {
102 Dialog.alert(m(msg("Downloaded {fileName}", { fileName: download.fileName })), undefined, [
103 { text: m(msg("Not now")), style: "cancel" },
104 {
105 text: m(msg("Save or share")),
106 onPress: () =>
107 void downloadAndShareAttachment({
108 url: download.url,
109 attachment: { name: download.fileName, mimeType: "application/octet-stream" },
110 signal: new AbortController().signal,
111 }).catch((cause: unknown) =>
112 Dialog.alert(
113 m(msg("Could not save the download")),
114 cause instanceof Error ? (errorDisplayMessage(cause, m) ?? cause.message) : undefined,
115 ),
116 ),
117 },
118 ]);
119}
120
121const MAX_REFUSALS = 3;
122
123export function PreviewStreamWebView(
124 props: Omit<PreviewStreamConfiguration, "access" | "labels"> &
125 Omit<NativeStreamBridge, "onUnauthorized" | "onRefused"> & {
126 readonly environmentId: EnvironmentId;
127 readonly paused?: boolean;
128 },
129) {
130 const { access, error, refresh, retryAfter } = usePreviewStreamAccess(props.environmentId);
131 const gt = useGT();
132 if (access && !props.paused) {
133 return (
134 <AuthorizedPreviewStream
135 {...props}
136 access={access}
137 onUnauthorized={refresh}
138 onRefused={retryAfter}
139 />
140 );
141 }
142 return (
143 <View
144 className={
145 props.compact
146 ? "flex-1 items-center justify-center"
147 : "flex-1 items-center justify-center gap-4 px-6"
148 }
149 >
150 {props.compact || !error ? <AppActivityIndicator colorClassName="accent-icon" /> : null}
151 {!props.compact && (
152 <>
153 <AppText
154 selectable={!!error}
155 className={
156 error ? "text-center text-sm text-foreground-muted" : "text-sm text-foreground-muted"
157 }
158 >
159 {error || gt("Connecting to browser...")}
160 </AppText>
161 {error && (
162 <View className="items-center">
163 <Button label={gt("Retry")} tone="secondary" onPress={refresh} />
164 </View>
165 )}
166 </>
167 )}
168 </View>
169 );
170}
171
172function AuthorizedPreviewStream({
173 ref,
174 ...props
175}: Omit<PreviewStreamConfiguration, "labels"> & NativeStreamBridge) {
176 const gt = useGT();
177 const [attempt, setAttempt] = useState(0);
178 const [previousAccess, setPreviousAccess] = useState(props.access);
179 // Wait for refreshed access, including cookie credentials with unchanged JSON.
180 if (props.access !== previousAccess) {
181 setPreviousAccess(props.access);
182 setAttempt((current) => current + 1);
183 }
184 const processRetried = useRef(false);
185 const unauthorized = useRef(0);
186 const configuration = JSON.stringify({
187 access: props.access,
188 threadId: props.threadId,
189 tabId: props.tabId,
190 interactive: props.interactive,
191 background: props.background,
192 labels: {
193 page: gt("Browser page"),
194 pageInput: gt("Browser page input"),
195 pictureInPictureNotReady: gt("The page has not shown yet. Try again in a moment."),
196 pictureInPictureUnavailable: gt("Picture in picture is unavailable."),
197 },
198 } satisfies PreviewStreamConfiguration);
199 return (
200 <PreviewStreamDocumentView
201 key={`${attempt}:${configuration}`}
202 {...props}
203 ref={ref}
204 configuration={configuration}
205 onUnauthorized={() => {
206 const refusals = ++unauthorized.current;
207 if (refusals >= MAX_REFUSALS) return false;
208 props.onRefused(refusals === 1 ? 0 : 1_000 * 2 ** (refusals - 1));
209 return true;
210 }}
211 onRetry={() => {
212 processRetried.current = false;
213 unauthorized.current = 0;
214 props.onUnauthorized();
215 }}
216 onStreaming={() => {
217 processRetried.current = false;
218 unauthorized.current = 0;
219 }}
220 onRecoverProcess={() => {
221 if (processRetried.current) return false;
222 processRetried.current = true;
223 setAttempt((current) => current + 1);
224 return true;
225 }}
226 />
227 );
228}
229
230function PreviewStreamDocumentView({
231 ref,
232 configuration,
233 background,
234 compact,
235 pdfUri,
236 onUnauthorized,
237 onGone,
238 onViewport,
239 onScrollDirection,
240 onControl,
241 onPictureInPicture,
242 onStreamingChange,
243 onRetry,
244 onStreaming,
245 onRecoverProcess,
246}: Omit<NativeStreamBridge, "onUnauthorized" | "onRefused"> & {
247 readonly configuration: string;
248 readonly background: string;
249 readonly onUnauthorized: () => boolean;
250 readonly onRetry: () => void;
251 readonly onStreaming: () => void;
252 readonly onRecoverProcess: () => boolean;
253}) {
254 const webView = useRef<WebView<object>>(null);
255 const gt = useGT();
256 const messages = useMessages();
257 const active = useRef(false);
258 const failed = useRef(false);
259 const bootstrapTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
260 const [status, setStatus] = useState<"connecting" | "streaming" | "error">("connecting");
261 const [error, setError] = useState<string | null>(null);
262 const [gone, setGone] = useState(false);
263 const [hostSetup, setHostSetup] = useState<PreviewStreamHostSetup | null>(null);
264 const [control, setControl] = useState<PreviewStreamControl | null>(null);
265 const dialogRef = useRef<PreviewStreamControl["dialog"]>(null);
266 const [promptText, setPromptText] = useState("");
267 const [fileChooser, setFileChooser] = useState<PreviewStreamFileChooser | null>(null);
268 const answerFileChooser = (pick: boolean) => {
269 const chooser = fileChooser;
270 if (!chooser) return;
271 setFileChooser(null);
272 void sendFilesToPage(chooser, pick).catch((cause: unknown) =>
273 Dialog.alert(
274 m(msg("Could not send the files to the page")),
275 cause instanceof Error ? (errorDisplayMessage(cause, m) ?? cause.message) : undefined,
276 ),
277 );
278 };
279 const [selectMenu, setSelectMenu] = useState<PreviewStreamSelectMenu | null>(null);
280 const command = (input: PreviewStreamInput) =>
281 webView.current?.injectJavaScript(
282 `window.T3PreviewStream?.command(${JSON.stringify(input)}); true;`,
283 );
284 // Reads here rather than in the screen: a tab switch during the iOS paste prompt unmounts
285 // this view and nulls its WebView ref, so the text can never type into another tab.
286 const paste = () =>
287 void Clipboard.getStringAsync().then(
288 (text) => {
289 if (text) command({ type: "text", text });
290 },
291 () => Dialog.alert(m(msg("Could not read the clipboard"))),
292 );
293 const clearBootstrapTimer = () => {
294 if (bootstrapTimer.current === null) return;
295 clearTimeout(bootstrapTimer.current);
296 bootstrapTimer.current = null;
297 };
298 const fail = (message: string) => {
299 if (!active.current || failed.current) return;
300 failed.current = true;
301 clearBootstrapTimer();
302 webView.current?.injectJavaScript("window.T3PreviewStream?.stop(); true;");
303 onStreamingChange?.(false);
304 setControl(null);
305 setFileChooser(null);
306 setSelectMenu(null);
307 onControl?.(null);
308 setError(message);
309 setStatus("error");
310 };
311 const bootstrapTimedOut = useEffectEvent(() =>
312 fail(m(msg("Browser viewer could not start. Reconnect to try again."))),
313 );
314 const streamEnded = useEffectEvent(() => {
315 onStreamingChange?.(false);
316 onControl?.(null);
317 });
318 // The stream lives exactly as long as this view.
319 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts the bootstrap timeout and stops the WebView stream when this view unmounts
320 useLayoutEffect(() => {
321 active.current = true;
322 const view = webView.current;
323 bootstrapTimer.current = setTimeout(bootstrapTimedOut, 15_000);
324 return () => {
325 if (bootstrapTimer.current !== null) clearTimeout(bootstrapTimer.current);
326 bootstrapTimer.current = null;
327 active.current = false;
328 view?.injectJavaScript("window.T3PreviewStream?.stop(); true;");
329 streamEnded();
330 };
331 }, []);
332 const source = {
333 html: previewStreamDocument(
334 configuration,
335 previewStreamScript,
336 gt("Browser viewer stopped unexpectedly."),
337 ),
338 baseUrl: Platform.OS === "android" ? "https://localhost/" : "file:///",
339 };
340 useImperativeHandle(ref, () => ({
341 command,
342 paste,
343 togglePictureInPicture: () =>
344 webView.current?.injectJavaScript("window.T3PreviewStream?.pictureInPicture(); true;"),
345 }));
346 const processTerminated = () => {
347 if (!active.current || failed.current) return;
348 if (!onRecoverProcess()) fail(m(msg("Browser viewer stopped. Reconnect to try again.")));
349 };
350 return (
351 <View className="flex-1" style={{ backgroundColor: background }}>
352 {/* With control, the bar's menu offers releasing it, so the row would only take space. */}
353 {!compact && control?.controller !== "you" ? (
354 <View className="flex-row items-center justify-between gap-2 border-b border-secondary-border px-3 py-2">
355 <AppText className="text-xs text-foreground-muted">
356 {previewStreamControlLabel(control, messages)}
357 </AppText>
358 {control?.canOperate ? (
359 <Button
360 label={gt("Take control")}
361 tone="secondary"
362 disabled={control.controller === "another-viewer"}
363 onPress={() => command({ type: "takeControl" })}
364 />
365 ) : null}
366 </View>
367 ) : null}
368 <View className="relative flex-1">
369 <WebView<object>
370 ref={webView}
371 source={source}
372 originWhitelist={["*"]}
373 scrollEnabled={false}
374 bounces={false}
375 mixedContentMode="always"
376 allowUniversalAccessFromFileURLs
377 contentInsetAdjustmentBehavior="never"
378 setSupportMultipleWindows={false}
379 allowsInlineMediaPlayback
380 allowsPictureInPictureMediaPlayback
381 mediaPlaybackRequiresUserAction={false}
382 style={{ flex: 1, backgroundColor: background }}
383 onError={() => fail(m(msg("Browser viewer could not load. Reconnect to try again.")))}
384 onHttpError={() => fail(m(msg("Browser viewer could not load. Reconnect to try again.")))}
385 onContentProcessDidTerminate={processTerminated}
386 onRenderProcessGone={processTerminated}
387 onShouldStartLoadWithRequest={(request) =>
388 request.url === "about:blank" || request.url === source.baseUrl
389 }
390 onMessage={(event) => {
391 if (!active.current || failed.current) return;
392 const message = previewStreamMessage(event.nativeEvent.data);
393 if (message === null) return;
394 switch (message.type) {
395 case "control": {
396 setControl(message);
397 if (message.controller !== "you") setSelectMenu(null);
398 const previousDialog = dialogRef.current;
399 dialogRef.current = message.dialog;
400 setPromptText((draft) => previewPromptText(previousDialog, message.dialog, draft));
401 onControl?.(message);
402 return;
403 }
404 case "unauthorized":
405 if (!onUnauthorized()) {
406 fail(
407 m(msg("This session can't open the browser stream. Reconnect to try again.")),
408 );
409 }
410 return;
411 case "gone":
412 setGone(true);
413 fail(m(msg("This tab was closed.")));
414 onGone?.();
415 return;
416 case "hostSetup":
417 setHostSetup({ need: message.need, command: message.command });
418 fail(previewStreamHostSetupMessage(message, m));
419 return;
420 case "viewport":
421 onViewport?.(message);
422 return;
423 case "scroll":
424 onScrollDirection?.(message.direction);
425 return;
426 case "clipboard":
427 void Clipboard.setStringAsync(message.text).catch(() => undefined);
428 return;
429 case "download":
430 offerDownload(message);
431 return;
432 case "fileChooser":
433 setFileChooser(message.chooser);
434 return;
435 case "selectMenu":
436 setSelectMenu(message.menu);
437 return;
438 case "pictureInPicture":
439 onPictureInPicture?.(message, message.detail);
440 return;
441 case "status":
442 if (message.status !== "connecting") clearBootstrapTimer();
443 if (message.status === "error") {
444 fail(message.detail ?? m(msg("Browser stream failed.")));
445 return;
446 }
447 setStatus(message.status);
448 if (message.status === "connecting") {
449 // Dialogs may have closed and reopened while this viewer was disconnected.
450 dialogRef.current = null;
451 setControl(null);
452 onControl?.(null);
453 }
454 onStreamingChange?.(message.status === "streaming");
455 if (message.status === "streaming") onStreaming();
456 }
457 }}
458 />
459 {pdfUri ? (
460 <View className="absolute inset-0">
461 <PdfPreview key={pdfUri} uri={pdfUri} />
462 </View>
463 ) : null}
464 </View>
465 {!compact && fileChooser && control?.controller === "you" ? (
466 <View className="absolute inset-x-3 top-16 gap-3 rounded-xl border border-secondary-border bg-secondary p-4">
467 <AppText className="text-sm text-secondary-foreground">
468 {fileChooser.multiple
469 ? gt("The page asks for files.")
470 : gt("The page asks for a file.")}
471 </AppText>
472 <View className="flex-row justify-end gap-3">
473 <Button label={gt("Cancel")} tone="text" onPress={() => answerFileChooser(false)} />
474 <Button
475 label={fileChooser.multiple ? gt("Choose files") : gt("Choose file")}
476 tone="secondary"
477 onPress={() => answerFileChooser(true)}
478 />
479 </View>
480 </View>
481 ) : null}
482 {!compact && selectMenu && control?.controller === "you" ? (
483 <Sheet
484 key={selectMenu.id}
485 title={gt("Choose an option")}
486 onClose={() =>
487 setSelectMenu((current) => (current?.id === selectMenu.id ? null : current))
488 }
489 >
490 {/* oxlint-disable-next-line t3code/require-registered-list-scroll -- Sheet content; the sheet keeps its own header handling. */}
491 <LegendList
492 data={selectMenu.options}
493 // The page answers by option index.
494 keyExtractor={(_, index) => String(index)}
495 extraData={selectMenu}
496 estimatedItemSize={48}
497 className="flex-1"
498 nestedScrollEnabled
499 contentInsetAdjustmentBehavior="automatic"
500 contentContainerStyle={{ padding: 16 }}
501 renderItem={({ item, index }) => (
502 <ListChoiceRow
503 label={item.label}
504 selected={index === selectMenu.selectedIndex}
505 separated={index > 0}
506 disabled={item.disabled}
507 onPress={() => {
508 setSelectMenu(null);
509 command({ type: "selectMenu", id: selectMenu.id, index });
510 }}
511 />
512 )}
513 />
514 </Sheet>
515 ) : null}
516 {!compact && control?.dialog ? (
517 <View className="absolute inset-x-3 top-16 gap-3 rounded-xl border border-secondary-border bg-secondary p-4">
518 <AppText className="text-sm text-secondary-foreground">{control.dialog.message}</AppText>
519 {control.controller === "you" ? (
520 <>
521 {control.dialog.type === "prompt" ? (
522 <TextInput
523 accessibilityLabel={gt("Dialog response")}
524 className="rounded-lg border border-input-border bg-input px-3 py-2 text-foreground"
525 placeholderTextColorClassName="accent-placeholder"
526 selectionColorClassName="accent-focus/32"
527 value={promptText}
528 onChangeText={setPromptText}
529 />
530 ) : null}
531 <View className="flex-row justify-end gap-3">
532 <Button
533 label={gt("Dismiss", { $context: "rejects a page dialog" })}
534 tone="text"
535 onPress={() => command({ type: "dialog", accept: false })}
536 />
537 <Button
538 label={gt("Accept", { $context: "accepts a page dialog" })}
539 tone="secondary"
540 onPress={() =>
541 command({
542 type: "dialog",
543 accept: true,
544 ...(control.dialog?.type === "prompt" ? { promptText } : {}),
545 })
546 }
547 />
548 </View>
549 </>
550 ) : (
551 <AppText className="text-xs text-foreground-muted">
552 {gt("Take control to respond.")}
553 </AppText>
554 )}
555 </View>
556 ) : null}
557 {status !== "streaming" ? (
558 <View
559 className="absolute inset-0 items-center justify-center gap-4 px-6"
560 style={{ backgroundColor: background }}
561 >
562 {status === "connecting" ? <AppActivityIndicator colorClassName="accent-icon" /> : null}
563 {compact ? null : (
564 <AppText
565 accessibilityLiveRegion="polite"
566 className="text-center text-sm text-foreground-muted"
567 >
568 {status === "error" ? error : gt("Connecting to browser...")}
569 </AppText>
570 )}
571 {status === "error" && hostSetup && !compact ? (
572 <Pressable
573 accessibilityRole="button"
574 accessibilityLabel={gt("Copy {command}", { command: hostSetup.command })}
575 className="w-full flex-row items-center gap-2 rounded-xl border border-secondary-border bg-secondary px-4 py-3"
576 onPress={() => {
577 void Clipboard.setStringAsync(hostSetup.command).catch(() => undefined);
578 }}
579 >
580 <AppText selectable className="flex-1 font-mono text-sm text-secondary-foreground">
581 {hostSetup.command}
582 </AppText>
583 <AppText className="text-xs text-foreground-muted">
584 {gt("Copy", { $context: "verb" })}
585 </AppText>
586 </Pressable>
587 ) : null}
588 {status === "error" && !gone && !compact ? (
589 <View className="items-center">
590 <Button
591 label={hostSetup ? gt("Try again") : gt("Reconnect")}
592 tone="secondary"
593 onPress={onRetry}
594 />
595 </View>
596 ) : null}
597 </View>
598 ) : null}
599 </View>
600 );
601}