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 [password, setPassword] = useState("");
268 const [fileChooser, setFileChooser] = useState<PreviewStreamFileChooser | null>(null);
269 const answerFileChooser = (pick: boolean) => {
270 const chooser = fileChooser;
271 if (!chooser) return;
272 setFileChooser(null);
273 void sendFilesToPage(chooser, pick).catch((cause: unknown) =>
274 Dialog.alert(
275 m(msg("Could not send the files to the page")),
276 cause instanceof Error ? (errorDisplayMessage(cause, m) ?? cause.message) : undefined,
277 ),
278 );
279 };
280 const [selectMenu, setSelectMenu] = useState<PreviewStreamSelectMenu | null>(null);
281 const command = (input: PreviewStreamInput) =>
282 webView.current?.injectJavaScript(
283 `window.T3PreviewStream?.command(${JSON.stringify(input)}); true;`,
284 );
285 // Reads here rather than in the screen: a tab switch during the iOS paste prompt unmounts
286 // this view and nulls its WebView ref, so the text can never type into another tab.
287 const paste = () =>
288 void Clipboard.getStringAsync().then(
289 (text) => {
290 if (text) command({ type: "text", text });
291 },
292 () => Dialog.alert(m(msg("Could not read the clipboard"))),
293 );
294 const clearBootstrapTimer = () => {
295 if (bootstrapTimer.current === null) return;
296 clearTimeout(bootstrapTimer.current);
297 bootstrapTimer.current = null;
298 };
299 const fail = (message: string) => {
300 if (!active.current || failed.current) return;
301 failed.current = true;
302 clearBootstrapTimer();
303 webView.current?.injectJavaScript("window.T3PreviewStream?.stop(); true;");
304 onStreamingChange?.(false);
305 setControl(null);
306 setFileChooser(null);
307 setSelectMenu(null);
308 onControl?.(null);
309 setError(message);
310 setStatus("error");
311 };
312 const bootstrapTimedOut = useEffectEvent(() =>
313 fail(m(msg("Browser viewer could not start. Reconnect to try again."))),
314 );
315 const streamEnded = useEffectEvent(() => {
316 onStreamingChange?.(false);
317 onControl?.(null);
318 });
319 // The stream lives exactly as long as this view.
320 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts the bootstrap timeout and stops the WebView stream when this view unmounts
321 useLayoutEffect(() => {
322 active.current = true;
323 const view = webView.current;
324 bootstrapTimer.current = setTimeout(bootstrapTimedOut, 15_000);
325 return () => {
326 if (bootstrapTimer.current !== null) clearTimeout(bootstrapTimer.current);
327 bootstrapTimer.current = null;
328 active.current = false;
329 view?.injectJavaScript("window.T3PreviewStream?.stop(); true;");
330 streamEnded();
331 };
332 }, []);
333 const source = {
334 html: previewStreamDocument(
335 configuration,
336 previewStreamScript,
337 gt("Browser viewer stopped unexpectedly."),
338 ),
339 baseUrl: Platform.OS === "android" ? "https://localhost/" : "file:///",
340 };
341 useImperativeHandle(ref, () => ({
342 command,
343 paste,
344 togglePictureInPicture: () =>
345 webView.current?.injectJavaScript("window.T3PreviewStream?.pictureInPicture(); true;"),
346 }));
347 const processTerminated = () => {
348 if (!active.current || failed.current) return;
349 if (!onRecoverProcess()) fail(m(msg("Browser viewer stopped. Reconnect to try again.")));
350 };
351 return (
352 <View className="flex-1" style={{ backgroundColor: background }}>
353 {/* With control, the bar's menu offers releasing it, so the row would only take space. */}
354 {!compact && control?.controller !== "you" ? (
355 <View className="flex-row items-center justify-between gap-2 border-b border-secondary-border px-3 py-2">
356 <AppText className="text-xs text-foreground-muted">
357 {previewStreamControlLabel(control, messages)}
358 </AppText>
359 {control?.canOperate ? (
360 <Button
361 label={gt("Take control")}
362 tone="secondary"
363 disabled={control.controller === "another-viewer"}
364 onPress={() => command({ type: "takeControl" })}
365 />
366 ) : null}
367 </View>
368 ) : null}
369 <View className="relative flex-1">
370 <WebView<object>
371 ref={webView}
372 source={source}
373 originWhitelist={["*"]}
374 scrollEnabled={false}
375 bounces={false}
376 mixedContentMode="always"
377 allowUniversalAccessFromFileURLs
378 contentInsetAdjustmentBehavior="never"
379 setSupportMultipleWindows={false}
380 allowsInlineMediaPlayback
381 allowsPictureInPictureMediaPlayback
382 mediaPlaybackRequiresUserAction={false}
383 style={{ flex: 1, backgroundColor: background }}
384 onError={() => fail(m(msg("Browser viewer could not load. Reconnect to try again.")))}
385 onHttpError={() => fail(m(msg("Browser viewer could not load. Reconnect to try again.")))}
386 onContentProcessDidTerminate={processTerminated}
387 onRenderProcessGone={processTerminated}
388 onShouldStartLoadWithRequest={(request) =>
389 request.url === "about:blank" || request.url === source.baseUrl
390 }
391 onMessage={(event) => {
392 if (!active.current || failed.current) return;
393 const message = previewStreamMessage(event.nativeEvent.data);
394 if (message === null) return;
395 switch (message.type) {
396 case "control": {
397 setControl(message);
398 if (message.controller !== "you") setSelectMenu(null);
399 const previousDialog = dialogRef.current;
400 dialogRef.current = message.dialog;
401 setPromptText((draft) => previewPromptText(previousDialog, message.dialog, draft));
402 setPassword((draft) => previewPromptText(previousDialog, message.dialog, draft));
403 onControl?.(message);
404 return;
405 }
406 case "unauthorized":
407 if (!onUnauthorized()) {
408 fail(
409 m(msg("This session can't open the browser stream. Reconnect to try again.")),
410 );
411 }
412 return;
413 case "gone":
414 setGone(true);
415 fail(m(msg("This tab was closed.")));
416 onGone?.();
417 return;
418 case "hostSetup":
419 setHostSetup({ need: message.need, command: message.command });
420 fail(previewStreamHostSetupMessage(message, m));
421 return;
422 case "viewport":
423 onViewport?.(message);
424 return;
425 case "scroll":
426 onScrollDirection?.(message.direction);
427 return;
428 case "clipboard":
429 void Clipboard.setStringAsync(message.text).catch(() => undefined);
430 return;
431 case "download":
432 offerDownload(message);
433 return;
434 case "fileChooser":
435 setFileChooser(message.chooser);
436 return;
437 case "selectMenu":
438 setSelectMenu(message.menu);
439 return;
440 case "pictureInPicture":
441 onPictureInPicture?.(message, message.detail);
442 return;
443 case "status":
444 if (message.status !== "connecting") clearBootstrapTimer();
445 if (message.status === "error") {
446 fail(message.detail ?? m(msg("Browser stream failed.")));
447 return;
448 }
449 setStatus(message.status);
450 if (message.status === "connecting") {
451 // Dialogs may have closed and reopened while this viewer was disconnected.
452 dialogRef.current = null;
453 setControl(null);
454 onControl?.(null);
455 }
456 onStreamingChange?.(message.status === "streaming");
457 if (message.status === "streaming") onStreaming();
458 }
459 }}
460 />
461 {pdfUri ? (
462 <View className="absolute inset-0">
463 <PdfPreview key={pdfUri} uri={pdfUri} />
464 </View>
465 ) : null}
466 </View>
467 {!compact && fileChooser && control?.controller === "you" ? (
468 <View className="absolute inset-x-3 top-16 gap-3 rounded-xl border border-secondary-border bg-secondary p-4">
469 <AppText className="text-sm text-secondary-foreground">
470 {fileChooser.multiple
471 ? gt("The page asks for files.")
472 : gt("The page asks for a file.")}
473 </AppText>
474 <View className="flex-row justify-end gap-3">
475 <Button label={gt("Cancel")} tone="text" onPress={() => answerFileChooser(false)} />
476 <Button
477 label={fileChooser.multiple ? gt("Choose files") : gt("Choose file")}
478 tone="secondary"
479 onPress={() => answerFileChooser(true)}
480 />
481 </View>
482 </View>
483 ) : null}
484 {!compact && selectMenu && control?.controller === "you" ? (
485 <Sheet
486 key={selectMenu.id}
487 title={gt("Choose an option")}
488 onClose={() =>
489 setSelectMenu((current) => (current?.id === selectMenu.id ? null : current))
490 }
491 >
492 {/* oxlint-disable-next-line t3code/require-registered-list-scroll -- Sheet content; the sheet keeps its own header handling. */}
493 <LegendList
494 data={selectMenu.options}
495 // The page answers by option index.
496 keyExtractor={(_, index) => String(index)}
497 extraData={selectMenu}
498 estimatedItemSize={48}
499 className="flex-1"
500 nestedScrollEnabled
501 contentInsetAdjustmentBehavior="automatic"
502 contentContainerStyle={{ padding: 16 }}
503 renderItem={({ item, index }) => (
504 <ListChoiceRow
505 label={item.label}
506 selected={index === selectMenu.selectedIndex}
507 separated={index > 0}
508 disabled={item.disabled}
509 onPress={() => {
510 setSelectMenu(null);
511 command({ type: "selectMenu", id: selectMenu.id, index });
512 }}
513 />
514 )}
515 />
516 </Sheet>
517 ) : null}
518 {!compact && control?.dialog ? (
519 <View className="absolute inset-x-3 top-16 gap-3 rounded-xl border border-secondary-border bg-secondary p-4">
520 <AppText className="text-sm text-secondary-foreground">{control.dialog.message}</AppText>
521 {control.controller === "you" ? (
522 <>
523 {control.dialog.type === "prompt" ? (
524 <TextInput
525 accessibilityLabel={gt("Dialog response")}
526 className="rounded-lg border border-input-border bg-input px-3 py-2 text-foreground"
527 placeholderTextColorClassName="accent-placeholder"
528 selectionColorClassName="accent-focus/32"
529 value={promptText}
530 onChangeText={setPromptText}
531 />
532 ) : null}
533 {control.dialog.type === "auth" ? (
534 <>
535 <TextInput
536 accessibilityLabel={gt("Username")}
537 autoCapitalize="none"
538 autoCorrect={false}
539 className="min-h-[48px] rounded-lg border border-input-border bg-input px-3 py-2 text-foreground android:min-h-[50px]"
540 placeholder={gt("Username")}
541 placeholderTextColorClassName="accent-placeholder"
542 selectionColorClassName="accent-focus/32"
543 value={promptText}
544 onChangeText={setPromptText}
545 />
546 <TextInput
547 accessibilityLabel={gt("Password")}
548 autoCapitalize="none"
549 autoCorrect={false}
550 secureTextEntry
551 className="min-h-[48px] rounded-lg border border-input-border bg-input px-3 py-2 text-foreground android:min-h-[50px]"
552 placeholder={gt("Password")}
553 placeholderTextColorClassName="accent-placeholder"
554 selectionColorClassName="accent-focus/32"
555 value={password}
556 onChangeText={setPassword}
557 />
558 </>
559 ) : null}
560 <View className="flex-row justify-end gap-3">
561 <Button
562 label={gt("Dismiss", { $context: "rejects a page dialog" })}
563 tone="text"
564 onPress={() =>
565 command({
566 type: "dialog",
567 accept: false,
568 authChallengeId: control.dialog?.authChallengeId,
569 })
570 }
571 />
572 <Button
573 label={gt("Accept", { $context: "accepts a page dialog" })}
574 tone="secondary"
575 onPress={() =>
576 command({
577 type: "dialog",
578 accept: true,
579 ...(control.dialog?.type === "prompt" ? { promptText } : {}),
580 ...(control.dialog?.type === "auth"
581 ? {
582 authChallengeId: control.dialog.authChallengeId,
583 username: promptText,
584 password,
585 }
586 : {}),
587 })
588 }
589 />
590 </View>
591 </>
592 ) : (
593 <AppText className="text-xs text-foreground-muted">
594 {gt("Take control to respond.")}
595 </AppText>
596 )}
597 </View>
598 ) : null}
599 {status !== "streaming" ? (
600 <View
601 className="absolute inset-0 items-center justify-center gap-4 px-6"
602 style={{ backgroundColor: background }}
603 >
604 {status === "connecting" ? <AppActivityIndicator colorClassName="accent-icon" /> : null}
605 {compact ? null : (
606 <AppText
607 accessibilityLiveRegion="polite"
608 className="text-center text-sm text-foreground-muted"
609 >
610 {status === "error" ? error : gt("Connecting to browser...")}
611 </AppText>
612 )}
613 {status === "error" && hostSetup && !compact ? (
614 <Pressable
615 accessibilityRole="button"
616 accessibilityLabel={gt("Copy {command}", { command: hostSetup.command })}
617 className="w-full flex-row items-center gap-2 rounded-xl border border-secondary-border bg-secondary px-4 py-3"
618 onPress={() => {
619 void Clipboard.setStringAsync(hostSetup.command).catch(() => undefined);
620 }}
621 >
622 <AppText selectable className="flex-1 font-mono text-sm text-secondary-foreground">
623 {hostSetup.command}
624 </AppText>
625 <AppText className="text-xs text-foreground-muted">
626 {gt("Copy", { $context: "verb" })}
627 </AppText>
628 </Pressable>
629 ) : null}
630 {status === "error" && !gone && !compact ? (
631 <View className="items-center">
632 <Button
633 label={hostSetup ? gt("Try again") : gt("Reconnect")}
634 tone="secondary"
635 onPress={onRetry}
636 />
637 </View>
638 ) : null}
639 </View>
640 ) : null}
641 </View>
642 );
643}