import{slicedToArray as e}from"../../_virtual/_rollupPluginBabelHelpers.js";import{useState as n,useRef as o,useContext as t,useEffect as i,useCallback as r}from"react";import{GridKeyboardNavigationContext as u}from"../../components/GridKeyboardNavigationContext/GridKeyboardNavigationContext.js";import a from"../useFullKeyboardListeners.js";import c from"../useEventListener/index.js";import{getActiveIndexFromInboundNavigation as s,calcActiveIndexAfterArrowNavigation as f}from"./gridKeyboardNavigationHelper.js";import{useLastNavigationDirection as d}from"../../components/Menu/Menu/hooks/useLastNavigationDirection.js";function l(l){var m=l.ref,v=l.itemsCount,b=l.numberOfItemsInLine,I=l.onItemClicked,p=l.getItemByIndex,x=void 0===p?function(e){}:p,g=l.focusOnMount,N=void 0!==g&&g,O=l.focusItemIndexOnMount,y=void 0===O?-1:O,j=l.disabledIndexes,C=void 0===j?[]:j,L=n(N&&-1!==y),k=e(L,2),K=k[0],M=k[1],A=o(!1),S=n(K?y:-1),h=e(S,2),w=h[0],B=h[1],D=n(!0),E=e(D,2),G=E[0],H=E[1],_=t(u);i((function(){A.current?M(!1):A.current=!0}),[w]);var F=r((function(){var e;return null===(e=m.current)||void 0===e?void 0:e.blur()}),[m]),P=d().lastNavigationDirectionRef,R=r((function(){var e=P.current;if(e){if(-1===w){var n=s({direction:e,numberOfItemsInLine:b,itemsCount:v});B(n)}H(!0)}else-1===w&&B(0)}),[w,v,P,b]),T=r((function(){H(!1)}),[H]),q=r((function(){H(!0),B(-1)}),[B]);c({eventName:"focus",callback:R,ref:m}),c({eventName:"mousedown",callback:T,ref:m}),c({eventName:"blur",callback:q,ref:m}),i((function(){var e;w>-1&&(null===(e=m.current)||void 0===e||e.focus())}),[w,m]);var z=r((function(e){var n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];H(n),B(e),I(x(e),e)}),[B,I,x]),J=r((function(){if(G)return z(w,!0)}),[G,z,w]);return a({ref:m,onSelectionKey:J,onArrowNavigation:function(e){if(H(!0),-1!==w){var n=f({activeIndex:w,itemsCount:v,numberOfItemsInLine:b,direction:e,disabledIndexes:C}),o=n.nextIndex;n.isOutbound?null==_||_.onOutboundNavigation(m,e):B(o)}else B(0)},onEscape:F,focusOnMount:N}),{activeIndex:G?w:-1,onSelectionAction:z,isInitialActiveState:K}}export{l as default};
