UNPKG

lucid-ui

Version:

A UI component library from AppNexus.

348 lines (284 loc) 16.6 kB
function _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); } import _flatten from "lodash/flatten"; import _keys from "lodash/keys"; 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; } 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 _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); } function _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); }; } 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 _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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; } import React, { PureComponent } from 'react'; import PropTypes from 'react-peek/prop-types'; import { lucidClassNames } from '../../util/style-helpers'; import { extractFields, stackByFields } from '../../util/chart-helpers'; import { 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; export var Bars = /*#__PURE__*/function (_PureComponent) { _inherits(Bars, _PureComponent); var _super = _createSuper(Bars); function Bars() { var _this; _classCallCheck(this, Bars); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _super.call.apply(_super, [this].concat(args)); _defineProperty(_assertThisInitialized(_this), "defaultTooltipFormatter", function (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])); })); }); _defineProperty(_assertThisInitialized(_this), "handleMouseEnter", function (hoveringSeriesIndex) { _this.setState({ hoveringSeriesIndex: hoveringSeriesIndex }); }); _defineProperty(_assertThisInitialized(_this), "handleMouseOut", function () { _this.setState({ hoveringSeriesIndex: null }); }); _defineProperty(_assertThisInitialized(_this), "state", { hoveringSeriesIndex: null }); return _this; } _createClass(Bars, [{ key: "render", value: function render() { var _this2 = 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, function (num) { return "".concat(num); })).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, yScale.domain()[0]); // 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], //@ts-ignore yStackedMax || _max(_map(transformedData, function (x) { return _last(_last(x)); }))]); } return /*#__PURE__*/React.createElement("g", _extends({}, omitProps(passThroughs, undefined, _keys(Bars.propTypes)), { 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 // @ts-ignore ? xScale(data[seriesIndex][xField]) : // prettier-ignore // @ts-ignore innerXScale(pointsIndex) + // prettier-ignore // @ts-ignore 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 ? // prettier-ignore //@ts-ignore yScale.range()[0] - yScale(_last(series)[1]) : // prettier-ignore //@ts-ignore yScale.range()[0] - yScale(_max(_flatten(series))), width: xScale.bandwidth() // @ts-ignore , x: xScale(data[seriesIndex][xField]), y: yScale(_max(_flatten(series))), series: series, seriesIndex: seriesIndex, onMouseEnter: _this2.handleMouseEnter, onMouseOut: _this2.handleMouseOut, xFormatter: xFormatter, xField: xField, renderBody: renderTooltipBody || _this2.defaultTooltipFormatter, data: data })); })); } }]); return Bars; }(PureComponent); _defineProperty(Bars, "displayName", 'Bars'); _defineProperty(Bars, "peek", { description: "\n\t\t\t\t*For use within an `svg`*\n\n\t\t\t\tBars are typically used to represent categorical data and can be\n\t\t\t\tstacked or grouped.\n\t\t\t", categories: ['visualizations', 'chart primitives'], madeFrom: ['Bar', 'ToolTip', 'Legend'] }); _defineProperty(Bars, "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 }); _defineProperty(Bars, "defaultProps", { 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 }); export var PureToolTip = /*#__PURE__*/function (_PureComponent2) { _inherits(PureToolTip, _PureComponent2); var _super2 = _createSuper(PureToolTip); function PureToolTip() { var _this3; _classCallCheck(this, PureToolTip); for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } _this3 = _super2.call.apply(_super2, [this].concat(args)); _defineProperty(_assertThisInitialized(_this3), "handleMouseEnter", function () { _this3.props.onMouseEnter(_this3.props.seriesIndex); }); return _this3; } _createClass(PureToolTip, [{ key: "render", value: 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( //@ts-ignore data[seriesIndex][xField], data[seriesIndex])), /*#__PURE__*/React.createElement(ToolTip.Body, null, renderBody(data[seriesIndex]))); } }]); return PureToolTip; }(PureComponent); _defineProperty(PureToolTip, "displayName", 'PureToolTip'); _defineProperty(PureToolTip, "_isPrivate", true); _defineProperty(PureToolTip, "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 }); export default Bars;