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

ComposerBannerStack.tsx

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