"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

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

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

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");

/*
 * 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 EuiDataGridControlHeaderCell = function EuiDataGridControlHeaderCell(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)('euiDataGridHeaderCell', className);

  var _useState = (0, _react.useState)(false),
      _useState2 = (0, _slicedToArray2.default)(_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 = (0, _slicedToArray2.default)(_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-euigrid-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("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 = (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-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.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: "euiDataGridHeaderCell__content"
  }, /*#__PURE__*/_react.default.createElement(HeaderCellRender, null)));
};

exports.EuiDataGridControlHeaderCell = EuiDataGridControlHeaderCell;
EuiDataGridControlHeaderCell.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
};