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