"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.EuiBreadcrumbs = void 0;

var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _react = _interopRequireWildcard(require("react"));

var _classnames = _interopRequireDefault(require("classnames"));

var _i18n = require("../i18n");

var _inner_text = require("../inner_text");

var _link = require("../link");

var _popover = require("../popover");

var _icon = require("../icon");

var _services = require("../../services");

var _breakpoint = require("../../services/breakpoint");

/*
 * SPDX-License-Identifier: Apache-2.0
 *
 * The OpenSearch Contributors require contributions made to
 * this file be licensed under the Apache-2.0 license or a
 * compatible open source license.
 *
 * Modifications Copyright OpenSearch Contributors. See
 * GitHub history for details.
 */

/*
 * Licensed to Elasticsearch B.V. under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch B.V. licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var responsiveDefault = {
  xs: 1,
  s: 2,
  m: 4
};

var limitBreadcrumbs = function limitBreadcrumbs(breadcrumbs, max, allBreadcrumbs) {
  var breadcrumbsAtStart = [];
  var breadcrumbsAtEnd = [];
  var limit = Math.min(max, breadcrumbs.length);
  var start = Math.floor(limit / 2);
  var overflowBreadcrumbs = allBreadcrumbs.slice(start, start + breadcrumbs.length - limit);

  for (var i = 0; i < limit; i++) {
    // We'll alternate with displaying breadcrumbs at the end and at the start, but be biased
    // towards breadcrumbs the end so that if max is an odd number, we'll have one more
    // breadcrumb visible at the end than at the beginning.
    var isEven = i % 2 === 0; // We're picking breadcrumbs from the front AND the back, so we treat each iteration as a
    // half-iteration.

    var normalizedIndex = Math.floor(i * 0.5);
    var indexOfBreadcrumb = isEven ? breadcrumbs.length - 1 - normalizedIndex : normalizedIndex;
    var breadcrumb = breadcrumbs[indexOfBreadcrumb];

    if (isEven) {
      breadcrumbsAtEnd.unshift(breadcrumb);
    } else {
      breadcrumbsAtStart.push(breadcrumb);
    }
  }

  var EuiBreadcrumbCollapsed = function EuiBreadcrumbCollapsed() {
    var _useState = (0, _react.useState)(false),
        _useState2 = (0, _slicedToArray2.default)(_useState, 2),
        isPopoverOpen = _useState2[0],
        setIsPopoverOpen = _useState2[1];

    var ellipsisButton = /*#__PURE__*/_react.default.createElement(_i18n.EuiI18n, {
      token: "euiBreadcrumbs.collapsedBadge.ariaLabel",
      default: "Show collapsed breadcrumbs"
    }, function (ariaLabel) {
      return /*#__PURE__*/_react.default.createElement(_link.EuiLink, {
        className: "euiBreadcrumb__collapsedLink",
        color: "subdued",
        "aria-label": ariaLabel,
        title: ariaLabel,
        onClick: function onClick() {
          return setIsPopoverOpen(!isPopoverOpen);
        }
      }, "\u2026 ", /*#__PURE__*/_react.default.createElement(_icon.EuiIcon, {
        type: "arrowDown",
        size: "s"
      }));
    });

    return /*#__PURE__*/_react.default.createElement(_react.Fragment, null, /*#__PURE__*/_react.default.createElement(_popover.EuiPopover, {
      className: "euiBreadcrumb euiBreadcrumb--collapsed",
      button: ellipsisButton,
      isOpen: isPopoverOpen,
      closePopover: function closePopover() {
        return setIsPopoverOpen(false);
      }
    }, /*#__PURE__*/_react.default.createElement(EuiBreadcrumbs, {
      className: "euiBreadcrumbs__inPopover",
      breadcrumbs: overflowBreadcrumbs,
      responsive: false,
      truncate: false,
      max: 0
    })), /*#__PURE__*/_react.default.createElement(EuiBreadcrumbSeparator, null));
  };

  if (max < breadcrumbs.length) {
    breadcrumbsAtStart.push( /*#__PURE__*/_react.default.createElement(EuiBreadcrumbCollapsed, {
      key: "collapsed"
    }));
  }

  return [].concat(breadcrumbsAtStart, breadcrumbsAtEnd);
};

var EuiBreadcrumbSeparator = function EuiBreadcrumbSeparator() {
  return /*#__PURE__*/_react.default.createElement("div", {
    className: "euiBreadcrumbSeparator"
  });
};

