Open History to see the last commit
1import type { 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 { cn } from "~/lib/utils";
12import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons";
13import { PierreEntryIcon } from "./chat/PierreEntryIcon";
14import {
15 COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
16 CONTEXT_INLINE_CHIP_FOCUS_CLASS_NAME,
17 CONTEXT_INLINE_CHIP_ICON_TONE_CLASS_NAMES,
18 CONTEXT_INLINE_CHIP_INTERACTIVE_CLASS_NAME,
19 CONTEXT_INLINE_CHIP_TONE_CLASS_NAMES,
20 middleTruncateAttachmentName,
21} from "./composerInlineChip";
22import { PullRequestContextDetails } from "./PullRequestContextDetails";
23import { Button } from "./ui/button";
24import { Popover, PopoverPopup, PopoverTitle, PopoverTrigger } from "./ui/popover";
25import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
26
27/** Shared visual slots; each surface keeps ownership of payload lookup and actions. */
28export function ContextChipShell({
29 icon,
30 label,
31 labelClassName,
32 tooltip,
33 tooltipClassName = "max-w-96 whitespace-pre-wrap leading-tight",
34 interactive,
35 unresolved,
36 className,
37 ...props
38}: ComponentProps<"span"> & {
39 icon: ReactNode;
40 label: string;
41 labelClassName: string;
42 tooltip?: ReactNode;
43 tooltipClassName?: string;
44 interactive?: boolean;
45 unresolved?: boolean;
46}) {
47 const chip = (
48 <span
49 className={cn(
50 className,
51 interactive && CONTEXT_INLINE_CHIP_INTERACTIVE_CLASS_NAME,
52 tooltip && CONTEXT_INLINE_CHIP_FOCUS_CLASS_NAME,
53 unresolved && "border-dashed text-foreground",
54 )}
55 data-context-unresolved={unresolved ? "true" : undefined}
56 tabIndex={tooltip ? 0 : undefined}
57 {...props}
58 >
59 {icon}
60 <span className={labelClassName}>{label}</span>
61 </span>
62 );
63 if (!tooltip) return chip;
64 return (
65 <Tooltip>
66 <TooltipTrigger render={chip} />
67 <TooltipPopup side="top" className={tooltipClassName}>
68 {tooltip}
69 </TooltipPopup>
70 </Tooltip>
71 );
72}
73
74export function ContextChipPopover(props: {
75 copyMarkdown?: string;
76 accessibleLabel: string;
77 chip: ReactNode;
78 children: ReactNode;
79 triggerClassName?: string;
80 popupClassName?: string;
81 viewportClassName?: string;
82}) {
83 return (
84 <Popover>
85 <PopoverTrigger
86 render={
87 <Button
88 variant="chip"
89 className={cn(
90 "inline-flex max-w-full cursor-pointer items-center rounded-[0.5em] align-middle",
91 CONTEXT_INLINE_CHIP_FOCUS_CLASS_NAME,
92 props.triggerClassName,
93 )}
94 aria-label={`${props.accessibleLabel}. Show details`}
95 data-markdown-copy={props.copyMarkdown}
96 />
97 }
98 >
99 {props.chip}
100 </PopoverTrigger>
101 <PopoverPopup
102 side="top"
103 className={cn("w-[min(36rem,calc(100vw-2rem))]", props.popupClassName)}
104 viewportClassName={cn("overflow-x-auto p-2", props.viewportClassName)}
105 >
106 <PopoverTitle className="sr-only">{props.accessibleLabel}</PopoverTitle>
107 {props.children}
108 </PopoverPopup>
109 </Popover>
110 );
111}
112
113export function PullRequestChip(props: {
114 metadata: PullRequestContextMetadata;
115 label: string;
116 kindLabel: string;
117 className: string;
118 labelClassName: string;
119 copyMarkdown?: string;
120 onOpen: (event: MouseEvent<HTMLElement>, url: string) => void;
121}) {
122 return (
123 <Tooltip>
124 <TooltipTrigger
125 render={
126 <Button
127 variant="chip"
128 className={cn(
129 props.className,
130 CONTEXT_INLINE_CHIP_FOCUS_CLASS_NAME,
131 CONTEXT_INLINE_CHIP_INTERACTIVE_CLASS_NAME,
132 "cursor-pointer",
133 )}
134 aria-label={`Open ${props.kindLabel} ${props.label}: ${props.metadata.title}`}
135 data-markdown-copy={props.copyMarkdown}
136 onClick={(event) => props.onOpen(event, props.metadata.url)}
137 >
138 <PullRequestGlyph.pullRequest
139 className={cn(COMPOSER_INLINE_CHIP_ICON_CLASS_NAME, "size-3.5")}
140 />
141 <span className={props.labelClassName}>{props.label}</span>
142 </Button>
143 }
144 />
145 <TooltipPopup side="top">
146 <PullRequestContextDetails metadata={props.metadata} />
147 </TooltipPopup>
148 </Tooltip>
149 );
150}
151
152/** Sample the loaded thumbnail once; transparent pixels should not darken its accent. */
153function averageImageColor(image: HTMLImageElement): string | undefined {
154 try {
155 const canvas = document.createElement("canvas");
156 canvas.width = canvas.height = 16;
157 const context = canvas.getContext("2d");
158 if (!context) return;
159 context.drawImage(image, 0, 0, 16, 16);
160 const { data } = context.getImageData(0, 0, 16, 16);
161 let red = 0;
162 let green = 0;
163 let blue = 0;
164 let alpha = 0;
165 for (let index = 0; index < data.length; index += 4) {
166 const weight = data[index + 3]!;
167 red += data[index]! * weight;
168 green += data[index + 1]! * weight;
169 blue += data[index + 2]! * weight;
170 alpha += weight;
171 }
172 if (alpha === 0) return;
173 return `rgb(${Math.round(red / alpha)} ${Math.round(green / alpha)} ${Math.round(blue / alpha)})`;
174 } catch {
175 // Cross-origin or unavailable pixels keep the default image tone and preview action.
176 return;
177 }
178}
179
180export function ImageChipButton({
181 name,
182 previewUrl,
183 className,
184 labelClassName,
185 size,
186 suffix,
187 style,
188 ...props
189}: ComponentProps<"button"> & {
190 name: string;
191 previewUrl: string | undefined;
192 labelClassName: string;
193 /** Every attachment chip reports its size; images are no exception. */
194 size: string;
195 suffix?: string | null;
196}) {
197 const [sample, setSample] = useState<{ url: string; color: string | undefined }>();
198 const [corsFailedUrl, setCorsFailedUrl] = useState<string>();
199 const accent = sample?.url === previewUrl ? sample?.color : undefined;
200 return (
201 <Button
202 variant="chip"
203 className={cn(
204 className,
205 CONTEXT_INLINE_CHIP_TONE_CLASS_NAMES.image,
206 CONTEXT_INLINE_CHIP_INTERACTIVE_CLASS_NAME,
207 "cursor-zoom-in",
208 )}
209 aria-label={`Image attachment, ${name}, ${size}`}
210 style={{ ...style, ...(accent ? { "--context-chip-accent": accent } : {}) } as CSSProperties}
211 {...props}
212 >
213 {previewUrl ? (
214 <img
215 key={previewUrl}
216 crossOrigin={corsFailedUrl === previewUrl ? undefined : "anonymous"}
217 src={previewUrl}
218 alt=""
219 className="size-3.5 shrink-0 rounded-sm object-cover"
220 onError={() => setCorsFailedUrl(previewUrl)}
221 onLoad={(event) =>
222 setSample({ url: previewUrl, color: averageImageColor(event.currentTarget) })
223 }
224 />
225 ) : (
226 <ImageIcon
227 className={cn(
228 COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
229 CONTEXT_INLINE_CHIP_ICON_TONE_CLASS_NAMES.image,
230 "size-3.5",
231 )}
232 />
233 )}
234 <span className={cn(labelClassName, "max-w-72")}>{middleTruncateAttachmentName(name)}</span>
235 <span className="shrink-0 text-[10px] text-current">{size}</span>
236 {suffix ? <span className="text-[10px] text-current">{suffix}</span> : null}
237 </Button>
238 );
239}
240
241export function FileChip(props: {
242 name: string;
243 size: string;
244 isVideo: boolean;
245 theme: "light" | "dark";
246 className: string;
247 labelClassName: string;
248 accessibleLabel: string;
249 tooltip: string;
250 suffix?: string | null;
251 copyMarkdown?: string;
252 disabled?: boolean;
253 error?: boolean;
254 unresolved?: boolean;
255 onOpen?: (() => void) | undefined;
256}) {
257 const className = cn(
258 props.className,
259 props.isVideo
260 ? CONTEXT_INLINE_CHIP_TONE_CLASS_NAMES.video
261 : CONTEXT_INLINE_CHIP_TONE_CLASS_NAMES.file,
262 props.onOpen && !props.disabled && CONTEXT_INLINE_CHIP_INTERACTIVE_CLASS_NAME,
263 props.onOpen && !props.disabled && (props.isVideo ? "cursor-zoom-in" : "cursor-pointer"),
264 props.unresolved && "border-dashed text-foreground",
265 props.error && "border-destructive/35 bg-destructive/8 text-destructive",
266 );
267 const content = <FileChipContent {...props} />;
268 const attributes = {
269 className,
270 "aria-label": [props.accessibleLabel, props.suffix].filter(Boolean).join(", "),
271 "data-markdown-copy": props.copyMarkdown,
272 "data-context-unresolved": props.unresolved ? "true" : undefined,
273 };
274 return (
275 <Tooltip>
276 <TooltipTrigger
277 render={
278 props.onOpen ? (
279 <Button variant="chip" disabled={props.disabled} onClick={props.onOpen} {...attributes}>
280 {content}
281 </Button>
282 ) : (
283 <span tabIndex={0} {...attributes}>
284 {content}
285 </span>
286 )
287 }
288 />
289 <TooltipPopup side="top" className="max-w-80 whitespace-pre-wrap leading-tight">
290 {props.tooltip}
291 </TooltipPopup>
292 </Tooltip>
293 );
294}
295
296function FileChipContent(props: {
297 name: string;
298 size: string;
299 isVideo: boolean;
300 theme: "light" | "dark";
301 labelClassName: string;
302 suffix?: string | null;
303}) {
304 return (
305 <>
306 {props.isVideo ? (
307 <FilmIcon
308 className={cn(
309 COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
310 CONTEXT_INLINE_CHIP_ICON_TONE_CLASS_NAMES.video,
311 "size-3.5",
312 )}
313 />
314 ) : (
315 <PierreEntryIcon
316 pathValue={props.name}
317 kind="file"
318 theme={props.theme}
319 className="size-3.5"
320 />
321 )}
322 <span className={cn(props.labelClassName, "max-w-72")}>
323 {middleTruncateAttachmentName(props.name)}
324 </span>
325 <span className="shrink-0 text-[10px] text-current">{props.size}</span>
326 {props.suffix ? <span className="text-[10px] text-current">{props.suffix}</span> : null}
327 </>
328 );
329}
330
331export function UnresolvedChip(props: {
332 label: string;
333 className: string;
334 labelClassName: string;
335 tooltip: string;
336 tooltipClassName: string;
337 copyMarkdown?: string;
338}) {
339 return (
340 <ContextChipShell
341 icon={<CircleDashedIcon className={cn(COMPOSER_INLINE_CHIP_ICON_CLASS_NAME, "size-3.5")} />}
342 label={props.label}
343 className={props.className}
344 labelClassName={props.labelClassName}
345 aria-label={`Unavailable context, ${props.label}`}
346 data-markdown-copy={props.copyMarkdown}
347 tooltip={props.tooltip}
348 tooltipClassName={props.tooltipClassName}
349 unresolved
350 />
351 );
352}