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

pullRequestPresentation.tsx

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