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