import{getTabbableElements as e}from"./chunk.I7QNFR2M.js";function*activeElements(e=document.activeElement){null!=e&&(yield e,"shadowRoot"in e&&e.shadowRoot&&"closed"!==e.shadowRoot.mode&&(yield*activeElements(e.shadowRoot.activeElement)))}var t=[],n=class{constructor(t){this.tabDirection="forward",this.handleFocusIn=()=>{this.checkFocus()},this.handleKeyDown=t=>{var n;if("Tab"!==t.key)return;t.shiftKey?this.tabDirection="backward":this.tabDirection="forward",t.preventDefault();const s=e(this.element),i=s[0];let o=this.startElementAlreadyFocused(i)?0:this.currentFocusIndex;if(-1===o)return this.currentFocus=i,void this.currentFocus.focus({preventScroll:!0});const c="forward"===this.tabDirection?1:-1;o+c>=s.length?o=0:this.currentFocusIndex+c<0?o=s.length-1:o+=c,this.currentFocus=s[o],null==(n=this.currentFocus)||n.focus({preventScroll:!0}),setTimeout((()=>this.checkFocus()))},this.handleKeyUp=()=>{this.tabDirection="forward"},this.element=t}activate(){t.push(this.element),document.addEventListener("focusin",this.handleFocusIn),document.addEventListener("keydown",this.handleKeyDown),document.addEventListener("keyup",this.handleKeyUp)}deactivate(){t=t.filter((e=>e!==this.element)),this.currentFocus=null,document.removeEventListener("focusin",this.handleFocusIn),document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("keyup",this.handleKeyUp)}isActive(){return t[t.length-1]===this.element}checkFocus(){if(this.isActive()){const t=e(this.element);if(!this.element.matches(":focus-within")){const e=t[0],n=t[t.length-1],s="forward"===this.tabDirection?e:n;"function"==typeof(null==s?void 0:s.focus)&&(this.currentFocus=s,s.focus({preventScroll:!0}))}}}get currentFocusIndex(){return e(this.element).findIndex((e=>e===this.currentFocus))}startElementAlreadyFocused(e){for(const t of activeElements())if(e===t)return!0;return!1}};export{n as Modal};