import{appendStyle}from"./utils/append-style.js";import{XElement}from"./XElement.js";let _observer=null;const _storedScrollPositions=new WeakMap;export class XWidget extends XElement{constructor(){super(),this.style.setProperty("display","flex"),this.style.setProperty("flex-direction","column"),this.style.setProperty("align-items","stretch"),this.style.setProperty("justify-content","flex-start"),this.style.setProperty("contain","layout style"),this._visible=!1,this._shadowRoot,this._defaultFocusedElement=null,this._elementsToRestoreScrollPositionsFor=[],this._onShownCallback,this._onHiddenCallback,this._onResizedCallback,_observer||(_observer=new ResizeObserver((e=>{for(const s of e){const e=s.target;e._visible&&e._onResizedCallback&&e._onResizedCallback.call(null)}}))),_observer.observe(this),this.setElementsToRestoreScrollPositionsFor([this])}isShowing(){return this._visible}registerRequiredCSS(e,s){appendStyle(this._shadowRoot||this,e,s)}setOnShown(e){this._onShownCallback=e}setOnHidden(e){this._onHiddenCallback=e}setOnResized(e){this._onResizedCallback=e}setElementsToRestoreScrollPositionsFor(e){for(const s of this._elementsToRestoreScrollPositionsFor)s.removeEventListener("scroll",XWidget._storeScrollPosition,{capture:!1});this._elementsToRestoreScrollPositionsFor=e;for(const s of this._elementsToRestoreScrollPositionsFor)s.addEventListener("scroll",XWidget._storeScrollPosition,{passive:!0,capture:!1})}restoreScrollPositions(){for(const e of this._elementsToRestoreScrollPositionsFor){const s=_storedScrollPositions.get(e);s&&(e.scrollTop=s.scrollTop,e.scrollLeft=s.scrollLeft)}}static _storeScrollPosition(e){const s=e.currentTarget;_storedScrollPositions.set(s,{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop})}setDefaultFocusedElement(e){if(e&&!this.isSelfOrAncestor(e))throw new Error("Default focus must be descendant");this._defaultFocusedElement=e}focus(){if(!this._visible)return;let e;if(this._defaultFocusedElement&&this.isSelfOrAncestor(this._defaultFocusedElement))e=this._defaultFocusedElement;else if(-1!==this.tabIndex)e=this;else{let s=this.traverseNextNode(this);for(;s;){if(s instanceof XWidget&&s._visible){e=s;break}s=s.traverseNextNode(this)}}e&&!e.hasFocus()&&(e===this?HTMLElement.prototype.focus.call(this):e.focus())}connectedCallback(){this._visible=!0,this.restoreScrollPositions(),this._onShownCallback&&this._onShownCallback.call(null)}disconnectedCallback(){this._visible=!1,this._onHiddenCallback&&this._onHiddenCallback.call(null)}}self.customElements.define("x-widget",XWidget);