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

pullRequestPresentation.tsx

533 lines16.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} 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 <presentation.Icon aria-hidden className="size-3" />
367 {presentation.label}
368 </Badge>
369 );
371​
372export function PullRequestActorAvatar({
373 actor,
374 className,
375}: {
376 actor: PullRequestActor | null;
377 className?: string;
378}) {
379 const login = actor?.login ?? "ghost";
380 const avatarUrl = actor?.avatarUrl ?? null;
381 const [failedAvatarUrl, setFailedAvatarUrl] = useState<string | null>(null);
382 return avatarUrl === null || failedAvatarUrl === avatarUrl ? (
383 <span
384 aria-hidden
385 className={cn(
386 "flex size-4 shrink-0 items-center justify-center rounded-full bg-muted text-3xs font-medium text-muted-foreground",
387 className,
388 )}
389 >
390 {login.slice(0, 1).toUpperCase()}
391 </span>
392 ) : (
393 <img
394 aria-hidden
395 alt=""
396 src={avatarUrl}
397 loading="lazy"
398 className={cn("size-4 shrink-0 rounded-full bg-muted object-cover", className)}
399 onError={() => setFailedAvatarUrl(avatarUrl)}
400 />
401 );
403​
404export function PullRequestActorLabel({
405 actor,
406 className,
407 variant = "label",
408 tooltip = true,
409 profileUrl,
410}: {
411 actor: PullRequestActor | null;
412 className?: string;
413 variant?: "label" | "avatar";
414 tooltip?: boolean;
415 profileUrl?: string | null;
416}) {
417 const login = actor?.login ?? "ghost";
418 const label = (
419 <span className={cn("flex min-w-0 items-center", variant === "label" && "gap-1.5")}>
420 <PullRequestActorAvatar actor={actor} />
421 <span className={variant === "label" ? "truncate font-medium text-foreground" : "sr-only"}>
422 {login}
423 </span>
424 </span>
425 );
426 const placement = cn("flex min-w-0 shrink", className);
427 if (!tooltip) return <span className={placement}>{label}</span>;
428 return (
429 <Tooltip>
430 <TooltipTrigger
431 render={
432 profileUrl ? (
433 <InlineButton
434 className={placement}
435 render={
436 <a
437 href={profileUrl}
438 target="_blank"
439 rel="noopener noreferrer"
440 aria-label={`Open ${login}'s profile`}
441 />
442 }
443 />
444 ) : (
445 <span className={placement} />
446 )
447 }
448 >
449 {label}
450 </TooltipTrigger>
451 <TooltipPopup side="top">
452 {actor?.name && actor.name !== login ? `${actor.name} (@${login})` : login}
453 {profileUrl ? " · Open profile" : ""}
454 </TooltipPopup>
455 </Tooltip>
456 );
458​
459export function PullRequestDiffStat({
460 additions,
461 deletions,
462 className,
463}: {
464 additions: number;
465 deletions: number;
466 className?: string;
467}) {
468 if (additions === 0 && deletions === 0) {
469 return null;
470 }
471 return (
472 <span className={cn("inline-flex items-baseline gap-1 tabular-nums", className)}>
473 <span className="text-diff-addition-foreground">+{formatDiffCount(additions)}</span>
474 <span className="text-diff-deletion">-{formatDiffCount(deletions)}</span>
475 </span>
476 );
478​
479function separatorKey(segment: ReactNode): string {
480 return `separator:${isValidElement(segment) ? String(segment.key) : String(segment)}`;
482​
483export function PullRequestMetaLine({
484 children,
485 className,
486}: {
487 children: ReactNode;
488 className?: string;
489}) {
490 const segments = Children.toArray(children);
491 return (
492 <span className={cn("flex min-w-0 items-center gap-1.5", className)}>
493 {segments.flatMap((segment, index) =>
494 index === 0
495 ? segment
496 : [
497 <span
498 aria-hidden
499 className="shrink-0 text-muted-foreground/50"
500 key={separatorKey(segment)}
501 >
502 ·
503 </span>,
504 segment,
505 ],
506 )}
507 </span>
508 );
510​
511export function summarizePullRequestChecks(checks: ReadonlyArray<PullRequestCheck>): string {
512 if (checks.length === 0) return "No checks reported";
513 const actionRequired = checks.filter((check) => check.status === "action-required");
514 const workflowApprovalRequired = actionRequired.filter(isWorkflowApprovalCheck).length;
515 const otherActionRequired = actionRequired.length - workflowApprovalRequired;
516 const failed = checks.filter(
517 (check) => check.status === "failure" || check.status === "cancelled",
518 ).length;
519 const pending = checks.filter((check) => check.status === "pending").length;
520 const passed = checks.filter((check) => check.status === "success").length;
521 if (failed > 0) return `${failed} of ${checks.length} failing`;
522 if (workflowApprovalRequired > 0 && otherActionRequired > 0) {
523 return `${workflowApprovalRequired} ${workflowApprovalRequired === 1 ? "workflow" : "workflows"} and ${otherActionRequired} ${otherActionRequired === 1 ? "check" : "checks"} awaiting action`;
524 }
525 if (workflowApprovalRequired > 0) {
526 return `${workflowApprovalRequired} ${workflowApprovalRequired === 1 ? "workflow" : "workflows"} awaiting approval`;
527 }
528 if (otherActionRequired > 0) {
529 return `${otherActionRequired} ${otherActionRequired === 1 ? "check" : "checks"} awaiting action`;
530 }
531 if (pending > 0) return `${pending} of ${checks.length} running`;
532 return passed === checks.length ? "All checks passed" : `${passed} of ${checks.length} passing`;