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) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) 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; }

/*
 * 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.
 */
import React, { useContext, useEffect, useRef, useState } from 'react';
import PropTypes from "prop-types";
import classnames from 'classnames';
import { keys } from '../../services';
import tabbable from 'tabbable';
import { DataGridFocusContext } from './data_grid_context';
export var EuiDataGridControlHeaderCell = function EuiDataGridControlHeaderCell(props) {
  var controlColumn = props.controlColumn,
      index = props.index,
      headerIsInteractive = props.headerIsInteractive,
      className = props.className;

  var _useContext = useContext(DataGridFocusContext),
      setFocusedCell = _useContext.setFocusedCell,
      onFocusUpdate = _useContext.onFocusUpdate;

  var HeaderCellRender = controlColumn.headerCellRender,
      width = controlColumn.width,
      id = controlColumn.id;
  var classes = classnames('euiDataGridHeaderCell', className);

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      isFocused = _useState2[0],
      setIsFocused = _useState2[1];

  useEffect(function () {
    onFocusUpdate([index, -1], function (isFocused) {
      setIsFocused(isFocused);
    });
  }, [index, onFocusUpdate]);
  var headerRef = useRef(null);

  var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      isCellEntered = _useState4[0],
      setIsCellEntered = _useState4[1];

  useEffect(function () {
    if (headerRef.current) {
      var enableInteractives = function enableInteractives() {
        var interactiveElements = headerRef.current.querySelectorAll('[data-euigrid-tab-managed]');

        for (var i = 0; i < interactiveElements.length; i++) {
          interactiveElements[i].setAttribute('tabIndex', '0');
        }
      };

      var disableInteractives = function disableInteractives() {
        var tababbles = tabbable(headerRef.current);

        if (tababbles.length > 1) {
          console.warn("EuiDataGridHeaderCell 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-euigrid-tab-managed', 'true');
          element.setAttribute('tabIndex', '-1');
        }
      };

      if (isCellEntered) {
        enableInteractives();
        var tabbables = tabbable(headerRef.current);

        if (tabbables.length > 0) {
          tabbables[0].focus();
        }
      } else {
        disableInteractives();
      }
    }
  }, [isCellEntered]);
  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 keys.ENTER:
            {
              event.preventDefault();
              setIsCellEntered(true);
              break;
            }

          case keys.ESCAPE:
            {
              event.preventDefault(); // move focus to cell

              setIsCellEntered(false);
              headerRef.current.focus();
              break;
            }

          case 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-euigrid-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.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.createElement("div", {
    className: "euiDataGridHeaderCell__content"
  }, /*#__PURE__*/React.createElement(HeaderCellRender, null)));
};
EuiDataGridControlHeaderCell.propTypes = {
  index: PropTypes.number.isRequired,
  controlColumn: PropTypes.shape({
    /**
       * Used as the React `key` when rendering content
       */
    id: PropTypes.string.isRequired,

    /**
       * Component to render in the column header
       */
    headerCellRender: PropTypes.elementType.isRequired,

    /**
       * Component to render for each row in the column
       */
    rowCellRender: PropTypes.oneOfType([PropTypes.func.isRequired, PropTypes.func.isRequired]).isRequired,

    /**
       * Width of the column, uses are unable to change this
       */
    width: PropTypes.number.isRequired
  }).isRequired,
  headerIsInteractive: PropTypes.bool.isRequired,
  className: PropTypes.string
};