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";
8
9// Match the duration-220 exit transition before removing a dismissed notice.
10const DISMISS_TRANSITION_MS = 220;
11
12export interface ComposerBannerStackItem {
13 readonly id: string;
14 readonly variant: ComposerBannerVariant;
15 readonly priority?: "urgent" | "activity" | "notice";
16 readonly compact?: boolean;
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 === "activity") {
35 return 0;
36 }
37 if (item.priority === "urgent" || item.variant === "error" || item.variant === "warning") {
38 return 1;
39 }
40 return 2;
41}
42
43interface ComposerBannerStackProps {
44 readonly className?: string;
45 readonly items: ReadonlyArray<ComposerBannerStackEntry>;
46}
47
48export function ComposerBannerStack({ className, items }: ComposerBannerStackProps) {
49 const [stackExpanded, setStackExpanded] = useState(false);
50 const noticesRef = useRef<HTMLDivElement>(null);
51 const peekRef = useRef<HTMLButtonElement>(null);
52 const expandedItemsRef = useRef<HTMLDivElement>(null);
53 const pendingFocusRef = useRef<"peek" | "notice" | null>(null);
54 const expandedItemsId = useId();
55 const [requestedExitingItemId, setExitingItemId] = useState<string | null>(null);
56 const dismissTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
57 const exitingItemId =
58 requestedExitingItemId !== null && items.some((item) => item.id === requestedExitingItemId)
59 ? requestedExitingItemId
60 : null;
61
62 useEffect(() => {
63 return () => {
64 if (dismissTimeoutRef.current) {
65 clearTimeout(dismissTimeoutRef.current);
66 }
67 };
68 }, []);
69
70 useEffect(() => {
71 if (items.length < 2) setStackExpanded(false);
72 }, [items.length]);
73
74 useLayoutEffect(() => {
75 if (stackExpanded && pendingFocusRef.current === "notice") {
76 pendingFocusRef.current = null;
77 const firstControl = expandedItemsRef.current?.querySelector<HTMLElement>(
78 'button:not(:disabled), a[href], input:not(:disabled), [tabindex="0"]',
79 );
80 (firstControl ?? expandedItemsRef.current)?.focus({ preventScroll: true });
81 } else if (!stackExpanded && pendingFocusRef.current === "peek") {
82 pendingFocusRef.current = null;
83 peekRef.current?.focus({ preventScroll: true });
84 }
85 }, [stackExpanded]);
86
87 if (items.length === 0) {
88 return null;
89 }
90
91 // Activity stays attached. Urgency and severity only order the notices behind it.
92 const orderedItems = items.toSorted((a, b) => bannerPriority(a) - bannerPriority(b));
93 const frontItem = orderedItems[0];
94 if (!frontItem) {
95 return null;
96 }
97 const stackedItems = orderedItems.slice(1);
98 const hasStack = stackedItems.length > 0;
99 const showCollapsedStackCap = hasStack && exitingItemId !== frontItem.id;
100 const firstStackedItem = stackedItems[0];
101
102 const requestDismiss = (item: ComposerBannerStackEntry) => {
103 if (!("onDismiss" in item) || !item.onDismiss || exitingItemId) {
104 return;
105 }
106 setExitingItemId(item.id);
107 if (dismissTimeoutRef.current) {
108 clearTimeout(dismissTimeoutRef.current);
109 }
110 dismissTimeoutRef.current = setTimeout(() => {
111 dismissTimeoutRef.current = null;
112 item.onDismiss?.();
113 }, DISMISS_TRANSITION_MS);
114 };
115
116 return (
117 <ComposerBanner.Attachment
118 className={className}
119 data-composer-banner-drawer="true"
120 data-chat-composer-collapsed-controls="true"
121 >
122 <div className={cn("relative flex flex-col-reverse", hasStack && stackExpanded && "z-50")}>
123 <div
124 key={frontItem.id}
125 className={cn(
126 "relative z-10 transition-[translate,opacity] duration-220 ease-in",
127 exitingItemId === frontItem.id
128 ? "pointer-events-none translate-y-16 opacity-0"
129 : "opacity-100",
130 )}
131 onPointerDownCapture={() => {
132 setStackExpanded(false);
133 const activeElement = document.activeElement;
134 if (
135 activeElement instanceof HTMLElement &&
136 noticesRef.current?.contains(activeElement)
137 ) {
138 activeElement.blur();
139 }
140 }}
141 >
142 <ComposerBannerStackAlert
143 item={frontItem}
144 attached
145 exiting={exitingItemId === frontItem.id}
146 onDismissRequest={() => requestDismiss(frontItem)}
147 />
148 </div>
149 {hasStack ? (
150 <div
151 ref={noticesRef}
152 className="relative z-20 min-h-3"
153 onPointerEnter={(event) => {
154 if (event.pointerType === "touch") return;
155 if (document.activeElement === peekRef.current) {
156 pendingFocusRef.current = "notice";
157 }
158 setStackExpanded(true);
159 }}
160 onPointerLeave={(event) => {
161 if (!event.currentTarget.contains(document.activeElement)) setStackExpanded(false);
162 }}
163 onBlurCapture={(event) => {
164 if (
165 !event.currentTarget.contains(event.relatedTarget) &&
166 !event.currentTarget.matches(":hover")
167 ) {
168 setStackExpanded(false);
169 }
170 }}
171 onKeyDown={(event) => {
172 if (event.key !== "Escape" || !stackExpanded) return;
173 event.preventDefault();
174 event.stopPropagation();
175 pendingFocusRef.current = "peek";
176 setStackExpanded(false);
177 }}
178 >
179 {showCollapsedStackCap && firstStackedItem ? (
180 <ComposerBanner.Peek
181 ref={peekRef}
182 variant={firstStackedItem.variant}
183 aria-label="Show other notices"
184 aria-expanded={stackExpanded}
185 aria-controls={expandedItemsId}
186 aria-hidden={stackExpanded || undefined}
187 tabIndex={stackExpanded ? -1 : 0}
188 onClick={(event) => {
189 event.currentTarget.focus({ preventScroll: true });
190 pendingFocusRef.current = "notice";
191 setStackExpanded(true);
192 }}
193 className={cn(stackExpanded && "pointer-events-none invisible opacity-0")}
194 />
195 ) : null}
196 <div
197 id={expandedItemsId}
198 ref={expandedItemsRef}
199 role="group"
200 aria-label="Other notices"
201 tabIndex={-1}
202 data-composer-banner-stack-expanded-items="true"
203 className={cn(
204 "grid transition-[grid-template-rows] duration-150 ease-out focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring",
205 stackExpanded ? "grid-rows-[1fr]" : "grid-rows-[0fr]",
206 )}
207 >
208 <div className="min-h-0 overflow-hidden">
209 <div
210 className={cn(
211 "transform-gpu space-y-2 pb-2 transition-[opacity,transform] duration-150 ease-out will-change-[opacity,transform]",
212 stackExpanded
213 ? "pointer-events-auto visible translate-y-0 opacity-100"
214 : "pointer-events-none invisible translate-y-1 opacity-0",
215 )}
216 >
217 {stackedItems.map((item) => (
218 <div
219 key={item.id}
220 className={cn(
221 "transition-[translate,opacity] duration-220 ease-in",
222 exitingItemId === item.id
223 ? "pointer-events-none translate-y-28 opacity-0"
224 : "opacity-100",
225 )}
226 >
227 <ComposerBannerStackAlert
228 item={item}
229 attached={false}
230 exiting={exitingItemId === item.id}
231 onDismissRequest={() => requestDismiss(item)}
232 />
233 </div>
234 ))}
235 </div>
236 </div>
237 </div>
238 </div>
239 ) : null}
240 </div>
241 </ComposerBanner.Attachment>
242 );
243}
244
245function ComposerBannerStackAlert({
246 item,
247 attached,
248 exiting,
249 onDismissRequest,
250}: {
251 readonly item: ComposerBannerStackEntry;
252 readonly attached: boolean;
253 readonly exiting: boolean;
254 readonly onDismissRequest: () => void;
255}) {
256 if ("content" in item) {
257 return (
258 <ComposerBanner.Root
259 density="comfortable"
260 placement={attached ? "attached" : "floating"}
261 variant={item.variant}
262 >
263 {item.content}
264 </ComposerBanner.Root>
265 );
266 }
267 return (
268 <ComposerBanner.Root
269 role="alert"
270 placement={attached ? "attached" : "floating"}
271 variant={item.variant}
272 density="comfortable"
273 >
274 <ComposerBanner.Row layout={item.compact ? "wrap-actions-narrow" : "wrap-actions"}>
275 <ComposerBanner.Icon className="h-(--composer-banner-icon-column) self-start">
276 {item.icon}
277 </ComposerBanner.Icon>
278 <ComposerBanner.Content className="whitespace-nowrap">
279 <span className="min-w-0 truncate font-medium leading-7 sm:leading-6">{item.title}</span>
280 {item.description ? (
281 <span className={item.compact ? "contents" : "flex min-w-8 flex-1 items-center gap-1"}>
282 <span
283 className={cn(
284 "min-w-0 truncate text-muted-foreground",
285 item.compact && "shrink-[9999] @max-[400px]:sr-only",
286 )}
287 >
288 {item.description}
289 </span>
290 <Popover>
291 <PopoverTrigger
292 openOnHover
293 render={
294 <Button
295 size="icon-xs"
296 variant="ghost"
297 aria-label="Show notice details"
298 className={cn(
299 "flex-none text-muted-foreground hover:text-foreground",
300 item.compact && "hidden @max-[400px]:inline-flex",
301 )}
302 />
303 }
304 >
305 <InfoIcon className="size-3.5" />
306 </PopoverTrigger>
307 <PopoverPopup
308 aria-label="Notice details"
309 tooltipStyle
310 side="top"
311 className="max-w-80 whitespace-normal text-pretty wrap-anywhere"
312 >
313 <ComposerBanner.Scroll className="max-h-[min(var(--available-height),24rem,40dvh)]">
314 {item.description}
315 </ComposerBanner.Scroll>
316 </PopoverPopup>
317 </Popover>
318 </span>
319 ) : null}
320 </ComposerBanner.Content>
321 {item.actions || item.onDismiss ? (
322 <ComposerBanner.Actions>
323 {item.actions}
324 {item.onDismiss ? (
325 <ComposerBanner.Dismiss
326 aria-label={item.dismissLabel ?? "Dismiss warning"}
327 disabled={exiting}
328 onClick={onDismissRequest}
329 />
330 ) : null}
331 </ComposerBanner.Actions>
332 ) : null}
333 </ComposerBanner.Row>
334 {item.children ? <ComposerBanner.Children>{item.children}</ComposerBanner.Children> : null}
335 </ComposerBanner.Root>
336 );
337}