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

pullRequestPresentation.tsx

494 lines16.2 KB

1import { Spinner } from "~/components/ui/spinner";
2import type {
3 PullRequestActor,
4 PullRequestCheck,
5 PullRequestCheckStatus,
6 PullRequestChecksState,
7 PullRequestMergeability,
8 PullRequestState,
9} from "@t3tools/contracts";
10import {
11 CircleCheckIcon,
12 CircleDashedIcon,
13 CircleDotIcon,
14 CircleXIcon,
15 GitMergeIcon,
16 GitPullRequestClosedIcon,
17 GitPullRequestDraftIcon,
18 GitPullRequestIcon,
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, merged, and draft use the same
37 * ink as the thread badge in `ThreadStatusIndicators`, so one pull request cannot look like two
38 * different things in two places.
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: Spinner, toneClassName: "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 | typeof Spinner; 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 profileUrl,
362}: {
363 actor: PullRequestActor | null;
364 className?: string;
365 labelClassName?: string;
366 tooltip?: boolean;
367 profileUrl?: string | null;
368}) {
369 const login = actor?.login ?? "ghost";
370 const label = (
371 <>
372 <PullRequestActorAvatar actor={actor} />
373 <span className={cn("truncate", labelClassName)}>{login}</span>
374 </>
375 );
376 if (!tooltip) {
377 return <span className={cn("flex min-w-0 items-center gap-1.5", className)}>{label}</span>;
378 }
379 return (
380 <Tooltip>
381 <TooltipTrigger
382 render={
383 profileUrl ? (
384 <a
385 href={profileUrl}
386 target="_blank"
387 rel="noopener noreferrer"
388 aria-label={`Open ${login}'s profile`}
389 />
390 ) : (
391 <span />
392 )
393 }
394 className={cn(
395 "flex min-w-0 items-center gap-1.5",
396 profileUrl &&
397 "cursor-pointer rounded-sm underline-offset-2 outline-none hover:text-foreground hover:underline focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
398 className,
399 )}
400 >
401 {label}
402 </TooltipTrigger>
403 <TooltipPopup side="top">{profileUrl ? `Open ${login}'s profile` : login}</TooltipPopup>
404 </Tooltip>
405 );
407​
408/** Added and removed lines, coloured the way every host colours them. */
409export function PullRequestDiffStat({
410 additions,
411 deletions,
412 className,
413}: {
414 additions: number;
415 deletions: number;
416 className?: string;
417}) {
418 // Not every host reports line counts. Showing "+0 -0" would read as an empty change set
419 // rather than as a missing one, so the stat is left out instead.
420 if (additions === 0 && deletions === 0) {
421 return null;
422 }
423 return (
424 <span className={cn("inline-flex items-baseline gap-1 tabular-nums", className)}>
425 <span className="text-emerald-600 dark:text-emerald-300/90">
426 +{additions.toLocaleString()}
427 </span>
428 <span className="text-destructive">-{deletions.toLocaleString()}</span>
429 </span>
430 );
432​
433/**
434 * Dot-separated metadata. It owns the separator, and draws one only between the segments that
435 * survive, so a caller can render `{condition ? <span/> : null}` without leaving a stray dot.
436 * `Children.toArray` drops the nullish entries and keys what remains, which a plain array
437 * check would not do for a single child or a fragment. A separator borrows the key of the
438 * segment it precedes, so it stays stable without counting positions.
439 */
440function separatorKey(segment: ReactNode): string {
441 return `separator:${isValidElement(segment) ? String(segment.key) : String(segment)}`;
443​
444export function PullRequestMetaLine({
445 children,
446 className,
447}: {
448 children: ReactNode;
449 className?: string;
450}) {
451 const segments = Children.toArray(children);
452 return (
453 <span className={cn("flex min-w-0 items-center gap-1.5", className)}>
454 {segments.flatMap((segment, index) =>
455 index === 0
456 ? segment
457 : [
458 <span
459 aria-hidden
460 className="shrink-0 text-muted-foreground/50"
461 key={separatorKey(segment)}
462 >
463 ·
464 </span>,
465 segment,
466 ],
467 )}
468 </span>
469 );
471​
472export function summarizePullRequestChecks(checks: ReadonlyArray<PullRequestCheck>): string {
473 if (checks.length === 0) return "No checks reported";
474 const actionRequired = checks.filter((check) => check.status === "action-required");
475 const workflowApprovalRequired = actionRequired.filter(isWorkflowApprovalCheck).length;
476 const otherActionRequired = actionRequired.length - workflowApprovalRequired;
477 const failed = checks.filter(
478 (check) => check.status === "failure" || check.status === "cancelled",
479 ).length;
480 const pending = checks.filter((check) => check.status === "pending").length;
481 const passed = checks.filter((check) => check.status === "success").length;
482 if (failed > 0) return `${failed} of ${checks.length} failing`;
483 if (workflowApprovalRequired > 0 && otherActionRequired > 0) {
484 return `${workflowApprovalRequired} ${workflowApprovalRequired === 1 ? "workflow" : "workflows"} and ${otherActionRequired} ${otherActionRequired === 1 ? "check" : "checks"} awaiting action`;
485 }
486 if (workflowApprovalRequired > 0) {
487 return `${workflowApprovalRequired} ${workflowApprovalRequired === 1 ? "workflow" : "workflows"} awaiting approval`;
488 }
489 if (otherActionRequired > 0) {
490 return `${otherActionRequired} ${otherActionRequired === 1 ? "check" : "checks"} awaiting action`;
491 }
492 if (pending > 0) return `${pending} of ${checks.length} running`;
493 return passed === checks.length ? "All checks passed" : `${passed} of ${checks.length} passing`;