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.

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