@coinbase/cds-web-visualization 3.4.0-beta.24 → 3.4.0-beta.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dts/chart/Path.d.ts +4 -2
  3. package/dts/chart/Path.d.ts.map +1 -1
  4. package/dts/chart/PeriodSelector.d.ts +1 -1
  5. package/dts/chart/bar/Bar.d.ts +18 -54
  6. package/dts/chart/bar/Bar.d.ts.map +1 -1
  7. package/dts/chart/bar/BarPlot.d.ts.map +1 -1
  8. package/dts/chart/bar/BarStack.d.ts +4 -4
  9. package/dts/chart/bar/BarStack.d.ts.map +1 -1
  10. package/dts/chart/bar/DefaultBar.d.ts.map +1 -1
  11. package/dts/chart/bar/DefaultBarStack.d.ts.map +1 -1
  12. package/dts/chart/point/Point.d.ts +2 -1
  13. package/dts/chart/point/Point.d.ts.map +1 -1
  14. package/dts/chart/scrubber/Scrubber.d.ts +4 -2
  15. package/dts/chart/scrubber/Scrubber.d.ts.map +1 -1
  16. package/dts/chart/utils/bar.d.ts +153 -0
  17. package/dts/chart/utils/bar.d.ts.map +1 -1
  18. package/dts/chart/utils/chart.d.ts +2 -1
  19. package/dts/chart/utils/chart.d.ts.map +1 -1
  20. package/dts/chart/utils/path.d.ts.map +1 -1
  21. package/dts/sparkline/Sparkline.d.ts +2 -1
  22. package/dts/sparkline/Sparkline.d.ts.map +1 -1
  23. package/dts/sparkline/SparklineArea.d.ts +2 -1
  24. package/dts/sparkline/SparklineArea.d.ts.map +1 -1
  25. package/dts/sparkline/SparklineGradient.d.ts +2 -1
  26. package/dts/sparkline/SparklineGradient.d.ts.map +1 -1
  27. package/dts/sparkline/sparkline-interactive/SparklineInteractive.d.ts +2 -1
  28. package/dts/sparkline/sparkline-interactive/SparklineInteractive.d.ts.map +1 -1
  29. package/esm/chart/Path.js +2 -1
  30. package/esm/chart/bar/Bar.js +4 -6
  31. package/esm/chart/bar/BarChart.js +7 -7
  32. package/esm/chart/bar/BarPlot.js +17 -27
  33. package/esm/chart/bar/BarStack.js +90 -295
  34. package/esm/chart/bar/DefaultBar.js +13 -19
  35. package/esm/chart/bar/DefaultBarStack.js +12 -19
  36. package/esm/chart/utils/bar.js +813 -0
  37. package/esm/chart/utils/chart.js +2 -1
  38. package/esm/chart/utils/path.js +5 -13
  39. package/esm/sparkline/Sparkline.js +2 -1
  40. package/esm/sparkline/SparklineArea.js +2 -1
  41. package/esm/sparkline/SparklineGradient.js +2 -1
  42. package/esm/sparkline/sparkline-interactive/SparklineInteractive.js +2 -1
  43. package/package.json +5 -5
@@ -6,6 +6,8 @@ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol"
6
6
  function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
7
7
  function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
8
8
  function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
9
+ import { defaultAxisId as fallbackAxisId } from './axis';
10
+ import { evaluateGradientAtValue } from './gradient';
9
11
  import { defaultTransition } from './transition';
10
12
 
11
13
  /**
@@ -19,6 +21,24 @@ import { defaultTransition } from './transition';
19
21
  * { type: 'tween', duration: 0.75, staggerDelay: 0.25 }
20
22
  */
21
23
 
