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

contextChipParts.tsx

376 lines11.4 KB

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