import e from"/static/logging/index.js";const s=e.getLogger("@quotquot/style"),t=new class{constructor(){this.sheets={}}addSheet(e,t){let o=this.sheets[e];if(o)return o.promise?(s.debug(`stylesheet ${e} is loading`),o.promise.then((()=>{o.refcount++,s.debug(`stylesheet ${e} is loaded (${o.refcount})`)}))):(o.refcount++,s.debug(`stylesheet ${e} is cached (${o.refcount})`),Promise.resolve(o.sheet));const n=new CSSStyleSheet;this.sheets[e]=o={sheet:n,refcount:0};const h=fetch(e).then((e=>e.text())).then((e=>n.replace(e))).then((()=>(o.refcount++,s.debug(`stylesheet ${e} is fetched (${o.refcount})`),delete o.promise,n)));return h.catch((s=>delete this.sheets[e])),o.promise=h,h}async release(e){const t=this.sheets[e];t&&!t.promise?(t.refcount--,0===t.refcount&&(s.debug(`removing stylesheet ${e}`),delete this.sheets[e])):s.warn(`unknown stylesheet ${e}`)}},o="adoptedStyleSheets"in document;s.debug(`adoptedStyleSheets ${o?"":"not "}supported`);var n=o?class{constructor(e){this.sheets=new Map}async setup(e){await this._syncStyles(e.shadowRoot,e.state.styles)}async cleanup(e){for(const e of this.sheets.keys())t.release(e);e.shadowRoot.adoptedStyleSheets=[],this.sheets.clear()}async onBeforeUpdate(e,s){s.styles&&await this._syncStyles(e.shadowRoot,s.styles)}async _syncStyles(e,o){for(const e of this.sheets.keys())-1===o.indexOf(e)&&(s.debug(`removing style ${e}`),t.release(e),this.sheets.delete(e));for(const e of o)this.sheets.has(e)||(s.debug(`adding style ${e}`),this.sheets.set(e,await t.addSheet(e)));e.adoptedStyleSheets=this.sheets.values()}}:class{constructor(e){this.links=new Map}async setup(e){this._syncStyles(e.shadowRoot,e.state.styles)}async cleanup(e){for(const s of this.links.values())e.shadowRoot.removeChild(s);this.links.clear()}async onBeforeUpdate(e,s){s.styles&&this._syncStyles(e.shadowRoot,s.styles)}_syncStyles(e,t){for(const o of this.links.keys())-1===t.indexOf(o)&&(s.debug(`removing style ${o}`),e.removeChild(this.links.get(o)),this.links.delete(o));for(const e of t)if(!this.links.has(e)){s.debug(`adding style ${e}`);const t=document.createElement("link");t.rel="stylesheet",t.href=e,this.links.set(e,t)}for(const s of Array.from(t).reverse())e.insertBefore(this.links.get(s),e.firstChild)}};export{n as default};
