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

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