source: node_modules/recharts/lib/util/ChartUtils.js

Last change on this file was a762898, checked in by istevanoska <ilinastevanoska@…>, 5 months ago

Added visualizations

  • Property mode set to 100644
File size: 19.4 KB
Line 
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.getCateCoordinateOfBar = exports.getBaseValueOfBar = exports.getBandSizeOfAxis = exports.calculatePolarTooltipPos = exports.calculateCartesianTooltipPos = exports.appendOffsetOfLegend = exports.MIN_VALUE_REG = exports.MAX_VALUE_REG = void 0;
7exports.getCateCoordinateOfLine = getCateCoordinateOfLine;
8exports.getDomainOfStackGroups = exports.getCoordinatesOfGrid = void 0;
9exports.getNormalizedStackId = getNormalizedStackId;
10exports.getTicksOfAxis = exports.getStackedData = void 0;
11exports.getTooltipEntry = getTooltipEntry;
12exports.getTooltipNameProp = getTooltipNameProp;
13exports.getValueByDataKey = getValueByDataKey;
14exports.truncateByDomain = exports.offsetSign = exports.offsetPositive = exports.isCategoricalAxis = void 0;
15var _sortBy = _interopRequireDefault(require("es-toolkit/compat/sortBy"));
16var _get = _interopRequireDefault(require("es-toolkit/compat/get"));
17var _d3Shape = require("victory-vendor/d3-shape");
18var _DataUtils = require("./DataUtils");
19var _getSliced = require("./getSliced");
20var _isWellBehavedNumber = require("./isWellBehavedNumber");
21function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
22function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
23function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
24function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
25function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
26function _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); }
27function getValueByDataKey(obj, dataKey, defaultValue) {
28 if ((0, _DataUtils.isNullish)(obj) || (0, _DataUtils.isNullish)(dataKey)) {
29 return defaultValue;
30 }
31 if ((0, _DataUtils.isNumOrStr)(dataKey)) {
32 return (0, _get.default)(obj, dataKey, defaultValue);
33 }
34 if (typeof dataKey === 'function') {
35 return dataKey(obj);
36 }
37 return defaultValue;
38}
39var appendOffsetOfLegend = (offset, legendSettings, legendSize) => {
40 if (legendSettings && legendSize) {
41 var {
42 width: boxWidth,
43 height: boxHeight
44 } = legendSize;
45 var {
46 align,
47 verticalAlign,
48 layout
49 } = legendSettings;
50 if ((layout === 'vertical' || layout === 'horizontal' && verticalAlign === 'middle') && align !== 'center' && (0, _DataUtils.isNumber)(offset[align])) {
51 return _objectSpread(_objectSpread({}, offset), {}, {
52 [align]: offset[align] + (boxWidth || 0)
53 });
54 }
55 if ((layout === 'horizontal' || layout === 'vertical' && align === 'center') && verticalAlign !== 'middle' && (0, _DataUtils.isNumber)(offset[verticalAlign])) {
56 return _objectSpread(_objectSpread({}, offset), {}, {
57 [verticalAlign]: offset[verticalAlign] + (boxHeight || 0)
58 });
59 }
60 }
61 return offset;
62};
63exports.appendOffsetOfLegend = appendOffsetOfLegend;
64var isCategoricalAxis = (layout, axisType) => layout === 'horizontal' && axisType === 'xAxis' || layout === 'vertical' && axisType === 'yAxis' || layout === 'centric' && axisType === 'angleAxis' || layout === 'radial' && axisType === 'radiusAxis';
65
66/**
67 * Calculate the Coordinates of grid
68 * @param {Array} ticks The ticks in axis
69 * @param {Number} minValue The minimum value of axis
70 * @param {Number} maxValue The maximum value of axis
71 * @param {boolean} syncWithTicks Synchronize grid lines with ticks or not
72 * @return {Array} Coordinates
73 */
74exports.isCategoricalAxis = isCategoricalAxis;
75var getCoordinatesOfGrid = (ticks, minValue, maxValue, syncWithTicks) => {
76 if (syncWithTicks) {
77 return ticks.map(entry => entry.coordinate);
78 }
79 var hasMin, hasMax;
80 var values = ticks.map(entry => {
81 if (entry.coordinate === minValue) {
82 hasMin = true;
83 }
84 if (entry.coordinate === maxValue) {
85 hasMax = true;
86 }
87 return entry.coordinate;
88 });
89 if (!hasMin) {
90 values.push(minValue);
91 }
92 if (!hasMax) {
93 values.push(maxValue);
94 }
95 return values;
96};
97exports.getCoordinatesOfGrid = getCoordinatesOfGrid;
98/**
99 * Of on four almost identical implementations of tick generation.
100 * The four horsemen of tick generation are:
101 * - {@link selectTooltipAxisTicks}
102 * - {@link combineAxisTicks}
103 * - {@link getTicksOfAxis}.
104 * - {@link combineGraphicalItemTicks}
105 */
106var getTicksOfAxis = (axis, isGrid, isAll) => {
107 if (!axis) {
108 return null;
109 }
110 var {
111 duplicateDomain,
112 type,
113 range,
114 scale,
115 realScaleType,
116 isCategorical,
117 categoricalDomain,
118 tickCount,
119 ticks,
120 niceTicks,
121 axisType
122 } = axis;
123 if (!scale) {
124 return null;
125 }
126 var offsetForBand = realScaleType === 'scaleBand' && scale.bandwidth ? scale.bandwidth() / 2 : 2;
127 var offset = (isGrid || isAll) && type === 'category' && scale.bandwidth ? scale.bandwidth() / offsetForBand : 0;
128 offset = axisType === 'angleAxis' && range && range.length >= 2 ? (0, _DataUtils.mathSign)(range[0] - range[1]) * 2 * offset : offset;
129
130 // The ticks set by user should only affect the ticks adjacent to axis line
131 if (isGrid && (ticks || niceTicks)) {
132 var result = (ticks || niceTicks || []).map((entry, index) => {
133 var scaleContent = duplicateDomain ? duplicateDomain.indexOf(entry) : entry;
134 var scaled = scale.map(scaleContent);
135 if (!(0, _isWellBehavedNumber.isWellBehavedNumber)(scaled)) {
136 return null;
137 }
138 return {
139 // If the scaleContent is not a number, the coordinate will be NaN.
140 // That could be the case for example with a PointScale and a string as domain.
141 coordinate: scaled + offset,
142 value: entry,
143 offset,
144 index
145 };
146 }).filter(_DataUtils.isNotNil);
147 return result;
148 }
149
150 // When axis is a categorical axis, but the type of axis is number or the scale of axis is not "auto"
151 if (isCategorical && categoricalDomain) {
152 return categoricalDomain.map((entry, index) => {
153 var scaled = scale.map(entry);
154 if (!(0, _isWellBehavedNumber.isWellBehavedNumber)(scaled)) {
155 return null;
156 }
157 return {
158 coordinate: scaled + offset,
159 value: entry,
160 index,
161 offset
162 };
163 }).filter(_DataUtils.isNotNil);
164 }
165 if (scale.ticks && !isAll && tickCount != null) {
166 return scale.ticks(tickCount).map((entry, index) => {
167 var scaled = scale.map(entry);
168 if (!(0, _isWellBehavedNumber.isWellBehavedNumber)(scaled)) {
169 return null;
170 }
171 return {
172 coordinate: scaled + offset,
173 value: entry,
174 index,
175 offset
176 };
177 }).filter(_DataUtils.isNotNil);
178 }
179
180 // When axis has duplicated text, serial numbers are used to generate scale
181 return scale.domain().map((entry, index) => {
182 var scaled = scale.map(entry);
183 if (!(0, _isWellBehavedNumber.isWellBehavedNumber)(scaled)) {
184 return null;
185 }
186 return {
187 coordinate: scaled + offset,
188 // @ts-expect-error can't use Date as an index
189 value: duplicateDomain ? duplicateDomain[entry] : entry,
190 index,
191 offset
192 };
193 }).filter(_DataUtils.isNotNil);
194};
195
196/**
197 * Both value and domain are tuples of two numbers
198 * - but the type stays as array of numbers until we have better support in rest of the app
199 * @param value input that will be truncated
200 * @param domain boundaries
201 * @returns tuple of two numbers
202 */
203exports.getTicksOfAxis = getTicksOfAxis;
204var truncateByDomain = (value, domain) => {
205 if (!domain || domain.length !== 2 || !(0, _DataUtils.isNumber)(domain[0]) || !(0, _DataUtils.isNumber)(domain[1])) {
206 return value;
207 }
208 var minValue = Math.min(domain[0], domain[1]);
209 var maxValue = Math.max(domain[0], domain[1]);
210 var result = [value[0], value[1]];
211 if (!(0, _DataUtils.isNumber)(value[0]) || value[0] < minValue) {
212 result[0] = minValue;
213 }
214 if (!(0, _DataUtils.isNumber)(value[1]) || value[1] > maxValue) {
215 result[1] = maxValue;
216 }
217 if (result[0] > maxValue) {
218 result[0] = maxValue;
219 }
220 if (result[1] < minValue) {
221 result[1] = minValue;
222 }
223 return result;
224};
225
226/**
227 * Stacks all positive numbers above zero and all negative numbers below zero.
228 *
229 * If all values in the series are positive then this behaves the same as 'none' stacker.
230 *
231 * @param {Array} series from d3-shape Stack
232 * @return {Array} series with applied offset
233 */
234exports.truncateByDomain = truncateByDomain;
235var offsetSign = series => {
236 var _series$;
237 var n = series.length;
238 if (n <= 0) {
239 return;
240 }
241 var m = (_series$ = series[0]) === null || _series$ === void 0 ? void 0 : _series$.length;
242 if (m == null || m <= 0) {
243 return;
244 }
245 for (var j = 0; j < m; ++j) {
246 var positive = 0;
247 var negative = 0;
248 for (var i = 0; i < n; ++i) {
249 var row = series[i];
250 var col = row === null || row === void 0 ? void 0 : row[j];
251 if (col == null) {
252 continue;
253 }
254 var series1 = col[1];
255 var series0 = col[0];
256 var value = (0, _DataUtils.isNan)(series1) ? series0 : series1;
257 if (value >= 0) {
258 col[0] = positive;
259 positive += value;
260 col[1] = positive;
261 } else {
262 col[0] = negative;
263 negative += value;
264 col[1] = negative;
265 }
266 }
267 }
268};
269
270/**
271 * Replaces all negative values with zero when stacking data.
272 *
273 * If all values in the series are positive then this behaves the same as 'none' stacker.
274 *
275 * @param {Array} series from d3-shape Stack
276 * @return {Array} series with applied offset
277 */
278exports.offsetSign = offsetSign;
279var offsetPositive = series => {
280 var _series$2;
281 var n = series.length;
282 if (n <= 0) {
283 return;
284 }
285 var m = (_series$2 = series[0]) === null || _series$2 === void 0 ? void 0 : _series$2.length;
286 if (m == null || m <= 0) {
287 return;
288 }
289 for (var j = 0; j < m; ++j) {
290 var positive = 0;
291 for (var i = 0; i < n; ++i) {
292 var row = series[i];
293 var col = row === null || row === void 0 ? void 0 : row[j];
294 if (col == null) {
295 continue;
296 }
297 var value = (0, _DataUtils.isNan)(col[1]) ? col[0] : col[1];
298 if (value >= 0) {
299 col[0] = positive;
300 positive += value;
301 col[1] = positive;
302 } else {
303 col[0] = 0;
304 col[1] = 0;
305 }
306 }
307 }
308};
309
310/**
311 * Function type to compute offset for stacked data.
312 *
313 * d3-shape has something fishy going on with its types.
314 * In @definitelytyped/d3-shape, this function (the offset accessor) is typed as Series<> => void.
315 * However! When I actually open the storybook I can see that the offset accessor actually receives Array<Series<>>.
316 * The same I can see in the source code itself:
317 * https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/66042
318 * That one unfortunately has no types but we can tell it passes three-dimensional array.
319 *
320 * Which leads me to believe that definitelytyped is wrong on this one.
321 * There's open discussion on this topic without much attention:
322 * https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/66042
323 */
324exports.offsetPositive = offsetPositive;
325var STACK_OFFSET_MAP = {
326 sign: offsetSign,
327 // @ts-expect-error definitelytyped types are incorrect
328 expand: _d3Shape.stackOffsetExpand,
329 // @ts-expect-error definitelytyped types are incorrect
330 none: _d3Shape.stackOffsetNone,
331 // @ts-expect-error definitelytyped types are incorrect
332 silhouette: _d3Shape.stackOffsetSilhouette,
333 // @ts-expect-error definitelytyped types are incorrect
334 wiggle: _d3Shape.stackOffsetWiggle,
335 positive: offsetPositive
336};
337var getStackedData = (data, dataKeys, offsetType) => {
338 var _STACK_OFFSET_MAP$off;
339 var offsetAccessor = (_STACK_OFFSET_MAP$off = STACK_OFFSET_MAP[offsetType]) !== null && _STACK_OFFSET_MAP$off !== void 0 ? _STACK_OFFSET_MAP$off : _d3Shape.stackOffsetNone;
340 var stack = (0, _d3Shape.stack)().keys(dataKeys).value((d, key) => Number(getValueByDataKey(d, key, 0))).order(_d3Shape.stackOrderNone)
341 // @ts-expect-error definitelytyped types are incorrect
342 .offset(offsetAccessor);
343 var result = stack(data);
344
345 // Post-process ranged data: if value is an array of two numbers, use them directly without stacking
346 result.forEach((series, seriesIndex) => {
347 series.forEach((point, pointIndex) => {
348 var value = getValueByDataKey(data[pointIndex], dataKeys[seriesIndex], 0);
349 if (Array.isArray(value) && value.length === 2 && (0, _DataUtils.isNumber)(value[0]) && (0, _DataUtils.isNumber)(value[1])) {
350 // eslint-disable-next-line prefer-destructuring,no-param-reassign
351 point[0] = value[0];
352 // eslint-disable-next-line prefer-destructuring,no-param-reassign
353 point[1] = value[1];
354 }
355 });
356 });
357 return result;
358};
359
360/**
361 * Externally, we accept both strings and numbers as stack IDs
362 * @inline
363 */
364
365/**
366 * Stack IDs in the external props allow numbers; but internally we use it as an object key
367 * and object keys are always strings. Also, it would be kinda confusing if stackId=8 and stackId='8' were different stacks
368 * so let's just force a string.
369 */
370exports.getStackedData = getStackedData;
371function getNormalizedStackId(publicStackId) {
372 return publicStackId == null ? undefined : String(publicStackId);
373}
374function getCateCoordinateOfLine(_ref) {
375 var {
376 axis,
377 ticks,
378 bandSize,
379 entry,
380 index,
381 dataKey
382 } = _ref;
383 if (axis.type === 'category') {
384 // find coordinate of category axis by the value of category
385 // @ts-expect-error why does this use direct object access instead of getValueByDataKey?
386 if (!axis.allowDuplicatedCategory && axis.dataKey && !(0, _DataUtils.isNullish)(entry[axis.dataKey])) {
387 // @ts-expect-error why does this use direct object access instead of getValueByDataKey?
388 var matchedTick = (0, _DataUtils.findEntryInArray)(ticks, 'value', entry[axis.dataKey]);
389 if (matchedTick) {
390 return matchedTick.coordinate + bandSize / 2;
391 }
392 }
393 return ticks !== null && ticks !== void 0 && ticks[index] ? ticks[index].coordinate + bandSize / 2 : null;
394 }
395 var value = getValueByDataKey(entry, !(0, _DataUtils.isNullish)(dataKey) ? dataKey : axis.dataKey);
396 var scaled = axis.scale.map(value);
397 if (!(0, _DataUtils.isNumber)(scaled)) {
398 return null;
399 }
400 return scaled;
401}
402var getCateCoordinateOfBar = _ref2 => {
403 var {
404 axis,
405 ticks,
406 offset,
407 bandSize,
408 entry,
409 index
410 } = _ref2;
411 if (axis.type === 'category') {
412 return ticks[index] ? ticks[index].coordinate + offset : null;
413 }
414 // @ts-expect-error getValueByDataKey does not validate the output type
415 var value = getValueByDataKey(entry, axis.dataKey, axis.scale.domain()[index]);
416 if ((0, _DataUtils.isNullish)(value)) {
417 return null;
418 }
419 var scaled = axis.scale.map(value);
420 if (!(0, _DataUtils.isNumber)(scaled)) {
421 return null;
422 }
423 return scaled - bandSize / 2 + offset;
424};
425exports.getCateCoordinateOfBar = getCateCoordinateOfBar;
426var getBaseValueOfBar = _ref3 => {
427 var {
428 numericAxis
429 } = _ref3;
430 var domain = numericAxis.scale.domain();
431 if (numericAxis.type === 'number') {
432 // @ts-expect-error type number means the domain has numbers in it but this relationship is not known to typescript
433 var minValue = Math.min(domain[0], domain[1]);
434 // @ts-expect-error type number means the domain has numbers in it but this relationship is not known to typescript
435 var maxValue = Math.max(domain[0], domain[1]);
436 if (minValue <= 0 && maxValue >= 0) {
437 return 0;
438 }
439 if (maxValue < 0) {
440 return maxValue;
441 }
442 return minValue;
443 }
444 return domain[0];
445};
446exports.getBaseValueOfBar = getBaseValueOfBar;
447var getDomainOfSingle = data => {
448 var flat = data.flat(2).filter(_DataUtils.isNumber);
449 return [Math.min(...flat), Math.max(...flat)];
450};
451var makeDomainFinite = domain => {
452 return [domain[0] === Infinity ? 0 : domain[0], domain[1] === -Infinity ? 0 : domain[1]];
453};
454var getDomainOfStackGroups = (stackGroups, startIndex, endIndex) => {
455 if (stackGroups == null) {
456 return undefined;
457 }
458 return makeDomainFinite(Object.keys(stackGroups).reduce((result, stackId) => {
459 var group = stackGroups[stackId];
460 if (!group) {
461 return result;
462 }
463 var {
464 stackedData
465 } = group;
466 var domain = stackedData.reduce((res, entry) => {
467 var sliced = (0, _getSliced.getSliced)(entry, startIndex, endIndex);
468 var s = getDomainOfSingle(sliced);
469 if (!(0, _isWellBehavedNumber.isWellBehavedNumber)(s[0]) || !(0, _isWellBehavedNumber.isWellBehavedNumber)(s[1])) {
470 return res;
471 }
472 return [Math.min(res[0], s[0]), Math.max(res[1], s[1])];
473 }, [Infinity, -Infinity]);
474 return [Math.min(domain[0], result[0]), Math.max(domain[1], result[1])];
475 }, [Infinity, -Infinity]));
476};
477exports.getDomainOfStackGroups = getDomainOfStackGroups;
478var MIN_VALUE_REG = exports.MIN_VALUE_REG = /^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/;
479var MAX_VALUE_REG = exports.MAX_VALUE_REG = /^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/;
480
481/**
482 * Calculate the size between two category
483 * @param {Object} axis The options of axis
484 * @param {Array} ticks The ticks of axis
485 * @param {Boolean} isBar if items in axis are bars
486 * @return {Number} Size
487 */
488var getBandSizeOfAxis = (axis, ticks, isBar) => {
489 if (axis && axis.scale && axis.scale.bandwidth) {
490 var bandWidth = axis.scale.bandwidth();
491 if (!isBar || bandWidth > 0) {
492 return bandWidth;
493 }
494 }
495 if (axis && ticks && ticks.length >= 2) {
496 var orderedTicks = (0, _sortBy.default)(ticks, o => o.coordinate);
497 var bandSize = Infinity;
498 for (var i = 1, len = orderedTicks.length; i < len; i++) {
499 var cur = orderedTicks[i];
500 var prev = orderedTicks[i - 1];
501 bandSize = Math.min(((cur === null || cur === void 0 ? void 0 : cur.coordinate) || 0) - ((prev === null || prev === void 0 ? void 0 : prev.coordinate) || 0), bandSize);
502 }
503 return bandSize === Infinity ? 0 : bandSize;
504 }
505 return isBar ? undefined : 0;
506};
507exports.getBandSizeOfAxis = getBandSizeOfAxis;
508function getTooltipEntry(_ref4) {
509 var {
510 tooltipEntrySettings,
511 dataKey,
512 payload,
513 value,
514 name
515 } = _ref4;
516 return _objectSpread(_objectSpread({}, tooltipEntrySettings), {}, {
517 dataKey,
518 payload,
519 value,
520 name
521 });
522}
523function getTooltipNameProp(nameFromItem, dataKey) {
524 if (nameFromItem) {
525 return String(nameFromItem);
526 }
527 if (typeof dataKey === 'string') {
528 return dataKey;
529 }
530 return undefined;
531}
532var calculateCartesianTooltipPos = (coordinate, layout) => {
533 if (layout === 'horizontal') {
534 return coordinate.chartX;
535 }
536 if (layout === 'vertical') {
537 return coordinate.chartY;
538 }
539 return undefined;
540};
541exports.calculateCartesianTooltipPos = calculateCartesianTooltipPos;
542var calculatePolarTooltipPos = (rangeObj, layout) => {
543 if (layout === 'centric') {
544 return rangeObj.angle;
545 }
546 return rangeObj.radius;
547};
548exports.calculatePolarTooltipPos = calculatePolarTooltipPos;
Note: See TracBrowser for help on using the repository browser.