Skip to content

g1t/apps/web/app/root.tsx

548 lines21,915 bytesCodeBlame
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 { 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 useParams,
28 useRouteError,
29 useRouteLoaderData,
30 useSubmit,
31} from "react-router";
32
33import { type User, hasAccessIn, sharedWorkspaces } from "@g1t/contracts";
34
35import type { Route } from "./+types/root";
36import appCss from "./app.css?url";
37import displayFont from "@g1t/theme/fonts/bricolage-grotesque-latin.woff2?url";
38import sansFont from "@g1t/theme/fonts/hanken-grotesk-latin.woff2?url";
39import { Logo } from "./components/logo";
40import { Avatar, ButtonLink, SubmitButton, notACredential } from "./components/ui";
41import {
42 DropdownMenu,
43 DropdownMenuContent,
44 DropdownMenuItem,
45 DropdownMenuLabel,
46 DropdownMenuSeparator,
47 DropdownMenuTrigger,
48} from "./components/ui/dropdown-menu";
49import { AppShell, Progress, type ShellData } from "./components/shell";
50import { SiteFooter } from "./components/footer";
51import { SpikeBanner } from "./components/spike-banner";
52import { readCookie } from "./lib/mission";
53import { WORKSPACE_COOKIE, workspaceFor } from "./lib/workspace-choice";
54import { NotFound } from "./components/not-found";
55import { usesAppShell } from "./lib/chrome";
56import { CommandPalette, type PaletteCommand, usePaletteShortcut } from "./components/command-palette";
57import { billing, inbox, projects } from "./lib/services.server";
58import { countsFor, readableRepos } from "./lib/access.server";
59import { shortCache } from "./lib/cache.server";
60import { getViewer, viewerMiddleware } from "./lib/session.server";
61import { registrationMode } from "./lib/registration.server";
62import { addresses } from "./lib/addresses.server";
63import { useSignUpCopy } from "./lib/registration";
64
65
66export const links: Route.LinksFunction = () => [
67 { rel: "icon", href: "/favicon.ico", sizes: "32x32" },
68 { rel: "icon", type: "image/svg+xml", href: "/favicon.svg" },
69 { rel: "icon", type: "image/png", sizes: "192x192", href: "/icon-192.png" },
70 { rel: "apple-touch-icon", href: "/apple-touch-icon.png" },
71 // The text and headline faces are wanted on every page, so they start
72 // loading with the stylesheet; mono waits until something uses it.
73 { rel: "preload", href: sansFont, as: "font", type: "font/woff2", crossOrigin: "anonymous" },
74 { rel: "preload", href: displayFont, as: "font", type: "font/woff2", crossOrigin: "anonymous" },
75];
76
77export const middleware: Route.MiddlewareFunction[] = [viewerMiddleware];
78
79export async function loader({ context, params, request }: Route.LoaderArgs) {
80 const user = getViewer(context);
81 const chosen = readCookie(request.headers.get("cookie"), WORKSPACE_COOKIE);
82 // What sign-up buttons say: Request access while g1t is invite-only.
83 const [shell, mode] = await Promise.all([
84 user ? shellFor(user, params, chosen, context) : visitorShell(params, context),
85 user ? Promise.resolve(null) : registrationMode(),
86 ]);
87 // Where this g1t lives, for clone lines, agent setup and link previews.
88 return { user, shell, inviteOnly: mode !== "open", addresses: addresses() };
89}
90
91/**
92 * The sidebar for someone not signed in: nothing of their own, only the
93 * open counts of the project being looked at. One call, and only in a
94 * project; it answers the same for a private project as a missing one.
95 */
96async function visitorShell(params: { owner?: string; repo?: string }, context: Route.LoaderArgs["context"]): Promise<ShellData> {
97 const path = params.owner && params.repo ? { namespace: params.owner, name: params.repo } : null;
98 const counts = path ? await countsFor(context, params) : null;
99 return {
100 workspace: null,
101 repos: [],
102 repo: path && counts?.ok ? { ...path, member: false, issues: counts.value.issues, pulls: counts.value.pulls } : null,
103 limit: null,
104 monthUsageMicros: null,
105 };
106}
107
108/**
109 * The sidebar only changes with the workspace or repository being looked
110 * at, or after something was submitted: not on every page within them.
111 */
112export function shouldRevalidate({
113 currentParams,
114 nextParams,
115 formMethod,
116 defaultShouldRevalidate,
117}: ShouldRevalidateFunctionArgs) {
118 if (formMethod && formMethod !== "GET") return defaultShouldRevalidate;
119 return currentParams.owner !== nextParams.owner || currentParams.repo !== nextParams.repo;
120}
121
122/**
123 * The sidebar: the workspace you chose (lib/workspace-choice.ts), or the
124 * one whose own pages these are; its projects; and the repository being
125 * looked at. A project in another workspace does not switch it.
126 */
127async function shellFor(
128 user: User,
129 params: { owner?: string; repo?: string },
130 chosen: string | null,
131 context: Route.LoaderArgs["context"],
132): Promise<ShellData> {
133 const memberships = user.workspaces ?? [];
134 const workspace = workspaceFor(memberships, chosen, params);
135 const path = params.owner && params.repo ? { namespace: params.owner, name: params.repo } : null;
136 const now = new Date();
137 const monthStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString();
138 // What the sidebar shows of the workspace changes rarely: kept for a few
139 // seconds per person and workspace, except just after they changed
140 // something (lib/cache.server.ts).
141 const kept = <T,>(what: string, load: () => Promise<T>) =>
142 workspace ? shortCache(`shell:${what}:${user.id}:${workspace.slug}`, SHELL_TTL_MS, load) : Promise.resolve(null);
143 const [listed, counts, status, usage, limit, entitlements, shared, unread] = await Promise.all([
144 kept("projects", () => projects.list(workspace!.slug, user)),
145 path ? countsFor(context, params) : Promise.resolve(null),
146 // Whether billing is on, without reading the account: that asks the
147 // card processor about the workspace's cards, too slow for every page.
148 kept("status", () => billing.status()).catch(() => null),
149 kept(`usage:${monthStart}`, () => billing.usage(workspace!.slug, user, monthStart)),
150 kept("limit", () => billing.limit(workspace!.slug, user)).catch(() => null),
151 kept("entitlements", () => billing.entitlements(workspace!.slug)).catch(() => null),
152 sharedRepos(user),
153 // The bell's count: one query, never kept, so marking an item shows at once.
154 inbox.counts(user.username).catch(() => null),
155 ]);
156 return {
157 workspace,
158 // Projects are what the sidebar lists: what the workspace builds and runs.
159 repos: listed?.ok
160 ? listed.value.map((project) => ({
161 namespace: project.workspace,
162 name: project.slug,
163 title: project.name,
164 isPrivate: project.private,
165 }))
166 : [],
167 repo:
168 path && counts?.ok
169 ? {
170 ...path,
171 // Until the repository's own page says what their role is.
172 member: hasAccessIn(user, path.namespace),
173 issues: counts.value.issues,
174 pulls: counts.value.pulls,
175 }
176 : null,
177 // Where the workspace stands against its usage limit, once billing is on.
178 limit:
179 status?.enabled && limit?.ok
180 ? {
181 exposureMicros: limit.value.exposureMicros,
182 ceilingMicros: limit.value.ceilingMicros,
183 state: limit.value.state,
184 comped: limit.value.trust === "internal",
185 }
186 : null,
187 free: Boolean(status?.free),
188 // A spend spike or a hold pauses new compute: the shell says so on every page.
189 compute:
190 workspace && entitlements && (entitlements.paused || entitlements.spike?.status === "open")
191 ? { paused: entitlements.paused, spike: entitlements.spike ?? null, owner: workspace.role === "owner" }
192 : null,
193 shared,
194 inbox: unread,
195 // While g1t is free every charge is zero, so usage is shown at cost.
196 monthUsageMicros: usage?.ok ? (usage.value.free ? usage.value.usedMicros : usage.value.spentMicros) : null,
197 };
198}
199
200/** How long one isolate keeps the sidebar's workspace answers. */
201const SHELL_TTL_MS = 15_000;
202
203/** Most repositories listed under Shared with you. */
204const MAX_SHARED = 20;
205
206/**
207 * Repositories shared with the user in workspaces they do not belong to,
208 * by their grants: only those, never the workspace's other repositories.
209 */
210async function sharedRepos(user: User): Promise<ShellData["shared"]> {
211 const outside = new Set(sharedWorkspaces(user));
212 if (outside.size === 0) return [];
213 const ids = (user.grants ?? []).filter((grant) => outside.has(grant.workspace)).map((grant) => grant.repo_id).slice(0, MAX_SHARED);
214 const found = await readableRepos(ids, user);
215 return found
216 .map((repo) => ({ namespace: repo.namespace, name: repo.name, isPrivate: repo.isPrivate }))
217 .sort((a, b) => `${a.namespace}/${a.name}`.localeCompare(`${b.namespace}/${b.name}`));
218}
219
220function HeaderLink({ to, children }: { to: string; children: React.ReactNode }) {
221 return (
222 <NavLink
223 to={to}
224 className={({ isActive }) =>
225 `rounded-md px-2.5 py-1.5 text-sm transition-colors hover:bg-raised hover:text-fg ${
226 isActive ? "text-fg" : "text-muted"
227 }`
228 }
229 >
230 {children}
231 </NavLink>
232 );
233}
234
235/** What the palette offers someone without the app's sidebar. */
236const PUBLIC_COMMANDS: PaletteCommand[] = [
237 { label: "Explore", hint: "Public projects", to: "/explore", icon: <Compass size={15} /> },
238 { label: "Search g1t", hint: "Repositories, code, issues, people", to: "/search", icon: <Search size={15} /> },
239 { label: "Pricing", to: "/pricing", icon: <CreditCard size={15} /> },
240 { label: "Documentation", to: "https://docs.g1t.sh/", icon: <BookOpen size={15} /> },
241 { label: "Sign in", to: "/login", icon: <LogIn size={15} /> },
242 { label: "Sign up", to: "/register", icon: <Plus size={15} /> },
243];
244
245/** Sign up, or Request access while g1t is invite-only. */
246function SignUpButton() {
247 const copy = useSignUpCopy();
248 return <ButtonLink to="/register">{copy.primary}</ButtonLink>;
249}
250
251function Header({ user }: { user: User | null | undefined }) {
252 const submit = useSubmit();
253 const signUp = useSignUpCopy();
254 const [palette, setPalette] = useState(false);
255 usePaletteShortcut(() => setPalette((open) => !open));
256 const params = useParams();
257 const repo = params.owner && params.repo ? `${params.owner}/${params.repo}` : null;
258 return (
259 <header className="sticky top-0 z-40 border-b border-line bg-surface/85 backdrop-blur">
260 <div className="mx-auto flex h-14 max-w-6xl items-center gap-2 px-4">
261 <Link to="/" aria-label="g1t home" className="mr-2 flex">
262 <Logo />
263 </Link>
264 <Form action="/search" role="search" className="relative hidden grow sm:block sm:max-w-xs">
265 <Search
266 size={14}
267 className="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-faint"
268 />
269 <input
270 name="q"
271 {...notACredential()}
272 placeholder="Search g1t"
273 aria-label="Search g1t"
274 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"
275 />
276 <kbd 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">
277 ⌘K
278 </kbd>
279 </Form>
280 <button
281 type="button"
282 aria-label="Search g1t"
283 onClick={() => setPalette(true)}
284 className="flex size-10 items-center justify-center rounded-md text-muted transition-colors hover:bg-raised hover:text-fg sm:hidden"
285 >
286 <Search size={18} />
287 </button>
288 <CommandPalette
289 open={palette}
290 onOpenChange={setPalette}
291 commands={user ? [{ label: "Mission control", to: "/", icon: <LayoutDashboard size={15} /> }, ...PUBLIC_COMMANDS.slice(0, 4)] : PUBLIC_COMMANDS.map((command) => (command.to === "/register" ? { ...command, label: signUp.primary } : command))}
292 repo={repo}
293 />
294 <nav aria-label="Main" className="hidden items-center gap-0.5 sm:flex">
295 <HeaderLink to="/explore">Explore</HeaderLink>
296 <HeaderLink to="/pricing">Pricing</HeaderLink>
297 <HeaderLink to="https://docs.g1t.sh/">Docs</HeaderLink>
298 </nav>
299 <div className="ml-auto flex items-center gap-2">
300 {/* On a phone the links fold into one menu, so the bar fits. */}
301 <DropdownMenu>
302 <DropdownMenuTrigger
303 aria-label="Menu"
304 className="flex size-10 items-center justify-center rounded-md text-muted outline-none transition-colors hover:bg-raised hover:text-fg data-[state=open]:bg-raised data-[state=open]:text-fg sm:hidden"
305 >
306 <Menu size={18} />
307 </DropdownMenuTrigger>
308 <DropdownMenuContent align="end" className="w-52">
309 <DropdownMenuItem asChild className="min-h-11">
310 <Link to="/explore">
311 <Compass />
312 Explore
313 </Link>
314 </DropdownMenuItem>
315 <DropdownMenuItem asChild className="min-h-11">
316 <Link to="/pricing">
317 <CreditCard />
318 Pricing
319 </Link>
320 </DropdownMenuItem>
321 <DropdownMenuItem asChild className="min-h-11">
322 <Link to="https://docs.g1t.sh/">
323 <BookOpen />
324 Docs
325 </Link>
326 </DropdownMenuItem>
327 {!user && (
328 <>
329 <DropdownMenuSeparator />
330 <DropdownMenuItem asChild className="min-h-11">
331 <Link to="/login">
332 <LogIn />
333 Sign in
334 </Link>
335 </DropdownMenuItem>
336 </>
337 )}
338 </DropdownMenuContent>
339 </DropdownMenu>
340 {user ? (
341 <>
342 <Link
343 to="/new"
344 aria-label="New project"
345 className="rounded-md border border-line p-1.5 text-muted transition-colors hover:border-line-strong hover:text-fg"
346 >
347 <Plus size={16} />
348 </Link>
349 <DropdownMenu>
350 <DropdownMenuTrigger
351 aria-label="Account menu"
352 className="flex items-center gap-1.5 rounded-md p-1 outline-none transition-colors hover:bg-raised data-[state=open]:bg-raised"
353 >
354 <Avatar name={user.username} image={user.avatar} size={24} />
355 <ChevronDown size={14} className="text-faint" />
356 </DropdownMenuTrigger>
357 <DropdownMenuContent align="end" className="w-56">
358 <DropdownMenuLabel>
359 Signed in as{" "}
360 <span className="font-mono font-medium text-fg">
361 {user.username}
362 </span>
363 </DropdownMenuLabel>
364 <DropdownMenuSeparator />
365 {(user.workspaces ?? []).map((membership) => (
366 <DropdownMenuItem asChild key={membership.slug}>
367 <Link to={`/${membership.slug}`}>
368 <Avatar name={membership.slug} image={membership.avatar} size={16} square />
369 <span className="min-w-0 truncate">{membership.name || membership.slug}</span>
370 </Link>
371 </DropdownMenuItem>
372 ))}
373 <DropdownMenuItem asChild>
374 <Link to="/workspaces/new">
375 <Plus />
376 New workspace
377 </Link>
378 </DropdownMenuItem>
379 <DropdownMenuSeparator />
380 <DropdownMenuItem asChild>
381 <Link to="/">
382 <LayoutDashboard />
383 Mission control
384 </Link>
385 </DropdownMenuItem>
386 <DropdownMenuItem asChild>
387 <Link to="/new">
388 <Plus />
389 New project
390 </Link>
391 </DropdownMenuItem>
392 <DropdownMenuSeparator />
393 <DropdownMenuItem asChild>
394 <Link to="/settings/profile">
395 <Settings />
396 Settings
397 </Link>
398 </DropdownMenuItem>
399 <DropdownMenuItem asChild>
400 <Link to="https://docs.g1t.sh/quickstart/">
401 <BookOpen />
402 Documentation
403 </Link>
404 </DropdownMenuItem>
405 <DropdownMenuSeparator />
406 {/* Submitted from here: the menu closes on select, and a button
407 that has left the page cannot submit a form. */}
408 <DropdownMenuItem
409 onSelect={() => submit(null, { method: "post", action: "/logout" })}
410 >
411 <LogOut />
412 Sign out
413 </DropdownMenuItem>
414 </DropdownMenuContent>
415 </DropdownMenu>
416 </>
417 ) : (
418 <>
419 <span className="hidden sm:contents">
420 <HeaderLink to="/login">Sign in</HeaderLink>
421 </span>
422 <SignUpButton />
423 </>
424 )}
425 </div>
426 </div>
427 </header>
428 );
429}
430
431export function Layout({ children }: { children: React.ReactNode }) {
432 // Undefined when the root loader itself failed.
433 const root = useRouteLoaderData<typeof loader>("root");
434 const user = root?.user;
435 const { pathname, search } = useLocation();
436 // /verify lands here with ?sent=1 once it has sent the link again.
437 const sentAgain = new URLSearchParams(search).get("sent") === "1";
438 // Drawn around the error page too: a 404 keeps the sidebar out of a
439 // project or workspace the viewer cannot see.
440 const error = useRouteError();
441 const missing = isRouteErrorResponse(error) && error.status === 404;
442 // The billing page shows the full banner itself.
443 const paused = root?.shell?.compute && root.shell.workspace && !pathname.endsWith("/-/billing") && (
444 <SpikeBanner
445 compact
446 slug={root.shell.workspace.slug}
447 entitlements={{ paused: root.shell.compute.paused, spike: root.shell.compute.spike }}
448 owner={root.shell.compute.owner}
449 />
450 );
451 const verify = user && !user.verified && (
452 <Form
453 method="post"
454 action="/verify"
455 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"
456 >
457 <span role="status">
458 {sentAgain
459 ? "We sent the link again. It can take a minute to arrive."
460 : "Confirm your email address to create repositories and push. We sent you a link."}
461 </span>
462 <SubmitButton
463 name="intent"
464 value="resend-verification"
465 pending="Sending…"
466 className="inline-flex items-center gap-1.5 font-medium underline underline-offset-4 disabled:opacity-50"
467 >
468 {sentAgain ? "Send another" : "Send it again"}
469 </SubmitButton>
470 </Form>
471 );
472 const banner =
473 paused || verify ? (
474 <>
475 {paused}
476 {verify}
477 </>
478 ) : null;
479 return (
480 <html lang="en">
481 <head>
482 <meta charSet="utf-8" />
483 <meta name="viewport" content="width=device-width, initial-scale=1" />
484 <meta name="theme-color" content="#0f0f11" />
485 {/* The stylesheet before everything React Router preloads, so a slow
486 connection paints sooner (docs/research/css-shipping.md). */}
487 <link rel="stylesheet" href={appCss} precedence="default" />
488 <Meta />
489 <Links />
490 </head>
491 <body className="flex min-h-screen flex-col">
492 {root?.shell && usesAppShell(pathname, user != null) ? (
493 <AppShell user={user ?? null} shell={root.shell} missing={missing} banner={banner}>
494 {children}
495 </AppShell>
496 ) : (
497 <>
498 <Progress />
499 <Header user={user} />
500 {banner}
501 <div className="grow">{children}</div>
502 <SiteFooter user={user} />
503 </>
504 )}
505 <ScrollRestoration />
506 <Scripts />
507 </body>
508 </html>
509 );
510}
511
512export default function App() {
513 return <Outlet />;
514}
515
516export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
517 let title = "Something went wrong";
518 let details = "An unexpected error occurred. Try again in a moment.";
519 let stack: string | undefined;
520
521 if (isRouteErrorResponse(error)) {
522 // The same page for something private and something missing.
523 if (error.status === 404) return <NotFound data={error.data} />;
524 if (typeof error.data === "string" && error.data) {
525 details = error.data;
526 }
527 } else if (import.meta.env.DEV && error instanceof Error) {
528 details = error.message;
529 stack = error.stack;
530 }
531
532 return (
533 <main className="mx-auto max-w-xl px-4 py-32 text-center">
534 <h1 className="text-2xl font-semibold tracking-tight">{title}</h1>
535 <p className="mt-3 text-muted">{details}</p>
536 <div className="mt-8">
537 <ButtonLink to="/" variant="quiet">
538 Back to home
539 </ButtonLink>
540 </div>
541 {stack && (
542 <pre className="mt-8 overflow-x-auto rounded-lg border border-line p-4 text-left text-xs">
543 <code>{stack}</code>
544 </pre>
545 )}
546 </main>
547 );
548}