Skip to content

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

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