"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 = _interopRequireWildcard(require("react"));

var _keyCodes = require("../../accessibility-utils/keyCodes");

var _uniqueId = _interopRequireDefault(require("../../utils/uniqueId"));

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

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

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

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

var useAccessNavigationManager = function useAccessNavigationManager(props) {
  var configuration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var activecss = configuration.activecss,
      wrap = configuration.wrap,
      focus = configuration.focus,
      _configuration$keyNam = configuration.keyName,
      keyName = _configuration$keyNam === void 0 ? {} : _configuration$keyNam,
      grid = configuration.grid,
      onKeyDown = configuration.onKeyDown; //let [ activeDescendantValue,setActiveDescendantValue ] = useState();
  // class AccessNavigationManager extends React.Component{
  //     constructor(props){
  //super(props)
  //this.state = { activedescendantId : undefined }
  // this.rootEle = null;
  // this.uitype = null;
  // this.onKeyDownCallBack = null;
  // this.rootEleId = uniqueNumber();
  // this.getRootRef = this.getRootRef.bind(this);
  // this.currentNodeEle = null;
  // this.currentNodeIndex = 0;

  var rootEle = null; //const uitype = null;
  //const onKeyDownCallBack = null;

  var rootEleId = (0, _uniqueId["default"])();
  var currentNodeEle = null;
  var currentNodeIndex = 0;
  var isFocused; // this.focusGridView = this.focusGridView.bind(this);
  // this.focusFirst = this.focusFirst.bind(this);
  // this.getFocusableTree = this.getFocusableTree.bind(this);
  // this.defaultKeyPress = this.defaultKeyPress.bind(this);
  // this.getNextRowCurrentIndexEle = this.getNextRowCurrentIndexEle.bind(this);
  // this.getNextRowEle = this.getNextRowEle.bind(this);
  // this.focusManager = this.focusManager.bind(this);
  // this.wrapNextRowChangeIndex = this.wrapNextRowChangeIndex.bind(this);
  // this.setCurrentNodeIndex = this.setCurrentNodeIndex.bind(this);
  // this.getItemProps = this.getItemProps.bind(this);
  // this.keyMoving = this.keyMoving.bind(this);
  // this.navigationProps = this.navigationProps.bind(this);
  //}

  var getRootRef = function getRootRef() {
    if (rootEle === null) {
      rootEle = document.querySelector("[data-aria-rootid=\"".concat(rootEleId, "\"]"));
    }

    return rootEle;
  }; // useEffect(()=>{
  //     return ()=>{ rootEle = null }
  // },[])
  // componentWillUnmount(){
  //   rootEle = null;
  // }


  var wrapNextRowChangeIndex = function wrapNextRowChangeIndex(mode, node) {
    if (mode === 'next') {
      currentNodeIndex = 0;
    } else {
      /** not get parent children in Selection element */
      if (node.getAttribute("data-aria-row") === 'true' && !node.contains(currentNodeEle)) {
        currentNodeIndex = (node && node.querySelectorAll('[data-aria-col="true"]').length) + 1;
      }
    }
  };

  var getFocusableTree = function getFocusableTree(root, mode) {
    var walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, mode === 'next' || mode === 'previous' ? {
      acceptNode: function acceptNode(node) {
        if (node.getAttribute('data-aria-col') === 'true' || node.getAttribute('data-aria-item') === 'true') {
          return NodeFilter.FILTER_ACCEPT;
        } else {
          wrapNextRowChangeIndex(mode, node);
          return NodeFilter.FILTER_SKIP;
        }
      }
    } : mode === 'nextRow' ? {
      acceptNode: function acceptNode(node) {
        if (node.getAttribute('data-aria-row') === 'true') {
          return NodeFilter.FILTER_ACCEPT;
        } else {
          return NodeFilter.FILTER_SKIP;
        }
      }
    } : {
      acceptNode: function acceptNode(node) {
        if (node.getAttribute('data-aria-row') === 'true' && currentNodeIndex <= (node && node.querySelectorAll('[data-aria-col="true"]').length)) {
          return NodeFilter.FILTER_ACCEPT;
        } else {
          return NodeFilter.FILTER_SKIP;
        }
      }
    });
    return walker;
  };

  var focusManager = function focusManager(mode) {
    var nextNode;
    var rootEle = getRootRef();
    var walker = getFocusableTree(rootEle, mode); //slet { focusVisible,focusProps } = useFocusVisible({});

    var node = currentNodeEle ? currentNodeEle : walker.currentNode;

    if (rootEle.contains(node)) {
      walker.currentNode = node;
      nextNode = mode === 'next' ? walker.nextNode() : walker.previousNode();

      if (nextNode !== null) {
        currentNodeEle = nextNode;

        if (mode === 'next') {
          currentNodeIndex++;
        } else {
          currentNodeIndex--;
        }
      } else {
        if (wrap) {
          walker.currentNode = rootEle;
          nextNode = mode === 'next' ? walker.nextNode() : walker.lastChild();

          if (mode === 'next') {
            currentNodeIndex++;
          } else {
            currentNodeIndex--;
          }
        } else {
          return;
        }
      }

      walker.currentNode = node;

      if (walker.currentNode && currentNodeEle) {
        activecss && walker.currentNode.classList.remove(activecss); //walker.currentNode.setAttribute('aria-selected','false')
        //this.setState({ariaSelected:undefined})
      }
    }

    if (wrap) {
      currentNodeEle = nextNode;
    }

    if (currentNodeEle) {
      activecss && currentNodeEle.classList.add(activecss); //currentNodeEle.setAttribute('aria-selected','true')
      //this.setState({activedescendantId:this.currentNodeEle.id})
      //setActiveDescendantValue( ()=>{ return currentNodeEle.id } )

      !focus && currentNodeEle.scrollIntoView({
        block: 'nearest'
      });
      focus && currentNodeEle.focus();
    }

    return currentNodeEle;
  };

  var getNextRowCurrentIndexEle = function getNextRowCurrentIndexEle(nextSibling) {
    var walker = getFocusableTree(nextSibling, 'next');

    for (var i = 0; i < currentNodeIndex; i++) {
      currentNodeEle = walker.nextNode();
    }
  };

  var getNextRowEle = function getNextRowEle(mode, currentRoot, nextChildRow) {
    var rootEle = getRootRef();
    var gridWalker = getFocusableTree(rootEle, nextChildRow || 'nextRow');
    var node = currentNodeEle ? currentNodeEle : gridWalker.currentNode;
    var previousNode;

    if (rootEle.contains(node)) {
      gridWalker.currentNode = currentRoot || node;
      previousNode = gridWalker.currentNode;
    }

    gridWalker.parentNode();
    var nextSibling = mode === 'last' ? gridWalker.lastChild() : mode === 'next' ? gridWalker.nextNode() : gridWalker.previousNode();
    var nextSiblingChildLength = nextSibling && nextSibling.querySelectorAll('[data-aria-col="true"]').length || 0;
    return {
      nextSibling: nextSibling,
      previousNode: previousNode,
      nextSiblingChildLength: nextSiblingChildLength
    };
  };

  var focusGridView = function focusGridView(mode) {
    var rootEle = getRootRef();

    var _getNextRowEle = getNextRowEle(mode),
        nextSibling = _getNextRowEle.nextSibling,
        previousNode = _getNextRowEle.previousNode,
        nextSiblingChildLength = _getNextRowEle.nextSiblingChildLength;

    if (nextSibling !== null) {
      if (currentNodeIndex <= nextSiblingChildLength) {
        getNextRowCurrentIndexEle(nextSibling);
      } else {
        var _getNextRowEle2 = getNextRowEle(mode, '', 'nextChildRow'),
            _nextSibling = _getNextRowEle2.nextSibling;

        _nextSibling && getNextRowCurrentIndexEle(_nextSibling);
      }
    } else {
      if (wrap) {
        var _getNextRowEle3 = getNextRowEle(mode === 'next' ? 'next' : 'last', rootEle),
            _nextSibling2 = _getNextRowEle3.nextSibling,
            _nextSiblingChildLength = _getNextRowEle3.nextSiblingChildLength;

        if (currentNodeIndex <= _nextSiblingChildLength) {
          getNextRowCurrentIndexEle(_nextSibling2);
        }
      } else {
        return;
      }
    }

    if (previousNode && currentNodeEle && activecssf) {
      previousNode.classList.remove(activecss);
    }

    if (currentNodeEle && activecss) {
      currentNodeEle.classList.add(activecss);
      focus && currentNodeEle.focus();
    }
  };

  var setCurrentNodeIndex = function setCurrentNodeIndex() {
    var rootEle = getRootRef();
    var walkerRow = getFocusableTree(rootEle, 'nextRow');
    walkerRow.currentNode = currentNodeEle;
    var getChildNodes = walkerRow.parentNode();

    if (getChildNodes && getChildNodes.children) {
      Object.keys(getChildNodes.children).forEach(function (element, index) {
        if (getChildNodes.children[element] === currentNodeEle) {
          currentNodeIndex = index + 1;
        }
      });
    } else {
      return;
    }
  };

  var focusFirst = function focusFirst(itemId) {
    var rootEle = getRootRef();
    var from = rootEle.querySelector("[data-aria-itemid=\"".concat(itemId, "\"]"));
    var walker = getFocusableTree(rootEle, 'next');
    var node = currentNodeEle ? currentNodeEle : walker.currentNode;

    if (rootEle.contains(node) && activecss) {
      node && node.classList.remove(activecss);
    }

    if (!from) {
      currentNodeEle = walker.nextNode();
    } else {
      currentNodeEle = from;
      setCurrentNodeIndex();
    }

    if (currentNodeEle && activecss) {
      currentNodeEle.classList.add(activecss);
      focus && currentNodeEle.focus();
    }

    return currentNodeEle;
  };

  var keyMoving = function keyMoving(e, keys) {
    if (keys.toLowerCase() === 'left' || keys.toLowerCase() === 'up') {
      if (keys.toLowerCase() === 'up') {
        grid ? focusGridView('previous') : focusManager('previous');
        e && e.preventDefault();
      } else {
        focusManager('previous');
      }
    } else if (keys.toLowerCase() === 'right' || keys.toLowerCase() === 'down') {
      if (keys.toLowerCase() === 'down') {
        grid ? focusGridView('next') : focusManager('next');
        e && e.preventDefault();
      } else {
        focusManager('next');
      }
    } else if (keys.toLowerCase() === 'tabforward' || keys.toLowerCase() === 'tabbackward') {
      if (keys.toLowerCase() === 'tabforward') {
        e && e.preventDefault();
        focusManager('next');
      } else {
        focusManager('previous');
      }
    }
  };

  var defaultKeyPress = function defaultKeyPress(e) {
    onKeyDown && onKeyDown(e);
    var keyCode = e.keyCode;
    var arrowleft = _keyCodes.keyNames.arrowleft,
        arrowright = _keyCodes.keyNames.arrowright,
        arrowtop = _keyCodes.keyNames.arrowtop,
        arrowbottom = _keyCodes.keyNames.arrowbottom;
    var leftArrow = _keyCodes.keyCodes.leftArrow,
        rightArrow = _keyCodes.keyCodes.rightArrow,
        topArrow = _keyCodes.keyCodes.topArrow,
        bottomArrow = _keyCodes.keyCodes.bottomArrow;

    if (Object.keys(keyName).length) {
      Object.keys(keyName).forEach(function (keys) {
        keyName[keys].forEach(function (value) {
          if (value.indexOf('shift') !== -1 && event.shiftKey) {
            var splitedKey = value.split('+')[1];

            if (splitedKey.toLowerCase() === e.key.toLowerCase()) {
              keyMoving(e, keys);
            }
          } else {
            if (value.toLowerCase() === e.key.toLowerCase()) {
              keyMoving(e, keys);
            }
          }
        });
      });
    } else {
      if (keyCode === 37) {
        grid && focusManager('previous');
      }

      if (keyCode === 39) {
        grid && focusManager('next');
      }

      if (keyCode === 40) {
        e && e.preventDefault();
        grid && focusGridView('next');
        !grid && focusManager('next');
      }

      if (keyCode === 38) {
        e && e.preventDefault();
        grid && focusGridView('previous');
        !grid && focusManager('previous');
      }
    }

    if (keyCode === 13) {
      currentNodeEle && currentNodeEle.click();
    }
  };

  var getItemProps = function getItemProps(id) {
    //let { role,id,dataAriaItem={} } = props;
    var genratedRandomId = id || (0, _uniqueId["default"])();
    var dataAriaItems = {
      'data-aria-item': 'true',
      'data-aria-itemid': genratedRandomId,
      'onKeyDown': function onKeyDown(e) {
        defaultKeyPress(e);
      } //id : genratedRadomId, 
      //role,
      //'aria-selected' : this.state.ariaSelected,
      //...dataAriaItem

    };
    var dataAriaCol = {
      'data-aria-col': 'true',
      'data-aria-itemid': genratedRandomId,
      'onKeyDown': defaultKeyPress
    }; //   if(uitype === 'listbox' || uitype === 'grid'){
    //     dataAriaItems['onKeyDown'] = defaultKeyPress.bind(this,this.onKeyDownCallBack);
    //     dataAriaCol['onKeyDown'] = defaultKeyPress.bind(this,onKeyDownCallBack)
    //   }

    return {
      dataAriaCol: dataAriaCol,
      dataAriaColDisabled: {
        'data-aria-col': 'false',
        'aria-disabled': 'true'
      },
      dataAriaRow: {
        'data-aria-row': 'true'
      },
      dataAriaItem: dataAriaItems,
      dataAriaItemDisabled: {
        'data-aria-item': 'false',
        'aria-disabled': 'true'
      },
      itemId: genratedRandomId
    };
  };

  var navigationProps = function navigationProps() {
    //let { onKeyDown,type,popupOpen,listElementProps={},targetElementProps={},inputProps={} } = props || {};
    //uitype = type;
    //onKeyDownCallBack = onKeyDown;
    //let rootElementProps = {};
    //   let listElementProp = {
    //     role: 'listbox', 
    //     id: rootEleId,
    //     ...listElementProps
    //   }
    //  rootElementProps
    //   if(type === 'combobox'){
    //     //rootElementProps['role'] = "combobox"; 
    //     //rootElementProps['aria-owns'] = this.rootEleId;
    //     rootElementProps['data-aria-rootid'] = rootEleId
    //   }
    //   else if(type === 'grid'){
    //     rootElementProps['role'] = "grid"; 
    //     rootElementProps['data-aria-rootid'] = rootEleId
    //   }
    //   else{
    //     listElementProp['aria-activedescendant'] = activeDescendantValue
    //     rootElementProps['data-aria-rootid'] = rootEleId
    //   }
    return {
      rootElementProps: {
        'data-aria-rootid': rootEleId
      },
      focusFirst: focusFirst,
      //focusManager : focusManager,
      inputProps: {
        onKeyDown: defaultKeyPress //   'aria-activedescendant' : activeDescendantValue,
        //   'aria-owns' : rootEleId,
        //   'role':'combobox', 
        //   ...inputProps

      },
      getItemProps: getItemProps,
      isFocused: isFocused //listElementProps : listElementProp,
      // targetElementProps:{
      //   'aria-controls' : rootEleId,
      //   'aria-haspopup': listElementProps.role ||'listbox',
      //   'aria-expanded': popupOpen ? 'true' : 'false',
      //   ...targetElementProps
      // }  

    };
  };

  return navigationProps(); // render(){
  //     return <WrappedComponent navigationProps={this.navigationProps}/>
  // }
  //}
  // return hoistStatics(AccessNavigationManager,WrappedComponent);
};

var _default = useAccessNavigationManager; // if (__DOCS__) {
//   AccessNavigationManager.docs = {
//     componentGroup: componentGroups.Components,
//     folderName : componentCategories.Accessibility
//   };
// }

exports["default"] = _default;