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

LocalPreviewRouteScreen.tsx

245 lines9.5 KB

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 { loopbackUrlForDevice } 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 );
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("the environment", { $context: "stands in for an environment name in a sentence" });
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} doesn't share its localhost", {
141 environment: environmentLabel,
142 })}
143 detail={gt(
144 "The preview tunnel is off there, so its local servers only open in the streamed browser.",
145 )}
146 />
147 </View>
148 </View>
149 ) : unsupported !== null ? (
150 <View
151 className="absolute inset-0 items-center justify-center"
152 style={{ backgroundColor: themeVariables["--color-sheet-solid"] }}
153 >
154 <View className="w-full max-w-md">
155 <EmptyState
156 variant="plain"
157 title={gt("This device can't open localhost pages")}
158 detail={gt("{reason} You can still use the streamed browser for this tab.", {
159 reason: unsupported,
160 })}
161 />
162 </View>
163 </View>
164 ) : failed ? (
165 // Opaque, so the webview's own error page never shows through the sheet color.
166 <View
167 className="absolute inset-0 items-center justify-center"
168 style={{ backgroundColor: themeVariables["--color-sheet-solid"] }}
169 >
170 <View className="w-full max-w-md">
171 <EmptyState
172 variant="plain"
173 title={
174 outdated
175 ? gt("Update T3 Code on {environment}", { environment: environmentLabel })
176 : disconnected
177 ? gt("Not connected to {environment}", { environment: environmentLabel })
178 : gt("Can't reach {host}", { host: hostOf(current) })
179 }
180 detail={
181 outdated
182 ? gt(
183 "{environment} runs a version of T3 Code that can't open its localhost pages on this device. Update it there, then try again.",
184 { environment: environmentLabel },
185 )
186 : disconnected
187 ? gt(
188 "Pages on {environment}’s localhost load through its connection. Try again once it reconnects.",
189 { environment: environmentLabel },
190 )
191 : gt(
192 "Nothing is listening on port {port} on {environment}. Start the server there, then try again.",
193 { port: portOf(current), environment: environmentLabel },
194 )
195 }
196 actionLabel={gt("Try again")}
197 onAction={retry}
198 />
199 {debug ? (
200 <AppText
201 selectable
202 className="px-6 text-center font-mono text-xs text-foreground-muted"
203 >
204 {debug}
205 </AppText>
206 ) : null}
207 </View>
208 </View>
209 ) : null}
210 </>
211 )}
212 </BrowserChrome>
213 </SafeAreaView>
214 );
216​
217function portOf(value: string): string {
218 try {
219 const url = new URL(value);
220 return url.port || (url.protocol === "https:" ? "443" : "80");
221 } catch {
222 return "?";
223 }
225​
226function hostOf(value: string): string {
227 try {
228 return new URL(value).host;
229 } catch {
230 return value;
231 }
233​
234// The unspecified address would name the phone itself, so it becomes the environment's localhost.
235function forDevice(url: string): string {
236 return loopbackUrlForDevice(url) ?? url;
238​
239function normalizedOrNull(value: string): string | null {
240 try {
241 return normalizePreviewUrl(value);
242 } catch {
243 return null;
244 }