pr_01m47d24b0e6n91zwymwxg0vpx/apps/web/app/root.tsx

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