g1t/apps/web/app/root.tsx

537 lines21,299 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, 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, 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] = 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 ]);
154 return {
155 workspace,
156 // Projects are what the sidebar lists: what the workspace builds and runs.
157 repos: listed?.ok
158 ? listed.value.map((project) => ({
159 namespace: project.workspace,
160 name: project.slug,
161 title: project.name,
162 isPrivate: project.private,
163 }))
164 : [],
165 repo:
166 path && counts?.ok
167 ? {
168 ...path,
169 // Until the repository's own page says what their role is.
170 member: hasAccessIn(user, path.namespace),
171 issues: counts.value.issues,
172 pulls: counts.value.pulls,
173 }
174 : null,
175 // Where the workspace stands against its usage limit, once billing is on.
176 limit:
177 status?.enabled && limit?.ok
178 ? {
179 exposureMicros: limit.value.exposureMicros,
180 ceilingMicros: limit.value.ceilingMicros,
181 state: limit.value.state,
182 comped: limit.value.trust === "internal",
183 }
184 : null,
185 free: Boolean(status?.free),
186 // A spend spike or a hold pauses new compute: the shell says so on every page.
187 compute:
188 workspace && entitlements && (entitlements.paused || entitlements.spike?.status === "open")
189 ? { paused: entitlements.paused, spike: entitlements.spike ?? null, owner: workspace.role === "owner" }
190 : null,
191 shared,
192 // While g1t is free every charge is zero, so usage is shown at cost.
193 monthUsageMicros: usage?.ok ? (usage.value.free ? usage.value.usedMicros : usage.value.spentMicros) : null,
194 };
195}
196
197/** How long one isolate keeps the sidebar's workspace answers. */
198const SHELL_TTL_MS = 15_000;
199
200/** Most repositories listed under Shared with you. */
201const MAX_SHARED = 20;
202
203/**
204 * Repositories shared with the user in workspaces they do not belong to,
205 * by their grants: only those, never the workspace's other repositories.
206 */
207async function sharedRepos(user: User): Promise<ShellData["shared"]> {
208 const outside = new Set(sharedWorkspaces(user));
209 if (outside.size === 0) return [];
210 const ids = (user.grants ?? []).filter((grant) => outside.has(grant.workspace)).map((grant) => grant.repo_id).slice(0, MAX_SHARED);
211 const found = await readableRepos(ids, user);
212 return found
213 .map((repo) => ({ namespace: repo.namespace, name: repo.name, isPrivate: repo.isPrivate }))
214 .sort((a, b) => `${a.namespace}/${a.name}`.localeCompare(`${b.namespace}/${b.name}`));
215}
216
217function HeaderLink({ to, children }: { to: string; children: React.ReactNode }) {
218 return (
219 <NavLink
220 to={to}
221 className={({ isActive }) =>
222 `rounded-md px-2.5 py-1.5 text-sm transition-colors hover:bg-raised hover:text-fg ${
223 isActive ? "text-fg" : "text-muted"
224 }`
225 }
226 >
227 {children}
228 </NavLink>
229 );
230}
231
232/** What the palette offers someone without the app's sidebar. */
233const PUBLIC_COMMANDS: PaletteCommand[] = [
234 { label: "Explore", hint: "Public projects", to: "/explore", icon: <Compass size={15} /> },
235 { label: "Search g1t", hint: "Repositories, code, issues, people", to: "/search", icon: <Search size={15} /> },
236 { label: "Pricing", to: "/pricing", icon: <CreditCard size={15} /> },
237 { label: "Documentation", to: "https://docs.g1t.sh/", icon: <BookOpen size={15} /> },
238 { label: "Sign in", to: "/login", icon: <LogIn size={15} /> },
239 { label: "Sign up", to: "/register", icon: <Plus size={15} /> },
240];
241
242/** Sign up, or Request access while g1t is invite-only. */
243function SignUpButton() {
244 const copy = useSignUpCopy();
245 return <ButtonLink to="/register">{copy.primary}</ButtonLink>;
246}
247
248function Header({ user }: { user: User | null | undefined }) {
249 const submit = useSubmit();
250 const signUp = useSignUpCopy();
251 const [palette, setPalette] = useState(false);
252 usePaletteShortcut(() => setPalette((open) => !open));
253 const params = useParams();
254 const repo = params.owner && params.repo ? `${params.owner}/${params.repo}` : null;
255 return (
256 <header className="sticky top-0 z-40 border-b border-line bg-surface/85 backdrop-blur">
257 <div className="mx-auto flex h-14 max-w-6xl items-center gap-2 px-4">
258 <Link to="/" aria-label="g1t home" className="mr-2 flex">
259 <Logo />
260 </Link>
261 <Form action="/search" role="search" className="relative hidden grow sm:block sm:max-w-xs">
262 <Search
263 size={14}
264 className="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-faint"
265 />
266 <input
267 name="q"
268 {...notACredential()}
269 placeholder="Search g1t"
270 aria-label="Search g1t"
271 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"
272 />
273 <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">
274 ⌘K
275 </kbd>
276 </Form>
277 <button
278 type="button"
279 aria-label="Search g1t"
280 onClick={() => setPalette(true)}
281 className="flex size-10 items-center justify-center rounded-md text-muted transition-colors hover:bg-raised hover:text-fg sm:hidden"
282 >
283 <Search size={18} />
284 </button>
285 <CommandPalette
286 open={palette}
287 onOpenChange={setPalette}
288 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))}
289 repo={repo}
290 />
291 <nav aria-label="Main" className="hidden items-center gap-0.5 sm:flex">
292 <HeaderLink to="/explore">Explore</HeaderLink>
293 <HeaderLink to="/pricing">Pricing</HeaderLink>
294 <HeaderLink to="https://docs.g1t.sh/">Docs</HeaderLink>
295 </nav>
296 <div className="ml-auto flex items-center gap-2">
297 {/* On a phone the links fold into one menu, so the bar fits. */}
298 <DropdownMenu>
299 <DropdownMenuTrigger
300 aria-label="Menu"
301 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"
302 >
303 <Menu size={18} />
304 </DropdownMenuTrigger>
305 <DropdownMenuContent align="end" className="w-52">
306 <DropdownMenuItem asChild className="min-h-11">
307 <Link to="/explore">
308 <Compass />
309 Explore
310 </Link>
311 </DropdownMenuItem>
312 <DropdownMenuItem asChild className="min-h-11">
313 <Link to="/pricing">
314 <CreditCard />
315 Pricing
316 </Link>
317 </DropdownMenuItem>
318 <DropdownMenuItem asChild className="min-h-11">
319 <Link to="https://docs.g1t.sh/">
320 <BookOpen />
321 Docs
322 </Link>
323 </DropdownMenuItem>
324 {!user && (
325 <>
326 <DropdownMenuSeparator />
327 <DropdownMenuItem asChild className="min-h-11">
328 <Link to="/login">
329 <LogIn />
330 Sign in
331 </Link>
332 </DropdownMenuItem>
333 </>
334 )}
335 </DropdownMenuContent>
336 </DropdownMenu>
337 {user ? (
338 <>
339 <Link
340 to="/new"
341 aria-label="New project"
342 className="rounded-md border border-line p-1.5 text-muted transition-colors hover:border-line-strong hover:text-fg"
343 >
344 <Plus size={16} />
345 </Link>
346 <DropdownMenu>
347 <DropdownMenuTrigger
348 aria-label="Account menu"
349 className="flex items-center gap-1.5 rounded-md p-1 outline-none transition-colors hover:bg-raised data-[state=open]:bg-raised"
350 >
351 <Avatar name={user.username} image={user.avatar} size={24} />
352 <ChevronDown size={14} className="text-faint" />
353 </DropdownMenuTrigger>
354 <DropdownMenuContent align="end" className="w-56">
355 <DropdownMenuLabel>
356 Signed in as{" "}
357 <span className="font-mono font-medium text-fg">
358 {user.username}
359 </span>
360 </DropdownMenuLabel>
361 <DropdownMenuSeparator />
362 {(user.workspaces ?? []).map((membership) => (
363 <DropdownMenuItem asChild key={membership.slug}>
364 <Link to={`/${membership.slug}`}>
365 <Avatar name={membership.slug} image={membership.avatar} size={16} square />
366 <span className="min-w-0 truncate">{membership.name || membership.slug}</span>
367 </Link>
368 </DropdownMenuItem>
369 ))}
370 <DropdownMenuItem asChild>
371 <Link to="/workspaces/new">
372 <Plus />
373 New workspace
374 </Link>
375 </DropdownMenuItem>
376 <DropdownMenuSeparator />
377 <DropdownMenuItem asChild>
378 <Link to="/">
379 <LayoutDashboard />
380 Mission control
381 </Link>
382 </DropdownMenuItem>
383 <DropdownMenuItem asChild>
384 <Link to="/new">
385 <Plus />
386 New project
387 </Link>
388 </DropdownMenuItem>
389 <DropdownMenuSeparator />
390 <DropdownMenuItem asChild>
391 <Link to="/settings/profile">
392 <Settings />
393 Settings
394 </Link>
395 </DropdownMenuItem>
396 <DropdownMenuItem asChild>
397 <Link to="https://docs.g1t.sh/quickstart/">
398 <BookOpen />
399 Documentation
400 </Link>
401 </DropdownMenuItem>
402 <DropdownMenuSeparator />
403 {/* Submitted from here: the menu closes on select, and a button
404 that has left the page cannot submit a form. */}
405 <DropdownMenuItem
406 onSelect={() => submit(null, { method: "post", action: "/logout" })}
407 >
408 <LogOut />
409 Sign out
410 </DropdownMenuItem>
411 </DropdownMenuContent>
412 </DropdownMenu>
413 </>
414 ) : (
415 <>
416 <span className="hidden sm:contents">
417 <HeaderLink to="/login">Sign in</HeaderLink>
418 </span>
419 <SignUpButton />
420 </>
421 )}
422 </div>
423 </div>
424 </header>
425 );
426}
427
428export function Layout({ children }: { children: React.ReactNode }) {
429 // Undefined when the root loader itself failed.
430 const root = useRouteLoaderData<typeof loader>("root");
431 const user = root?.user;
432 const { pathname } = useLocation();
433 // Drawn around the error page too: a 404 keeps the sidebar out of a
434 // project or workspace the viewer cannot see.
435 const error = useRouteError();
436 const missing = isRouteErrorResponse(error) && error.status === 404;
437 // The billing page shows the full banner itself.
438 const paused = root?.shell?.compute && root.shell.workspace && !pathname.endsWith("/-/billing") && (
439 <SpikeBanner
440 compact
441 slug={root.shell.workspace.slug}
442 entitlements={{ paused: root.shell.compute.paused, spike: root.shell.compute.spike }}
443 owner={root.shell.compute.owner}
444 />
445 );
446 const verify = user && !user.verified && (
447 <Form
448 method="post"
449 action="/verify"
450 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"
451 >
452 <span>
453 Confirm your email address to create repositories and push. We
454 sent you a link.
455 </span>
456 <button type="submit" className="font-medium underline underline-offset-4">
457 Send it again
458 </button>
459 </Form>
460 );
461 const banner =
462 paused || verify ? (
463 <>
464 {paused}
465 {verify}
466 </>
467 ) : null;
468 return (
469 <html lang="en">
470 <head>
471 <meta charSet="utf-8" />
472 <meta name="viewport" content="width=device-width, initial-scale=1" />
473 <meta name="theme-color" content="#0f0f11" />
474 {/* The stylesheet before everything React Router preloads, so a slow
475 connection paints sooner (docs/research/css-shipping.md). */}
476 <link rel="stylesheet" href={appCss} precedence="default" />
477 <Meta />
478 <Links />
479 </head>
480 <body className="flex min-h-screen flex-col">
481 {root?.shell && usesAppShell(pathname, user != null) ? (
482 <AppShell user={user ?? null} shell={root.shell} missing={missing} banner={banner}>
483 {children}
484 </AppShell>
485 ) : (
486 <>
487 <Progress />
488 <Header user={user} />
489 {banner}
490 <div className="grow">{children}</div>
491 <SiteFooter user={user} />
492 </>
493 )}
494 <ScrollRestoration />
495 <Scripts />
496 </body>
497 </html>
498 );
499}
500
501export default function App() {
502 return <Outlet />;
503}
504
505export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
506 let title = "Something went wrong";
507 let details = "An unexpected error occurred. Try again in a moment.";
508 let stack: string | undefined;
509
510 if (isRouteErrorResponse(error)) {
511 // The same page for something private and something missing.
512 if (error.status === 404) return <NotFound data={error.data} />;
513 if (typeof error.data === "string" && error.data) {
514 details = error.data;
515 }
516 } else if (import.meta.env.DEV && error instanceof Error) {
517 details = error.message;
518 stack = error.stack;
519 }
520
521 return (
522 <main className="mx-auto max-w-xl px-4 py-32 text-center">
523 <h1 className="text-2xl font-semibold tracking-tight">{title}</h1>
524 <p className="mt-3 text-muted">{details}</p>
525 <div className="mt-8">
526 <ButtonLink to="/" variant="quiet">
527 Back to home
528 </ButtonLink>
529 </div>
530 {stack && (
531 <pre className="mt-8 overflow-x-auto rounded-lg border border-line p-4 text-left text-xs">
532 <code>{stack}</code>
533 </pre>
534 )}
535 </main>
536 );
537}