Open History to see the last commit
1import type { EnvironmentId, PullRequestContextMetadata } from "@t3tools/contracts";
2import { CircleDashedIcon, FilmIcon, ImageIcon } from "lucide-react";
3import {
4 useState,
5 type ComponentProps,
6 type CSSProperties,
7 type MouseEvent,
8 type ReactNode,
9} from "react";
10
11import { PULL_REQUEST_STATE_PRESENTATION } from "~/components/pullRequest/pullRequestIcons";
12import type { PullRequestContextDisplayState } from "~/lib/composerContextRecords";
13import { PierreEntryIcon } from "./chat/PierreEntryIcon";
14import { middleTruncateAttachmentName } from "./composerInlineChip";
15import { PullRequestContextDetails } from "./PullRequestContextDetails";
16import { ContextChip, ContextChipLabel, type ContextChipKind } from "./ContextChip";
17import { Popover, PopoverPopup, PopoverTitle, PopoverTrigger } from "./ui/popover";
18import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
19import { PullRequestLinkPreview } from "./pullRequest/PullRequestLinkPreview";
20import { usePullRequestPreviewTarget } from "~/lib/openPullRequestLink";
21
22/** ContextChip kind for a pull request context in each display state. */
23export const PULL_REQUEST_CHIP_KINDS = {
24 open: "pr-open",
25 draft: "pr-draft",
26 merged: "pr-merged",
27 closed: "pr-closed",
28 unknown: "pull-request",
29} as const satisfies Record<PullRequestContextDisplayState | "unknown", ContextChipKind>;
30
31/** A static chip with an optional tooltip; each surface keeps ownership of payload lookup. */
32export function ContextChipShell({
33 icon,
34 label,
35 tooltip,
36 ...props
37}: Omit<ComponentProps<typeof ContextChip>, "className" | "render"> & {
38 icon: ReactNode;
39 label: string;
40 /** Newlines in the tooltip are kept. */
41 tooltip?: ReactNode;
42}) {
43 const chip = (
44 <ContextChip
45 data-context-unresolved={props.state === "unresolved" ? "true" : undefined}
46 tabIndex={tooltip ? 0 : undefined}
47 {...props}
48 >
49 {icon}
50 <ContextChipLabel>{label}</ContextChipLabel>
51 </ContextChip>
52 );
53 if (!tooltip) return chip;
54 return (
55 <Tooltip>
56 <TooltipTrigger render={chip} />
57 <TooltipPopup side="top" className="whitespace-pre-wrap">
58 {tooltip}
59 </TooltipPopup>
60 </Tooltip>
61 );
62}
63
64/** A chip that opens its details in a popover; the chip itself is the trigger. */
65export function ContextChipPopover(props: {
66 kind: ContextChipKind;
67 icon: ReactNode;
68 label: string;
69 copyMarkdown?: string;
70 accessibleLabel: string;
71 children: ReactNode;
72}) {
73 return (
74 <Popover>
75 <PopoverTrigger
76 render={
77 <ContextChip
78 kind={props.kind}
79 render={<button type="button" />}
80 aria-label={`${props.accessibleLabel}. Show details`}
81 data-markdown-copy={props.copyMarkdown}
82 />
83 }
84 >
85 {props.icon}
86 <ContextChipLabel>{props.label}</ContextChipLabel>
87 </PopoverTrigger>
88 <PopoverPopup side="top" width="lg" padding="compact">
89 <PopoverTitle className="sr-only">{props.accessibleLabel}</PopoverTitle>
90 {props.children}
91 </PopoverPopup>
92 </Popover>
93 );
94}
95
96export function PullRequestChip(props: {
97 metadata: PullRequestContextMetadata;
98 environmentId: EnvironmentId | null;
99 label: string;
100 kindLabel: string;
101 kind: ContextChipKind;
102 copyMarkdown?: string;
103 onOpen: (event: MouseEvent<HTMLElement>, url: string) => void;
104}) {
105 const previewTarget = usePullRequestPreviewTarget(props.environmentId, props.metadata.url);
106 const displayState =
107 props.metadata.state === "open" && props.metadata.isDraft ? "draft" : props.metadata.state;
108 const StateIcon = PULL_REQUEST_STATE_PRESENTATION[displayState].Icon;
109 const button = (
110 <ContextChip
111 kind={props.kind}
112 render={<button type="button" />}
113 aria-label={`Open ${props.kindLabel} ${props.label}: ${props.metadata.title}`}
114 data-markdown-copy={props.copyMarkdown}
115 onClick={(event) => props.onOpen(event, props.metadata.url)}
116 onAuxClick={(event) => props.onOpen(event, props.metadata.url)}
117 >
118 <StateIcon />
119 <ContextChipLabel>{props.label}</ContextChipLabel>
120 </ContextChip>
121 );
122 if (previewTarget !== null) {
123 return (
124 <PullRequestLinkPreview
125 link={button}
126 originalUrl={props.metadata.url}
127 target={previewTarget}
128 confirmBeforeOpen={false}
129 fallback={<PullRequestContextDetails metadata={props.metadata} />}
130 />
131 );
132 }
133 return (
134 <Tooltip>
135 <TooltipTrigger render={button} />
136 <TooltipPopup side="top">
137 <PullRequestContextDetails metadata={props.metadata} />
138 </TooltipPopup>
139 </Tooltip>
140 );
141}
142
143/** Sample the loaded thumbnail once; transparent pixels should not darken its accent. */
144function averageImageColor(image: HTMLImageElement): string | undefined {
145 try {
146 const canvas = document.createElement("canvas");
147 canvas.width = canvas.height = 16;
148 const context = canvas.getContext("2d");
149 if (!context) return;
150 context.drawImage(image, 0, 0, 16, 16);
151 const { data } = context.getImageData(0, 0, 16, 16);
152 let red = 0;
153 let green = 0;
154 let blue = 0;
155 let alpha = 0;
156 for (let index = 0; index < data.length; index += 4) {
157 const weight = data[index + 3]!;
158 red += data[index]! * weight;
159 green += data[index + 1]! * weight;
160 blue += data[index + 2]! * weight;
161 alpha += weight;
162 }
163 if (alpha === 0) return;
164 return `rgb(${Math.round(red / alpha)} ${Math.round(green / alpha)} ${Math.round(blue / alpha)})`;
165 } catch {
166 // Cross-origin or unavailable pixels keep the default image tone and preview action.
167 return;
168 }
169}
170
171export function ImageChipButton({
172 name,
173 previewUrl,
174 size,
175 suffix,
176 style,
177 ...props
178}: Omit<ComponentProps<typeof ContextChip>, "kind" | "render"> & {
179 name: string;
180 previewUrl: string | undefined;
181 /** Every attachment chip reports its size; images are no exception. */
182 size: string;
183 suffix?: string | null;
184}) {
185 const [sample, setSample] = useState<{ url: string; color: string | undefined }>();
186 const [corsFailedUrl, setCorsFailedUrl] = useState<string>();
187 const accent = sample?.url === previewUrl ? sample?.color : undefined;
188 return (
189 <ContextChip
190 kind="image"
191 render={<button type="button" />}
192 aria-label={`Image attachment, ${name}, ${size}`}
193 style={{ ...style, ...(accent ? { "--context-chip-accent": accent } : {}) } as CSSProperties}
194 {...props}
195 >
196 {previewUrl ? (
197 <img
198 key={previewUrl}
199 crossOrigin={corsFailedUrl === previewUrl ? undefined : "anonymous"}
200 src={previewUrl}
201 alt=""
202 className="size-[1.17em] shrink-0 rounded-sm object-cover"
203 onError={() => setCorsFailedUrl(previewUrl)}
204 onLoad={(event) =>
205 setSample({ url: previewUrl, color: averageImageColor(event.currentTarget) })
206 }
207 />
208 ) : (
209 <ImageIcon />
210 )}
211 <ContextChipLabel className="max-w-72">{middleTruncateAttachmentName(name)}</ContextChipLabel>
212 <span className="shrink-0 text-3xs text-current">{size}</span>
213 {suffix ? <span className="text-3xs text-current">{suffix}</span> : null}
214 </ContextChip>
215 );
216}
217
218export function FileChip(props: {
219 name: string;
220 size: string;
221 isVideo: boolean;
222 theme: "light" | "dark";
223 accessibleLabel: string;
224 tooltip: string;
225 suffix?: string | null;
226 copyMarkdown?: string;
227 disabled?: boolean;
228 error?: boolean;
229 unresolved?: boolean;
230 onOpen?: (() => void) | undefined;
231}) {
232 const content = <FileChipContent {...props} />;
233 const state = props.unresolved
234 ? ("unresolved" as const)
235 : props.error
236 ? ("invalid" as const)
237 : null;
238 const attributes = {
239 kind: props.isVideo ? "video" : "file",
240 ...(state ? { state } : {}),
241 "aria-label": [props.accessibleLabel, props.suffix].filter(Boolean).join(", "),
242 "data-markdown-copy": props.copyMarkdown,
243 "data-context-unresolved": props.unresolved ? "true" : undefined,
244 } as const;
245 return (
246 <Tooltip>
247 <TooltipTrigger
248 render={
249 props.onOpen ? (
250 <ContextChip
251 render={<button type="button" disabled={props.disabled} />}
252 onClick={props.onOpen}
253 {...attributes}
254 >
255 {content}
256 </ContextChip>
257 ) : (
258 <ContextChip tabIndex={0} {...attributes}>
259 {content}
260 </ContextChip>
261 )
262 }
263 />
264 <TooltipPopup side="top" className="whitespace-pre-wrap">
265 {props.tooltip}
266 </TooltipPopup>
267 </Tooltip>
268 );
269}
270
271function FileChipContent(props: {
272 name: string;
273 size: string;
274 isVideo: boolean;
275 theme: "light" | "dark";
276 suffix?: string | null;
277}) {
278 return (
279 <>
280 {props.isVideo ? (
281 <FilmIcon />
282 ) : (
283 <PierreEntryIcon pathValue={props.name} kind="file" theme={props.theme} />
284 )}
285 <ContextChipLabel className="max-w-72">
286 {middleTruncateAttachmentName(props.name)}
287 </ContextChipLabel>
288 <span className="shrink-0 text-3xs text-current">{props.size}</span>
289 {props.suffix ? <span className="text-3xs text-current">{props.suffix}</span> : null}
290 </>
291 );
292}
293
294export function UnresolvedChip(props: { label: string; tooltip: string; copyMarkdown?: string }) {
295 return (
296 <ContextChipShell
297 icon={<CircleDashedIcon />}
298 label={props.label}
299 state="unresolved"
300 aria-label={`Unavailable context, ${props.label}`}
301 data-markdown-copy={props.copyMarkdown}
302 tooltip={props.tooltip}
303 />
304 );
305}