"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FieldValueSelectionFilter = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _services = require("../../../services");
var _predicate = require("../../../services/predicate");
var _popover = require("../../popover");
var _filter_group = require("../../filter_group");
var _filter_group2 = require("../../filter_group/filter_group.styles");
var _selectable = require("../../selectable");
var _query4 = require("../query");
var _ast = require("../query/ast");
var _react2 = require("@emotion/react");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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 _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _extends() { _extends = Object.assign ? Object.assign.bind() : 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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread 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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
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 _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, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); 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 } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : 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; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } 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 { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } /*
                                                                                                                                                                                                                                                                                                                                                                                               * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
                                                                                                                                                                                                                                                                                                                                                                                               * or more contributor license agreements. Licensed under the Elastic License
                                                                                                                                                                                                                                                                                                                                                                                               * 2.0 and the Server Side Public License, v 1; you may not use this file except
                                                                                                                                                                                                                                                                                                                                                                                               * in compliance with, at your election, the Elastic License 2.0 or the Server
                                                                                                                                                                                                                                                                                                                                                                                               * Side Public License, v 1.
                                                                                                                                                                                                                                                                                                                                                                                               */
var defaults = {
  config: {
    multiSelect: true,
    filterWith: 'prefix',
    loadingMessage: 'Loading...',
    noOptionsMessage: 'No options found',
    searchThreshold: 10
  }
};
var FieldValueSelectionFilter = /*#__PURE__*/function (_Component) {
  _inherits(FieldValueSelectionFilter, _Component);
  var _super = _createSuper(FieldValueSelectionFilter);
  function FieldValueSelectionFilter(props) {
    var _this;
    _classCallCheck(this, FieldValueSelectionFilter);
    _this = _super.call(this, props);
    _defineProperty(_assertThisInitialized(_this), "resolveOptionsLoader", function () {
      var options = _this.props.config.options;
      if ((0, _predicate.isArray)(options)) {
        return function () {
          return Promise.resolve(options);
        };
      }
      return function () {
        var cachedOptions = _this.state.cachedOptions;
        if (cachedOptions) {
          return Promise.resolve(cachedOptions);
        }
        return options().then(function (opts) {
          // If a cache time is set, populate the cache and also schedule a
          // cache reset.
          if (_this.props.config.cache != null && _this.props.config.cache > 0) {
            _this.setState({
              cachedOptions: opts
            });
            setTimeout(function () {
              _this.setState({
                cachedOptions: null
              });
            }, _this.props.config.cache);
          }
          return opts;
        });
      };
    });
    var _options = props.config.options;
    var preloadedOptions = (0, _predicate.isArray)(_options) ? {
      all: _options,
      shown: _options
    } : null;
    _this.state = {
      popoverOpen: false,
      error: null,
      options: preloadedOptions,
      activeItems: []
    };
    return _this;
  }
  _createClass(FieldValueSelectionFilter, [{
    key: "closePopover",
    value: function closePopover() {
      this.setState({
        popoverOpen: false
      });
    }
  }, {
    key: "onButtonClick",
    value: function onButtonClick() {
      var _this2 = this;
      this.setState(function (prevState) {
        if (!prevState.popoverOpen) {
          // loading options updates the state, so we'll do that in the animation frame
          window.requestAnimationFrame(function () {
            _this2.loadOptions();
          });
        }
        return {
          options: null,
          error: null,
          popoverOpen: !prevState.popoverOpen
        };
      });
    }
  }, {
    key: "loadOptions",
    value: function loadOptions() {
      var _this3 = this;
      var loader = this.resolveOptionsLoader();
      this.setState({
        options: null,
        error: null
      });
      loader().then(function (options) {
        var items = {
          on: [],
          off: [],
          rest: []
        };
        var _this3$props = _this3.props,
          query = _this3$props.query,
          config = _this3$props.config;
        var multiSelect = _this3.resolveMultiSelect();
        if (options) {
          options.forEach(function (op) {
            var optionField = op.field || config.field;
            if (optionField) {
              var clause = multiSelect === 'or' ? query.getOrFieldClause(optionField, op.value) : query.getSimpleFieldClause(optionField, op.value);
              var checked = _this3.resolveChecked(clause);
              if (!checked) {
                items.rest.push(op);
              } else if (checked === 'on') {
                items.on.push(op);
              } else {
                items.off.push(op);
              }
            }
            return;
          });
        }
        _this3.setState({
          error: null,
          activeItems: items.on,
          options: {
            all: options,
            shown: [].concat(_toConsumableArray(items.on), _toConsumableArray(items.off), _toConsumableArray(items.rest))
          }
        });
      }).catch(function () {
        _this3.setState({
          options: null,
          error: 'Could not load options'
        });
      });
    }
  }, {
    key: "filterOptions",
    value: function filterOptions() {
      var _this4 = this;
      var q = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
      this.setState(function (prevState) {
        if ((0, _predicate.isNil)(prevState.options)) {
          return {};
        }
        var predicate = _this4.getOptionFilter();
        return _objectSpread(_objectSpread({}, prevState), {}, {
          options: _objectSpread(_objectSpread({}, prevState.options), {}, {
            shown: prevState.options.all.filter(function (option, i, options) {
              var name = _this4.resolveOptionName(option).toLowerCase();
              var query = q.toLowerCase();
              return predicate(name, query, options);
            })
          })
        });
      });
    }
  }, {
    key: "getOptionFilter",
    value: function getOptionFilter() {
      var filterWith = this.props.config.filterWith || defaults.config.filterWith;
      if (typeof filterWith === 'function') {
        return filterWith;
      }
      if (filterWith === 'includes') {
        return function (name, query) {
          return name.includes(query);
        };
      }
      return function (name, query) {
        return name.startsWith(query);
      };
    }
  }, {
    key: "resolveOptionName",
    value: function resolveOptionName(option) {
      return option.name || option.value.toString();
    }
  }, {
    key: "onOptionClick",
    value: function onOptionClick(field, value, checked) {
      var multiSelect = this.resolveMultiSelect();
      var _this$props$config = this.props.config,
        _this$props$config$au = _this$props$config.autoClose,
        autoClose = _this$props$config$au === void 0 ? true : _this$props$config$au,
        _this$props$config$op = _this$props$config.operator,
        operator = _this$props$config$op === void 0 ? _ast.Operator.EQ : _this$props$config$op;

      // we're closing popover only if the user can only select one item... if the
      // user can select more, we'll leave it open so she can continue selecting

      if (!multiSelect && autoClose) {
        this.closePopover();
        var _query = checked ? this.props.query.removeSimpleFieldClauses(field).addSimpleFieldValue(field, value, true, operator) : this.props.query.removeSimpleFieldClauses(field);
        this.props.onChange(_query);
      } else {
        if (multiSelect === 'or') {
          var _query2 = checked ? this.props.query.addOrFieldValue(field, value, true, operator) : this.props.query.removeOrFieldValue(field, value);
          this.props.onChange(_query2);
        } else {
          var _query3 = checked ? this.props.query.addSimpleFieldValue(field, value, true, operator) : this.props.query.removeSimpleFieldValue(field, value);
          this.props.onChange(_query3);
        }
      }
    }
  }, {
    key: "resolveMultiSelect",
    value: function resolveMultiSelect() {
      var config = this.props.config;
      return !(0, _predicate.isNil)(config.multiSelect) ? config.multiSelect : defaults.config.multiSelect;
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      if (this.props.query.text.length) this.loadOptions();
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      if (this.props.query !== prevProps.query) this.loadOptions();
    }
  }, {
    key: "render",
    value: function render() {
      var _this5 = this;
      var _this$props = this.props,
        query = _this$props.query,
        config = _this$props.config;
      var multiSelect = this.resolveMultiSelect();
      var activeTop = this.isActiveField(config.field);
      var activeItem = this.state.options ? this.state.options.all.some(function (item) {
        return _this5.isActiveField(item.field);
      }) : false;
      var activeItemsCount = this.state.activeItems.length;
      var active = (activeTop || activeItem) && activeItemsCount > 0;
      var button = (0, _react2.jsx)(_filter_group.EuiFilterButton, {
        iconType: "arrowDown",
        iconSide: "right",
        onClick: this.onButtonClick.bind(this),
        hasActiveFilters: active,
        numActiveFilters: active ? activeItemsCount : undefined,
        grow: true
      }, config.name);
      var items = this.state.options ? this.state.options.shown.map(function (option) {
        var _option$view;
        var optionField = option.field || config.field;
        if (optionField == null) {
          throw new Error('option.field or field should be provided in <FieldValueSelectionFilter/>');
        }
        var clause = multiSelect === 'or' ? query.getOrFieldClause(optionField, option.value) : query.getSimpleFieldClause(optionField, option.value);
        var label = _this5.resolveOptionName(option);
        var checked = _this5.resolveChecked(clause);
        return {
          label: label,
          checked: checked,
          data: {
            view: (_option$view = option.view) !== null && _option$view !== void 0 ? _option$view : label,
            value: option.value,
            optionField: optionField
          }
        };
      }) : [];
      var threshold = config.searchThreshold || defaults.config.searchThreshold;
      var isOverSearchThreshold = this.state.options && this.state.options.all.length >= threshold;
      var searchProps = {
        searchable: false
      };
      if (isOverSearchThreshold) {
        searchProps = {
          searchable: true,
          searchProps: {
            compressed: true,
            disabled: this.state.error != null
          }
        };
      }
      return (0, _react2.jsx)(_services.RenderWithEuiTheme, null, function (euiThemeContext) {
        return (0, _react2.jsx)(_popover.EuiPopover, {
          button: button,
          isOpen: _this5.state.popoverOpen,
          closePopover: _this5.closePopover.bind(_this5),
          panelPaddingSize: "none",
          anchorPosition: "downCenter",
          panelProps: {
            css: (0, _filter_group2.euiFilterGroupStyles)(euiThemeContext).euiFilterGroup__popoverPanel
          }
        }, (0, _react2.jsx)(_selectable.EuiSelectable, _extends({
          singleSelection: !multiSelect,
          "aria-label": config.name,
          options: items,
          renderOption: function renderOption(option) {
            return option.view;
          },
          isLoading: (0, _predicate.isNil)(_this5.state.options),
          loadingMessage: config.loadingMessage || defaults.config.loadingMessage,
          emptyMessage: config.noOptionsMessage || defaults.config.noOptionsMessage,
          errorMessage: _this5.state.error,
          noMatchesMessage: config.noOptionsMessage || defaults.config.noOptionsMessage,
          listProps: {
            isVirtualized: isOverSearchThreshold || false
          },
          onChange: function onChange(options, event, changedOption) {
            if (changedOption.data) {
              _this5.onOptionClick(changedOption.data.optionField, changedOption.data.value, changedOption.checked);
            }
          }
        }, searchProps), function (list, search) {
          return (0, _react2.jsx)(_react.default.Fragment, null, isOverSearchThreshold && (0, _react2.jsx)(_popover.EuiPopoverTitle, {
            paddingSize: "s"
          }, search), list);
        }));
      });
    }
  }, {
    key: "resolveChecked",
    value: function resolveChecked(clause) {
      if (clause) {
        return _query4.Query.isMust(clause) ? 'on' : 'off';
      }
    }
  }, {
    key: "isActiveField",
    value: function isActiveField(field) {
      if (typeof field !== 'string') {
        return false;
      }
      var query = this.props.query;
      var multiSelect = this.resolveMultiSelect();
      if (multiSelect === 'or') {
        return query.hasOrFieldClause(field);
      }
      return query.hasSimpleFieldClause(field);
    }
  }]);
  return FieldValueSelectionFilter;
}(_react.Component);
exports.FieldValueSelectionFilter = FieldValueSelectionFilter;
FieldValueSelectionFilter.propTypes = {
  index: _propTypes.default.number.isRequired,
  config: _propTypes.default.shape({
    type: _propTypes.default.oneOf(["field_value_selection"]).isRequired,
    field: _propTypes.default.string,
    name: _propTypes.default.string.isRequired,
    /**
       * See #FieldValueOptionType
       */
    options: _propTypes.default.oneOfType([_propTypes.default.arrayOf(_propTypes.default.shape({
      field: _propTypes.default.string,
      value: _propTypes.default.oneOfType([_propTypes.default.string.isRequired, _propTypes.default.number.isRequired, _propTypes.default.bool.isRequired, _propTypes.default.shape({
        type: _propTypes.default.oneOf(["date"]).isRequired,
        raw: _propTypes.default.any.isRequired,
        granularity: _propTypes.default.oneOfType([_propTypes.default.shape({
          es: _propTypes.default.oneOf(["d", "w", "M", "y"]).isRequired,
          js: _propTypes.default.oneOf(["day", "week", "month", "year"]).isRequired,
          isSame: _propTypes.default.func.isRequired,
          start: _propTypes.default.func.isRequired,
          startOfNext: _propTypes.default.func.isRequired,
          iso8601: _propTypes.default.func.isRequired
        }).isRequired, _propTypes.default.oneOf([undefined])]).isRequired,
        text: _propTypes.default.string.isRequired,
        resolve: _propTypes.default.func.isRequired
      }).isRequired]).isRequired,
      name: _propTypes.default.string,
      view: _propTypes.default.node
    }).isRequired).isRequired, _propTypes.default.func.isRequired]).isRequired,
    filterWith: _propTypes.default.oneOfType([_propTypes.default.oneOf(["prefix", "includes"]), _propTypes.default.func.isRequired]),
    cache: _propTypes.default.number,
    multiSelect: _propTypes.default.oneOfType([_propTypes.default.bool.isRequired, _propTypes.default.oneOf(["and", "or"])]),
    loadingMessage: _propTypes.default.string,
    noOptionsMessage: _propTypes.default.string,
    searchThreshold: _propTypes.default.number,
    available: _propTypes.default.func,
    autoClose: _propTypes.default.bool,
    operator: _propTypes.default.oneOf(["eq", "exact", "gt", "gte", "lt", "lte"])
  }).isRequired,
  query: _propTypes.default.any.isRequired,
  onChange: _propTypes.default.func.isRequired
};