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