Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

contextChipParts.tsx

366 lines10.8 KB

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 { 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";
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 );
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 className={cn("w-[min(36rem,calc(100vw-2rem))]", props.popupClassName)}
106 viewportClassName={cn("overflow-x-auto p-2", props.viewportClassName)}
107 >
108 <PopoverTitle className="sr-only">{props.accessibleLabel}</PopoverTitle>
109 {props.children}
110 </PopoverPopup>
111 </Popover>
112 );
114​
115export function PullRequestChip(props: {
116 metadata: PullRequestContextMetadata;
117 environmentId: EnvironmentId | null;
118 label: string;
119 kindLabel: string;
120 className: string;
121 labelClassName: string;
122 copyMarkdown?: string;
123 onOpen: (event: MouseEvent<HTMLElement>, url: string) => void;
124}) {
125 const previewTarget = usePullRequestPreviewTarget(props.environmentId, props.metadata.url);
126 const button = (
127 <Button
128 variant="chip"
129 className={cn(
130 props.className,
131 CONTEXT_INLINE_CHIP_FOCUS_CLASS_NAME,
132 CONTEXT_INLINE_CHIP_INTERACTIVE_CLASS_NAME,
133 "cursor-pointer",
134 )}
135 aria-label={`Open ${props.kindLabel} ${props.label}: ${props.metadata.title}`}
136 data-markdown-copy={props.copyMarkdown}
137 onClick={(event) => props.onOpen(event, props.metadata.url)}
138 >
139 <PullRequestGlyph.pullRequest
140 className={cn(COMPOSER_INLINE_CHIP_ICON_CLASS_NAME, "size-3.5")}
141 />
142 <span className={props.labelClassName}>{props.label}</span>
143 </Button>
144 );
145 if (previewTarget !== null) {
146 return (
147 <PullRequestLinkPreview
148 link={button}
149 originalUrl={props.metadata.url}
150 target={previewTarget}
151 confirmBeforeOpen={false}
152 fallback={<PullRequestContextDetails metadata={props.metadata} />}
153 />
154 );
155 }
156 return (
157 <Tooltip>
158 <TooltipTrigger render={button} />
159 <TooltipPopup side="top">
160 <PullRequestContextDetails metadata={props.metadata} />
161 </TooltipPopup>
162 </Tooltip>
163 );
165​
166/** Sample the loaded thumbnail once; transparent pixels should not darken its accent. */
167function averageImageColor(image: HTMLImageElement): string | undefined {
168 try {
169 const canvas = document.createElement("canvas");
170 canvas.width = canvas.height = 16;
171 const context = canvas.getContext("2d");
172 if (!context) return;
173 context.drawImage(image, 0, 0, 16, 16);
174 const { data } = context.getImageData(0, 0, 16, 16);
175 let red = 0;
176 let green = 0;
177 let blue = 0;
178 let alpha = 0;
179 for (let index = 0; index < data.length; index += 4) {
180 const weight = data[index + 3]!;
181 red += data[index]! * weight;
182 green += data[index + 1]! * weight;
183 blue += data[index + 2]! * weight;
184 alpha += weight;
185 }
186 if (alpha === 0) return;
187 return `rgb(${Math.round(red / alpha)} ${Math.round(green / alpha)} ${Math.round(blue / alpha)})`;
188 } catch {
189 // Cross-origin or unavailable pixels keep the default image tone and preview action.
190 return;
191 }
193​
194export function ImageChipButton({
195 name,
196 previewUrl,
197 className,
198 labelClassName,
199 size,
200 suffix,
201 style,
202 ...props
203}: ComponentProps<"button"> & {
204 name: string;
205 previewUrl: string | undefined;
206 labelClassName: string;
207 /** Every attachment chip reports its size; images are no exception. */
208 size: string;
209 suffix?: string | null;
210}) {
211 const [sample, setSample] = useState<{ url: string; color: string | undefined }>();
212 const [corsFailedUrl, setCorsFailedUrl] = useState<string>();
213 const accent = sample?.url === previewUrl ? sample?.color : undefined;
214 return (
215 <Button
216 variant="chip"
217 className={cn(
218 className,
219 CONTEXT_INLINE_CHIP_TONE_CLASS_NAMES.image,
220 CONTEXT_INLINE_CHIP_INTERACTIVE_CLASS_NAME,
221 "cursor-zoom-in",
222 )}
223 aria-label={`Image attachment, ${name}, ${size}`}
224 style={{ ...style, ...(accent ? { "--context-chip-accent": accent } : {}) } as CSSProperties}
225 {...props}
226 >
227 {previewUrl ? (
228 <img
229 key={previewUrl}
230 crossOrigin={corsFailedUrl === previewUrl ? undefined : "anonymous"}
231 src={previewUrl}
232 alt=""
233 className="size-3.5 shrink-0 rounded-sm object-cover"
234 onError={() => setCorsFailedUrl(previewUrl)}
235 onLoad={(event) =>
236 setSample({ url: previewUrl, color: averageImageColor(event.currentTarget) })
237 }
238 />
239 ) : (
240 <ImageIcon
241 className={cn(
242 COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
243 CONTEXT_INLINE_CHIP_ICON_TONE_CLASS_NAMES.image,
244 "size-3.5",
245 )}
246 />
247 )}
248 <span className={cn(labelClassName, "max-w-72")}>{middleTruncateAttachmentName(name)}</span>
249 <span className="shrink-0 text-[10px] text-current">{size}</span>
250 {suffix ? <span className="text-[10px] text-current">{suffix}</span> : null}
251 </Button>
252 );
254​
255export function FileChip(props: {
256 name: string;
257 size: string;
258 isVideo: boolean;
259 theme: "light" | "dark";
260 className: string;
261 labelClassName: string;
262 accessibleLabel: string;
263 tooltip: string;
264 suffix?: string | null;
265 copyMarkdown?: string;
266 disabled?: boolean;
267 error?: boolean;
268 unresolved?: boolean;
269 onOpen?: (() => void) | undefined;
270}) {
271 const className = cn(
272 props.className,
273 props.isVideo
274 ? CONTEXT_INLINE_CHIP_TONE_CLASS_NAMES.video
275 : CONTEXT_INLINE_CHIP_TONE_CLASS_NAMES.file,
276 props.onOpen && !props.disabled && CONTEXT_INLINE_CHIP_INTERACTIVE_CLASS_NAME,
277 props.onOpen && !props.disabled && (props.isVideo ? "cursor-zoom-in" : "cursor-pointer"),
278 props.unresolved && "border-dashed text-foreground",
279 props.error && "border-destructive/35 bg-destructive/8 text-destructive",
280 );
281 const content = <FileChipContent {...props} />;
282 const attributes = {
283 className,
284 "aria-label": [props.accessibleLabel, props.suffix].filter(Boolean).join(", "),
285 "data-markdown-copy": props.copyMarkdown,
286 "data-context-unresolved": props.unresolved ? "true" : undefined,
287 };
288 return (
289 <Tooltip>
290 <TooltipTrigger
291 render={
292 props.onOpen ? (
293 <Button variant="chip" disabled={props.disabled} onClick={props.onOpen} {...attributes}>
294 {content}
295 </Button>
296 ) : (
297 <span tabIndex={0} {...attributes}>
298 {content}
299 </span>
300 )
301 }
302 />
303 <TooltipPopup side="top" className="max-w-80 whitespace-pre-wrap leading-tight">
304 {props.tooltip}
305 </TooltipPopup>
306 </Tooltip>
307 );
309​
310function FileChipContent(props: {
311 name: string;
312 size: string;
313 isVideo: boolean;
314 theme: "light" | "dark";
315 labelClassName: string;
316 suffix?: string | null;
317}) {
318 return (
319 <>
320 {props.isVideo ? (
321 <FilmIcon
322 className={cn(
323 COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
324 CONTEXT_INLINE_CHIP_ICON_TONE_CLASS_NAMES.video,
325 "size-3.5",
326 )}
327 />
328 ) : (
329 <PierreEntryIcon
330 pathValue={props.name}
331 kind="file"
332 theme={props.theme}
333 className="size-3.5"
334 />
335 )}
336 <span className={cn(props.labelClassName, "max-w-72")}>
337 {middleTruncateAttachmentName(props.name)}
338 </span>
339 <span className="shrink-0 text-[10px] text-current">{props.size}</span>
340 {props.suffix ? <span className="text-[10px] text-current">{props.suffix}</span> : null}
341 </>
342 );
344​
345export function UnresolvedChip(props: {
346 label: string;
347 className: string;
348 labelClassName: string;
349 tooltip: string;
350 tooltipClassName: string;
351 copyMarkdown?: string;
352}) {
353 return (
354 <ContextChipShell
355 icon={<CircleDashedIcon className={cn(COMPOSER_INLINE_CHIP_ICON_CLASS_NAME, "size-3.5")} />}
356 label={props.label}
357 className={props.className}
358 labelClassName={props.labelClassName}
359 aria-label={`Unavailable context, ${props.label}`}
360 data-markdown-copy={props.copyMarkdown}
361 tooltip={props.tooltip}
362 tooltipClassName={props.tooltipClassName}
363 unresolved
364 />
365 );