Open History to see the last commit
1import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
2import { EnvironmentId } from "@t3tools/contracts";
3import { normalizePreviewUrl } from "@t3tools/shared/preview";
4import { msg, useGT } from "gt-react-native";
5import { useRef, useState } from "react";
6import { View } from "react-native";
7import { SafeAreaView } from "react-native-safe-area-context";
8
9import { AppText } from "../../components/ui/AppText";
10import * as Dialog from "../../components/ui/Dialog";
11import { EmptyState } from "../../components/ui/EmptyState";
12import { m } from "../../i18n/messages";
13import { useEnvironmentPreviewTunnelOff } from "../../state/entities";
14import { useEnvironments } from "../../state/environments";
15import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
16import { BrowserChrome } from "./BrowserBar";
17import { localPreviewUrlForDevice } from "./browserTabs";
18import { TunnelWebView, type TunnelNavigation, type TunnelWebViewRef } from "./TunnelWebView";
19
20type LocalPreviewRouteScreenProps = StaticScreenProps<{
21 readonly environmentId: string;
22 readonly url: string;
23}>;
24
25export function LocalPreviewRouteScreen({ route }: LocalPreviewRouteScreenProps) {
26 const navigation = useNavigation();
27 return (
28 <LocalPreviewScreen
29 environmentId={EnvironmentId.make(route.params.environmentId)}
30 url={route.params.url}
31 onClose={() => navigation.goBack()}
32 />
33 );
34}
35
36/**
37 * Another environment's localhost page rendered by this device's own webview, full screen or, with
38 * `onMaximize`, in the inspector pane.
39 */
40export function LocalPreviewScreen(props: {
41 readonly environmentId: EnvironmentId;
42 readonly url: string;
43 readonly onClose: () => void;
44 readonly onMaximize?: (url: string) => void;
45}) {
46 const { environmentId, onMaximize } = props;
47 const gt = useGT();
48 const initialUrl = forDevice(props.url);
49 const environmentLabel =
50 useEnvironments().presentationById.get(environmentId)?.entry.target.label ??
51 gt({ context: "stands in for an environment name in a sentence" })`the environment`;
52 const { themeVariables } = useAppearancePreferences();
53 const tunnelOff = useEnvironmentPreviewTunnelOff(environmentId);
54 const webView = useRef<TunnelWebViewRef>(null);
55 const [requested, setRequested] = useState(initialUrl);
56 const [page, setPage] = useState<TunnelNavigation | null>(null);
57 const [failed, setFailed] = useState(false);
58 const [disconnected, setDisconnected] = useState(false);
59 const [outdated, setOutdated] = useState(false);
60 const [debug, setDebug] = useState<string | undefined>(undefined);
61 const [unsupported, setUnsupported] = useState<string | null>(null);
62 // After a failed load the webview reports no URL, so the address stays on the one asked for.
63 const current = (!failed && page?.url) || requested;
64
65 const open = (value: string) => {
66 const normalized = normalizedOrNull(value);
67 const next = normalized === null ? null : forDevice(normalized);
68 if (next === null) {
69 Dialog.alert(m(msg("Could not open this address")), m(msg("Enter an http or https URL.")));
70 return;
71 }
72 setFailed(false);
73 setRequested(next);
74 void webView.current?.loadUrl(next);
75 };
76 const retry = () => {
77 setFailed(false);
78 void webView.current?.reload();
79 };
80 const back = () => void webView.current?.goBack();
81 const canGoBack = page?.canGoBack ?? false;
82 const pageColor = failed || tunnelOff || unsupported !== null ? null : page?.pageColor || null;
83
84 return (
85 // Full screen spans the Duo's rail, so it insets its own sides; the pane is inset already.
86 <SafeAreaView
87 edges={onMaximize ? [] : ["left", "right"]}
88 style={{ flex: 1, backgroundColor: pageColor ?? themeVariables["--color-sheet-solid"] }}
89 >
90 <BrowserChrome
91 scrollsUnderBar
92 inPane={onMaximize !== undefined}
93 holdExpanded={failed}
94 bar={{
95 url: current,
96 editable: true,
97 canGoBack,
98 onClose: props.onClose,
99 onBack: back,
100 onReload: retry,
101 onSubmit: open,
102 onMaximize: onMaximize ? () => onMaximize(current) : undefined,
103 pageColor,
104 }}
105 >
106 {({ topInset, onScrollDirection }) => (
107 <>
108 <TunnelWebView
109 key={environmentId}
110 ref={webView}
111 className="flex-1"
112 environmentId={environmentId}
113 url={initialUrl}
114 topInset={topInset}
115 onNavigationChange={(next) => {
116 if (next.loading) setFailed(false);
117 setPage(next);
118 }}
119 onScrollDirection={onScrollDirection}
120 onAccess={(available) => setDisconnected(!available)}
121 onLoadError={(failure) => {
122 if (failure.unsupported) return setUnsupported(failure.description);
123 // A link to another port fails with that port's address, not the one typed earlier.
124 if (failure.url) setRequested(failure.url);
125 setDebug(failure.debug);
126 // Without a cause, a refused tunnel request reported through onAccess stands in.
127 if (failure.cause) setDisconnected(failure.cause === "environment");
128 setOutdated(failure.cause === "outdated");
129 setFailed(true);
130 }}
131 />
132 {tunnelOff ? (
133 <View
134 className="absolute inset-0 items-center justify-center"
135 style={{ backgroundColor: themeVariables["--color-sheet-solid"] }}
136 >
137 <View className="w-full max-w-md">
138 <EmptyState
139 variant="plain"
140 title={gt`${{ environment: environmentLabel }} doesn't share its localhost`}
141 detail={gt`The preview tunnel is off there, so its local servers only open in the streamed browser.`}
142 />
143 </View>
144 </View>
145 ) : unsupported !== null ? (
146 <View
147 className="absolute inset-0 items-center justify-center"
148 style={{ backgroundColor: themeVariables["--color-sheet-solid"] }}
149 >
150 <View className="w-full max-w-md">
151 <EmptyState
152 variant="plain"
153 title={gt`This device can't open localhost pages`}
154 detail={gt`${{ reason: unsupported }} You can still use the streamed browser for this tab.`}
155 />
156 </View>
157 </View>
158 ) : failed ? (
159 // Opaque, so the webview's own error page never shows through the sheet color.
160 <View
161 className="absolute inset-0 items-center justify-center"
162 style={{ backgroundColor: themeVariables["--color-sheet-solid"] }}
163 >
164 <View className="w-full max-w-md">
165 <EmptyState
166 variant="plain"
167 title={
168 outdated
169 ? gt`Update T3 Code on ${{ environment: environmentLabel }}`
170 : disconnected
171 ? gt`Not connected to ${{ environment: environmentLabel }}`
172 : gt`Can't reach ${{ host: hostOf(current) }}`
173 }
174 detail={
175 outdated
176 ? gt`${{ environment: environmentLabel }} runs a version of T3 Code that can't open its localhost pages on this device. Update it there, then try again.`
177 : disconnected
178 ? gt`Pages on ${{ environment: environmentLabel }}’s localhost load through its connection. Try again once it reconnects.`
179 : gt`Nothing is listening on port ${{ port: portOf(current) }} on ${{ environment: environmentLabel }}. Start the server there, then try again.`
180 }
181 actionLabel={gt`Try again`}
182 onAction={retry}
183 />
184 {debug ? (
185 <AppText
186 selectable
187 className="px-6 text-center font-mono text-xs text-foreground-muted"
188 >
189 {debug}
190 </AppText>
191 ) : null}
192 </View>
193 </View>
194 ) : null}
195 </>
196 )}
197 </BrowserChrome>
198 </SafeAreaView>
199 );
200}
201
202function portOf(value: string): string {
203 try {
204 const url = new URL(value);
205 return url.port || (url.protocol === "https:" ? "443" : "80");
206 } catch {
207 return "?";
208 }
209}
210
211function hostOf(value: string): string {
212 try {
213 return new URL(value).host;
214 } catch {
215 return value;
216 }
217}
218
219// A route URL that is not a web address opens the preview empty, ready for one to be typed.
220function forDevice(url: string): string {
221 return localPreviewUrlForDevice(url) ?? "";
222}
223
224function normalizedOrNull(value: string): string | null {
225 try {
226 return normalizePreviewUrl(value);
227 } catch {
228 return null;
229 }
230}