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

ComposerBannerStack.tsx

391 lines13.1 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";
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;
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;
42​
43interface ComposerBannerStackProps {
44 readonly className?: string;
45 readonly items: ReadonlyArray<ComposerBannerStackEntry>;
46 readonly attachedAbove?: ReactNode;
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 if (items.length < 2 && stackExpanded) {
72 setStackExpanded(false);
73 }
74​
75 useLayoutEffect(() => {
76 if (stackExpanded && pendingFocusRef.current === "notice") {
77 pendingFocusRef.current = null;
78 const firstControl = expandedItemsRef.current?.querySelector<HTMLElement>(
79 'button:not(:disabled), a[href], input:not(:disabled), [tabindex="0"]',
80 );
81 (firstControl ?? expandedItemsRef.current)?.focus({ preventScroll: true });
82 } else if (!stackExpanded && pendingFocusRef.current === "peek") {
83 pendingFocusRef.current = null;
84 peekRef.current?.focus({ preventScroll: true });
85 }
86 }, [stackExpanded]);
87​
88 const orderedItems = items.toSorted((a, b) => bannerPriority(a) - bannerPriority(b));
89 const frontItem = orderedItems[0];
90 if (!frontItem) {
91 return (
92 <>
93 {null}
94 {attachedAbove}
95 {null}
96 </>
97 );
98 }
99 const stackedItems = orderedItems.slice(1);
100 const hasStack = stackedItems.length > 0;
101 const showCollapsedStackCap = hasStack && exitingItemId !== frontItem.id;
102 const firstStackedItem = stackedItems[0];
103​
104 const requestDismiss = (item: ComposerBannerStackEntry) => {
105 if (!("onDismiss" in item) || !item.onDismiss || exitingItemId) {
106 return;
107 }
108 setExitingItemId(item.id);
109 if (dismissTimeoutRef.current) {
110 clearTimeout(dismissTimeoutRef.current);
111 }
112 dismissTimeoutRef.current = setTimeout(() => {
113 dismissTimeoutRef.current = null;
114 item.onDismiss?.();
115 }, DISMISS_TRANSITION_MS);
116 };
117​
118 return (
119 <>
120 {hasStack ? (
121 <div
122 ref={noticesRef}
123 data-composer-banner-stack="true"
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 {/* Horizontal clipping shaves the right border at fractional widths. */}
182 <div className="min-h-0 overflow-y-clip">
183 <div
184 className={cn(
185 "transform-gpu space-y-2 pb-2 transition-[opacity,transform] duration-150 ease-out will-change-transform",
186 stackExpanded
187 ? "pointer-events-auto visible translate-y-0 opacity-100"
188 : "pointer-events-none invisible translate-y-1 opacity-0",
189 )}
190 >
191 {stackedItems.map((item) => (
192 <div
193 key={item.id}
194 className={cn(
195 "transition-[opacity,translate] duration-220 ease-in",
196 exitingItemId === item.id
197 ? "pointer-events-none translate-y-28 opacity-0"
198 : "opacity-100",
199 )}
200 >
201 <ComposerBannerStackAlert
202 item={item}
203 attached={false}
204 exiting={exitingItemId === item.id}
205 onDismissRequest={() => requestDismiss(item)}
206 />
207 </div>
208 ))}
209 </div>
210 </div>
211 </div>
212 </div>
213 ) : null}
214 {attachedAbove}
215 <ComposerBanner.Attachment
216 className={className}
217 data-composer-banner-drawer="true"
218 data-chat-composer-collapsed-controls="true"
219 >
220 <div
221 key={frontItem.id}
222 className={cn(
223 "relative z-10 transition-[opacity,translate] duration-220 ease-in",
224 exitingItemId === frontItem.id
225 ? "pointer-events-none translate-y-16 opacity-0"
226 : "opacity-100",
227 )}
228 onPointerDownCapture={() => {
229 setStackExpanded(false);
230 const activeElement = document.activeElement;
231 if (
232 activeElement instanceof HTMLElement &&
233 noticesRef.current?.contains(activeElement)
234 ) {
235 activeElement.blur();
236 }
237 }}
238 >
239 <ComposerBannerStackAlert
240 item={frontItem}
241 attached
242 exiting={exitingItemId === frontItem.id}
243 onDismissRequest={() => requestDismiss(frontItem)}
244 />
245 </div>
246 </ComposerBanner.Attachment>
247 </>
248 );
250​
251function NoticeText({
252 children,
253 className,
254 detailsLabel,
255}: {
256 readonly children: ReactNode;
257 readonly className: string;
258 readonly detailsLabel: string;
259}) {
260 const textRef = useRef<HTMLSpanElement>(null);
261 const detailsRef = useRef<HTMLButtonElement>(null);
262 const [showDetails, setShowDetails] = useState(false);
263​
264 useLayoutEffect(() => {
265 const text = textRef.current;
266 if (!text) return;
267 const measure = () => {
268 // Ignore the space taken by the details button itself so it cannot
269 // sustain its own overflow after the text would otherwise fit.
270 const recoveredWidth = detailsRef.current ? detailsRef.current.offsetWidth + 4 : 0;
271 const hidden = getComputedStyle(text).position === "absolute";
272 setShowDetails(
273 hidden ||
274 [text, ...text.querySelectorAll("*")].some(
275 (element) => element.scrollWidth > element.clientWidth + recoveredWidth,
276 ),
277 );
278 };
279 measure();
280 const stopObserving = observeResize(text, measure);
281 const mutations = new MutationObserver(measure);
282 mutations.observe(text, { childList: true, subtree: true, characterData: true });
283 return () => {
284 stopObserving();
285 mutations.disconnect();
286 };
287 }, []);
288​
289 return (
290 <span className="contents">
291 <span ref={textRef} className={className}>
292 {children}
293 </span>
294 {showDetails ? (
295 <Popover>
296 <PopoverTrigger
297 openOnHover
298 render={
299 <Button
300 ref={detailsRef}
301 size="icon-xs"
302 variant="ghost-muted"
303 aria-label={detailsLabel}
304 className="flex-none"
305 />
306 }
307 >
308 <InfoIcon />
309 </PopoverTrigger>
310 <PopoverPopup
311 aria-label="Notice details"
312 tooltipStyle
313 side="top"
314 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"
315 >
316 <ComposerBanner.Scroll className="max-h-[min(var(--available-height),24rem,40dvh)]">
317 {children}
318 </ComposerBanner.Scroll>
319 </PopoverPopup>
320 </Popover>
321 ) : null}
322 </span>
323 );
325​
326function ComposerBannerStackAlert({
327 item,
328 attached,
329 exiting,
330 onDismissRequest,
331}: {
332 readonly item: ComposerBannerStackEntry;
333 readonly attached: boolean;
334 readonly exiting: boolean;
335 readonly onDismissRequest: () => void;
336}) {
337 if ("content" in item) {
338 return (
339 <ComposerBanner.Root
340 density="comfortable"
341 placement={attached ? "attached" : "floating"}
342 variant={item.variant}
343 >
344 {item.content}
345 </ComposerBanner.Root>
346 );
347 }
348 return (
349 <ComposerBanner.Root
350 role="alert"
351 placement={attached ? "attached" : "floating"}
352 variant={item.variant}
353 density="comfortable"
354 >
355 <ComposerBanner.Row layout={item.priority === "activity" ? "inline" : "wrap-actions"}>
356 <ComposerBanner.Icon className="h-(--composer-banner-icon-column) self-start">
357 {item.icon}
358 </ComposerBanner.Icon>
359 <ComposerBanner.Content className="whitespace-nowrap">
360 <NoticeText
361 detailsLabel="Show title details"
362 className="min-w-0 truncate font-medium leading-7 sm:leading-6"
363 >
364 {item.title}
365 </NoticeText>
366 {item.description ? (
367 <NoticeText
368 detailsLabel="Show notice details"
369 className="w-0 min-w-0 grow truncate text-muted-foreground @max-[400px]:sr-only"
370 >
371 {item.description}
372 </NoticeText>
373 ) : null}
374 </ComposerBanner.Content>
375 {item.actions || item.onDismiss ? (
376 <ComposerBanner.Actions>
377 {item.actions}
378 {item.onDismiss ? (
379 <ComposerBanner.Dismiss
380 aria-label={item.dismissLabel ?? "Dismiss warning"}
381 disabled={exiting}
382 onClick={onDismissRequest}
383 />
384 ) : null}
385 </ComposerBanner.Actions>
386 ) : null}
387 </ComposerBanner.Row>
388 {item.children ? <ComposerBanner.Children>{item.children}</ComposerBanner.Children> : null}
389 </ComposerBanner.Root>
390 );