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

__root.tsx

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