"use strict";

function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "EuiDataGridControlHeaderCell", {
  enumerable: true,
  get: function get() {
    return _data_grid_control_header_cell.EuiDataGridControlHeaderCell;
  }
});
exports.OuiDataGridControlHeaderCell = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _classnames = _interopRequireDefault(require("classnames"));
var _services = require("../../services");
var _tabbable = require("tabbable");
var _data_grid_context = require("./data_grid_context");
var _data_grid_control_header_cell = require("../../eui_components/datagrid/data_grid_control_header_cell");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) { "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); } return f; })(e, t); }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _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(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) { n[e] = r[e]; } return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) { ; } } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } /*
 * 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 OuiDataGridControlHeaderCell = function OuiDataGridControlHeaderCell(props) {
  var controlColumn = props.controlColumn,
    index = props.index,
    headerIsInteractive = props.headerIsInteractive,
    className = props.className;
  var _useContext = (0, _react.useContext)(_data_grid_context.DataGridFocusContext),
    setFocusedCell = _useContext.setFocusedCell,
    onFocusUpdate = _useContext.onFocusUpdate;
  var HeaderCellRender = controlColumn.headerCellRender,
    width = controlColumn.width,
    id = controlColumn.id;
  var classes = (0, _classnames.default)('ouiDataGridHeaderCell', className);
  var _useState = (0, _react.useState)(false),
    _useState2 = _slicedToArray(_useState, 2),
    isFocused = _useState2[0],
    setIsFocused = _useState2[1];
  (0, _react.useEffect)(function () {
    onFocusUpdate([index, -1], function (isFocused) {
      setIsFocused(isFocused);
    });
  }, [index, onFocusUpdate]);
  var headerRef = (0, _react.useRef)(null);
  var _useState3 = (0, _react.useState)(false),
    _useState4 = _slicedToArray(_useState3, 2),
    isCellEntered = _useState4[0],
    setIsCellEntered = _useState4[1];
  (0, _react.useEffect)(function () {
    if (headerRef.current) {
      var enableInteractives = function enableInteractives() {
        var interactiveElements = headerRef.current.querySelectorAll('[data-ouigrid-tab-managed]');
        for (var i = 0; i < interactiveElements.length; i++) {
          interactiveElements[i].setAttribute('tabIndex', '0');
        }
      };
      var disableInteractives = function disableInteractives() {
        var tababbles = (0, _tabbable.tabbable)(headerRef.current);
        if (tababbles.length > 1) {
          console.warn("OuiDataGridHeaderCell expects at most 1 tabbable element, ".concat(tababbles.length, " found instead"));
        }
        for (var i = 0; i < tababbles.length; i++) {
          var element = tababbles[i];
          element.setAttribute('data-ouigrid-tab-managed', 'true');
          element.setAttribute('tabIndex', '-1');
        }
      };
      if (isCellEntered) {
        enableInteractives();
        var tabbables = (0, _tabbable.tabbable)(headerRef.current);
        if (tabbables.length > 0) {
          tabbables[0].focus();
        }
      } else {
        disableInteractives();
      }
    }
  }, [isCellEntered]);
  (0, _react.useEffect)(function () {
    if (headerRef.current) {
      // focusin bubbles while focus does not, and this needs to react to children gaining focus
      var onFocusIn = function onFocusIn(e) {
        if (headerIsInteractive === false) {
          // header is not interactive, avoid focusing
          requestAnimationFrame(function () {
            return headerRef.current.blur();
          });
          e.preventDefault();
          return false;
        } else {
          // take the focus
          setFocusedCell([index, -1]);
        }
      }; // focusout bubbles while blur does not, and this needs to react to the children losing focus
      var onFocusOut = function onFocusOut() {
        // wait for the next element to receive focus, then update interactives' state
        requestAnimationFrame(function () {
          if (headerRef.current) {
            if (headerRef.current.contains(document.activeElement) === false) {
              setIsCellEntered(false);
            }
          }
        });
      };
      var onKeyUp = function onKeyUp(event) {
        switch (event.key) {
          case _services.keys.ENTER:
            {
              event.preventDefault();
              setIsCellEntered(true);
              break;
            }
          case _services.keys.ESCAPE:
            {
              event.preventDefault();
              // move focus to cell
              setIsCellEntered(false);
              headerRef.current.focus();
              break;
            }
          case _services.keys.F2:
            {
              event.preventDefault();
              if (document.activeElement === headerRef.current) {
                // move focus into cell's interactives
                setIsCellEntered(true);
              } else {
                // move focus to cell
                setIsCellEntered(false);
                headerRef.current.focus();
              }
              break;
            }
        }
      };
      if (isFocused) {
        var interactives = headerRef.current.querySelectorAll('[data-ouigrid-tab-managed]');
        if (interactives.length === 1) {
          setIsCellEntered(true);
        } else {
          headerRef.current.focus();
        }
      } else {
        setIsCellEntered(false);
      }
      var headerNode = headerRef.current;
      // @ts-ignore-next line TS doesn't have focusin
      headerNode.addEventListener('focusin', onFocusIn);
      headerNode.addEventListener('focusout', onFocusOut);
      headerNode.addEventListener('keyup', onKeyUp);
      return function () {
        // @ts-ignore-next line TS doesn't have focusin
        headerNode.removeEventListener('focusin', onFocusIn);
        headerNode.removeEventListener('focusout', onFocusOut);
        headerNode.removeEventListener('keyup', onKeyUp);
      };
    }
  }, [setFocusedCell, headerIsInteractive, isFocused, setIsCellEntered, index]);
  return /*#__PURE__*/_react.default.createElement("div", {
    role: "columnheader",
    ref: headerRef,
    tabIndex: isFocused ? 0 : -1,
    className: classes,
    "data-test-subj": "dataGridHeaderCell-".concat(id),
    style: width != null ? {
      width: "".concat(width, "px")
    } : {}
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: "ouiDataGridHeaderCell__content"
  }, /*#__PURE__*/_react.default.createElement(HeaderCellRender, null)));
};

/* OUI -> EUI Aliases: Build-Time */
exports.OuiDataGridControlHeaderCell = OuiDataGridControlHeaderCell;
OuiDataGridControlHeaderCell.propTypes = {
  index: _propTypes.default.number.isRequired,
  controlColumn: _propTypes.default.shape({
    /**
       * Used as the React `key` when rendering content
       */
    id: _propTypes.default.string.isRequired,
    /**
       * Component to render in the column header
       */
    headerCellRender: _propTypes.default.elementType.isRequired,
    /**
       * Component to render for each row in the column
       */
    rowCellRender: _propTypes.default.oneOfType([_propTypes.default.func.isRequired, _propTypes.default.func.isRequired]).isRequired,
    /**
       * Width of the column, uses are unable to change this
       */
    width: _propTypes.default.number.isRequired
  }).isRequired,
  headerIsInteractive: _propTypes.default.bool.isRequired,
  className: _propTypes.default.string
};
/* OUI -> EUI Aliases: Build-Time */