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

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

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

var _keyBoardShortCut = _interopRequireDefault(require("../../accessibility-utils/keyBoardShortCut"));

var _keyNavigator = _interopRequireDefault(require("../../accessibility-utils/keyNavigator"));

var _Box = _interopRequireDefault(require("../layout/Box"));

var _AccessibilityControlPropTypes = _interopRequireWildcard(require("./AccessibilityControl.propTypes.js"));

var _AccessibilityControlModule = _interopRequireDefault(require("./AccessibilityControl.module.css"));

var _componentCategories = _interopRequireDefault(require("../../docs-utils/componentCategories"));

var _componentGroups = _interopRequireDefault(require("../../docs-utils/componentGroups"));

var _focusVisibleContext = _interopRequireDefault(require("../../accessibility-utils/focusVisibleContext"));

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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

var AccessibilityControl = /*#__PURE__*/function (_React$Component) {
  _inherits(AccessibilityControl, _React$Component);

  var _super = _createSuper(AccessibilityControl);

  function AccessibilityControl(props) {
    var _this;

    _classCallCheck(this, AccessibilityControl);

    _this = _super.call(this, props);
    _this.state = {
      hadKeyboardEvent: true
    };
    _this.isValidFocusTarget = _this.isValidFocusTarget.bind(_assertThisInitialized(_this));
    _this.addFocusVisibleClass = _this.addFocusVisibleClass.bind(_assertThisInitialized(_this));
    _this.removeFocusVisibleClass = _this.removeFocusVisibleClass.bind(_assertThisInitialized(_this));
    _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this));
    _this.onPointerDown = _this.onPointerDown.bind(_assertThisInitialized(_this));
    _this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this));
    _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this));
    _this.handleEventListner = _this.handleEventListner.bind(_assertThisInitialized(_this));
    _this.getEle = null;
    return _this;
  }

  _createClass(AccessibilityControl, [{
    key: "handleEventListner",
    value: function handleEventListner() {
      var _this2 = this;

      var ele = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
      var handleType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "addEventListener";
      var eventDetails = [{
        name: "keydown",
        functionName: "onKeyDown"
      }, {
        name: "mousedown",
        functionName: "onPointerDown"
      }, {
        name: "pointerdown",
        functionName: "onPointerDown"
      }, {
        name: "touchstart",
        functionName: "onPointerDown"
      }, {
        name: "focus",
        functionName: "onFocus"
      }, {
        name: "blur",
        functionName: "onBlur"
      }];
      eventDetails.forEach(function (eventDetail, i) {
        var name = eventDetail.name,
            functionName = eventDetail.functionName;

        if (ele) {
          ele[handleType](name, _this2[functionName], true);
        }
      });
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      var bindEvent = this.props.bindEvent;
      var handleEvent = bindEvent == "document" ? document : this.getEle;
      this.handleEventListner(handleEvent, "addEventListener");
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      var bindEvent = this.props.bindEvent;
      var handleEvent = bindEvent == "document" ? document : this.getEle;
      this.handleEventListner(handleEvent, "removeEventListener");
      this.removeFocusVisibleClass(document.activeElement);
    }
  }, {
    key: "isValidFocusTarget",
    value: function isValidFocusTarget(el) {
      if (el && el !== document && el.nodeName !== "HTML" && el.nodeName !== "BODY" && "classList" in el && "contains" in el.classList && document.activeElement.dataset.accessibilityRoot !== "true") {
        return true;
      }

      return false;
    }
  }, {
    key: "addFocusVisibleClass",
    value: function addFocusVisibleClass(el) {
      var _this$props$customCla = this.props.customClassName,
          customClassName = _this$props$customCla === void 0 ? {} : _this$props$customCla;
      var _customClassName$focu = customClassName.focuscss,
          focuscss = _customClassName$focu === void 0 ? _AccessibilityControlModule["default"].focusVisible : _customClassName$focu;
      var customFocusCss = el.getAttribute("data-aria-focusstyle");

      if (el.hasAttribute("data-focus-added")) {
        return;
      }

      if (customFocusCss) {
        el.classList.add(customFocusCss);
      } else {
        el.classList.add(focuscss);
      }

      el.setAttribute("data-focus-added", "");
    }
  }, {
    key: "removeFocusVisibleClass",
    value: function removeFocusVisibleClass(el) {
      var _this$props$customCla2 = this.props.customClassName,
          customClassName = _this$props$customCla2 === void 0 ? {} : _this$props$customCla2;
      var _customClassName$focu2 = customClassName.focuscss,
          focuscss = _customClassName$focu2 === void 0 ? _AccessibilityControlModule["default"].focusVisible : _customClassName$focu2;
      var customFocusCss = el.getAttribute("data-aria-focusstyle");

      if (!el.hasAttribute("data-focus-added")) {
        return;
      }

      if (customFocusCss) {
        el.classList.remove(customFocusCss);
      } else {
        el.classList.remove(focuscss);
      }

      el.removeAttribute("data-focus-added");
    }
  }, {
    key: "onKeyDown",
    value: function onKeyDown(e) {
      var _this$props = this.props,
          defaultAriaShortCut = _this$props.defaultAriaShortCut,
          customAriaShortCut = _this$props.customAriaShortCut,
          isKeyNavigation = _this$props.isKeyNavigation;
      var currentActiveEle = document.activeElement;

      if (e.metaKey || e.altKey || e.ctrlKey) {
        return;
      }

      if (this.isValidFocusTarget(currentActiveEle)) {
        this.addFocusVisibleClass(currentActiveEle);
      }

      this.setState({
        hadKeyboardEvent: true
      });
      (0, _keyBoardShortCut["default"])(e, currentActiveEle, defaultAriaShortCut, customAriaShortCut);
      isKeyNavigation && (0, _keyNavigator["default"])(e, currentActiveEle);
    }
  }, {
    key: "onPointerDown",
    value: function onPointerDown(e) {
      this.setState({
        hadKeyboardEvent: false
      });
      this.removeFocusVisibleClass(e.target);
    }
  }, {
    key: "onFocus",
    value: function onFocus(e) {
      if (!this.isValidFocusTarget(e.target)) {
        return;
      }

      if (this.state.hadKeyboardEvent) {
        this.addFocusVisibleClass(e.target);
      }
    }
  }, {
    key: "onBlur",
    value: function onBlur(e) {
      if (!this.isValidFocusTarget(e.target)) {
        return;
      }

      if (e.target.hasAttribute("data-focus-added")) {
        this.removeFocusVisibleClass(e.target);
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;

      var _this$props2 = this.props,
          children = _this$props2.children,
          _this$props2$customCl = _this$props2.customClassName,
          customClassName = _this$props2$customCl === void 0 ? {} : _this$props2$customCl,
          bindEvent = _this$props2.bindEvent,
          focusLoop = _this$props2.focusLoop,
          autoFocus = _this$props2.autoFocus;
      var hadKeyboardEvent = this.state.hadKeyboardEvent;
      var _customClassName$box = customClassName.box,
          box = _customClassName$box === void 0 ? "" : _customClassName$box;

      if (bindEvent == "document") {
        return /*#__PURE__*/_react["default"].createElement(_focusVisibleContext["default"].Provider, {
          value: {
            hadKeyboardEvent: hadKeyboardEvent,
            isInitialized: true
          }
        }, /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, " ", children, " "));
      } else {
        return /*#__PURE__*/_react["default"].createElement(_focusVisibleContext["default"].Provider, {
          value: {
            hadKeyboardEvent: hadKeyboardEvent,
            isInitialized: true
          }
        }, /*#__PURE__*/_react["default"].createElement(_Box["default"], {
          focusLoop: focusLoop,
          autoFocus: autoFocus,
          eleRef: function eleRef(ele) {
            _this3.getEle = ele;
          },
          "data-accessibility-root": true,
          className: _AccessibilityControlModule["default"].common + " " + box
        }, children));
      }
    }
  }]);

  return AccessibilityControl;
}(_react["default"].Component);

exports["default"] = AccessibilityControl;
AccessibilityControl.propTypes = _AccessibilityControlPropTypes["default"];
AccessibilityControl.defaultProps = _AccessibilityControlPropTypes.defaultPropTypes;
AccessibilityControl.propsDescription = _AccessibilityControlPropTypes.propsDescription;

if (false) {
  AccessibilityControl.docs = {
    componentGroup: _componentGroups["default"].Components,
    folderName: _componentCategories["default"].Accessibility
  };
}