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

ComposerBannerStack.tsx

375 lines12.9 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 // 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 {/* Clip only the collapsing axis: at fractional widths a horizontal clip
182 shaves the notice's right border. */}
183 <div className="min-h-0 overflow-y-clip">
184 <div
185 className={cn(
186 "transform-gpu space-y-2 pb-2 transition-[opacity,transform] duration-150 ease-out will-change-transform",
187 stackExpanded
188 ? "pointer-events-auto visible translate-y-0 opacity-100"
189 : "pointer-events-none invisible translate-y-1 opacity-0",
190 )}
191 >
192 {stackedItems.map((item) => (
193 <div
194 key={item.id}
195 className={cn(
196 "transition-[opacity,translate] duration-220 ease-in",
197 exitingItemId === item.id
198 ? "pointer-events-none translate-y-28 opacity-0"
199 : "opacity-100",
200 )}
201 >
202 <ComposerBannerStackAlert
203 item={item}
204 attached={false}
205 exiting={exitingItemId === item.id}
206 onDismissRequest={() => requestDismiss(item)}
207 />
208 </div>
209 ))}
210 </div>
211 </div>
212 </div>
213 </div>
214 ) : null}
215 {attachedAbove}
216 <ComposerBanner.Attachment
217 className={className}
218 data-composer-banner-drawer="true"
219 data-chat-composer-collapsed-controls="true"
220 >
221 <div
222 key={frontItem.id}
223 className={cn(
224 "relative z-10 transition-[opacity,translate] duration-220 ease-in",
225 exitingItemId === frontItem.id
226 ? "pointer-events-none translate-y-16 opacity-0"
227 : "opacity-100",
228 )}
229 onPointerDownCapture={() => {
230 setStackExpanded(false);
231 const activeElement = document.activeElement;
232 if (
233 activeElement instanceof HTMLElement &&
234 noticesRef.current?.contains(activeElement)
235 ) {
236 activeElement.blur();
237 }
238 }}
239 >
240 <ComposerBannerStackAlert
241 item={frontItem}
242 attached
243 exiting={exitingItemId === frontItem.id}
244 onDismissRequest={() => requestDismiss(frontItem)}
245 />
246 </div>
247 </ComposerBanner.Attachment>
248 </>
249 );
251​
252function NoticeDescription({ children }: { children: ReactNode }) {
253 const descriptionRef = useRef<HTMLSpanElement>(null);
254 const detailsRef = useRef<HTMLButtonElement>(null);
255 const [showDetails, setShowDetails] = useState(false);
256​
257 useLayoutEffect(() => {
258 const description = descriptionRef.current;
259 if (!description) return;
260 const measure = () => {
261 // Ignore the space taken by the details button itself so it cannot
262 // sustain its own overflow after the description would otherwise fit.
263 const recoveredWidth = detailsRef.current ? detailsRef.current.offsetWidth + 4 : 0;
264 const hidden = getComputedStyle(description).position === "absolute";
265 setShowDetails(
266 hidden ||
267 [description, ...description.querySelectorAll("*")].some(
268 (element) => element.scrollWidth > element.clientWidth + recoveredWidth,
269 ),
270 );
271 };
272 measure();
273 const stopObserving = observeResize(description, measure);
274 const mutations = new MutationObserver(measure);
275 mutations.observe(description, { childList: true, subtree: true, characterData: true });
276 return () => {
277 stopObserving();
278 mutations.disconnect();
279 };
280 }, []);
281​
282 return (
283 <span className="contents">
284 <span
285 ref={descriptionRef}
286 className="w-0 min-w-0 grow truncate text-muted-foreground @max-[400px]:sr-only"
287 >
288 {children}
289 </span>
290 {showDetails ? (
291 <Popover>
292 <PopoverTrigger
293 openOnHover
294 render={
295 <Button
296 ref={detailsRef}
297 size="icon-xs"
298 variant="ghost-muted"
299 aria-label="Show notice details"
300 className="flex-none"
301 />
302 }
303 >
304 <InfoIcon />
305 </PopoverTrigger>
306 <PopoverPopup
307 aria-label="Notice details"
308 tooltipStyle
309 side="top"
310 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"
311 >
312 <ComposerBanner.Scroll className="max-h-[min(var(--available-height),24rem,40dvh)]">
313 {children}
314 </ComposerBanner.Scroll>
315 </PopoverPopup>
316 </Popover>
317 ) : null}
318 </span>
319 );
321​
322function ComposerBannerStackAlert({
323 item,
324 attached,
325 exiting,
326 onDismissRequest,
327}: {
328 readonly item: ComposerBannerStackEntry;
329 readonly attached: boolean;
330 readonly exiting: boolean;
331 readonly onDismissRequest: () => void;
332}) {
333 if ("content" in item) {
334 return (
335 <ComposerBanner.Root
336 density="comfortable"
337 placement={attached ? "attached" : "floating"}
338 variant={item.variant}
339 >
340 {item.content}
341 </ComposerBanner.Root>
342 );
343 }
344 return (
345 <ComposerBanner.Root
346 role="alert"
347 placement={attached ? "attached" : "floating"}
348 variant={item.variant}
349 density="comfortable"
350 >
351 <ComposerBanner.Row layout={item.priority === "activity" ? "inline" : "wrap-actions"}>
352 <ComposerBanner.Icon className="h-(--composer-banner-icon-column) self-start">
353 {item.icon}
354 </ComposerBanner.Icon>
355 <ComposerBanner.Content className="whitespace-nowrap">
356 <span className="min-w-0 truncate font-medium leading-7 sm:leading-6">{item.title}</span>
357 {item.description ? <NoticeDescription>{item.description}</NoticeDescription> : null}
358 </ComposerBanner.Content>
359 {item.actions || item.onDismiss ? (
360 <ComposerBanner.Actions>
361 {item.actions}
362 {item.onDismiss ? (
363 <ComposerBanner.Dismiss
364 aria-label={item.dismissLabel ?? "Dismiss warning"}
365 disabled={exiting}
366 onClick={onDismissRequest}
367 />
368 ) : null}
369 </ComposerBanner.Actions>
370 ) : null}
371 </ComposerBanner.Row>
372 {item.children ? <ComposerBanner.Children>{item.children}</ComposerBanner.Children> : null}
373 </ComposerBanner.Root>
374 );