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.

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