var EuiBreadcrumbs = function EuiBreadcrumbs(_ref) {
  var breadcrumbs = _ref.breadcrumbs,
      className = _ref.className,
      _ref$responsive = _ref.responsive,
      responsive = _ref$responsive === void 0 ? responsiveDefault : _ref$responsive,
      _ref$truncate = _ref.truncate,
      truncate = _ref$truncate === void 0 ? true : _ref$truncate,
      _ref$max = _ref.max,
      max = _ref$max === void 0 ? 5 : _ref$max,
      rest = (0, _objectWithoutProperties2.default)(_ref, ["breadcrumbs", "className", "responsive", "truncate", "max"]);

  var _useState3 = (0, _react.useState)((0, _breakpoint.getBreakpoint)(typeof window === 'undefined' ? -Infinity : window.innerWidth)),
      _useState4 = (0, _slicedToArray2.default)(_useState3, 2),
      currentBreakpoint = _useState4[0],
      setCurrentBreakpoint = _useState4[1];

  var functionToCallOnWindowResize = (0, _services.throttle)(function () {
    var newBreakpoint = (0, _breakpoint.getBreakpoint)(window.innerWidth);

    if (newBreakpoint !== currentBreakpoint) {
      setCurrentBreakpoint(newBreakpoint);
    } // reacts every 50ms to resize changes and always gets the final update

  }, 50); // Add window resize handlers

  (0, _react.useEffect)(function () {
    window.addEventListener('resize', functionToCallOnWindowResize);
    return function () {
      window.removeEventListener('resize', functionToCallOnWindowResize);
    };
  }, [responsive, functionToCallOnWindowResize]);
  var breadcrumbElements = breadcrumbs.map(function (breadcrumb, index) {
    var text = breadcrumb.text,
        href = breadcrumb.href,
        onClick = breadcrumb.onClick,
        truncate = breadcrumb.truncate,
        breadcrumbClassName = breadcrumb.className,
        breadcrumbRest = (0, _objectWithoutProperties2.default)(breadcrumb, ["text", "href", "onClick", "truncate", "className"]);
    var isLastBreadcrumb = index === breadcrumbs.length - 1;
    var breadcrumbClasses = (0, _classnames.default)('euiBreadcrumb', breadcrumbClassName, {
      'euiBreadcrumb--last': isLastBreadcrumb,
      'euiBreadcrumb--truncate': truncate
    });
    var link;

    if (!href && !onClick) {
      link = /*#__PURE__*/_react.default.createElement(_inner_text.EuiInnerText, null, function (ref, innerText) {
        return /*#__PURE__*/_react.default.createElement("span", (0, _extends2.default)({
          ref: ref,
          className: breadcrumbClasses,
          title: innerText,
          "aria-current": isLastBreadcrumb ? 'page' : 'false'
        }, breadcrumbRest), text);
      });
    } else {
      link = /*#__PURE__*/_react.default.createElement(_inner_text.EuiInnerText, null, function (ref, innerText) {
        return /*#__PURE__*/_react.default.createElement(_link.EuiLink, (0, _extends2.default)({
          ref: ref,
          color: isLastBreadcrumb ? 'text' : 'subdued',
          onClick: onClick,
          href: href,
          className: breadcrumbClasses,
          title: innerText
        }, breadcrumbRest), text);
      });
    }

    var separator;

    if (!isLastBreadcrumb) {
      separator = /*#__PURE__*/_react.default.createElement(EuiBreadcrumbSeparator, null);
    }

    return /*#__PURE__*/_react.default.createElement(_react.Fragment, {
      key: index
    }, link, separator);
  }); // Use the default object if they simply passed `true` for responsive

  var responsiveObject = (0, _typeof2.default)(responsive) === 'object' ? responsive : responsiveDefault; // The max property collapses any breadcrumbs past the max quantity.
  // This is the same behavior we want for responsiveness.
  // So calculate the max value based on the combination of `max` and `responsive`

  var calculatedMax = max; // Set the calculated max to the number associated with the currentBreakpoint key if it exists

  if (responsive && responsiveObject[currentBreakpoint]) {
    calculatedMax = responsiveObject[currentBreakpoint];
  } // Final check is to make sure max is used over a larger breakpoint value


  if (max && calculatedMax) {
    calculatedMax = max < calculatedMax ? max : calculatedMax;
  }

  var limitedBreadcrumbs = calculatedMax ? limitBreadcrumbs(breadcrumbElements, calculatedMax, breadcrumbs) : breadcrumbElements;
  var classes = (0, _classnames.default)('euiBreadcrumbs', className, {
    'euiBreadcrumbs--truncate': truncate
  });
  return /*#__PURE__*/_react.default.createElement("nav", (0, _extends2.default)({
    "aria-label": "breadcrumb",
    className: classes
  }, rest), limitedBreadcrumbs);
};

exports.EuiBreadcrumbs = EuiBreadcrumbs;
EuiBreadcrumbs.propTypes = {
  className: _propTypes.default.string,
  "aria-label": _propTypes.default.string,
  "data-test-subj": _propTypes.default.string,

  /**
     * Hides extra (above the max) breadcrumbs under a collapsed item as the window gets smaller.
     * Pass a custom #EuiBreadcrumbResponsiveMaxCount object to change the number of breadcrumbs to show at the particular breakpoints.
     * Omitting or passing a `0` value will show all breadcrumbs.
     *
     * Pass `false` to turn this behavior off.
     *
     * Default: `{ xs: 1, s: 2, m: 4 }`
     */
  responsive: _propTypes.default.oneOfType([_propTypes.default.bool.isRequired, _propTypes.default.any.isRequired]),

  /**
     * Forces all breadcrumbs to single line and
     * truncates each breadcrumb to a particular width,
     * except for the last item
     */
  truncate: _propTypes.default.bool,

  /**
     * Collapses the inner items past the maximum set here
     * into a single ellipses item
     */
  max: _propTypes.default.oneOfType([_propTypes.default.number.isRequired, _propTypes.default.oneOf([null])]),

  /**
     * The array of individual #EuiBreadcrumb items
     */
  breadcrumbs: _propTypes.default.arrayOf(_propTypes.default.shape({
    className: _propTypes.default.string,
    "aria-label": _propTypes.default.string,
    "data-test-subj": _propTypes.default.string,

    /**
       * Visible label of the breadcrumb
       */
    text: _propTypes.default.node.isRequired,
    href: _propTypes.default.string,
    onClick: _propTypes.default.func,

    /**
       * Force a max-width on the breadcrumb text
       */
    truncate: _propTypes.default.bool
  }).isRequired).isRequired
};