"use strict";

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); }
var _react = _interopRequireWildcard(require("react"));
var _index = require("./index");
var _faker = require("@faker-js/faker");
var _react2 = require("@emotion/react");
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 _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 _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 _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 = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } /*
                                                                       * 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.
                                                                       */ /// <reference types="cypress" />
/// <reference types="cypress-real-events" />
/// <reference types="../../../cypress/support" />
var columns = [{
  id: 'Name'
}, {
  id: 'Email',
  cellActions: [function (_ref) {
    var rowIndex = _ref.rowIndex,
      columnId = _ref.columnId,
      Component = _ref.Component;
    var row = ++rowIndex;
    return (0, _react2.jsx)(Component, {
      onClick: function onClick() {},
      iconType: "heart",
      "aria-label": "Send love to ".concat(row, ", column \"").concat(columnId, "\" ")
    }, "Send love");
  }]
}, {
  id: 'User ID',
  schema: 'string'
}, {
  id: 'Account balance'
}, {
  id: 'Last purchase',
  schema: 'datetime'
}, {
  id: 'Favorite distro',
  schema: 'favoriteDistro'
}];
var storeData = [];
for (var i = 1; i < 11; i++) {
  storeData.push({
    Name: "".concat(_faker.faker.person.lastName(), ", ").concat(_faker.faker.person.firstName(), " ").concat(_faker.faker.person.suffix()),
    Email: "".concat(_faker.faker.internet.email()),
    'User ID': "".concat(_faker.faker.number.int({
      min: 1000000,
      max: 9999999
    })),
    'Account balance': _faker.faker.finance.amount(),
    'Last purchase': "".concat(_faker.faker.date.past()),
    'Favorite distro': i % 2 === 0 ? 'Alma' : 'Debian'
  });
}
var commaSeparateNumbers = function commaSeparateNumbers(numberString) {
  // extract the groups-of-three digits that are right-aligned
  return numberString.replace(/((\d{3})+)$/, function (match) {
    return (
      // then replace each group of xyz digits with ,xyz
      match.replace(/(\d{3})/g, ',$1')
    );
  });
};
var DataGrid = function DataGrid() {
  var _useState = (0, _react.useState)(columns.map(function (_ref2) {
      var id = _ref2.id;
      return id;
    })),
    _useState2 = _slicedToArray(_useState, 2),
    visibleColumns = _useState2[0],
    setVisibleColumns = _useState2[1];
  var _useState3 = (0, _react.useState)(storeData),
    _useState4 = _slicedToArray(_useState3, 2),
    data = _useState4[0],
    setData = _useState4[1];
  var _useState5 = (0, _react.useState)([{
      id: 'custom',
      direction: 'asc'
    }]),
    _useState6 = _slicedToArray(_useState5, 2),
    sortingColumns = _useState6[0],
    setSortingColumns = _useState6[1];
  var setSorting = function setSorting(sortingColumns) {
    var sortedData = _toConsumableArray(data).sort(function (a, b) {
      for (var _i2 = 0; _i2 < sortingColumns.length; _i2++) {
        var column = sortingColumns[_i2];
        var aValue = a[column.id];
        var bValue = b[column.id];
        if (aValue < bValue) return column.direction === 'asc' ? -1 : 1;
        if (aValue > bValue) return column.direction === 'asc' ? 1 : -1;
      }
      return 0;
    });
    setData(sortedData);
    setSortingColumns(sortingColumns);
  };
  return (0, _react2.jsx)(_index.EuiDataGrid, {
    "aria-label": "Data grid schema example",
    columns: columns,
    columnVisibility: {
      visibleColumns: visibleColumns,
      setVisibleColumns: setVisibleColumns
    },
    rowCount: data.length,
    inMemory: {
      level: 'sorting'
    },
    renderCellValue: function renderCellValue(_ref3) {
      var rowIndex = _ref3.rowIndex,
        columnId = _ref3.columnId,
        schema = _ref3.schema;
      var value = data[rowIndex][columnId];
      if (schema === 'numeric') {
        value = commaSeparateNumbers(value);
      }
      return value;
    },
    sorting: {
      columns: sortingColumns,
      onSort: setSorting
    },
    schemaDetectors: [{
      type: 'favoriteDistro',
      textTransform: 'capitalize',
      detector: function detector(value) {
        return value.toLowerCase() === 'alma' || value.toLowerCase() === 'debian' ? 1 : 0;
      },
      comparator: function comparator(a, b, direction) {
        var aValue = a.toLowerCase() === 'alma';
        var bValue = b.toLowerCase() === 'alma';
        if (aValue < bValue) return direction === 'asc' ? 1 : -1;
        if (aValue > bValue) return direction === 'asc' ? -1 : 1;
        return 0;
      },
      sortTextAsc: 'Alma to Debian',
      sortTextDesc: 'Debian to Alma',
      icon: 'starFilled',
      color: '#800080'
    }]
  });
};
beforeEach(function () {
  cy.viewport(1280, 800); // large breakpoint
  cy.mount((0, _react2.jsx)("div", {
    style: {
      width: '80%',
      margin: '0 auto'
    }
  }, (0, _react2.jsx)(DataGrid, null)));
});
describe('EuiDataGrid', function () {
  describe('Automated accessibility check', function () {
    it('has zero violations on first render', function () {
      cy.checkAxe();
    });
    it('has zero violations when the columns visibility menu is open', function () {
      cy.get('button[data-test-subj="dataGridColumnSelectorButton"]').realClick();
      cy.checkAxe();
    });
    it('has zero violations when the hide all columns button is clicked', function () {
      cy.get('button[data-test-subj="dataGridColumnSelectorButton"]').realClick();
      cy.get('button[data-test-subj="dataGridColumnSelectorHideAllButton"]').realClick();
      // TODO: Log this issue and remove the skipFailures boolean when fixed
      cy.checkAxe({
        skipFailures: true
      });
    });
    it('has zero violations when the columns reorder searchbox returns multiple results', function () {
      cy.get('button[data-test-subj="dataGridColumnSelectorButton"]').realClick();
      cy.get('input[data-test-subj="dataGridColumnSelectorSearch"]').type('a');
      cy.get('div.euiSwitch--compressed').should(function ($s) {
        expect($s).to.have.length(5);
      });
      cy.checkAxe();
    });
    it('has zero violations when the columns reorder searchbox returns 1 result', function () {
      cy.get('button[data-test-subj="dataGridColumnSelectorButton"]').realClick();
      cy.get('input[data-test-subj="dataGridColumnSelectorSearch"]').type('favorite');
      cy.get('div.euiSwitch--compressed').should(function ($s) {
        expect($s).to.have.length(1);
      });
      cy.checkAxe();
    });
    it('has zero violations when the columns reorder searchbox returns 0 results', function () {
      cy.get('button[data-test-subj="dataGridColumnSelectorButton"]').realClick();
      cy.get('input[data-test-subj="dataGridColumnSelectorSearch"]').type('x');
      cy.get('div.euiSwitch--compressed').should(function ($s) {
        expect($s).to.have.length(0);
      });
      cy.checkAxe();
    });
    it('has zero violations when the keyboard shortcut menu is open', function () {
      cy.get('button[data-test-subj="dataGridKeyboardShortcutsButton"]').realClick();
      cy.checkAxe();
    });
    it('has zero violations when the grid display menu is open', function () {
      cy.get('button[data-test-subj="dataGridDisplaySelectorButton"]').realClick();
      cy.checkAxe();
    });
    it('has zero violations when the column actions menu is open', function () {
      cy.get('button.euiDataGridHeaderCell__button').first().realClick();
      cy.checkAxe();
    });
    it('has zero violations when a cell expansion popover is open', function () {
      cy.get('div[data-gridcell-visible-row-index="0"][data-gridcell-column-index="1"]').realClick();
      cy.get('div[data-gridcell-visible-row-index="0"][data-gridcell-column-index="1"]').find('button.euiButtonIcon').last().realClick();
      cy.checkAxe();
    });
    it('has zero violations on sort and when the columns sorting menu is open', function () {
      cy.get('button.euiDataGridHeaderCell__button').last().realClick();
      cy.get('button.euiListGroupItem__button').contains('Sort Alma to Debian').should('exist').realClick();
      cy.get('div[data-test-subj="dataGridColumnSortingPopover"] button').realClick();
      cy.checkAxe();
    });
    it('has zero violations when fullscreen is open', function () {
      cy.get('button[data-test-subj="dataGridFullScreenButton"]').realClick();
      cy.get('div.euiDataGrid--fullScreen').should('exist');
      cy.checkAxe();
    });
  });
});