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

__root.tsx

407 lines13.1 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 {primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
131 <RelayClientInstallDialog />
132 <ConnectOnboardingDialog />
133 <SshPasswordPromptDialog />
134 <SlowRpcRequestToastCoordinator />
135 <HostedStaticEnvironmentBootstrap />
136 {primaryEnvironmentAuthenticated ? <EventRouter /> : null}
137 {primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}
138 {appShell}
139 </AnchoredToastProvider>
140 </ToastProvider>
141 );
143​
144function DocumentTitleSync() {
145 const primaryServerVersion =
146 useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
147 const title = resolveServerBackedAppDisplayName({
148 baseName: APP_BASE_NAME,
149 fallbackDisplayName: APP_DISPLAY_NAME,
150 fallbackStageLabel: APP_STAGE_LABEL,
151 primaryServerVersion,
152 });
153​
154 useEffect(() => {
155 document.title = title;
156 }, [title]);
157​
158 return null;
160​
161function HostedStaticEnvironmentBootstrap() {
162 const { environments } = useEnvironments();
163 const activeEnvironmentId = useActiveEnvironmentId();
164​
165 useEffect(() => {
166 if (
167 environments.some(
168 (environment) => environment.entry.target._tag === "PrimaryConnectionTarget",
169 )
170 ) {
171 return;
172 }
173​
174 if (activeEnvironmentId) {
175 return;
176 }
177​
178 const firstSavedEnvironment = environments[0];
179 if (!firstSavedEnvironment) {
180 return;
181 }
182​
183 setActiveEnvironmentId(firstSavedEnvironment.environmentId);
184 }, [activeEnvironmentId, environments]);
185​
186 return null;
188​
189function RootRouteErrorView({ error, reset }: ErrorComponentProps) {
190 const message = errorMessage(error);
191 const details = errorDetails(error);
192​
193 return (
194 <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
195 <div className="pointer-events-none absolute inset-0 opacity-80">
196 <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)]" />
197 <div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_90%,var(--color-black))_0%,var(--background)_55%)]" />
198 </div>
199​
200 <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">
201 <p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
202 {APP_DISPLAY_NAME}
203 </p>
204 <h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">
205 Something went wrong.
206 </h1>
207 <p className="mt-2 text-sm leading-relaxed text-muted-foreground">{message}</p>
208​
209 <div className="mt-5 flex flex-wrap gap-2">
210 <Button size="sm" onClick={() => reset()}>
211 Try again
212 </Button>
213 <Button size="sm" variant="outline" onClick={() => window.location.reload()}>
214 Reload app
215 </Button>
216 </div>
217​
218 <details className="group mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">
219 <summary className="cursor-pointer list-none px-3 py-2 text-xs font-medium text-muted-foreground">
220 <span className="group-open:hidden">Show error details</span>
221 <span className="hidden group-open:inline">Hide error details</span>
222 </summary>
223 <pre className="max-h-56 overflow-auto border-t border-border/70 bg-background/80 px-3 py-2 text-xs text-foreground/85">
224 {details}
225 </pre>
226 </details>
227 </section>
228 </div>
229 );
231​
232function errorMessage(error: unknown): string {
233 if (error instanceof Error && error.message.trim().length > 0) {
234 return error.message;
235 }
236​
237 if (typeof error === "string" && error.trim().length > 0) {
238 return error;
239 }
240​
241 return "An unexpected router error occurred.";
243​
244function errorDetails(error: unknown): string {
245 if (error instanceof Error) {
246 return error.stack ?? error.message;
247 }
248​
249 if (typeof error === "string") {
250 return error;
251 }
252​
253 try {
254 return JSON.stringify(error, null, 2);
255 } catch {
256 return "No additional error details are available.";
257 }
259​
260function AuthenticatedTracingBootstrap() {
261 useEffect(() => {
262 void configureClientTracing();
263 }, []);
264​
265 return null;
267​
268function EventRouter() {
269 const navigate = useNavigate();
270 const pathname = useLocation({ select: (loc) => loc.pathname });
271 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
272 const primaryEnvironment = usePrimaryEnvironment();
273 const openInEditor = useAtomCommand(shellEnvironment.openInEditor, {
274 reportFailure: false,
275 });
276 const serverConfig = useAtomValue(primaryServerConfigAtom);
277 const serverConfigEvent = useAtomValue(primaryServerConfigEventAtom);
278 const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
279 const readPathname = useEffectEvent(() => pathname);
280 const handledBootstrapThreadIdRef = useRef<string | null>(null);
281 const handledConfigEventRef = useRef(serverConfigEvent);
282 const [keybindingsToastController] = useState<KeybindingsUpdateToastController>(() =>
283 createKeybindingsUpdateToastController({}),
284 );
285​
286 const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
287 if (!payload) return;
288​
289 setActiveEnvironmentId(payload.environment.environmentId);
290 void (async () => {
291 if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
292 return;
293 }
294 const bootstrapProject = readProject(
295 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
296 );
297 const bootstrapProjectKey =
298 (bootstrapProject
299 ? deriveLogicalProjectKeyFromSettings(bootstrapProject, projectGroupingSettings)
300 : null) ??
301 (serverConfig?.cwd
302 ? derivePhysicalProjectKeyFromPath(payload.environment.environmentId, serverConfig.cwd)
303 : null) ??
304 scopedProjectKey(
305 scopeProjectRef(payload.environment.environmentId, payload.bootstrapProjectId),
306 );
307 useUiStateStore.getState().setProjectExpanded(bootstrapProjectKey, true);
308​
309 if (readPathname() !== "/") {
310 return;
311 }
312 if (handledBootstrapThreadIdRef.current === payload.bootstrapThreadId) {
313 return;
314 }
315 await navigate({
316 to: "/$environmentId/$threadId",
317 params: {
318 environmentId: payload.environment.environmentId,
319 threadId: payload.bootstrapThreadId,
320 },
321 replace: true,
322 });
323 handledBootstrapThreadIdRef.current = payload.bootstrapThreadId;
324 })().catch(() => undefined);
325 });
326​
327 const handleServerConfigUpdated = useEffectEvent(() => {
328 const decision = keybindingsToastController.handle(serverConfigEvent);
329 if (!decision) {
330 return;
331 }
332​
333 if (decision._tag === "Success") {
334 toastManager.add({
335 type: "success",
336 title: "Keybindings updated",
337 description: "Keybindings configuration reloaded successfully.",
338 });
339 return;
340 }
341​
342 toastManager.add(
343 stackedThreadToast({
344 type: "warning",
345 title: "Invalid keybindings configuration",
346 description: decision.message,
347 actionVariant: "outline",
348 actionProps: {
349 children: "Open keybindings.json",
350 onClick: () => {
351 if (!serverConfig || !primaryEnvironment) {
352 return;
353 }
354​
355 const editor = resolveAndPersistPreferredEditor(serverConfig.availableEditors);
356 if (!editor) {
357 return;
358 }
359 void (async () => {
360 const result = await openInEditor({
361 environmentId: primaryEnvironment.environmentId,
362 input: {
363 cwd: serverConfig.keybindingsConfigPath,
364 editor,
365 },
366 });
367 if (result._tag === "Success") {
368 return;
369 }
370 const error = squashAtomCommandFailure(result);
371 toastManager.add(
372 stackedThreadToast({
373 type: "error",
374 title: "Unable to open keybindings file",
375 description:
376 error instanceof Error ? error.message : "Unknown error opening file.",
377 }),
378 );
379 })();
380 },
381 },
382 }),
383 );
384 });
385​
386 useEffect(() => {
387 if (!serverConfig) {
388 return;
389 }
390​
391 setActiveEnvironmentId(serverConfig.environment.environmentId);
392 }, [serverConfig]);
393​
394 useEffect(() => {
395 handleWelcome(serverWelcome);
396 }, [serverWelcome]);
397​
398 useEffect(() => {
399 if (serverConfigEvent === null || handledConfigEventRef.current === serverConfigEvent) {
400 return;
401 }
402 handledConfigEventRef.current = serverConfigEvent;
403 handleServerConfigUpdated();
404 }, [serverConfigEvent]);
405​
406 return null;