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.

g1t.sh
737 linesCodeBlameRaw
1import { Bot, CircleCheck, CircleSlash, Pencil, Trash2 } from "lucide-react";
2import type { CSSProperties, ReactNode } from "react";
3import { Form, Link } from "react-router";
4
5import type { AgentRef, Comment, Issue, Pull, State } from "@g1t/contracts";
6
7import { mayChangeComment } from "../lib/comments";
8import { chipStyle } from "../lib/labels";
9import { repoAt } from "../lib/markdown-plugins";
10import { Markdown } from "./markdown";
11import { IssueIcon, PullIcon } from "./work-icons";
12import { MentionTextarea } from "./mention-textarea";
13import { ErrorText, SubmitButton, TimeAgo } from "./ui";
14import { Badge } from "./ui/badge";
15import {
16 AlertDialog,
17 AlertDialogAction,
18 AlertDialogCancel,
19 AlertDialogContent,
20 AlertDialogDescription,
21 AlertDialogFooter,
22 AlertDialogHeader,
23 AlertDialogTitle,
24 AlertDialogTrigger,
25} from "./ui/alert-dialog";
26import { Avatar } from "./ui/avatar";
27import { Button } from "./ui/button";
28import { Card } from "./ui/card";
29import { CheckboxOption } from "./ui/checkbox";
30import { Hint } from "./ui/hint";
31import { UserCard } from "./user-card";
32
33export { IssueIcon, PullIcon };
34
35/** Hues for the labels every repository starts with. */
36const LABEL_HUES: Record<string, number> = {
37 bug: 25,
38 feature: 150,
39 docs: 240,
40 chore: 80,
41 question: 310,
42};
43
44/** A stable hue for any other label, from its name. */
45function hueFor(name: string): number {
46 let hash = 0;
47 for (const char of name) hash = (hash * 31 + char.charCodeAt(0)) % 360;
48 return hash;
49}
50
51/**
52 * A label's chip: in its own color when the page knows it (the
53 * repository's labels, by name), else in a hue chosen from its name.
54 */
55export function Label({ name, color }: { name: string; color?: string | null }) {
56 const hue = LABEL_HUES[name] ?? hueFor(name);
57 const own = chipStyle(color);
58 const style: CSSProperties = Object.keys(own).length > 0 ? own : {
59 // Light text on a dark page, deep text on a light one (lib/theme.ts).
60 color: `light-dark(oklch(0.46 0.13 ${hue}), oklch(0.84 0.11 ${hue}))`,
61 borderColor: `light-dark(oklch(0.55 0.13 ${hue} / 0.35), oklch(0.84 0.11 ${hue} / 0.35))`,
62 backgroundColor: `light-dark(oklch(0.55 0.13 ${hue} / 0.08), oklch(0.84 0.11 ${hue} / 0.1))`,
63 };
64 return (
65 <span
66 style={style}
67 className="inline-flex shrink-0 items-center rounded-full border px-2 py-px text-xs font-medium"
68 >
69 {name}
70 </span>
71 );
72}
73
74/** The people an issue is assigned to, as overlapping avatars. */
75export function AssigneeStack({ people }: { people: string[] }) {
76 if (people.length === 0) return null;
77 const shown = people.slice(0, 3);
78 return (
79 <Hint label={`Assigned to ${people.join(", ")}`}>
80 <span className="flex shrink-0 items-center">
81 <span className="sr-only">Assigned to {people.join(", ")}</span>
82 {shown.map((name, index) => (
83 <span key={name} className={`rounded-full ring-2 ring-bg ${index > 0 ? "-ml-1.5" : ""}`} aria-hidden>
84 <Avatar name={name} size={18} />
85 </span>
86 ))}
87 {people.length > shown.length && (
88 <span className="ml-1 text-xs text-faint" aria-hidden>
89 +{people.length - shown.length}
90 </span>
91 )}
92 </span>
93 </Hint>
94 );
95}
96
97/** The agent working on an issue now. */
98export function Assignee({ agent }: { agent: string }) {
99 return (
100 <Hint label={`Assigned to ${agent}`}>
101 <Badge tone="accent" className="text-xs">
102 <Bot size={12} />
103 <span className="sr-only">Assigned to </span>
104 {agent}
105 </Badge>
106 </Hint>
107 );
108}
109
110const PILL = "inline-flex shrink-0 items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium";
111
112/** The large state badge at the top of an issue. */
113export function IssueState({ issue }: { issue: Pick<Issue, "state" | "reason"> }) {
114 const style =
115 issue.state === "open"
116 ? "border-success/30 bg-success/10 text-success"
117 : issue.reason === "not_planned"
118 ? "border-line bg-surface text-muted"
119 : "border-merged/30 bg-merged/10 text-merged";
120 return (
121 <span className={`${PILL} ${style}`}>
122 <IssueIcon issue={issue} size={14} />
123 {issue.state === "open"
124 ? "Open"
125 : issue.reason === "not_planned"
126 ? "Closed as not planned"
127 : "Closed"}
128 </span>
129 );
130}
131
132const PULL_STYLES: Record<Pull["status"], string> = {
133 draft: "border-line bg-surface text-muted",
134 open: "border-success/30 bg-success/10 text-success",
135 merged: "border-merged/30 bg-merged/10 text-merged",
136 closed: "border-danger/30 bg-danger/10 text-danger",
137};
138
139const PULL_NAMES: Record<Pull["status"], string> = {
140 draft: "Draft",
141 open: "Open",
142 merged: "Merged",
143 closed: "Closed",
144};
145
146export function PullState({ status }: { status: Pull["status"] }) {
147 return (
148 <span className={`${PILL} ${PULL_STYLES[status]}`}>
149 <PullIcon status={status} size={14} />
150 {PULL_NAMES[status]}
151 </span>
152 );
153}
154
155/** The open and closed switch above a list. `to` is the list's own path. */
156export function StateTabs({
157 to,
158 state,
159 query = "",
160 action,
161}: {
162 to: string;
163 state: State;
164 /** Other query parameters to keep, e.g. `label=bug`. */
165 query?: string;
166 action?: ReactNode;
167}) {
168 const link = (value: State) =>
169 `${to}?${[value === "open" ? "" : "state=closed", query].filter(Boolean).join("&")}`;
170 const tab = (value: State, label: string) => (
171 <Link
172 to={link(value)}
173 aria-current={state === value ? "page" : undefined}
174 className={
175 "inline-flex h-full items-center rounded-[5px] px-2.5 text-sm transition-colors " +
176 (state === value ? "bg-raised font-medium text-fg" : "text-muted hover:text-fg")
177 }
178 >
179 {label}
180 </Link>
181 );
182 return (
183 <div className="flex flex-wrap items-center justify-between gap-3">
184 {/* A filter, the height of the filters beside it: the section's views above it outweigh it. */}
185 <Card tone="plain" radius="lg" className="flex h-8 gap-0.5 rounded-md p-0.5">
186
187 {tab("open", "Open")}
188 {tab("closed", "Closed")}
189 </Card>
190 {action}
191 </div>
192 );
193}
194
195const VERDICTS = {
196 approve: { label: "approved these changes", style: "text-success" },
197 request_changes: { label: "requested changes", style: "text-danger" },
198} as const;
199
200/**
201 * A person's name (or `children`) linking to their profile at `/u/<name>`.
202 * g1t, and names that are not usernames, stay plain text.
203 */
204export function PersonLink({
205 name,
206 className,
207 label,
208 children,
209}: {
210 name: string;
211 className?: string;
212 label?: string;
213 children?: ReactNode;
214}) {
215 // g1t itself has no profile; its name carries a small label instead, and
216 // its card says what it is.
217 if (name === "g1t" && !children) {
218 return (
219 <UserCard username="g1t">
220 <span tabIndex={0} className="inline-flex items-baseline gap-1 rounded outline-none focus-visible:ring-2 focus-visible:ring-accent">
221 <span className={className}>g1t</span>
222 <span className="rounded border border-line px-1 text-[0.625rem] leading-[1.35] font-medium text-muted">bot</span>
223 </span>
224 </UserCard>
225 );
226 }
227 if (name === "g1t") {
228 return (
229 <UserCard username="g1t">
230 <span className={className}>{children}</span>
231 </UserCard>
232 );
233 }
234 // Ghost, a deleted account, has no profile and no card.
235 if (name === "ghost" || !/^[a-z0-9-]{1,39}$/i.test(name)) {
236 return <span className={className}>{children ?? name}</span>;
237 }
238 return (
239 <UserCard username={name}>
240 <Link to={`/u/${name.toLowerCase()}`} className={className} aria-label={label}>
241 {children ?? name}
242 </Link>
243 </UserCard>
244 );
245}
246
247/**
248 * Comments in order, then the box to add one. On a pull request, `review`
249 * says where its changes are shown and whether the viewer may give a
250 * verdict.
251 */
252/**
253 * One entry in a conversation: who, what they did and when, then what they
254 * wrote. The author's avatar sits beside it, as on any forge.
255 */
256export function TimelineItem({
257 author,
258 agent,
259 action,
260 at,
261 edited,
262 aside,
263 children,
264}: {
265 author: string;
266 /**
267 * Set when one of the workspace's former agents wrote it, as itself:
268 * shown by its name with an Agent badge, and whom it acted for, in place
269 * of `author`.
270 */
271 agent?: { ref: AgentRef; actingFor?: string | null };
272 /** What they did, after their name: "commented", "opened this". */
273 action: ReactNode;
274 at?: string;
275 /** When what they wrote was last edited, if it was. */
276 edited?: string | null;
277 /** Shown at the right of the header. */
278 aside?: ReactNode;
279 children?: ReactNode;
280}) {
281 const face = (size: number) =>
282 agent ? (
283 <Avatar name={agent.ref.displayName} agent size={size} />
284 ) : (
285 <Avatar name={author} size={size} />
286 );
287 return (
288 <div className="flex gap-3">
289 <span className="mt-1 hidden shrink-0 sm:block">
290 {agent ? (
291 face(32)
292 ) : (
293 <PersonLink name={author} label={`${author}'s profile`}>
294 {face(32)}
295 </PersonLink>
296 )}
297 </span>
298 <Card asChild className="min-w-0 grow overflow-hidden">
299 <article>
300 <header className="flex flex-wrap items-center gap-x-2 gap-y-1 border-b border-line bg-raised/40 px-4 py-2 text-sm text-muted">
301 <span className="sm:hidden">{face(18)}</span>
302 {agent ? (
303 <AgentName agent={agent.ref} />
304 ) : (
305 <PersonLink name={author} className="font-medium text-fg hover:underline" />
306 )}
307 {action}
308 {at && <TimeAgo at={at} />}
309 {agent?.actingFor && (
310 <span className="text-xs text-faint">
311 on behalf of{" "}
312 <PersonLink name={agent.actingFor} className="hover:text-fg hover:underline">
313 @{agent.actingFor}
314 </PersonLink>
315 </span>
316 )}
317 {edited && (
318 <Hint
319 label={
320 <>
321 Edited <TimeAgo at={edited} />
322 </>
323 }
324 >
325 <span tabIndex={0} className="text-xs text-faint">
326 edited
327 </span>
328 </Hint>
329 )}
330 {aside && <span className="ml-auto min-w-0">{aside}</span>}
331 </header>
332 {children && <div className="px-4 py-3">{children}</div>}
333 </article>
334 </Card>
335 </div>
336 );
337}
338
339/** A former agent's name, with an Agent badge. */
340function AgentName({ agent }: { agent: AgentRef }) {
341 return (
342 <span className="inline-flex items-center gap-1.5">
343 <span className="font-medium text-fg">{agent.displayName}</span>
344 <Badge tone="accent" className="px-1.5 text-[0.625rem] leading-[1.35]">
345 Agent
346 </Badge>
347 </span>
348 );
349}
350
351/** That an agent's review is advisory, and why it counts toward nothing. */
352function AdvisoryChip() {
353 return (
354 <Hint label="Agent reviews don't count toward required approvals">
355 <span tabIndex={0} className="inline-flex rounded-full outline-none focus-visible:ring-2 focus-visible:ring-accent">
356 <Badge tone="neutral">Advisory</Badge>
357 </span>
358 </Hint>
359 );
360}
361
362type Review = { changesUrl: string; canJudge: boolean };
363
364/**
365 * Text with each `#12` linked to the issue or pull request of that number,
366 * and each file named in backticks shown as code, linked to its diff when
367 * `filesUrl` says where the changes are.
368 */
369function WithReferences({ text, base, filesUrl }: { text: string; base?: string; filesUrl?: string }) {
370 if (!base) return <>{text}</>;
371 return (
372 <>
373 {text.split(/(#\d+|`[^`\n]+`)/).map((part, index) =>
374 /^`[^`]+`$/.test(part) ? (
375 filesUrl ? (
376 <Link
377 key={index}
378 to={`${filesUrl}#file-${part.slice(1, -1)}`}
379 className="font-mono text-xs text-fg hover:underline"
380 >
381 {part.slice(1, -1)}
382 </Link>
383 ) : (
384 <code key={index} className="font-mono text-xs text-fg">
385 {part.slice(1, -1)}
386 </code>
387 )
388 ) : /^#\d+$/.test(part) ? (
389 // Issues and pull requests share numbers; the issue page forwards.
390 <Link
391 key={index}
392 to={`${base}/issues/${part.slice(1)}`}
393 className="font-medium text-fg hover:underline"
394 >
395 {part}
396 </Link>
397 ) : (
398 part
399 ),
400 )}
401 </>
402 );
403}
404
405/** Something that happened, as one line on the conversation's rail. */
406function TimelineEvent({ comment, base, filesUrl }: { comment: Comment; base?: string; filesUrl?: string }) {
407 return (
408 <div className="flex items-center gap-3 text-sm text-muted">
409 <span className="hidden w-8 shrink-0 justify-center sm:flex">
410 <span className="size-2 rounded-full border border-line-strong bg-bg" />
411 </span>
412 <span className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-0.5">
413 <Avatar name={comment.author.username} size={16} />
414 <PersonLink name={comment.author.username} className="font-medium text-fg hover:underline" />
415 <span>
416 <WithReferences text={comment.body} base={base} filesUrl={filesUrl} />
417 </span>
418 <span className="text-faint">
419 · <TimeAgo at={comment.createdAt} />
420 </span>
421 </span>
422 </div>
423 );
424}
425
426/** Edit and Delete, under a comment the viewer may change. */
427function CommentActions({
428 comment,
429 can,
430 error,
431}: {
432 comment: Comment;
433 can: { edit: boolean; delete: boolean };
434 error?: string | null;
435}) {
436 return (
437 <div className="mt-3 border-t border-line pt-2 text-sm">
438 <div className="flex flex-wrap items-center gap-1">
439 {can.edit && (
440 <details className="open:order-last open:w-full">
441 <summary className="inline-flex cursor-pointer list-none items-center gap-1 rounded-md px-1.5 py-1 text-xs text-faint hover:text-fg">
442 <Pencil size={12} />
443 Edit
444 </summary>
445 <Form method="post" className="mt-2 space-y-2">
446 <input type="hidden" name="action" value="edit-comment" />
447 <input type="hidden" name="comment" value={comment.id} />
448 <MentionTextarea name="body" rows={4} defaultValue={comment.body} />
449 <SubmitButton match={{ action: "edit-comment", comment: comment.id }} pending="Saving…">
450 Save
451 </SubmitButton>
452 </Form>
453 </details>
454 )}
455 {can.delete && (
456 <AlertDialog>
457 <AlertDialogTrigger asChild>
458 <Button
459 type="button"
460 variant="ghost"
461 size="inline"
462 className="gap-1 px-1.5 py-1 text-xs text-faint hover:text-danger font-normal"
463 >
464 <Trash2 size={12} />
465 Delete
466 </Button>
467 </AlertDialogTrigger>
468 <AlertDialogContent>
469 <Form method="post" className="grid gap-4">
470 <input type="hidden" name="action" value="delete-comment" />
471 <input type="hidden" name="comment" value={comment.id} />
472 <AlertDialogHeader>
473 <AlertDialogTitle>Delete this comment?</AlertDialogTitle>
474 <AlertDialogDescription>It is removed from the conversation for everyone. This cannot be undone.</AlertDialogDescription>
475 </AlertDialogHeader>
476 <AlertDialogFooter>
477 <AlertDialogCancel>Cancel</AlertDialogCancel>
478 <AlertDialogAction asChild>
479 <button type="submit">
480 <Trash2 size={14} />
481 Delete comment
482 </button>
483 </AlertDialogAction>
484 </AlertDialogFooter>
485 </Form>
486 </AlertDialogContent>
487 </AlertDialog>
488 )}
489 </div>
490 {error && <ErrorText>{error}</ErrorText>}
491 </div>
492 );
493}
494
495/**
496 * The conversation of an issue or a pull request, oldest first: what
497 * people and agents wrote, and between those, what happened.
498 */
499export function CommentList({
500 comments,
501 review,
502 base,
503 viewerId,
504 canModerate = false,
505 failed,
506}: {
507 comments: Comment[];
508 review?: Review;
509 /** The repository's path, so that `#12` in an event can be linked. */
510 base?: string;
511 /** The signed-in viewer, who may edit and delete their own comments. */
512 viewerId?: string | null;
513 /** Maintain and up: may edit and delete anyone's comments. */
514 canModerate?: boolean;
515 /** Why editing or deleting a comment was refused, under that comment. */
516 failed?: { comment: string; error?: string | null } | null;
517}) {
518 return (
519 <>
520 {comments.map((comment) => {
521 if (comment.kind === "event") {
522 return <TimelineEvent key={comment.id} comment={comment} base={base} filesUrl={review?.changesUrl} />;
523 }
524 const verdict = comment.verdict && VERDICTS[comment.verdict];
525 const can = mayChangeComment(comment, viewerId, canModerate);
526 return (
527 <TimelineItem
528 key={comment.id}
529 author={comment.author.username}
530 agent={
531 comment.agent && {
532 ref: comment.agent,
533 actingFor: comment.actingFor?.username,
534 }
535 }
536 at={comment.createdAt}
537 action={
538 <>
539 {verdict ? (
540 <span className={`flex items-center gap-1 font-medium ${verdict.style}`}>
541 {comment.verdict === "approve" ? (
542 <CircleCheck size={14} />
543 ) : (
544 <CircleSlash size={14} />
545 )}
546 {verdict.label}
547 </span>
548 ) : (
549 <span>{comment.advisory ? "reviewed" : "commented"}</span>
550 )}
551 {comment.advisory && <AdvisoryChip />}
552 </>
553 }
554 edited={comment.editedAt}
555 aside={
556 comment.path &&
557 review && (
558 <Link
559 to={`${review.changesUrl}#file-${comment.path}`}
560 className="block truncate font-mono text-xs text-faint hover:text-fg"
561 >
562 {comment.path}
563 {comment.line != null && `:${comment.line}`}
564 </Link>
565 )
566 }
567 >
568 {comment.body && <Markdown source={comment.body} repo={repoAt(base)} />}
569 {(can.edit || can.delete) && (
570 <CommentActions comment={comment} can={can} error={failed?.comment === comment.id ? failed.error : null} />
571 )}
572 </TimelineItem>
573 );
574 })}
575 </>
576 );
577}
578
579/** Where a signed-in person writes a comment, or a review. */
580export function CommentForm({
581 author,
582 resetKey,
583 review,
584 handles,
585}: {
586 /** The viewer's username, or null if they are signed out. */
587 author: string | null;
588 /** Changes when a comment is added, which clears the box. */
589 resetKey: number;
590 review?: Review;
591 /** Teams the box offers to mention, as `@workspace/team`. */
592 handles?: readonly string[];
593}) {
594 if (!author) {
595 return (
596 <p className="text-sm text-muted">
597 <Link to="/login" className="text-fg underline underline-offset-4">
598 Sign in
599 </Link>{" "}
600 to comment.
601 </p>
602 );
603 }
604 return (
605 <div className="flex gap-3">
606 <span className="mt-1 hidden shrink-0 sm:block">
607 <Avatar name={author} size={32} />
608 </span>
609 <Form method="post" className="min-w-0 grow space-y-2" key={resetKey}>
610 <input type="hidden" name="action" value="comment" />
611 <MentionTextarea
612 name="body"
613 handles={handles}
614 rows={3}
615 placeholder={
616 review?.canJudge
617 ? "Leave a comment, or a review. Markdown works."
618 : "Leave a comment. Markdown works."
619 }
620 />
621 <div className="flex flex-wrap gap-2">
622 {/* A plain comment's verdict is none the action knows, so each button tells its own post apart. */}
623 <SubmitButton name="verdict" value="comment" match={{ action: "comment" }} pending="Commenting…">
624 Comment
625 </SubmitButton>
626 {review?.canJudge && (
627 <>
628 <SubmitButton variant="outline" name="verdict" value="approve" match={{ action: "comment" }} pending="Approving…">
629 <CircleCheck size={14} className="text-success" />
630 Approve
631 </SubmitButton>
632 <SubmitButton
633 variant="outline"
634 name="verdict"
635 value="request_changes"
636 match={{ action: "comment" }}
637 pending="Requesting changes…"
638 >
639 <CircleSlash size={14} className="text-danger" />
640 Request changes
641 </SubmitButton>
642 </>
643 )}
644 </div>
645 </Form>
646 </div>
647 );
648}
649
650/**
651 * Checkboxes for choosing people: the workspace's members, anyone already
652 * chosen, and a box for other usernames. Posts `name` for each ticked and
653 * `others` for the rest.
654 */
655export function PeoplePicker({
656 name,
657 members,
658 chosen,
659 placeholder = "Other usernames, comma separated",
660}: {
661 name: string;
662 members: string[];
663 chosen: string[];
664 placeholder?: string;
665}) {
666 const people = [...new Set([...members, ...chosen])];
667 return (
668 <>
669 {people.length > 0 && (
670 <div className="space-y-1.5">
671 {people.map((person) => (
672 <CheckboxOption
673 key={person}
674 name={name}
675 value={person}
676 defaultChecked={chosen.includes(person)}
677 className="items-center"
678 labelClassName="flex items-center gap-2"
679 label={
680 <>
681 <Avatar name={person} size={18} />
682 <span className="font-mono text-xs">{person}</span>
683 </>
684 }
685 />
686 ))}
687 </div>
688 )}
689 <input
690 name="others"
691 placeholder={placeholder}
692 autoComplete="off"
693 data-1p-ignore
694 className="w-full rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none placeholder:text-faint hover:border-line-strong focus:border-accent-dim"
695 />
696 </>
697 );
698}
699
700/**
701 * Where each reviewer stands: their most recent verdict. An agent's review
702 * is advisory and is not one of them.
703 */
704export function verdicts(comments: Comment[]): { reviewer: string; verdict: NonNullable<Comment["verdict"]> }[] {
705 const latest = new Map<string, NonNullable<Comment["verdict"]>>();
706 for (const comment of comments) {
707 if (comment.verdict && !comment.agent && !comment.advisory) latest.set(comment.author.username, comment.verdict);
708 }
709 return [...latest].map(([reviewer, verdict]) => ({ reviewer, verdict }));
710}
711
712/** `2 files +12 −3`: the size of a pull request's change. */
713export function ChangeSize({ files }: { files: Pull["files"] }) {
714 if (files.length === 0) return null;
715 const additions = files.reduce((sum, file) => sum + file.additions, 0);
716 const deletions = files.reduce((sum, file) => sum + file.deletions, 0);
717 return (
718 <span className="flex shrink-0 items-center gap-1.5 font-mono text-xs text-faint">
719 <span>
720 {files.length} {files.length === 1 ? "file" : "files"}
721 </span>
722 <span className="text-success">+{additions}</span>
723 <span className="text-danger">−{deletions}</span>
724 </span>
725 );
726}
727
728/** The words of a Markdown text, without its markup, for a one-line preview. */
729export function plainText(markdown: string): string {
730 return markdown
731 .replace(/```[\s\S]*?```/g, " ")
732 .replace(/^\s{0,3}(#{1,6}|[-*+]|\d+\.)\s+/gm, "")
733 .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1")
734 .replace(/[*_`~]/g, "")
735 .replace(/\s+/g, " ")
736 .trim();
737}