Liferay.Loader.define("analytics-reports-web@1.0.39/js/components/Chart", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/loading-indicator', 'frontend-js-react-web$classnames', 'frontend-js-react-web', 'frontend-js-react-web$prop-types', 'frontend-js-react-web$react', 'frontend-js-recharts$recharts', '../context/ChartStateContext', '../context/ConnectionContext', '../context/StoreContext', '../utils/dateFormat', '../utils/numberFormat', './CustomDots', './CustomTooltip', './TimeSpanSelector'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    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);
    }

    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = Chart;

    var _loadingIndicator = _interopRequireDefault(require("@frontend-taglib-clay$clayui/loading-indicator"));

    var _classnames = _interopRequireDefault(require("frontend-js-react-web$classnames"));

    var _frontendJsReactWeb = require("frontend-js-react-web");

    var _propTypes = _interopRequireDefault(require("frontend-js-react-web$prop-types"));

    var _react = _interopRequireWildcard(require("frontend-js-react-web$react"));

    var _recharts = require("frontend-js-recharts$recharts");

    var _ChartStateContext = require("../context/ChartStateContext");

    var _ConnectionContext = _interopRequireDefault(require("../context/ConnectionContext"));

    var _StoreContext = require("../context/StoreContext");

    var _dateFormat = require("../utils/dateFormat");

    var _numberFormat = require("../utils/numberFormat");

    var _CustomDots = require("./CustomDots");

    var _CustomTooltip = _interopRequireDefault(require("./CustomTooltip"));

    var _TimeSpanSelector = _interopRequireDefault(require("./TimeSpanSelector"));

    function _getRequireWildcardCache() {
      if (typeof WeakMap !== "function") return null;var cache = new WeakMap();_getRequireWildcardCache = function _getRequireWildcardCache() {
        return cache;
      };return cache;
    }

    function _interopRequireWildcard(obj) {
      if (obj && obj.__esModule) {
        return obj;
      }if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
        return { default: obj };
      }var cache = _getRequireWildcardCache();if (cache && cache.has(obj)) {
        return cache.get(obj);
      }var newObj = {};var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;if (desc && (desc.get || desc.set)) {
            Object.defineProperty(newObj, key, desc);
          } else {
            newObj[key] = obj[key];
          }
        }
      }newObj.default = obj;if (cache) {
        cache.set(obj, newObj);
      }return newObj;
    }

    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { default: obj };
    }

    function 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;
    }

    function _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;
    }

    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 _slicedToArray(arr, i) {
      return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
    }

    function _nonIterableRest() {
      throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }

    function _iterableToArrayLimit(arr, i) {
      if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
        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;
    }

    var CHART_COLORS = {
      analyticsReportsHistoricalReads: '#50D2A0',
      analyticsReportsHistoricalViews: '#4B9BFF',
      cartesianGrid: '#E7E7ED',
      publishDate: '#2E5AAC'
    };
    var CHART_SIZES = {
      dotRadius: 4,
      fill: 'white',
      height: 220,
      lineWidth: 2,
      width: 280,
      yAxisWidth: 40
    };
    var DAY_IN_MILLISECONDS = 24 * 60 * 60 * 1000;
    var HOUR_IN_MILLISECONDS = 60 * 60 * 1000;
    var LAST_24_HOURS = 'last-24-hours';
    var METRICS_STATIC_VALUES = {
      analyticsReportsHistoricalReads: {
        color: CHART_COLORS.analyticsReportsHistoricalReads,
        iconType: 'square',
        langKey: Liferay.Language.get('reads-metric')
      },
      analyticsReportsHistoricalViews: {
        color: CHART_COLORS.analyticsReportsHistoricalViews,
        iconType: 'circle',
        langKey: Liferay.Language.get('views-metric')
      }
    };

    function keyToTranslatedLabelValue(key) {
      var _METRICS_STATIC_VALUE, _METRICS_STATIC_VALUE2;

      return (_METRICS_STATIC_VALUE = (_METRICS_STATIC_VALUE2 = METRICS_STATIC_VALUES[key]) === null || _METRICS_STATIC_VALUE2 === void 0 ? void 0 : _METRICS_STATIC_VALUE2.langKey) !== null && _METRICS_STATIC_VALUE !== void 0 ? _METRICS_STATIC_VALUE : key;
    }

    function keyToHexColor(key) {
      var _METRICS_STATIC_VALUE3, _METRICS_STATIC_VALUE4;

      return (_METRICS_STATIC_VALUE3 = (_METRICS_STATIC_VALUE4 = METRICS_STATIC_VALUES[key]) === null || _METRICS_STATIC_VALUE4 === void 0 ? void 0 : _METRICS_STATIC_VALUE4.color) !== null && _METRICS_STATIC_VALUE3 !== void 0 ? _METRICS_STATIC_VALUE3 : '#666666';
    }

    function keyToIconType(key) {
      var _METRICS_STATIC_VALUE5, _METRICS_STATIC_VALUE6;

      return (_METRICS_STATIC_VALUE5 = (_METRICS_STATIC_VALUE6 = METRICS_STATIC_VALUES[key]) === null || _METRICS_STATIC_VALUE6 === void 0 ? void 0 : _METRICS_STATIC_VALUE6.iconType) !== null && _METRICS_STATIC_VALUE5 !== void 0 ? _METRICS_STATIC_VALUE5 : 'line';
    }
    /*
     * If a number is bigger than 1000 it will transform it to kilos
     *
     * 4 => 4
     * 4000 => '4K'
     */

    function thousandsToKilosFormater(value) {
      if (value > 1000) {
        return value / 1000 + 'K';
      }

      return value;
    }

    function legendFormatterGenerator(totals, languageTag, publishedToday, validAnalyticsConnection) {
      return function (value) {
        var preformattedNumber = totals[value];
        return (/*#__PURE__*/_react.default.createElement("span", null, /*#__PURE__*/_react.default.createElement("span", {
            className: "custom-".concat(keyToIconType(value), " mr-2"),
            style: {
              backgroundColor: keyToHexColor(value)
            }
          }), /*#__PURE__*/_react.default.createElement("span", {
            className: "mr-2 text-secondary"
          }, keyToTranslatedLabelValue(value)), /*#__PURE__*/_react.default.createElement("span", {
            className: "font-weight-bold"
          }, validAnalyticsConnection && preformattedNumber !== null && !publishedToday ? (0, _numberFormat.numberFormat)(languageTag, preformattedNumber) : '-'))
        );
      };
    }

    function Chart(_ref) {
      var _ref$dataProviders = _ref.dataProviders,
          dataProviders = _ref$dataProviders === void 0 ? [] : _ref$dataProviders,
          languageTag = _ref.languageTag,
          publishDate = _ref.publishDate,
          timeSpanOptions = _ref.timeSpanOptions;

      var _useContext = (0, _react.useContext)(_ConnectionContext.default),
          validAnalyticsConnection = _useContext.validAnalyticsConnection;

      var _useContext2 = (0, _react.useContext)(_StoreContext.StoreContext),
          _useContext3 = _slicedToArray(_useContext2, 1),
          publishedToday = _useContext3[0].publishedToday;

      var chartState = (0, _ChartStateContext.useChartState)();

      var _useDateTitle = (0, _ChartStateContext.useDateTitle)(),
          firstDate = _useDateTitle.firstDate,
          lastDate = _useDateTitle.lastDate;

      var isPreviousPeriodButtonDisabled = (0, _ChartStateContext.useIsPreviousPeriodButtonDisabled)();

      var _useHistoricalWarning = (0, _StoreContext.useHistoricalWarning)(),
          _useHistoricalWarning2 = _slicedToArray(_useHistoricalWarning, 2),
          addHistoricalWarning = _useHistoricalWarning2[1];

      var addDataSetItems = (0, _ChartStateContext.useAddDataSetItems)();
      var changeTimeSpanKey = (0, _ChartStateContext.useChangeTimeSpanKey)();
      var nextTimeSpan = (0, _ChartStateContext.useNextTimeSpan)();
      var previousTimeSpan = (0, _ChartStateContext.usePreviousTimeSpan)();
      var setLoading = (0, _ChartStateContext.useSetLoading)();
      var dateFormatters = (0, _react.useMemo)(function () {
        return (0, _dateFormat.generateDateFormatters)(languageTag);
      }, [languageTag]);
      var title = dateFormatters.formatChartTitle([firstDate, lastDate]);
      var isMounted = (0, _frontendJsReactWeb.useIsMounted)();
      (0, _react.useEffect)(function () {
        var gone = false;
        setLoading();
        var timeSpanComparator = chartState.timeSpanKey === LAST_24_HOURS ? HOUR_IN_MILLISECONDS : DAY_IN_MILLISECONDS;
        var keys = ['analyticsReportsHistoricalViews', 'analyticsReportsHistoricalReads'];

        if (validAnalyticsConnection) {
          var promises = dataProviders.map(function (getter) {
            return getter({
              timeSpanKey: chartState.timeSpanKey,
              timeSpanOffset: chartState.timeSpanOffset
            });
          });
          allSettled(promises).then(function (data) {
            if (gone || !isMounted()) {
              return;
            }

            var dataSetItems = {};

            for (var i = 0; i < data.length; i++) {
              if (data[i].status === 'fulfilled') {
                dataSetItems = _objectSpread(_objectSpread({}, dataSetItems), data[i].value);
              } else {
                addHistoricalWarning();
              }
            }

            addDataSetItems({
              dataSetItems: dataSetItems,
              keys: keys,
              timeSpanComparator: timeSpanComparator
            });
          });
        } else {
          addDataSetItems({
            keys: keys,
            timeSpanComparator: timeSpanComparator
          });
        }

        return function () {
          gone = true;
        }; // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [chartState.timeSpanKey, chartState.timeSpanOffset]);
      var dataSet = chartState.dataSet;
      var histogram = dataSet.histogram,
          keyList = dataSet.keyList;
      var referenceDotPosition = (0, _react.useMemo)(function () {
        var publishDateISOString = new Date(publishDate).toISOString();
        return chartState.timeSpanKey === LAST_24_HOURS ? publishDateISOString.split(':')[0].concat(':00:00') : publishDateISOString.split('T')[0].concat('T00:00:00');
      }, [chartState.timeSpanKey, publishDate]);

      var legendFormatter = dataSet && legendFormatterGenerator(dataSet.totals, languageTag, publishedToday, validAnalyticsConnection);
      var xAxisFormatter = chartState.timeSpanKey === LAST_24_HOURS ? dateFormatters.formatNumericHour : dateFormatters.formatNumericDay;
      var lineChartWrapperClasses = (0, _classnames.default)('line-chart-wrapper', {
        'line-chart-wrapper--loading': chartState.loading
      });
      return (/*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, timeSpanOptions.length && /*#__PURE__*/_react.default.createElement("div", {
          className: "c-mb-3 c-mt-4"
        }, /*#__PURE__*/_react.default.createElement(_TimeSpanSelector.default, {
          disabledNextTimeSpan: chartState.timeSpanOffset === 0,
          disabledPreviousPeriodButton: isPreviousPeriodButtonDisabled,
          onNextTimeSpanClick: nextTimeSpan,
          onPreviousTimeSpanClick: previousTimeSpan,
          onTimeSpanChange: function handleTimeSpanChange(event) {
            var value = event.target.value;
            changeTimeSpanKey({
              key: value
            });
          },
          timeSpanKey: chartState.timeSpanKey,
          timeSpanOptions: timeSpanOptions
        })), dataSet ? /*#__PURE__*/_react.default.createElement("div", {
          className: lineChartWrapperClasses
        }, chartState.loading && /*#__PURE__*/_react.default.createElement(_loadingIndicator.default, {
          className: "chart-loading-indicator",
          small: true
        }), title && /*#__PURE__*/_react.default.createElement("h5", {
          className: "mb-3"
        }, title), /*#__PURE__*/_react.default.createElement("div", {
          className: "line-chart"
        }, /*#__PURE__*/_react.default.createElement(_recharts.LineChart, {
          data: histogram,
          height: CHART_SIZES.height,
          width: CHART_SIZES.width
        }, /*#__PURE__*/_react.default.createElement(_recharts.Legend, {
          formatter: legendFormatter,
          iconSize: 0,
          layout: "vertical",
          verticalAlign: "top",
          wrapperStyle: {
            left: 0,
            top: 0
          }
        }), /*#__PURE__*/_react.default.createElement(_recharts.CartesianGrid, {
          stroke: CHART_COLORS.cartesianGrid,
          strokeDasharray: "0 0",
          vertical: true,
          verticalPoints: [CHART_SIZES.width - CHART_SIZES.dotRadius]
        }), /*#__PURE__*/_react.default.createElement(_recharts.XAxis, {
          axisLine: {
            stroke: CHART_COLORS.cartesianGrid
          },
          dataKey: "label",
          domain: !validAnalyticsConnection || histogram.length === 0 ? [new Date(chartState.timeRange.startDate).getDate(), new Date(chartState.timeRange.endDate).getDate()] : [],
          interval: "preserveStartEnd",
          tickCount: 7,
          tickFormatter: function tickFormatter(value) {
            return validAnalyticsConnection && histogram.length !== 0 ? xAxisFormatter(value) : value;
          },
          tickLine: false,
          type: validAnalyticsConnection && histogram.length !== 0 ? 'category' : 'number'
        }), !validAnalyticsConnection || publishedToday || histogram.length === 0 ? /*#__PURE__*/_react.default.createElement(_recharts.YAxis, {
          axisLine: {
            stroke: CHART_COLORS.cartesianGrid
          },
          tickLine: false,
          ticks: [0, 50, 100],
          width: CHART_SIZES.yAxisWidth
        }) : /*#__PURE__*/_react.default.createElement(_recharts.YAxis, {
          allowDecimals: false,
          axisLine: {
            stroke: CHART_COLORS.cartesianGrid
          },
          minTickGap: 3,
          tickFormatter: thousandsToKilosFormater,
          tickLine: false,
          width: CHART_SIZES.yAxisWidth
        }), validAnalyticsConnection && !publishedToday && /*#__PURE__*/_react.default.createElement(_recharts.Tooltip, {
          animationDuration: 0,
          content: /*#__PURE__*/_react.default.createElement(_CustomTooltip.default, {
            publishDateFill: CHART_COLORS.publishDate,
            showPublishedDateLabel: isPreviousPeriodButtonDisabled
          }),
          cursor: validAnalyticsConnection && histogram.length !== 0 && !publishedToday,
          formatter: function formatter(value, name) {
            return [(0, _numberFormat.numberFormat)(languageTag, value), keyToTranslatedLabelValue(name), keyToIconType(name)];
          },
          labelFormatter: dateFormatters.formatLongDate,
          separator: ': '
        }), keyList.map(function (keyName) {
          var color = keyToHexColor(keyName);
          var shape = keyToIconType(keyName);
          return (/*#__PURE__*/_react.default.createElement(_recharts.Line, {
              activeDot: /*#__PURE__*/_react.default.createElement(_CustomDots.ActiveDot, {
                shape: shape
              }),
              dataKey: keyName,
              dot: /*#__PURE__*/_react.default.createElement(_CustomDots.Dot, {
                shape: shape
              }),
              fill: color,
              isAnimationActive: false,
              key: keyName,
              stroke: color,
              strokeWidth: CHART_SIZES.lineWidth,
              type: "monotone"
            })
          );
        }), validAnalyticsConnection && !publishedToday && /*#__PURE__*/_react.default.createElement(_recharts.ReferenceDot, {
          isFront: true,
          r: 4,
          stroke: CHART_COLORS.publishDate,
          strokeWidth: CHART_SIZES.lineWidth,
          x: referenceDotPosition,
          y: 0
        })))) : null)
      );
    }

    function allSettled(promises) {
      return Promise.all(promises.map(function (promise) {
        return promise.then(function (value) {
          return {
            status: 'fulfilled',
            value: value
          };
        }).catch(function (reason) {
          return {
            reason: reason,
            status: 'rejected'
          };
        });
      }));
    }
    //# sourceMappingURL=Chart.js.map
  }
});
//# sourceMappingURL=Chart.js.map