pr_01m47d15m3e54sn21z27rpy5n9/apps/web/app/root.tsx

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