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

__root.tsx

418 lines13.4 KB

1import { type ServerLifecycleWelcomePayload } from "@t3tools/contracts";
2import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
3import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
4import {
5 Outlet,
6 createRootRoute,
7 type ErrorComponentProps,
8 useLocation,
9 useNavigate,
10} from "@tanstack/react-router";
11import { useEffect, useEffectEvent, useRef, useState } from "react";
12​
13import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "../branding";
14import { resolveServerBackedAppDisplayName } from "../branding.logic";
15import { AppSidebarLayout } from "../components/AppSidebarLayout";
16import { CommandPalette } from "../components/CommandPalette";
17import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog";
18import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog";
19import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";
20import { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";
21import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";
22import { Button } from "../components/ui/button";
23import {
24 AnchoredToastProvider,
25 stackedThreadToast,
26 ToastProvider,
27 toastManager,
28} from "../components/ui/toast";
29import { resolveAndPersistPreferredEditor } from "../editorPreferences";
30import { useClientSettings } from "../hooks/useSettings";
31import {
32 deriveLogicalProjectKeyFromSettings,
33 derivePhysicalProjectKeyFromPath,
34 selectProjectGroupingSettings,
35} from "../logicalProject";
36import { useUiStateStore } from "../uiStateStore";
37import { syncBrowserChromeTheme } from "../hooks/useTheme";
38import { configureClientTracing } from "../observability/clientTracing";
39import { resolveInitialServerAuthGateState } from "../environments/primary";
40import { hasHostedPairingRequest, isHostedStaticApp } from "../hostedPairing";
41import { shellEnvironment } from "../state/shell";
42import { useAtomValue } from "@effect/atom-react";
43import { useAtomCommand } from "../state/use-atom-command";
44import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
45import {
46 primaryServerConfigAtom,
47 primaryServerConfigEventAtom,
48 primaryServerWelcomeAtom,
49} from "../state/server";
50import { readProject, setActiveEnvironmentId, useActiveEnvironmentId } from "../state/entities";
51import {
52 createKeybindingsUpdateToastController,
53 type KeybindingsUpdateToastController,
54} from "../components/KeybindingsUpdateToast.logic";
55​
56export const Route = createRootRoute({
57 beforeLoad: async ({ location }) => {
58 if (location.pathname === "/pair" && hasHostedPairingRequest(new URL(window.location.href))) {
59 return {
60 authGateState: {
61 status: "hosted-pairing",
62 } as const,
63 };
64 }
65​
66 if (isHostedStaticApp(new URL(window.location.href))) {
67 return {
68 authGateState: {
69 status: "hosted-static",
70 } as const,
71 };
72 }
73​
74 const authGateState = await resolveInitialServerAuthGateState();
75 return {
76 authGateState,
77 };
78 },
79 component: RootRouteView,
80 errorComponent: RootRouteErrorView,
81 head: () => ({
82 meta: [{ name: "title", content: APP_DISPLAY_NAME }],
83 }),
84});
85​
86function RootRouteView() {
87 const pathname = useLocation({ select: (location) => location.pathname });
88 const { authGateState } = Route.useRouteContext();
89 const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";
90​
91 useEffect(() => {
92 const frame = window.requestAnimationFrame(() => {
93 syncBrowserChromeTheme();
94 });
95 return () => {
96 window.cancelAnimationFrame(frame);
97 };
98 }, [pathname]);
99​
100 if (pathname === "/pair" || pathname === "/connect" || pathname.startsWith("/connect/")) {
101 return (
102 <>
103 <DocumentTitleSync />
104 <Outlet />
105 </>
106 );
107 }
108​
109 if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") {
110 return (
111 <>
112 <DocumentTitleSync />
113 <Outlet />
114 </>
115 );
116 }
117​
118 const appShell = (
119 <CommandPalette>
120 <AppSidebarLayout>
121 <Outlet />
122 </AppSidebarLayout>
123 </CommandPalette>
124 );
125​
126 return (
127 <ToastProvider>
128 <AnchoredToastProvider>
129 <DocumentTitleSync />
130 <GlassAppearanceSync />
131 {primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
132 <RelayClientInstallDialog />
133 <ConnectOnboardingDialog />
134 <SshPasswordPromptDialog />
135 <SlowRpcRequestToastCoordinator />
136 <HostedStaticEnvironmentBootstrap />
137 {primaryEnvironmentAuthenticated ? <EventRouter /> : null}
138 {primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
139 {appShell}
140 </AnchoredToastProvider>
141 </ToastProvider>
142 );
144​
145function GlassAppearanceSync() {
146 const glassOpacity = useClientSettings((settings) => settings.glassOpacity);
147​
148 useEffect(() => {
149 document.documentElement.style.setProperty("--glass-opacity", `${glassOpacity}%`);
150 }, [glassOpacity]);
151​
152 return null;
154​
155function DocumentTitleSync() {
156 const primaryServerVersion =
157 useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
158 const title = resolveServerBackedAppDisplayName({
159 baseName: APP_BASE_NAME,
160 fallbackDisplayName: APP_DISPLAY_NAME,
161 fallbackStageLabel: APP_STAGE_LABEL,
162 primaryServerVersion,
163 });
164​
165 useEffect(() => {
166 document.title = title;
167 }, [title]);
168​
169 return null;
171​
172function HostedStaticEnvironmentBootstrap() {
173 const { environments } = useEnvironments();
174 const activeEnvironmentId = useActiveEnvironmentId();
175​
176 useEffect(() => {
177 if (
178 environments.some(
179 (environment) => environment.entry.target._tag === "PrimaryConnectionTarget",
180 )
181 ) {
182 return;
183 }
184​
185 if (activeEnvironmentId) {
186 return;
187 }
188​
189 const firstSavedEnvironment = environments[0];
190 if (!firstSavedEnvironment) {
191 return;
192 }
193​
194 setActiveEnvironmentId(firstSavedEnvironment.environmentId);
195 }, [activeEnvironmentId, environments]);
196​
197 return null;
199​
200function RootRouteErrorView({ error, reset }: ErrorComponentProps) {
201 const message = errorMessage(error);
202 const details = errorDetails(error);
203​
204 return (
205 <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
206 <div className="pointer-events-none absolute inset-0 opacity-80">
207 <div className="absolute inset-x-0 top-0 h-44 bg-[radial-gradient(44rem_16rem_at_top,color-mix(in_srgb,var(--color-red-500)_16%,transparent),transparent)]" />
208 <div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_90%,var(--color-black))_0%,var(--background)_55%)]" />
209 </div>
210​
211 <section className="relative w-full max-w-xl rounded-2xl border border-border/80 bg-card/90 p-6 shadow-2xl shadow-black/20 backdrop-blur-md sm:p-8">
212 <p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
213 {APP_DISPLAY_NAME}
214 </p>
215 <h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">
216 Something went wrong.
217 </h1>
218 <p className="mt-2 text-sm leading-relaxed text-muted-foreground">{message}</p>
219​
220 <div className="mt-5 flex flex-wrap gap-2">
221 <Button size="sm" onClick={() => reset()}>
222 Try again
223 </Button>
224 <Button size="sm" variant="outline" onClick={() => window.location.reload()}>
225 Reload app
226 </Button>
227 </div>
228​
229 <details className="group mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
230 <summary className="cursor-pointer list-none px-3 py-2 text-xs font-medium text-muted-foreground">
231 <span className="group-open:hidden">Show error details</span>
232 <span className="hidden group-open:inline">Hide error details</span>
233 </summary>
234 <pre className="max-h-56 overflow-auto border-t border-border/70 bg-background/80 px-3 py-2 text-xs text-foreground/85">
235 {details}
236 </pre>
237 </details>
238 </section>
239 </div>
240 );
242​
243function errorMessage(error: unknown): string {
244 if (error instanceof Error && error.message.trim().length > 0) {
245 return error.message;
246 }
247​
248 if (typeof error === "string" && error.trim().length > 0) {
249 return error;
250 }
251​
252 return "An unexpected router error occurred.";
254​
255function errorDetails(error: unknown): string {
256 if (error instanceof Error) {
257 return error.stack ?? error.message;
258 }
259​
260 if (typeof error === "string") {
261 return error;
262 }
263​
264 try {
265 return JSON.stringify(error, null, 2);
266 } catch {
267 return "No additional error details are available.";
268 }
270​
271function AuthenticatedTracingBootstrap() {
272 useEffect(() => {
273 void configureClientTracing();
274 }, []);
275​
276 return null;
278​
279function EventRouter() {
280 const navigate = useNavigate();
281 const pathname = useLocation({ select: (loc) => loc.pathname });
282 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
283 const primaryEnvironment = usePrimaryEnvironment();
284 const openInEditor = useAtomCommand(shellEnvironment.openInEditor, {
285 reportFailure: false,
286 });
287 const serverConfig = useAtomValue(primaryServerConfigAtom);
288 const serverConfigEvent = useAtomValue(primaryServerConfigEventAtom);
289 const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
290 const readPathname = useEffectEvent(() => pathname);
291 const handledBootstrapThreadIdRef = useRef<string | null>(null);
292 const handledConfigEventRef = useRef(serverConfigEvent);
293 const [keybindingsToastController] = useState<KeybindingsUpdateToastController>(() =>
294 createKeybindingsUpdateToastController({}),
295 );
296​
297 const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
298 if (!payload) return;
299​
300 setActiveEnvironmentId(payload.environment.environmentId);
301 void (async () => {
302 if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
303 return;
304 }
305 const bootstrapProject = readProject(
306 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
307 );
308 const bootstrapProjectKey =
309 (bootstrapProject
310 ? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
311 : null) ??
312 (serverConfig?.cwd
313 ? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
314 : null) ??
315 scopedProjectKey(
316 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
317 );
318 useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
319​
320 if (readPathname() !== "/") {
321 return;
322 }
323 if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
324 return;
325 }
326 await navigate({
327 to: "/$environmentId/$threadId",
328 params: {
329 environmentId: payload.environment.environmentId,
330 threadId: payload.bootstrapThreadId,
331 },
332 replace: true,
333 });
334 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
335 })().catch(() => undefined);
336 });
337​
338 const handleServerConfigUpdated = useEffectEvent(() => {
339 const decision = keybindingsToastController.handle(serverConfigEvent);
340 if (!decision) {
341 return;
342 }
343​
344 if (decision._tag === "Success") {
345 toastManager.add({
346 type: "success",
347 title: "Keybindings updated",
348 description: "Keybindings configuration reloaded successfully.",
349 });
350 return;
351 }
352​
353 toastManager.add(
354 stackedThreadToast({
355 type: "warning",
356 title: "Invalid keybindings configuration",
357 description: decision.message,
358 actionVariant: "outline",
359 actionProps: {
360 children: "Open keybindings.json",
361 onClick: () => {
362 if (!serverConfig || !primaryEnvironment) {
363 return;
364 }
365​
366 const editor = resolveAndPersistPreferredEditor(serverConfig.availableEditors);
367 if (!editor) {
368 return;
369 }
370 void (async () => {
371 const result = await openInEditor({
372 environmentId: primaryEnvironment.environmentId,
373 input: {
374 cwd: serverConfig.keybindingsConfigPath,
375 editor,
376 },
377 });
378 if (result._tag === "Success") {
379 return;
380 }
381 const error = squashAtomCommandFailure(result);
382 toastManager.add(
383 stackedThreadToast({
384 type: "error",
385 title: "Unable to open keybindings file",
386 description:
387 error instanceof Error ? error.message : "Unknown error opening file.",
388 }),
389 );
390 })();
391 },
392 },
393 }),
394 );
395 });
396​
397 useEffect(() => {
398 if (!serverConfig) {
399 return;
400 }
401​
402 setActiveEnvironmentId(serverConfig.environment.environmentId);
403 }, [serverConfig]);
404​
405 useEffect(() => {
406 handleWelcome(serverWelcome);
407 }, [serverWelcome]);
408​
409 useEffect(() => {
410 if (serverConfigEvent === null || handledConfigEventRef.current === serverConfigEvent) {
411 return;
412 }
413 handledConfigEventRef.current = serverConfigEvent;
414 handleServerConfigUpdated();
415 }, [serverConfigEvent]);
416​
417 return null;