Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ComposerBannerStack.tsx

332 lines11.5 KB

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;
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;
41​
42interface ComposerBannerStackProps {
43 readonly className?: string;
44 readonly items: ReadonlyArray<ComposerBannerStackEntry>;
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 key={frontItem.id}
124 className={cn(
125 "relative z-10 transition-[translate,opacity] duration-220 ease-in",
126 exitingItemId === frontItem.id
127 ? "pointer-events-none translate-y-16 opacity-0"
128 : "opacity-100",
129 )}
130 onPointerDownCapture={() => {
131 setStackExpanded(false);
132 const activeElement = document.activeElement;
133 if (
134 activeElement instanceof HTMLElement &&
135 noticesRef.current?.contains(activeElement)
136 ) {
137 activeElement.blur();
138 }
139 }}
140 >
141 <ComposerBannerStackAlert
142 item={frontItem}
143 attached
144 exiting={exitingItemId === frontItem.id}
145 onDismissRequest={() => requestDismiss(frontItem)}
146 />
147 </div>
148 {hasStack ? (
149 <div
150 ref={noticesRef}
151 className="relative z-20 min-h-3"
152 onPointerEnter={(event) => {
153 if (event.pointerType === "touch") return;
154 if (document.activeElement === peekRef.current) {
155 pendingFocusRef.current = "notice";
156 }
157 setStackExpanded(true);
158 }}
159 onPointerLeave={(event) => {
160 if (!event.currentTarget.contains(document.activeElement)) setStackExpanded(false);
161 }}
162 onBlurCapture={(event) => {
163 if (
164 !event.currentTarget.contains(event.relatedTarget) &&
165 !event.currentTarget.matches(":hover")
166 ) {
167 setStackExpanded(false);
168 }
169 }}
170 onKeyDown={(event) => {
171 if (event.key !== "Escape" || !stackExpanded) return;
172 event.preventDefault();
173 event.stopPropagation();
174 pendingFocusRef.current = "peek";
175 setStackExpanded(false);
176 }}
177 >
178 {showCollapsedStackCap && firstStackedItem ? (
179 <ComposerBanner.Peek
180 ref={peekRef}
181 variant={firstStackedItem.variant}
182 aria-label="Show other notices"
183 aria-expanded={stackExpanded}
184 aria-controls={expandedItemsId}
185 aria-hidden={stackExpanded || undefined}
186 tabIndex={stackExpanded ? -1 : 0}
187 onClick={(event) => {
188 event.currentTarget.focus({ preventScroll: true });
189 pendingFocusRef.current = "notice";
190 setStackExpanded(true);
191 }}
192 className={cn(stackExpanded && "pointer-events-none invisible opacity-0")}
193 />
194 ) : null}
195 <div
196 id={expandedItemsId}
197 ref={expandedItemsRef}
198 role="group"
199 aria-label="Other notices"
200 tabIndex={-1}
201 data-composer-banner-stack-expanded-items="true"
202 className={cn(
203 "grid transition-[grid-template-rows] duration-150 ease-out focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring",
204 stackExpanded ? "grid-rows-[1fr]" : "grid-rows-[0fr]",
205 )}
206 >
207 <div className="min-h-0 overflow-hidden">
208 <div
209 className={cn(
210 "transform-gpu space-y-2 pb-2 transition-[opacity,transform] duration-150 ease-out will-change-[opacity,transform]",
211 stackExpanded
212 ? "pointer-events-auto visible translate-y-0 opacity-100"
213 : "pointer-events-none invisible translate-y-1 opacity-0",
214 )}
215 >
216 {stackedItems.map((item) => (
217 <div
218 key={item.id}
219 className={cn(
220 "transition-[translate,opacity] duration-220 ease-in",
221 exitingItemId === item.id
222 ? "pointer-events-none translate-y-28 opacity-0"
223 : "opacity-100",
224 )}
225 >
226 <ComposerBannerStackAlert
227 item={item}
228 attached={false}
229 exiting={exitingItemId === item.id}
230 onDismissRequest={() => requestDismiss(item)}
231 />
232 </div>
233 ))}
234 </div>
235 </div>
236 </div>
237 </div>
238 ) : null}
239 </div>
240 </ComposerBanner.Attachment>
241 );
243​
244function ComposerBannerStackAlert({
245 item,
246 attached,
247 exiting,
248 onDismissRequest,
249}: {
250 readonly item: ComposerBannerStackEntry;
251 readonly attached: boolean;
252 readonly exiting: boolean;
253 readonly onDismissRequest: () => void;
254}) {
255 if ("content" in item) {
256 return (
257 <ComposerBanner.Root
258 density="comfortable"
259 placement={attached ? "attached" : "floating"}
260 variant={item.variant}
261 >
262 {item.content}
263 </ComposerBanner.Root>
264 );
265 }
266 return (
267 <ComposerBanner.Root
268 role="alert"
269 placement={attached ? "attached" : "floating"}
270 variant={item.variant}
271 density="comfortable"
272 >
273 <ComposerBanner.Row layout="wrap-actions-narrow">
274 <ComposerBanner.Icon className="h-(--composer-banner-icon-column) self-start">
275 {item.icon}
276 </ComposerBanner.Icon>
277 <ComposerBanner.Content className="whitespace-nowrap">
278 <span
279 className={cn(
280 "min-w-0 font-medium leading-7 sm:leading-6",
281 typeof item.title === "string" && "truncate",
282 )}
283 >
284 {item.title}
285 </span>
286 {item.description ? (
287 <>
288 <span className="min-w-0 shrink-[9999] truncate text-muted-foreground @max-[400px]:sr-only">
289 {item.description}
290 </span>
291 <Popover>
292 <PopoverTrigger
293 openOnHover
294 render={
295 <Button
296 size="icon-xs"
297 variant="ghost"
298 aria-label="Show notice details"
299 className="hidden flex-none text-muted-foreground hover:text-foreground @max-[400px]:inline-flex"
300 />
301 }
302 >
303 <InfoIcon className="size-3.5" />
304 </PopoverTrigger>
305 <PopoverPopup
306 tooltipStyle
307 side="top"
308 className="max-w-72 whitespace-normal text-pretty"
309 >
310 {item.description}
311 </PopoverPopup>
312 </Popover>
313 </>
314 ) : null}
315 </ComposerBanner.Content>
316 {item.actions || item.onDismiss ? (
317 <ComposerBanner.Actions>
318 {item.actions}
319 {item.onDismiss ? (
320 <ComposerBanner.Dismiss
321 aria-label={item.dismissLabel ?? "Dismiss warning"}
322 disabled={exiting}
323 onClick={onDismissRequest}
324 />
325 ) : null}
326 </ComposerBanner.Actions>
327 ) : null}
328 </ComposerBanner.Row>
329 {item.children ? <ComposerBanner.Children>{item.children}</ComposerBanner.Children> : null}
330 </ComposerBanner.Root>
331 );