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

pullRequestPresentation.tsx

555 lines16.6 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} from "@t3tools/contracts";
12import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
13import {
14 CircleCheckIcon,
15 CircleDashedIcon,
16 CircleDotIcon,
17 CircleSlashIcon,
18 CircleXIcon,
19 UserCheckIcon,
20 UserRoundIcon,
21 UserRoundXIcon,
22} from "lucide-react";
23import { Children, type CSSProperties, isValidElement, type ReactNode, useState } from "react";
24​
25import { cn } from "~/lib/utils";
26​
27import { Badge } from "../ui/badge";
28import { InlineButton } from "../ui/button";
29import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
30import type { PullRequestReviewOutcome } from "./pullRequestDetail.logic";
31import { pullRequestLabelColor } from "./pullRequestList.logic";
32import {
33 PULL_REQUEST_STATE_PRESENTATION,
34 PullRequestGlyph,
35 type PullRequestStatePresentation,
36 type PullRequestGlyphIcon,
37} from "./pullRequestIcons";
38​
39export function PullRequestLabelChip({
40 label,
41 size = "sm",
42 className,
43 children,
44}: {
45 label: Pick<PullRequestLabel, "name" | "color">;
46 size?: "sm" | "default";
47 className?: string;
48 children?: ReactNode;
49}) {
50 const color = pullRequestLabelColor(label.color);
51 return (
52 <Badge
53 size={size}
54 variant={color ? "label" : "secondary"}
55 className={cn("min-w-0 max-w-40 shrink justify-start", className)}
56 {...(color ? { style: { "--label": color } as CSSProperties } : {})}
57 >
58 <span className="truncate">{label.name}</span>
59 {children}
60 </Badge>
61 );
63​
64function reviewDecisionPresentation(decision: PullRequestReviewDecision) {
65 switch (decision) {
66 case "approved":
67 return {
68 Icon: UserCheckIcon,
69 label: "Approved",
70 toneClassName: CHECK_STATUS_PRESENTATION.success.toneClassName,
71 };
72 case "changes-requested":
73 return {
74 Icon: UserRoundXIcon,
75 label: "Changes requested",
76 toneClassName: "text-amber-600/90 dark:text-amber-400/80",
77 };
78 case "review-required":
79 return {
80 Icon: UserRoundIcon,
81 label: "Awaiting review",
82 toneClassName: "text-muted-foreground/60",
83 };
84 }
86​
87export function PullRequestReviewDecisionGlyph({
88 decision,
89}: {
90 decision: PullRequestReviewDecision;
91}) {
92 const presentation = reviewDecisionPresentation(decision);
93 return (
94 <Tooltip>
95 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
96 <presentation.Icon aria-hidden className={cn("size-3.5", presentation.toneClassName)} />
97 <span className="sr-only">{presentation.label}</span>
98 </TooltipTrigger>
99 <TooltipPopup>{presentation.label}</TooltipPopup>
100 </Tooltip>
101 );
103​
104export function resolvePullRequestState(input: {
105 readonly state: PullRequestState;
106 readonly isDraft: boolean;
107}): PullRequestStatePresentation {
108 const key = input.state === "open" && input.isDraft ? "draft" : input.state;
109 return PULL_REQUEST_STATE_PRESENTATION[key];
111​
112export interface PullRequestConflictPresentation {
113 readonly label: string;
114 readonly toneClassName: string;
115 readonly Icon: PullRequestGlyphIcon;
117​
118function resolvePullRequestConflict(input: {
119 readonly state: PullRequestState;
120 readonly isDraft: boolean;
121 readonly mergeability?: PullRequestMergeability;
122 readonly baseBranch?: string;
123}): PullRequestConflictPresentation | null {
124 if (input.state !== "open" || input.isDraft || input.mergeability !== "conflicting") {
125 return null;
126 }
127 return {
128 label: input.baseBranch ? `Conflicts with ${input.baseBranch}` : "Has conflicts",
129 toneClassName: "text-destructive",
130 Icon: PullRequestGlyph.conflicting,
131 };
133​
134export function PullRequestStateGlyph({
135 state,
136 isDraft,
137 className,
138}: {
139 state: PullRequestState;
140 isDraft: boolean;
141 className?: string;
142}) {
143 const presentation = resolvePullRequestState({ state, isDraft });
144 return (
145 <Tooltip>
146 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
147 <presentation.Icon
148 role="img"
149 aria-label={presentation.label}
150 className={cn("size-4 shrink-0", presentation.toneClassName, className)}
151 />
152 </TooltipTrigger>
153 <TooltipPopup>{presentation.label}</TooltipPopup>
154 </Tooltip>
155 );
157​
158export function PullRequestConflictGlyph({
159 state,
160 isDraft,
161 mergeability,
162 baseBranch,
163 className,
164}: {
165 state: PullRequestState;
166 isDraft: boolean;
167 mergeability?: PullRequestMergeability;
168 baseBranch?: string;
169 className?: string;
170}) {
171 const presentation = resolvePullRequestConflict({
172 state,
173 isDraft,
174 ...(mergeability === undefined ? {} : { mergeability }),
175 ...(baseBranch === undefined ? {} : { baseBranch }),
176 });
177 if (presentation === null) return null;
178 return (
179 <Tooltip>
180 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
181 <presentation.Icon
182 role="img"
183 aria-label={presentation.label}
184 className={cn("size-4 shrink-0", presentation.toneClassName, className)}
185 />
186 </TooltipTrigger>
187 <TooltipPopup>{presentation.label}</TooltipPopup>
188 </Tooltip>
189 );
191​
192const CHECK_STATUS_PRESENTATION = {
193 pending: { label: "Running", Icon: Spinner, toneClassName: "text-amber-500" },
194 "action-required": {
195 label: "Awaiting action",
196 Icon: CircleDotIcon,
197 toneClassName: "text-amber-600 dark:text-amber-400/90",
198 },
199 success: {
200 label: "Passed",
201 Icon: CircleCheckIcon,
202 toneClassName: "text-emerald-600 dark:text-emerald-300/90",
203 },
204 failure: { label: "Failed", Icon: CircleXIcon, toneClassName: "text-destructive" },
205 cancelled: { label: "Cancelled", Icon: CircleXIcon, toneClassName: "text-destructive" },
206 skipped: { label: "Skipped", Icon: CircleSlashIcon, toneClassName: "text-muted-foreground/70" },
207 neutral: { label: "Neutral", Icon: CircleDashedIcon, toneClassName: "text-muted-foreground/70" },
208} as const satisfies Record<
209 PullRequestCheckStatus,
210 { label: string; Icon: typeof CircleCheckIcon | typeof Spinner; toneClassName: string }
211>;
212​
213function isWorkflowApprovalCheck(check: Pick<PullRequestCheck, "status" | "url">): boolean {
214 return (
215 check.status === "action-required" &&
216 check.url !== null &&
217 /\/actions\/runs\/\d+(?:\/|$)/u.test(check.url)
218 );
220​
221export function pullRequestCheckStatusLabel(
222 check: Pick<PullRequestCheck, "status" | "url">,
223): string {
224 return isWorkflowApprovalCheck(check)
225 ? "Awaiting approval"
226 : CHECK_STATUS_PRESENTATION[check.status].label;
228​
229export function PullRequestCheckStatusIcon({ status }: { status: PullRequestCheckStatus }) {
230 const presentation = CHECK_STATUS_PRESENTATION[status];
231 return (
232 <presentation.Icon
233 aria-hidden
234 className={cn("size-3.5 shrink-0", presentation.toneClassName)}
235 />
236 );
238​
239const CHECKS_STATE_PRESENTATION = {
240 passing: {
241 label: "All checks have passed",
242 Icon: CircleCheckIcon,
243 toneClassName: CHECK_STATUS_PRESENTATION.success.toneClassName,
244 },
245 failing: {
246 label: "Some checks were not successful",
247 Icon: CircleXIcon,
248 toneClassName: "text-destructive",
249 },
250 pending: {
251 label: "Some checks haven't completed yet",
252 Icon: CircleDotIcon,
253 toneClassName: "text-amber-600 dark:text-amber-400/90",
254 },
255} as const satisfies Record<
256 PullRequestChecksState,
257 { label: string; Icon: typeof CircleCheckIcon; toneClassName: string }
258>;
259​
260export function pullRequestChecksStatePresentation(state: PullRequestChecksState) {
261 return CHECKS_STATE_PRESENTATION[state];
263​
264export function pullRequestChecksState(
265 checks: ReadonlyArray<PullRequestCheck>,
266): PullRequestChecksState | null {
267 if (checks.length === 0) return null;
268 const statuses = new Set(checks.map((check) => check.status));
269 if (statuses.has("failure") || statuses.has("cancelled")) return "failing";
270 if (statuses.has("pending") || statuses.has("action-required")) return "pending";
271 return statuses.has("success") ? "passing" : null;
273​
274const REVIEW_OUTCOME_PRESENTATION = {
275 approved: {
276 label: "Approved",
277 Icon: CircleCheckIcon,
278 toneClassName: "text-emerald-600 dark:text-emerald-300/90",
279 ringClassName: "ring-2 ring-emerald-500 dark:ring-emerald-400",
280 staleRingClassName:
281 "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))]",
282 fillClassName: "fill-emerald-500 dark:fill-emerald-400",
283 badgeVariant: "success",
284 },
285 "changes-requested": {
286 label: "Changes requested",
287 Icon: CircleXIcon,
288 toneClassName: "text-destructive",
289 ringClassName: "ring-2 ring-destructive",
290 staleRingClassName: "ring-2 ring-[color-mix(in_srgb,var(--destructive)_35%,var(--background))]",
291 fillClassName: "fill-destructive",
292 badgeVariant: "error",
293 },
294 dismissed: {
295 label: "Review dismissed",
296 Icon: CircleDashedIcon,
297 toneClassName: "text-muted-foreground/70",
298 ringClassName: "ring-2 ring-muted-foreground/60",
299 staleRingClassName:
300 "ring-2 ring-[color-mix(in_srgb,var(--contrast-muted-foreground)_30%,var(--background))]",
301 fillClassName: "fill-muted-foreground",
302 badgeVariant: "outline",
303 },
304} as const satisfies Record<
305 PullRequestReviewOutcome,
306 {
307 label: string;
308 Icon: typeof CircleCheckIcon;
309 toneClassName: string;
310 ringClassName: string;
311 staleRingClassName: string;
312 fillClassName: string;
313 badgeVariant: "success" | "error" | "outline";
314 }
315>;
316​
317export function pullRequestReviewOutcomeToneClassName(outcome: PullRequestReviewOutcome): string {
318 return REVIEW_OUTCOME_PRESENTATION[outcome].toneClassName;
320​
321// Mix rings with the background to prevent avatars showing through their overlap.
322export function pullRequestReviewOutcomeRingClassName(
323 outcome: PullRequestReviewOutcome,
324 stale = false,
325): string {
326 const presentation = REVIEW_OUTCOME_PRESENTATION[outcome];
327 return stale ? presentation.staleRingClassName : presentation.ringClassName;
329​
330export function pullRequestReviewOutcomeStaleLabel(outcome: PullRequestReviewOutcome): string {
331 return `${REVIEW_OUTCOME_PRESENTATION[outcome].label} earlier changes`;
333​
334export function PullRequestReviewOutcomeIcon({
335 outcome,
336 className,
337}: {
338 outcome: PullRequestReviewOutcome;
339 className?: string;
340}) {
341 const presentation = REVIEW_OUTCOME_PRESENTATION[outcome];
342 return (
343 <presentation.Icon
344 aria-hidden
345 className={cn("size-3.5 shrink-0", presentation.toneClassName, className)}
346 />
347 );
349​
350// Ring color alone blends into colorful bot avatars; the glyph gives each verdict a shape.
351export function PullRequestReviewOutcomeAvatarBadge({
352 outcome,
353 stale = false,
354}: {
355 outcome: PullRequestReviewOutcome;
356 stale?: boolean;
357}) {
358 const presentation = REVIEW_OUTCOME_PRESENTATION[outcome];
359 return (
360 <presentation.Icon
361 aria-hidden
362 strokeWidth={3}
363 className={cn(
364 "absolute -right-1 -bottom-1 size-3 text-background",
365 presentation.fillClassName,
366 stale && "opacity-50",
367 )}
368 />
369 );
371​
372export function pullRequestReviewOutcomeLabel(outcome: PullRequestReviewOutcome): string {
373 return REVIEW_OUTCOME_PRESENTATION[outcome].label;
375​
376export function PullRequestReviewOutcomeBadge({
377 outcome,
378 className,
379}: {
380 outcome: PullRequestReviewOutcome;
381 className?: string;
382}) {
383 const presentation = REVIEW_OUTCOME_PRESENTATION[outcome];
384 return (
385 <Badge size="sm" variant={presentation.badgeVariant} className={className}>
386 <span className="inline-flex items-baseline gap-1">
387 <presentation.Icon aria-hidden className="size-3 self-center" />
388 <span>{presentation.label}</span>
389 </span>
390 </Badge>
391 );
393​
394export function PullRequestActorAvatar({
395 actor,
396 className,
397}: {
398 actor: PullRequestActor | null;
399 className?: string;
400}) {
401 const login = actor?.login ?? "ghost";
402 const avatarUrl = actor?.avatarUrl ?? null;
403 const [failedAvatarUrl, setFailedAvatarUrl] = useState<string | null>(null);
404 return avatarUrl === null || failedAvatarUrl === avatarUrl ? (
405 <span
406 aria-hidden
407 className={cn(
408 "flex size-4 shrink-0 items-center justify-center rounded-full bg-muted text-3xs font-medium text-muted-foreground",
409 className,
410 )}
411 >
412 {login.slice(0, 1).toUpperCase()}
413 </span>
414 ) : (
415 <img
416 aria-hidden
417 alt=""
418 src={avatarUrl}
419 loading="lazy"
420 className={cn("size-4 shrink-0 rounded-full bg-muted object-cover", className)}
421 onError={() => setFailedAvatarUrl(avatarUrl)}
422 />
423 );
425​
426export function PullRequestActorLabel({
427 actor,
428 className,
429 variant = "label",
430 tooltip = true,
431 profileUrl,
432}: {
433 actor: PullRequestActor | null;
434 className?: string;
435 variant?: "label" | "avatar";
436 tooltip?: boolean;
437 profileUrl?: string | null;
438}) {
439 const login = actor?.login ?? "ghost";
440 const label = (
441 <span className={cn("flex min-w-0 items-baseline", variant === "label" && "gap-1.5")}>
442 <PullRequestActorAvatar actor={actor} className="self-center" />
443 <span className={variant === "label" ? "truncate font-medium text-foreground" : "sr-only"}>
444 {login}
445 </span>
446 </span>
447 );
448 const placement = cn("flex min-w-0 shrink", className);
449 if (!tooltip) return <span className={placement}>{label}</span>;
450 return (
451 <Tooltip>
452 <TooltipTrigger
453 render={
454 profileUrl ? (
455 <InlineButton
456 className={placement}
457 render={
458 <a
459 href={profileUrl}
460 target="_blank"
461 rel="noopener noreferrer"
462 aria-label={`Open ${login}'s profile`}
463 />
464 }
465 />
466 ) : (
467 <span className={placement} />
468 )
469 }
470 >
471 {label}
472 </TooltipTrigger>
473 <TooltipPopup side="top">
474 {actor?.name && actor.name !== login ? `${actor.name} (@${login})` : login}
475 {profileUrl ? " · Open profile" : ""}
476 </TooltipPopup>
477 </Tooltip>
478 );
480​
481export function PullRequestDiffStat({
482 additions,
483 deletions,
484 className,
485}: {
486 additions: number;
487 deletions: number;
488 className?: string;
489}) {
490 if (additions === 0 && deletions === 0) {
491 return null;
492 }
493 return (
494 <span className={cn("inline-flex items-baseline gap-1 tabular-nums", className)}>
495 <span className="text-diff-addition-foreground">+{formatDiffCount(additions)}</span>
496 <span className="text-diff-deletion">-{formatDiffCount(deletions)}</span>
497 </span>
498 );
500​
501function separatorKey(segment: ReactNode): string {
502 return `separator:${isValidElement(segment) ? String(segment.key) : String(segment)}`;
504​
505export function PullRequestMetaLine({
506 children,
507 className,
508}: {
509 children: ReactNode;
510 className?: string;
511}) {
512 const segments = Children.toArray(children);
513 return (
514 <span className={cn("flex min-w-0 items-center gap-1.5", className)}>
515 {segments.flatMap((segment, index) =>
516 index === 0
517 ? segment
518 : [
519 <span
520 aria-hidden
521 className="shrink-0 text-muted-foreground/50"
522 key={separatorKey(segment)}
523 >
524 ·
525 </span>,
526 segment,
527 ],
528 )}
529 </span>
530 );
532​
533export function summarizePullRequestChecks(checks: ReadonlyArray<PullRequestCheck>): string {
534 if (checks.length === 0) return "No checks reported";
535 const actionRequired = checks.filter((check) => check.status === "action-required");
536 const workflowApprovalRequired = actionRequired.filter(isWorkflowApprovalCheck).length;
537 const otherActionRequired = actionRequired.length - workflowApprovalRequired;
538 const failed = checks.filter(
539 (check) => check.status === "failure" || check.status === "cancelled",
540 ).length;
541 const pending = checks.filter((check) => check.status === "pending").length;
542 const passed = checks.filter((check) => check.status === "success").length;
543 if (failed > 0) return `${failed} of ${checks.length} failing`;
544 if (workflowApprovalRequired > 0 && otherActionRequired > 0) {
545 return `${workflowApprovalRequired} ${workflowApprovalRequired === 1 ? "workflow" : "workflows"} and ${otherActionRequired} ${otherActionRequired === 1 ? "check" : "checks"} awaiting action`;
546 }
547 if (workflowApprovalRequired > 0) {
548 return `${workflowApprovalRequired} ${workflowApprovalRequired === 1 ? "workflow" : "workflows"} awaiting approval`;
549 }
550 if (otherActionRequired > 0) {
551 return `${otherActionRequired} ${otherActionRequired === 1 ? "check" : "checks"} awaiting action`;
552 }
553 if (pending > 0) return `${pending} of ${checks.length} running`;
554 return passed === checks.length ? "All checks passed" : `${passed} of ${checks.length} passing`;