Skip to content

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.sh
248 linesCodeBlameRaw
1import { waitUntil } from "cloudflare:workers";
2import { Box, Lock } from "lucide-react";
3import type { ReactNode } from "react";
4import { Link, Outlet, type ShouldRevalidateFunctionArgs, data, useLocation, useRouteLoaderData } from "react-router";
5
6import type { Project } from "@g1t/contracts";
7
8import type { Route } from "./+types/layout";
9import { Topics } from "../../components/topics";
10import { page } from "../../lib/meta";
11import { type Tab as PageTab, tabsFor } from "../../lib/project-nav";
12import { SoonPill } from "../../components/ui";
13import { Badge } from "../../components/ui/badge";
14import { Hint } from "../../components/ui/hint";
15import { TabStrip } from "../../components/ui/tab-strip";
16import { ProjectStrip } from "../../components/mobile";
17import { seesSettings } from "../../lib/access";
18import { WatchMenu } from "../../components/notifications";
19import { PinButton } from "../../components/pin-button";
20import { StarButton } from "../../components/star-button";
21import { ArchivedBanner } from "../../components/repo-lifecycle";
22import { WelcomeBanner } from "../../components/welcome";
23import { clearWelcome, welcomes } from "../../lib/invites";
24import { notFound } from "../../lib/not-found.server";
25import { redirectIfRenamed, redirectIfTransferred } from "../../lib/renamed.server";
26import { accessFor, countsFor, projectFor, repoFor } from "../../lib/access.server";
27import { inbox, projects, repos } from "../../lib/services.server";
28import { getViewer, roleIn, unwrap } from "../../lib/session.server";
29
30export function meta({ loaderData: loaded, params, ...args }: Route.MetaArgs) {
31 return page(args, { title: `${loaded?.project?.name ?? params.repo} · ${params.owner} · g1t` });
32}
33
34export async function loader({ params, context, request }: Route.LoaderArgs) {
35 const viewer = getViewer(context);
36 const path = { namespace: params.owner, name: params.repo };
37 // Members pin the workspace's projects, and what they open is their Recent.
38 const member = viewer ? roleIn(viewer, params.owner) != null : false;
39 const [repo, counts, found, watching, shortcuts, stars] = await Promise.all([
40 repoFor(context, params),
41 countsFor(context, params),
42 projectFor(context, params),
43 // How the person watches it, for the header's Watch menu, as soon as
44 // the repository is known.
45 viewer
46 ? repoFor(context, params).then((found) => (found.ok ? inbox.watching(viewer.username, found.value.id).catch(() => null) : null))
47 : null,
48 // Whether they pinned it, for the header's Pin button.
49 member ? projects.shortcuts(params.owner, viewer).catch(() => null) : null,
50 // How many starred it and whether they did, for the header's Star button.
51 repos.stars(path, viewer).then((found) => (found.ok ? found.value : null)).catch(() => null),
52 ]);
53 if (!repo.ok && !found.ok) {
54 // Under a workspace's old name, after a rename: the project is at the new one.
55 await redirectIfRenamed(request, params.owner);
56 // A repository transferred to another workspace: it is there now.
57 await redirectIfTransferred(request, params.owner, params.repo, viewer);
58 throw notFound("project");
59 }
60 let project: Project | null = found.ok ? found.value : null;
61 // A repository made a moment ago, before its project: make it now.
62 if (!project && repo.ok && !repo.value.forkOf) {
63 const own = await projects.byRepo(repo.value.id);
64 project = own.find((p) => p.slug === params.repo.toLowerCase()) ?? own[0] ?? null;
65 }
66 // Opened just now: it leads their Recent, recorded after the page is sent.
67 if (member && project) waitUntil(projects.visited(viewer!, project.id).catch(() => undefined));
68 const value = unwrap(repo);
69 // The viewer's role on the repository and what it lets them do, for the
70 // pages under it and the sidebar.
71 const access = accessFor(viewer, value);
72 // Just given access with an invite: welcomed once (routes/invite.tsx).
73 const welcome = Boolean(access.role) && welcomes(request.headers.get("cookie"), `${value.namespace}/${value.name}`);
74 const headers = welcome ? { "Set-Cookie": clearWelcome(new URL(request.url).protocol === "https:") } : undefined;
75 return data({
76 welcome,
77 repo: value,
78 project,
79 open: counts.ok ? counts.value : { issues: 0, pulls: 0 },
80 access,
81 member: access.insider,
82 watching,
83 // Null for a pull request's working copy, or when it could not be read.
84 stars: value.forkOf ? null : stars,
85 signedIn: Boolean(viewer),
86 // Null when they cannot pin it: not one of their workspaces.
87 pinned: member && project ? (shortcuts?.pinned ?? []).some((pinned) => pinned.id === project.id) : null,
88 }, { headers });
89}
90
91/**
92 * The project's header, tabs and the viewer's role change with the project
93 * or after something was submitted, not from one page of it to the next,
94 * nor when a page refreshes itself.
95 */
96export function shouldRevalidate({ currentParams, nextParams, formMethod, defaultShouldRevalidate }: ShouldRevalidateFunctionArgs) {
97 if (formMethod && formMethod !== "GET") return defaultShouldRevalidate;
98 return currentParams.owner !== nextParams.owner || currentParams.repo !== nextParams.repo;
99}
100
101/** The project the page is in, for the pages under it. */
102export function useProject() {
103 return useRouteLoaderData<typeof loader>("routes/repo/layout");
104}
105
106/** A repository's topics, each a way into Explore. */
107function Header({ project, isPrivate, archived, namespace, name, description, large, actions }: {
108 project: Project | null;
109 isPrivate: boolean;
110 namespace: string;
111 name: string;
112 description: string | null;
113 archived?: boolean;
114 large?: boolean;
115 /** At the end of the row: Pin, Watch and Star. */
116 actions?: ReactNode;
117}) {
118 const base = `/${namespace}/${name}`;
119 return (
120 <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
121 <span
122 className={`flex shrink-0 items-center justify-center rounded-md bg-raised text-muted ring-1 ring-line ${large ? "size-8" : "size-6"}`}
123 >
124 {isPrivate ? <Lock size={large ? 15 : 13} /> : <Box size={large ? 15 : 13} />}
125 </span>
126 <h1 className={large ? "text-lg" : "text-[0.9375rem]"}>
127 <Link to={`/${namespace}`} className="font-mono text-muted hover:text-fg">
128 {namespace}
129 </Link>
130 <span className="mx-1.5 text-faint">/</span>
131 <Link to={base} className="font-semibold hover:underline">
132 {project?.name ?? name}
133 </Link>
134 </h1>
135 <Badge size="md">{isPrivate ? "private" : "public"}</Badge>
136 {archived && <Badge size="md">archived</Badge>}
137 {/* On a phone, on its own line under the name and the Watch menu. */}
138 {description && <p className="order-last min-w-0 basis-full truncate text-sm text-muted sm:order-none sm:basis-0 sm:flex-1">{description}</p>}
139 {actions && <div className="ml-auto flex shrink-0 items-center gap-2">{actions}</div>}
140 </div>
141 );
142}
143
144/**
145 * The views of the page the project is on, as tabs across its top: Files,
146 * Commits and what is coming under Code, and so on. Soon tabs open their
147 * roadmap page, under the same tabs.
148 */
149function PageTabs({ base, tabs }: { base: string; tabs: PageTab[] }) {
150 const { pathname } = useLocation();
151 const rest = pathname.slice(base.length + 1);
152 const current = (tab: PageTab) =>
153 [tab.path, ...(tab.also ?? [])].some((path) => rest === path || (!tab.exact && rest.startsWith(`${path}/`)));
154 return (
155 <TabStrip label="Views" className="-mb-px gap-1">
156 {tabs.map((tab) => (
157 <Hint key={tab.path} label={tab.about}>
158 <Link
159 to={`${base}/${tab.path}`}
160 prefetch="intent"
161 // Current by the tab's own rule: a link's address alone would also
162 // mark Overview current on every page under it.
163 aria-current={current(tab) ? "page" : undefined}
164 data-active={current(tab) || undefined}
165 className={`flex items-center gap-1.5 border-b-2 px-3 pt-1 pb-2.5 text-sm transition-colors ${
166 current(tab)
167 ? "border-accent font-medium text-fg"
168 : tab.soon
169 ? "border-transparent text-faint hover:text-muted"
170 : "border-transparent text-muted hover:text-fg"
171 }`}
172 >
173 {tab.label}
174 {tab.soon && <SoonPill />}
175 </Link>
176 </Hint>
177 ))}
178 </TabStrip>
179 );
180}
181
182export default function ProjectLayout({ loaderData }: Route.ComponentProps) {
183 const { repo, project, member, access, welcome, watching, pinned, stars, signedIn } = loaderData;
184 const base = `/${repo.namespace}/${repo.name}`;
185 // The project's own description, else the repository's as it is now.
186 const description = (project && !project.descriptionInherited ? project.description : null) ?? repo.description;
187 const { pathname } = useLocation();
188 const rest = pathname.slice(base.length + 1);
189 const tabs = tabsFor(rest, member, access.can);
190 // The files' own About says what it is and its topics, as the one place.
191 const filesPage = /^(code|tree|blob|commits?|branches|tags|releases|compare)(\/|$)/.test(rest);
192 // Everyone, signed in or not, finds the project's pages in the sidebar;
193 // the page shows its name, and the views of the page it is on as tabs.
194 return (
195 <>
196 <div data-page-head className="border-b border-line">
197 <div className={`mx-auto max-w-6xl px-4 sm:px-5 ${tabs ? "pt-3" : "py-3"}`}>
198 <Header
199 project={project}
200 isPrivate={repo.isPrivate}
201 archived={Boolean(repo.archivedAt)}
202 namespace={repo.namespace}
203 name={repo.name}
204 // The files' own About says it there, as the one place.
205 description={filesPage ? null : description}
206 actions={
207 watching || stars || (project && pinned != null) ? (
208 <>
209 {project && pinned != null && (
210 <PinButton workspace={project.workspace} slug={project.slug} name={project.name} pinned={pinned} />
211 )}
212 {watching && <WatchMenu action={`${base}/notifications`} level={watching.level} events={watching.events} />}
213 {stars && <StarButton base={base} name={`${repo.namespace}/${repo.name}`} stars={stars} signedIn={signedIn} />}
214 </>
215 ) : null
216 }
217 />
218 {/* On the files' pages, About shows them. */}
219 {!filesPage && <Topics topics={repo.topics} />}
220 {/* A phone, or a visitor: the project's pages, which the sidebar lists for someone signed in. */}
221 <div className={signedIn ? "mt-3 md:hidden" : "mt-3"}>
222 <ProjectStrip base={base} member={member} can={access.can} settings={seesSettings(access)} counts={loaderData.open} always={!signedIn} />
223 </div>
224 {tabs && (
225 <div className="mt-3">
226 <PageTabs base={base} tabs={tabs} />
227 </div>
228 )}
229 </div>
230 </div>
231 <div className="mx-auto max-w-6xl px-4 py-6 sm:px-5">
232 {welcome && (
233 <div className="mb-6">
234 <WelcomeBanner title={`You're in ${repo.namespace}/${repo.name}`}>
235 You have the {access.role} role on it now. Its code, issues and pull requests are yours to work on.
236 </WelcomeBanner>
237 </div>
238 )}
239 {repo.archivedAt && (
240 <div className="mb-6">
241 <ArchivedBanner base={base} owner={access.can.administer} settings={/^settings(\/|$)/.test(pathname.slice(base.length + 1))} />
242 </div>
243 )}
244 <Outlet />
245 </div>
246 </>
247 );
248}