pr_01m47d15m3e54sn21z27rpy5n9/apps/web/app/root.tsx

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