flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/apps/web/app/root.tsx

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