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 NoticeDescription({ children }: { children: ReactNode }) {
254 const descriptionRef = useRef<HTMLSpanElement>(null);
255 const detailsRef = useRef<HTMLButtonElement>(null);
256 const [showDetails, setShowDetails] = useState(false);
257
258 useLayoutEffect(() => {
259 const description = descriptionRef.current;
260 if (!description) return;
261 const measure = () => {
262 // Ignore the space taken by the details button itself so it cannot
263 // sustain its own overflow after the description would otherwise fit.
264 const recoveredWidth = detailsRef.current ? detailsRef.current.offsetWidth + 4 : 0;
265 const hidden = getComputedStyle(description).position === "absolute";
266 setShowDetails(
267 hidden ||
268 [description, ...description.querySelectorAll("*")].some(
269 (element) => element.scrollWidth > element.clientWidth + recoveredWidth,
270 ),
271 );
272 };
273 measure();
274 const stopObserving = observeResize(description, measure);
275 const mutations = new MutationObserver(measure);
276 mutations.observe(description, { childList: true, subtree: true, characterData: true });
277 return () => {
278 stopObserving();
279 mutations.disconnect();
280 };
281 }, []);
282
283 return (
284 <span className="contents">
285 <span
286 ref={descriptionRef}
287 className="w-0 min-w-0 grow truncate text-muted-foreground @max-[400px]:sr-only"
288 >
289 {children}
290 </span>
291 {showDetails ? (
292 <Popover>
293 <PopoverTrigger
294 openOnHover
295 render={
296 <Button
297 ref={detailsRef}
298 size="icon-xs"
299 variant="ghost-muted"
300 aria-label="Show notice details"
301 className="flex-none"
302 />
303 }
304 >
305 <InfoIcon />
306 </PopoverTrigger>
307 <PopoverPopup
308 aria-label="Notice details"
309 tooltipStyle
310 side="top"
311 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"
312 >
313 <ComposerBanner.Scroll className="max-h-[min(var(--available-height),24rem,40dvh)]">
314 {children}
315 </ComposerBanner.Scroll>
316 </PopoverPopup>
317 </Popover>
318 ) : null}
319 </span>
320 );
321}
322
323function ComposerBannerStackAlert({
324 item,
325 attached,
326 exiting,
327 onDismissRequest,
328}: {
329 readonly item: ComposerBannerStackEntry;
330 readonly attached: boolean;
331 readonly exiting: boolean;
332 readonly onDismissRequest: () => void;
333}) {
334 if ("content" in item) {
335 return (
336 <ComposerBanner.Root
337 density="comfortable"
338 placement={attached ? "attached" : "floating"}
339 variant={item.variant}
340 >
341 {item.content}
342 </ComposerBanner.Root>
343 );
344 }
345 return (
346 <ComposerBanner.Root
347 role="alert"
348 placement={attached ? "attached" : "floating"}
349 variant={item.variant}
350 density="comfortable"
351 >
352 <ComposerBanner.Row layout={item.priority === "activity" ? "inline" : "wrap-actions"}>
353 <ComposerBanner.Icon className="h-(--composer-banner-icon-column) self-start">
354 {item.icon}
355 </ComposerBanner.Icon>
356 <ComposerBanner.Content className="whitespace-nowrap">
357 <span className="min-w-0 truncate font-medium leading-7 sm:leading-6">{item.title}</span>
358 {item.description ? <NoticeDescription>{item.description}</NoticeDescription> : null}
359 </ComposerBanner.Content>
360 {item.actions || item.onDismiss ? (
361 <ComposerBanner.Actions>
362 {item.actions}
363 {item.onDismiss ? (
364 <ComposerBanner.Dismiss
365 aria-label={item.dismissLabel ?? "Dismiss warning"}
366 disabled={exiting}
367 onClick={onDismissRequest}
368 />
369 ) : null}
370 </ComposerBanner.Actions>
371 ) : null}
372 </ComposerBanner.Row>
373 {item.children ? <ComposerBanner.Children>{item.children}</ComposerBanner.Children> : null}
374 </ComposerBanner.Root>
375 );
376}