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

pullRequestPresentation.tsx

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