UNPKG

recharts

Version:
507 lines (454 loc) 19 kB
import _isEqual from "lodash/isEqual"; import _isFunction from "lodash/isFunction"; import _isNil from "lodash/isNil"; var _class, _class2, _temp; function _typeof(obj) { 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); } function _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); } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } function _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; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _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); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * @fileOverview Render a group of scatters */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Animate from 'react-smooth'; import classNames from 'classnames'; import pureRender from '../util/PureRender'; import Layer from '../container/Layer'; import LabelList from '../component/LabelList'; import { PRESENTATION_ATTRIBUTES, EVENT_ATTRIBUTES, LEGEND_TYPES, TOOLTIP_TYPES, getPresentationAttributes, filterEventsOfChild, isSsr, findAllByType } from '../util/ReactUtils'; import ZAxis from './ZAxis'; import Curve from '../shape/Curve'; import Symbols from '../shape/Symbols'; import ErrorBar from './ErrorBar'; import Cell from '../component/Cell'; import { uniqueId, interpolateNumber, getLinearRegression } from '../util/DataUtils'; import { getValueByDataKey, getCateCoordinateOfLine } from '../util/ChartUtils'; var Scatter = pureRender(_class = (_temp = _class2 = /*#__PURE__*/ function (_Component) { _inherits(Scatter, _Component); function Scatter() { var _getPrototypeOf2; var _this; _classCallCheck(this, Scatter); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Scatter)).call.apply(_getPrototypeOf2, [this].concat(args))); _this.state = { isAnimationFinished: false }; _this.cachePrevPoints = function (points) { _this.setState({ prevPoints: points }); }; _this.handleAnimationEnd = function () { _this.setState({ isAnimationFinished: true }); }; _this.handleAnimationStart = function () { _this.setState({ isAnimationFinished: false }); }; _this.id = uniqueId('recharts-scatter-'); return _this; } _createClass(Scatter, [{ key: "componentWillReceiveProps", value: function componentWillReceiveProps(nextProps) { var _this$props = this.props, animationId = _this$props.animationId, points = _this$props.points; if (nextProps.animationId !== animationId) { this.cachePrevPoints(points); } } }, { key: "renderSymbolsStatically", value: function renderSymbolsStatically(points) { var _this2 = this; var _this$props2 = this.props, shape = _this$props2.shape, activeShape = _this$props2.activeShape, activeIndex = _this$props2.activeIndex; var baseProps = getPresentationAttributes(this.props); return points.map(function (entry, i) { var props = _objectSpread({ key: "symbol-".concat(i) }, baseProps, entry); return React.createElement(Layer, _extends({ className: "recharts-scatter-symbol" }, filterEventsOfChild(_this2.props, entry, i), { key: "symbol-".concat(i) }), _this2.constructor.renderSymbolItem(activeIndex === i ? activeShape : shape, props)); }); } }, { key: "renderSymbolsWithAnimation", value: function renderSymbolsWithAnimation() { var _this3 = this; var _this$props3 = this.props, points = _this$props3.points, isAnimationActive = _this$props3.isAnimationActive, animationBegin = _this$props3.animationBegin, animationDuration = _this$props3.animationDuration, animationEasing = _this$props3.animationEasing, animationId = _this$props3.animationId; var prevPoints = this.state.prevPoints; return React.createElement(Animate, { begin: animationBegin, duration: animationDuration, isActive: isAnimationActive, easing: animationEasing, from: { t: 0 }, to: { t: 1 }, key: "pie-".concat(animationId), onAnimationEnd: this.handleAnimationEnd, onAnimationStart: this.handleAnimationStart }, function (_ref) { var t = _ref.t; var stepData = points.map(function (entry, index) { var prev = prevPoints && prevPoints[index]; if (prev) { var interpolatorCx = interpolateNumber(prev.cx, entry.cx); var interpolatorCy = interpolateNumber(prev.cy, entry.cy); var interpolatorSize = interpolateNumber(prev.size, entry.size); return _objectSpread({}, entry, { cx: interpolatorCx(t), cy: interpolatorCy(t), size: interpolatorSize(t) }); } var interpolator = interpolateNumber(0, entry.size); return _objectSpread({}, entry, { size: interpolator(t) }); }); return React.createElement(Layer, null, _this3.renderSymbolsStatically(stepData)); }); } }, { key: "renderSymbols", value: function renderSymbols() { var _this$props4 = this.props, points = _this$props4.points, isAnimationActive = _this$props4.isAnimationActive; var prevPoints = this.state.prevPoints; if (isAnimationActive && points && points.length && (!prevPoints || !_isEqual(prevPoints, points))) { return this.renderSymbolsWithAnimation(); } return this.renderSymbolsStatically(points); } }, { key: "renderErrorBar", value: function renderErrorBar() { var isAnimationActive = this.props.isAnimationActive; if (isAnimationActive && !this.state.isAnimationFinished) { return null; } var _this$props5 = this.props, points = _this$props5.points, xAxis = _this$props5.xAxis, yAxis = _this$props5.yAxis, children = _this$props5.children; var errorBarItems = findAllByType(children, ErrorBar); if (!errorBarItems) { return null; } function dataPointFormatterY(dataPoint, dataKey) { return { x: dataPoint.cx, y: dataPoint.cy, value: dataPoint.y, errorVal: getValueByDataKey(dataPoint, dataKey) }; } function dataPointFormatterX(dataPoint, dataKey) { return { x: dataPoint.cx, y: dataPoint.cy, value: dataPoint.x, errorVal: getValueByDataKey(dataPoint, dataKey) }; } return errorBarItems.map(function (item, i) { var direction = item.props.direction; return React.cloneElement(item, { key: i, data: points, xAxis: xAxis, yAxis: yAxis, layout: direction === 'x' ? 'vertical' : 'horizontal', dataPointFormatter: direction === 'x' ? dataPointFormatterX : dataPointFormatterY }); }); } }, { key: "renderLine", value: function renderLine() { var _this$props6 = this.props, points = _this$props6.points, line = _this$props6.line, lineType = _this$props6.lineType, lineJointType = _this$props6.lineJointType; var scatterProps = getPresentationAttributes(this.props); var customLineProps = getPresentationAttributes(line); var linePoints, lineItem; if (lineType === 'joint') { linePoints = points.map(function (entry) { return { x: entry.cx, y: entry.cy }; }); } else if (lineType === 'fitting') { var _getLinearRegression = getLinearRegression(points), xmin = _getLinearRegression.xmin, xmax = _getLinearRegression.xmax, a = _getLinearRegression.a, b = _getLinearRegression.b; var linearExp = function linearExp(x) { return a * x + b; }; linePoints = [{ x: xmin, y: linearExp(xmin) }, { x: xmax, y: linearExp(xmax) }]; } var lineProps = _objectSpread({}, scatterProps, { fill: 'none', stroke: scatterProps && scatterProps.fill }, customLineProps, { points: linePoints }); if (React.isValidElement(line)) { lineItem = React.cloneElement(line, lineProps); } else if (_isFunction(line)) { lineItem = line(lineProps); } else { lineItem = React.createElement(Curve, _extends({}, lineProps, { type: lineJointType })); } return React.createElement(Layer, { className: "recharts-scatter-line", key: "recharts-scatter-line" }, lineItem); } }, { key: "render", value: function render() { var _this$props7 = this.props, hide = _this$props7.hide, points = _this$props7.points, line = _this$props7.line, className = _this$props7.className, xAxis = _this$props7.xAxis, yAxis = _this$props7.yAxis, left = _this$props7.left, top = _this$props7.top, width = _this$props7.width, height = _this$props7.height, id = _this$props7.id; if (hide || !points || !points.length) { return null; } var _this$state = this.state, isAnimationActive = _this$state.isAnimationActive, isAnimationFinished = _this$state.isAnimationFinished; var layerClass = classNames('recharts-scatter', className); var needClip = xAxis && xAxis.allowDataOverflow || yAxis && yAxis.allowDataOverflow; var clipPathId = _isNil(id) ? this.id : id; return React.createElement(Layer, { className: layerClass, clipPath: needClip ? "url(#clipPath-".concat(clipPathId, ")") : null }, needClip ? React.createElement("defs", null, React.createElement("clipPath", { id: "clipPath-".concat(clipPathId) }, React.createElement("rect", { x: left, y: top, width: width, height: height }))) : null, line && this.renderLine(), this.renderErrorBar(), React.createElement(Layer, { key: "recharts-scatter-symbols" }, this.renderSymbols()), (!isAnimationActive || isAnimationFinished) && LabelList.renderCallByParent(this.props, points)); } }], [{ key: "renderSymbolItem", value: function renderSymbolItem(option, props) { var symbol; if (React.isValidElement(option)) { symbol = React.cloneElement(option, props); } else if (_isFunction(option)) { symbol = option(props); } else { symbol = React.createElement(Symbols, _extends({}, props, { type: option })); } return symbol; } }]); return Scatter; }(Component), _class2.displayName = 'Scatter', _class2.propTypes = _objectSpread({}, EVENT_ATTRIBUTES, PRESENTATION_ATTRIBUTES, { xAxisId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), yAxisId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), zAxisId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), line: PropTypes.oneOfType([PropTypes.bool, PropTypes.object, PropTypes.func, PropTypes.element]), lineType: PropTypes.oneOf(['fitting', 'joint']), lineJointType: PropTypes.oneOfType([PropTypes.oneOf(['basis', 'basisClosed', 'basisOpen', 'linear', 'linearClosed', 'natural', 'monotoneX', 'monotoneY', 'monotone', 'step', 'stepBefore', 'stepAfter']), PropTypes.func]), legendType: PropTypes.oneOf(LEGEND_TYPES), tooltipType: PropTypes.oneOf(TOOLTIP_TYPES), className: PropTypes.string, name: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), activeIndex: PropTypes.number, activeShape: PropTypes.oneOfType([PropTypes.object, PropTypes.func, PropTypes.element]), shape: PropTypes.oneOfType([PropTypes.oneOf(['circle', 'cross', 'diamond', 'square', 'star', 'triangle', 'wye']), PropTypes.element, PropTypes.func]), points: PropTypes.arrayOf(PropTypes.shape({ cx: PropTypes.number, cy: PropTypes.number, size: PropTypes.number, node: PropTypes.shape({ x: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), y: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), z: PropTypes.oneOfType([PropTypes.number, PropTypes.string]) }), payload: PropTypes.any })), hide: PropTypes.bool, isAnimationActive: PropTypes.bool, animationId: PropTypes.number, animationBegin: PropTypes.number, animationDuration: PropTypes.number, animationEasing: PropTypes.oneOf(['ease', 'ease-in', 'ease-out', 'ease-in-out', 'linear']) }), _class2.defaultProps = { xAxisId: 0, yAxisId: 0, zAxisId: 0, legendType: 'circle', lineType: 'joint', lineJointType: 'linear', data: [], shape: 'circle', hide: false, isAnimationActive: !isSsr(), animationBegin: 0, animationDuration: 400, animationEasing: 'linear' }, _class2.getComposedData = function (_ref2) { var xAxis = _ref2.xAxis, yAxis = _ref2.yAxis, zAxis = _ref2.zAxis, item = _ref2.item, displayedData = _ref2.displayedData, onItemMouseLeave = _ref2.onItemMouseLeave, onItemMouseEnter = _ref2.onItemMouseEnter, offset = _ref2.offset, xAxisTicks = _ref2.xAxisTicks, yAxisTicks = _ref2.yAxisTicks; var tooltipType = item.props.tooltipType; var cells = findAllByType(item.props.children, Cell); var xAxisDataKey = _isNil(xAxis.dataKey) ? item.props.dataKey : xAxis.dataKey; var yAxisDataKey = _isNil(yAxis.dataKey) ? item.props.dataKey : yAxis.dataKey; var zAxisDataKey = zAxis && zAxis.dataKey; var defaultRangeZ = zAxis ? zAxis.range : ZAxis.defaultProps.range; var defaultZ = defaultRangeZ && defaultRangeZ[0]; var xBandSize = xAxis.scale.bandwidth ? xAxis.scale.bandwidth() : 0; var yBandSize = yAxis.scale.bandwidth ? yAxis.scale.bandwidth() : 0; var points = displayedData.map(function (entry, index) { var x = entry[xAxisDataKey]; var y = entry[yAxisDataKey]; var z = !_isNil(zAxisDataKey) && entry[zAxisDataKey] || '-'; var tooltipPayload = [{ name: xAxis.name || xAxis.dataKey, unit: xAxis.unit || '', value: x, payload: entry, dataKey: xAxisDataKey, type: tooltipType }, { name: yAxis.name || yAxis.dataKey, unit: yAxis.unit || '', value: y, payload: entry, dataKey: yAxisDataKey, type: tooltipType }]; if (z !== '-') { tooltipPayload.push({ name: zAxis.name || zAxis.dataKey, unit: zAxis.unit || '', value: z, payload: entry, dataKey: zAxisDataKey, type: tooltipType }); } var cx = getCateCoordinateOfLine({ axis: xAxis, ticks: xAxisTicks, bandSize: xBandSize, entry: entry, index: index, dataKey: xAxisDataKey }); var cy = getCateCoordinateOfLine({ axis: yAxis, ticks: yAxisTicks, bandSize: yBandSize, entry: entry, index: index, dataKey: yAxisDataKey }); var size = z !== '-' ? zAxis.scale(z) : defaultZ; var radius = Math.sqrt(Math.max(size, 0) / Math.PI); return _objectSpread({}, entry, { cx: cx, cy: cy, x: cx - radius, y: cy - radius, xAxis: xAxis, yAxis: yAxis, zAxis: zAxis, width: 2 * radius, height: 2 * radius, size: size, node: { x: x, y: y, z: z }, tooltipPayload: tooltipPayload, tooltipPosition: { x: cx, y: cy }, payload: entry }, cells && cells[index] && cells[index].props); }); return _objectSpread({ onMouseLeave: onItemMouseLeave, onMouseEnter: onItemMouseEnter, points: points }, offset); }, _temp)) || _class; export default Scatter;