"use strict";

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

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

var _reactFocusLock = _interopRequireDefault(require("react-focus-lock"));

var _index = require("../button/index.js");

var _index2 = require("../icon/index.js");

var _index3 = require("../input/index.js");

var _index4 = require("../popover/index.js");

var _index5 = require("../styles/index.js");

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

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

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(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(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; }

function ColumnIcon(props) {
  if (props.column.kind === _constants.COLUMNS.BOOLEAN) {
    return '01';
  }

  if (props.column.kind === _constants.COLUMNS.CATEGORICAL) {
    return 'abc';
  }

  if (props.column.kind === _constants.COLUMNS.NUMERICAL) {
    return '#';
  }

  return _react.default.createElement(_index2.Filter, null);
}

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

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

  _react.default.useEffect(function () {
    if (inputRef.current) {
      inputRef.current.focus();
    }
  }, [inputRef.current]);

  return _react.default.createElement("div", {
    tabIndex: "0",
    role: "listbox",
    className: css({
      minWidth: '320px',
      paddingTop: theme.sizing.scale600,
      paddingBottom: theme.sizing.scale600
    }),
    onKeyDown: props.onKeyDown
  }, _react.default.createElement("p", {
    className: css(_objectSpread({}, theme.typography.font100, {
      marginTop: 'unset',
      paddingRight: theme.sizing.scale600,
      paddingLeft: theme.sizing.scale600
    }))
  }, "Select column to filter by"), props.searchable && _react.default.createElement("div", {
    className: css({
      marginBottom: theme.sizing.scale500,
      marginRight: theme.sizing.scale600,
      marginLeft: theme.sizing.scale600
    })
  }, _react.default.createElement(_index3.Input, {
    inputRef: inputRef,
    value: props.query,
    onChange: function onChange(event) {
      return props.onQueryChange(event.target.value);
    },
    placeholder: "Search for a column to filter by...",
    size: _index3.SIZE.compact,
    clearable: true
  })), !props.columns.length && _react.default.createElement("div", {
    className: css(_objectSpread({}, theme.typography.font100, {
      paddingRight: theme.sizing.scale600,
      paddingLeft: theme.sizing.scale600
    }))
  }, "No columns available."), _react.default.createElement("ul", {
    className: css({
      listStyleType: 'none',
      marginBlockStart: 'unset',
      marginBlockEnd: 'unset',
      paddingInlineStart: 'unset'
    })
  }, props.columns.map(function (column, index) {
    var isHighlighted = index === props.highlightIndex;
    return (// handled on the wrapper element
      // eslint-disable-next-line jsx-a11y/click-events-have-key-events
      _react.default.createElement("li", {
        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({}, theme.typography.font100, {
          alignItems: 'center',
          backgroundColor: isHighlighted ? theme.colors.mono200 : null,
          cursor: 'pointer',
          display: 'flex',
          paddingTop: theme.sizing.scale100,
          paddingRight: theme.sizing.scale600,
          paddingBottom: theme.sizing.scale100,
          paddingLeft: theme.sizing.scale600
        }))
      }, _react.default.createElement("div", {
        className: css(_objectSpread({}, theme.typography.font150, {
          fontSize: '8px',
          alignItems: 'center',
          backgroundColor: theme.colors.mono300,
          borderRadius: theme.borders.radius200,
          display: 'flex',
          height: theme.sizing.scale800,
          justifyContent: 'center',
          marginRight: theme.sizing.scale300,
          width: theme.sizing.scale800
        }))
      }, _react.default.createElement(ColumnIcon, {
        column: column
      })), column.title)
    );
  })));
}

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

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

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

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

  var _React$useState7 = _react.default.useState(null),
      _React$useState8 = _slicedToArray(_React$useState7, 2),
      activeColumn = _React$useState8[0],
      setActiveColumn = _React$useState8[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;
    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 row.data[columnIndex];
    });
  }, [props.columns, props.rows, activeColumn]);

  function handleKeyDown(event) {
    if (event.keyCode === 13) {
      event.preventDefault();
      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 _react.default.createElement(_index4.Popover, {
    placement: _index4.PLACEMENT.bottomLeft,
    content: function content() {
      if (Filter && activeColumn) {
        return (// eslint-disable-next-line jsx-a11y/no-autofocus
          _react.default.createElement(_reactFocusLock.default, {
            autoFocus: false
          }, _react.default.createElement(Filter, {
            data: activeColumnData,
            close: handleClose,
            setFilter: function setFilter(filterParams) {
              return props.onSetFilter(filterParams, activeColumn.title);
            }
          }))
        );
      }

      return _react.default.createElement(Options, {
        columns: columns,
        highlightIndex: highlightIndex,
        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
  }, _react.default.createElement(_index.Button, {
    shape: _index.SHAPE.pill,
    size: _index.SIZE.compact,
    onKeyDown: handleKeyDown,
    overrides: {
      BaseButton: {
        style: {
          marginLeft: theme.sizing.scale500,
          marginBottom: theme.sizing.scale500
        }
      }
    }
  }, "Add Filter"));
}

var _default = FilterMenu;
exports.default = _default;