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

ComposerBannerStack.tsx

302 lines10.4 KB

1import { useEffect, useId, useLayoutEffect, useRef, useState, type ReactNode } from "react";
2​
3import { cn } from "~/lib/utils";
4import { ComposerBanner, type ComposerBannerVariant } from "./ComposerBanner";
5​
6// Match the duration-220 exit transition before removing a dismissed notice.
7const DISMISS_TRANSITION_MS = 220;
8​
9export interface ComposerBannerStackItem {
10 readonly id: string;
11 readonly variant: ComposerBannerVariant;
12 readonly priority?: "urgent" | "activity" | "notice";
13 readonly icon: ReactNode;
14 readonly title: ReactNode;
15 readonly description?: ReactNode;
16 readonly children?: ReactNode;
17 readonly actions?: ReactNode;
18 readonly className?: string;
19 readonly dismissLabel?: string;
20 readonly onDismiss?: () => void;
22​
23export type ComposerBannerStackContent = Pick<
24 ComposerBannerStackItem,
25 "id" | "variant" | "priority" | "className"
26> & { readonly content: ReactNode };
27​
28type ComposerBannerStackEntry = ComposerBannerStackItem | ComposerBannerStackContent;
29​
30function bannerPriority(item: ComposerBannerStackEntry) {
31 if (item.priority === "activity") {
32 return 0;
33 }
34 if (item.priority === "urgent" || item.variant === "error" || item.variant === "warning") {
35 return 1;
36 }
37 return 2;
39​
40interface ComposerBannerStackProps {
41 readonly className?: string;
42 readonly items: ReadonlyArray<ComposerBannerStackEntry>;
44​
45export function ComposerBannerStack({ className, items }: ComposerBannerStackProps) {
46 const [stackExpanded, setStackExpanded] = useState(false);
47 const noticesRef = useRef<HTMLDivElement>(null);
48 const peekRef = useRef<HTMLButtonElement>(null);
49 const expandedItemsRef = useRef<HTMLDivElement>(null);
50 const pendingFocusRef = useRef<"peek" | "notice" | null>(null);
51 const expandedItemsId = useId();
52 const [requestedExitingItemId, setExitingItemId] = useState<string | null>(null);
53 const dismissTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
54 const exitingItemId =
55 requestedExitingItemId !== null && items.some((item) => item.id === requestedExitingItemId)
56 ? requestedExitingItemId
57 : null;
58​
59 useEffect(() => {
60 return () => {
61 if (dismissTimeoutRef.current) {
62 clearTimeout(dismissTimeoutRef.current);
63 }
64 };
65 }, []);
66​
67 useEffect(() => {
68 if (items.length < 2) setStackExpanded(false);
69 }, [items.length]);
70​
71 useLayoutEffect(() => {
72 if (stackExpanded && pendingFocusRef.current === "notice") {
73 pendingFocusRef.current = null;
74 const firstControl = expandedItemsRef.current?.querySelector<HTMLElement>(
75 'button:not(:disabled), a[href], input:not(:disabled), [tabindex="0"]',
76 );
77 (firstControl ?? expandedItemsRef.current)?.focus({ preventScroll: true });
78 } else if (!stackExpanded && pendingFocusRef.current === "peek") {
79 pendingFocusRef.current = null;
80 peekRef.current?.focus({ preventScroll: true });
81 }
82 }, [stackExpanded]);
83​
84 if (items.length === 0) {
85 return null;
86 }
87​
88 // Activity stays attached. Urgency and severity only order the notices behind it.
89 const orderedItems = items.toSorted((a, b) => bannerPriority(a) - bannerPriority(b));
90 const frontItem = orderedItems[0];
91 if (!frontItem) {
92 return null;
93 }
94 const stackedItems = orderedItems.slice(1);
95 const hasStack = stackedItems.length > 0;
96 const showCollapsedStackCap = hasStack && exitingItemId !== frontItem.id;
97 const firstStackedItem = stackedItems[0];
98​
99 const requestDismiss = (item: ComposerBannerStackEntry) => {
100 if (!("onDismiss" in item) || !item.onDismiss || exitingItemId) {
101 return;
102 }
103 setExitingItemId(item.id);
104 if (dismissTimeoutRef.current) {
105 clearTimeout(dismissTimeoutRef.current);
106 }
107 dismissTimeoutRef.current = setTimeout(() => {
108 dismissTimeoutRef.current = null;
109 item.onDismiss?.();
110 }, DISMISS_TRANSITION_MS);
111 };
112​
113 return (
114 <ComposerBanner.Attachment
115 className={className}
116 data-composer-banner-drawer="true"
117 data-chat-composer-collapsed-controls="true"
118 >
119 <div className={cn("relative flex flex-col-reverse", hasStack && stackExpanded && "z-50")}>
120 <div
121 className={cn(
122 "relative z-10 transition-[translate,opacity] duration-220 ease-in",
123 exitingItemId === frontItem.id
124 ? "pointer-events-none translate-y-16 opacity-0"
125 : "opacity-100",
126 )}
127 onPointerDownCapture={() => {
128 setStackExpanded(false);
129 const activeElement = document.activeElement;
130 if (
131 activeElement instanceof HTMLElement &&
132 noticesRef.current?.contains(activeElement)
133 ) {
134 activeElement.blur();
135 }
136 }}
137 >
138 <ComposerBannerStackAlert
139 item={frontItem}
140 attached
141 exiting={exitingItemId === frontItem.id}
142 onDismissRequest={() => requestDismiss(frontItem)}
143 />
144 </div>
145 {hasStack ? (
146 <div
147 ref={noticesRef}
148 className={cn("relative z-20", stackExpanded && "min-h-3")}
149 onPointerEnter={(event) => {
150 if (event.pointerType === "touch") return;
151 if (document.activeElement === peekRef.current) {
152 pendingFocusRef.current = "notice";
153 }
154 setStackExpanded(true);
155 }}
156 onPointerLeave={(event) => {
157 if (!event.currentTarget.contains(document.activeElement)) setStackExpanded(false);
158 }}
159 onBlurCapture={(event) => {
160 if (
161 !event.currentTarget.contains(event.relatedTarget) &&
162 !event.currentTarget.matches(":hover")
163 ) {
164 setStackExpanded(false);
165 }
166 }}
167 onKeyDown={(event) => {
168 if (event.key !== "Escape" || !stackExpanded) return;
169 event.preventDefault();
170 event.stopPropagation();
171 pendingFocusRef.current = "peek";
172 setStackExpanded(false);
173 }}
174 >
175 {showCollapsedStackCap && firstStackedItem ? (
176 <ComposerBanner.Peek
177 ref={peekRef}
178 variant={firstStackedItem.variant}
179 aria-label="Show other notices"
180 aria-expanded={stackExpanded}
181 aria-controls={expandedItemsId}
182 aria-hidden={stackExpanded || undefined}
183 tabIndex={stackExpanded ? -1 : 0}
184 onClick={(event) => {
185 event.currentTarget.focus({ preventScroll: true });
186 pendingFocusRef.current = "notice";
187 setStackExpanded(true);
188 }}
189 className={cn(stackExpanded && "pointer-events-none invisible opacity-0")}
190 />
191 ) : null}
192 <div
193 id={expandedItemsId}
194 ref={expandedItemsRef}
195 role="group"
196 aria-label="Other notices"
197 tabIndex={-1}
198 data-composer-banner-stack-expanded-items="true"
199 className={cn(
200 "grid transition-[grid-template-rows] duration-150 ease-out focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring",
201 stackExpanded ? "grid-rows-[1fr]" : "grid-rows-[0fr]",
202 )}
203 >
204 <div className="min-h-0 overflow-hidden">
205 <div
206 className={cn(
207 "transform-gpu space-y-2 pb-2 transition-[opacity,transform] duration-150 ease-out will-change-[opacity,transform]",
208 stackExpanded
209 ? "pointer-events-auto visible translate-y-0 opacity-100"
210 : "pointer-events-none invisible translate-y-1 opacity-0",
211 )}
212 >
213 {stackedItems.map((item) => (
214 <div
215 key={item.id}
216 className={cn(
217 "transition-[translate,opacity] duration-220 ease-in",
218 exitingItemId === item.id
219 ? "pointer-events-none translate-y-28 opacity-0"
220 : "opacity-100",
221 )}
222 >
223 <ComposerBannerStackAlert
224 item={item}
225 attached={false}
226 exiting={exitingItemId === item.id}
227 onDismissRequest={() => requestDismiss(item)}
228 />
229 </div>
230 ))}
231 </div>
232 </div>
233 </div>
234 </div>
235 ) : null}
236 </div>
237 </ComposerBanner.Attachment>
238 );
240​
241function ComposerBannerStackAlert({
242 item,
243 attached,
244 exiting,
245 onDismissRequest,
246}: {
247 readonly item: ComposerBannerStackEntry;
248 readonly attached: boolean;
249 readonly exiting: boolean;
250 readonly onDismissRequest: () => void;
251}) {
252 if ("content" in item) {
253 return (
254 <ComposerBanner.Root
255 placement={attached ? "attached" : "floating"}
256 variant={item.variant}
257 className={item.className}
258 >
259 {item.content}
260 </ComposerBanner.Root>
261 );
262 }
263​
264 return (
265 <ComposerBanner.Root
266 role="alert"
267 placement={attached ? "attached" : "floating"}
268 variant={item.variant}
269 className={item.className}
270 >
271 <ComposerBanner.Row layout="wrap-actions">
272 <ComposerBanner.Icon>{item.icon}</ComposerBanner.Icon>
273 <ComposerBanner.Content className="font-medium">{item.title}</ComposerBanner.Content>
274 {item.actions || item.onDismiss ? (
275 <ComposerBanner.Actions>
276 {item.actions}
277 {item.onDismiss ? (
278 <ComposerBanner.Dismiss
279 aria-label={item.dismissLabel ?? "Dismiss warning"}
280 disabled={exiting}
281 onClick={onDismissRequest}
282 />
283 ) : null}
284 </ComposerBanner.Actions>
285 ) : null}
286 </ComposerBanner.Row>
287 {item.description || item.children ? (
288 <ComposerBanner.Children>
289 {item.description ? (
290 <ComposerBanner.Row>
291 <ComposerBanner.Icon />
292 <ComposerBanner.Content className="text-muted-foreground">
293 {item.description}
294 </ComposerBanner.Content>
295 </ComposerBanner.Row>
296 ) : null}
297 {item.children}
298 </ComposerBanner.Children>
299 ) : null}
300 </ComposerBanner.Root>
301 );