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

pullRequestPresentation.tsx

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