Open History to see the last commit
1import { InfoIcon } from "lucide-react";
2import { useId, useLayoutEffect, useRef, useState, type ReactNode } from "react";
3import { flushSync } from "react-dom";
4
5import { cn } from "~/lib/utils";
6import { Button } from "../ui/button";
7import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
8import { ComposerBanner, type ComposerBannerVariant } from "./ComposerBanner";
9import { observeResize } from "~/lib/observeResize";
10
11// Match the duration-220 exit transition before removing a dismissed notice.
12const DISMISS_TRANSITION_MS = 220;
13
14export interface ComposerBannerStackItem {
15 readonly id: string;
16 readonly variant: ComposerBannerVariant;
17 readonly priority?: "urgent" | "activity" | "notice";
18 readonly icon: ReactNode;
19 readonly title: ReactNode;
20 readonly description?: ReactNode;
21 readonly children?: ReactNode;
22 readonly actions?: ReactNode;
23 readonly dismissLabel?: string;
24 readonly onDismiss?: () => void;
25}
26
27export type ComposerBannerStackContent = Pick<
28 ComposerBannerStackItem,
29 "id" | "variant" | "priority"
30> & { readonly content: ReactNode };
31
32type ComposerBannerStackEntry = ComposerBannerStackItem | ComposerBannerStackContent;
33
34function bannerPriority(item: ComposerBannerStackEntry) {
35 if (item.priority === "urgent" || item.variant === "error" || item.variant === "warning") {
36 return 0;
37 }
38 if (item.priority === "activity") {
39 return 1;
40 }
41 return 2;
42}
43
44interface ComposerBannerStackProps {
45 readonly className?: string;
46 readonly items: ReadonlyArray<ComposerBannerStackEntry>;
47 readonly attachedAbove?: ReactNode;
48}
49
50export function ComposerBannerStack({ className, items, attachedAbove }: ComposerBannerStackProps) {
51 const [stackExpanded, setStackExpanded] = useState(false);
52 const noticesRef = useRef<HTMLDivElement>(null);
53 const peekRef = useRef<HTMLButtonElement>(null);
54 const expandedItemsRef = useRef<HTMLDivElement>(null);
55 const expandedItemsId = useId();
56 const [requestedExitingItemId, setExitingItemId] = useState<string | null>(null);
57 const exitingItemId =
58 requestedExitingItemId !== null && items.some((item) => item.id === requestedExitingItemId)
59 ? requestedExitingItemId
60 : null;
61
62 if (items.length < 2 && stackExpanded) {
63 setStackExpanded(false);
64 }
65
66 const expandAndFocusNotice = () => {
67 flushSync(() => setStackExpanded(true));
68 const container = expandedItemsRef.current;
69 const firstControl = container?.querySelector<HTMLElement>(
70 'button:not(:disabled), a[href], input:not(:disabled), [tabindex="0"]',
71 );
72 (firstControl ?? container)?.focus({ preventScroll: true });
73 };
74
75 const orderedItems = items.toSorted((a, b) => bannerPriority(a) - bannerPriority(b));
76 const frontItem = orderedItems[0];
77 if (!frontItem) {
78 return (
79 <>
80 {null}
81 {attachedAbove}
82 {null}
83 </>
84 );
85 }
86 const stackedItems = orderedItems.slice(1);
87 const hasStack = stackedItems.length > 0;
88 const showCollapsedStackCap = hasStack && exitingItemId !== frontItem.id;
89 const firstStackedItem = stackedItems[0];
90
91 const requestDismiss = (item: ComposerBannerStackEntry) => {
92 if (!("onDismiss" in item) || !item.onDismiss || exitingItemId) {
93 return;
94 }
95 setExitingItemId(item.id);
96 // A timer, not transitionend: the dismissal must commit even when the stack unmounts
97 // (thread switch) or a collapsed composer hides it mid-exit, and transitionend never fires then.
98 setTimeout(() => item.onDismiss?.(), DISMISS_TRANSITION_MS);
99 };
100
101 return (
102 <>
103 {hasStack ? (
104 <div
105 ref={noticesRef}
106 data-composer-banner-stack="true"
107 data-chat-composer-collapsed-controls="true"
108 className={cn("relative z-20 min-h-3", stackExpanded && "z-50")}
109 onPointerEnter={(event) => {
110 if (event.pointerType === "touch") return;
111 if (document.activeElement === peekRef.current) {
112 expandAndFocusNotice();
113 return;
114 }
115 setStackExpanded(true);
116 }}
117 onPointerLeave={(event) => {
118 if (!event.currentTarget.contains(document.activeElement)) setStackExpanded(false);
119 }}
120 onBlurCapture={(event) => {
121 if (
122 !event.currentTarget.contains(event.relatedTarget) &&
123 !event.currentTarget.matches(":hover")
124 ) {
125 setStackExpanded(false);
126 }
127 }}
128 onKeyDown={(event) => {
129 if (event.key !== "Escape" || !stackExpanded) return;
130 event.preventDefault();
131 event.stopPropagation();
132 flushSync(() => setStackExpanded(false));
133 peekRef.current?.focus({ preventScroll: true });
134 }}
135 >
136 {showCollapsedStackCap && firstStackedItem ? (
137 <ComposerBanner.Peek
138 ref={peekRef}
139 variant={firstStackedItem.variant}
140 aria-label="Show other notices"
141 aria-expanded={stackExpanded}
142 aria-controls={expandedItemsId}
143 aria-hidden={stackExpanded || undefined}
144 tabIndex={stackExpanded ? -1 : 0}
145 onClick={(event) => {
146 event.currentTarget.focus({ preventScroll: true });
147 expandAndFocusNotice();
148 }}
149 className={cn(stackExpanded && "pointer-events-none invisible opacity-0")}
150 />
151 ) : null}
152 <div
153 id={expandedItemsId}
154 ref={expandedItemsRef}
155 role="group"
156 aria-label="Other notices"
157 tabIndex={-1}
158 data-composer-banner-stack-expanded-items="true"
159 className={cn(
160 "grid transition-[grid-template-rows] duration-150 ease-out focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring",
161 stackExpanded ? "grid-rows-[1fr]" : "grid-rows-[0fr]",
162 )}
163 >
164 {/* Horizontal clipping shaves the right border at fractional widths. */}
165 <div className="min-h-0 overflow-y-clip">
166 <div
167 className={cn(
168 "transform-gpu space-y-2 pb-2 transition-[opacity,transform] duration-150 ease-out will-change-transform",
169 stackExpanded
170 ? "pointer-events-auto visible translate-y-0 opacity-100"
171 : "pointer-events-none invisible translate-y-1 opacity-0",
172 )}
173 >
174 {stackedItems.map((item) => (
175 <div
176 key={item.id}
177 className={cn(
178 "transition-[opacity,translate] duration-220 ease-in",
179 exitingItemId === item.id
180 ? "pointer-events-none translate-y-28 opacity-0"
181 : "opacity-100",
182 )}
183 >
184 <ComposerBannerStackAlert
185 item={item}
186 attached={false}
187 exiting={exitingItemId === item.id}
188 onDismissRequest={() => requestDismiss(item)}
189 />
190 </div>
191 ))}
192 </div>
193 </div>
194 </div>
195 </div>
196 ) : null}
197 {attachedAbove}
198 <ComposerBanner.Attachment
199 className={className}
200 data-composer-banner-drawer="true"
201 data-chat-composer-collapsed-controls="true"
202 >
203 <div
204 key={frontItem.id}
205 className={cn(
206 "relative z-10 transition-[opacity,translate] duration-220 ease-in",
207 exitingItemId === frontItem.id
208 ? "pointer-events-none translate-y-16 opacity-0"
209 : "opacity-100",
210 )}
211 onPointerDownCapture={() => {
212 setStackExpanded(false);
213 const activeElement = document.activeElement;
214 if (
215 activeElement instanceof HTMLElement &&
216 noticesRef.current?.contains(activeElement)
217 ) {
218 activeElement.blur();
219 }
220 }}
221 >
222 <ComposerBannerStackAlert
223 item={frontItem}
224 attached
225 exiting={exitingItemId === frontItem.id}
226 onDismissRequest={() => requestDismiss(frontItem)}
227 />
228 </div>
229 </ComposerBanner.Attachment>
230 </>
231 );
232}
233
234function NoticeText({
235 children,
236 className,
237 detailsLabel,
238}: {
239 readonly children: ReactNode;
240 readonly className: string;
241 readonly detailsLabel: string;
242}) {
243 const textRef = useRef<HTMLSpanElement>(null);
244 const detailsRef = useRef<HTMLButtonElement>(null);
245 const [showDetails, setShowDetails] = useState(false);
246
247 useLayoutEffect(() => {
248 const text = textRef.current;
249 if (!text) return;
250 const measure = () => {
251 // Ignore the space taken by the details button itself so it cannot
252 // sustain its own overflow after the text would otherwise fit.
253 const recoveredWidth = detailsRef.current ? detailsRef.current.offsetWidth + 4 : 0;
254 const hidden = getComputedStyle(text).position === "absolute";
255 setShowDetails(
256 hidden ||
257 [text, ...text.querySelectorAll("*")].some(
258 (element) => element.scrollWidth > element.clientWidth + recoveredWidth,
259 ),
260 );
261 };
262 measure();
263 const stopObserving = observeResize(text, measure);
264 const mutations = new MutationObserver(measure);
265 mutations.observe(text, { childList: true, subtree: true, characterData: true });
266 return () => {
267 stopObserving();
268 mutations.disconnect();
269 };
270 }, []);
271
272 return (
273 <span className="contents">
274 <span ref={textRef} className={className}>
275 {children}
276 </span>
277 {showDetails ? (
278 <Popover>
279 <PopoverTrigger
280 openOnHover
281 render={
282 <Button
283 ref={detailsRef}
284 size="icon-xs"
285 variant="ghost-muted"
286 aria-label={detailsLabel}
287 className="flex-none"
288 />
289 }
290 >
291 <InfoIcon />
292 </PopoverTrigger>
293 <PopoverPopup
294 aria-label="Notice details"
295 tooltipStyle
296 side="top"
297 className="max-w-[min(30rem,calc(100vw-2rem))] whitespace-normal wrap-anywhere [--inline-button-text-align:start] [--inline-button-white-space:normal] [&_[data-slot=inline-button]]:max-w-full"
298 >
299 <ComposerBanner.Scroll className="max-h-[min(var(--available-height),24rem,40dvh)]">
300 {children}
301 </ComposerBanner.Scroll>
302 </PopoverPopup>
303 </Popover>
304 ) : null}
305 </span>
306 );
307}
308
309function ComposerBannerStackAlert({
310 item,
311 attached,
312 exiting,
313 onDismissRequest,
314}: {
315 readonly item: ComposerBannerStackEntry;
316 readonly attached: boolean;
317 readonly exiting: boolean;
318 readonly onDismissRequest: () => void;
319}) {
320 if ("content" in item) {
321 return (
322 <ComposerBanner.Root
323 density="comfortable"
324 placement={attached ? "attached" : "floating"}
325 variant={item.variant}
326 >
327 {item.content}
328 </ComposerBanner.Root>
329 );
330 }
331 return (
332 <ComposerBanner.Root
333 role="alert"
334 placement={attached ? "attached" : "floating"}
335 variant={item.variant}
336 density="comfortable"
337 >
338 <ComposerBanner.Row layout={item.priority === "activity" ? "inline" : "wrap-actions"}>
339 <ComposerBanner.Icon className="h-(--composer-banner-icon-column) self-start">
340 {item.icon}
341 </ComposerBanner.Icon>
342 <ComposerBanner.Content className="whitespace-nowrap">
343 <NoticeText
344 detailsLabel="Show title details"
345 className="min-w-0 truncate font-medium leading-7 sm:leading-6"
346 >
347 {item.title}
348 </NoticeText>
349 {item.description ? (
350 <NoticeText
351 detailsLabel="Show notice details"
352 className="w-0 min-w-0 grow truncate text-muted-foreground @max-[400px]:sr-only"
353 >
354 {item.description}
355 </NoticeText>
356 ) : null}
357 </ComposerBanner.Content>
358 {item.actions || item.onDismiss ? (
359 <ComposerBanner.Actions>
360 {item.actions}
361 {item.onDismiss ? (
362 <ComposerBanner.Dismiss
363 aria-label={item.dismissLabel ?? "Dismiss warning"}
364 disabled={exiting}
365 onClick={onDismissRequest}
366 />
367 ) : null}
368 </ComposerBanner.Actions>
369 ) : null}
370 </ComposerBanner.Row>
371 {item.children ? <ComposerBanner.Children>{item.children}</ComposerBanner.Children> : null}
372 </ComposerBanner.Root>
373 );
374}