24
+ /**
25
+ * Computes a bar's normalized [0, 1] position along the category axis, used for
26
+ * stagger-delay calculations.
27
+ *
28
+ * Vertical charts stagger left-to-right (x axis); horizontal charts stagger
29
+ * top-to-bottom (y axis). Returns 0 when the drawing area has no extent.
30
+ *
31
+ * @param layout - The layout of the chart
32
+ * @param x - Bar's left edge in pixels
33
+ * @param y - Bar's top edge in pixels
34
+ */
35
+ export const getNormalizedStagger = (layout, x, y, drawingArea) => {
36
+ if (layout === 'horizontal') {
37
+ return drawingArea.height > 0 ? (y - drawingArea.y) / drawingArea.height : 0;
38
+ }
39
+ return drawingArea.width > 0 ? (x - drawingArea.x) / drawingArea.width : 0;
40
+ };
41
+
22
42
  /**
23
43
  * Strips `staggerDelay` from a transition and computes a positional delay.
24
44
  *
@@ -71,4 +91,797 @@ export function getBarSizeAdjustment(barCount, gapSize) {
71
91
  return 0;
72
92
  }
73
93
  return gapSize * (barCount - 1) / barCount;
94
+ }
95
+ /**
96
+ * Groups bar series into stack groups scoped by stackId + axis IDs.
97
+ *
98
+ * Series with no `stackId` are treated as independent stacks keyed by series id.
99
+ * Axis IDs are included in the group key so series on different axes never stack together.
100
+ */
101
+ export function getStackGroups(series) {
102
+ let defaultAxisId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : fallbackAxisId;
103
+ const groups = {};
104
+ series.forEach(entry => {
105
+ var _entry$xAxisId, _entry$yAxisId;
106
+ const xAxisId = (_entry$xAxisId = entry.xAxisId) !== null && _entry$xAxisId !== void 0 ? _entry$xAxisId : defaultAxisId;
107
+ const yAxisId = (_entry$yAxisId = entry.yAxisId) !== null && _entry$yAxisId !== void 0 ? _entry$yAxisId : defaultAxisId;
108
+ const stackId = entry.stackId || "individual-".concat(entry.id);
109
+ const stackKey = "".concat(stackId, ":").concat(xAxisId, ":").concat(yAxisId);
110
+ if (!groups[stackKey]) {
111
+ groups[stackKey] = {
112
+ stackId: stackKey,
113
+ series: [],
114
+ xAxisId: entry.xAxisId,
115
+ yAxisId: entry.yAxisId
116
+ };
117
+ }
118
+ groups[stackKey].series.push(entry);
119
+ });
120
+ return Object.values(groups);
121
+ }
122
+
123
+ /**
124
+ * A single positioned bar in a stack, used throughout all bar layout helpers.
125
+ */
126
+ /**
127
+ * A single positioned bar — the source-of-truth data shape for the bar system.
128
+ *
129
+ * Layout fields (`valuePos`, `length`) are axis-agnostic and used by helper
130
+ * functions during computation. Rendering fields (`x`, `y`, `width`, `height`,
131
+ * `origin`, `dataX`, `dataY`) are derived at the end of `getBars` and can be
132
+ * passed directly to the `<Bar>` component.
133
+ *
134
+ * `BarBaseProps` in `Bar.tsx` picks from this type.
135
+ */
136
+ /**
137
+ * A fully computed bar ready to render — extends `BarBaseProps` with required
138
+ * identity fields and internal layout data used by helper functions.
139
+ *
140
+ * `getBars` returns `BarData[]` with every `BarBaseProps` field populated so
141
+ * the `<Bar>` component can consume them directly.
142
+ */
143
+
144
+ /**
145
+ * Applies proportional gap distribution to a stack of bars, maintaining total stack length.
146
+ * Gaps are only inserted between bars that have `shouldApplyGap = true`.
147
+ * Positive (above-baseline) and negative (below-baseline) groups are gapped independently.
148
+ *
149
+ * @param bars - Array of bar items with current valuePos and length
150
+ * @param stackGap - Gap size in pixels between adjacent bars
151
+ * @param layout - The layout of the chart
152
+ * @param baseline - Pixel position of the zero value on the value axis
153
+ * @returns New array of bars with adjusted valuePos and length
154
+ */
155
+ function applyStackGap(bars, stackGap, layout, baseline) {
156
+ if (!stackGap || bars.length <= 1) return bars;
157
+ const result = [...bars];
158
+ const barsAboveBaseline = bars.filter(bar => {
159
+ const [bottom, top] = [...bar.dataValue].sort((a, b) => a - b);
160
+ return bottom >= 0 && top !== bottom && bar.shouldApplyGap;
161
+ });
162
+ const barsBelowBaseline = bars.filter(bar => {
163
+ const [bottom, top] = [...bar.dataValue].sort((a, b) => a - b);
164
+ return top <= 0 && bottom !== top && bar.shouldApplyGap;
165
+ });
166
+ const applyGapGroup = (group, growing) => {
167
+ if (group.length <= 1) return;
168
+ const totalGapSpace = stackGap * (group.length - 1);
169
+ const totalDataLength = group.reduce((sum, bar) => sum + bar.length, 0);
170
+ const lengthReduction = totalGapSpace / totalDataLength;
171
+ const sortedBars = growing ? [...group].sort((a, b) => b.valuePos - a.valuePos) : [...group].sort((a, b) => a.valuePos - b.valuePos);
172
+ let currentEdge = baseline;
173
+ sortedBars.forEach((bar, index) => {
174
+ const newLength = bar.length * (1 - lengthReduction);
175
+ let newValuePos;
176
+ if (growing) {
177
+ newValuePos = currentEdge - newLength;
178
+ currentEdge = newValuePos - (index < sortedBars.length - 1 ? stackGap : 0);
179
+ } else {
180
+ newValuePos = currentEdge;
181
+ currentEdge = newValuePos + newLength + (index < sortedBars.length - 1 ? stackGap : 0);
182
+ }
183
+ const barIndex = result.findIndex(b => b.seriesId === bar.seriesId);
184
+ if (barIndex !== -1) {
185
+ result[barIndex] = _objectSpread(_objectSpread({}, result[barIndex]), {}, {
186
+ length: newLength,
187
+ valuePos: newValuePos
188
+ });
189
+ }
190
+ });
191
+ };
192
+
193
+ // Positive bars: grow up in vertical (decreasing Y), grow right in horizontal (increasing X)
194
+ applyGapGroup(barsAboveBaseline, layout === 'vertical');
195
+ // Negative bars: grow down in vertical (increasing Y), grow left in horizontal (decreasing X)
196
+ applyGapGroup(barsBelowBaseline, layout !== 'vertical');
197
+ return result;
198
+ }
199
+
200
+ /**
201
+ * Expands bars that are shorter than `barMinSize` to the minimum size.
202
+ * Non-expanded bars are scaled down proportionally to keep the total bar length constant,
203
+ * preventing stacked bars from overflowing the chart area.
204
+ *
205
+ * Bars are then repositioned from the baseline, preserving original gaps between them.
206
+ *
207
+ * @param bars - Array of bar items with current valuePos and length
208
+ * @param barMinSize - Minimum bar size in pixels
209
+ * @param layout - The layout of the chart
210
+ * @param baseline - Pixel position of the zero value on the value axis
211
+ * @returns New array of bars with adjusted valuePos and length
212
+ */
213
+ function applyBarMinSize(bars, barMinSize, layout, baseline) {
214
+ if (!barMinSize || bars.length === 0) return bars;
215
+ const originalTotalLength = bars.reduce((sum, bar) => sum + bar.length, 0);
216
+ const needsExpansion = bars.map(bar => bar.length < barMinSize);
217
+ const expandedTotalLength = bars.reduce((sum, bar, i) => sum + (needsExpansion[i] ? barMinSize : bar.length), 0);
218
+ let finalLengths;
219
+ if (expandedTotalLength > originalTotalLength) {
220
+ // Scale down non-expanded bars to keep total bar length constant
221
+ const spaceForExpanded = needsExpansion.filter(Boolean).length * barMinSize;
222
+ const spaceForNonExpanded = Math.max(0, originalTotalLength - spaceForExpanded);
223
+ const nonExpandedOrigTotal = bars.reduce((sum, bar, i) => !needsExpansion[i] ? sum + bar.length : sum, 0);
224
+ const scaleFactor = nonExpandedOrigTotal > 0 ? spaceForNonExpanded / nonExpandedOrigTotal : 0;
225
+ finalLengths = bars.map((bar, i) => needsExpansion[i] ? barMinSize : bar.length * scaleFactor);
226
+ } else {
227
+ finalLengths = bars.map((bar, i) => needsExpansion[i] ? barMinSize : bar.length);
228
+ }
229
+ const expandedBars = bars.map((bar, i) => _objectSpread(_objectSpread({}, bar), {}, {
230
+ length: finalLengths[i]
231
+ }));
232
+ const newPositions = new Map();
233
+
234
+ // Range bars (shouldApplyGap=false) float at data-defined coordinates independent of the
235
+ // baseline. Restacking them from the zero baseline would place them off-screen when the
236
+ // y-axis domain doesn't include 0 (e.g., a price chart with domain [28000, 37000]).
237
+ // Instead, expand them in-place, centered on their original midpoint.
238
+ for (let i = 0; i < bars.length; i++) {
239
+ if (bars[i].shouldApplyGap === false) {
240
+ const originalMid = bars[i].valuePos + bars[i].length / 2;
241
+ newPositions.set(bars[i].seriesId, {
242
+ valuePos: originalMid - expandedBars[i].length / 2,
243
+ length: expandedBars[i].length
244
+ });
245
+ }
246
+ }
247
+
248
+ // Stacked bars (shouldApplyGap=true/undefined): classify by which side of the baseline
249
+ // they're on and restack from the baseline outward.
250
+ const stackedSortedBars = [...expandedBars].filter(bar => bar.shouldApplyGap !== false).sort((a, b) => a.valuePos - b.valuePos);
251
+ if (stackedSortedBars.length > 0) {
252
+ // Classify using dataValue to correctly identify which side of the baseline each bar is on,
253
+ // independent of the current valuePos (which hasn't been repositioned yet).
254
+ const barsAboveBaseline = stackedSortedBars.filter(bar => {
255
+ const [bottom, top] = [...bar.dataValue].sort((a, b) => a - b);
256
+ return layout === 'vertical' ? bottom >= 0 && top !== bottom : top <= 0 && top !== bottom;
257
+ });
258
+ const barsBelowBaseline = stackedSortedBars.filter(bar => {
259
+ const [bottom, top] = [...bar.dataValue].sort((a, b) => a - b);
260
+ return layout === 'vertical' ? top <= 0 && top !== bottom : bottom >= 0 && top !== bottom;
261
+ });
262
+
263
+ // Restack bars above baseline (growing away from it in the positive direction)
264
+ let currentAbove = baseline;
265
+ for (let i = barsAboveBaseline.length - 1; i >= 0; i--) {
266
+ const bar = barsAboveBaseline[i];
267
+ const newValuePos = currentAbove - bar.length;
268
+ newPositions.set(bar.seriesId, {
269
+ valuePos: newValuePos,
270
+ length: bar.length
271
+ });
272
+ if (i > 0) {
273
+ const nextBar = barsAboveBaseline[i - 1];
274
+ const originalCurrent = bars.find(b => b.seriesId === bar.seriesId);
275
+ const originalNext = bars.find(b => b.seriesId === nextBar.seriesId);
276
+ const originalGap = originalCurrent.valuePos - (originalNext.valuePos + originalNext.length);
277
+ currentAbove = newValuePos - originalGap;
278
+ }
279
+ }
280
+
281
+ // Restack bars below baseline (growing away from it in the negative direction)
282
+ let currentBelow = baseline;
283
+ for (let i = 0; i < barsBelowBaseline.length; i++) {
284
+ const bar = barsBelowBaseline[i];
285
+ newPositions.set(bar.seriesId, {
286
+ valuePos: currentBelow,
287
+ length: bar.length
288
+ });
289
+ if (i < barsBelowBaseline.length - 1) {
290
+ const nextBar = barsBelowBaseline[i + 1];
291
+ const originalCurrent = bars.find(b => b.seriesId === bar.seriesId);
292
+ const originalNext = bars.find(b => b.seriesId === nextBar.seriesId);
293
+ const originalGap = originalNext.valuePos - (originalCurrent.valuePos + originalCurrent.length);
294
+ currentBelow = currentBelow + bar.length + originalGap;
295
+ }
296
+ }
297
+ }
298
+ return expandedBars.map(bar => {
299
+ const newPos = newPositions.get(bar.seriesId);
300
+ if (newPos) return _objectSpread(_objectSpread({}, bar), {}, {
301
+ valuePos: newPos.valuePos,
302
+ length: newPos.length
303
+ });
304
+ return bar;
305
+ });
306
+ }
307
+
308
+ /**
309
+ * Computes per-bar initial animation origin positions for bar entrance animations.
310
+ *
311
+ * Bars are stacked from the baseline in their respective directions so they start at
312
+ * distinct, non-overlapping positions with the gap already applied:
313
+ * - Positive bars: stack rightward (horizontal) / upward (vertical) from the baseline.
314
+ * - Negative bars: stack leftward (horizontal) / downward (vertical) from the baseline.
315
+ *
316
+ * The bar closest to the baseline always gets index 0 and starts exactly at the baseline.
317
+ *
318
+ * @param bars - Array of bar items with final valuePos, length, and dataValue
319
+ * @param initialBarMinSizes - Per-bar initial sizes in pixels for entrance animation
320
+ * @param stackGap - Gap between adjacent bars in pixels
321
+ * @param baseline - Pixel position of the zero value on the value axis
322
+ * @param layout - The layout of the chart
323
+ * @returns Array of origin positions (one per bar, parallel to input), all defaulting to baseline
324
+ */
325
+ function getBarOrigins(bars, initialBarMinSizes, stackGap, baseline, layout) {
326
+ const result = bars.map(() => baseline);
327
+ if (bars.length === 0 || initialBarMinSizes.every(size => !size)) return result;
328
+ const isPositive = bar => {
329
+ const [lo, hi] = [...bar.dataValue].sort((a, b) => a - b);
330
+ return lo >= 0 && hi !== lo;
331
+ };
332
+ const isNegative = bar => {
333
+ const [lo, hi] = [...bar.dataValue].sort((a, b) => a - b);
334
+ return hi <= 0 && hi !== lo;
335
+ };
336
+ const positiveBars = bars.map((bar, i) => ({
337
+ bar,
338
+ i
339
+ })).filter(_ref => {
340
+ let {
341
+ bar
342
+ } = _ref;
343
+ return isPositive(bar);
344
+ }).sort((a, b) => layout === 'vertical' ? b.bar.valuePos - a.bar.valuePos // vertical: largest Y pixel = closest to bottom baseline
345
+ : a.bar.valuePos - b.bar.valuePos // horizontal: smallest X pixel = closest to left baseline
346
+ );
347
+ if (layout === 'vertical') {
348
+ let currentPositive = baseline;
349
+ positiveBars.forEach((_ref2, idx) => {
350
+ var _initialBarMinSizes$i;
351
+ let {
352
+ i
353
+ } = _ref2;
354
+ const initialSize = (_initialBarMinSizes$i = initialBarMinSizes[i]) !== null && _initialBarMinSizes$i !== void 0 ? _initialBarMinSizes$i : 0;
355
+ currentPositive -= initialSize;
356
+ result[i] = currentPositive;
357
+ if (idx < positiveBars.length - 1) {
358
+ currentPositive -= stackGap;
359
+ }
360
+ });
361
+ } else {
362
+ let currentPositive = baseline;
363
+ positiveBars.forEach((_ref3, idx) => {
364
+ var _initialBarMinSizes$i2;
365
+ let {
366
+ i
367
+ } = _ref3;
368
+ const initialSize = (_initialBarMinSizes$i2 = initialBarMinSizes[i]) !== null && _initialBarMinSizes$i2 !== void 0 ? _initialBarMinSizes$i2 : 0;
369
+ result[i] = currentPositive;
370
+ currentPositive += initialSize;
371
+ if (idx < positiveBars.length - 1) {
372
+ currentPositive += stackGap;
373
+ }
374
+ });
375
+ }
376
+ const negativeBars = bars.map((bar, i) => ({
377
+ bar,
378
+ i
379
+ })).filter(_ref4 => {
380
+ let {
381
+ bar
382
+ } = _ref4;
383
+ return isNegative(bar);
384
+ }).sort((a, b) => layout === 'vertical' ? a.bar.valuePos - b.bar.valuePos // vertical: smallest Y pixel = closest to top baseline
385
+ : b.bar.valuePos + b.bar.length - (a.bar.valuePos + a.bar.length) // horizontal: largest right edge = closest to baseline
386
+ );
387
+ if (layout === 'vertical') {
388
+ let currentNegative = baseline;
389
+ negativeBars.forEach((_ref5, idx) => {
390
+ var _initialBarMinSizes$i3;
391
+ let {
392
+ i
393
+ } = _ref5;
394
+ const initialSize = (_initialBarMinSizes$i3 = initialBarMinSizes[i]) !== null && _initialBarMinSizes$i3 !== void 0 ? _initialBarMinSizes$i3 : 0;
395
+ result[i] = currentNegative;
396
+ currentNegative += initialSize;
397
+ if (idx < negativeBars.length - 1) {
398
+ currentNegative += stackGap;
399
+ }
400
+ });
401
+ } else {
402
+ let currentNegative = baseline;
403
+ negativeBars.forEach((_ref6, idx) => {
404
+ var _initialBarMinSizes$i4;
405
+ let {
406
+ i
407
+ } = _ref6;
408
+ const initialSize = (_initialBarMinSizes$i4 = initialBarMinSizes[i]) !== null && _initialBarMinSizes$i4 !== void 0 ? _initialBarMinSizes$i4 : 0;
409
+ currentNegative -= initialSize;
410
+ result[i] = currentNegative;
411
+ if (idx < negativeBars.length - 1) {
412
+ currentNegative -= stackGap;
413
+ }
414
+ });
415
+ }
416
+ return result;
417
+ }
418
+
419
+ /**
420
+ * Computes stack clip origin [start, end] that covers the bounding box
421
+ * of all bars at their stacked starting positions (as computed by `getBarOrigins`).
422
+ *
423
+ * This is passed to `DefaultBarStack` so the clip animation starts in sync with the
424
+ * individual bar animations — no bars leak outside the clip on frame 0.
425
+ *
426
+ * @param barOrigins - Per-bar initial origins from `getBarOrigins`
427
+ * @param barMinSizes - Per-bar minimum sizes in pixels (or a uniform value)
428
+ * @returns [originStart, originEnd] or undefined when barMinSize is 0 / no bars
429
+ */
430
+ export function getStackOrigin(barOrigins, barMinSizes) {
431
+ if (barOrigins.length === 0) return undefined;
432
+ const minSizes = Array.isArray(barMinSizes) ? barMinSizes : barOrigins.map(() => barMinSizes);
433
+ let rangeStart = Number.POSITIVE_INFINITY;
434
+ let rangeEnd = Number.NEGATIVE_INFINITY;
435
+ for (let i = 0; i < barOrigins.length; i++) {
436
+ var _minSizes$i;
437
+ const minSize = (_minSizes$i = minSizes[i]) !== null && _minSizes$i !== void 0 ? _minSizes$i : 0;
438
+ if (minSize <= 0) continue;
439
+ const barStart = barOrigins[i];
440
+ const barEnd = barStart + minSize;
441
+ rangeStart = Math.min(rangeStart, barStart, barEnd);
442
+ rangeEnd = Math.max(rangeEnd, barStart, barEnd);
443
+ }
444
+ if (!Number.isFinite(rangeStart) || !Number.isFinite(rangeEnd)) return undefined;
445
+ return [rangeStart, rangeEnd];
446
+ }
447
+ function getInitialBarMinSizes(bars, barMinSize, stackMinSize) {
448
+ const perBarMinFromBarMinSize = barMinSize !== null && barMinSize !== void 0 ? barMinSize : 0;
449
+ if (bars.length === 0) return [];
450
+ if (!stackMinSize) {
451
+ return bars.map(() => perBarMinFromBarMinSize);
452
+ }
453
+ const totalBarLength = bars.reduce((sum, bar) => sum + bar.length, 0);
454
+ const perBarMinFromStack = totalBarLength ? bars.map(bar => stackMinSize * bar.length / totalBarLength) : bars.map(() => stackMinSize / bars.length);
455
+ return perBarMinFromStack.map(stackMin => Math.max(perBarMinFromBarMinSize, stackMin));
456
+ }
457
+
458
+ /**
459
+ * Computes the initial clip rect used for stack enter animations.
460
+ */
461
+ export function getStackInitialClipRect(stackRect, layout, origin) {
462
+ const {
463
+ x,
464
+ y,
465
+ width,
466
+ height
467
+ } = stackRect;
468
+ if (Array.isArray(origin)) {
469
+ const [originStart, originEnd] = origin;
470
+ if (layout === 'vertical') {
471
+ return {
472
+ x,
473
+ y: originStart,
474
+ width,
475
+ height: originEnd - originStart
476
+ };
477
+ }
478
+ return {
479
+ x: originStart,
480
+ y,
481
+ width: originEnd - originStart,
482
+ height
483
+ };
484
+ }
485
+ const initialSize = 1;
486
+ if (layout === 'vertical') {
487
+ const valueBaseline = origin !== null && origin !== void 0 ? origin : y + height;
488
+ return {
489
+ x,
490
+ y: valueBaseline,
491
+ width,
492
+ height: initialSize
493
+ };
494
+ }
495
+ const valueBaseline = origin !== null && origin !== void 0 ? origin : x;
496
+ return {
497
+ x: valueBaseline,
498
+ y,
499
+ width: initialSize,
500
+ height
501
+ };
502
+ }
503
+
504
+ /**
505
+ * Scales a stack of bars up so the total stack extent meets `stackMinSize`.
506
+ * For a single bar, the bar is expanded away from the baseline.
507
+ * For multiple bars, all bars are scaled proportionally, preserving relative gaps.
508
+ *
509
+ * @param bars - Array of bar items with current valuePos and length
510
+ * @param stackMinSize - Minimum stack size in pixels
511
+ * @param stackSize - Current total pixel extent of the stack
512
+ * @param stackBounds - Current bounding rect of the stack
513
+ * @param layout - The layout of the chart
514
+ * @param indexPos - Pixel position along the categorical (index) axis
515
+ * @param thickness - Bar thickness in pixels
516
+ * @param baseline - Pixel position of the zero value on the value axis
517
+ * @returns Updated bars and stackBounds; unchanged if stackSize >= stackMinSize
518
+ */
519
+ function applyStackMinSize(bars, stackMinSize, stackSize, stackBounds, layout, indexPos, thickness, baseline) {
520
+ if (!stackMinSize || stackSize >= stackMinSize) return {
521
+ bars,
522
+ stackBounds
523
+ };
524
+ if (bars.length === 0) return {
525
+ bars,
526
+ stackBounds
527
+ };
528
+ let updatedBars = [...bars];
529
+ let updatedBounds = _objectSpread({}, stackBounds);
530
+ if (bars.length === 1) {
531
+ const bar = bars[0];
532
+ const sizeIncrease = stackMinSize - bar.length;
533
+ const [bottom, top] = [...bar.dataValue].sort((a, b) => a - b);
534
+ let newValuePos;
535
+ const newLength = stackMinSize;
536
+ if (bottom >= 0 && top !== bottom) {
537
+ // Bar is on the positive side: vertical→expands upward (↑), horizontal→expands rightward (→)
538
+ newValuePos = layout === 'vertical' ? bar.valuePos - sizeIncrease : bar.valuePos;
539
+ } else if (top <= 0 && top !== bottom) {
540
+ // Bar is on the negative side: vertical→expands downward (↓), horizontal→expands leftward (←)
541
+ newValuePos = layout === 'vertical' ? bar.valuePos : bar.valuePos - sizeIncrease;
542
+ } else {
543
+ // Bar spans baseline or is zero: expand equally in both directions
544
+ newValuePos = bar.valuePos - sizeIncrease / 2;
545
+ }
546
+ updatedBars = [_objectSpread(_objectSpread({}, bar), {}, {
547
+ valuePos: newValuePos,
548
+ length: newLength
549
+ })];
550
+ updatedBounds = {
551
+ x: layout === 'vertical' ? indexPos : newValuePos,
552
+ y: layout === 'vertical' ? newValuePos : indexPos,
553
+ width: layout === 'vertical' ? thickness : newLength,
554
+ height: layout === 'vertical' ? newLength : thickness
555
+ };
556
+ } else {
557
+ const totalBarLength = bars.reduce((sum, bar) => sum + bar.length, 0);
558
+ const totalGapLength = stackSize - totalBarLength;
559
+ const requiredBarLength = stackMinSize - totalGapLength;
560
+ const barScaleFactor = requiredBarLength / totalBarLength;
561
+ const sortedBars = [...bars].sort((a, b) => a.valuePos - b.valuePos);
562
+
563
+ // For vertical: positive bars are above baseline (smaller Y), negative bars are below (larger Y)
564
+ // For horizontal: positive bars are right of baseline (larger X), negative bars are left (smaller X)
565
+ const barsOnPositiveSide = layout === 'vertical' ? sortedBars.filter(bar => bar.valuePos + bar.length <= baseline) : sortedBars.filter(bar => bar.valuePos >= baseline);
566
+ const barsOnNegativeSide = layout === 'vertical' ? sortedBars.filter(bar => bar.valuePos >= baseline) : sortedBars.filter(bar => bar.valuePos + bar.length <= baseline);
567
+ const newPositions = new Map();
568
+ if (layout === 'vertical') {
569
+ // Stack from baseline upward (decreasing valuePos) for positive bars
570
+ let currentPos = baseline;
571
+ for (let i = barsOnPositiveSide.length - 1; i >= 0; i--) {
572
+ const bar = barsOnPositiveSide[i];
573
+ const newLength = bar.length * barScaleFactor;
574
+ const newValuePos = currentPos - newLength;
575
+ newPositions.set(bar.seriesId, {
576
+ valuePos: newValuePos,
577
+ length: newLength
578
+ });
579
+ if (i > 0) {
580
+ const nextBar = barsOnPositiveSide[i - 1];
581
+ const originalGap = bar.valuePos - (nextBar.valuePos + nextBar.length);
582
+ currentPos = newValuePos - originalGap;
583
+ }
584
+ }
585
+ // Stack from baseline downward (increasing valuePos) for negative bars
586
+ let currentPosBelow = baseline;
587
+ for (let i = 0; i < barsOnNegativeSide.length; i++) {
588
+ const bar = barsOnNegativeSide[i];
589
+ const newLength = bar.length * barScaleFactor;
590
+ newPositions.set(bar.seriesId, {
591
+ valuePos: currentPosBelow,
592
+ length: newLength
593
+ });
594
+ if (i < barsOnNegativeSide.length - 1) {
595
+ const nextBar = barsOnNegativeSide[i + 1];
596
+ const originalGap = nextBar.valuePos - (bar.valuePos + bar.length);
597
+ currentPosBelow = currentPosBelow + newLength + originalGap;
598
+ }
599
+ }
600
+ } else {
601
+ // Stack from baseline rightward (increasing valuePos) for positive bars
602
+ let currentPos = baseline;
603
+ for (let i = 0; i < barsOnPositiveSide.length; i++) {
604
+ const bar = barsOnPositiveSide[i];
605
+ const newLength = bar.length * barScaleFactor;
606
+ newPositions.set(bar.seriesId, {
607
+ valuePos: currentPos,
608
+ length: newLength
609
+ });
610
+ if (i < barsOnPositiveSide.length - 1) {
611
+ const nextBar = barsOnPositiveSide[i + 1];
612
+ const originalGap = nextBar.valuePos - (bar.valuePos + bar.length);
613
+ currentPos = currentPos + newLength + originalGap;
614
+ }
615
+ }
616
+ // Stack from baseline leftward (decreasing valuePos) for negative bars
617
+ let currentPosLeft = baseline;
618
+ for (let i = barsOnNegativeSide.length - 1; i >= 0; i--) {
619
+ const bar = barsOnNegativeSide[i];
620
+ const newLength = bar.length * barScaleFactor;
621
+ const newValuePos = currentPosLeft - newLength;
622
+ newPositions.set(bar.seriesId, {
623
+ valuePos: newValuePos,
624
+ length: newLength
625
+ });
626
+ if (i > 0) {
627
+ const nextBar = barsOnNegativeSide[i - 1];
628
+ const originalGap = bar.valuePos - (nextBar.valuePos + nextBar.length);
629
+ currentPosLeft = newValuePos - originalGap;
630
+ }
631
+ }
632
+ }
633
+ updatedBars = bars.map(bar => {
634
+ const newPos = newPositions.get(bar.seriesId);
635
+ if (!newPos) return bar;
636
+ return _objectSpread(_objectSpread({}, bar), {}, {
637
+ length: newPos.length,
638
+ valuePos: newPos.valuePos
639
+ });
640
+ });
641
+ const newMinValuePos = Math.min(...updatedBars.map(bar => bar.valuePos));
642
+ const newMaxValuePos = Math.max(...updatedBars.map(bar => bar.valuePos + bar.length));
643
+ updatedBounds = {
644
+ x: layout === 'vertical' ? indexPos : newMinValuePos,
645
+ y: layout === 'vertical' ? newMinValuePos : indexPos,
646
+ width: layout === 'vertical' ? thickness : newMaxValuePos - newMinValuePos,
647
+ height: layout === 'vertical' ? newMaxValuePos - newMinValuePos : thickness
648
+ };
649
+ }
650
+ return {
651
+ bars: updatedBars,
652
+ stackBounds: updatedBounds
653
+ };
654
+ }
655
+
656
+ /**
657
+ * Applies border-radius flags to a sorted stack of bars.
658
+ *
659
+ * Faces at the outer edges of the stack remain rounded; faces where two bars
660
+ * touch internally are squared. When `stackGap` is non-zero every face keeps
661
+ * its rounded corner because all bars are visually separated.
662
+ *
663
+ * @param bars - Bars with `roundTop`/`roundBottom` flags and position data
664
+ * @param layout - The layout of the chart
665
+ * @param stackGap - Pixel gap between adjacent bars (non-zero ⇒ all faces stay rounded)
666
+ * @returns New array of bars with corrected `roundTop`/`roundBottom` flags
667
+ */
668
+ function applyBorderRadiusLogic(bars, layout, stackGap) {
669
+ if (bars.length === 0) return bars;
670
+
671
+ // Sort from "lower coordinate" face to "higher coordinate" face along the value axis:
672
+ // Vertical → descending valuePos (largest Y first = closest to baseline)
673
+ // Horizontal → ascending valuePos (smallest X first = closest to baseline)
674
+ const sortedBars = layout === 'vertical' ? [...bars].sort((a, b) => b.valuePos - a.valuePos) : [...bars].sort((a, b) => a.valuePos - b.valuePos);
675
+ return sortedBars.map((a, index) => {
676
+ const barBefore = index > 0 ? sortedBars[index - 1] : null;
677
+ const barAfter = index < sortedBars.length - 1 ? sortedBars[index + 1] : null;
678
+
679
+ // shouldRoundLower: face with the smaller coordinate (top in vertical, left in horizontal)
680
+ const shouldRoundLower = (layout === 'vertical' ? index === sortedBars.length - 1 : index === 0) || Boolean(a.shouldApplyGap && stackGap) || !a.shouldApplyGap && barAfter !== null && barAfter.valuePos + barAfter.length !== a.valuePos;
681
+
682
+ // shouldRoundHigher: face with the larger coordinate (bottom in vertical, right in horizontal)
683
+ const shouldRoundHigher = (layout === 'vertical' ? index === 0 : index === sortedBars.length - 1) || Boolean(a.shouldApplyGap && stackGap) || !a.shouldApplyGap && barBefore !== null && barBefore.valuePos !== a.valuePos + a.length;
684
+ return _objectSpread(_objectSpread({}, a), {}, {
685
+ roundTop: Boolean(a.roundTop && (layout === 'vertical' ? shouldRoundLower : shouldRoundHigher)),
686
+ roundBottom: Boolean(a.roundBottom && (layout === 'vertical' ? shouldRoundHigher : shouldRoundLower))
687
+ });
688
+ });
689
+ }
690
+
691
+ /**
692
+ * Threshold for treating a position as touching the baseline.
693
+ * Positions within this distance are considered at the baseline for rounding purposes.
694
+ */
695
+ export const EPSILON = 1e-4;
696
+
697
+ /**
698
+ * Computes and clamps the stack baseline position on the value axis.
699
+ *
700
+ * - If the full domain is positive, baseline is domain min.
701
+ * - If the full domain is negative, baseline is domain max.
702
+ * - If the domain crosses zero, baseline is 0.
703
+ */
704
+ export function getStackBaseline(valueScale, stackRect, layout) {
705
+ const [domainMin, domainMax] = valueScale.domain();
706
+ const baselineValue = domainMin >= 0 ? domainMin : domainMax <= 0 ? domainMax : 0;
707
+ const baselinePos = valueScale(baselineValue);
708
+ if (layout === 'vertical') {
709
+ return Math.max(stackRect.y, Math.min(baselinePos !== null && baselinePos !== void 0 ? baselinePos : stackRect.y + stackRect.height, stackRect.y + stackRect.height));
710
+ }
711
+ return Math.max(stackRect.x, Math.min(baselinePos !== null && baselinePos !== void 0 ? baselinePos : stackRect.x, stackRect.x + stackRect.width));
712
+ }
713
+ function getStackBoundsForLayout(layout, indexPos, thickness, minValuePos, stackSize) {
714
+ if (layout === 'vertical') {
715
+ return {
716
+ x: indexPos,
717
+ y: minValuePos,
718
+ width: thickness,
719
+ height: stackSize
720
+ };
721
+ }
722
+ return {
723
+ x: minValuePos,
724
+ y: indexPos,
725
+ width: stackSize,
726
+ height: thickness
727
+ };
728
+ }
729
+ function getStackSizeForLayout(layout, stackRect) {
730
+ return layout === 'vertical' ? stackRect.height : stackRect.width;
731
+ }
732
+
733
+ /**
734
+ * Computes the positioned bar entries and bounding rect for a single stack at one category index.
735
+ *
736
+ * This is the pure computation extracted from `BarStack`'s `useMemo` so it can be tested
737
+ * independently and reused across contexts.
738
+ *
739
+ * @param params.series - Series configs for this stack
740
+ * @param params.seriesData - Stacked data for each series, keyed by series id
741
+ * @param params.categoryIndex - Index of the category being rendered
742
+ * @param params.indexPos - Pixel position along the categorical axis
743
+ * @param params.thickness - Bar thickness in pixels
744
+ * @param params.valueScale - Scale function for the value axis
745
+ * @param params.seriesGradients - Precomputed gradient configs per series (null entries are skipped)
746
+ * @param params.roundBaseline - Whether to round the face touching the baseline
747
+ * @param params.layout - The layout of the chart
748
+ * @param params.baseline - Pixel position of the zero value on the value axis
749
+ * @param params.stackGap - Gap between adjacent bars in pixels
750
+ * @param params.barMinSize - Minimum individual bar size in pixels
751
+ * @param params.stackMinSize - Minimum total stack size in pixels
752
+ * @param params.defaultFill - Fallback fill color when a series has no color or gradient
753
+ * @returns Positioned bar entries and the stack's bounding rect
754
+ */
755
+ export function getBars(params) {
756
+ const {
757
+ series,
758
+ seriesData,
759
+ categoryIndex,
760
+ categoryValue,
761
+ indexPos,
762
+ thickness,
763
+ valueScale,
764
+ seriesGradients,
765
+ roundBaseline,
766
+ layout,
767
+ baseline,
768
+ stackGap,
769
+ barMinSize,
770
+ stackMinSize,
771
+ defaultFill,
772
+ borderRadius,
773
+ defaultFillOpacity,
774
+ defaultStroke,
775
+ defaultStrokeWidth,
776
+ defaultBarComponent
777
+ } = params;
778
+ let allBars = [];
779
+ series.forEach(s => {
780
+ var _valueScale, _valueScale2, _s$color;
781
+ const data = seriesData[s.id];
782
+ if (!data) return;
783
+ const value = data[categoryIndex];
784
+ if (value === null || value === undefined) return;
785
+ const originalData = s.data;
786
+ const originalValue = originalData === null || originalData === void 0 ? void 0 : originalData[categoryIndex];
787
+ // Only apply gap logic if the original data wasn't tuple format
788
+ const shouldApplyGap = !Array.isArray(originalValue);
789
+
790
+ // Sort to be in ascending order
791
+ const [bottom, top] = [...value].sort((a, b) => a - b);
792
+ const edgeBottom = (_valueScale = valueScale(bottom)) !== null && _valueScale !== void 0 ? _valueScale : baseline;
793
+ const edgeTop = (_valueScale2 = valueScale(top)) !== null && _valueScale2 !== void 0 ? _valueScale2 : baseline;
794
+
795
+ // In horizontal layout: roundTop is Right (edgeTop), roundBottom is Left (edgeBottom)
796
+ // getBarPath already handles the mapping of roundTop/roundBottom to coordinates.
797
+ const roundTop = roundBaseline || Math.abs(edgeTop - baseline) >= EPSILON;
798
+ const roundBottom = roundBaseline || Math.abs(edgeBottom - baseline) >= EPSILON;
799
+
800
+ // Calculate length (measured along the value axis)
801
+ const length = Math.abs(edgeBottom - edgeTop);
802
+ const valuePos = Math.min(edgeBottom, edgeTop);
803
+
804
+ // Skip bars that would have zero or negative height
805
+ if (length <= 0) return;
806
+ let barFill = (_s$color = s.color) !== null && _s$color !== void 0 ? _s$color : defaultFill;
807
+
808
+ // Evaluate gradient if provided (using precomputed stops)
809
+ const seriesGradientConfig = seriesGradients.find(g => (g === null || g === void 0 ? void 0 : g.seriesId) === s.id);
810
+ if (seriesGradientConfig && originalValue !== null && originalValue !== undefined) {
811
+ var _seriesGradientConfig;
812
+ const axis = (_seriesGradientConfig = seriesGradientConfig.gradient.axis) !== null && _seriesGradientConfig !== void 0 ? _seriesGradientConfig : 'y';
813
+ let evalValue;
814
+ if (axis === 'x') {
815
+ // X-axis gradient: In vertical it's the index, in horizontal it's the value.
816
+ evalValue = layout === 'vertical' ? categoryIndex : Array.isArray(originalValue) ? originalValue[1] : originalValue;
817
+ } else {
818
+ // Y-axis gradient: In vertical it's the value, in horizontal it's the index.
819
+ evalValue = layout === 'vertical' ? Array.isArray(originalValue) ? originalValue[1] : originalValue : categoryIndex;
820
+ }
821
+ const evaluatedColor = evaluateGradientAtValue(seriesGradientConfig.stops, evalValue, seriesGradientConfig.scale);
822
+ if (evaluatedColor) {
823
+ barFill = evaluatedColor;
824
+ }
825
+ }
826
+ allBars.push({
827
+ seriesId: s.id,
828
+ valuePos,
829
+ length,
830
+ dataValue: value,
831
+ fill: barFill,
832
+ roundTop,
833
+ roundBottom,
834
+ shouldApplyGap,
835
+ BarComponent: s.BarComponent,
836
+ x: 0,
837
+ y: 0,
838
+ width: 0,
839
+ height: 0,
840
+ origin: 0
841
+ });
842
+ });
843
+
844
+ // Apply proportional gap distribution to maintain total stack length
845
+ if (stackGap && allBars.length > 1) {
846
+ allBars = applyStackGap(allBars, stackGap, layout, baseline);
847
+ }
848
+
849
+ // Apply barMinSize constraints
850
+ if (barMinSize) {
851
+ allBars = applyBarMinSize(allBars, barMinSize, layout, baseline);
852
+ }
853
+ allBars = applyBorderRadiusLogic(allBars, layout, stackGap);
854
+
855
+ // Apply stackMinSize constraints
856
+ if (stackMinSize && allBars.length > 0) {
857
+ const minValuePos = Math.min(...allBars.map(bar => bar.valuePos));
858
+ const maxValuePos = Math.max(...allBars.map(bar => bar.valuePos + bar.length));
859
+ const stackSize = maxValuePos - minValuePos;
860
+ const stackBounds = getStackBoundsForLayout(layout, indexPos, thickness, minValuePos, stackSize);
861
+ const result = applyStackMinSize(allBars, stackMinSize, stackSize, stackBounds, layout, indexPos, thickness, baseline);
862
+ allBars = result.bars;
863
+
864
+ // Reapply border radius logic only if we actually scaled
865
+ const newStackSize = getStackSizeForLayout(layout, result.stackBounds);
866
+ if (newStackSize < stackMinSize) {
867
+ allBars = applyBorderRadiusLogic(allBars, layout, stackGap);
868
+ }
869
+ }
870
+ const initialBarMinSizes = getInitialBarMinSizes(allBars, barMinSize, stackMinSize);
871
+ const barOrigins = getBarOrigins(allBars, initialBarMinSizes, stackGap !== null && stackGap !== void 0 ? stackGap : 0, baseline, layout);
872
+ return allBars.map((bar, i) => _objectSpread(_objectSpread({}, bar), {}, {
873
+ x: layout === 'vertical' ? indexPos : bar.valuePos,
874
+ y: layout === 'vertical' ? bar.valuePos : indexPos,
875
+ width: layout === 'vertical' ? thickness : bar.length,
876
+ height: layout === 'vertical' ? bar.length : thickness,
877
+ dataX: layout === 'vertical' ? categoryValue : bar.dataValue,
878
+ dataY: layout === 'vertical' ? bar.dataValue : categoryValue,
879
+ origin: barOrigins[i],
880
+ borderRadius,
881
+ fillOpacity: defaultFillOpacity,
882
+ stroke: defaultStroke,
883
+ strokeWidth: defaultStrokeWidth,
884
+ minSize: initialBarMinSizes[i],
885
+ BarComponent: bar.BarComponent || defaultBarComponent
886
+ }));
74
887
  }