-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathChartBar.tsx
More file actions
256 lines (239 loc) · 7.5 KB
/
ChartBar.tsx
File metadata and controls
256 lines (239 loc) · 7.5 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
import React, { useCallback } from "react";
import {
Bar,
BarChart,
CartesianGrid,
ReferenceArea,
ReferenceLine,
XAxis,
YAxis,
type XAxisProps,
type YAxisProps,
} from "recharts";
import { ChartTooltip, ChartTooltipContent } from "~/components/primitives/charts/Chart";
import { useChartContext } from "./ChartContext";
import { ChartBarInvalid, ChartBarLoading, ChartBarNoData } from "./ChartLoading";
import { useHasNoData } from "./ChartRoot";
import { ZoomTooltip, useZoomHandlers } from "./ChartZoom";
//TODO: fix the first and last bars in a stack not having rounded corners
type ReferenceLineProps = {
value: number;
label: string;
};
// ============================================================================
// COMPOUND COMPONENT API
// ============================================================================
export type ChartBarRendererProps = {
/** Stack ID for stacked bar charts */
stackId?: string;
/** Custom X-axis props to merge with defaults */
xAxisProps?: Partial<XAxisProps>;
/** Custom Y-axis props to merge with defaults */
yAxisProps?: Partial<YAxisProps>;
/** Reference line (horizontal) */
referenceLine?: ReferenceLineProps;
/** Custom tooltip label formatter */
tooltipLabelFormatter?: (label: string, payload: any[]) => string;
/** Width injected by ResponsiveContainer */
width?: number;
/** Height injected by ResponsiveContainer */
height?: number;
};
/**
* Bar chart renderer for the compound component system.
* Must be used within a Chart.Root.
*
* @example
* ```tsx
* <Chart.Root config={config} data={data} dataKey="day">
* <Chart.Bar stackId="a" />
* <Chart.Legend />
* </Chart.Root>
* ```
*/
export function ChartBarRenderer({
stackId,
xAxisProps: xAxisPropsProp,
yAxisProps: yAxisPropsProp,
referenceLine,
tooltipLabelFormatter,
width,
height,
}: ChartBarRendererProps) {
const { config, data, dataKey, dataKeys, visibleSeries, state, highlight, setActivePayload, zoom, showLegend } = useChartContext();
const hasNoData = useHasNoData();
const zoomHandlers = useZoomHandlers();
const enableZoom = zoom !== null;
const handleBarClick = useCallback(
(barData: any, e: React.MouseEvent) => {
if (!enableZoom || !zoom) return;
e.stopPropagation();
if (!zoom.isSelecting) {
zoom.toggleInspectionLine(barData[dataKey]);
}
},
[enableZoom, zoom, dataKey]
);
// Handle mouse leave to also reset highlight
const handleMouseLeave = useCallback(() => {
zoomHandlers.onMouseLeave?.();
highlight.reset();
}, [zoomHandlers, highlight]);
// Render loading/error states
if (state === "loading") {
return <ChartBarLoading />;
} else if (state === "noData" || hasNoData) {
return <ChartBarNoData />;
} else if (state === "invalid") {
return <ChartBarInvalid />;
}
// Get the x-axis ticks based on tooltip state
// Only hide middle ticks when zoom is enabled (to make room for zoom instructions)
const xAxisTicks =
enableZoom && highlight.tooltipActive && data.length > 2
? [data[0]?.[dataKey], data[data.length - 1]?.[dataKey]]
: undefined;
return (
<BarChart
data={data}
width={width}
height={height}
barCategoryGap={1}
onMouseDown={zoomHandlers.onMouseDown}
onMouseMove={(e: any) => {
zoomHandlers.onMouseMove?.(e);
if (e?.activePayload?.length) {
setActivePayload(e.activePayload, e.activeTooltipIndex);
highlight.setTooltipActive(true);
} else {
highlight.setTooltipActive(false);
}
}}
onMouseUp={zoomHandlers.onMouseUp}
onClick={zoomHandlers.onClick}
onMouseLeave={handleMouseLeave}
>
<CartesianGrid vertical={false} stroke="#272A2E" />
<XAxis
dataKey={dataKey}
tickLine={false}
tickMargin={10}
axisLine={false}
ticks={xAxisTicks}
interval="preserveStartEnd"
tick={{
fill: "#878C99",
fontSize: 11,
style: { fontVariantNumeric: "tabular-nums" },
}}
{...xAxisPropsProp}
/>
<YAxis
axisLine={false}
tickLine={false}
tickMargin={8}
tick={{
fill: "#878C99",
fontSize: 11,
style: { fontVariantNumeric: "tabular-nums" },
}}
domain={["auto", (dataMax: number) => dataMax * 1.15]}
{...yAxisPropsProp}
/>
{/* When legend is shown below the chart, render tooltip with cursor only (no content popup).
Otherwise render the full tooltip with zoom instructions. */}
<ChartTooltip
cursor={{ fill: "rgba(255, 255, 255, 0.06)" }}
content={
showLegend ? (
() => null
) : tooltipLabelFormatter ? (
<ChartTooltipContent />
) : (
<ZoomTooltip
isSelecting={zoom?.isSelecting}
refAreaLeft={zoom?.refAreaLeft}
refAreaRight={zoom?.refAreaRight}
invalidSelection={zoom?.invalidSelection}
/>
)
}
labelFormatter={tooltipLabelFormatter}
allowEscapeViewBox={{ x: false, y: true }}
/>
{/* Zoom selection area - rendered before bars to appear behind them */}
{enableZoom && zoom?.refAreaLeft !== null && zoom?.refAreaRight !== null && (
<ReferenceArea
x1={zoom.refAreaLeft}
x2={zoom.refAreaRight}
strokeOpacity={0.4}
fill="#3B82F6"
fillOpacity={0.3}
/>
)}
{visibleSeries.map((key, index, array) => {
const dimmed =
!zoom?.isSelecting &&
highlight.activeBarKey !== null &&
highlight.activeBarKey !== key;
return (
<Bar
key={key}
dataKey={key}
stackId={stackId}
fill={config[key]?.color}
radius={
[
index === array.length - 1 ? 2 : 0,
index === array.length - 1 ? 2 : 0,
index === 0 ? 2 : 0,
index === 0 ? 2 : 0,
] as [number, number, number, number]
}
activeBar={false}
fillOpacity={dimmed ? 0.2 : 1}
onClick={(data, index, e) => handleBarClick(data, e)}
onMouseEnter={(entry, index) => {
if (entry.tooltipPayload?.[0]) {
const { dataKey: hoveredKey } = entry.tooltipPayload[0];
highlight.setHoveredBar(hoveredKey, index);
}
}}
onMouseLeave={highlight.reset}
isAnimationActive={false}
/>
);
})}
{/* Horizontal reference line */}
{referenceLine && (
<ReferenceLine
y={referenceLine.value}
label={{
position: "top",
value: referenceLine.label,
fill: "#878C99",
fontSize: 11,
}}
isFront={true}
stroke="#3B3E45"
strokeDasharray="4 4"
className="pointer-events-none"
/>
)}
{/* Zoom inspection line - rendered after bars to appear on top */}
{enableZoom && zoom?.inspectionLine && (
<ReferenceLine
x={zoom.inspectionLine}
stroke="#D7D9DD"
strokeWidth={2}
isFront={true}
onClick={(e: any) => {
e?.stopPropagation?.();
zoom.clearInspectionLine();
}}
/>
)}
{/* Note: Legend is now rendered by ChartRoot outside the chart container */}
</BarChart>
);
}