UNPKG

lucid-ui

Version:

A UI component library from AppNexus.

262 lines (239 loc) 11.8 kB
import _flatten from "lodash/flatten"; import _last from "lodash/last"; import _max from "lodash/max"; import _times from "lodash/times"; import _identity from "lodash/identity"; import _get from "lodash/get"; import _map from "lodash/map"; import _memoize from "lodash/memoize"; 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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } import React from 'react'; import PropTypes from 'react-peek/prop-types'; import { lucidClassNames } from '../../util/style-helpers'; import { extractFields, stackByFields } from '../../util/chart-helpers'; import { createClass, omitProps } from '../../util/component-types'; import * as d3Scale from 'd3-scale'; import * as chartConstants from '../../constants/charts'; import shallowCompare from 'react-addons-shallow-compare'; import Bar from '../Bar/Bar'; import { ToolTipDumb as ToolTip } from '../ToolTip/ToolTip'; import Legend from '../Legend/Legend'; // memoizing to maintain referential equality across renders, for performance // optimization with shallow comparison var memoizedExtractFields = _memoize(extractFields); var memoizedStackByFields = _memoize(stackByFields); var cx = lucidClassNames.bind('&-Bars'); var arrayOf = PropTypes.arrayOf, func = PropTypes.func, number = PropTypes.number, object = PropTypes.object, bool = PropTypes.bool, string = PropTypes.string; var Bars = createClass({ displayName: 'Bars', statics: {}, propTypes: { className: string, data: arrayOf(object).isRequired, legend: object, hasToolTips: bool, palette: arrayOf(string), colorMap: object, xScale: func.isRequired, xField: string, xFormatter: func, yScale: func.isRequired, yFields: arrayOf(string), yFormatter: func, yStackedMax: number, yTooltipFormatter: func, isStacked: bool, colorOffset: number, renderTooltipBody: func }, defaultTooltipFormatter: function defaultTooltipFormatter(dataPoint) { var _this$props = this.props, colorMap = _this$props.colorMap, colorOffset = _this$props.colorOffset, isStacked = _this$props.isStacked, legend = _this$props.legend, palette = _this$props.palette, yFields = _this$props.yFields, yFormatter = _this$props.yFormatter, yTooltipFormatter = _this$props.yTooltipFormatter; return /*#__PURE__*/React.createElement(Legend, { hasBorders: false, isReversed: isStacked }, _map(yFields, function (field, fieldIndex) { return /*#__PURE__*/React.createElement(Legend.Item, { key: fieldIndex, hasPoint: true, pointKind: 1, color: _get(colorMap, field, palette[(fieldIndex + colorOffset) % palette.length]) }, yTooltipFormatter(_get(legend, field, field), yFormatter(dataPoint[field], dataPoint), dataPoint[field])); })); }, handleMouseEnter: function handleMouseEnter(hoveringSeriesIndex) { this.setState({ hoveringSeriesIndex: hoveringSeriesIndex }); }, handleMouseOut: function handleMouseOut() { this.setState({ hoveringSeriesIndex: null }); }, shouldComponentUpdate: function shouldComponentUpdate() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return shallowCompare.apply(void 0, [this].concat(args)); }, getDefaultProps: function getDefaultProps() { return { hasToolTips: true, xField: 'x', xFormatter: _identity, yFields: ['y'], yFormatter: _identity, yTooltipFormatter: function yTooltipFormatter(yField, yValueFormatted) { return "".concat(yField, ": ").concat(yValueFormatted); }, renderTooltipBody: null, isStacked: false, colorOffset: 0, palette: chartConstants.PALETTE_7 }; }, getInitialState: function getInitialState() { return { hoveringSeriesIndex: null }; }, render: function render() { var _this = this; var _this$props2 = this.props, className = _this$props2.className, data = _this$props2.data, hasToolTips = _this$props2.hasToolTips, palette = _this$props2.palette, colorMap = _this$props2.colorMap, colorOffset = _this$props2.colorOffset, xScale = _this$props2.xScale, xField = _this$props2.xField, xFormatter = _this$props2.xFormatter, yScaleOriginal = _this$props2.yScale, yFields = _this$props2.yFields, yStackedMax = _this$props2.yStackedMax, renderTooltipBody = _this$props2.renderTooltipBody, isStacked = _this$props2.isStacked, passThroughs = _objectWithoutProperties(_this$props2, ["className", "data", "hasToolTips", "palette", "colorMap", "colorOffset", "xScale", "xField", "xFormatter", "yScale", "yFields", "yStackedMax", "renderTooltipBody", "isStacked"]); var hoveringSeriesIndex = this.state.hoveringSeriesIndex; // This scale is used for grouped bars var innerXScale = d3Scale.scaleBand().domain(_times(yFields.length)).range([0, xScale.bandwidth()]).round(true); // Copy the original so we can mutate it var yScale = yScaleOriginal.copy(); // If we are stacked, we need to calculate a new domain based on the sum of // the various series' y data. One row per series. var transformedData = isStacked ? memoizedStackByFields(data, yFields) : memoizedExtractFields(data, yFields); // If we are stacked, we need to calculate a new domain based on the sum of // the various group's y data if (isStacked) { yScale.domain([yScale.domain()[0], yStackedMax || _max(_map(transformedData, function (x) { return _last(_last(x)); }))]); } return /*#__PURE__*/React.createElement("g", _extends({}, omitProps(passThroughs, Bars), { className: cx(className, '&') }), _map(transformedData, function (series, seriesIndex) { return /*#__PURE__*/React.createElement("g", { key: seriesIndex }, _map(series, function (_ref, pointsIndex) { var _ref2 = _slicedToArray(_ref, 2), start = _ref2[0], end = _ref2[1]; return /*#__PURE__*/React.createElement(Bar, { key: pointsIndex, x: isStacked ? xScale(data[seriesIndex][xField]) : innerXScale(pointsIndex) + xScale(data[seriesIndex][xField]), y: yScale(end), height: yScale(start) - yScale(end), width: isStacked ? xScale.bandwidth() : innerXScale.bandwidth(), color: _get(colorMap, yFields[pointsIndex], palette[(pointsIndex + colorOffset) % palette.length]) }); }), /*#__PURE__*/React.createElement(PureToolTip, { isExpanded: hasToolTips && hoveringSeriesIndex === seriesIndex, height: isStacked ? yScale.range()[0] - yScale(_last(series)[1]) : yScale.range()[0] - yScale(_max(_flatten(series))), width: xScale.bandwidth(), x: xScale(data[seriesIndex][xField]), y: yScale(_max(_flatten(series))), series: series, seriesIndex: seriesIndex, onMouseEnter: _this.handleMouseEnter, onMouseOut: _this.handleMouseOut, xFormatter: xFormatter, xField: xField, renderBody: renderTooltipBody || _this.defaultTooltipFormatter, data: data })); })); } }); export var PureToolTip = createClass({ _isPrivate: true, propTypes: { data: arrayOf(object), height: number, isExpanded: bool, onMouseEnter: func, onMouseOut: func, renderBody: func, seriesIndex: number, width: number, x: number, xField: string, xFormatter: func, y: number }, shouldComponentUpdate: function shouldComponentUpdate() { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return shallowCompare.apply(void 0, [this].concat(args)); }, handleMouseEnter: function handleMouseEnter() { this.props.onMouseEnter(this.props.seriesIndex); }, render: function render() { var _this$props3 = this.props, isExpanded = _this$props3.isExpanded, height = _this$props3.height, width = _this$props3.width, x = _this$props3.x, y = _this$props3.y, seriesIndex = _this$props3.seriesIndex, onMouseOut = _this$props3.onMouseOut, renderBody = _this$props3.renderBody, data = _this$props3.data, xFormatter = _this$props3.xFormatter, xField = _this$props3.xField; return /*#__PURE__*/React.createElement(ToolTip, { isExpanded: isExpanded, flyOutMaxWidth: "none", isLight: true }, /*#__PURE__*/React.createElement(ToolTip.Target, { elementType: "g" }, /*#__PURE__*/React.createElement("rect", { className: cx('&-tooltip-hover-zone'), height: height, width: width, x: x, y: y, onMouseEnter: this.handleMouseEnter, onMouseOut: onMouseOut })), /*#__PURE__*/React.createElement(ToolTip.Title, null, xFormatter(data[seriesIndex][xField], data[seriesIndex])), /*#__PURE__*/React.createElement(ToolTip.Body, null, renderBody(data[seriesIndex]))); } }); export default Bars;