import{useCallback as e,useMemo as t,useEffect as n,useRef as s}from"react";import i from"../useKeyEvent/index.js";import o from"../useEventListener/index.js";import u from"../usePrevious/index.js";import{getNextSelectableIndex as c,getPreviousSelectableIndex as r}from"./useActiveDescendantListFocusHelpers.js";import{useListenFocusTriggers as l}from"../useListenFocusTriggers/index.js";var a;!function(e){e.UP="ArrowUp",e.DOWN="ArrowDown",e.RIGHT="ArrowRight",e.LEFT="ArrowLeft"}(a||(a={}));function m(t){var n=t.itemsCount,s=t.focusedElementRef,o=t.visualFocusItemIndex,u=t.setVisualFocusItemIndex,l=t.isHorizontalList,m=t.isItemSelectable,I=t.listenerOptions,d=t.triggeredByKeyboard,f=l?a.RIGHT:a.DOWN,v=l?a.LEFT:a.UP,x=e((function(e){var t;document.activeElement===s.current&&(!d.current&&(d.current=!0,o>-1)||(e===f?t=c({isItemSelectable:m,visualFocusItemIndex:o,itemsCount:n}):e===v&&(t=r({isItemSelectable:m,visualFocusItemIndex:o,itemsCount:n})),t>-1&&t!==o&&u(t)))}),[s,d,f,v,o,u,m,n]),F=e((function(){x(v)}),[v,x]),b=e((function(){x(f)}),[f,x]);i(Object.assign({keys:[f],callback:b},I)),i(Object.assign({keys:[v],callback:F},I))}function I(n){var s=n.visualFocusItemIndex,o=n.focusedElementRef,u=n.itemsCount,c=n.setVisualFocusItemIndex,r=n.onItemClick,l=n.isItemSelectable,a=n.listenerOptions,m=void 0===a?void 0:a,I=n.isIgnoreSpaceAsItemSelection,d=void 0!==I&&I,f=t((function(){return d?["Enter"]:["Enter"," "]}),[d]),v=e((function(e,t){r&&(t>=0&&u>t)&&l(t)&&(s!==t&&c(t),r(e,t))}),[u,r,l,s,c]),x=e((function(e){o.current.contains(document.activeElement)&&v(e,s)}),[v,o,s]);i(Object.assign({keys:f,callback:x},m))}function d(t){var s=t.focusedElementRef,i=t.visualFocusItemIndex,c=t.setVisualFocusItemIndex,r=u(s),l=e((function(){-1!==i&&c(-1)}),[c,i]);n((function(){null===(null==s?void 0:s.current)&&null!==(null==r?void 0:r.current)&&l()}),[s.current,r,l]),o({eventName:"blur",ref:s,callback:l})}function f(t){var n=t.focusedElementRef,i=t.isItemSelectable,o=t.visualFocusItemIndex,u=t.setVisualFocusItemIndex,r=t.itemsCount,a=t.defaultVisualFocusItemIndex,m=void 0===a?-1:a,I=s(!1),d=e((function(){var e;(I.current=!0,o!==m)&&(e=i(m)?m:c({isItemSelectable:i,itemsCount:r,visualFocusItemIndex:m}),u(e))}),[m,i,r,u,I,o]),f=e((function(){I.current=!1}),[I]);return l({ref:n,onFocusByKeyboard:d,onFocusByMouse:f}),{triggeredByKeyboard:I}}function v(e){var t=e.visualFocusItemIndex,s=e.itemsIds,i=e.isItemSelectable,o=e.setVisualFocusItemIndex,r=u(s);n((function(){var e;void 0!==r&&r!==s&&void 0!==r&&-1!==t?e=s.indexOf(r[t]):e=t;if(e!==t)if(i(e))o(e);else{var n=c({isItemSelectable:i,visualFocusItemIndex:e,itemsCount:s.length});o(n)}}),[t,s,i,o,r])}export{d as useCleanVisualFocusOnBlur,v as useKeepFocusOnItemWhenListChanged,f as useSetDefaultItemOnFocusEvent,m as useSupportArrowsKeyboardNavigation,I as useSupportPressItemKeyboardNavigation};
