Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

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