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