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