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