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.

559 linesCodeBlameRaw
1import { ArrowUpRight, ChevronLeft, ChevronRight, LayoutGrid, List, Rocket, Search } from "lucide-react";
2import { type KeyboardEvent, useEffect, useRef, useState } from "react";
3import { Form, Link, useLocation, useNavigation, useSubmit } from "react-router";
4
5import type { Route } from "./+types/projects";
6import { host } from "../../components/deploy";
7import { PinButton } from "../../components/pin-button";
8import { EmptyState, TimeAgo, notACredential } from "../../components/ui";
9import { Button } from "../../components/ui/button";
10import { Badge } from "../../components/ui/badge";
11import { Card } from "../../components/ui/card";
12import { Checkbox } from "../../components/ui/checkbox";
13import { Kbd } from "../../components/ui/kbd";
14import { SelectField } from "../../components/ui/select";
15import { page as pageMeta } from "../../lib/meta";
16import {
17 LANGUAGE_OF,
18 type Listed,
19 type ProjectQuery,
20 SORTS,
21 facetsOf,
22 filterProjects,
23 isFiltered,
24 lastUpdated,
25 nextRow,
26 pageOf,
27 projectQueryString,
28 readProjectQuery,
29} from "../../lib/project-list";
30import { kindLabel, primaryLink } from "../../lib/project-kind";
31import { ProjectIcon } from "../../components/project-icon";
32import { deployments, projects } from "../../lib/services.server";
33import { getViewer, roleIn } from "../../lib/session.server";
34import { workspaceProjects } from "../../lib/workspace-projects.server";
35import { Unavailable } from "../../components/boundary";
36import { isFailed, part } from "../../lib/partial";
37
38export function meta({ params, ...args }: Route.MetaArgs) {
39 return pageMeta(args, { title: `Projects · ${params.owner} · g1t` });
40}
41
42/**
43 * Every project the viewer can see, filtered, sorted and paged here: one
44 * listing (shared with the sidebar's), with Deployments and the viewer's
45 * pins asked for at the same time.
46 */
47export async function loader({ params, context, request }: Route.LoaderArgs) {
48 const viewer = getViewer(context);
49 const slug = params.owner.toLowerCase();
50 const role = roleIn(viewer, slug);
51 const query = readProjectQuery(new URL(request.url).searchParams);
52 const [listed, deploys, shortcuts] = await Promise.all([
53 workspaceProjects(slug, viewer),
54 // Where each project runs: without it, rows lead to their homepage
55 // rather than production, and the page says why.
56 role ? part(deployments.overview(slug, viewer), "Production links") : null,
57 // The viewer's pins only order the list; without them it is in its usual order.
58 role ? projects.shortcuts(slug, viewer).catch(() => null) : null,
59 ]);
60 const live = new Map((!isFailed(deploys) && deploys?.ok ? deploys.value : []).map((entry) => [entry.slug, entry]));
61 const full = new Map((listed.ok ? listed.value : []).map((project) => [project.id, project]));
62 const all: Listed[] = (listed.ok ? listed.value : []).map((project) => ({
63 id: project.id,
64 slug: project.slug,
65 name: project.name,
66 description: project.description,
67 private: project.private,
68 archived: project.archived,
69 kind: project.kind,
70 ecosystem: project.ecosystem,
71 updatedAt: project.updatedAt,
72 pushedAt: project.pushedAt ?? null,
73 activity: project.activity ?? 0,
74 // Hosted on g1t.page, or an app that deploys itself (its own workflows or pipeline).
75 deploying: (live.get(project.slug)?.enabled ?? false) || (project.kind === "app" && project.runs === "elsewhere"),
76 }));
77 const matched = filterProjects(all, query);
78 const shown = pageOf(matched, query.page);
79 return {
80 slug,
81 role,
82 query: { ...query, page: shown.page },
83 total: all.length,
84 matched: matched.length,
85 page: { page: shown.page, pages: shown.pages, from: shown.from, to: shown.to },
86 // Production where g1t serves it or elsewhere, else its homepage or docs.
87 items: shown.items.map((project) => {
88 const one = full.get(project.id)!;
89 return { ...project, runs: one.runs, production: primaryLink(one, live.get(project.slug)?.production?.url) };
90 }),
91 facets: facetsOf(all),
92 pinned: (shortcuts?.pinned ?? []).map((project) => project.id),
93 failed: !listed.ok,
94 deploysFailed: isFailed(deploys) ? deploys : null,
95 };
96}
97
98type Item = Route.ComponentProps["loaderData"]["items"][number];
99
100const CONTROL =
101 "h-9 rounded-md border border-line bg-surface px-2.5 text-sm text-fg outline-none transition-colors hover:border-line-strong focus:border-accent-dim";
102/** A filter's select, on the same surface as the other controls. */
103const FILTER = "w-auto bg-surface";
104
105/** Its language, its kind when it is not an app, and its state, as small words. */
106function Facts({ project }: { project: Item }) {
107 const language = project.ecosystem ? LANGUAGE_OF[project.ecosystem] : null;
108 return (
109 <>
110 {language && <span>{language}</span>}
111 {project.kind !== "app" && <span>{kindLabel(project)}</span>}
112 {project.deploying && (
113 <span className="inline-flex items-center gap-1 text-success">
114 <Rocket size={11} />
115 {project.runs === "elsewhere" ? "Deploys itself" : "Deploys"}
116 </span>
117 )}
118 <span className="text-faint">
119 Updated <TimeAgo at={lastUpdated(project)} />
120 </span>
121 </>
122 );
123}
124
125function ProjectRow({ project, slug, pinned, member }: { project: Item; slug: string; pinned: boolean; member: boolean }) {
126 const to = `/${slug}/${project.slug}`;
127 return (
128 <li className="group relative flex items-center gap-3 px-4 py-3 transition-colors focus-within:bg-raised/60 hover:bg-raised/60">
129 <span className="flex size-8 shrink-0 items-center justify-center rounded-md bg-raised text-muted ring-1 ring-line">
130 <ProjectIcon kind={project.kind} size={14} />
131 </span>
132 <div className="min-w-0 grow">
133 <div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
134 <Link
135 to={to}
136 prefetch="intent"
137 data-row
138 className="truncate font-medium outline-none after:absolute after:inset-0 hover:underline focus-visible:underline"
139 >
140 {project.name}
141 </Link>
142 {project.name.toLowerCase() !== project.slug && <span className="truncate font-mono text-xs text-faint">{project.slug}</span>}
143 {project.private && <Badge size="md">private</Badge>}
144 {project.archived && <Badge size="md">archived</Badge>}
145 </div>
146 {project.description && <p className="mt-0.5 truncate text-sm text-muted">{project.description}</p>}
147 <p className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-xs text-muted">
148 <Facts project={project} />
149 </p>
150 </div>
151 {project.production && (
152 <a
153 href={project.production}
154 className="relative z-10 hidden shrink-0 items-center gap-1 font-mono text-xs text-muted hover:text-accent md:flex"
155 >
156 {host(project.production)}
157 <ArrowUpRight size={11} />
158 </a>
159 )}
160 {member && <PinButton workspace={slug} slug={project.slug} name={project.name} pinned={pinned} compact />}
161 </li>
162 );
163}
164
165function ProjectTile({ project, slug, pinned, member }: { project: Item; slug: string; pinned: boolean; member: boolean }) {
166 return (
167 <li className="group relative flex flex-col rounded-2xl border border-line bg-surface p-5 transition-colors focus-within:border-line-strong hover:border-line-strong">
168 <div className="flex items-start gap-3">
169 <span className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-raised text-muted ring-1 ring-line">
170 <ProjectIcon kind={project.kind} size={15} />
171 </span>
172 <div className="min-w-0 grow">
173 <Link
174 to={`/${slug}/${project.slug}`}
175 prefetch="intent"
176 data-row
177 className="block truncate font-medium outline-none after:absolute after:inset-0 hover:underline focus-visible:underline"
178 >
179 {project.name}
180 </Link>
181 {project.production ? (
182 <a href={project.production} className="relative z-10 mt-0.5 flex items-center gap-1 truncate font-mono text-xs text-muted hover:text-accent">
183 {host(project.production)}
184 <ArrowUpRight size={11} className="shrink-0" />
185 </a>
186 ) : (
187 <p className="mt-0.5 truncate font-mono text-xs text-faint">{project.slug}</p>
188 )}
189 </div>
190 {member && <PinButton workspace={slug} slug={project.slug} name={project.name} pinned={pinned} compact className="-mt-1 -mr-2" />}
191 </div>
192 <p className="mt-3 line-clamp-2 min-h-10 text-sm text-muted">{project.description ?? ""}</p>
193 <p className="mt-auto flex flex-wrap items-center gap-x-3 gap-y-0.5 border-t border-line pt-3 text-xs text-muted">
194 {project.private && <span>Private</span>}
195 {project.archived && <span>Archived</span>}
196 <Facts project={project} />
197 </p>
198 </li>
199 );
200}
201
202/** The pages around the current one: the first, the last, and two either side. */
203function pageNumbers(page: number, pages: number): (number | null)[] {
204 const wanted = new Set([1, pages, page - 2, page - 1, page, page + 1, page + 2].filter((n) => n >= 1 && n <= pages));
205 const sorted = [...wanted].sort((a, b) => a - b);
206 return sorted.flatMap((n, i) => (i > 0 && n - sorted[i - 1]! > 1 ? [null, n] : [n]));
207}
208
209function Pages({ query, page, pages }: { query: ProjectQuery; page: number; pages: number }) {
210 if (pages <= 1) return null;
211 const link = "flex h-8 min-w-8 items-center justify-center rounded-md px-2 text-sm transition-colors";
212 return (
213 <nav aria-label="Pages" className="mt-6 flex flex-wrap items-center justify-center gap-1">
214 {page > 1 ? (
215 <Link to={projectQueryString(query, { page: page - 1 })} className={`${link} gap-1 text-muted hover:bg-raised hover:text-fg`}>
216 <ChevronLeft size={14} />
217 Previous
218 </Link>
219 ) : null}
220 {pageNumbers(page, pages).map((n, i) =>
221 n == null ? (
222 <span key={`gap${i}`} className="px-1 text-faint">
223 …
224 </span>
225 ) : (
226 <Link
227 key={n}
228 to={projectQueryString(query, { page: n })}
229 aria-current={n === page ? "page" : undefined}
230 className={`${link} tabular-nums ${n === page ? "bg-raised font-medium text-fg ring-1 ring-line" : "text-muted hover:bg-raised hover:text-fg"}`}
231 >
232 {n}
233 </Link>
234 ),
235 )}
236 {page < pages ? (
237 <Link to={projectQueryString(query, { page: page + 1 })} className={`${link} gap-1 text-muted hover:bg-raised hover:text-fg`}>
238 Next
239 <ChevronRight size={14} />
240 </Link>
241 ) : null}
242 </nav>
243 );
244}
245
246export default function WorkspaceProjects({ loaderData }: Route.ComponentProps) {
247 const { slug, role, query, total, matched, page, items, facets, pinned, failed } = loaderData;
248 const submit = useSubmit();
249 const navigation = useNavigation();
250 const { pathname } = useLocation();
251 const form = useRef<HTMLFormElement>(null);
252 const searchBox = useRef<HTMLInputElement>(null);
253 const typing = useRef<ReturnType<typeof setTimeout> | null>(null);
254 const deploysBox = useRef<HTMLButtonElement>(null);
255 const [deploys, setDeploys] = useState(query.deployments);
256 const member = role != null;
257 const pins = new Set(pinned);
258 // A filter or page of this list on its way: the list says it is busy.
259 const busy = navigation.state === "loading" && navigation.location?.pathname === pathname;
260
261 const apply = (delay = 0) => {
262 if (typing.current) clearTimeout(typing.current);
263 typing.current = setTimeout(() => {
264 if (form.current) submit(form.current, { replace: true, preventScrollReset: true });
265 }, delay);
266 };
267 useEffect(() => () => void (typing.current && clearTimeout(typing.current)), []);
268 // Back and forward change the address, not the fields: they follow it,
269 // except the one being used.
270 useEffect(() => {
271 const fields = form.current?.elements;
272 if (!fields) return;
273 const values: Record<string, string> = {
274 q: query.q,
275 visibility: query.visibility,
276 kind: query.kind,
277 language: query.language ?? "",
278 archived: query.archived,
279 sort: query.sort,
280 };
281 for (const [name, value] of Object.entries(values)) {
282 const field = fields.namedItem(name) as HTMLInputElement | HTMLSelectElement | null;
283 if (field && field !== document.activeElement && "value" in field) field.value = value;
284 }
285 if (deploysBox.current !== document.activeElement) setDeploys(query.deployments);
286 }, [query]);
287
288 // `/` goes to the search, from anywhere on the page that is not a field.
289 useEffect(() => {
290 const onKey = (event: globalThis.KeyboardEvent) => {
291 const target = event.target as HTMLElement | null;
292 if (event.key !== "/" || event.metaKey || event.ctrlKey || event.altKey) return;
293 if (target && (target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName))) return;
294 event.preventDefault();
295 searchBox.current?.focus();
296 };
297 window.addEventListener("keydown", onKey);
298 return () => window.removeEventListener("keydown", onKey);
299 }, []);
300
301 // The arrows (and j and k) move between projects; Enter opens one.
302 const list = useRef<HTMLDivElement>(null);
303 const onListKey = (event: KeyboardEvent<HTMLDivElement>) => {
304 const rows = [...(list.current?.querySelectorAll<HTMLAnchorElement>("a[data-row]") ?? [])];
305 const at = rows.indexOf(document.activeElement as HTMLAnchorElement);
306 const key = event.key === "ArrowRight" ? "ArrowDown" : event.key === "ArrowLeft" ? "ArrowUp" : event.key;
307 if (at < 0 && key !== "ArrowDown" && key !== "j") return;
308 const to = nextRow(key, at, rows.length);
309 if (to == null || event.metaKey || event.ctrlKey || event.altKey) return;
310 event.preventDefault();
311 rows[to]?.focus();
312 };
313 // From the search box, down goes to the first project.
314 const onSearchKey = (event: KeyboardEvent<HTMLInputElement>) => {
315 if (event.key === "ArrowDown") {
316 event.preventDefault();
317 list.current?.querySelector<HTMLAnchorElement>("a[data-row]")?.focus();
318 }
319 if (event.key === "Escape" && event.currentTarget.value) {
320 event.currentTarget.value = "";
321 apply();
322 }
323 };
324
325 const filtered = isFiltered(query);
326 const option = (label: string, count: number) => `${label} (${count})`;
327
328 return (
329 <div>
330 <Form ref={form} id="project-filters" method="get" role="search" aria-label="Find projects" className="flex flex-wrap items-center gap-2">
331 <div className="relative w-full sm:w-72">
332 <Search size={14} className="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-faint" />
333 <input
334 ref={searchBox}
335 type="search"
336 name="q"
337 defaultValue={query.q}
338 {...notACredential()}
339 placeholder="Find a project…"
340 aria-label="Find a project"
341 aria-keyshortcuts="/"
342 onChange={() => apply(250)}
343 onKeyDown={onSearchKey}
344 className={`${CONTROL} w-full pr-8 pl-8 placeholder:text-faint`}
345 />
346 <kbd className="pointer-events-none absolute top-1/2 right-2 hidden -translate-y-1/2 rounded bg-raised px-1.5 font-mono text-[0.625rem] text-muted ring-1 ring-line sm:block">
347 /
348 </kbd>
349 </div>
350 <SelectField
351 key={`visibility-${query.visibility}`}
352 name="visibility"
353 aria-label="Visibility"
354 defaultValue={query.visibility}
355 afterChange={() => apply()}
356 className={FILTER}
357 options={[
358 { value: "all", label: "All visibility" },
359 { value: "public", label: option("Public", facets.visibility.public) },
360 { value: "private", label: option("Private", facets.visibility.private) },
361 ]}
362 />
363 <SelectField
364 key={`kind-${query.kind}`}
365 name="kind"
366 aria-label="Kind"
367 defaultValue={query.kind}
368 afterChange={() => apply()}
369 className={FILTER}
370 options={[
371 { value: "all", label: "All kinds" },
372 { value: "app", label: option("Apps", facets.kind.app) },
373 { value: "library", label: option("Libraries", facets.kind.library) },
374 ...(facets.kind.tool > 0 || query.kind === "tool" ? [{ value: "tool", label: option("Tools", facets.kind.tool) }] : []),
375 ...(facets.kind.docs > 0 || query.kind === "docs" ? [{ value: "docs", label: option("Docs", facets.kind.docs) }] : []),
376 ...(facets.kind.other > 0 || query.kind === "other" ? [{ value: "other", label: option("Other", facets.kind.other) }] : []),
377 ]}
378 />
379 {(facets.languages.length > 0 || query.language) && (
380 <SelectField
381 key={`language-${query.language ?? ""}`}
382 name="language"
383 aria-label="Language"
384 defaultValue={query.language ?? ""}
385 afterChange={() => apply()}
386 className={FILTER}
387 options={[
388 { value: "", label: "Any language" },
389 ...facets.languages.map((language) => ({ value: language.name, label: option(language.name, language.count) })),
390 ]}
391 />
392 )}
393 {(facets.archived > 0 || query.archived !== "hide") && (
394 <SelectField
395 key={`archived-${query.archived}`}
396 name="archived"
397 aria-label="Archived"
398 defaultValue={query.archived}
399 afterChange={() => apply()}
400 className={FILTER}
401 options={[
402 { value: "hide", label: "Without archived" },
403 { value: "include", label: "With archived" },
404 { value: "only", label: option("Only archived", facets.archived) },
405 ]}
406 />
407 )}
408 {member && (
409 <label className={`${CONTROL} flex cursor-pointer items-center gap-2 select-none`}>
410 <Checkbox
411 ref={deploysBox}
412 name="deployments"
413 value="on"
414 checked={deploys}
415 onCheckedChange={(checked) => {
416 setDeploys(checked === true);
417 apply();
418 }}
419 />
420 Deploys
421 <span className="text-xs tabular-nums text-faint">{facets.deploying}</span>
422 </label>
423 )}
424 {query.view !== "list" && <input type="hidden" name="view" value={query.view} />}
425 <noscript>
426 <Button type="submit" variant="outline" className="bg-surface px-2.5 font-normal text-fg">
427 Apply
428 </Button>
429 </noscript>
430 </Form>
431
432 <div className="mt-4 flex flex-wrap items-center gap-3 text-sm">
433 <p className="text-muted" aria-live="polite">
434 {filtered ? (
435 <>
436 <span className="font-medium text-fg tabular-nums">{matched}</span> of {total} {total === 1 ? "project" : "projects"}
437 {query.q && (
438 <>
439 {" "}
440 matching <span className="text-fg">“{query.q}”</span>
441 </>
442 )}
443 </>
444 ) : (
445 <>
446 <span className="font-medium text-fg tabular-nums">{total}</span> {total === 1 ? "project" : "projects"}
447 </>
448 )}
449 {page.pages > 1 && (
450 <span className="text-faint">
451 {" "}
452 · showing {page.from}–{page.to}
453 </span>
454 )}
455 </p>
456 {filtered && (
457 <Link to={projectQueryString({ ...query, q: "", visibility: "all", kind: "all", language: null, deployments: false, archived: "hide" })} className="text-xs text-muted hover:text-fg">
458 Clear filters
459 </Link>
460 )}
461 <div className="ml-auto flex items-center gap-2">
462 {/* Part of the filters' form, beside the view it orders. */}
463 <SelectField
464 key={`sort-${query.sort}`}
465 form="project-filters"
466 name="sort"
467 aria-label="Sort"
468 defaultValue={query.sort}
469 afterChange={() => apply()}
470 size="sm"
471 className={FILTER}
472 align="end"
473 options={SORTS.map((sort) => ({ value: sort.value, label: sort.label }))}
474 />
475 <Card asChild tone="bg" radius="lg" className="flex items-center gap-0.5 p-0.5">
476 <nav aria-label="View">
477 {(
478 [
479 ["list", "List", <List key="list" size={14} />],
480 ["grid", "Grid", <LayoutGrid key="grid" size={14} />],
481 ] as const
482 ).map(([view, label, icon]) => (
483 <Link
484 key={view}
485 to={projectQueryString(query, { view, page: query.page })}
486 replace
487 preventScrollReset
488 aria-label={`${label} view`}
489 aria-current={query.view === view ? "true" : undefined}
490 className={`flex size-7 items-center justify-center rounded-md transition-colors ${
491 query.view === view ? "bg-raised text-fg ring-1 ring-line" : "text-faint hover:text-fg"
492 }`}
493 >
494 {icon}
495 </Link>
496 ))}
497 </nav>
498 </Card>
499 </div>
500 </div>
501
502 <div ref={list} onKeyDown={onListKey} aria-busy={busy || undefined} className={`mt-4 transition-opacity ${busy ? "opacity-60" : ""}`}>
503 {!failed && loaderData.deploysFailed && (
504 <div className="mb-3">
505 <Unavailable what={loaderData.deploysFailed.what} compact />
506 </div>
507 )}
508 {failed ? (
509 <EmptyState title="Projects cannot be listed right now">Try again in a moment.</EmptyState>
510 ) : total === 0 ? (
511 <EmptyState title="No projects yet">
512 {member ? (
513 <>
514 <Link to={`/new?workspace=${slug}`} className="text-accent hover:underline">
515 Create one
516 </Link>
517 , or push a repository and it becomes one.
518 </>
519 ) : (
520 "This workspace has no public projects."
521 )}
522 </EmptyState>
523 ) : items.length === 0 ? (
524 <EmptyState title="No projects match">
525 Try other words or filters, or{" "}
526 <Link to={projectQueryString({ ...query, q: "", visibility: "all", kind: "all", language: null, deployments: false, archived: "hide" })} className="text-accent hover:underline">
527 clear them
528 </Link>
529 .
530 </EmptyState>
531 ) : query.view === "grid" ? (
532 <ul aria-label="Projects" className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
533 {items.map((project) => (
534 <ProjectTile key={project.id} project={project} slug={slug} pinned={pins.has(project.id)} member={member} />
535 ))}
536 </ul>
537 ) : (
538 <Card asChild divided className="overflow-hidden">
539 <ul aria-label="Projects">
540 {items.map((project) => (
541 <ProjectRow key={project.id} project={project} slug={slug} pinned={pins.has(project.id)} member={member} />
542 ))}
543 </ul>
544 </Card>
545 )}
546 </div>
547 <Pages query={query} page={page.page} pages={page.pages} />
548 {items.length > 0 && (
549 <p className="mt-4 hidden text-center text-xs text-faint sm:block">
550 <Kbd>/</Kbd> to find,{" "}
551 <Kbd>↑</Kbd>{" "}
552 <Kbd>↓</Kbd> to move,{" "}
553 <Kbd>Enter</Kbd> to open
554 </p>
555 )}
556 </div>
557 );
558}
559