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

pullRequestPresentation.tsx

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