Open History to see the last commit
1import type { EnvironmentId, PullRequestContextMetadata } from "@t3tools/contracts";
2import { CircleDashedIcon, FilmIcon, ImageIcon } from "lucide-react";
3import {
4 useEffect,
5 useState,
6 type ComponentProps,
7 type CSSProperties,
8 type MouseEvent,
9 type ReactNode,
10} from "react";
11import { useAssetUrlState } from "~/assets/assetUrls";
12import { documentIconColorForFileName } from "~/pierre-icons";
13
14import { PULL_REQUEST_STATE_PRESENTATION } from "~/components/pullRequest/pullRequestIcons";
15import type { PullRequestContextDisplayState } from "~/lib/composerContextRecords";
16import { PierreEntryIcon } from "./chat/PierreEntryIcon";
17import { middleTruncateAttachmentName } from "./composerInlineChip";
18import { PullRequestContextDetails } from "./PullRequestContextDetails";
19import { ContextChip, ContextChipLabel, type ContextChipKind } from "./ContextChip";
20import { Popover, PopoverPopup, PopoverTitle, PopoverTrigger } from "./ui/popover";
21import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
22import { PullRequestLinkPreview } from "./pullRequest/PullRequestLinkPreview";
23import { usePullRequestPreviewTarget } from "~/lib/openPullRequestLink";
24
25export const PULL_REQUEST_CHIP_KINDS = {
26 open: "pr-open",
27 draft: "pr-draft",
28 merged: "pr-merged",
29 closed: "pr-closed",
30 unknown: "pull-request",
31} as const satisfies Record<PullRequestContextDisplayState | "unknown", ContextChipKind>;
32
33export function ContextChipShell({
34 icon,
35 label,
36 tooltip,
37 ...props
38}: Omit<ComponentProps<typeof ContextChip>, "className" | "render"> & {
39 icon: ReactNode;
40 label: string;
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
64export function ContextChipPopover(props: {
65 kind: ContextChipKind;
66 icon: ReactNode;
67 label: string;
68 copyMarkdown?: string;
69 accessibleLabel: string;
70 children: ReactNode;
71}) {
72 return (
73 <Popover>
74 <PopoverTrigger
75 render={
76 <ContextChip
77 kind={props.kind}
78 render={<button type="button" />}
79 aria-label={`${props.accessibleLabel}. Show details`}
80 data-markdown-copy={props.copyMarkdown}
81 />
82 }
83 >
84 {props.icon}
85 <ContextChipLabel>{props.label}</ContextChipLabel>
86 </PopoverTrigger>
87 <PopoverPopup side="top" width="lg" padding="compact">
88 <PopoverTitle className="sr-only">{props.accessibleLabel}</PopoverTitle>
89 {props.children}
90 </PopoverPopup>
91 </Popover>
92 );
93}
94
95export function PullRequestChip(props: {
96 metadata: PullRequestContextMetadata;
97 environmentId: EnvironmentId | null;
98 label: string;
99 kindLabel: string;
100 kind: ContextChipKind;
101 copyMarkdown?: string;
102 onOpen: (event: MouseEvent<HTMLElement>, url: string) => void;
103}) {
104 const previewTarget = usePullRequestPreviewTarget(props.environmentId, props.metadata.url);
105 const displayState =
106 props.metadata.state === "open" && props.metadata.isDraft ? "draft" : props.metadata.state;
107 const StateIcon = PULL_REQUEST_STATE_PRESENTATION[displayState].Icon;
108 const button = (
109 <ContextChip
110 kind={props.kind}
111 render={<button type="button" />}
112 aria-label={`Open ${props.kindLabel} ${props.label}: ${props.metadata.title}`}
113 data-markdown-copy={props.copyMarkdown}
114 onClick={(event) => props.onOpen(event, props.metadata.url)}
115 onAuxClick={(event) => props.onOpen(event, props.metadata.url)}
116 >
117 <StateIcon />
118 <ContextChipLabel>{props.label}</ContextChipLabel>
119 </ContextChip>
120 );
121 if (previewTarget !== null) {
122 return (
123 <PullRequestLinkPreview
124 link={button}
125 originalUrl={props.metadata.url}
126 target={previewTarget}
127 confirmBeforeOpen={false}
128 fallback={<PullRequestContextDetails metadata={props.metadata} />}
129 />
130 );
131 }
132 return (
133 <Tooltip>
134 <TooltipTrigger render={button} />
135 <TooltipPopup side="top">
136 <PullRequestContextDetails metadata={props.metadata} />
137 </TooltipPopup>
138 </Tooltip>
139 );
140}
141
142function averageImageColor(image: HTMLImageElement): string | undefined {
143 try {
144 const canvas = document.createElement("canvas");
145 canvas.width = canvas.height = 16;
146 const context = canvas.getContext("2d");
147 if (!context) return;
148 context.drawImage(image, 0, 0, 16, 16);
149 const { data } = context.getImageData(0, 0, 16, 16);
150 let red = 0;
151 let green = 0;
152 let blue = 0;
153 let alpha = 0;
154 for (let index = 0; index < data.length; index += 4) {
155 const weight = data[index + 3]!;
156 red += data[index]! * weight;
157 green += data[index + 1]! * weight;
158 blue += data[index + 2]! * weight;
159 alpha += weight;
160 }
161 if (alpha === 0) return;
162 return `rgb(${Math.round(red / alpha)} ${Math.round(green / alpha)} ${Math.round(blue / alpha)})`;
163 } catch {
164 return;
165 }
166}
167
168export function ImageChipButton({
169 name,
170 previewUrl,
171 size,
172 suffix,
173 disabled,
174 onPreviewError,
175 style,
176 ...props
177}: Omit<ComponentProps<typeof ContextChip>, "kind" | "render"> & {
178 name: string;
179 previewUrl: string | undefined;
180 size: string;
181 suffix?: string | null | undefined;
182 disabled?: boolean | undefined;
183 onPreviewError?: (() => void) | undefined;
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" disabled={disabled} />}
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={() => {
204 if (corsFailedUrl === previewUrl) onPreviewError?.();
205 else setCorsFailedUrl(previewUrl);
206 }}
207 onLoad={(event) =>
208 setSample({ url: previewUrl, color: averageImageColor(event.currentTarget) })
209 }
210 />
211 ) : (
212 <ImageIcon />
213 )}
214 <ContextChipLabel className="flex items-baseline gap-[0.33em]">
215 <span className="max-w-72 truncate">{middleTruncateAttachmentName(name)}</span>
216 <span className="shrink-0 text-3xs text-current">{size}</span>
217 {suffix ? <span className="text-3xs text-current">{suffix}</span> : null}
218 </ContextChipLabel>
219 </ContextChip>
220 );
221}
222
223export function FileChip(props: {
224 name: string;
225 size: string;
226 isVideo: boolean;
227 theme: "light" | "dark";
228 accessibleLabel: string;
229 tooltip: string;
230 suffix?: string | null;
231 copyMarkdown?: string;
232 disabled?: boolean;
233 error?: boolean;
234 unresolved?: boolean;
235 onOpen?: (() => void) | undefined;
236 svgPreview?:
237 | {
238 file?: Blob | null | undefined;
239 environmentId?: EnvironmentId | undefined;
240 attachmentId?: string | undefined;
241 }
242 | undefined;
243}) {
244 if (props.svgPreview && !props.unresolved) return <SvgFileChip {...props} />;
245 const content = <FileChipContent {...props} />;
246 const accent = props.isVideo ? undefined : documentIconColorForFileName(props.name);
247 const state = props.unresolved
248 ? ("unresolved" as const)
249 : props.error
250 ? ("invalid" as const)
251 : null;
252 const attributes = {
253 kind: props.isVideo ? "video" : "file",
254 style: accent ? ({ "--context-chip-accent": accent } as CSSProperties) : undefined,
255 ...(state ? { state } : {}),
256 "aria-label": [props.accessibleLabel, props.suffix].filter(Boolean).join(", "),
257 "data-markdown-copy": props.copyMarkdown,
258 "data-context-unresolved": props.unresolved ? "true" : undefined,
259 } as const;
260 return (
261 <Tooltip>
262 <TooltipTrigger
263 render={
264 props.onOpen ? (
265 <ContextChip
266 render={<button type="button" disabled={props.disabled} />}
267 onClick={props.onOpen}
268 {...attributes}
269 >
270 {content}
271 </ContextChip>
272 ) : (
273 <ContextChip tabIndex={0} {...attributes}>
274 {content}
275 </ContextChip>
276 )
277 }
278 />
279 <TooltipPopup side="top" className="whitespace-pre-wrap">
280 {props.tooltip}
281 </TooltipPopup>
282 </Tooltip>
283 );
284}
285
286function SvgFileChip(props: ComponentProps<typeof FileChip>) {
287 const preview = props.svgPreview;
288 const [local, setLocal] = useState<{ file: Blob; url: string }>();
289 const [failedPreviewUrl, setFailedPreviewUrl] = useState<string>();
290 const asset = useAssetUrlState(
291 preview?.file ? null : (preview?.environmentId ?? null),
292 preview?.attachmentId
293 ? {
294 _tag: "attachment",
295 attachmentId: preview.attachmentId,
296 fileName: props.name,
297 mimeType: "image/svg+xml",
298 disposition: "inline",
299 }
300 : null,
301 );
302 useEffect(() => {
303 const file = preview?.file;
304 if (!file) return;
305 const url = URL.createObjectURL(file);
306 // oxlint-disable-next-line react/set-state-in-effect -- Publish a Blob URL with its cleanup registered.
307 setLocal({ file, url });
308 return () => URL.revokeObjectURL(url);
309 }, [preview?.file]);
310 const url = preview?.file
311 ? local?.file === preview.file
312 ? local.url
313 : undefined
314 : asset._tag === "Success"
315 ? asset.url
316 : undefined;
317 if (url !== undefined && failedPreviewUrl === url) {
318 return <FileChip {...props} svgPreview={undefined} />;
319 }
320 return (
321 <Tooltip>
322 <TooltipTrigger
323 render={
324 <ImageChipButton
325 name={props.name}
326 size={props.size}
327 previewUrl={url}
328 suffix={props.suffix}
329 disabled={props.disabled}
330 onClick={props.onOpen}
331 onPreviewError={() => setFailedPreviewUrl(url)}
332 data-markdown-copy={props.copyMarkdown}
333 aria-label={props.accessibleLabel}
334 {...(props.error ? { state: "invalid" as const } : {})}
335 />
336 }
337 />
338 <TooltipPopup side="top" className="whitespace-pre-wrap">
339 {props.tooltip}
340 </TooltipPopup>
341 </Tooltip>
342 );
343}
344
345function FileChipContent(props: {
346 name: string;
347 size: string;
348 isVideo: boolean;
349 theme: "light" | "dark";
350 suffix?: string | null;
351}) {
352 return (
353 <>
354 {props.isVideo ? (
355 <FilmIcon />
356 ) : (
357 <PierreEntryIcon pathValue={props.name} kind="file" theme={props.theme} />
358 )}
359 <ContextChipLabel className="flex items-baseline gap-[0.33em]">
360 <span className="max-w-72 truncate">{middleTruncateAttachmentName(props.name)}</span>
361 <span className="shrink-0 text-3xs text-current">{props.size}</span>
362 {props.suffix ? <span className="text-3xs text-current">{props.suffix}</span> : null}
363 </ContextChipLabel>
364 </>
365 );
366}
367
368export function UnresolvedChip(props: { label: string; tooltip: string; copyMarkdown?: string }) {
369 return (
370 <ContextChipShell
371 icon={<CircleDashedIcon />}
372 label={props.label}
373 state="unresolved"
374 aria-label={`Unavailable context, ${props.label}`}
375 data-markdown-copy={props.copyMarkdown}
376 tooltip={props.tooltip}
377 />
378 );
379}