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 === "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 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-chat-composer-collapsed-controls="true"
125 className={cn("relative z-20 min-h-3", stackExpanded && "z-50")}
126 onPointerEnter={(event) => {
127 if (event.pointerType === "touch") return;
128 if (document.activeElement === peekRef.current) {
129 pendingFocusRef.current = "notice";
130 }
131 setStackExpanded(true);
132 }}
133 onPointerLeave={(event) => {
134 if (!event.currentTarget.contains(document.activeElement)) setStackExpanded(false);
135 }}
136 onBlurCapture={(event) => {
137 if (
138 !event.currentTarget.contains(event.relatedTarget) &&
139 !event.currentTarget.matches(":hover")
140 ) {
141 setStackExpanded(false);
142 }
143 }}
144 onKeyDown={(event) => {
145 if (event.key !== "Escape" || !stackExpanded) return;
146 event.preventDefault();
147 event.stopPropagation();
148 pendingFocusRef.current = "peek";
149 setStackExpanded(false);
150 }}
151 >
152 {showCollapsedStackCap && firstStackedItem ? (
153 <ComposerBanner.Peek
154 ref={peekRef}
155 variant={firstStackedItem.variant}
156 aria-label="Show other notices"
157 aria-expanded={stackExpanded}
158 aria-controls={expandedItemsId}
159 aria-hidden={stackExpanded || undefined}
160 tabIndex={stackExpanded ? -1 : 0}
161 onClick={(event) => {
162 event.currentTarget.focus({ preventScroll: true });
163 pendingFocusRef.current = "notice";
164 setStackExpanded(true);
165 }}
166 className={cn(stackExpanded && "pointer-events-none invisible opacity-0")}
167 />
168 ) : null}
169 <div
170 id={expandedItemsId}
171 ref={expandedItemsRef}
172 role="group"
173 aria-label="Other notices"
174 tabIndex={-1}
175 data-composer-banner-stack-expanded-items="true"
176 className={cn(
177 "grid transition-[grid-template-rows] duration-150 ease-out focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring",
178 stackExpanded ? "grid-rows-[1fr]" : "grid-rows-[0fr]",
179 )}
180 >
181 <div className="min-h-0 overflow-hidden">
182 <div
183 className={cn(
184 "transform-gpu space-y-2 pb-2 transition-[opacity,transform] duration-150 ease-out will-change-[opacity,transform]",
185 stackExpanded
186 ? "pointer-events-auto visible translate-y-0 opacity-100"
187 : "pointer-events-none invisible translate-y-1 opacity-0",
188 )}
189 >
190 {stackedItems.map((item) => (
191 <div
192 key={item.id}
193 className={cn(
194 "transition-[opacity,translate] duration-220 ease-in",
195 exitingItemId === item.id
196 ? "pointer-events-none translate-y-28 opacity-0"
197 : "opacity-100",
198 )}
199 >
200 <ComposerBannerStackAlert
201 item={item}
202 attached={false}
203 exiting={exitingItemId === item.id}
204 onDismissRequest={() => requestDismiss(item)}
205 />
206 </div>
207 ))}
208 </div>
209 </div>
210 </div>
211 </div>
212 ) : null}
213 {attachedAbove}
214 <ComposerBanner.Attachment
215 className={className}
216 data-composer-banner-drawer="true"
217 data-chat-composer-collapsed-controls="true"
218 >
219 <div
220 key={frontItem.id}
221 className={cn(
222 "relative z-10 transition-[opacity,translate] duration-220 ease-in",
223 exitingItemId === frontItem.id
224 ? "pointer-events-none translate-y-16 opacity-0"
225 : "opacity-100",
226 )}
227 onPointerDownCapture={() => {
228 setStackExpanded(false);
229 const activeElement = document.activeElement;
230 if (
231 activeElement instanceof HTMLElement &&
232 noticesRef.current?.contains(activeElement)
233 ) {
234 activeElement.blur();
235 }
236 }}
237 >
238 <ComposerBannerStackAlert
239 item={frontItem}
240 attached
241 exiting={exitingItemId === frontItem.id}
242 onDismissRequest={() => requestDismiss(frontItem)}
243 />
244 </div>
245 </ComposerBanner.Attachment>
246 </>
247 );
248}
249
250function NoticeDescription({ children }: { children: ReactNode }) {
251 const descriptionRef = useRef<HTMLSpanElement>(null);
252 const detailsRef = useRef<HTMLButtonElement>(null);
253 const [showDetails, setShowDetails] = useState(false);
254
255 useLayoutEffect(() => {
256 const description = descriptionRef.current;
257 if (!description) return;
258 const measure = () => {
259 // Ignore the space taken by the details button itself so it cannot
260 // sustain its own overflow after the description would otherwise fit.
261 const recoveredWidth = detailsRef.current ? detailsRef.current.offsetWidth + 4 : 0;
262 const hidden = getComputedStyle(description).position === "absolute";
263 setShowDetails(
264 hidden ||
265 [description, ...description.querySelectorAll("*")].some(
266 (element) => element.scrollWidth > element.clientWidth + recoveredWidth,
267 ),
268 );
269 };
270 measure();
271 const stopObserving = observeResize(description, measure);
272 const mutations = new MutationObserver(measure);
273 mutations.observe(description, { childList: true, subtree: true, characterData: true });
274 return () => {
275 stopObserving();
276 mutations.disconnect();
277 };
278 }, []);
279
280 return (
281 <span className="contents">
282 <span
283 ref={descriptionRef}
284 className="w-0 min-w-0 grow truncate text-muted-foreground @max-[400px]:sr-only"
285 >
286 {children}
287 </span>
288 {showDetails ? (
289 <Popover>
290 <PopoverTrigger
291 openOnHover
292 render={
293 <Button
294 ref={detailsRef}
295 size="icon-xs"
296 variant="ghost-muted"
297 aria-label="Show notice details"
298 className="flex-none"
299 />
300 }
301 >
302 <InfoIcon />
303 </PopoverTrigger>
304 <PopoverPopup
305 aria-label="Notice details"
306 tooltipStyle
307 side="top"
308 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"
309 >
310 <ComposerBanner.Scroll className="max-h-[min(var(--available-height),24rem,40dvh)]">
311 {children}
312 </ComposerBanner.Scroll>
313 </PopoverPopup>
314 </Popover>
315 ) : null}
316 </span>
317 );
318}
319
320function ComposerBannerStackAlert({
321 item,
322 attached,
323 exiting,
324 onDismissRequest,
325}: {
326 readonly item: ComposerBannerStackEntry;
327 readonly attached: boolean;
328 readonly exiting: boolean;
329 readonly onDismissRequest: () => void;
330}) {
331 if ("content" in item) {
332 return (
333 <ComposerBanner.Root
334 density="comfortable"
335 placement={attached ? "attached" : "floating"}
336 variant={item.variant}
337 >
338 {item.content}
339 </ComposerBanner.Root>
340 );
341 }
342 return (
343 <ComposerBanner.Root
344 role="alert"
345 placement={attached ? "attached" : "floating"}
346 variant={item.variant}
347 density="comfortable"
348 >
349 <ComposerBanner.Row layout={item.priority === "activity" ? "inline" : "wrap-actions"}>
350 <ComposerBanner.Icon className="h-(--composer-banner-icon-column) self-start">
351 {item.icon}
352 </ComposerBanner.Icon>
353 <ComposerBanner.Content className="whitespace-nowrap">
354 <span className="min-w-0 truncate font-medium leading-7 sm:leading-6">{item.title}</span>
355 {item.description ? <NoticeDescription>{item.description}</NoticeDescription> : null}
356 </ComposerBanner.Content>
357 {item.actions || item.onDismiss ? (
358 <ComposerBanner.Actions>
359 {item.actions}
360 {item.onDismiss ? (
361 <ComposerBanner.Dismiss
362 aria-label={item.dismissLabel ?? "Dismiss warning"}
363 disabled={exiting}
364 onClick={onDismissRequest}
365 />
366 ) : null}
367 </ComposerBanner.Actions>
368 ) : null}
369 </ComposerBanner.Row>
370 {item.children ? <ComposerBanner.Children>{item.children}</ComposerBanner.Children> : null}
371 </ComposerBanner.Root>
372 );
373}