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