@spectrum-web-components/reactive-controllers
Version:
ReactiveControllers for powering common UI patterns
3 lines (2 loc) • 1.76 kB
JavaScript
"use strict";export const elementResolverUpdatedSymbol=Symbol("element resolver updated");export class ElementResolutionController{constructor(e,{selector:t}={selector:""}){this._element=null;this._selector="";this.mutationCallback=e=>{let t=!1;e.forEach(s=>{if(!t){if(s.type==="childList"){const r=this.element&&[...s.removedNodes].includes(this.element),l=!!this.selector&&[...s.addedNodes].some(this.elementIsSelected);t=t||r||l}if(s.type==="attributes"){const r=s.target===this.element,l=!!this.selector&&this.elementIsSelected(s.target);t=t||r||l}}}),t&&this.resolveElement()};this.elementIsSelected=e=>{var t;return this.selectorIsId?(e==null?void 0:e.id)===this.selectorAsId:(t=e==null?void 0:e.matches)==null?void 0:t.call(e,this.selector)};this.host=e,this.selector=t,this.observer=new MutationObserver(this.mutationCallback),this.host.addController(this)}get element(){return this._element}set element(e){if(e===this.element)return;const t=this.element;this._element=e,this.host.requestUpdate(elementResolverUpdatedSymbol,t)}get selector(){return this._selector}set selector(e){e!==this.selector&&(this.releaseElement(),this._selector=e,this.resolveElement())}get selectorAsId(){return this.selector.slice(1)}get selectorIsId(){return!!this.selector&&this.selector.startsWith("#")}hostConnected(){this.resolveElement(),this.observer.observe(this.host.getRootNode(),{subtree:!0,childList:!0,attributes:!0})}hostDisconnected(){this.releaseElement(),this.observer.disconnect()}resolveElement(){if(!this.selector){this.releaseElement();return}const e=this.host.getRootNode();this.element=this.selectorIsId?e.getElementById(this.selectorAsId):e.querySelector(this.selector)}releaseElement(){this.element=null}}
//# sourceMappingURL=ElementResolution.js.map