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

BrowserPreviewRouteScreen.tsx

252 lines8.9 KB

1import { SheetHeader } from "../../components/ui/SheetHeader";
2import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
3import * as Dialog from "../../components/ui/Dialog";
4import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
5import { EnvironmentId, ThreadId, type PreviewSessionSnapshot } from "@t3tools/contracts";
6import { normalizePreviewUrl, previewPdfAssetUrl } from "@t3tools/shared/preview";
7import * as Option from "effect/Option";
8import { useEffect, useRef, useState } from "react";
9import { Platform, TextInput, View } from "react-native";
10import { useSafeAreaInsets } from "react-native-safe-area-context";
11​
12import { ControlPill } from "../../components/ui/ControlPill";
13import { useContentTopInset } from "../../components/ui/useBarInset";
14import { useAppForeground } from "../../lib/appState";
15​
16import { useThreadServerBrowserTabs } from "../../state/preview";
17import { usePreparedConnection } from "../../state/session";
18import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
19import { BrowserTabMenu } from "./BrowserTabMenu";
20import { browserTabTitle, browserTabUrl, latestBrowserTab } from "./browserTabs";
21import {
22 PreviewStreamWebView,
23 type PreviewPictureInPictureState,
24 type PreviewStreamRef,
25} from "./PreviewStreamWebView";
26​
27const NO_PICTURE_IN_PICTURE: PreviewPictureInPictureState = { supported: false, active: false };
28​
29type BrowserPreviewRouteScreenProps = StaticScreenProps<{
30 readonly environmentId: string;
31 readonly threadId: string;
32 readonly tabId?: string;
33}>;
34​
35export function BrowserPreviewRouteScreen({ route }: BrowserPreviewRouteScreenProps) {
36 const navigation = useNavigation();
37 const onClose = () => navigation.goBack();
38 return (
39 <BrowserPreviewScreen
40 environmentId={EnvironmentId.make(route.params.environmentId)}
41 threadId={ThreadId.make(route.params.threadId)}
42 initialTabId={route.params.tabId ?? null}
43 onClose={onClose}
44 />
45 );
47​
48function BrowserPreviewScreen({
49 environmentId,
50 threadId,
51 initialTabId,
52 onClose,
53}: {
54 readonly environmentId: EnvironmentId;
55 readonly threadId: ThreadId;
56 readonly initialTabId: string | null;
57 readonly onClose: () => void;
58}) {
59 const insets = useSafeAreaInsets();
60 const contentTopInset = useContentTopInset();
61 const { themeVariables } = useAppearancePreferences();
62 const prepared = usePreparedConnection(environmentId);
63 const httpBaseUrl = Option.isSome(prepared) ? prepared.value.httpBaseUrl : null;
64 const focused = useIsFocused();
65 const foreground = useAppForeground();
66 const [selectedTabId, setSelectedTabId] = useState(initialTabId);
67 const [pictureInPicture, setPictureInPicture] = useState(NO_PICTURE_IN_PICTURE);
68 const [streaming, setStreaming] = useState(false);
69 const [canControl, setCanControl] = useState(false);
70 const streamRef = useRef<PreviewStreamRef>(null);
71 const { tabs, loaded } = useThreadServerBrowserTabs({ environmentId, threadId, enabled: true });
72 const tab = tabs.find((entry) => entry.tabId === selectedTabId) ?? latestBrowserTab(tabs);
73 const pdfUri =
74 tab?.navStatus._tag === "Success" ? previewPdfAssetUrl(tab.navStatus.url, httpBaseUrl) : null;
75 const tabId = tab?.tabId ?? null;
76 if (tabId !== null && tabId !== selectedTabId) {
77 setPictureInPicture(NO_PICTURE_IN_PICTURE);
78 setSelectedTabId(tabId);
79 }
80 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- closes the focused route through the navigator once the thread has no browser tabs left
81 useEffect(() => {
82 if (focused && loaded && tabs.length === 0) onClose();
83 }, [focused, loaded, tabs.length, onClose]);
84 const onPictureInPicture = (state: PreviewPictureInPictureState, detail?: string) => {
85 setPictureInPicture({ supported: state.supported, active: state.active });
86 if (detail) Dialog.alert("Picture in picture is unavailable", detail);
87 };
88 const selectTab = (next: string) => {
89 setPictureInPicture(NO_PICTURE_IN_PICTURE);
90 setSelectedTabId(next);
91 };
92 const live = (focused && foreground) || pictureInPicture.active;
93​
94 return (
95 <View
96 className="flex-1 bg-sheet"
97 style={{ paddingTop: contentTopInset, paddingBottom: insets.bottom }}
98 >
99 <SheetHeader
100 title={tab ? browserTabTitle(tab) : "Browser"}
101 onClose={onClose}
102 accessibilityLabel="Close browser"
103 actions={
104 // Android WebView cannot play video in picture in picture.
105 Platform.OS === "ios" &&
106 pictureInPicture.supported &&
107 (pictureInPicture.active || pdfUri === null)
108 ? [
109 {
110 accessibilityLabel: pictureInPicture.active
111 ? "Exit picture in picture"
112 : "Picture in picture",
113 icon: {
114 ios: pictureInPicture.active ? "pip.exit" : "pip.enter",
115 android: "visibility",
116 },
117 selected: pictureInPicture.active,
118 onPress: () => streamRef.current?.togglePictureInPicture(),
119 },
120 ]
121 : []
122 }
123 menus={
124 tabs.length > 1
125 ? [
126 {
127 title: "Tabs",
128 icon: "square.on.square",
129 items: tabs.map((entry) => ({
130 id: entry.tabId,
131 title: browserTabTitle(entry),
132 subtitle: browserTabUrl(entry),
133 selected: entry.tabId === tabId,
134 onPress: () => selectTab(entry.tabId),
135 })),
136 },
137 ]
138 : []
139 }
140 />
141 {tab ? (
142 <>
143 <BrowserAddressBar
144 key={`address:${tab.tabId}`}
145 environmentId={environmentId}
146 tab={tab}
147 streaming={streaming}
148 ready={streaming && canControl}
149 onCommand={(input) => streamRef.current?.command(input)}
150 onPaste={() => streamRef.current?.paste()}
151 />
152 {live ? (
153 <PreviewStreamWebView
154 key={`stream:${tab.tabId}`}
155 environmentId={environmentId}
156 threadId={threadId}
157 tabId={tab.tabId}
158 pdfUri={pdfUri}
159 ref={streamRef}
160 interactive
161 background={themeVariables["--color-sheet-solid"]}
162 onPictureInPicture={onPictureInPicture}
163 onStreamingChange={setStreaming}
164 onControl={(control) => setCanControl(control?.controller === "you")}
165 />
166 ) : (
167 <View className="flex-1" />
168 )}
169 </>
170 ) : (
171 <View className="flex-1 items-center justify-center">
172 {focused && foreground ? (
173 <AppActivityIndicator color={themeVariables["--color-icon"]} />
174 ) : null}
175 </View>
176 )}
177 </View>
178 );
180​
181function BrowserAddressBar({
182 environmentId,
183 tab,
184 ready,
185 streaming,
186 onCommand,
187 onPaste,
188}: {
189 readonly environmentId: EnvironmentId;
190 readonly tab: PreviewSessionSnapshot;
191 readonly ready: boolean;
192 readonly streaming: boolean;
193 readonly onCommand: PreviewStreamRef["command"];
194 readonly onPaste: () => void;
195}) {
196 const url = browserTabUrl(tab);
197 const [draft, setDraft] = useState<string | null>(null);
198 const submit = () => {
199 const value = draft ?? url;
200 setDraft(null);
201 try {
202 onCommand({ type: "navigate", url: normalizePreviewUrl(value) });
203 } catch {
204 Dialog.alert("Could not open this address", "Enter an http or https URL.");
205 }
206 };
207 return (
208 <View className="flex-row items-center gap-1 px-2 pb-2">
209 <ControlPill
210 icon="chevron.left"
211 accessibilityLabel="Back"
212 disabled={!ready || !tab.canGoBack}
213 onPress={() => onCommand({ type: "history", delta: -1 })}
214 />
215 <ControlPill
216 icon="chevron.right"
217 accessibilityLabel="Forward"
218 disabled={!ready || !tab.canGoForward}
219 onPress={() => onCommand({ type: "history", delta: 1 })}
220 />
221 <TextInput
222 accessibilityLabel="Address"
223 editable={ready}
224 value={draft ?? url}
225 onChangeText={setDraft}
226 onBlur={() => setDraft(null)}
227 onSubmitEditing={submit}
228 placeholder="Enter a URL"
229 placeholderTextColorClassName="accent-placeholder"
230 autoCapitalize="none"
231 autoCorrect={false}
232 keyboardType="url"
233 returnKeyType="go"
234 selectTextOnFocus
235 lineBreakModeIOS="tail"
236 className="h-10 min-w-0 flex-1 rounded-full border border-input-border bg-input px-4 font-sans text-sm text-foreground"
237 />
238 <ControlPill
239 icon="arrow.clockwise"
240 accessibilityLabel="Reload page"
241 disabled={!ready}
242 onPress={() => onCommand({ type: "reload" })}
243 />
244 <BrowserTabMenu
245 environmentId={environmentId}
246 tab={tab}
247 streaming={streaming}
248 onPaste={ready ? onPaste : undefined}
249 />
250 </View>
251 );