"use strict";

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

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

var _button = require("../button");

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

var _input = require("../input");

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

var _styles = require("../styles");

var _reactUid = require("react-uid");

var _constants = require("./constants");

var _textSearch = require("./text-search");

var _locale = require("../locale");

var _focusVisible = require("../utils/focusVisible");

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); 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 _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) || _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) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_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 ColumnIcon = function ColumnIcon(props) {
  if (props.column.kind === _constants.COLUMNS.BOOLEAN) {
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, "01");
  }

  if (props.column.kind === _constants.COLUMNS.CATEGORICAL) {
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, "abc");
  }

  if (props.column.kind === _constants.COLUMNS.DATETIME) {
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, "dt");
  }

  if (props.column.kind === _constants.COLUMNS.NUMERICAL) {
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, "#");
  }

  return /*#__PURE__*/_react.default.createElement(_icon.Filter, null);
};

function Options(props) {
  var _useStyletron = (0, _styles.useStyletron)(),
      _useStyletron2 = _slicedToArray(_useStyletron, 2),
      css = _useStyletron2[0],
      theme = _useStyletron2[1];

  var locale = _react.default.useContext(_locale.LocaleContext);

  var inputRef = _react.default.useRef(null);

  _react.default.useEffect(function () {
    if (inputRef.current) {
      // @ts-ignore
      inputRef.current.focus();
    }
  }, [inputRef.current]);

  var _React$useState = _react.default.useState(false),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      focusVisible = _React$useState2[0],
      setFocusVisible = _React$useState2[1];

  var seed = (0, _reactUid.useUIDSeed)();

  var buiRef = _react.default.useRef(props.columns.map(function (col) {
    return seed(col);
  }));

  var activeDescendant = buiRef.current[props.highlightIndex] ? "bui-".concat(buiRef.current[props.highlightIndex]) : undefined;
  var optionsLabelId = seed('options-label');

  var handleFocus = function handleFocus(event) {
    if ((0, _focusVisible.isFocusVisible)(event)) {
      setFocusVisible(true);
    }
  }; // eslint-disable-next-line @typescript-eslint/no-unused-vars


  var handleBlur = function handleBlur(event) {
    if (focusVisible !== false) {
      setFocusVisible(false);
    }
  };

  return /*#__PURE__*/_react.default.createElement("div", {
    className: css({
      backgroundColor: theme.colors.menuFill,
      minWidth: '320px',
      outline: focusVisible ? "3px solid ".concat(theme.colors.borderAccent) : 'none',
      paddingTop: theme.sizing.scale600,
      paddingBottom: theme.sizing.scale600
    })
  }, /*#__PURE__*/_react.default.createElement("p", {
    id: optionsLabelId,
    className: css(_objectSpread(_objectSpread({}, theme.typography.font100), {}, {
      marginTop: 'unset',
      paddingRight: theme.sizing.scale600,
      paddingLeft: theme.sizing.scale600
    }))
  }, locale.datatable.optionsLabel), props.searchable && /*#__PURE__*/_react.default.createElement("div", {
    className: css({
      marginBottom: theme.sizing.scale500,
      marginRight: theme.sizing.scale600,
      marginLeft: theme.sizing.scale600
    })
  }, /*#__PURE__*/_react.default.createElement(_input.Input, {
    inputRef: inputRef,
    value: props.query,
    onChange: function onChange(event) {
      return props.onQueryChange(event.target.value);
    },
    placeholder: locale.datatable.optionsSearch,
    size: _input.SIZE.compact,
    clearable: true
  })), !props.columns.length && /*#__PURE__*/_react.default.createElement("div", {
    className: css(_objectSpread(_objectSpread({}, theme.typography.font100), {}, {
      paddingRight: theme.sizing.scale600,
      paddingLeft: theme.sizing.scale600
    }))
  }, locale.datatable.optionsEmpty), /*#__PURE__*/_react.default.createElement("ul", {
    onKeyDown: props.onKeyDown,
    onFocus: handleFocus,
    onBlur: handleBlur,
    tabIndex: 0,
    role: "listbox",
    "aria-activedescendant": activeDescendant,
    "aria-labelledby": optionsLabelId,
    className: css({
      listStyleType: 'none',
      marginBlockStart: 'unset',
      marginBlockEnd: 'unset',
      maxHeight: '256px',
      paddingInlineStart: 'unset',
      outline: 'none',
      overflowY: 'auto'
    })
  }, props.columns.map(function (column, index) {
    var isHighlighted = index === props.highlightIndex;
    return (
      /*#__PURE__*/
      // handled on the wrapper element
      // eslint-disable-next-line jsx-a11y/click-events-have-key-events
      _react.default.createElement("li", {
        id: "bui-".concat(buiRef.current[index]),
        role: "option",
        "aria-selected": isHighlighted,
        onMouseEnter: function onMouseEnter() {
          return props.onMouseEnter(index);
        },
        onClick: function onClick() {
          return props.onClick(column);
        },
        key: column.title,
        className: css(_objectSpread(_objectSpread({}, theme.typography.font100), {}, {
          alignItems: 'center',
          // @ts-ignore
          backgroundColor: isHighlighted ? theme.colors.menuFillHover : null,
          cursor: 'pointer',
          display: 'flex',
          paddingTop: theme.sizing.scale100,
          paddingRight: theme.sizing.scale600,
          paddingBottom: theme.sizing.scale100,
          paddingLeft: theme.sizing.scale600
        }))
      }, /*#__PURE__*/_react.default.createElement("div", {
        className: css(_objectSpread(_objectSpread({}, theme.typography.font150), {}, {
          fontSize: '8px',
          alignItems: 'center',
          backgroundColor: theme.colors.backgroundTertiary,
          borderRadius: theme.borders.radius200,
          display: 'flex',
          height: theme.sizing.scale800,
          justifyContent: 'center',
          marginRight: theme.sizing.scale300,
          width: theme.sizing.scale800
        }))
      }, /*#__PURE__*/_react.default.createElement(ColumnIcon, {
        column: column
      })), column.title)
    );
  })));
}

