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

contextChipParts.tsx

298 lines8.9 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 { 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 );
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 );
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 );
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 }
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="max-w-72">{middleTruncateAttachmentName(name)}</ContextChipLabel>
205 <span className="shrink-0 text-3xs text-current">{size}</span>
206 {suffix ? <span className="text-3xs text-current">{suffix}</span> : null}
207 </ContextChip>
208 );
210​
211export function FileChip(props: {
212 name: string;
213 size: string;
214 isVideo: boolean;
215 theme: "light" | "dark";
216 accessibleLabel: string;
217 tooltip: string;
218 suffix?: string | null;
219 copyMarkdown?: string;
220 disabled?: boolean;
221 error?: boolean;
222 unresolved?: boolean;
223 onOpen?: (() => void) | undefined;
224}) {
225 const content = <FileChipContent {...props} />;
226 const state = props.unresolved
227 ? ("unresolved" as const)
228 : props.error
229 ? ("invalid" as const)
230 : null;
231 const attributes = {
232 kind: props.isVideo ? "video" : "file",
233 ...(state ? { state } : {}),
234 "aria-label": [props.accessibleLabel, props.suffix].filter(Boolean).join(", "),
235 "data-markdown-copy": props.copyMarkdown,
236 "data-context-unresolved": props.unresolved ? "true" : undefined,
237 } as const;
238 return (
239 <Tooltip>
240 <TooltipTrigger
241 render={
242 props.onOpen ? (
243 <ContextChip
244 render={<button type="button" disabled={props.disabled} />}
245 onClick={props.onOpen}
246 {...attributes}
247 >
248 {content}
249 </ContextChip>
250 ) : (
251 <ContextChip tabIndex={0} {...attributes}>
252 {content}
253 </ContextChip>
254 )
255 }
256 />
257 <TooltipPopup side="top" className="whitespace-pre-wrap">
258 {props.tooltip}
259 </TooltipPopup>
260 </Tooltip>
261 );
263​
264function FileChipContent(props: {
265 name: string;
266 size: string;
267 isVideo: boolean;
268 theme: "light" | "dark";
269 suffix?: string | null;
270}) {
271 return (
272 <>
273 {props.isVideo ? (
274 <FilmIcon />
275 ) : (
276 <PierreEntryIcon pathValue={props.name} kind="file" theme={props.theme} />
277 )}
278 <ContextChipLabel className="max-w-72">
279 {middleTruncateAttachmentName(props.name)}
280 </ContextChipLabel>
281 <span className="shrink-0 text-3xs text-current">{props.size}</span>
282 {props.suffix ? <span className="text-3xs text-current">{props.suffix}</span> : null}
283 </>
284 );
286​
287export function UnresolvedChip(props: { label: string; tooltip: string; copyMarkdown?: string }) {
288 return (
289 <ContextChipShell
290 icon={<CircleDashedIcon />}
291 label={props.label}
292 state="unresolved"
293 aria-label={`Unavailable context, ${props.label}`}
294 data-markdown-copy={props.copyMarkdown}
295 tooltip={props.tooltip}
296 />
297 );