1"use client";
2
3import { Slot as SlotPrimitive } from "radix-ui";
4import * as React from "react";
5import { useComposedRefs } from "@/lib/compose-refs";
6import { cn } from "@/lib/utils";
7
8interface GetBadgeLabel<T> {
9 /**
10 * Callback that returns a label string for each badge item.
11 * Optional for primitive arrays (strings, numbers), required for object arrays.
12 * @example getBadgeLabel={(item) => item.name}
13 */
14 getBadgeLabel: (item: T) => string;
15}
16
17type BadgeOverflowElement = React.ComponentRef<typeof BadgeOverflow>;
18
19type BadgeOverflowProps<T = string> = React.ComponentProps<"div"> &
20 (T extends object ? GetBadgeLabel<T> : Partial<GetBadgeLabel<T>>) & {
21 items: T[];
22 lineCount?: number;
23 renderBadge: (item: T, label: string) => React.ReactNode;
24 renderOverflow?: (count: number) => React.ReactNode;
25 asChild?: boolean;
26 };
27
28function BadgeOverflow<T = string>(props: BadgeOverflowProps<T>) {
29 const {
30 items,
31 getBadgeLabel: getBadgeLabelProp,
32 lineCount = 1,
33 renderBadge,
34 renderOverflow,
35 asChild,
36 className,
37 style,
38 ref,
39 ...rootProps
40 } = props;
41
42 const getBadgeLabel = React.useCallback(
43 (item: T): string => {
44 if (typeof item === "object" && !getBadgeLabelProp) {
45 throw new Error(
46 "`getBadgeLabel` is required when using array of objects",
47 );
48 }
49 return getBadgeLabelProp ? getBadgeLabelProp(item) : (item as string);
50 },
51 [getBadgeLabelProp],
52 );
53
54 const rootRef = React.useRef<BadgeOverflowElement | null>(null);
55 const composedRef = useComposedRefs(ref, rootRef);
56 const measureRef = React.useRef<HTMLDivElement | null>(null);
57 const [containerWidth, setContainerWidth] = React.useState(0);
58 const [badgeGap, setBadgeGap] = React.useState(4);
59 const [badgeHeight, setBadgeHeight] = React.useState(20);
60 const [overflowBadgeWidth, setOverflowBadgeWidth] = React.useState(40);
61 const [isMeasured, setIsMeasured] = React.useState(false);
62 const [badgeWidths, setBadgeWidths] = React.useState<Map<string, number>>(
63 new Map(),
64 );
65
66 React.useLayoutEffect(() => {
67 if (!rootRef.current || !measureRef.current) return;
68
69 function measureContainer() {
70 if (!rootRef.current || !measureRef.current) return;
71
72 const computedStyle = getComputedStyle(rootRef.current);
73
74 const gapValue = computedStyle.gap;
75 const gap = gapValue ? parseFloat(gapValue) : 4;
76 setBadgeGap(gap);
77
78 const paddingLeft = parseFloat(computedStyle.paddingLeft) || 0;
79 const paddingRight = parseFloat(computedStyle.paddingRight) || 0;
80 const totalPadding = paddingLeft + paddingRight;
81
82 const widthMap = new Map<string, number>();
83 const measureChildren = measureRef.current.children;
84
85 for (let i = 0; i < items.length; i++) {
86 const child = measureChildren[i] as HTMLElement | undefined;
87 if (child) {
88 const label = getBadgeLabel(items[i] as T);
89 widthMap.set(label, child.offsetWidth);
90 }
91 }
92 setBadgeWidths(widthMap);
93
94 const firstBadge = measureChildren[0] as HTMLElement | undefined;
95 if (firstBadge) {
96 setBadgeHeight(firstBadge.offsetHeight || 20);
97 }
98
99 const overflowChild = measureChildren[items.length] as
100 | HTMLElement
101 | undefined;
102
103 if (overflowChild) {
104 setOverflowBadgeWidth(overflowChild.offsetWidth || 40);
105 }
106
107 const width = rootRef.current.clientWidth - totalPadding;
108 setContainerWidth(width);
109 setIsMeasured(true);
110 }
111
112 measureContainer();
113
114 const resizeObserver = new ResizeObserver(measureContainer);
115 resizeObserver.observe(rootRef.current);
116
117 return () => {
118 resizeObserver.disconnect();
119 };
120 }, [items, getBadgeLabel]);
121
122 const placeholderHeight = React.useMemo(
123 () => badgeHeight * lineCount + badgeGap * (lineCount - 1),
124 [badgeHeight, badgeGap, lineCount],
125 );
126
127 const { visibleItems, hiddenCount } = React.useMemo(() => {
128 if (!containerWidth || items.length === 0 || badgeWidths.size === 0) {
129 return { visibleItems: items, hiddenCount: 0 };
130 }
131
132 let currentLineWidth = 0;
133 let currentLine = 1;
134 const visible: T[] = [];
135
136 for (let i = 0; i < items.length; i++) {
137 const item = items[i];
138 if (!item) continue;
139
140 const label = getBadgeLabel(item);
141 const badgeWidth = badgeWidths.get(label);
142
143 if (!badgeWidth) {
144 // Skip items that haven't been measured yet
145 continue;
146 }
147
148 const widthWithGap = badgeWidth + badgeGap;
149 const isLastLine = currentLine === lineCount;
150 const hasMoreItems = i < items.length - 1;
151
152 const availableWidth =
153 isLastLine && hasMoreItems
154 ? containerWidth - overflowBadgeWidth - badgeGap
155 : containerWidth;
156
157 if (currentLineWidth + widthWithGap <= availableWidth) {
158 currentLineWidth += widthWithGap;
159 visible.push(item);
160 } else if (currentLine < lineCount) {
161 currentLine++;
162 currentLineWidth = widthWithGap;
163 visible.push(item);
164 } else {
165 // We're on the last line and this badge doesn't fit
166 break;
167 }
168 }
169
170 return {
171 visibleItems: visible,
172 hiddenCount: Math.max(0, items.length - visible.length),
173 };
174 }, [
175 items,
176 getBadgeLabel,
177 containerWidth,
178 lineCount,
179 badgeGap,
180 overflowBadgeWidth,
181 badgeWidths,
182 ]);
183
184 const Comp = asChild ? SlotPrimitive.Slot : "div";
185
186 return (
187 <>
188 <div
189 ref={measureRef}
190 className="pointer-events-none invisible absolute flex flex-wrap"
191 style={{ gap: badgeGap }}
192 >
193 {items.map((item, index) => (
194 <React.Fragment key={index}>
195 {renderBadge(item, getBadgeLabel(item))}
196 </React.Fragment>
197 ))}
198 {renderOverflow ? (
199 renderOverflow(99)
200 ) : (
201 <div className="inline-flex h-5 shrink-0 items-center rounded-md border px-1.5 font-semibold text-xs">
202 +99
203 </div>
204 )}
205 </div>
206 {isMeasured ? (
207 <Comp
208 data-slot="badge-overflow"
209 {...rootProps}
210 ref={composedRef}
211 className={cn("flex flex-wrap", className)}
212 style={{
213 gap: badgeGap,
214 ...style,
215 }}
216 >
217 {visibleItems.map((item, index) => (
218 <React.Fragment key={index}>
219 {renderBadge(item, getBadgeLabel(item))}
220 </React.Fragment>
221 ))}
222 {hiddenCount > 0 &&
223 (renderOverflow ? (
224 renderOverflow(hiddenCount)
225 ) : (
226 <div className="inline-flex h-5 shrink-0 items-center rounded-md border px-1.5 font-semibold text-xs">
227 +{hiddenCount}
228 </div>
229 ))}
230 </Comp>
231 ) : (
232 <Comp
233 data-slot="badge-overflow"
234 {...rootProps}
235 ref={composedRef}
236 className={cn("flex flex-wrap", className)}
237 style={{
238 gap: badgeGap,
239 minHeight: placeholderHeight,
240 ...style,
241 }}
242 >
243 {items
244 .slice(
245 0,
246 Math.min(items.length, lineCount * 3 - (lineCount > 1 ? 1 : 0)),
247 )
248 .map((item, index) => (
249 <React.Fragment key={index}>
250 {renderBadge(item, getBadgeLabel(item))}
251 </React.Fragment>
252 ))}
253 </Comp>
254 )}
255 </>
256 );
257}
258
259export { BadgeOverflow };
260