g1t/apps/web/app/root.tsx

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