Open History to see the last commit
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 );
62}
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 }
85}
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 );
102}
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];
110}
111
112export interface PullRequestConflictPresentation {
113 readonly label: string;
114 readonly toneClassName: string;
115 readonly Icon: PullRequestGlyphIcon;
116}
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 };
132}
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 );
156}
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 );
190}
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 );
219}
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;
227}
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 );
237}
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];
262}
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;
272}
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 badgeVariant: "success",
283 },
284 "changes-requested": {
285 label: "Changes requested",
286 Icon: CircleXIcon,
287 toneClassName: "text-destructive",
288 ringClassName: "ring-2 ring-destructive",
289 staleRingClassName: "ring-2 ring-[color-mix(in_srgb,var(--destructive)_35%,var(--background))]",
290 badgeVariant: "error",
291 },
292 dismissed: {
293 label: "Review dismissed",
294 Icon: CircleDashedIcon,
295 toneClassName: "text-muted-foreground/70",
296 ringClassName: "ring-2 ring-muted-foreground/60",
297 staleRingClassName:
298 "ring-2 ring-[color-mix(in_srgb,var(--contrast-muted-foreground)_30%,var(--background))]",
299 badgeVariant: "outline",
300 },
301} as const satisfies Record<
302 PullRequestReviewOutcome,
303 {
304 label: string;
305 Icon: typeof CircleCheckIcon;
306 toneClassName: string;
307 ringClassName: string;
308 staleRingClassName: string;
309 badgeVariant: "success" | "error" | "outline";
310 }
311>;
312
313export function pullRequestReviewOutcomeToneClassName(outcome: PullRequestReviewOutcome): string {
314 return REVIEW_OUTCOME_PRESENTATION[outcome].toneClassName;
315}
316
317// Mix rings with the background to prevent avatars showing through their overlap.
318export function pullRequestReviewOutcomeRingClassName(
319 outcome: PullRequestReviewOutcome,
320 stale = false,
321): string {
322 const presentation = REVIEW_OUTCOME_PRESENTATION[outcome];
323 return stale ? presentation.staleRingClassName : presentation.ringClassName;
324}
325
326export function pullRequestReviewOutcomeStaleLabel(outcome: PullRequestReviewOutcome): string {
327 return `${REVIEW_OUTCOME_PRESENTATION[outcome].label} earlier changes`;
328}
329
330export function PullRequestReviewOutcomeIcon({
331 outcome,
332 className,
333}: {
334 outcome: PullRequestReviewOutcome;
335 className?: string;
336}) {
337 const presentation = REVIEW_OUTCOME_PRESENTATION[outcome];
338 return (
339 <presentation.Icon
340 aria-hidden
341 className={cn("size-3.5 shrink-0", presentation.toneClassName, className)}
342 />
343 );
344}
345
346export function pullRequestReviewOutcomeLabel(outcome: PullRequestReviewOutcome): string {
347 return REVIEW_OUTCOME_PRESENTATION[outcome].label;
348}
349
350export function PullRequestReviewOutcomeBadge({
351 outcome,
352 className,
353}: {
354 outcome: PullRequestReviewOutcome;
355 className?: string;
356}) {
357 const presentation = REVIEW_OUTCOME_PRESENTATION[outcome];
358 return (
359 <Badge size="sm" variant={presentation.badgeVariant} className={className}>
360 <span className="inline-flex items-baseline gap-1">
361 <presentation.Icon aria-hidden className="size-3 self-center" />
362 <span>{presentation.label}</span>
363 </span>
364 </Badge>
365 );
366}
367
368export function PullRequestActorAvatar({
369 actor,
370 className,
371}: {
372 actor: PullRequestActor | null;
373 className?: string;
374}) {
375 const login = actor?.login ?? "ghost";
376 const avatarUrl = actor?.avatarUrl ?? null;
377 const [failedAvatarUrl, setFailedAvatarUrl] = useState<string | null>(null);
378 return avatarUrl === null || failedAvatarUrl === avatarUrl ? (
379 <span
380 aria-hidden
381 className={cn(
382 "flex size-4 shrink-0 items-center justify-center rounded-full bg-muted text-3xs font-medium text-muted-foreground",
383 className,
384 )}
385 >
386 {login.slice(0, 1).toUpperCase()}
387 </span>
388 ) : (
389 <img
390 aria-hidden
391 alt=""
392 src={avatarUrl}
393 loading="lazy"
394 className={cn("size-4 shrink-0 rounded-full bg-muted object-cover", className)}
395 onError={() => setFailedAvatarUrl(avatarUrl)}
396 />
397 );
398}
399
400export function PullRequestActorLabel({
401 actor,
402 className,
403 variant = "label",
404 tooltip = true,
405 profileUrl,
406}: {
407 actor: PullRequestActor | null;
408 className?: string;
409 variant?: "label" | "avatar";
410 tooltip?: boolean;
411 profileUrl?: string | null;
412}) {
413 const login = actor?.login ?? "ghost";
414 const label = (
415 <span className={cn("flex min-w-0 items-baseline", variant === "label" && "gap-1.5")}>
416 <PullRequestActorAvatar actor={actor} className="self-center" />
417 <span className={variant === "label" ? "truncate font-medium text-foreground" : "sr-only"}>
418 {login}
419 </span>
420 </span>
421 );
422 const placement = cn("flex min-w-0 shrink", className);
423 if (!tooltip) return <span className={placement}>{label}</span>;
424 return (
425 <Tooltip>
426 <TooltipTrigger
427 render={
428 profileUrl ? (
429 <InlineButton
430 className={placement}
431 render={
432 <a
433 href={profileUrl}
434 target="_blank"
435 rel="noopener noreferrer"
436 aria-label={`Open ${login}'s profile`}
437 />
438 }
439 />
440 ) : (
441 <span className={placement} />
442 )
443 }
444 >
445 {label}
446 </TooltipTrigger>
447 <TooltipPopup side="top">
448 {actor?.name && actor.name !== login ? `${actor.name} (@${login})` : login}
449 {profileUrl ? " · Open profile" : ""}
450 </TooltipPopup>
451 </Tooltip>
452 );
453}
454
455export function PullRequestDiffStat({
456 additions,
457 deletions,
458 className,
459}: {
460 additions: number;
461 deletions: number;
462 className?: string;
463}) {
464 if (additions === 0 && deletions === 0) {
465 return null;
466 }
467 return (
468 <span className={cn("inline-flex items-baseline gap-1 tabular-nums", className)}>
469 <span className="text-diff-addition-foreground">+{formatDiffCount(additions)}</span>
470 <span className="text-diff-deletion">-{formatDiffCount(deletions)}</span>
471 </span>
472 );
473}
474
475function separatorKey(segment: ReactNode): string {
476 return `separator:${isValidElement(segment) ? String(segment.key) : String(segment)}`;
477}
478
479export function PullRequestMetaLine({
480 children,
481 className,
482}: {
483 children: ReactNode;
484 className?: string;
485}) {
486 const segments = Children.toArray(children);
487 return (
488 <span className={cn("flex min-w-0 items-center gap-1.5", className)}>
489 {segments.flatMap((segment, index) =>
490 index === 0
491 ? segment
492 : [
493 <span
494 aria-hidden
495 className="shrink-0 text-muted-foreground/50"
496 key={separatorKey(segment)}
497 >
498 ·
499 </span>,
500 segment,
501 ],
502 )}
503 </span>
504 );
505}
506
507export function summarizePullRequestChecks(checks: ReadonlyArray<PullRequestCheck>): string {
508 if (checks.length === 0) return "No checks reported";
509 const actionRequired = checks.filter((check) => check.status === "action-required");
510 const workflowApprovalRequired = actionRequired.filter(isWorkflowApprovalCheck).length;
511 const otherActionRequired = actionRequired.length - workflowApprovalRequired;
512 const failed = checks.filter(
513 (check) => check.status === "failure" || check.status === "cancelled",
514 ).length;
515 const pending = checks.filter((check) => check.status === "pending").length;
516 const passed = checks.filter((check) => check.status === "success").length;
517 if (failed > 0) return `${failed} of ${checks.length} failing`;
518 if (workflowApprovalRequired > 0 && otherActionRequired > 0) {
519 return `${workflowApprovalRequired} ${workflowApprovalRequired === 1 ? "workflow" : "workflows"} and ${otherActionRequired} ${otherActionRequired === 1 ? "check" : "checks"} awaiting action`;
520 }
521 if (workflowApprovalRequired > 0) {
522 return `${workflowApprovalRequired} ${workflowApprovalRequired === 1 ? "workflow" : "workflows"} awaiting approval`;
523 }
524 if (otherActionRequired > 0) {
525 return `${otherActionRequired} ${otherActionRequired === 1 ? "check" : "checks"} awaiting action`;
526 }
527 if (pending > 0) return `${pending} of ${checks.length} running`;
528 return passed === checks.length ? "All checks passed" : `${passed} of ${checks.length} passing`;
529}