g1t/apps/web/app/routes/workspace/overview.tsx

400 lines17,460 bytesCodeBlame
1import { ArrowRight, ArrowUpRight, Box, CircleDot, GitBranch, GitPullRequest, KeyRound, Lock, Plus, Rocket } from "lucide-react";
2import { Link } from "react-router";
3
4import type { PackageSummary, Project, ProjectDeploys, User } from "@g1t/contracts";
5
6import type { Route } from "./+types/overview";
7import { host, StatusDot } from "../../components/deploy";
8import { Avatar, ButtonLink, CopyLine, Pill, TimeAgo } from "../../components/ui";
9import { UsageCard } from "../../components/usage-card";
10import { PullIcon } from "../../components/work-icons";
11import { planStatus, type UsageGlance, usageGlance } from "../../lib/billing";
12import { openedBy } from "../../lib/opened-by";
13import { cloneUrl, useAddresses } from "../../lib/addresses";
14import { libraryPackages, packageLine, packagePath } from "../../lib/project-kind";
15import { billing, deployments, identity, packages, projects as projectsApi, work } from "../../lib/services.server";
16import { getViewer, roleIn } from "../../lib/session.server";
17
18/** Projects whose open issues and pull requests are counted. */
19const MAX_COUNTED = 30;
20/** Projects whose pull requests are listed under "In progress". */
21const MAX_LISTED = 8;
22const MAX_PULLS = 8;
23const MAX_FACES = 8;
24/** The trial as published, when the price book cannot be read. */
25const DEFAULT_TRIAL_MICROS = 5_000_000;
26
27/**
28 * The month for the Usage card, for members only: what was spent, what
29 * pays first and what it went on. Fetched here, not with the sidebar, so
30 * only this page pays for it; a billing service that cannot answer leaves
31 * the card out rather than the page.
32 */
33async function usageFor(slug: string, viewer: User | null): Promise<UsageGlance | null> {
34 const now = new Date();
35 const monthStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString();
36 const [account, usage, features, entitlements, limit, book] = await Promise.all([
37 billing.account(slug, viewer).catch(() => null),
38 billing.usage(slug, viewer, monthStart).catch(() => null),
39 billing.features(slug, viewer).catch(() => null),
40 billing.entitlements(slug).catch(() => null),
41 billing.limit(slug, viewer).catch(() => null),
42 billing.prices().catch(() => null),
43 ]);
44 if (!account?.ok || !usage?.ok) return null;
45 // Without payments set up (a g1t run without billing), there is no plan to show.
46 if (!account.value.status.enabled && !usage.value.free) return null;
47 const plan = features?.ok ? (features.value.find((state) => state.plan.feature === "plan") ?? null) : null;
48 return usageGlance({
49 usage: usage.value,
50 status: planStatus(plan, entitlements),
51 entitlements,
52 limit: limit?.ok ? limit.value : null,
53 trialMicros: book?.free?.trialWorkspaceMicros ?? DEFAULT_TRIAL_MICROS,
54 });
55}
56
57export async function loader({ params, context }: Route.LoaderArgs) {
58 const viewer = getViewer(context);
59 const slug = params.owner.toLowerCase();
60 const role = roleIn(viewer, slug);
61 const [listed, members, deploys, usage, published] = await Promise.all([
62 projectsApi.list(slug, viewer),
63 role ? identity.listMembers(slug, viewer) : null,
64 role ? deployments.overview(slug, viewer) : null,
65 role ? usageFor(slug, viewer) : null,
66 // One listing for every card: a library's card shows its package where an app's shows production.
67 packages.list(slug, viewer).catch(() => null),
68 ]);
69 const projects = listed.ok ? listed.value : [];
70
71 const pathOf = (project: Project) =>
72 project.source.kind === "hosted" ? project.source.repo : { namespace: project.workspace, name: project.slug };
73 const counted = projects.slice(0, MAX_COUNTED);
74 const counts = await Promise.all(counted.map((project) => work.counts(pathOf(project), viewer)));
75 const open: Record<string, { issues: number; pulls: number }> = {};
76 counted.forEach((project, i) => {
77 const result = counts[i];
78 if (result.ok) open[project.id] = result.value;
79 });
80
81 const busy = counted.filter((project) => (open[project.id]?.pulls ?? 0) > 0).slice(0, MAX_LISTED);
82 const lists = await Promise.all(busy.map((project) => work.listPulls(pathOf(project), viewer, "open")));
83 const pulls = lists
84 .flatMap((result, i) => (result.ok ? result.value.map((pull) => ({ pull, project: busy[i] })) : []))
85 .sort((a, b) => b.pull.updatedAt.localeCompare(a.pull.updatedAt))
86 .slice(0, MAX_PULLS);
87
88 const bySlug: Record<string, ProjectDeploys> = {};
89 for (const entry of deploys?.ok ? deploys.value : []) bySlug[entry.slug] = entry;
90
91 const byRepo = new Map<string, PackageSummary[]>();
92 for (const pkg of published?.ok ? published.value : []) {
93 if (pkg.repo) byRepo.set(pkg.repo.id, [...(byRepo.get(pkg.repo.id) ?? []), pkg]);
94 }
95 const packageOf: Record<string, PackageSummary> = {};
96 for (const project of projects) {
97 if (project.kind !== "library" || project.source.kind !== "hosted") continue;
98 const first = libraryPackages(byRepo.get(project.source.repoId) ?? [])[0];
99 if (first) packageOf[project.id] = first;
100 }
101
102 return {
103 slug,
104 role,
105 projects,
106 open,
107 deploys: bySlug,
108 packageOf,
109 pulls: pulls.map(({ pull, project }) => ({ pull, slug: project.slug, name: project.name })),
110 members: members?.ok ? members.value : null,
111 usage,
112 };
113}
114
115function Stat({ value, label }: { value: number; label: string }) {
116 return (
117 <div className="rounded-xl border border-line bg-surface px-4 py-3">
118 <p className="text-xl font-semibold tabular-nums tracking-tight">{value}</p>
119 <p className="text-xs text-muted">{label}</p>
120 </div>
121 );
122}
123
124/** What a member sees in a workspace with no projects yet. */
125function GetStarted({ slug }: { slug: string }) {
126 const addresses = useAddresses();
127 return (
128 <div className="rounded-2xl border border-line bg-surface p-8">
129 <span className="flex size-10 items-center justify-center rounded-xl bg-accent/10 text-accent ring-1 ring-accent/30">
130 <Box size={18} />
131 </span>
132 <h2 className="mt-4 text-lg font-semibold tracking-tight">Create your first project</h2>
133 <p className="mt-1.5 max-w-xl text-sm text-muted">
134 A project is what you build and run: its code, the issues that say what should change, the agents and
135 people who change it, and where it is deployed.
136 </p>
137 <div className="mt-6 flex flex-wrap gap-3">
138 <ButtonLink to={`/new?workspace=${slug}`} variant="accent">
139 <Plus size={14} />
140 New project
141 </ButtonLink>
142 </div>
143 <p className="mt-6 text-sm text-muted">Or push code you already have, and it becomes a project:</p>
144 <div className="mt-2 max-w-xl">
145 <CopyLine prompt text={`git push ${cloneUrl(addresses, `${slug}/my-project`)} main`} />
146 </div>
147 </div>
148 );
149}
150
151function ProjectCard({
152 project,
153 open,
154 deploys,
155 pkg,
156 member,
157}: {
158 project: Project;
159 open: { issues: number; pulls: number } | undefined;
160 deploys: ProjectDeploys | undefined;
161 /** For a library, the package it publishes. */
162 pkg: PackageSummary | undefined;
163 member: boolean;
164}) {
165 const library = project.kind === "library";
166 const base = `/${project.workspace}/${project.slug}`;
167 const production = deploys?.production ?? null;
168 const latest = deploys?.latest ?? null;
169 const source = project.source.kind === "hosted" ? project.source : null;
170 return (
171 <li className="group relative flex flex-col rounded-2xl border border-line bg-surface p-5 transition-colors hover:border-line-strong">
172 <div className="flex items-start gap-3">
173 <span className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-raised text-muted ring-1 ring-line">
174 {project.private ? <Lock size={15} /> : <Box size={15} />}
175 </span>
176 <div className="min-w-0 grow">
177 <Link to={base} prefetch="intent" className="font-medium after:absolute after:inset-0 hover:underline">
178 {project.name}
179 </Link>
180 {production ? (
181 <a
182 href={production.url}
183 className="relative z-10 mt-0.5 flex items-center gap-1 truncate font-mono text-xs text-muted hover:text-accent"
184 >
185 {host(production.url)}
186 <ArrowUpRight size={11} className="shrink-0" />
187 </a>
188 ) : library && pkg ? (
189 <Link
190 to={packagePath(pkg)}
191 className="relative z-10 mt-0.5 block truncate font-mono text-xs text-muted hover:text-accent"
192 >
193 {packageLine(pkg)}
194 </Link>
195 ) : (
196 <p className="mt-0.5 truncate text-xs text-faint">
197 {project.description ?? (library ? "Not published yet" : deploys?.enabled ? "Not deployed yet" : "Deployments are off")}
198 </p>
199 )}
200 </div>
201 {(project.private || project.archived) && (
202 <span className="flex shrink-0 gap-1.5">
203 {project.private && <Pill>private</Pill>}
204 {project.archived && <Pill>archived</Pill>}
205 </span>
206 )}
207 </div>
208
209 {project.description && (production || (library && pkg)) && <p className="mt-3 line-clamp-2 text-sm text-muted">{project.description}</p>}
210
211 <div className="mt-auto pt-5">
212 {member && latest && (
213 <p className="mb-3 flex items-center gap-2 text-xs text-muted">
214 <StatusDot status={latest.status} />
215 <span className="truncate">
216 {latest.kind === "production" ? "Production" : `Preview of ${latest.branch}`}
217 </span>
218 <span className="ml-auto shrink-0 text-faint">
219 <TimeAgo at={latest.createdAt} />
220 </span>
221 </p>
222 )}
223 <div className="flex items-center gap-4 border-t border-line pt-3 text-xs text-muted">
224 {source && (
225 <span className="flex min-w-0 items-center gap-1.5 font-mono">
226 <GitBranch size={12} className="shrink-0 text-faint" />
227 <span className="truncate">{source.defaultBranch}</span>
228 </span>
229 )}
230 <span className="flex items-center gap-1">
231 <CircleDot size={12} className="text-faint" />
232 {open?.issues ?? 0}
233 </span>
234 <span className="flex items-center gap-1">
235 <GitPullRequest size={12} className="text-faint" />
236 {open?.pulls ?? 0}
237 </span>
238 {member && deploys?.enabled && (deploys.previews ?? 0) > 0 && (
239 <span className="ml-auto flex items-center gap-1 text-accent">
240 <Rocket size={12} />
241 {deploys.previews} {deploys.previews === 1 ? "preview" : "previews"}
242 </span>
243 )}
244 </div>
245 </div>
246 </li>
247 );
248}
249
250export default function WorkspaceOverview({ loaderData }: Route.ComponentProps) {
251 const { slug, role, projects, open, deploys, pulls, members, usage } = loaderData;
252 const totals = Object.values(open).reduce(
253 (sum, counts) => ({ issues: sum.issues + counts.issues, pulls: sum.pulls + counts.pulls }),
254 { issues: 0, pulls: 0 },
255 );
256 const liveApps = Object.values(deploys).filter((entry) => entry.production).length;
257 return (
258 <div className="grid gap-10 lg:grid-cols-[1fr_18rem]">
259 <div className="min-w-0 space-y-10">
260 {projects.length === 0 && role ? (
261 <GetStarted slug={slug} />
262 ) : (
263 <>
264 <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
265 <Stat value={projects.length} label={projects.length === 1 ? "Project" : "Projects"} />
266 <Stat value={liveApps} label="In production" />
267 <Stat value={totals.issues} label="Open issues" />
268 <Stat value={totals.pulls} label="Pull requests in progress" />
269 </div>
270
271 <section>
272 <div className="flex items-center justify-between">
273 <h2 className="text-sm font-medium text-muted">Projects</h2>
274 {role && (
275 <Link to={`/new?workspace=${slug}`} className="inline-flex items-center gap-1 text-xs text-muted hover:text-fg">
276 <Plus size={13} />
277 New project
278 </Link>
279 )}
280 </div>
281 <ul className="mt-3 grid gap-4 sm:grid-cols-2">
282 {projects.map((project) => (
283 <ProjectCard
284 key={project.id}
285 project={project}
286 open={open[project.id]}
287 deploys={deploys[project.slug]}
288 pkg={loaderData.packageOf[project.id]}
289 member={role != null}
290 />
291 ))}
292 </ul>
293 </section>
294
295 {pulls.length > 0 && (
296 <section>
297 <h2 className="text-sm font-medium text-muted">In progress</h2>
298 <ul className="mt-3 divide-y divide-line overflow-hidden rounded-xl border border-line bg-surface">
299 {pulls.map(({ pull, slug: project, name }) => (
300 <li key={pull.id}>
301 <Link
302 prefetch="intent"
303 to={`/${slug}/${project}/pull/${pull.number}`}
304 className="flex items-center gap-3 px-4 py-3 transition-colors hover:bg-raised"
305 >
306 <PullIcon status={pull.status} />
307 <span className="min-w-0 grow">
308 <span className="block truncate font-medium">{pull.title}</span>
309 <span className="text-xs text-muted">
310 {name} <span className="font-mono">#{pull.number}</span>
311 {pull.issue != null && ` · for #${pull.issue}`} · {openedBy(pull).name}
312 </span>
313 </span>
314 <span className="hidden shrink-0 text-xs text-muted sm:block">
315 {pull.status === "draft" ? "Being worked on" : "Ready for review"}
316 </span>
317 <span className="w-14 shrink-0 text-right text-xs text-faint">
318 <TimeAgo at={pull.updatedAt} />
319 </span>
320 </Link>
321 </li>
322 ))}
323 </ul>
324 </section>
325 )}
326 </>
327 )}
328 </div>
329
330 <aside className="space-y-6">
331 {role && usage && <UsageCard slug={slug} glance={usage} owner={role === "owner"} />}
332
333 {members ? (
334 <section>
335 <div className="flex items-center justify-between">
336 <h2 className="text-sm font-medium">Members</h2>
337 <Link to={`/${slug}/-/people`} className="text-xs text-muted hover:text-fg">
338 {role === "owner" ? "Manage" : "See all"}
339 </Link>
340 </div>
341 <ul className="mt-3 space-y-1.5">
342 {members.slice(0, MAX_FACES).map((member) => (
343 <li key={member.username} className="flex items-center gap-2 text-sm">
344 <Avatar name={member.username} />
345 <span className="grow truncate font-mono">{member.username}</span>
346 {member.role === "owner" && <Pill>owner</Pill>}
347 </li>
348 ))}
349 </ul>
350 {members.length > MAX_FACES && <p className="mt-2 text-xs text-faint">and {members.length - MAX_FACES} more</p>}
351 </section>
352 ) : (
353 <p className="text-sm text-muted">
354 Members of this workspace build its projects. Anyone can open an issue or a pull request on a public one.
355 </p>
356 )}
357
358 {role && (
359 <section className="rounded-xl border border-line bg-surface p-5">
360 <h2 className="flex items-center gap-2 font-medium">
361 <Rocket size={15} className="text-faint" />
362 Deploy on g1t.page
363 </h2>
364 <p className="mt-1.5 text-sm text-muted">
365 Off until you turn them on for a project, under its Settings. Then production builds from its default
366 branch, with a live preview for every pull request. Apps cost nothing while no one visits.
367 </p>
368 <Link
369 prefetch="intent"
370 to={`/${slug}/-/billing`}
371 className="mt-3 inline-flex items-center gap-1 text-sm text-accent hover:underline"
372 >
373 Billing and plans <ArrowRight size={13} />
374 </Link>
375 </section>
376 )}
377
378 {role && (
379 <section className="rounded-xl border border-line bg-surface p-5">
380 <h2 className="flex items-center gap-2 font-medium">
381 <KeyRound size={15} className="text-faint" />
382 Automate without a service account
383 </h2>
384 <p className="mt-1.5 text-sm text-muted">
385 A workspace has access tokens of its own for CI, integrations and agents. They act as the workspace,
386 not as a person.
387 </p>
388 <Link
389 prefetch="intent"
390 to={`/${slug}/-/tokens`}
391 className="mt-3 inline-flex items-center gap-1 text-sm text-accent hover:underline"
392 >
393 Access tokens <ArrowRight size={13} />
394 </Link>
395 </section>
396 )}
397 </aside>
398 </div>
399 );
400}