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.

276 linesCodeBlameRaw
1import { waitUntil } from "cloudflare:workers";
2import { Box, GitFork, Link2, 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 { projectHomepage } from "../../lib/about";
11import { page } from "../../lib/meta";
12import { type Tab as PageTab, tabsFor } from "../../lib/project-nav";
13import { Badge } from "../../components/ui/badge";
14import { Hint } from "../../components/ui/hint";
15import { NavTab, NavTabs } from "../../components/ui/nav-tabs";
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 { ForkButton, type Forking } from "../../components/fork-button";
22import { ArchivedBanner } from "../../components/repo-lifecycle";
23import { WelcomeBanner } from "../../components/welcome";
24import { clearWelcome, welcomes } from "../../lib/invites";
25import { notFound } from "../../lib/not-found.server";
26import { redirectIfRenamed, redirectIfTransferred } from "../../lib/renamed.server";
27import { accessFor, countsFor, projectFor, repoFor } from "../../lib/access.server";
28import { inbox, projects, repos, work } from "../../lib/services.server";
29import { getViewer, roleIn, unwrap } from "../../lib/session.server";
30import { isFailed, orElse, part } from "../../lib/partial";
31
32/** How many forks the header counts before it says "100+". */
33const FORKS_COUNTED = 100;
34
35export function meta({ loaderData: loaded, params, ...args }: Route.MetaArgs) {
36 return page(args, { title: `${loaded?.project?.name ?? params.repo} · ${params.owner} · g1t` });
37}
38
39export async function loader({ params, context, request }: Route.LoaderArgs) {
40 const viewer = getViewer(context);
41 const path = { namespace: params.owner, name: params.repo };
42 // Members pin the workspace's projects, and what they open is their Recent.
43 const member = viewer ? roleIn(viewer, params.owner) != null : false;
44 const [repo, counts, found, watching, shortcuts, stars, forks, issues] = await Promise.all([
45 repoFor(context, params),
46 // The repository is what the frame is about; its open counts are only
47 // the tabs' badges, which do without them.
48 part(countsFor(context, params), "Open counts"),
49 projectFor(context, params),
50 // How the person watches it, for the header's Watch menu, as soon as
51 // the repository is known.
52 viewer
53 ? repoFor(context, params).then((found) => (found.ok ? inbox.watching(viewer.username, found.value.id).catch(() => null) : null))
54 : null,
55 // Whether they pinned it, for the header's Pin button.
56 member ? projects.shortcuts(params.owner, viewer).catch(() => null) : null,
57 // How many starred it and whether they did, for the header's Star button.
58 repos.stars(path, viewer).then((found) => (found.ok ? found.value : null)).catch(() => null),
59 // Its forks the viewer can see, counted up to 100, for the header's Fork button.
60 repos.forks(path, viewer, FORKS_COUNTED).then((found) => (found.ok ? found.value.length : null)).catch(() => null),
61 // Whether issues can be opened in it (off by default in a fork): Issues
62 // leaves its menus when they cannot. On when it could not be read.
63 work.getSettings(path, viewer).then((found) => (found.ok ? (found.value.issuesEnabled ?? true) : true)).catch(() => true),
64 ]);
65 if (!repo.ok && !found.ok) {
66 // Under a workspace's old name, after a rename: the project is at the new one.
67 await redirectIfRenamed(request, params.owner);
68 // A repository transferred to another workspace: it is there now.
69 await redirectIfTransferred(request, params.owner, params.repo, viewer);
70 throw notFound("project");
71 }
72 let project: Project | null = found.ok ? found.value : null;
73 // A repository made a moment ago, before its project: make it now.
74 if (!project && repo.ok && !repo.value.forkOf) {
75 // The repository still has its page when its project cannot be read: drawn by its own name.
76 const own = orElse(await part(projects.byRepo(repo.value.id), "Its project"), []);
77 project = own.find((p) => p.slug === params.repo.toLowerCase()) ?? own[0] ?? null;
78 }
79 // Opened just now: it leads their Recent, recorded after the page is sent.
80 if (member && project) waitUntil(projects.visited(viewer!, project.id).catch(() => undefined));
81 const value = unwrap(repo);
82 // The viewer's role on the repository and what it lets them do, for the
83 // pages under it and the sidebar.
84 const access = accessFor(viewer, value);
85 // Just given access with an invite: welcomed once (routes/invite.tsx).
86 const welcome = Boolean(access.role) && welcomes(request.headers.get("cookie"), `${value.namespace}/${value.name}`);
87 // Fork shows when it may be forked, and to its admins turned off when it
88 // may not; never on a pull request's working copy.
89 const forkable = !value.isPrivate || Boolean(value.allowForking);
90 const forking: Forking | null =
91 value.forkOf || forks == null || (!forkable && !access.can.administer)
92 ? null
93 : { count: Math.min(forks, FORKS_COUNTED), more: forks >= FORKS_COUNTED, allowed: forkable };
94 const headers = welcome ? { "Set-Cookie": clearWelcome(new URL(request.url).protocol === "https:") } : undefined;
95 return data({
96 welcome,
97 repo: value,
98 project,
99 open: !isFailed(counts) && counts.ok ? counts.value : { issues: 0, pulls: 0 },
100 access,
101 member: access.insider,
102 watching,
103 // Null for a pull request's working copy, or when it could not be read.
104 stars: value.forkOf ? null : stars,
105 forking,
106 issues,
107 signedIn: Boolean(viewer),
108 // Null when they cannot pin it: not one of their workspaces.
109 pinned: member && project ? (shortcuts?.pinned ?? []).some((pinned) => pinned.id === project.id) : null,
110 }, { headers });
111}
112
113/**
114 * The project's header, tabs and the viewer's role change with the project
115 * or after something was submitted, not from one page of it to the next,
116 * nor when a page refreshes itself.
117 */
118export function shouldRevalidate({ currentParams, nextParams, formMethod, defaultShouldRevalidate }: ShouldRevalidateFunctionArgs) {
119 if (formMethod && formMethod !== "GET") return defaultShouldRevalidate;
120 return currentParams.owner !== nextParams.owner || currentParams.repo !== nextParams.repo;
121}
122
123/** The project the page is in, for the pages under it. */
124export function useProject() {
125 return useRouteLoaderData<typeof loader>("routes/repo/layout");
126}
127
128/** The project's name row: its kind, owner and name, visibility, and Pin, Watch and Star at the end. */
129function Header({ project, isPrivate, archived, namespace, name, large, actions, parent }: {
130 project: Project | null;
131 /** The repository it was forked from, when the viewer can see it. */
132 parent?: { namespace: string; name: string } | null;
133 isPrivate: boolean;
134 namespace: string;
135 name: string;
136 archived?: boolean;
137 large?: boolean;
138 /** At the end of the row: Pin, Watch and Star. */
139 actions?: ReactNode;
140}) {
141 const base = `/${namespace}/${name}`;
142 return (
143 <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
144 <span
145 className={`flex shrink-0 items-center justify-center rounded-md bg-raised text-muted ring-1 ring-line ${large ? "size-8" : "size-6"}`}
146 >
147 {isPrivate ? <Lock size={large ? 15 : 13} /> : <Box size={large ? 15 : 13} />}
148 </span>
149 <h1 className={large ? "text-lg" : "text-[0.9375rem]"}>
150 <Link to={`/${namespace}`} className="font-mono text-muted hover:text-fg">
151 {namespace}
152 </Link>
153 <span className="mx-1.5 text-faint">/</span>
154 <Link to={base} className="font-semibold hover:underline">
155 {project?.name ?? name}
156 </Link>
157 </h1>
158 <Badge size="md">{isPrivate ? "private" : "public"}</Badge>
159 {archived && <Badge size="md">archived</Badge>}
160 {actions && <div className="ml-auto flex shrink-0 items-center gap-2">{actions}</div>}
161 {parent && (
162 <p className="flex basis-full items-center gap-1.5 text-xs text-muted">
163 <GitFork size={12} className="shrink-0 text-faint" />
164 forked from
165 <Link to={`/${parent.namespace}/${parent.name}`} className="font-mono text-fg/80 hover:text-accent hover:underline">
166 {parent.namespace}/{parent.name}
167 </Link>
168 </p>
169 )}
170 </div>
171 );
172}
173
174/**
175 * The views of the section the page is in (Files, Commits and the rest
176 * under Code, and so on), at the top of the page's content: a secondary
177 * row that belongs to what is under it, not a second header. It runs the
178 * content's width on a rule of its own, so it heads everything below it
179 * and outweighs the filters there. Soon tabs open their roadmap page,
180 * under the same tabs.
181 */
182function PageTabs({ base, tabs }: { base: string; tabs: PageTab[] }) {
183 const { pathname } = useLocation();
184 const rest = pathname.slice(base.length + 1);
185 const current = (tab: PageTab) =>
186 [tab.path, ...(tab.also ?? [])].some((path) => rest === path || (!tab.exact && rest.startsWith(`${path}/`)));
187 return (
188 <div className="mb-6 border-b border-line pb-3">
189 <NavTabs label="Views" variant="pill">
190 {tabs.map((tab) => (
191 <Hint key={tab.path} label={tab.about}>
192 <NavTab variant="pill" to={`${base}/${tab.path}`} current={current(tab)} soon={tab.soon}>
193 {tab.label}
194 </NavTab>
195 </Hint>
196 ))}
197 </NavTabs>
198 </div>
199 );
200}
201
202export default function ProjectLayout({ loaderData }: Route.ComponentProps) {
203 const { repo, project, member, access, welcome, watching, pinned, stars, forking, signedIn } = loaderData;
204 const base = `/${repo.namespace}/${repo.name}`;
205 // A repository has no description: its project's is shown.
206 const description = project?.description ?? null;
207 // Its homepage, else the repository's website.
208 const site = projectHomepage(project) ?? repo.website ?? null;
209 const { pathname } = useLocation();
210 const rest = pathname.slice(base.length + 1);
211 const tabs = tabsFor(rest, member, access.can, { issues: loaderData.issues });
212 // One row of tabs for the project's pages, along the header's border (a
213 // member's sidebar has them on a computer), and the views of the section
214 // the page is in as a quieter row at the top of its content.
215 return (
216 <>
217 <div data-page-head className="border-b border-line">
218 {/* The project's pages close the header for a visitor, and on a phone; a member's sidebar lists them from 768px. */}
219 <div className={`mx-auto max-w-6xl px-4 pt-4 sm:px-5 ${signedIn ? "pb-4 max-md:pb-0" : ""}`}>
220 <Header
221 project={project}
222 isPrivate={repo.isPrivate}
223 archived={Boolean(repo.archivedAt)}
224 namespace={repo.namespace}
225 name={repo.name}
226 parent={repo.parent}
227 actions={
228 watching || stars || forking || (project && pinned != null) ? (
229 <>
230 {project && pinned != null && (
231 <PinButton workspace={project.workspace} slug={project.slug} name={project.name} pinned={pinned} />
232 )}
233 {watching && <WatchMenu action={`${base}/notifications`} level={watching.level} events={watching.events} />}
234 {forking && <ForkButton base={base} name={`${repo.namespace}/${repo.name}`} forking={forking} signedIn={signedIn} />}
235 {stars && <StarButton base={base} name={`${repo.namespace}/${repo.name}`} stars={stars} signedIn={signedIn} />}
236 </>
237 ) : null
238 }
239 />
240 {/* What it is, where it lives and its topics, the same on every page of it. */}
241 {description && <p className="mt-2 line-clamp-2 max-w-3xl text-sm text-muted">{description}</p>}
242 {site && (
243 <a
244 href={site}
245 rel="noopener nofollow"
246 className="mt-1.5 flex w-fit max-w-full min-w-0 items-center gap-1.5 text-sm font-medium text-accent hover:underline"
247 >
248 <Link2 size={14} className="shrink-0" />
249 <span className="truncate">{site.replace(/^https?:\/\//, "").replace(/\/$/, "")}</span>
250 </a>
251 )}
252 <Topics topics={repo.topics} className="mt-3" />
253 <div className={signedIn ? "mt-3 md:hidden" : "mt-3"}>
254 <ProjectStrip base={base} member={member} can={access.can} settings={seesSettings(access)} counts={loaderData.open} always={!signedIn} issues={loaderData.issues} />
255 </div>
256 </div>
257 </div>
258 <div className="mx-auto max-w-6xl px-4 py-6 sm:px-5">
259 {tabs && <PageTabs base={base} tabs={tabs} />}
260 {welcome && (
261 <div className="mb-6">
262 <WelcomeBanner title={`You're in ${repo.namespace}/${repo.name}`}>
263 You have the {access.role} role on it now. Its code, issues and pull requests are yours to work on.
264 </WelcomeBanner>
265 </div>
266 )}
267 {repo.archivedAt && (
268 <div className="mb-6">
269 <ArchivedBanner base={base} owner={access.can.administer} settings={/^settings(\/|$)/.test(pathname.slice(base.length + 1))} />
270 </div>
271 )}
272 <Outlet />
273 </div>
274 </>
275 );
276}