Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

pullRequestPresentation.tsx

684 lines20.2 KB

1import { Spinner } from "~/components/ui/spinner";
2import type {
3 PullRequestActor,
4 PullRequestCheck,
5 PullRequestCheckStatus,
6 PullRequestChecksState,
7 PullRequestLabel,
8 PullRequestMergeability,
9 PullRequestReviewDecision,
10 PullRequestState,
11 ScopedThreadRef,
12} from "@t3tools/contracts";
13import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
14import {
15 CircleCheckIcon,
16 CircleDashedIcon,
17 CircleDotIcon,
18 CircleSlashIcon,
19 CircleXIcon,
20 OctagonXIcon,
21 UserCheckIcon,
22 UserRoundIcon,
23 UserRoundXIcon,
24} from "lucide-react";
25import { msg, useGT, useMessages } from "gt-react";
26import { Children, type CSSProperties, isValidElement, type ReactNode, useState } from "react";
27​
28import { m, type MessageResolver } from "~/i18n/messages";
29import { useOpenLink } from "~/browser/useOpenLink";
30import { cn } from "~/lib/utils";
31​
32import { Badge } from "../ui/badge";
33import { InlineButton } from "../ui/button";
34import { SharedTooltipTrigger } from "../ui/shared-tooltip";
35import type { PullRequestReviewOutcome } from "./pullRequestDetail.logic";
36import { pullRequestLabelColor } from "./pullRequestList.logic";
37import {
38 PULL_REQUEST_STATE_PRESENTATION,
39 PullRequestGlyph,
40 type PullRequestStatePresentation,
41 type PullRequestGlyphIcon,
42} from "./pullRequestIcons";
43​
44export function PullRequestLabelChip({
45 label,
46 size = "sm",
47 className,
48 focusable = false,
49 children,
50}: {
51 label: Pick<PullRequestLabel, "name" | "color" | "description">;
52 size?: "sm" | "default";
53 className?: string;
54 focusable?: boolean;
55 children?: ReactNode;
56}) {
57 const color = pullRequestLabelColor(label.color);
58 const badge = (
59 <Badge
60 size={size}
61 variant={color ? "label" : "secondary"}
62 className={cn("min-w-0 max-w-40 shrink justify-start", className)}
63 {...(focusable && label.description ? { tabIndex: 0 } : {})}
64 {...(color ? { style: { "--label": color } as CSSProperties } : {})}
65 >
66 <span className="truncate">{label.name}</span>
67 {label.description ? <span className="sr-only">: {label.description}</span> : null}
68 {children}
69 </Badge>
70 );
71 if (!label.description) return badge;
72 return <SharedTooltipTrigger render={badge} label={label.description} />;
74​
75function reviewDecisionPresentation(decision: PullRequestReviewDecision) {
76 switch (decision) {
77 case "approved":
78 return {
79 Icon: UserCheckIcon,
80 label: msg("Approved", { $context: "review decision" }),
81 toneClassName: CHECK_STATUS_PRESENTATION.success.toneClassName,
82 };
83 case "changes-requested":
84 return {
85 Icon: UserRoundXIcon,
86 label: msg("Changes requested"),
87 toneClassName: "text-amber-600/90 dark:text-amber-400/80",
88 };
89 case "review-required":
90 return {
91 Icon: UserRoundIcon,
92 label: msg("Awaiting review"),
93 toneClassName: "text-muted-foreground/60",
94 };
95 }
97​
98export function PullRequestReviewDecisionGlyph({
99 decision,
100}: {
101 decision: PullRequestReviewDecision;
102}) {
103 const m = useMessages();
104 const presentation = reviewDecisionPresentation(decision);
105 return (
106 <SharedTooltipTrigger
107 render={<span className="inline-flex shrink-0" />}
108 label={m(presentation.label)}
109 >
110 <presentation.Icon aria-hidden className={cn("size-3.5", presentation.toneClassName)} />
111 <span className="sr-only">{m(presentation.label)}</span>
112 </SharedTooltipTrigger>
113 );
115​
116export function resolvePullRequestState(
117 input: {
118 readonly state: PullRequestState;
119 readonly isDraft: boolean;
120 },
121 resolve: MessageResolver = m,
122): PullRequestStatePresentation {
123 const key = input.state === "open" && input.isDraft ? "draft" : input.state;
124 const presentation = PULL_REQUEST_STATE_PRESENTATION[key];
125 return { ...presentation, label: resolve(presentation.label) };
127​
128export interface PullRequestConflictPresentation {
129 readonly label: string;
130 readonly toneClassName: string;
131 readonly Icon: PullRequestGlyphIcon;
133​
134function resolvePullRequestConflict(
135 input: {
136 readonly state: PullRequestState;
137 readonly isDraft: boolean;
138 readonly mergeability?: PullRequestMergeability;
139 readonly baseBranch?: string;
140 },
141 resolve: MessageResolver,
142): PullRequestConflictPresentation | null {
143 if (input.state !== "open" || input.isDraft || input.mergeability !== "conflicting") {
144 return null;
145 }
146 return {
147 label: input.baseBranch
148 ? resolve(msg("Conflicts with {baseBranch}", { baseBranch: input.baseBranch }))
149 : resolve(msg("Has conflicts")),
150 toneClassName: "text-destructive",
151 Icon: PullRequestGlyph.conflicting,
152 };
154​
155export function PullRequestStateGlyph({
156 state,
157 isDraft,
158 className,
159}: {
160 state: PullRequestState;
161 isDraft: boolean;
162 className?: string;
163}) {
164 const m = useMessages();
165 const presentation = resolvePullRequestState({ state, isDraft }, m);
166 return (
167 <SharedTooltipTrigger
168 render={<span className="inline-flex shrink-0" />}
169 label={presentation.label}
170 >
171 <presentation.Icon
172 role="img"
173 aria-label={presentation.label}
174 className={cn("size-4 shrink-0", presentation.toneClassName, className)}
175 />
176 </SharedTooltipTrigger>
177 );
179​
180export function PullRequestConflictGlyph({
181 state,
182 isDraft,
183 mergeability,
184 baseBranch,
185 className,
186}: {
187 state: PullRequestState;
188 isDraft: boolean;
189 mergeability?: PullRequestMergeability;
190 baseBranch?: string;
191 className?: string;
192}) {
193 const m = useMessages();
194 const presentation = resolvePullRequestConflict(
195 {
196 state,
197 isDraft,
198 ...(mergeability === undefined ? {} : { mergeability }),
199 ...(baseBranch === undefined ? {} : { baseBranch }),
200 },
201 m,
202 );
203 if (presentation === null) return null;
204 return (
205 <SharedTooltipTrigger
206 render={<span className="inline-flex shrink-0" />}
207 label={presentation.label}
208 >
209 <presentation.Icon
210 role="img"
211 aria-label={presentation.label}
212 className={cn("size-4 shrink-0", presentation.toneClassName, className)}
213 />
214 </SharedTooltipTrigger>
215 );
217​
218const CHECK_STATUS_PRESENTATION = {
219 pending: {
220 label: msg("Running", { $context: "check status" }),
221 Icon: Spinner,
222 toneClassName: "text-amber-500",
223 },
224 "action-required": {
225 label: msg("Awaiting action"),
226 Icon: CircleDotIcon,
227 toneClassName: "text-amber-600 dark:text-amber-400/90",
228 },
229 success: {
230 label: msg("Passed", { $context: "check status" }),
231 Icon: CircleCheckIcon,
232 toneClassName: "text-emerald-600 dark:text-emerald-300/90",
233 },
234 failure: {
235 label: msg("Failed", { $context: "check status" }),
236 Icon: CircleXIcon,
237 toneClassName: "text-destructive",
238 },
239 cancelled: {
240 label: msg("Cancelled", { $context: "check status" }),
241 Icon: OctagonXIcon,
242 toneClassName: "text-muted-foreground/70",
243 },
244 skipped: {
245 label: msg("Skipped", { $context: "check status" }),
246 Icon: CircleSlashIcon,
247 toneClassName: "text-muted-foreground/70",
248 },
249 neutral: {
250 label: msg("Neutral", { $context: "check status" }),
251 Icon: CircleDashedIcon,
252 toneClassName: "text-muted-foreground/70",
253 },
254} as const satisfies Record<
255 PullRequestCheckStatus,
256 { label: string; Icon: typeof CircleCheckIcon | typeof Spinner; toneClassName: string }
257>;
258​
259function isWorkflowApprovalCheck(check: Pick<PullRequestCheck, "status" | "url">): boolean {
260 return (
261 check.status === "action-required" &&
262 check.url !== null &&
263 /\/actions\/runs\/\d+(?:\/|$)/u.test(check.url)
264 );
266​
267export function pullRequestCheckStatusLabel(
268 check: Pick<PullRequestCheck, "status" | "url">,
269 resolve: MessageResolver = m,
270): string {
271 return isWorkflowApprovalCheck(check)
272 ? resolve(msg("Awaiting approval"))
273 : resolve(CHECK_STATUS_PRESENTATION[check.status].label);
275​
276export function PullRequestCheckStatusIcon({ status }: { status: PullRequestCheckStatus }) {
277 const presentation = CHECK_STATUS_PRESENTATION[status];
278 return (
279 <presentation.Icon
280 aria-hidden
281 className={cn("size-3.5 shrink-0", presentation.toneClassName)}
282 />
283 );
285​
286const CHECKS_STATE_PRESENTATION = {
287 passing: {
288 label: msg("All checks have passed"),
289 Icon: CircleCheckIcon,
290 toneClassName: CHECK_STATUS_PRESENTATION.success.toneClassName,
291 },
292 failing: {
293 label: msg("Some checks were not successful"),
294 Icon: CircleXIcon,
295 toneClassName: "text-destructive",
296 },
297 pending: {
298 label: msg("Some checks haven't completed yet"),
299 Icon: CircleDotIcon,
300 toneClassName: "text-amber-600 dark:text-amber-400/90",
301 },
302} as const satisfies Record<
303 PullRequestChecksState,
304 { label: string; Icon: typeof CircleCheckIcon; toneClassName: string }
305>;
306​
307export function pullRequestChecksStatePresentation(
308 state: PullRequestChecksState,
309 resolve: MessageResolver = m,
310) {
311 const presentation = CHECKS_STATE_PRESENTATION[state];
312 return { ...presentation, label: resolve(presentation.label) };
314​
315export function pullRequestChecksState(
316 checks: ReadonlyArray<PullRequestCheck>,
317): PullRequestChecksState | null {
318 if (checks.length === 0) return null;
319 const statuses = new Set(checks.map((check) => check.status));
320 if (statuses.has("failure") || statuses.has("cancelled")) return "failing";
321 if (statuses.has("pending") || statuses.has("action-required")) return "pending";
322 return statuses.has("success") ? "passing" : null;
324​
325const REVIEW_OUTCOME_PRESENTATION = {
326 approved: {
327 label: msg("Approved", { $context: "review outcome" }),
328 staleLabel: msg("Approved earlier changes", {
329 $context: "tooltip: this approval was given before the latest commits were pushed",
330 }),
331 Icon: CircleCheckIcon,
332 toneClassName: "text-emerald-600 dark:text-emerald-300/90",
333 ringClassName: "ring-2 ring-emerald-500 dark:ring-emerald-400",
334 staleRingClassName:
335 "ring-2 ring-[color-mix(in_srgb,var(--color-emerald-500)_35%,var(--background))] dark:ring-[color-mix(in_srgb,var(--color-emerald-400)_35%,var(--background))]",
336 fillClassName: "fill-emerald-500 dark:fill-emerald-400",
337 badgeVariant: "success",
338 },
339 "changes-requested": {
340 label: msg("Changes requested"),
341 staleLabel: msg("Changes requested earlier changes", {
342 $context:
343 "tooltip: the reviewer requested changes on an older version, before the latest commits",
344 }),
345 Icon: CircleXIcon,
346 toneClassName: "text-destructive",
347 ringClassName: "ring-2 ring-destructive",
348 staleRingClassName: "ring-2 ring-[color-mix(in_srgb,var(--destructive)_35%,var(--background))]",
349 fillClassName: "fill-destructive",
350 badgeVariant: "error",
351 },
352 dismissed: {
353 label: msg("Review dismissed"),
354 staleLabel: msg("Review dismissed earlier changes", {
355 $context: "tooltip: a review of an older version, before the latest commits, was dismissed",
356 }),
357 Icon: CircleDashedIcon,
358 toneClassName: "text-muted-foreground/70",
359 ringClassName: "ring-2 ring-muted-foreground/60",
360 staleRingClassName:
361 "ring-2 ring-[color-mix(in_srgb,var(--contrast-muted-foreground)_30%,var(--background))]",
362 fillClassName: "fill-muted-foreground",
363 badgeVariant: "outline",
364 },
365} as const satisfies Record<
366 PullRequestReviewOutcome,
367 {
368 label: string;
369 staleLabel: string;
370 Icon: typeof CircleCheckIcon;
371 toneClassName: string;
372 ringClassName: string;
373 staleRingClassName: string;
374 fillClassName: string;
375 badgeVariant: "success" | "error" | "outline";
376 }
377>;
378​
379export function pullRequestReviewOutcomeToneClassName(outcome: PullRequestReviewOutcome): string {
380 return REVIEW_OUTCOME_PRESENTATION[outcome].toneClassName;
382​
383// Mix rings with the background to prevent avatars showing through their overlap.
384export function pullRequestReviewOutcomeRingClassName(
385 outcome: PullRequestReviewOutcome,
386 stale = false,
387): string {
388 const presentation = REVIEW_OUTCOME_PRESENTATION[outcome];
389 return stale ? presentation.staleRingClassName : presentation.ringClassName;
391​
392export function pullRequestReviewOutcomeStaleLabel(
393 outcome: PullRequestReviewOutcome,
394 resolve: MessageResolver = m,
395): string {
396 return resolve(REVIEW_OUTCOME_PRESENTATION[outcome].staleLabel);
398​
399export function PullRequestReviewOutcomeIcon({
400 outcome,
401 className,
402}: {
403 outcome: PullRequestReviewOutcome;
404 className?: string;
405}) {
406 const presentation = REVIEW_OUTCOME_PRESENTATION[outcome];
407 return (
408 <presentation.Icon
409 aria-hidden
410 className={cn("size-3.5 shrink-0", presentation.toneClassName, className)}
411 />
412 );
414​
415// Ring color alone blends into colorful bot avatars; the glyph gives each verdict a shape.
416export function PullRequestReviewOutcomeAvatarBadge({
417 outcome,
418 stale = false,
419}: {
420 outcome: PullRequestReviewOutcome;
421 stale?: boolean;
422}) {
423 const presentation = REVIEW_OUTCOME_PRESENTATION[outcome];
424 return (
425 <presentation.Icon
426 aria-hidden
427 strokeWidth={3}
428 className={cn(
429 "absolute -right-1 -bottom-1 size-3 text-background",
430 presentation.fillClassName,
431 stale && "opacity-50",
432 )}
433 />
434 );
436​
437export function pullRequestReviewOutcomeLabel(
438 outcome: PullRequestReviewOutcome,
439 resolve: MessageResolver = m,
440): string {
441 return resolve(REVIEW_OUTCOME_PRESENTATION[outcome].label);
443​
444export function PullRequestReviewOutcomeBadge({
445 outcome,
446 className,
447}: {
448 outcome: PullRequestReviewOutcome;
449 className?: string;
450}) {
451 const m = useMessages();
452 const presentation = REVIEW_OUTCOME_PRESENTATION[outcome];
453 return (
454 <Badge size="sm" variant={presentation.badgeVariant} className={className}>
455 <span className="inline-flex items-baseline gap-1">
456 <presentation.Icon aria-hidden className="size-3 self-center" />
457 <span>{m(presentation.label)}</span>
458 </span>
459 </Badge>
460 );
462​
463export function PullRequestActorAvatar({
464 actor,
465 className,
466}: {
467 actor: PullRequestActor | null;
468 className?: string;
469}) {
470 const login = actor?.login ?? "ghost";
471 const avatarUrl = actor?.avatarUrl ?? null;
472 const [failedAvatarUrl, setFailedAvatarUrl] = useState<string | null>(null);
473 return avatarUrl === null || failedAvatarUrl === avatarUrl ? (
474 <span
475 aria-hidden
476 className={cn(
477 "flex size-4 shrink-0 items-center justify-center rounded-full bg-muted text-3xs font-medium text-muted-foreground",
478 className,
479 )}
480 >
481 {[...login][0]?.toUpperCase()}
482 </span>
483 ) : (
484 <img
485 aria-hidden
486 alt=""
487 src={avatarUrl}
488 loading="lazy"
489 className={cn("size-4 shrink-0 rounded-full bg-muted object-cover", className)}
490 onError={() => setFailedAvatarUrl(avatarUrl)}
491 />
492 );
494​
495export function PullRequestActorLabel({
496 actor,
497 className,
498 variant = "label",
499 tooltip = true,
500 profileUrl,
501 threadRef = null,
502}: {
503 actor: PullRequestActor | null;
504 className?: string;
505 variant?: "label" | "avatar";
506 tooltip?: boolean;
507 profileUrl?: string | null;
508 threadRef?: ScopedThreadRef | null;
509}) {
510 const gt = useGT();
511 const openLink = useOpenLink(threadRef);
512 const login = actor?.login ?? "ghost";
513 const label = (
514 <span className={cn("flex min-w-0 items-baseline", variant === "label" && "gap-1.5")}>
515 <PullRequestActorAvatar actor={actor} className="self-center" />
516 <span className={variant === "label" ? "truncate font-medium text-foreground" : "sr-only"}>
517 {login}
518 </span>
519 </span>
520 );
521 const placement = cn("flex min-w-0 shrink", className);
522 if (!tooltip) return <span className={placement}>{label}</span>;
523 return (
524 <SharedTooltipTrigger
525 render={
526 profileUrl ? (
527 <InlineButton
528 className={placement}
529 render={
530 <a
531 href={profileUrl}
532 target="_blank"
533 rel="noopener noreferrer"
534 aria-label={gt("Open {login}'s profile", { login })}
535 />
536 }
537 onClick={(event) => {
538 event.preventDefault();
539 void openLink(profileUrl, { event }).catch(console.error);
540 }}
541 />
542 ) : (
543 <span className={placement} />
544 )
545 }
546 label={
547 <>
548 {actor?.name && actor.name !== login ? `${actor.name} (@${login})` : login}
549 {profileUrl ? ` · ${gt("Open profile")}` : ""}
550 </>
551 }
552 >
553 {label}
554 </SharedTooltipTrigger>
555 );
557​
558export function PullRequestDiffStat({
559 additions,
560 deletions,
561 className,
562}: {
563 additions: number;
564 deletions: number;
565 className?: string;
566}) {
567 if (additions === 0 && deletions === 0) {
568 return null;
569 }
570 return (
571 <span className={cn("inline-flex items-baseline gap-1 tabular-nums", className)}>
572 <span className="text-diff-addition-foreground">+{formatDiffCount(additions)}</span>
573 <span className="text-diff-deletion">-{formatDiffCount(deletions)}</span>
574 </span>
575 );
577​
578function separatorKey(segment: ReactNode): string {
579 return `separator:${isValidElement(segment) ? String(segment.key) : String(segment)}`;
581​
582export function PullRequestMetaLine({
583 children,
584 className,
585}: {
586 children: ReactNode;
587 className?: string;
588}) {
589 const segments = Children.toArray(children);
590 return (
591 <span className={cn("flex min-w-0 items-center gap-1.5", className)}>
592 {segments.flatMap((segment, index) =>
593 index === 0
594 ? segment
595 : [
596 <span
597 aria-hidden
598 className="shrink-0 text-muted-foreground/50"
599 key={separatorKey(segment)}
600 >
601 ·
602 </span>,
603 segment,
604 ],
605 )}
606 </span>
607 );
609​
610/** The short label beside the checks icon; null when every check passed. */
611export function pullRequestChecksCountLabel(
612 checks: ReadonlyArray<PullRequestCheck>,
613 resolve: MessageResolver = m,
614): string | null {
615 const count = (statuses: ReadonlyArray<PullRequestCheckStatus>) =>
616 checks.filter((check) => statuses.includes(check.status)).length;
617 const failed = count(["failure", "cancelled"]);
618 if (failed > 0) {
619 return resolve(
620 msg("{count, plural, one {{count} failed} other {{count} failed}}", { count: failed }),
621 );
622 }
623 const awaitingAction = count(["action-required"]);
624 if (awaitingAction > 0) {
625 return resolve(
626 msg("{count, plural, one {{count} awaiting action} other {{count} awaiting action}}", {
627 count: awaitingAction,
628 }),
629 );
630 }
631 const running = count(["pending"]);
632 if (running > 0) {
633 return resolve(
634 msg("{count, plural, one {{count} running} other {{count} running}}", { count: running }),
635 );
636 }
637 return null;
639​
640export function summarizePullRequestChecks(
641 checks: ReadonlyArray<PullRequestCheck>,
642 resolve: MessageResolver = m,
643): string {
644 if (checks.length === 0) return resolve(msg("No checks reported"));
645 const actionRequired = checks.filter((check) => check.status === "action-required");
646 const workflowApprovalRequired = actionRequired.filter(isWorkflowApprovalCheck).length;
647 const otherActionRequired = actionRequired.length - workflowApprovalRequired;
648 const failed = checks.filter(
649 (check) => check.status === "failure" || check.status === "cancelled",
650 ).length;
651 const pending = checks.filter((check) => check.status === "pending").length;
652 const passed = checks.filter((check) => check.status === "success").length;
653 if (failed > 0)
654 return resolve(msg("{failed} of {total} failing", { failed, total: checks.length }));
655 if (workflowApprovalRequired > 0 && otherActionRequired > 0) {
656 return resolve(
657 msg(
658 "{workflows, plural, one {{workflows} workflow} other {{workflows} workflows}} and {checks, plural, one {{checks} check} other {{checks} checks}} awaiting action",
659 { workflows: workflowApprovalRequired, checks: otherActionRequired },
660 ),
661 );
662 }
663 if (workflowApprovalRequired > 0) {
664 return resolve(
665 msg(
666 "{count, plural, one {{count} workflow awaiting approval} other {{count} workflows awaiting approval}}",
667 { count: workflowApprovalRequired },
668 ),
669 );
670 }
671 if (otherActionRequired > 0) {
672 return resolve(
673 msg(
674 "{count, plural, one {{count} check awaiting action} other {{count} checks awaiting action}}",
675 { count: otherActionRequired },
676 ),
677 );
678 }
679 if (pending > 0)
680 return resolve(msg("{pending} of {total} running", { pending, total: checks.length }));
681 return passed === checks.length
682 ? resolve(msg("All checks passed"))
683 : resolve(msg("{passed} of {total} passing", { passed, total: checks.length }));