Skip to content
711 linesCodeBlameRaw
1import {
2 BookOpen,
3 ChevronDown,
4 Compass,
5 CreditCard,
6 LayoutDashboard,
7 LogIn,
8 LogOut,
9 Menu,
10 Plus,
11 Search,
12 Settings,
13} from "lucide-react";
14import { useEffect, useRef, useState } from "react";
15import {
16 Form,
17 isRouteErrorResponse,
18 Link,
19 Links,
20 Meta,
21 NavLink,
22 Outlet,
23 Scripts,
24 ScrollRestoration,
25 type ShouldRevalidateFunctionArgs,
26 useLocation,
27 useMatches,
28 useParams,
29 useRouteError,
30 useRouteLoaderData,
31 useSubmit,
32} from "react-router";
33
34import { type User, awaitsConfirmation, hasAccessIn, sharedWorkspaces } from "@g1t/contracts";
35
36import type { Route } from "./+types/root";
37import appCss from "./app.css?url";
38import displayFont from "@g1t/theme/fonts/bricolage-grotesque-latin.woff2?url";
39import sansFont from "@g1t/theme/fonts/hanken-grotesk-latin.woff2?url";
40import { Logo } from "./components/logo";
41import { Avatar, ButtonLink, SubmitButton, notACredential } from "./components/ui";
42import {
43 DropdownMenu,
44 DropdownMenuContent,
45 DropdownMenuItem,
46 DropdownMenuLabel,
47 DropdownMenuSeparator,
48 DropdownMenuTrigger,
49} from "./components/ui/dropdown-menu";
50import { AppShell, Progress, type ShellData, useLeaving } from "./components/shell";
51import { SiteFooter } from "./components/footer";
52import { SpikeBanner } from "./components/spike-banner";
53import { PolicyNotice } from "./components/policy-notice";
54import { identify } from "./lib/analytics.client";
55import { readCookie } from "./lib/mission";
56import { WORKSPACE_COOKIE, workspaceFor } from "./lib/workspace-choice";
57import { PageMain } from "./components/landmark";
58import { NotFound } from "./components/not-found";
59import { usesAppShell } from "./lib/chrome";
60import { CommandPalette, type PaletteCommand, PaletteKey, usePaletteShortcut } from "./components/command-palette";
61import { billing, chat, inbox, projects, workspaceAgents } from "./lib/services.server";
62import { unreadTotals } from "./lib/chat";
63import { countsFor, readableRepos } from "./lib/access.server";
64import { shortCache } from "./lib/cache.server";
65import { getViewer, viewerMiddleware } from "./lib/session.server";
66import { shortcutOf, workspaceProjects } from "./lib/workspace-projects.server";
67import { registrationMode } from "./lib/registration.server";
68import { addresses } from "./lib/addresses.server";
69import { useSignUpCopy } from "./lib/registration";
70import { RELOADED_KEY, reloadFixes } from "./lib/stale-build";
71import { useNonce } from "./lib/nonce";
72import { LiveNotifications } from "./components/notifications/live-notifications";
73
74
75export const links: Route.LinksFunction = () => [
76 { rel: "icon", href: "/favicon.ico", sizes: "32x32" },
77 { rel: "icon", type: "image/svg+xml", href: "/favicon.svg" },
78 { rel: "icon", type: "image/png", sizes: "192x192", href: "/icon-192.png" },
79 { rel: "apple-touch-icon", href: "/apple-touch-icon.png" },
80 // Installable: name, icons and colours for "Add to Home Screen" (public/manifest.webmanifest).
81 { rel: "manifest", href: "/manifest.webmanifest" },
82 // The text and headline faces are wanted on every page, so they start
83 // loading with the stylesheet; mono waits until something uses it.
84 { rel: "preload", href: sansFont, as: "font", type: "font/woff2", crossOrigin: "anonymous" },
85 { rel: "preload", href: displayFont, as: "font", type: "font/woff2", crossOrigin: "anonymous" },
86];
87
88export const middleware: Route.MiddlewareFunction[] = [viewerMiddleware];
89
90export async function loader({ context, params, request }: Route.LoaderArgs) {
91 const user = getViewer(context);
92 const chosen = readCookie(request.headers.get("cookie"), WORKSPACE_COOKIE);
93 // Whether sign-up takes an invite: the sign-up page says so, and
94 // Settings → Invites offers invites to g1t only then. Cached per isolate.
95 const [shell, mode] = await Promise.all([
96 // An account still confirming its address sees only the pages that
97 // allows (lib/confirm-gate.ts), in the visitor's frame.
98 user && !awaitsConfirmation(user)
99 ? shellFor(user, params, chosen, context).catch((error: unknown) => {
100 // A sidebar that could not be read is no reason to lose the page,
101 // or to draw it as if they were signed out.
102 console.error("root: the sidebar could not be read", error);
103 return bareShell(user, params, chosen);
104 })
105 : visitorShell(params, context),
106 registrationMode(),
107 ]);
108 // Where this g1t lives, for clone lines, agent setup and link previews.
109 return { user, shell, inviteOnly: mode !== "open", addresses: addresses() };
110}
111
112/**
113 * The sidebar for someone not signed in: nothing of their own, only the
114 * open counts of the project being looked at. One call, and only in a
115 * project; it answers the same for a private project as a missing one.
116 */
117async function visitorShell(params: { owner?: string; repo?: string }, context: Route.LoaderArgs["context"]): Promise<ShellData> {
118 const path = params.owner && params.repo ? { namespace: params.owner, name: params.repo } : null;
119 const counts = path ? await countsFor(context, params) : null;
120 return {
121 workspace: null,
122 repos: [],
123 repo: path && counts?.ok ? { ...path, member: false, issues: counts.value.issues, pulls: counts.value.pulls } : null,
124 limit: null,
125 monthUsageMicros: null,
126 };
127}
128
129/** The sidebar from what the session already says, with no service asked. */
130function bareShell(user: User, params: { owner?: string; repo?: string }, chosen: string | null): ShellData {
131 return {
132 workspace: workspaceFor(user.workspaces ?? [], chosen, params),
133 repos: [],
134 repo: null,
135 limit: null,
136 monthUsageMicros: null,
137 };
138}
139
140/**
141 * The sidebar only changes with the workspace or repository being looked
142 * at, or after something was submitted: not on every page within them.
143 */
144export function shouldRevalidate({
145 currentParams,
146 nextParams,
147 formMethod,
148 defaultShouldRevalidate,
149}: ShouldRevalidateFunctionArgs) {
150 if (formMethod && formMethod !== "GET") return defaultShouldRevalidate;
151 return currentParams.owner !== nextParams.owner || currentParams.repo !== nextParams.repo;
152}
153
154/**
155 * The sidebar: the workspace whose pages or project these are when it is
156 * one of yours, else the one you chose (lib/workspace-choice.ts); its
157 * projects; and the repository being looked at.
158 */
159async function shellFor(
160 user: User,
161 params: { owner?: string; repo?: string },
162 chosen: string | null,
163 context: Route.LoaderArgs["context"],
164): Promise<ShellData> {
165 const memberships = user.workspaces ?? [];
166 const workspace = workspaceFor(memberships, chosen, params);
167 const path = params.owner && params.repo ? { namespace: params.owner, name: params.repo } : null;
168 const now = new Date();
169 const monthStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString();
170 // What the sidebar shows of the workspace changes rarely: kept for a few
171 // seconds per person and workspace, except just after they changed
172 // something (lib/cache.server.ts).
173 const kept = <T,>(what: string, load: () => Promise<T>) =>
174 workspace ? shortCache(`shell:${what}:${user.id}:${workspace.slug}`, SHELL_TTL_MS, load) : Promise.resolve(null);
175 const [listed, counts, status, usage, limit, entitlements, shared, unread, shortcuts, chatUnread, teamAgents] = await Promise.all([
176 // Every project, for the palette and the count; the sidebar lists only
177 // the person's pinned and recent ones (lib/pins.ts).
178 workspace ? workspaceProjects(workspace.slug, user) : Promise.resolve(null),
179 path ? countsFor(context, params) : Promise.resolve(null),
180 // Whether billing is on, without reading the account: that asks the
181 // card processor about the workspace's cards, too slow for every page.
182 kept("status", () => billing.status()).catch(() => null),
183 kept(`usage:${monthStart}`, () => billing.usage(workspace!.slug, user, monthStart)).catch(() => null),
184 kept("limit", () => billing.limit(workspace!.slug, user)).catch(() => null),
185 kept("entitlements", () => billing.entitlements(workspace!.slug)).catch(() => null),
186 sharedRepos(user),
187 // The bell's count: one query, never kept, so marking an item shows at once.
188 inbox.counts(user.username).catch(() => null),
189 // Never kept: opening a project moves it up Recent.
190 workspace ? projects.shortcuts(workspace.slug, user).catch(() => null) : Promise.resolve(null),
191 // The rail's Chat badge: never kept, and never waited on for long.
192 workspace ? chatUnreadFor(workspace.slug, user) : Promise.resolve(null),
193 // Home's Recent and the Agents sidebar, on every page: never waited on for long.
194 workspace ? agentsFor(workspace.slug, user) : Promise.resolve(null),
195 ]);
196 return {
197 workspace,
198 // Projects are what the sidebar lists: what the workspace builds and runs.
199 repos: listed?.ok ? listed.value.map(shortcutOf) : [],
200 pinned: (shortcuts?.pinned ?? []).map(shortcutOf),
201 recent: (shortcuts?.recent ?? []).map(shortcutOf),
202 repo:
203 path && counts?.ok
204 ? {
205 ...path,
206 // Until the repository's own page says what their role is.
207 member: hasAccessIn(user, path.namespace),
208 issues: counts.value.issues,
209 pulls: counts.value.pulls,
210 }
211 : null,
212 // Where the workspace stands against its usage limit, once billing is on.
213 limit:
214 status?.enabled && limit?.ok
215 ? {
216 exposureMicros: limit.value.exposureMicros,
217 ceilingMicros: limit.value.ceilingMicros,
218 state: limit.value.state,
219 comped: limit.value.trust === "internal",
220 }
221 : null,
222 free: Boolean(status?.free),
223 // A spend spike or a hold pauses new compute: the shell says so on every page.
224 compute:
225 workspace && entitlements && (entitlements.paused || entitlements.spike?.status === "open")
226 ? { paused: entitlements.paused, spike: entitlements.spike ?? null, owner: workspace.role === "owner" }
227 : null,
228 shared,
229 inbox: unread,
230 chat: chatUnread,
231 agents: teamAgents,
232 // While g1t is free every charge is zero, so usage is shown at cost.
233 // Usage at price, the one figure every page shows.
234 monthUsageMicros: usage?.ok ? (usage.value.free ? usage.value.usedMicros : (usage.value.priceMicros ?? usage.value.spentMicros)) : null,
235 };
236}
237
238/** Starred and recent conversations Home's sidebar lists. */
239const SHELL_CONVERSATIONS = 8;
240
241/**
242 * What is unread in chat, for the rail, and the starred and latest
243 * conversations, for Home's sidebar; null when chat is slow to answer or
244 * does not.
245 */
246async function chatUnreadFor(slug: string, user: User): Promise<ShellData["chat"]> {
247 const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), CHAT_BADGE_WAIT_MS));
248 const read = chat
249 .sidebar(slug, user)
250 .then((result) => {
251 if (!result.ok) return null;
252 const entries = result.value.entries;
253 const latest = [...entries].sort((a, b) => (b.channel.last_message_at ?? "").localeCompare(a.channel.last_message_at ?? ""));
254 return {
255 ...unreadTotals(entries),
256 starred: entries.filter((e) => e.starred).slice(0, SHELL_CONVERSATIONS),
257 recent: latest.slice(0, SHELL_CONVERSATIONS),
258 };
259 })
260 .catch(() => null);
261 return Promise.race([read, timeout]);
262}
263
264/** The workspace's agents, as the shell lists them; null when the agents service is slow or down. */
265async function agentsFor(slug: string, user: User): Promise<ShellData["agents"]> {
266 const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), CHAT_BADGE_WAIT_MS));
267 const read = workspaceAgents
268 .list(slug, user)
269 .then((result) =>
270 result.ok
271 ? result.value
272 .filter((agent) => !agent.archived_at)
273 .map((agent) => ({
274 id: agent.id,
275 handle: agent.handle,
276 display_name: agent.display_name,
277 avatar: agent.avatar,
278 avatar_seed: agent.avatar_seed,
279 role: agent.role,
280 title: agent.title,
281 team: agent.team,
282 department: agent.department,
283 status: agent.status,
284 builtin: agent.builtin === true,
285 }))
286 : null,
287 )
288 .catch(() => null);
289 return Promise.race([read, timeout]);
290}
291
292/** The longest the rail's Chat badge holds up a page. */
293const CHAT_BADGE_WAIT_MS = 300;
294
295/**
296 * How long the sidebar's workspace answers are kept: as long as someone's
297 * own changes read fresh anyway (lib/perf.ts `PRIMARY_WINDOW_SECONDS`).
298 */
299const SHELL_TTL_MS = 30_000;
300
301/** Most repositories listed under Shared with you. */
302const MAX_SHARED = 20;
303
304/**
305 * Repositories shared with the user in workspaces they do not belong to,
306 * by their grants: only those, never the workspace's other repositories.
307 */
308async function sharedRepos(user: User): Promise<ShellData["shared"]> {
309 const outside = new Set(sharedWorkspaces(user));
310 if (outside.size === 0) return [];
311 const ids = (user.grants ?? []).filter((grant) => outside.has(grant.workspace)).map((grant) => grant.repo_id).slice(0, MAX_SHARED);
312 const found = await readableRepos(ids, user);
313 return found
314 .map((repo) => ({ namespace: repo.namespace, name: repo.name, isPrivate: repo.isPrivate }))
315 .sort((a, b) => `${a.namespace}/${a.name}`.localeCompare(`${b.namespace}/${b.name}`));
316}
317
318function HeaderLink({ to, children }: { to: string; children: React.ReactNode }) {
319 return (
320 <NavLink
321 to={to}
322 className={({ isActive }) =>
323 `rounded-md px-2.5 py-1.5 text-sm transition-colors hover:bg-raised hover:text-fg ${
324 isActive ? "text-fg" : "text-muted"
325 }`
326 }
327 >
328 {children}
329 </NavLink>
330 );
331}
332
333/** What the palette offers someone without the app's sidebar. */
334const PUBLIC_COMMANDS: PaletteCommand[] = [
335 { label: "Explore", hint: "Public projects", to: "/explore", icon: <Compass size={15} /> },
336 { label: "Search g1t", hint: "Repositories, code, issues, people", to: "/search", icon: <Search size={15} /> },
337 { label: "Pricing", to: "/pricing", icon: <CreditCard size={15} /> },
338 { label: "Documentation", to: "https://docs.g1t.sh/", icon: <BookOpen size={15} /> },
339 { label: "Sign in", to: "/login", icon: <LogIn size={15} /> },
340 { label: "Sign up", to: "/register", icon: <Plus size={15} /> },
341];
342
343/** Sign up: the sign-up page says whether it takes an invite. */
344function SignUpButton() {
345 const copy = useSignUpCopy();
346 return <ButtonLink to="/register">{copy.primary}</ButtonLink>;
347}
348
349function Header({ user }: { user: User | null | undefined }) {
350 const submit = useSubmit();
351 const signUp = useSignUpCopy();
352 const [palette, setPalette] = useState(false);
353 usePaletteShortcut(() => setPalette((open) => !open));
354 const params = useParams();
355 const repo = params.owner && params.repo ? `${params.owner}/${params.repo}` : null;
356 return (
357 <header className="sticky top-0 z-40 border-b border-line bg-surface/85 backdrop-blur">
358 <div className="mx-auto flex h-14 max-w-6xl items-center gap-2 px-4">
359 <Link to="/" aria-label="g1t home" className="mr-2 flex">
360 <Logo />
361 </Link>
362 <Form action="/search" role="search" className="relative hidden grow sm:block sm:max-w-xs">
363 <Search
364 size={14}
365 className="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-faint"
366 />
367 <input
368 name="q"
369 {...notACredential()}
370 placeholder="Search g1t"
371 aria-label="Search g1t"
372 className="w-full rounded-md border border-line bg-bg py-1.5 pr-12 pl-8 text-sm outline-none transition-colors placeholder:text-faint hover:border-line-strong focus:border-accent-dim"
373 />
374 <PaletteKey className="pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 rounded bg-raised px-1.5 font-mono text-[0.625rem] text-muted ring-1 ring-line" />
375 </Form>
376 <button
377 type="button"
378 aria-label="Search g1t"
379 onClick={() => setPalette(true)}
380 className="flex size-10 items-center justify-center rounded-md text-muted transition-colors hover:bg-raised hover:text-fg sm:hidden"
381 >
382 <Search size={18} />
383 </button>
384 <CommandPalette
385 open={palette}
386 onOpenChange={setPalette}
387 commands={user ? [{ label: "Home", to: "/", icon: <LayoutDashboard size={15} /> }, ...PUBLIC_COMMANDS.slice(0, 4)] : PUBLIC_COMMANDS.map((command) => (command.to === "/register" ? { ...command, label: signUp.primary } : command))}
388 repo={repo}
389 />
390 <nav aria-label="Main" className="hidden items-center gap-0.5 sm:flex">
391 <HeaderLink to="/explore">Explore</HeaderLink>
392 <HeaderLink to="/pricing">Pricing</HeaderLink>
393 <HeaderLink to="https://docs.g1t.sh/">Docs</HeaderLink>
394 </nav>
395 <div className="ml-auto flex items-center gap-2">
396 {/* On a phone the links fold into one menu, so the bar fits. */}
397 <DropdownMenu>
398 <DropdownMenuTrigger
399 aria-label="Menu"
400 className="flex size-10 items-center justify-center rounded-md text-muted outline-none transition-colors hover:bg-raised hover:text-fg focus-visible:ring-2 focus-visible:ring-accent data-[state=open]:bg-raised data-[state=open]:text-fg sm:hidden"
401 >
402 <Menu size={18} />
403 </DropdownMenuTrigger>
404 <DropdownMenuContent align="end" className="w-52">
405 <DropdownMenuItem asChild className="min-h-11">
406 <Link to="/explore">
407 <Compass />
408 Explore
409 </Link>
410 </DropdownMenuItem>
411 <DropdownMenuItem asChild className="min-h-11">
412 <Link to="/pricing">
413 <CreditCard />
414 Pricing
415 </Link>
416 </DropdownMenuItem>
417 <DropdownMenuItem asChild className="min-h-11">
418 <Link to="https://docs.g1t.sh/">
419 <BookOpen />
420 Docs
421 </Link>
422 </DropdownMenuItem>
423 {!user && (
424 <>
425 <DropdownMenuSeparator />
426 <DropdownMenuItem asChild className="min-h-11">
427 <Link to="/login">
428 <LogIn />
429 Sign in
430 </Link>
431 </DropdownMenuItem>
432 </>
433 )}
434 </DropdownMenuContent>
435 </DropdownMenu>
436 {user ? (
437 <>
438 <Link
439 to="/new"
440 aria-label="New project"
441 className="rounded-md border border-line p-1.5 text-muted transition-colors hover:border-line-strong hover:text-fg"
442 >
443 <Plus size={16} />
444 </Link>
445 <DropdownMenu>
446 <DropdownMenuTrigger
447 aria-label="Account menu"
448 className="flex items-center gap-1.5 rounded-md p-1 outline-none transition-colors hover:bg-raised focus-visible:ring-2 focus-visible:ring-accent data-[state=open]:bg-raised"
449 >
450 <Avatar name={user.username} image={user.avatar} size={24} />
451 <ChevronDown size={14} className="text-faint" />
452 </DropdownMenuTrigger>
453 <DropdownMenuContent align="end" className="w-56">
454 <DropdownMenuLabel>
455 Signed in as{" "}
456 <span className="font-mono font-medium text-fg">
457 {user.username}
458 </span>
459 </DropdownMenuLabel>
460 <DropdownMenuSeparator />
461 {(user.workspaces ?? []).map((membership) => (
462 <DropdownMenuItem asChild key={membership.slug}>
463 <Link to={`/${membership.slug}`}>
464 <Avatar name={membership.slug} image={membership.avatar} size={16} square />
465 <span className="min-w-0 truncate">{membership.name || membership.slug}</span>
466 </Link>
467 </DropdownMenuItem>
468 ))}
469 <DropdownMenuItem asChild>
470 <Link to="/workspaces/new">
471 <Plus />
472 New workspace
473 </Link>
474 </DropdownMenuItem>
475 <DropdownMenuSeparator />
476 <DropdownMenuItem asChild>
477 <Link to="/">
478 <LayoutDashboard />
479 Mission control
480 </Link>
481 </DropdownMenuItem>
482 <DropdownMenuItem asChild>
483 <Link to="/new">
484 <Plus />
485 New project
486 </Link>
487 </DropdownMenuItem>
488 <DropdownMenuSeparator />
489 <DropdownMenuItem asChild>
490 <Link to="/settings/profile">
491 <Settings />
492 Settings
493 </Link>
494 </DropdownMenuItem>
495 <DropdownMenuItem asChild>
496 <Link to="https://docs.g1t.sh/quickstart/">
497 <BookOpen />
498 Documentation
499 </Link>
500 </DropdownMenuItem>
501 <DropdownMenuSeparator />
502 {/* Submitted from here: the menu closes on select, and a button
503 that has left the page cannot submit a form. */}
504 <DropdownMenuItem
505 onSelect={() => submit(null, { method: "post", action: "/logout" })}
506 >
507 <LogOut />
508 Sign out
509 </DropdownMenuItem>
510 </DropdownMenuContent>
511 </DropdownMenu>
512 </>
513 ) : (
514 <>
515 <span className="hidden sm:contents">
516 <HeaderLink to="/login">Sign in</HeaderLink>
517 </span>
518 <SignUpButton />
519 </>
520 )}
521 </div>
522 </div>
523 </header>
524 );
525}
526
527/**
528 * The root's data as the browser last had it. When a navigation fails in a
529 * way that takes the root's data with it, the error is still drawn in the
530 * person's own frame, signed in, not the visitor's. Never kept on the
531 * server, where one module serves everyone.
532 */
533let lastRoot: Awaited<ReturnType<typeof loader>> | undefined;
534
535export function Layout({ children }: { children: React.ReactNode }) {
536 const nonce = useNonce();
537 // Undefined when the root loader itself failed.
538 const loaded = useRouteLoaderData<typeof loader>("root");
539 const inBrowser = typeof document !== "undefined";
540 if (loaded && inBrowser) lastRoot = loaded;
541 const root = loaded ?? (inBrowser ? lastRoot : undefined);
542 const user = root?.user;
543 const { pathname, search } = useLocation();
544 // Drawn around the error page too: a 404 keeps the sidebar out of a
545 // project or workspace the viewer cannot see.
546 const error = useRouteError();
547 const missing = isRouteErrorResponse(error) && error.status === 404;
548 // The billing page shows the full banner itself.
549 const paused = root?.shell?.compute && root.shell.workspace && !pathname.endsWith("/-/billing") && (
550 <SpikeBanner
551 compact
552 slug={root.shell.workspace.slug}
553 entitlements={{ paused: root.shell.compute.paused, spike: root.shell.compute.spike }}
554 owner={root.shell.compute.owner}
555 />
556 );
557 // On the few pages an account still confirming its address can open
558 // besides /confirm-email (policies, support, signing in): the way back.
559 const verify = user && awaitsConfirmation(user) && pathname !== "/confirm-email" && (
560 <p
561 role="status"
562 className="flex flex-wrap items-center justify-center gap-x-3 gap-y-1 border-b border-warn/30 bg-warn/10 px-4 py-2 text-sm"
563 >
564 <span>Confirm your email address to start using g1t.</span>
565 <Link to="/confirm-email" className="font-medium underline underline-offset-4">
566 Enter your code
567 </Link>
568 </p>
569 );
570 // A workspace that requires two-factor authentication of someone who
571 // has not turned it on: they keep their place, and cannot use it yet.
572 const held = user?.held && user.held.length > 0 && pathname !== "/settings/two-factor" && <PolicyNotice held={user.held} />;
573 const leaving = useLeaving();
574 const banner =
575 paused || verify || held ? (
576 <>
577 {paused}
578 {verify}
579 {held}
580 </>
581 ) : null;
582 return (
583 <html lang="en">
584 <head>
585 <meta charSet="utf-8" />
586 <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
587 <meta name="theme-color" content="#0f0f11" />
588 <meta name="apple-mobile-web-app-capable" content="yes" />
589 <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
590 {/* The stylesheet before everything React Router preloads, so a slow
591 connection paints sooner (docs/research/css-shipping.md). */}
592 <link rel="stylesheet" href={appCss} precedence="default" />
593 <Meta />
594 <Links nonce={nonce} />
595 </head>
596 <body className="flex min-h-screen flex-col">
597 {/* The first stop for the keyboard: past the menus, to the page. */}
598 <a
599 href="#content"
600 className="sr-only rounded-md bg-fg px-3 py-2 text-sm font-medium text-bg focus:not-sr-only focus:fixed focus:top-2 focus:left-2 focus:z-[70]"
601 >
602 Skip to content
603 </a>
604 {root?.shell && usesAppShell(pathname, user != null && !awaitsConfirmation(user)) ? (
605 <AppShell user={user ?? null} shell={root.shell} missing={missing} banner={banner}>
606 {children}
607 </AppShell>
608 ) : (
609 <>
610 <Progress />
611 <Header user={user} />
612 {banner}
613 <div id="content" tabIndex={-1} {...leaving} className={`grow outline-none ${leaving.className}`}>
614 {children}
615 </div>
616 <SiteFooter user={user} />
617 </>
618 )}
619 {/* Live notifications for the signed-in: the feed socket, toasts, the tab's count (components/notifications). */}
620 {user && !awaitsConfirmation(user) && (
621 <LiveNotifications workspace={root?.shell?.workspace?.slug ?? null} inbox={root?.shell?.inbox?.unread ?? null} />
622 )}
623 <ScrollRestoration nonce={nonce} />
624 <Scripts nonce={nonce} />
625 </body>
626 </html>
627 );
628}
629
630export default function App() {
631 const userId = useRouteLoaderData<typeof loader>("root")?.user?.id ?? null;
632 // Tell analytics who is signed in, once per change; signing out forgets them.
633 const lastUserId = useRef<string | null>(null);
634 useEffect(() => {
635 identify(userId, lastUserId.current);
636 lastUserId.current = userId;
637 }, [userId]);
638 return <Outlet />;
639}
640
641export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
642 const location = useLocation();
643 const matches = useMatches();
644 // A tab left open across a deploy: load the address again as a whole
645 // page, once, rather than show an error the reload fixes.
646 const reload = reloadFixes({
647 error,
648 status: isRouteErrorResponse(error) ? error.status : undefined,
649 // The first page a tab loads has the key "default"; a client navigation's is its own.
650 clientNavigation: location.key !== "default",
651 caughtByCatchAll: matches.at(-1)?.id === "routes/not-found",
652 });
653 const href = location.pathname + location.search + location.hash;
654 useEffect(() => {
655 if (!reload) return;
656 try {
657 if (sessionStorage.getItem(RELOADED_KEY) === href) return;
658 sessionStorage.setItem(RELOADED_KEY, href);
659 } catch {
660 // No session storage: reload anyway; a document load never asks again.
661 }
662 window.location.assign(href);
663 }, [reload, href]);
664 if (reload) {
665 return (
666 <PageMain className="mx-auto max-w-xl px-4 py-32 text-center text-sm text-muted" aria-busy="true">
667 <title>Loading · g1t</title>
668 Loading the latest version of g1t…
669 </PageMain>
670 );
671 }
672
673 let title = "Something went wrong";
674 let details = "An unexpected error occurred. Try again in a moment.";
675 let stack: string | undefined;
676
677 if (isRouteErrorResponse(error)) {
678 // The same page for something private and something missing.
679 if (error.status === 404) {
680 return (
681 <>
682 <title>Not found · g1t</title>
683 <NotFound data={error.data} />
684 </>
685 );
686 }
687 if (typeof error.data === "string" && error.data) {
688 details = error.data;
689 }
690 } else if (import.meta.env.DEV && error instanceof Error) {
691 details = error.message;
692 stack = error.stack;
693 }
694
695 return (
696 <PageMain className="mx-auto max-w-xl px-4 py-32 text-center">
697 <h1 className="text-2xl font-semibold tracking-tight">{title}</h1>
698 <p className="mt-3 text-muted">{details}</p>
699 <div className="mt-8">
700 <ButtonLink to="/" variant="quiet">
701 Back to home
702 </ButtonLink>
703 </div>
704 {stack && (
705 <pre className="mt-8 overflow-x-auto rounded-lg border border-line p-4 text-left text-xs">
706 <code>{stack}</code>
707 </pre>
708 )}
709 </PageMain>
710 );
711}