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: 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 ? gt`The page asks for files.` : 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 {control.dialog.type === "auth" ? (
532 <>
533 <TextInput
534 accessibilityLabel={gt`Username`}
535 autoCapitalize="none"
536 autoCorrect={false}
537 className="min-h-[48px] rounded-lg border border-input-border bg-input px-3 py-2 text-foreground android:min-h-[50px]"
538 placeholder={gt`Username`}
539 placeholderTextColorClassName="accent-placeholder"
540 selectionColorClassName="accent-focus/32"
541 value={promptText}
542 onChangeText={setPromptText}
543 />
544 <TextInput
545 accessibilityLabel={gt`Password`}
546 autoCapitalize="none"
547 autoCorrect={false}
548 secureTextEntry
549 className="min-h-[48px] rounded-lg border border-input-border bg-input px-3 py-2 text-foreground android:min-h-[50px]"
550 placeholder={gt`Password`}
551 placeholderTextColorClassName="accent-placeholder"
552 selectionColorClassName="accent-focus/32"
553 value={password}
554 onChangeText={setPassword}
555 />
556 </>
557 ) : null}
558 <View className="flex-row justify-end gap-3">
559 <Button
560 label={gt({ context: "rejects a page dialog" })`Dismiss`}
561 tone="text"
562 onPress={() =>
563 command({
564 type: "dialog",
565 accept: false,
566 authChallengeId: control.dialog?.authChallengeId,
567 })
568 }
569 />
570 <Button
571 label={gt({ context: "accepts a page dialog" })`Accept`}
572 tone="secondary"
573 onPress={() =>
574 command({
575 type: "dialog",
576 accept: true,
577 ...(control.dialog?.type === "prompt" ? { promptText } : {}),
578 ...(control.dialog?.type === "auth"
579 ? {
580 authChallengeId: control.dialog.authChallengeId,
581 username: promptText,
582 password,
583 }
584 : {}),
585 })
586 }
587 />
588 </View>
589 </>
590 ) : (
591 <AppText className="text-xs text-foreground-muted">
592 {gt`Take control to respond.`}
593 </AppText>
594 )}
595 </View>
596 ) : null}
597 {status !== "streaming" ? (
598 <View
599 className="absolute inset-0 items-center justify-center gap-4 px-6"
600 style={{ backgroundColor: background }}
601 >
602 {status === "connecting" ? <AppActivityIndicator colorClassName="accent-icon" /> : null}
603 {compact ? null : (
604 <AppText
605 accessibilityLiveRegion="polite"
606 className="text-center text-sm text-foreground-muted"
607 >
608 {status === "error" ? error : gt`Connecting to browser...`}
609 </AppText>
610 )}
611 {status === "error" && hostSetup && !compact ? (
612 <Pressable
613 accessibilityRole="button"
614 accessibilityLabel={gt`Copy ${{ command: hostSetup.command }}`}
615 className="w-full flex-row items-center gap-2 rounded-xl border border-secondary-border bg-secondary px-4 py-3"
616 onPress={() => {
617 void Clipboard.setStringAsync(hostSetup.command).catch(() => undefined);
618 }}
619 >
620 <AppText selectable className="flex-1 font-mono text-sm text-secondary-foreground">
621 {hostSetup.command}
622 </AppText>
623 <AppText className="text-xs text-foreground-muted">
624 {gt({ context: "verb" })`Copy`}
625 </AppText>
626 </Pressable>
627 ) : null}
628 {status === "error" && !gone && !compact ? (
629 <View className="items-center">
630 <Button
631 label={hostSetup ? gt`Try again` : gt`Reconnect`}
632 tone="secondary"
633 onPress={onRetry}
634 />
635 </View>
636 ) : null}
637 </View>
638 ) : null}
639 </View>
640 );
641}