UNPKG

tiny-essentials

Version:

Collection of small, essential scripts designed to be used across various projects. These simple utilities are crafted for speed, ease of use, and versatility.

1 lines 2.61 kB
(()=>{"use strict";var e={d:(t,r)=>{for(var s in r)e.o(r,s)&&!e.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:r[s]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};e.d(t,{TinyElementObserver:()=>r});const r=class{#e;get el(){return this.#e}set el(e){if(this.#e)throw new Error("The observed element has already been set and cannot be reassigned.");if(void 0!==e&&!(e instanceof Element))throw new TypeError("The observed element must be a valid DOM Element.");this.#e=e}#t={};get settings(){return this.#t}set settings(e){if("object"!=typeof e||null===e)throw new TypeError("settings must be a non-null object.");this.#t=e}#r=null;get observer(){return this.#r}#s=[];get detectors(){return this.#s.map(e=>[e[0],e[1]])}set detectors(e){if(!Array.isArray(e))throw new TypeError("detectors must be an array.");const t=[];for(const[r,s]of e){if("string"!=typeof r)throw new TypeError("Detector name must be a string.");if("function"!=typeof s)throw new TypeError(`Detector handler for "${r}" must be a function.`);t.push([r,s])}this.#s=t}get isActive(){return!!this.#r}get size(){return this.#s.length}constructor({el:e,initDetectors:t=[],initCfg:r={}}={}){this.el=e,t.length&&(this.detectors=t),r&&(this.settings=r)}clear(){this.#s=[]}start(){if(!this.#e)throw new Error("Cannot start observation: no target element has been set.");this.#r||(this.#r=new MutationObserver(e=>{e.forEach((e,t,r)=>this.#s.forEach(s=>s[1](e,t,r)))}),this.#r.observe(this.#e,this.#t))}stop(){this.#r&&(this.#r.disconnect(),this.#r=null)}add(e,t){this.#o(e,t),this.#s.push([e,t])}insertAtStart(e,t){this.#o(e,t),this.#s.unshift([e,t])}insertAt(e,t,r,s="after"){if(this.#o(t,r),"number"!=typeof e||e<0||e>=this.#s.length)throw new RangeError("Invalid index for insertDetectorAt.");const o="before"===s?e:e+1;this.#s.splice(o,0,[t,r])}removeAt(e){if("number"!=typeof e||e<0||e>=this.#s.length)throw new RangeError("Invalid index for removeDetectorAt.");this.#s.splice(e,1)}removeAround(e,t=0,r=0){if("number"!=typeof e||e<0||e>=this.#s.length)throw new RangeError("Invalid index for removeDetectorsAround.");const s=Math.max(0,e-t),o=t+1+r;this.#s.splice(s,o)}isIndexUsed(e){return e>=0&&e<this.#s.length}hasHandler(e){if("function"!=typeof e)throw new TypeError("Handler must be a function.");return this.#s.some(([t,r])=>r===e)}#o(e,t){if("string"!=typeof e||!e.trim())throw new TypeError("Detector name must be a non-empty string.");if("function"!=typeof t)throw new TypeError(`Detector handler for "${e}" must be a function.`)}destroy(){this.stop(),this.clear()}};window.TinyElementObserver=t.TinyElementObserver})();