UNPKG

21.9 kBJavaScriptView Raw
1function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
2
3import _isEqual from "lodash/isEqual";
4import _get from "lodash/get";
5import _isPlainObject from "lodash/isPlainObject";
6import _isFunction from "lodash/isFunction";
7import _isNil from "lodash/isNil";
8
9function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
10
11function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
12
13function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
14
15function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
16
17function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
18
19function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
20
21function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
22
23function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
24
25function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
26
27function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
28
29function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
30
31function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
32
33function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
34
35function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
36
37/**
38 * @fileOverview Render sectors of a pie
39 */
40import React, { PureComponent } from 'react';
41import Animate from 'react-smooth';
42import classNames from 'classnames';
43import { Layer } from '../container/Layer';
44import { Sector } from '../shape/Sector';
45import { Curve } from '../shape/Curve';
46import { Text } from '../component/Text';
47import { Label } from '../component/Label';
48import { LabelList } from '../component/LabelList';
49import { Cell } from '../component/Cell';
50import { findAllByType } from '../util/ReactUtils';
51import { Global } from '../util/Global';
52import { polarToCartesian, getMaxRadius } from '../util/PolarUtils';
53import { isNumber, getPercentValue, mathSign, interpolateNumber, uniqueId } from '../util/DataUtils';
54import { getValueByDataKey } from '../util/ChartUtils';
55import { warn } from '../util/LogUtils';
56import { filterProps, adaptEventsOfChild } from '../util/types';
57export var Pie = /*#__PURE__*/function (_PureComponent) {
58 _inherits(Pie, _PureComponent);
59
60 var _super = _createSuper(Pie);
61
62 function Pie(props) {
63 var _this;
64
65 _classCallCheck(this, Pie);
66
67 _this = _super.call(this, props);
68 _this.state = void 0;
69 _this.id = uniqueId('recharts-pie-');
70
71 _this.handleAnimationEnd = function () {
72 var onAnimationEnd = _this.props.onAnimationEnd;
73
74 _this.setState({
75 isAnimationFinished: true
76 });
77
78 if (_isFunction(onAnimationEnd)) {
79 onAnimationEnd();
80 }
81 };
82
83 _this.handleAnimationStart = function () {
84 var onAnimationStart = _this.props.onAnimationStart;
85
86 _this.setState({
87 isAnimationFinished: false
88 });
89
90 if (_isFunction(onAnimationStart)) {
91 onAnimationStart();
92 }
93 };
94
95 _this.state = {
96 isAnimationFinished: !props.isAnimationActive,
97 prevIsAnimationActive: props.isAnimationActive,
98 prevAnimationId: props.animationId
99 };
100 return _this;
101 }
102
103 _createClass(Pie, [{
104 key: "isActiveIndex",
105 value: function isActiveIndex(i) {
106 var activeIndex = this.props.activeIndex;
107
108 if (Array.isArray(activeIndex)) {
109 return activeIndex.indexOf(i) !== -1;
110 }
111
112 return i === activeIndex;
113 }
114 }, {
115 key: "renderLabels",
116 value: function renderLabels(sectors) {
117 var isAnimationActive = this.props.isAnimationActive;
118
119 if (isAnimationActive && !this.state.isAnimationFinished) {
120 return null;
121 }
122
123 var _this$props = this.props,
124 label = _this$props.label,
125 labelLine = _this$props.labelLine,
126 dataKey = _this$props.dataKey,
127 valueKey = _this$props.valueKey;
128 var pieProps = filterProps(this.props);
129 var customLabelProps = filterProps(label);
130 var customLabelLineProps = filterProps(labelLine);
131 var offsetRadius = label && label.offsetRadius || 20;
132 var labels = sectors.map(function (entry, i) {
133 var midAngle = (entry.startAngle + entry.endAngle) / 2;
134 var endPoint = polarToCartesian(entry.cx, entry.cy, entry.outerRadius + offsetRadius, midAngle);
135
136 var labelProps = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, pieProps), entry), {}, {
137 stroke: 'none'
138 }, customLabelProps), {}, {
139 index: i,
140 textAnchor: Pie.getTextAnchor(endPoint.x, entry.cx)
141 }, endPoint);
142
143 var lineProps = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, pieProps), entry), {}, {
144 fill: 'none',
145 stroke: entry.fill
146 }, customLabelLineProps), {}, {
147 index: i,
148 points: [polarToCartesian(entry.cx, entry.cy, entry.outerRadius, midAngle), endPoint],
149 key: 'line'
150 });
151
152 var realDataKey = dataKey; // TODO: compatible to lower versions
153
154 if (_isNil(dataKey) && _isNil(valueKey)) {
155 realDataKey = 'value';
156 } else if (_isNil(dataKey)) {
157 realDataKey = valueKey;
158 }
159
160 return (
161 /*#__PURE__*/
162 // eslint-disable-next-line react/no-array-index-key
163 React.createElement(Layer, {
164 key: "label-".concat(i)
165 }, labelLine && Pie.renderLabelLineItem(labelLine, lineProps), Pie.renderLabelItem(label, labelProps, getValueByDataKey(entry, realDataKey)))
166 );
167 });
168 return /*#__PURE__*/React.createElement(Layer, {
169 className: "recharts-pie-labels"
170 }, labels);
171 }
172 }, {
173 key: "renderSectorsStatically",
174 value: function renderSectorsStatically(sectors) {
175 var _this2 = this;
176
177 var _this$props2 = this.props,
178 activeShape = _this$props2.activeShape,
179 blendStroke = _this$props2.blendStroke;
180 return sectors.map(function (entry, i) {
181 var sectorOptions = _this2.isActiveIndex(i) ? activeShape : null;
182
183 var sectorProps = _objectSpread(_objectSpread({}, entry), {}, {
184 stroke: blendStroke ? entry.fill : entry.stroke
185 });
186
187 return /*#__PURE__*/React.createElement(Layer, _extends({
188 className: "recharts-pie-sector"
189 }, adaptEventsOfChild(_this2.props, entry, i), {
190 key: "sector-".concat(i) // eslint-disable-line react/no-array-index-key
191
192 }), Pie.renderSectorItem(sectorOptions, sectorProps));
193 });
194 }
195 }, {
196 key: "renderSectorsWithAnimation",
197 value: function renderSectorsWithAnimation() {
198 var _this3 = this;
199
200 var _this$props3 = this.props,
201 sectors = _this$props3.sectors,
202 isAnimationActive = _this$props3.isAnimationActive,
203 animationBegin = _this$props3.animationBegin,
204 animationDuration = _this$props3.animationDuration,
205 animationEasing = _this$props3.animationEasing,
206 animationId = _this$props3.animationId;
207 var _this$state = this.state,
208 prevSectors = _this$state.prevSectors,
209 prevIsAnimationActive = _this$state.prevIsAnimationActive;
210 return /*#__PURE__*/React.createElement(Animate, {
211 begin: animationBegin,
212 duration: animationDuration,
213 isActive: isAnimationActive,
214 easing: animationEasing,
215 from: {
216 t: 0
217 },
218 to: {
219 t: 1
220 },
221 key: "pie-".concat(animationId, "-").concat(prevIsAnimationActive),
222 onAnimationStart: this.handleAnimationStart,
223 onAnimationEnd: this.handleAnimationEnd
224 }, function (_ref) {
225 var t = _ref.t;
226 var stepData = [];
227 var first = sectors && sectors[0];
228 var curAngle = first.startAngle;
229 sectors.forEach(function (entry, index) {
230 var prev = prevSectors && prevSectors[index];
231 var paddingAngle = index > 0 ? _get(entry, 'paddingAngle', 0) : 0;
232
233 if (prev) {
234 var angleIp = interpolateNumber(prev.endAngle - prev.startAngle, entry.endAngle - entry.startAngle);
235
236 var latest = _objectSpread(_objectSpread({}, entry), {}, {
237 startAngle: curAngle + paddingAngle,
238 endAngle: curAngle + angleIp(t) + paddingAngle
239 });
240
241 stepData.push(latest);
242 curAngle = latest.endAngle;
243 } else {
244 var endAngle = entry.endAngle,
245 startAngle = entry.startAngle;
246 var interpolatorAngle = interpolateNumber(0, endAngle - startAngle);
247 var deltaAngle = interpolatorAngle(t);
248
249 var _latest = _objectSpread(_objectSpread({}, entry), {}, {
250 startAngle: curAngle + paddingAngle,
251 endAngle: curAngle + deltaAngle + paddingAngle
252 });
253
254 stepData.push(_latest);
255 curAngle = _latest.endAngle;
256 }
257 });
258 return /*#__PURE__*/React.createElement(Layer, null, _this3.renderSectorsStatically(stepData));
259 });
260 }
261 }, {
262 key: "renderSectors",
263 value: function renderSectors() {
264 var _this$props4 = this.props,
265 sectors = _this$props4.sectors,
266 isAnimationActive = _this$props4.isAnimationActive;
267 var prevSectors = this.state.prevSectors;
268
269 if (isAnimationActive && sectors && sectors.length && (!prevSectors || !_isEqual(prevSectors, sectors))) {
270 return this.renderSectorsWithAnimation();
271 }
272
273 return this.renderSectorsStatically(sectors);
274 }
275 }, {
276 key: "render",
277 value: function render() {
278 var _this$props5 = this.props,
279 hide = _this$props5.hide,
280 sectors = _this$props5.sectors,
281 className = _this$props5.className,
282 label = _this$props5.label,
283 cx = _this$props5.cx,
284 cy = _this$props5.cy,
285 innerRadius = _this$props5.innerRadius,
286 outerRadius = _this$props5.outerRadius,
287 isAnimationActive = _this$props5.isAnimationActive;
288 var isAnimationFinished = this.state.isAnimationFinished;
289
290 if (hide || !sectors || !sectors.length || !isNumber(cx) || !isNumber(cy) || !isNumber(innerRadius) || !isNumber(outerRadius)) {
291 return null;
292 }
293
294 var layerClass = classNames('recharts-pie', className);
295 return /*#__PURE__*/React.createElement(Layer, {
296 className: layerClass
297 }, this.renderSectors(), label && this.renderLabels(sectors), Label.renderCallByParent(this.props, null, false), (!isAnimationActive || isAnimationFinished) && LabelList.renderCallByParent(this.props, sectors, false));
298 }
299 }], [{
300 key: "getDerivedStateFromProps",
301 value: function getDerivedStateFromProps(nextProps, prevState) {
302 if (prevState.prevIsAnimationActive !== nextProps.isAnimationActive) {
303 return {
304 prevIsAnimationActive: nextProps.isAnimationActive,
305 prevAnimationId: nextProps.animationId,
306 curSectors: nextProps.sectors,
307 prevSectors: []
308 };
309 }
310
311 if (nextProps.isAnimationActive && nextProps.animationId !== prevState.prevAnimationId) {
312 return {
313 prevAnimationId: nextProps.animationId,
314 curSectors: nextProps.sectors,
315 prevSectors: prevState.curSectors
316 };
317 }
318
319 if (nextProps.sectors !== prevState.curSectors) {
320 return {
321 curSectors: nextProps.sectors
322 };
323 }
324
325 return null;
326 }
327 }, {
328 key: "getTextAnchor",
329 value: function getTextAnchor(x, cx) {
330 if (x > cx) {
331 return 'start';
332 }
333
334 if (x < cx) {
335 return 'end';
336 }
337
338 return 'middle';
339 }
340 }, {
341 key: "renderLabelLineItem",
342 value: function renderLabelLineItem(option, props) {
343 if ( /*#__PURE__*/React.isValidElement(option)) {
344 return /*#__PURE__*/React.cloneElement(option, props);
345 }
346
347 if (_isFunction(option)) {
348 return option(props);
349 }
350
351 return /*#__PURE__*/React.createElement(Curve, _extends({}, props, {
352 type: "linear",
353 className: "recharts-pie-label-line"
354 }));
355 }
356 }, {
357 key: "renderLabelItem",
358 value: function renderLabelItem(option, props, value) {
359 if ( /*#__PURE__*/React.isValidElement(option)) {
360 return /*#__PURE__*/React.cloneElement(option, props);
361 }
362
363 var label = value;
364
365 if (_isFunction(option)) {
366 label = option(props);
367
368 if ( /*#__PURE__*/React.isValidElement(label)) {
369 return label;
370 }
371 }
372
373 return /*#__PURE__*/React.createElement(Text, _extends({}, props, {
374 alignmentBaseline: "middle",
375 className: "recharts-pie-label-text"
376 }), label);
377 }
378 }, {
379 key: "renderSectorItem",
380 value: function renderSectorItem(option, props) {
381 if ( /*#__PURE__*/React.isValidElement(option)) {
382 return /*#__PURE__*/React.cloneElement(option, props);
383 }
384
385 if (_isFunction(option)) {
386 return option(props);
387 }
388
389 if (_isPlainObject(option)) {
390 return /*#__PURE__*/React.createElement(Sector, _extends({}, props, option));
391 }
392
393 return /*#__PURE__*/React.createElement(Sector, props);
394 }
395 }]);
396
397 return Pie;
398}(PureComponent);
399Pie.displayName = 'Pie';
400Pie.defaultProps = {
401 stroke: '#fff',
402 fill: '#808080',
403 legendType: 'rect',
404 cx: '50%',
405 cy: '50%',
406 startAngle: 0,
407 endAngle: 360,
408 innerRadius: 0,
409 outerRadius: '80%',
410 paddingAngle: 0,
411 labelLine: true,
412 hide: false,
413 minAngle: 0,
414 isAnimationActive: !Global.isSsr,
415 animationBegin: 400,
416 animationDuration: 1500,
417 animationEasing: 'ease',
418 nameKey: 'name',
419 blendStroke: false
420};
421
422Pie.parseDeltaAngle = function (startAngle, endAngle) {
423 var sign = mathSign(endAngle - startAngle);
424 var deltaAngle = Math.min(Math.abs(endAngle - startAngle), 360);
425 return sign * deltaAngle;
426};
427
428Pie.getRealPieData = function (item) {
429 var _item$props = item.props,
430 data = _item$props.data,
431 children = _item$props.children;
432 var presentationProps = filterProps(item.props);
433 var cells = findAllByType(children, Cell.displayName);
434
435 if (data && data.length) {
436 return data.map(function (entry, index) {
437 return _objectSpread(_objectSpread(_objectSpread({
438 payload: entry
439 }, presentationProps), entry), cells && cells[index] && cells[index].props);
440 });
441 }
442
443 if (cells && cells.length) {
444 return cells.map(function (cell) {
445 return _objectSpread(_objectSpread({}, presentationProps), cell.props);
446 });
447 }
448
449 return [];
450};
451
452Pie.parseCoordinateOfPie = function (item, offset) {
453 var top = offset.top,
454 left = offset.left,
455 width = offset.width,
456 height = offset.height;
457 var maxPieRadius = getMaxRadius(width, height);
458 var cx = left + getPercentValue(item.props.cx, width, width / 2);
459 var cy = top + getPercentValue(item.props.cy, height, height / 2);
460 var innerRadius = getPercentValue(item.props.innerRadius, maxPieRadius, 0);
461 var outerRadius = getPercentValue(item.props.outerRadius, maxPieRadius, maxPieRadius * 0.8);
462 var maxRadius = item.props.maxRadius || Math.sqrt(width * width + height * height) / 2;
463 return {
464 cx: cx,
465 cy: cy,
466 innerRadius: innerRadius,
467 outerRadius: outerRadius,
468 maxRadius: maxRadius
469 };
470};
471
472Pie.getComposedData = function (_ref2) {
473 var item = _ref2.item,
474 offset = _ref2.offset;
475 var pieData = Pie.getRealPieData(item);
476
477 if (!pieData || !pieData.length) {
478 return null;
479 }
480
481 var _item$props2 = item.props,
482 cornerRadius = _item$props2.cornerRadius,
483 startAngle = _item$props2.startAngle,
484 endAngle = _item$props2.endAngle,
485 paddingAngle = _item$props2.paddingAngle,
486 dataKey = _item$props2.dataKey,
487 nameKey = _item$props2.nameKey,
488 valueKey = _item$props2.valueKey,
489 tooltipType = _item$props2.tooltipType;
490 var minAngle = Math.abs(item.props.minAngle);
491 var coordinate = Pie.parseCoordinateOfPie(item, offset);
492 var deltaAngle = Pie.parseDeltaAngle(startAngle, endAngle);
493 var absDeltaAngle = Math.abs(deltaAngle);
494 var realDataKey = dataKey;
495
496 if (_isNil(dataKey) && _isNil(valueKey)) {
497 warn(false, "Use \"dataKey\" to specify the value of pie,\n the props \"valueKey\" will be deprecated in 1.1.0");
498 realDataKey = 'value';
499 } else if (_isNil(dataKey)) {
500 warn(false, "Use \"dataKey\" to specify the value of pie,\n the props \"valueKey\" will be deprecated in 1.1.0");
501 realDataKey = valueKey;
502 }
503
504 var notZeroItemCount = pieData.filter(function (entry) {
505 return getValueByDataKey(entry, realDataKey, 0) !== 0;
506 }).length;
507 var totalPadingAngle = (absDeltaAngle >= 360 ? notZeroItemCount : notZeroItemCount - 1) * paddingAngle;
508 var realTotalAngle = absDeltaAngle - notZeroItemCount * minAngle - totalPadingAngle;
509 var sum = pieData.reduce(function (result, entry) {
510 var val = getValueByDataKey(entry, realDataKey, 0);
511 return result + (isNumber(val) ? val : 0);
512 }, 0);
513 var sectors;
514
515 if (sum > 0) {
516 var prev;
517 sectors = pieData.map(function (entry, i) {
518 var val = getValueByDataKey(entry, realDataKey, 0);
519 var name = getValueByDataKey(entry, nameKey, i);
520 var percent = (isNumber(val) ? val : 0) / sum;
521 var tempStartAngle;
522
523 if (i) {
524 tempStartAngle = prev.endAngle + mathSign(deltaAngle) * paddingAngle * (val !== 0 ? 1 : 0);
525 } else {
526 tempStartAngle = startAngle;
527 }
528
529 var tempEndAngle = tempStartAngle + mathSign(deltaAngle) * ((val !== 0 ? minAngle : 0) + percent * realTotalAngle);
530 var midAngle = (tempStartAngle + tempEndAngle) / 2;
531 var middleRadius = (coordinate.innerRadius + coordinate.outerRadius) / 2;
532 var tooltipPayload = [{
533 name: name,
534 value: val,
535 payload: entry,
536 dataKey: realDataKey,
537 type: tooltipType
538 }];
539 var tooltipPosition = polarToCartesian(coordinate.cx, coordinate.cy, middleRadius, midAngle);
540 prev = _objectSpread(_objectSpread(_objectSpread({
541 percent: percent,
542 cornerRadius: cornerRadius,
543 name: name,
544 tooltipPayload: tooltipPayload,
545 midAngle: midAngle,
546 middleRadius: middleRadius,
547 tooltipPosition: tooltipPosition
548 }, entry), coordinate), {}, {
549 value: getValueByDataKey(entry, realDataKey),
550 startAngle: tempStartAngle,
551 endAngle: tempEndAngle,
552 payload: entry,
553 paddingAngle: mathSign(deltaAngle) * paddingAngle
554 });
555 return prev;
556 });
557 }
558
559 return _objectSpread(_objectSpread({}, coordinate), {}, {
560 sectors: sectors,
561 data: pieData
562 });
563};
\No newline at end of file