Skip to content

g1t/apps/web/app/routes/repo/layout.tsx

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