-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathChartLegendCompound.tsx
More file actions
367 lines (332 loc) · 12.7 KB
/
ChartLegendCompound.tsx
File metadata and controls
367 lines (332 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import React, { useMemo } from "react";
import type { AggregationType } from "~/components/metrics/QueryWidget";
import { useActivePayload, useChartContext } from "./ChartContext";
import { useSeriesTotal } from "./ChartRoot";
import { aggregateValues } from "./aggregation";
import { cn } from "~/utils/cn";
import { AnimatedNumber } from "../AnimatedNumber";
import { SimpleTooltip } from "../Tooltip";
const aggregationLabels: Record<AggregationType, string> = {
sum: "Sum",
avg: "Average",
count: "Count",
min: "Min",
max: "Max",
};
export type ChartLegendCompoundProps = {
/** Maximum number of legend items to show before collapsing */
maxItems?: number;
/** Hide the legend entirely (useful for conditional rendering) */
hidden?: boolean;
/** Additional className */
className?: string;
/** Label for the total row (derived from aggregation when not provided) */
totalLabel?: string;
/** Aggregation method – controls the header label and how totals are computed */
aggregation?: AggregationType;
/** Optional formatter for numeric values (e.g. bytes, duration) */
valueFormatter?: (value: number) => string;
/** Callback when "View all" button is clicked */
onViewAllLegendItems?: () => void;
/** When true, constrains legend to max 50% height with scrolling */
scrollable?: boolean;
};
/**
* Legend component for the chart compound system.
* Renders as a permanent element below the chart (not inside recharts).
* Automatically connects to chart context for highlighting.
*
* @example Using via Chart.Root showLegend prop (recommended)
* ```tsx
* <Chart.Root config={config} data={data} dataKey="day" showLegend maxLegendItems={5}>
* <Chart.Bar />
* </Chart.Root>
* ```
*/
export function ChartLegendCompound({
maxItems = Infinity,
hidden = false,
className,
totalLabel,
aggregation,
valueFormatter,
onViewAllLegendItems,
scrollable = false,
}: ChartLegendCompoundProps) {
const { config, dataKey, dataKeys, highlight, labelFormatter } = useChartContext();
const activePayload = useActivePayload();
const totals = useSeriesTotal(aggregation);
// Derive the effective label from the aggregation type when no explicit label is provided
const effectiveTotalLabel = totalLabel ?? (aggregation ? aggregationLabels[aggregation] : "Total");
// Calculate grand total by aggregating across all per-series values
const grandTotal = useMemo(() => {
const values = dataKeys.map((key) => totals[key] || 0);
if (!aggregation) {
// Default: sum
return values.reduce((a, b) => a + b, 0);
}
return aggregateValues(values, aggregation);
}, [totals, dataKeys, aggregation]);
// Calculate current total based on hover state (null when hovering a gap-filled point)
const currentTotal = useMemo((): number | null => {
if (!activePayload?.length) return grandTotal;
// Use the full data row so the total covers ALL dataKeys, not just visibleSeries
const dataRow = activePayload[0]?.payload;
if (!dataRow) return grandTotal;
const rawValues = dataKeys.map((key) => dataRow[key]);
const values = rawValues
.filter((v): v is number => v != null)
.map((v) => Number(v) || 0);
// All null → gap-filled point, return null to show dash
if (values.length === 0) return null;
if (!aggregation) {
return values.reduce((a, b) => a + b, 0);
}
return aggregateValues(values, aggregation);
}, [activePayload, grandTotal, dataKeys, aggregation]);
// Get the label for the total row - x-axis value when hovering, effectiveTotalLabel otherwise
const currentTotalLabel = useMemo(() => {
if (!activePayload?.length) return effectiveTotalLabel;
// Get the x-axis label from the payload's original data
const firstPayloadItem = activePayload[0];
const xAxisValue = firstPayloadItem?.payload?.[dataKey];
if (xAxisValue === undefined) return effectiveTotalLabel;
// Apply the formatter if provided, otherwise just stringify the value
const stringValue = String(xAxisValue);
return labelFormatter ? labelFormatter(stringValue) : stringValue;
}, [activePayload, dataKey, effectiveTotalLabel, labelFormatter]);
// Get current data for the legend based on hover state (values may be null for gap-filled points)
const currentData = useMemo((): Record<string, number | null> => {
if (!activePayload?.length) return totals;
// Use the full data row so ALL dataKeys are resolved from the hovered point,
// not just the visibleSeries present in activePayload.
const dataRow = activePayload[0]?.payload;
if (!dataRow) return totals;
const hoverData: Record<string, number | null> = {};
for (const key of dataKeys) {
const value = dataRow[key];
if (value !== undefined) {
hoverData[key] = value != null ? Number(value) || 0 : null;
}
}
return {
...totals,
...hoverData,
};
}, [activePayload, totals, dataKeys]);
// Prepare legend items with capped display
const legendItems = useMemo(() => {
const allItems = dataKeys.map((key) => ({
dataKey: key,
color: config[key]?.color,
label: config[key]?.label ?? key,
}));
if (allItems.length <= maxItems) {
return { visible: allItems, remaining: 0, hoveredHiddenItem: undefined };
}
const visibleItems = allItems.slice(0, maxItems);
const remainingCount = allItems.length - maxItems;
// If we're hovering over an item that's not visible in the legend,
// pass it separately to replace the "view more" row
let hoveredHiddenItem: (typeof allItems)[0] | undefined;
if (
highlight.activeBarKey &&
!visibleItems.some((item) => item.dataKey === highlight.activeBarKey)
) {
hoveredHiddenItem = allItems.find((item) => item.dataKey === highlight.activeBarKey);
}
return { visible: visibleItems, remaining: remainingCount, hoveredHiddenItem };
}, [config, dataKeys, maxItems, highlight.activeBarKey]);
if (hidden || dataKeys.length === 0) {
return null;
}
const isHovering = (activePayload?.length ?? 0) > 0;
return (
<div
className={cn("flex flex-col px-2 pb-2 pt-4 text-sm", scrollable && "max-h-[50%] min-h-0", className)}
>
{/* Total row */}
<div
className={cn(
"flex w-full shrink-0 items-center justify-between gap-2 rounded px-2 py-1 transition",
isHovering ? "text-text-bright" : "text-text-dimmed"
)}
>
<span className="font-medium">{currentTotalLabel}</span>
<span className="font-medium tabular-nums">
{currentTotal != null ? (
valueFormatter ? (
valueFormatter(currentTotal)
) : (
<AnimatedNumber value={currentTotal} duration={0.25} />
)
) : (
"\u2013"
)}
</span>
</div>
{/* Separator */}
<div className="mx-2 my-1 shrink-0 border-t border-charcoal-750" />
{/* Legend items - scrollable when scrollable prop is true */}
<div
className={cn(
"flex flex-col",
scrollable &&
"min-h-0 flex-1 overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-charcoal-600"
)}
>
{legendItems.visible.map((item) => {
const total = currentData[item.dataKey] ?? null;
const isActive = highlight.activeBarKey === item.dataKey;
return (
<div
key={item.dataKey}
className={cn(
"relative flex w-full cursor-default items-center justify-between gap-2 rounded px-2 py-1 transition",
(total == null || total === 0) && "opacity-50"
)}
onMouseEnter={() => highlight.setHoveredLegendItem(item.dataKey)}
onMouseLeave={() => highlight.reset()}
>
{/* Active highlight background */}
{isActive && item.color && (
<div
className="absolute inset-0 rounded opacity-10"
style={{ backgroundColor: item.color }}
/>
)}
<div className="relative flex w-full items-center justify-between gap-3 overflow-hidden">
<SimpleTooltip
button={
<div className="flex min-w-0 items-center gap-1.5">
{item.color && (
<div
className="w-1 shrink-0 self-stretch rounded-[2px]"
style={{ backgroundColor: item.color }}
/>
)}
<span
className={cn(
"truncate",
isActive ? "text-text-bright" : "text-text-dimmed"
)}
>
{item.label}
</span>
</div>
}
content={item.label}
side="top"
disableHoverableContent
className="max-w-xs break-words"
buttonClassName="cursor-default min-w-0"
/>
<span
className={cn(
"self-start tabular-nums",
isActive ? "text-text-bright" : "text-text-dimmed"
)}
>
{total != null ? (
valueFormatter ? (
valueFormatter(total)
) : (
<AnimatedNumber value={total} duration={0.25} />
)
) : (
"\u2013"
)}
</span>
</div>
</div>
);
})}
{/* View more row - replaced by hovered hidden item when applicable */}
{legendItems.remaining > 0 &&
(legendItems.hoveredHiddenItem ? (
<HoveredHiddenItemRow
item={legendItems.hoveredHiddenItem}
value={currentData[legendItems.hoveredHiddenItem.dataKey] ?? null}
remainingCount={legendItems.remaining - 1}
valueFormatter={valueFormatter}
/>
) : (
<ViewAllDataRow
remainingCount={legendItems.remaining}
onViewAll={onViewAllLegendItems}
/>
))}
</div>
</div>
);
}
type ViewAllDataRowProps = {
remainingCount: number;
onViewAll?: () => void;
};
function ViewAllDataRow({ remainingCount, onViewAll }: ViewAllDataRowProps) {
return (
<div
className="relative flex w-full cursor-pointer items-center justify-between gap-2 rounded px-2 py-1 transition hover:bg-charcoal-850"
onClick={onViewAll}
role="button"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onViewAll?.();
}
}}
>
<div className="relative flex w-full items-center justify-between gap-3">
<div className="flex items-center gap-1.5">
<div className="w-1 shrink-0 self-stretch rounded-[2px] border border-charcoal-600" />
<span className="text-text-dimmed tabular-nums">{remainingCount} more…</span>
</div>
<span className="self-start text-indigo-500">View all</span>
</div>
</div>
);
}
type HoveredHiddenItemRowProps = {
item: { dataKey: string; color?: string; label: React.ReactNode };
value: number | null;
remainingCount: number;
valueFormatter?: (value: number) => string;
};
function HoveredHiddenItemRow({ item, value, remainingCount, valueFormatter }: HoveredHiddenItemRowProps) {
return (
<div className="relative flex w-full items-center justify-between gap-2 rounded px-2 py-1">
{/* Active highlight background */}
{item.color && (
<div
className="absolute inset-0 rounded opacity-10"
style={{ backgroundColor: item.color }}
/>
)}
<div className="relative flex w-full items-center justify-between gap-3">
<div className="flex items-center gap-1.5">
{item.color && (
<div
className="w-1 shrink-0 self-stretch rounded-[2px]"
style={{ backgroundColor: item.color }}
/>
)}
<span className="text-text-bright">{item.label}</span>
{remainingCount > 0 && <span className="text-text-dimmed">+{remainingCount} more</span>}
</div>
<span className="tabular-nums text-text-bright">
{value != null ? (
valueFormatter ? (
valueFormatter(value)
) : (
<AnimatedNumber value={value} duration={0.25} />
)
) : (
"\u2013"
)}
</span>
</div>
</div>
);
}