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