UNPKG

recharts

Version:
716 lines (597 loc) 26.8 kB
'use strict'; var _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; }; var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _class, _temp; /** * @fileOverview Composed Chart */ Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var _Surface = require('../container/Surface'); var _Surface2 = _interopRequireDefault(_Surface); var _Tooltip = require('../component/Tooltip'); var _Tooltip2 = _interopRequireDefault(_Tooltip); var _CartesianChart2 = require('./CartesianChart'); var _CartesianChart3 = _interopRequireDefault(_CartesianChart2); var _Line = require('../cartesian/Line'); var _Line2 = _interopRequireDefault(_Line); var _Bar = require('../cartesian/Bar'); var _Bar2 = _interopRequireDefault(_Bar); var _Area = require('../cartesian/Area'); var _Area2 = _interopRequireDefault(_Area); var _Curve = require('../shape/Curve'); var _Curve2 = _interopRequireDefault(_Curve); var _Dot = require('../shape/Dot'); var _Dot2 = _interopRequireDefault(_Dot); var _Rectangle = require('../shape/Rectangle'); var _Rectangle2 = _interopRequireDefault(_Rectangle); var _ReactUtils = require('../util/ReactUtils'); var _ReactUtils2 = _interopRequireDefault(_ReactUtils); var _LodashUtils = require('../util/LodashUtils'); var _LodashUtils2 = _interopRequireDefault(_LodashUtils); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var ComposedChart = (_temp = _class = function (_CartesianChart) { _inherits(ComposedChart, _CartesianChart); function ComposedChart() { _classCallCheck(this, ComposedChart); return _possibleConstructorReturn(this, Object.getPrototypeOf(ComposedChart).apply(this, arguments)); } _createClass(ComposedChart, [{ key: 'getLineComposedData', /** * Compose the data of each line * @param {Object} xAxis The configuration of x-axis * @param {Object} yAxis The configuration of y-axis * @param {String} dataKey The unique key of a group * @return {Array} Composed data */ value: function getLineComposedData(xAxis, yAxis, dataKey) { var _props = this.props; var data = _props.data; var layout = _props.layout; var bandSize = this.getBandSize(layout === 'horizontal' ? xAxis.scale : yAxis.scale); var xTicks = this.getAxisTicks(xAxis); var yTicks = this.getAxisTicks(yAxis); return data.map(function (entry, index) { return { x: layout === 'horizontal' ? xTicks[index].coord + bandSize / 2 : xAxis.scale(entry[dataKey]), y: layout === 'horizontal' ? yAxis.scale(entry[dataKey]) : yTicks[index].coord + bandSize / 2, value: entry[dataKey] }; }); } /** * Compose the data of each area * @param {Object} xAxis The configuration of x-axis * @param {Object} yAxis The configuration of y-axis * @param {String} dataKey The unique key of a group * @param {Array} stackedData The stacked data of a area item * @return {Array} Composed data */ }, { key: 'getAreaComposedData', value: function getAreaComposedData(xAxis, yAxis, dataKey, stackedData) { var _props2 = this.props; var data = _props2.data; var layout = _props2.layout; var xTicks = this.getAxisTicks(xAxis); var yTicks = this.getAxisTicks(yAxis); var bandSize = this.getBandSize(layout === 'horizontal' ? xAxis.scale : yAxis.scale); var hasStack = stackedData && stackedData.length; var points = data.map(function (entry, index) { var value = hasStack ? stackedData[index] : [0, entry[dataKey]]; return { x: layout === 'horizontal' ? xTicks[index].coord + bandSize / 2 : xAxis.scale(value[1]), y: layout === 'horizontal' ? yAxis.scale(value[1]) : yTicks[index].coord + bandSize / 2, value: entry[dataKey] }; }); var range = undefined; var baseLine = undefined; var baseLineType = undefined; if (hasStack) { baseLineType = 'curve'; baseLine = stackedData.map(function (entry, index) { return { x: layout === 'horizontal' ? xTicks[index].coord + bandSize / 2 : xAxis.scale(entry[0]), y: layout === 'horizontal' ? yAxis.scale(entry[0]) : yTicks[index].coord + bandSize / 2 }; }); } else if (layout === 'horizontal') { baseLineType = layout; range = yAxis.scale.range(); baseLine = xAxis.orientation === 'top' ? Math.min(range[0], range[1]) : Math.max(range[0], range[1]); } else { baseLineType = layout; range = xAxis.scale.range(); baseLine = yAxis.orientation === 'left' ? Math.min(range[0], range[1]) : Math.max(range[0], range[1]); } return { points: points, baseLine: baseLine, baseLineType: baseLineType }; } /** * Compose the data of each bar * @param {Array} barPosition The offset and size of each bar * @param {Object} xAxis The configuration of x-axis * @param {Object} yAxis The configuration of y-axis * @param {Object} offset The offset of main part in the svg element * @param {String} dataKey The unique key of a group * @param {Array} stackedData The stacked data of a bar item * @return {Array} Composed data */ }, { key: 'getBarComposedData', value: function getBarComposedData(barPosition, xAxis, yAxis, offset, dataKey, stackedData) { var layout = this.props.layout; var _state = this.state; var dataStartIndex = _state.dataStartIndex; var dataEndIndex = _state.dataEndIndex; var data = this.props.data.slice(dataStartIndex, dataEndIndex + 1); var pos = barPosition[dataKey]; var xTicks = this.getAxisTicks(xAxis); var yTicks = this.getAxisTicks(yAxis); var baseValue = this.getBaseValue(xAxis, yAxis); var hasStack = stackedData && stackedData.length; return data.map(function (entry, index) { var value = stackedData ? stackedData[dataStartIndex + index] : [baseValue, entry[dataKey]]; var x = undefined; var y = undefined; var width = undefined; var height = undefined; if (layout === 'horizontal') { x = xTicks[index].coord + pos.offset; y = yAxis.scale(xAxis.orientation === 'top' ? value[0] : value[1]); width = pos.size; height = xAxis.orientation === 'top' ? yAxis.scale(value[1]) - yAxis.scale(value[0]) : yAxis.scale(value[0]) - yAxis.scale(value[1]); } else { x = xAxis.scale(yAxis.orientation === 'left' ? value[0] : value[1]); y = yTicks[index].coord + pos.offset; width = yAxis.orientation === 'left' ? xAxis.scale(value[1]) - xAxis.scale(value[0]) : xAxis.scale(value[0]) - xAxis.scale(value[1]); height = pos.size; } return _extends({}, entry, { x: x, y: y, width: width, height: height, value: value[1] }); }); } }, { key: 'getBaseValue', value: function getBaseValue(xAxis, yAxis) { var layout = this.props.layout; var scale = layout === 'horizontal' ? yAxis.scale : xAxis.scale; var domain = scale.domain(); return Math.max(Math.min(domain[0], domain[1]), 0); } /** * Calculate the size of each bar and the gap between two bars * @param {Number} bandSize The size of each category * @param {sizeList} sizeList The size of all groups * @return {Number} The size of each bar and the gap between two bars */ }, { key: 'getBarPosition', value: function getBarPosition(bandSize, sizeList) { var _props3 = this.props; var barGap = _props3.barGap; var barCategoryGap = _props3.barCategoryGap; var len = sizeList.length; var result = undefined; // whether or not is barSize setted by user if (sizeList[0].barSize === +sizeList[0].barSize) { (function () { var sum = sizeList.reduce(function (res, entry) { return res + entry.barSize; }, 0); sum += (len - 1) * barGap; var offset = (bandSize - sum) / 2 >> 0; var prev = { offset: offset - barGap, size: 0 }; result = sizeList.reduce(function (res, entry) { res[entry.dataKey] = { offset: prev.offset + prev.size + barGap, size: entry.barSize }; prev = res[entry.dataKey]; if (entry.stackList && entry.stackList.length) { entry.stackList.forEach(function (key) { res[key] = res[entry.dataKey]; }); } return res; }, {}); })(); } else { (function () { var offset = _LodashUtils2.default.getPercentValue(barCategoryGap, bandSize); var size = (bandSize - 2 * offset - (len - 1) * barGap) / len >> 0; result = sizeList.reduce(function (res, entry, i) { res[entry.dataKey] = { offset: offset + (size + barGap) * i, size: size }; if (entry.stackList && entry.stackList.length) { entry.stackList.forEach(function (key) { res[key] = res[entry.dataKey]; }); } return res; }, {}); })(); } return result; } /** * Calculate the size of all groups * @param {Object} stackGroups The items grouped by axisId and stackId * @return {Object} The size of all groups */ }, { key: 'getSizeList', value: function getSizeList(stackGroups) { var _props4 = this.props; var layout = _props4.layout; var barSize = _props4.barSize; return Object.keys(stackGroups).reduce(function (result, axisId) { var sgs = stackGroups[axisId].stackGroups; result[axisId] = Object.keys(sgs).reduce(function (res, stackId) { var items = sgs[stackId].items; var firstItem = items[0]; if (firstItem.type.displayName === 'Bar') { var dataKey = firstItem.props.dataKey; res.push({ dataKey: dataKey, stackList: items.slice(1).map(function (item) { return item.props.dataKey; }), barSize: firstItem.props.barSize || barSize }); } return res; }, []); return result; }, {}); } /** * Calculate the size between two category * @param {Function} scale Scale function * @return {Number} Size */ }, { key: 'getBandSize', value: function getBandSize(scale) { if (scale && scale.bandwidth) { return scale.bandwidth(); } return 0; } /** * Handler of mouse entering bar chart * @param {String} key The unique key of a group of data * @return {Object} null */ }, { key: 'handleBarMouseEnter', value: function handleBarMouseEnter(key) { this.setState({ activeBarKey: key }); } /** * Handler of mouse leaving area chart * @return {Object} null */ }, { key: 'handleBarMouseLeave', value: function handleBarMouseLeave() { this.setState({ activeBarKey: null }); } /** * Handler of mouse entering line chart * @param {String} key The unique key of a group of data * @return {Object} no return */ }, { key: 'handleLineMouseEnter', value: function handleLineMouseEnter(key) { this.setState({ activeLineKey: key }); } /** * Handler of mouse leaving line chart * @return {Object} no return */ }, { key: 'handleLineMouseLeave', value: function handleLineMouseLeave() { this.setState({ activeLineKey: null }); } /** * Handler of mouse entering area chart * @param {String} key The unique key of a group of data * @return {Object} null */ }, { key: 'handleAreaMouseEnter', value: function handleAreaMouseEnter(key) { this.setState({ activeAreaKey: key }); } /** * Handler of mouse leaving area chart * @return {Object} null */ }, { key: 'handleAreaMouseLeave', value: function handleAreaMouseLeave() { this.setState({ activeAreaKey: null }); } }, { key: 'renderCursor', value: function renderCursor(xAxisMap, yAxisMap, offset) { var children = this.props.children; var tooltipItem = _ReactUtils2.default.findChildByType(children, _Tooltip2.default); if (!tooltipItem || !tooltipItem.props.cursor || !this.state.isTooltipActive) { return null; } var layout = this.props.layout; var activeTooltipIndex = this.state.activeTooltipIndex; var axisMap = layout === 'horizontal' ? xAxisMap : yAxisMap; var ids = Object.keys(axisMap); var axis = axisMap[ids[0]]; var bandSize = this.getBandSize(axis.scale); var ticks = this.getAxisTicks(axis); var start = ticks[activeTooltipIndex].coord; var cursorProps = _extends({ fill: '#f1f1f1' }, _ReactUtils2.default.getPresentationAttributes(tooltipItem.props.cursor), { x: layout === 'horizontal' ? start : offset.left + 0.5, y: layout === 'horizontal' ? offset.top + 0.5 : start, width: layout === 'horizontal' ? bandSize : offset.width - 1, height: layout === 'horizontal' ? offset.height - 1 : bandSize }); return _react2.default.isValidElement(tooltipItem.props.cursor) ? _react2.default.cloneElement(tooltipItem.props.cursor, cursorProps) : _react2.default.createElement(_Rectangle2.default, cursorProps); } /** * Draw the lines * @param {Array} items All the instance of Line * @param {Object} xAxisMap The configuration of all x-axes * @param {Object} yAxisMap The configuration of all y-axes * @param {Object} offset The offset of main part in the svg element * @return {ReactComponent} All the instances of Line */ }, { key: 'renderLineItems', value: function renderLineItems(items, xAxisMap, yAxisMap, offset) { var _this2 = this; var children = this.props.children; var _state2 = this.state; var activeLineKey = _state2.activeLineKey; var isTooltipActive = _state2.isTooltipActive; var activeTooltipIndex = _state2.activeTooltipIndex; var tooltipItem = _ReactUtils2.default.findChildByType(children, _Tooltip2.default); var hasDot = tooltipItem && isTooltipActive; var dotItems = []; var lineItems = items.map(function (child, i) { var _child$props = child.props; var xAxisId = _child$props.xAxisId; var yAxisId = _child$props.yAxisId; var dataKey = _child$props.dataKey; var strokeWidth = _child$props.strokeWidth; var stroke = _child$props.stroke; var points = _this2.getLineComposedData(xAxisMap[xAxisId], yAxisMap[yAxisId], dataKey); var activePoint = points[activeTooltipIndex]; var pointStyle = { fill: stroke, strokeWidth: 2, stroke: '#fff' }; var finalStrokeWidth = strokeWidth === +strokeWidth ? strokeWidth : 1; finalStrokeWidth = activeLineKey === dataKey ? finalStrokeWidth + 2 : finalStrokeWidth; if (hasDot && activePoint) { dotItems.push(_react2.default.createElement(_Dot2.default, _extends({ key: 'area-dot-' + i, cx: activePoint.x, cy: activePoint.y, r: 4 }, pointStyle))); } return _react2.default.cloneElement(child, _extends({ key: 'line-' + i }, offset, { strokeWidth: finalStrokeWidth, onMouseLeave: _this2.handleLineMouseLeave.bind(_this2), onMouseEnter: _this2.handleLineMouseEnter.bind(_this2, dataKey), points: points })); }, this); return _react2.default.createElement( 'g', { key: 'recharts-line-wrapper' }, _react2.default.createElement( 'g', { key: 'recharts-line' }, lineItems ), _react2.default.createElement( 'g', { key: 'recharts-line-dot' }, dotItems ) ); } /** * Draw the areas * @param {Array} items React elements of Area * @param {Object} xAxisMap The configuration of all x-axis * @param {Object} yAxisMap The configuration of all y-axis * @param {Object} offset The offset of main part in the svg element * @param {Object} stackGroups The items grouped by axisId and stackId * @return {ReactComponent} The instances of Area */ }, { key: 'renderAreaItems', value: function renderAreaItems(items, xAxisMap, yAxisMap, offset, stackGroups) { var _this3 = this; var _props5 = this.props; var children = _props5.children; var layout = _props5.layout; var _state3 = this.state; var activeAreaKey = _state3.activeAreaKey; var isTooltipActive = _state3.isTooltipActive; var activeTooltipIndex = _state3.activeTooltipIndex; var tooltipItem = _ReactUtils2.default.findChildByType(children, _Tooltip2.default); var hasDot = tooltipItem && isTooltipActive; var dotItems = []; var areaItems = items.reduce(function (result, child, i) { var _child$props2 = child.props; var xAxisId = _child$props2.xAxisId; var yAxisId = _child$props2.yAxisId; var dataKey = _child$props2.dataKey; var fillOpacity = _child$props2.fillOpacity; var fill = _child$props2.fill; var axisId = layout === 'horizontal' ? xAxisId : yAxisId; var stackedData = stackGroups && stackGroups[axisId] && stackGroups[axisId].hasStack && _this3.getStackedDataOfItem(child, stackGroups[axisId].stackGroups); var composeData = _this3.getAreaComposedData(xAxisMap[xAxisId], yAxisMap[yAxisId], dataKey, stackedData); var activePoint = composeData.points && composeData.points[activeTooltipIndex]; var pointStyle = { fill: fill, strokeWidth: 2, stroke: '#fff' }; if (hasDot && activePoint) { dotItems.push(_react2.default.createElement(_Dot2.default, _extends({ key: 'area-dot-' + i, cx: activePoint.x, cy: activePoint.y, r: 4 }, pointStyle))); } var finalFillOpacity = fillOpacity === +fillOpacity ? fillOpacity : _Area2.default.defaultProps.fillOpacity; finalFillOpacity = activeAreaKey === dataKey ? Math.min(finalFillOpacity * 1.2, 1) : finalFillOpacity; var area = _react2.default.cloneElement(child, _extends({ key: 'area-' + i }, offset, composeData, { fillOpacity: finalFillOpacity, onMouseLeave: _this3.handleAreaMouseLeave.bind(_this3), onMouseEnter: _this3.handleAreaMouseEnter.bind(_this3, dataKey) })); return activeAreaKey === dataKey ? [].concat(_toConsumableArray(result), [area]) : [area].concat(_toConsumableArray(result)); }, []); return _react2.default.createElement( 'g', { key: 'recharts-area-wrapper' }, _react2.default.createElement( 'g', { key: 'recharts-area' }, areaItems ), _react2.default.createElement( 'g', { key: 'recharts-area-dot' }, dotItems ) ); } /** * Draw the bars * @param {Array} items All the instance of Bar * @param {Object} xAxisMap The configuration of all x-axis * @param {Object} yAxisMap The configuration of all y-axis * @param {Object} offset The offset of main part in the svg element * @param {Object} stackGroups The items grouped by axisId and stackId * @return {ReactComponent} All the instances of Bar */ }, { key: 'renderBarItems', value: function renderBarItems(items, xAxisMap, yAxisMap, offset, stackGroups) { var _this4 = this; if (!items || !items.length) { return null; } var layout = this.props.layout; var sizeList = this.getSizeList(stackGroups); var barPositionMap = {}; return items.map(function (child, i) { var _child$props3 = child.props; var xAxisId = _child$props3.xAxisId; var yAxisId = _child$props3.yAxisId; var dataKey = _child$props3.dataKey; var axisId = layout === 'horizontal' ? xAxisId : yAxisId; var bandSize = _this4.getBandSize(layout === 'horizontal' ? xAxisMap[xAxisId].scale : yAxisMap[yAxisId].scale); var barPosition = barPositionMap[axisId] || _this4.getBarPosition(bandSize, sizeList[axisId]); var stackedData = stackGroups && stackGroups[axisId] && stackGroups[axisId].hasStack && _this4.getStackedDataOfItem(child, stackGroups[axisId].stackGroups); return _react2.default.cloneElement(child, { key: 'bar-' + i, layout: layout, onMouseLeave: _this4.handleBarMouseLeave.bind(_this4), onMouseEnter: _this4.handleBarMouseEnter.bind(_this4, dataKey), data: _this4.getBarComposedData(barPosition, xAxisMap[xAxisId], yAxisMap[yAxisId], offset, dataKey, stackedData) }); }, this); } }, { key: 'render', value: function render() { if (!_ReactUtils2.default.validateWidthHeight(this)) { return null; } var _props6 = this.props; var style = _props6.style; var children = _props6.children; var className = _props6.className; var layout = _props6.layout; var width = _props6.width; var height = _props6.height; var numberAxisName = layout === 'horizontal' ? 'yAxis' : 'xAxis'; var lineItems = _ReactUtils2.default.findAllByType(children, _Line2.default); var barItems = _ReactUtils2.default.findAllByType(children, _Bar2.default); var areaItems = _ReactUtils2.default.findAllByType(children, _Area2.default); var items = [].concat(_toConsumableArray(lineItems), _toConsumableArray(barItems), _toConsumableArray(areaItems)); var stackGroups = this.getStackGroupsByAxisId(items, numberAxisName + 'Id'); var xAxisMap = this.getAxisMap('xAxis', items, numberAxisName === 'xAxis' && stackGroups); var yAxisMap = this.getAxisMap('yAxis', items, numberAxisName === 'yAxis' && stackGroups); var offset = this.getOffset(xAxisMap, yAxisMap); xAxisMap = this.getFormatAxisMap(xAxisMap, offset, 'xAxis'); yAxisMap = this.getFormatAxisMap(yAxisMap, offset, 'yAxis'); return _react2.default.createElement( 'div', { className: (0, _classnames2.default)('recharts-wrapper', className), style: _extends({ position: 'relative', cursor: 'default' }, style), onMouseEnter: this.handleMouseEnter.bind(this, offset, xAxisMap, yAxisMap), onMouseMove: this.handleMouseMove.bind(this, offset, xAxisMap, yAxisMap), onMouseLeave: this.handleMouseLeave.bind(this) }, _react2.default.createElement( _Surface2.default, { width: width, height: height }, this.renderGrid(xAxisMap, yAxisMap, offset), this.renderReferenceLines(xAxisMap, yAxisMap, offset), this.renderXAxis(xAxisMap), this.renderYAxis(yAxisMap), this.renderCursor(xAxisMap, yAxisMap, offset), this.renderAreaItems(areaItems, xAxisMap, yAxisMap, offset, stackGroups), this.renderBarItems(barItems, xAxisMap, yAxisMap, offset, stackGroups), this.renderLineItems(lineItems, xAxisMap, yAxisMap, offset) ), this.renderLegend(items), this.renderTooltip(items, offset) ); } }]); return ComposedChart; }(_CartesianChart3.default), _class.displayName = 'ComposedChart', _class.propTypes = { width: _react.PropTypes.number, height: _react.PropTypes.number, data: _react.PropTypes.arrayOf(_react.PropTypes.object), layout: _react.PropTypes.oneOf(['horizontal', 'vertical']), margin: _react.PropTypes.shape({ top: _react.PropTypes.number, right: _react.PropTypes.number, bottom: _react.PropTypes.number, left: _react.PropTypes.number }), className: _react.PropTypes.string, style: _react.PropTypes.object, children: _react.PropTypes.oneOfType([_react.PropTypes.arrayOf(_react.PropTypes.node), _react.PropTypes.node]) }, _class.defaultProps = { style: {}, barCategoryGap: '10%', barGap: 4, layout: 'horizontal', margin: { top: 5, right: 5, bottom: 5, left: 5 } }, _temp); exports.default = ComposedChart;