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