pr_01m47d15m3e54sn21z27rpy5n9/apps/web/app/root.tsx

397 lines13,380 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 [listed, counts, account] = await Promise.all([
91 workspace ? repos.list(user, { namespace: workspace.slug }) : Promise.resolve([]),
92 path ? work.counts(path, user) : Promise.resolve(null),
93 workspace ? billing.account(workspace.slug, user) : Promise.resolve(null),
94 ]);
95 return {
96 workspace,
97 repos: listed
98 .filter((repo) => !repo.forkOf)
99 .map(({ namespace, name, isPrivate }) => ({ namespace, name, isPrivate })),
100 repo:
101 path && counts?.ok
102 ? {
103 ...path,
104 member: roleIn(user, path.namespace) != null,
105 issues: counts.value.issues,
106 pulls: counts.value.pulls,
107 }
108 : null,
109 creditMicros:
110 account?.ok && account.value.status.enabled ? account.value.balanceMicros : null,
111 };
112}
113
114function HeaderLink({ to, children }: { to: string; children: React.ReactNode }) {
115 return (
116 <NavLink
117 to={to}
118 className={({ isActive }) =>
119 `rounded-md px-2.5 py-1.5 text-sm transition-colors hover:bg-raised hover:text-fg ${
120 isActive ? "text-fg" : "text-muted"
121 }`
122 }
123 >
124 {children}
125 </NavLink>
126 );
127}
128
129function Header({ user }: { user: User | null | undefined }) {
130 const submit = useSubmit();
131 return (
132 <header className="sticky top-0 z-40 border-b border-line bg-surface/85 backdrop-blur">
133 <div className="mx-auto flex h-14 max-w-6xl items-center gap-2 px-4">
134 <Link to="/" aria-label="g1t home" className="mr-2">
135 <Logo />
136 </Link>
137 <Form action="/search" role="search" className="relative hidden grow sm:block sm:max-w-xs">
138 <Search
139 size={14}
140 className="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-faint"
141 />
142 <input
143 name="q"
144 {...notACredential()}
145 placeholder="Search repositories"
146 aria-label="Search repositories"
147 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"
148 />
149 </Form>
150 <nav className="flex items-center gap-0.5">
151 <HeaderLink to="/explore">Explore</HeaderLink>
152 <HeaderLink to="https://docs.g1t.sh/">Docs</HeaderLink>
153 </nav>
154 <div className="ml-auto flex items-center gap-2">
155 {user ? (
156 <>
157 <Link
158 to="/new"
159 aria-label="New repository"
160 className="rounded-md border border-line p-1.5 text-muted transition-colors hover:border-line-strong hover:text-fg"
161 >
162 <Plus size={16} />
163 </Link>
164 <DropdownMenu>
165 <DropdownMenuTrigger
166 aria-label="Account menu"
167 className="flex items-center gap-1.5 rounded-md p-1 outline-none transition-colors hover:bg-raised data-[state=open]:bg-raised"
168 >
169 <Avatar name={user.username} size={24} />
170 <ChevronDown size={14} className="text-faint" />
171 </DropdownMenuTrigger>
172 <DropdownMenuContent align="end" className="w-56">
173 <DropdownMenuLabel>
174 Signed in as{" "}
175 <span className="font-mono font-medium text-fg">
176 {user.username}
177 </span>
178 </DropdownMenuLabel>
179 <DropdownMenuSeparator />
180 {(user.workspaces ?? []).map((membership) => (
181 <DropdownMenuItem asChild key={membership.slug}>
182 <Link to={`/${membership.slug}`}>
183 <Avatar name={membership.slug} size={16} square />
184 {membership.slug}
185 </Link>
186 </DropdownMenuItem>
187 ))}
188 <DropdownMenuItem asChild>
189 <Link to="/workspaces/new">
190 <Plus />
191 New workspace
192 </Link>
193 </DropdownMenuItem>
194 <DropdownMenuSeparator />
195 <DropdownMenuItem asChild>
196 <Link to="/">
197 <LayoutDashboard />
198 Mission control
199 </Link>
200 </DropdownMenuItem>
201 <DropdownMenuItem asChild>
202 <Link to="/new">
203 <Plus />
204 New repository
205 </Link>
206 </DropdownMenuItem>
207 <DropdownMenuSeparator />
208 <DropdownMenuItem asChild>
209 <Link to="/settings">
210 <Settings />
211 Settings
212 </Link>
213 </DropdownMenuItem>
214 <DropdownMenuItem asChild>
215 <Link to="https://docs.g1t.sh/quickstart/">
216 <BookOpen />
217 Documentation
218 </Link>
219 </DropdownMenuItem>
220 <DropdownMenuSeparator />
221 {/* Submitted from here: the menu closes on select, and a button
222 that has left the page cannot submit a form. */}
223 <DropdownMenuItem
224 onSelect={() => submit(null, { method: "post", action: "/logout" })}
225 >
226 <LogOut />
227 Sign out
228 </DropdownMenuItem>
229 </DropdownMenuContent>
230 </DropdownMenu>
231 </>
232 ) : (
233 <>
234 <HeaderLink to="/login">Sign in</HeaderLink>
235 <ButtonLink to="/register">Sign up</ButtonLink>
236 </>
237 )}
238 </div>
239 </div>
240 </header>
241 );
242}
243
244const FOOTER_LINKS: { title: string; links: [string, string][] }[] = [
245 {
246 title: "Product",
247 links: [
248 ["Explore repositories", "/explore"],
249 ["g1t agents", "https://docs.g1t.sh/guides/g1t-agents/"],
250 ["Bring your own agent", "https://docs.g1t.sh/guides/bring-your-own-agent/"],
251 ["Sign up", "/register"],
252 ],
253 },
254 {
255 title: "Developers",
256 links: [
257 ["Quickstart", "https://docs.g1t.sh/quickstart/"],
258 ["Concepts", "https://docs.g1t.sh/concepts/overview/"],
259 ["API reference", "https://docs.g1t.sh/api/reference/"],
260 ["OpenAPI", "https://api.g1t.sh/openapi.json"],
261 ["llms.txt", "/llms.txt"],
262 ],
263 },
264 {
265 title: "Project",
266 links: [
267 ["Source on g1t", "/syntaqx/g1t"],
268 ["Source on GitHub", "https://github.com/syntaqx/g1t"],
269 ["MIT license", "/syntaqx/g1t/blob/main/LICENSE"],
270 ],
271 },
272];
273
274function Footer() {
275 return (
276 <footer className="mt-24 border-t border-line">
277 <div className="mx-auto flex max-w-6xl flex-wrap gap-x-20 gap-y-8 px-4 py-12">
278 <div className="grow">
279 <Logo />
280 <p className="mt-3 max-w-xs text-sm text-muted">
281 A git forge for agents. Open source under the MIT license, built on
282 Cloudflare Workers and Artifacts.
283 </p>
284 </div>
285 {FOOTER_LINKS.map((group) => (
286 <div key={group.title}>
287 <p className="text-sm font-medium">{group.title}</p>
288 <ul className="mt-3 space-y-2 text-sm text-muted">
289 {group.links.map(([label, to]) => (
290 <li key={to}>
291 {/* Plain links: some targets are files or other hosts. */}
292 <a href={to} className="hover:text-fg">
293 {label}
294 </a>
295 </li>
296 ))}
297 </ul>
298 </div>
299 ))}
300 </div>
301 <div className="border-t border-line">
302 <p className="mx-auto max-w-6xl px-4 py-5 text-xs text-faint">
303 g1t is open source software, built on Cloudflare Workers and
304 Artifacts.
305 </p>
306 </div>
307 </footer>
308 );
309}
310
311export function Layout({ children }: { children: React.ReactNode }) {
312 // Undefined when the root loader itself failed.
313 const root = useRouteLoaderData<typeof loader>("root");
314 const user = root?.user;
315 const banner = user && !user.verified && (
316 <Form
317 method="post"
318 action="/verify"
319 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"
320 >
321 <span>
322 Confirm your email address to create repositories and push. We
323 sent you a link.
324 </span>
325 <button type="submit" className="font-medium underline underline-offset-4">
326 Send it again
327 </button>
328 </Form>
329 );
330 return (
331 <html lang="en">
332 <head>
333 <meta charSet="utf-8" />
334 <meta name="viewport" content="width=device-width, initial-scale=1" />
335 <meta name="theme-color" content="#0f0f11" />
336 <Meta />
337 <Links />
338 </head>
339 <body className="flex min-h-screen flex-col">
340 {user && root?.shell ? (
341 <AppShell user={user} shell={root.shell} banner={banner}>
342 {children}
343 </AppShell>
344 ) : (
345 <>
346 <Progress />
347 <Header user={user} />
348 {banner}
349 <div className="grow">{children}</div>
350 <Footer />
351 </>
352 )}
353 <ScrollRestoration />
354 <Scripts />
355 </body>
356 </html>
357 );
358}
359
360export default function App() {
361 return <Outlet />;
362}
363
364export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
365 let title = "Something went wrong";
366 let details = "An unexpected error occurred. Try again in a moment.";
367 let stack: string | undefined;
368
369 if (isRouteErrorResponse(error)) {
370 if (error.status === 404) {
371 title = "Page not found";
372 details = "There is nothing at this address, or you do not have access to it.";
373 } else if (typeof error.data === "string" && error.data) {
374 details = error.data;
375 }
376 } else if (import.meta.env.DEV && error instanceof Error) {
377 details = error.message;
378 stack = error.stack;
379 }
380
381 return (
382 <main className="mx-auto max-w-xl px-4 py-32 text-center">
383 <h1 className="text-2xl font-semibold tracking-tight">{title}</h1>
384 <p className="mt-3 text-muted">{details}</p>
385 <div className="mt-8">
386 <ButtonLink to="/" variant="quiet">
387 Back to home
388 </ButtonLink>
389 </div>
390 {stack && (
391 <pre className="mt-8 overflow-x-auto rounded-lg border border-line p-4 text-left text-xs">
392 <code>{stack}</code>
393 </pre>
394 )}
395 </main>
396 );
397}