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

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