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