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

pullRequestPresentation.tsx

475 lines15.6 KB

1import type {
2 PullRequestActor,
3 PullRequestCheck,
4 PullRequestCheckStatus,
5 PullRequestChecksState,
6 PullRequestMergeability,
7 PullRequestState,
8} from "@t3tools/contracts";
9import {
10 CircleCheckIcon,
11 CircleDashedIcon,
12 CircleDotIcon,
13 CircleXIcon,
14 GitMergeIcon,
15 GitPullRequestClosedIcon,
16 GitPullRequestDraftIcon,
17 GitPullRequestIcon,
18 LoaderIcon,
19 TriangleAlertIcon,
20} from "lucide-react";
21import { Children, isValidElement, type ReactNode } from "react";
22​
23import { cn } from "~/lib/utils";
24​
25import { Badge } from "../ui/badge";
26import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
27import type { PullRequestReviewOutcome } from "./pullRequestDetail.logic";
28​
29interface StatePresentation {
30 readonly label: string;
31 readonly toneClassName: string;
32 readonly Icon: typeof GitPullRequestIcon;
34​
35/**
36 * How a pull request's state reads on this page. Open, closed and merged use the same ink as
37 * the thread badge in `ThreadStatusIndicators`, so one pull request cannot look like two
38 * different things in two places; draft and conflicts are states that badge never shows.
39 *
40 * Draft outranks conflicts: a draft is not heading for a merge yet, so conflicts only surface
41 * once it is real work.
42 */
43export function resolvePullRequestState(input: {
44 readonly state: PullRequestState;
45 readonly isDraft: boolean;
46 readonly mergeability?: PullRequestMergeability;
47 readonly baseBranch?: string;
48}): StatePresentation {
49 if (input.state === "merged") {
50 return {
51 label: "Merged",
52 toneClassName: "text-violet-600 dark:text-violet-300/90",
53 Icon: GitMergeIcon,
54 };
55 }
56 if (input.state === "closed") {
57 return {
58 label: "Closed",
59 toneClassName: "text-red-600 dark:text-red-300/90",
60 Icon: GitPullRequestClosedIcon,
61 };
62 }
63 if (input.isDraft) {
64 return {
65 label: "Draft",
66 toneClassName: "text-zinc-500 dark:text-zinc-400/80",
67 Icon: GitPullRequestDraftIcon,
68 };
69 }
70 if (input.mergeability === "conflicting") {
71 return {
72 // "Has conflicts" leaves out the one thing a reader wants when the warning triangle catches
73 // their eye, so name the branch it collides with wherever the caller knows it.
74 label: input.baseBranch ? `Conflicts with ${input.baseBranch}` : "Has conflicts",
75 toneClassName: "text-destructive",
76 Icon: TriangleAlertIcon,
77 };
78 }
79 return {
80 label: "Open",
81 toneClassName: "text-emerald-600 dark:text-emerald-300/90",
82 Icon: GitPullRequestIcon,
83 };
85​
86export function PullRequestStateGlyph({
87 state,
88 isDraft,
89 mergeability,
90 baseBranch,
91 className,
92}: {
93 state: PullRequestState;
94 isDraft: boolean;
95 mergeability?: PullRequestMergeability;
96 baseBranch?: string;
97 className?: string;
98}) {
99 const presentation = resolvePullRequestState({
100 state,
101 isDraft,
102 ...(mergeability ? { mergeability } : {}),
103 ...(baseBranch ? { baseBranch } : {}),
104 });
105 return (
106 <Tooltip>
107 {/* The list row is itself a button, so the trigger stays a span: an interactive one would
108 nest a control inside that button and steal the row's click target. */}
109 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
110 <presentation.Icon
111 role="img"
112 aria-label={presentation.label}
113 className={cn("size-4 shrink-0", presentation.toneClassName, className)}
114 />
115 </TooltipTrigger>
116 <TooltipPopup>{presentation.label}</TooltipPopup>
117 </Tooltip>
118 );
120​
121const CHECK_STATUS_PRESENTATION = {
122 pending: { label: "Running", Icon: LoaderIcon, toneClassName: "animate-spin text-amber-500" },
123 "action-required": {
124 label: "Awaiting action",
125 Icon: CircleDotIcon,
126 toneClassName: "text-amber-600 dark:text-amber-400/90",
127 },
128 success: {
129 label: "Passed",
130 Icon: CircleCheckIcon,
131 toneClassName: "text-emerald-600 dark:text-emerald-300/90",
132 },
133 failure: { label: "Failed", Icon: CircleXIcon, toneClassName: "text-destructive" },
134 cancelled: { label: "Cancelled", Icon: CircleXIcon, toneClassName: "text-destructive" },
135 skipped: { label: "Skipped", Icon: CircleDashedIcon, toneClassName: "text-muted-foreground/70" },
136 neutral: { label: "Neutral", Icon: CircleDashedIcon, toneClassName: "text-muted-foreground/70" },
137} as const satisfies Record<
138 PullRequestCheckStatus,
139 { label: string; Icon: typeof CircleCheckIcon; toneClassName: string }
140>;
141​
142function isWorkflowApprovalCheck(check: Pick<PullRequestCheck, "status" | "url">): boolean {
143 return (
144 check.status === "action-required" &&
145 check.url !== null &&
146 /\/actions\/runs\/\d+(?:\/|$)/u.test(check.url)
147 );
149​
150export function pullRequestCheckStatusLabel(
151 check: Pick<PullRequestCheck, "status" | "url">,
152): string {
153 return isWorkflowApprovalCheck(check)
154 ? "Awaiting approval"
155 : CHECK_STATUS_PRESENTATION[check.status].label;
157​
158export function PullRequestCheckStatusIcon({ status }: { status: PullRequestCheckStatus }) {
159 const presentation = CHECK_STATUS_PRESENTATION[status];
160 return (
161 <presentation.Icon
162 aria-hidden
163 className={cn("size-3.5 shrink-0", presentation.toneClassName)}
164 />
165 );
167​
168/**
169 * The rollup a listing row carries, which is one word rather than the checks behind it. The
170 * headline is GitHub's own wording, so a reader who knows that page reads this one the same way.
171 */
172const CHECKS_STATE_PRESENTATION = {
173 passing: {
174 label: "All checks have passed",
175 Icon: CircleCheckIcon,
176 toneClassName: "text-emerald-600 dark:text-emerald-300/90",
177 },
178 failing: {
179 label: "Some checks were not successful",
180 Icon: CircleXIcon,
181 toneClassName: "text-destructive",
182 },
183 pending: {
184 label: "Some checks haven't completed yet",
185 Icon: CircleDotIcon,
186 toneClassName: "text-amber-600 dark:text-amber-400/90",
187 },
188} as const satisfies Record<
189 PullRequestChecksState,
190 { label: string; Icon: typeof CircleCheckIcon; toneClassName: string }
191>;
192​
193export function pullRequestChecksStatePresentation(state: PullRequestChecksState) {
194 return CHECKS_STATE_PRESENTATION[state];
196​
197/**
198 * The same rollup the server sends with a listing row, worked out here from the checks a detail
199 * already holds — so the header shows the icon without a second field travelling with it.
200 *
201 * Null for a change request with no checks: nothing to show beats a tick nobody earned.
202 */
203export function pullRequestChecksState(
204 checks: ReadonlyArray<PullRequestCheck>,
205): PullRequestChecksState | null {
206 if (checks.length === 0) return null;
207 const statuses = new Set(checks.map((check) => check.status));
208 if (statuses.has("failure") || statuses.has("cancelled")) return "failing";
209 if (statuses.has("pending") || statuses.has("action-required")) return "pending";
210 return statuses.has("success") ? "passing" : null;
212​
213/**
214 * How a verdict reads, in the one place every surface takes it from. The green is the green a
215 * passing check already wears in the same panel, so "approved" and "all checks passed" cannot
216 * look like two different kinds of good news.
217 *
218 * The ring runs a shade stronger than the text tones. At 16px across it is a thin arc, and the
219 * muted pairing that reads well as a word was barely there as an outline.
220 */
221const REVIEW_OUTCOME_PRESENTATION = {
222 approved: {
223 label: "Approved",
224 Icon: CircleCheckIcon,
225 toneClassName: "text-emerald-600 dark:text-emerald-300/90",
226 ringClassName: "ring-2 ring-emerald-500 dark:ring-emerald-400",
227 staleRingClassName:
228 "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))]",
229 badgeVariant: "success",
230 },
231 "changes-requested": {
232 label: "Changes requested",
233 Icon: CircleXIcon,
234 toneClassName: "text-destructive",
235 ringClassName: "ring-2 ring-destructive",
236 staleRingClassName: "ring-2 ring-[color-mix(in_srgb,var(--destructive)_35%,var(--background))]",
237 badgeVariant: "error",
238 },
239 dismissed: {
240 label: "Review dismissed",
241 Icon: CircleDashedIcon,
242 toneClassName: "text-muted-foreground/70",
243 ringClassName: "ring-2 ring-muted-foreground/60",
244 staleRingClassName:
245 "ring-2 ring-[color-mix(in_srgb,var(--contrast-muted-foreground)_30%,var(--background))]",
246 badgeVariant: "outline",
247 },
248} as const satisfies Record<
249 PullRequestReviewOutcome,
250 {
251 label: string;
252 Icon: typeof CircleCheckIcon;
253 toneClassName: string;
254 ringClassName: string;
255 staleRingClassName: string;
256 badgeVariant: "success" | "error" | "outline";
257 }
258>;
259​
260export function pullRequestReviewOutcomeToneClassName(outcome: PullRequestReviewOutcome): string {
261 return REVIEW_OUTCOME_PRESENTATION[outcome].toneClassName;
263​
264/** Worn by whatever wraps a reviewer's avatar, so their verdict reads without a row of its own. */
265/**
266 * A faded verdict is mixed into the background rather than made translucent. The ring is the only
267 * separator an avatar carrying one has — the summary drops the opaque `ring-background` where a
268 * verdict is drawn — and the stack overlaps by 4px, so an alpha ring would let the neighbour show
269 * straight through it and the two faces would merge.
270 */
271export function pullRequestReviewOutcomeRingClassName(
272 outcome: PullRequestReviewOutcome,
273 stale = false,
274): string {
275 const presentation = REVIEW_OUTCOME_PRESENTATION[outcome];
276 return stale ? presentation.staleRingClassName : presentation.ringClassName;
278​
279/**
280 * What a superseded verdict says, which is the same word with when it applied added. Commits
281 * landed after it, so it stands for code the branch no longer has.
282 */
283export function pullRequestReviewOutcomeStaleLabel(outcome: PullRequestReviewOutcome): string {
284 return `${REVIEW_OUTCOME_PRESENTATION[outcome].label} earlier changes`;
286​
287/** Decorative: every caller says which verdict this is in words beside it. */
288export function PullRequestReviewOutcomeIcon({
289 outcome,
290 className,
291}: {
292 outcome: PullRequestReviewOutcome;
293 className?: string;
294}) {
295 const presentation = REVIEW_OUTCOME_PRESENTATION[outcome];
296 return (
297 <presentation.Icon
298 aria-hidden
299 className={cn("size-3.5 shrink-0", presentation.toneClassName, className)}
300 />
301 );
303​
304export function pullRequestReviewOutcomeLabel(outcome: PullRequestReviewOutcome): string {
305 return REVIEW_OUTCOME_PRESENTATION[outcome].label;
307​
308export function PullRequestReviewOutcomeBadge({
309 outcome,
310 className,
311}: {
312 outcome: PullRequestReviewOutcome;
313 className?: string;
314}) {
315 const presentation = REVIEW_OUTCOME_PRESENTATION[outcome];
316 return (
317 <Badge size="sm" variant={presentation.badgeVariant} className={cn("gap-1", className)}>
318 <presentation.Icon aria-hidden className="size-3" />
319 {presentation.label}
320 </Badge>
321 );
323​
324export function PullRequestActorAvatar({
325 actor,
326 className,
327}: {
328 actor: PullRequestActor | null;
329 className?: string;
330}) {
331 const login = actor?.login ?? "ghost";
332 const avatarUrl = actor?.avatarUrl ?? null;
333 return avatarUrl === null ? (
334 // Not every host reports an avatar, so the initial stands in where none arrives.
335 <span
336 aria-hidden
337 className={cn(
338 "flex size-4 shrink-0 items-center justify-center rounded-full bg-muted text-[8px] font-medium text-muted-foreground",
339 className,
340 )}
341 >
342 {login.slice(0, 1).toUpperCase()}
343 </span>
344 ) : (
345 <img
346 aria-hidden
347 alt=""
348 src={avatarUrl}
349 loading="lazy"
350 className={cn("size-4 shrink-0 rounded-full bg-muted object-cover", className)}
351 />
352 );
354​
355/** GitHub attributes work from a deleted account to "ghost"; say the same word everywhere. */
356export function PullRequestActorLabel({
357 actor,
358 className,
359 labelClassName,
360 tooltip = true,
361}: {
362 actor: PullRequestActor | null;
363 className?: string;
364 labelClassName?: string;
365 tooltip?: boolean;
366}) {
367 const login = actor?.login ?? "ghost";
368 const label = (
369 <>
370 <PullRequestActorAvatar actor={actor} />
371 <span className={cn("truncate", labelClassName)}>{login}</span>
372 </>
373 );
374 if (!tooltip) {
375 return <span className={cn("flex min-w-0 items-center gap-1.5", className)}>{label}</span>;
376 }
377 return (
378 <Tooltip>
379 <TooltipTrigger
380 render={<span className={cn("flex min-w-0 items-center gap-1.5", className)} />}
381 >
382 {label}
383 </TooltipTrigger>
384 <TooltipPopup side="top">{login}</TooltipPopup>
385 </Tooltip>
386 );
388​
389/** Added and removed lines, coloured the way every host colours them. */
390export function PullRequestDiffStat({
391 additions,
392 deletions,
393 className,
394}: {
395 additions: number;
396 deletions: number;
397 className?: string;
398}) {
399 // Not every host reports line counts. Showing "+0 -0" would read as an empty change set
400 // rather than as a missing one, so the stat is left out instead.
401 if (additions === 0 && deletions === 0) {
402 return null;
403 }
404 return (
405 <span className={cn("inline-flex items-baseline gap-1 tabular-nums", className)}>
406 <span className="text-emerald-600 dark:text-emerald-300/90">
407 +{additions.toLocaleString()}
408 </span>
409 <span className="text-destructive">-{deletions.toLocaleString()}</span>
410 </span>
411 );
413​
414/**
415 * Dot-separated metadata. It owns the separator, and draws one only between the segments that
416 * survive, so a caller can render `{condition ? <span/> : null}` without leaving a stray dot.
417 * `Children.toArray` drops the nullish entries and keys what remains, which a plain array
418 * check would not do for a single child or a fragment. A separator borrows the key of the
419 * segment it precedes, so it stays stable without counting positions.
420 */
421function separatorKey(segment: ReactNode): string {
422 return `separator:${isValidElement(segment) ? String(segment.key) : String(segment)}`;
424​
425export function PullRequestMetaLine({
426 children,
427 className,
428}: {
429 children: ReactNode;
430 className?: string;
431}) {
432 const segments = Children.toArray(children);
433 return (
434 <span className={cn("flex min-w-0 items-center gap-1.5", className)}>
435 {segments.flatMap((segment, index) =>
436 index === 0
437 ? segment
438 : [
439 <span
440 aria-hidden
441 className="shrink-0 text-muted-foreground/50"
442 key={separatorKey(segment)}
443 >
444 ·
445 </span>,
446 segment,
447 ],
448 )}
449 </span>
450 );
452​
453export function summarizePullRequestChecks(checks: ReadonlyArray<PullRequestCheck>): string {
454 if (checks.length === 0) return "No checks reported";
455 const actionRequired = checks.filter((check) => check.status === "action-required");
456 const workflowApprovalRequired = actionRequired.filter(isWorkflowApprovalCheck).length;
457 const otherActionRequired = actionRequired.length - workflowApprovalRequired;
458 const failed = checks.filter(
459 (check) => check.status === "failure" || check.status === "cancelled",
460 ).length;
461 const pending = checks.filter((check) => check.status === "pending").length;
462 const passed = checks.filter((check) => check.status === "success").length;
463 if (failed > 0) return `${failed} of ${checks.length} failing`;
464 if (workflowApprovalRequired > 0 && otherActionRequired > 0) {
465 return `${workflowApprovalRequired} ${workflowApprovalRequired === 1 ? "workflow" : "workflows"} and ${otherActionRequired} ${otherActionRequired === 1 ? "check" : "checks"} awaiting action`;
466 }
467 if (workflowApprovalRequired > 0) {
468 return `${workflowApprovalRequired} ${workflowApprovalRequired === 1 ? "workflow" : "workflows"} awaiting approval`;
469 }
470 if (otherActionRequired > 0) {
471 return `${otherActionRequired} ${otherActionRequired === 1 ? "check" : "checks"} awaiting action`;
472 }
473 if (pending > 0) return `${pending} of ${checks.length} running`;
474 return passed === checks.length ? "All checks passed" : `${passed} of ${checks.length} passing`;