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

pullRequestPresentation.tsx

517 lines16.9 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 } 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 return avatarUrl === null ? (
356 // Not every host reports an avatar, so the initial stands in where none arrives.
357 <span
358 aria-hidden
359 className={cn(
360 "flex size-4 shrink-0 items-center justify-center rounded-full bg-muted text-[8px] font-medium text-muted-foreground",
361 className,
362 )}
363 >
364 {login.slice(0, 1).toUpperCase()}
365 </span>
366 ) : (
367 <img
368 aria-hidden
369 alt=""
370 src={avatarUrl}
371 loading="lazy"
372 className={cn("size-4 shrink-0 rounded-full bg-muted object-cover", className)}
373 />
374 );
376​
377/** GitHub attributes work from a deleted account to "ghost"; say the same word everywhere. */
378export function PullRequestActorLabel({
379 actor,
380 className,
381 labelClassName,
382 tooltip = true,
383 profileUrl,
384}: {
385 actor: PullRequestActor | null;
386 className?: string;
387 labelClassName?: string;
388 tooltip?: boolean;
389 profileUrl?: string | null;
390}) {
391 const login = actor?.login ?? "ghost";
392 const label = (
393 <>
394 <PullRequestActorAvatar actor={actor} />
395 <span className={cn("truncate", labelClassName)}>{login}</span>
396 </>
397 );
398 if (!tooltip) {
399 return <span className={cn("flex min-w-0 items-center gap-1.5", className)}>{label}</span>;
400 }
401 return (
402 <Tooltip>
403 <TooltipTrigger
404 render={
405 profileUrl ? (
406 <a
407 href={profileUrl}
408 target="_blank"
409 rel="noopener noreferrer"
410 aria-label={`Open ${login}'s profile`}
411 />
412 ) : (
413 <span />
414 )
415 }
416 className={cn(
417 "flex min-w-0 items-center gap-1.5",
418 profileUrl &&
419 "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",
420 className,
421 )}
422 >
423 {label}
424 </TooltipTrigger>
425 <TooltipPopup side="top">
426 {actor?.name && actor.name !== login ? `${actor.name} (@${login})` : login}
427 {profileUrl ? " · Open profile" : ""}
428 </TooltipPopup>
429 </Tooltip>
430 );
432​
433/** Added and removed lines, coloured the way every host colours them. */
434export function PullRequestDiffStat({
435 additions,
436 deletions,
437 className,
438}: {
439 additions: number;
440 deletions: number;
441 className?: string;
442}) {
443 // Not every host reports line counts. Showing "+0 -0" would read as an empty change set
444 // rather than as a missing one, so the stat is left out instead.
445 if (additions === 0 && deletions === 0) {
446 return null;
447 }
448 return (
449 <span className={cn("inline-flex items-baseline gap-1 tabular-nums", className)}>
450 <span className="text-diff-addition-foreground">+{additions.toLocaleString()}</span>
451 <span className="text-diff-deletion">-{deletions.toLocaleString()}</span>
452 </span>
453 );
455​
456/**
457 * Dot-separated metadata. It owns the separator, and draws one only between the segments that
458 * survive, so a caller can render `{condition ? <span/> : null}` without leaving a stray dot.
459 * `Children.toArray` drops the nullish entries and keys what remains, which a plain array
460 * check would not do for a single child or a fragment. A separator borrows the key of the
461 * segment it precedes, so it stays stable without counting positions.
462 */
463function separatorKey(segment: ReactNode): string {
464 return `separator:${isValidElement(segment) ? String(segment.key) : String(segment)}`;
466​
467export function PullRequestMetaLine({
468 children,
469 className,
470}: {
471 children: ReactNode;
472 className?: string;
473}) {
474 const segments = Children.toArray(children);
475 return (
476 <span className={cn("flex min-w-0 items-center gap-1.5", className)}>
477 {segments.flatMap((segment, index) =>
478 index === 0
479 ? segment
480 : [
481 <span
482 aria-hidden
483 className="shrink-0 text-muted-foreground/50"
484 key={separatorKey(segment)}
485 >
486 ·
487 </span>,
488 segment,
489 ],
490 )}
491 </span>
492 );
494​
495export function summarizePullRequestChecks(checks: ReadonlyArray<PullRequestCheck>): string {
496 if (checks.length === 0) return "No checks reported";
497 const actionRequired = checks.filter((check) => check.status === "action-required");
498 const workflowApprovalRequired = actionRequired.filter(isWorkflowApprovalCheck).length;
499 const otherActionRequired = actionRequired.length - workflowApprovalRequired;
500 const failed = checks.filter(
501 (check) => check.status === "failure" || check.status === "cancelled",
502 ).length;
503 const pending = checks.filter((check) => check.status === "pending").length;
504 const passed = checks.filter((check) => check.status === "success").length;
505 if (failed > 0) return `${failed} of ${checks.length} failing`;
506 if (workflowApprovalRequired > 0 && otherActionRequired > 0) {
507 return `${workflowApprovalRequired} ${workflowApprovalRequired === 1 ? "workflow" : "workflows"} and ${otherActionRequired} ${otherActionRequired === 1 ? "check" : "checks"} awaiting action`;
508 }
509 if (workflowApprovalRequired > 0) {
510 return `${workflowApprovalRequired} ${workflowApprovalRequired === 1 ? "workflow" : "workflows"} awaiting approval`;
511 }
512 if (otherActionRequired > 0) {
513 return `${otherActionRequired} ${otherActionRequired === 1 ? "check" : "checks"} awaiting action`;
514 }
515 if (pending > 0) return `${pending} of ${checks.length} running`;
516 return passed === checks.length ? "All checks passed" : `${passed} of ${checks.length} passing`;