function FilterMenu(props) {
  var _useStyletron3 = (0, _styles.useStyletron)(),
      _useStyletron4 = _slicedToArray(_useStyletron3, 2),
      theme = _useStyletron4[1];

  var locale = _react.default.useContext(_locale.LocaleContext);

  var _React$useState3 = _react.default.useState(false),
      _React$useState4 = _slicedToArray(_React$useState3, 2),
      isOpen = _React$useState4[0],
      setIsOpen = _React$useState4[1];

  var _React$useState5 = _react.default.useState(-1),
      _React$useState6 = _slicedToArray(_React$useState5, 2),
      highlightIndex = _React$useState6[0],
      setHighlightIndex = _React$useState6[1];

  var _React$useState7 = _react.default.useState(''),
      _React$useState8 = _slicedToArray(_React$useState7, 2),
      query = _React$useState8[0],
      setQuery = _React$useState8[1];

  var _React$useState9 = _react.default.useState(null),
      _React$useState10 = _slicedToArray(_React$useState9, 2),
      activeColumn = _React$useState10[0],
      setActiveColumn = _React$useState10[1];

  var handleOptionClick = _react.default.useCallback(setActiveColumn, []);

  var handleClose = _react.default.useCallback(function () {
    setIsOpen(false);
    setActiveColumn(null);
    setHighlightIndex(-1);
    setQuery('');
  }, []);

  var filterableColumns = _react.default.useMemo(function () {
    return props.columns.filter(function (column) {
      return column.filterable && !props.filters.has(column.title);
    });
  }, [props.columns, props.filters]);

  var columns = _react.default.useMemo(function () {
    return filterableColumns.filter(function (column) {
      return (0, _textSearch.matchesQuery)(column.title, query);
    });
  }, [filterableColumns, query]);

  var Filter = _react.default.useMemo(function () {
    if (!activeColumn) return null; // @ts-ignore

    return activeColumn.renderFilter;
  }, [activeColumn]);

  var activeColumnData = _react.default.useMemo(function () {
    var columnIndex = props.columns.findIndex(function (c) {
      return c === activeColumn;
    });
    if (columnIndex < 0) return [];
    return props.rows.map(function (row) {
      return props.columns[columnIndex].mapDataToValue(row.data);
    });
  }, [props.columns, props.rows, activeColumn]); // @ts-ignore


  function handleKeyDown(event) {
    if (event.keyCode === 13) {
      event.preventDefault(); // @ts-ignore

      setActiveColumn(columns[highlightIndex]);
    }

    if (event.keyCode === 38) {
      event.preventDefault();
      setHighlightIndex(Math.max(0, highlightIndex - 1));
    }

    if (event.keyCode === 40) {
      event.preventDefault();

      if (!isOpen) {
        setIsOpen(true);
      } else {
        setHighlightIndex(Math.min(columns.length - 1, highlightIndex + 1));
      }
    }
  }

  return /*#__PURE__*/_react.default.createElement(_popover.Popover, {
    focusLock: true,
    returnFocus: true,
    placement: _popover.PLACEMENT.bottomLeft,
    content: function content() {
      if (Filter && activeColumn) {
        return /*#__PURE__*/_react.default.createElement(Filter, {
          data: activeColumnData,
          close: handleClose // @ts-ignore
          ,
          setFilter: function setFilter(filterParams) {
            return props.onSetFilter(activeColumn.title, filterParams);
          }
        });
      }

      return /*#__PURE__*/_react.default.createElement(Options, {
        columns: columns,
        highlightIndex: highlightIndex // @ts-ignore
        ,
        onClick: handleOptionClick,
        onKeyDown: handleKeyDown,
        onMouseEnter: setHighlightIndex,
        onQueryChange: setQuery,
        query: query,
        searchable: filterableColumns.length >= 10
      });
    },
    onClick: function onClick() {
      if (isOpen) {
        handleClose();
      } else {
        setIsOpen(true);
      }
    },
    onClickOutside: handleClose,
    onEsc: handleClose,
    isOpen: isOpen,
    ignoreBoundary: true
  }, /*#__PURE__*/_react.default.createElement(_button.Button, {
    shape: _button.SHAPE.pill,
    size: _button.SIZE.compact,
    overrides: {
      BaseButton: {
        style: {
          marginLeft: theme.sizing.scale500,
          marginBottom: theme.sizing.scale500
        }
      }
    }
  }, locale.datatable.filterAdd));
}

var _default = FilterMenu;
exports.default = _default;