eyeejs
Version:
Library that make document manipulation a lot easier
1 lines • 11.9 kB
JavaScript
function getEvent(e,t={}){switch(e){case"click":case"dblclick":case"mousedown":case"mouseup":case"mousemove":case"mouseenter":case"mouseleave":case"mouseover":case"mouseout":return new MouseEvent(e,t);case"pointerdown":case"pointerup":case"pointermove":case"pointerenter":case"pointerleave":case"pointerover":case"pointerout":return new PointerEvent(e,t);case"keydown":case"keyup":case"keypress":return new KeyboardEvent(e,t);case"focus":case"blur":case"focusin":case"focusout":return new FocusEvent(e,t);case"input":case"change":case"submit":case"reset":return new Event(e,t);case"wheel":return new WheelEvent(e,t);case"copy":case"cut":case"paste":return new ClipboardEvent(e,t);case"scroll":case"resize":return new UIEvent(e,t);default:return new CustomEvent(e,t)}}const events=["click","dblclick","mousedown","mouseup","mousemove","mouseenter","mouseleave","mouseover","mouseout","contextmenu","keydown","keypress","keyup","focus","blur","focusin","focusout","submit","change","input","reset","select","touchstart","touchend","touchmove","touchcancel","pointerdown","pointerup","pointermove","pointerenter","pointerleave","pointercancel","dragstart","dragend","dragenter","dragover","dragleave","drop","resize","scroll","load","beforeunload","unload","play","pause","ended","volumechange","timeupdate","copy","cut","paste","animationstart","animationend","animationiteration","transitionstart","transitionend","DOMSubtreeModified","DOMNodeInserted","DOMNodeRemoved","error","hashchange","popstate"],htmlElements=["base","head","link","meta","style","title","body","address","article","aside","footer","header","h1","h2","h3","h4","h5","h6","main","nav","section","blockquote","dd","div","dl","dt","figcaption","figure","hr","li","ol","p","pre","ul","a","abbr","b","bdi","bdo","br","cite","code","data","dfn","em","i","kbd","mark","q","rp","rt","ruby","s","samp","small","span","strong","sub","sup","time","u","var","wbr","area","audio","img","map","track","video","embed","iframe","object","picture","portal","source","canvas","noscript","script","del","ins","caption","col","colgroup","table","tbody","td","tfoot","th","thead","tr","button","datalist","fieldset","form","input","label","legend","meter","optgroup","option","output","progress","select","textarea","details","dialog","summary","slot","template"];function flat(e){let t="";for(let n=0;n<e.length;n++){const s=e[n];s===s.toUpperCase()&&s!==s.toLowerCase()?t+="-"+s:t+=s}return t.toLowerCase()}function cmcl(e,t){let n=[];for(const s in t){const i=t[s],[r,a]=s.split(":"),[o,...c]=r.split(".");let[l=null,u=null]=(a||"").split("-").map((e=>e.trim())),h=eye(o.trim(),{class:c,parent:e,data:a?{value:l}:void 0});a&&l&&n.push({name:l,set:function(e,t){e.querySelector(`[data-value="${l}"]`).textContent=t??u}}),!i||"object"!=typeof i||i instanceof Array||(n=n.concat(cmcl(h,i)))}return n}let delegationEvents=["click","submit","input","change","keydown","keyup","keypress","focusin","focusout","mouseover","mouseout"];function EyeElement(){this.raw=null,this.length=0,this.datacollection=new WeakMap,this.dlgListeners=new Map}function eye(e,t,n){if("string"==typeof e&&0===e.indexOf("model:")){if(!t)return console.error("[EyeJS] Model creation requires parameter 'attr' as prototype, none delivered!");let[n,...s]=e.split(":")[1].split(" ").filter((e=>""!=e)),i=eye("div",{class:"eye-model "+n+" "+s.join(" "),data:{model:n,eyeModel:n}}),r=cmcl(i,t);return e=>{let t=i.clone(e?.parent);return t.refresh=function(e={}){let n=!1!==e.default;return r.forEach((s=>{(!0===n||!n&&e.hasOwnProperty(s.name))&&s.set(t,e[s.name])})),this},t.refresh(e)}}return(new EyeElement).init(e,t,n)}EyeElement.prototype={init:function(e,t,n){let s=this;if(e instanceof HTMLElement)this.raw=e;else if(htmlElements.includes(e))this.raw=document.createElement(e);else{let t="!"===e.slice(-1);if(this.raw=document.querySelectorAll(t?e.slice(0,-1):e),this.length=this.raw.length,0==this.length)return null;(1==this.length||t)&&(this.raw=this.raw.item(0))}function i(e){let t=e.type,n=s.dlgListeners,i=e.target,r=this;if(n.has(t)){let s=n.get(t);s?.forEach((({callback:t,target:n})=>{i.closest(n)&&t(e,r)}))}}return(this.raw instanceof NodeList?[...this.raw.entries()]:[[0,this.raw]]).forEach((([e,s])=>{let r=null;if(t)for(const e in t){const n=t[e];if("class"==e)s.classList.add.apply(s.classList,(n instanceof Array?n:n.split(" ")).filter((e=>""!=e)));else if("text"==e)s.textContent=n;else if("html"==e)s.innerHTML=n;else if("data"==e)for(const e in n)s.dataset[e]=n[e];else"parent"==e?r=n:e in s?s[e]=n:"_"!=e[0]&&s.setAttribute(e,s)}if(n)for(const e in n)-1!=e.indexOf("-")?s.style[e]=n[e]:s.style[flat(e)]=n[e];(r instanceof EyeElement||r instanceof HTMLElement)&&r.append(s),delegationEvents.forEach((e=>{s.addEventListener(e,i)}))})),events.forEach((e=>{s[e]=function(t){return t?"function"==typeof t&&s.on(e,t):s.trigger(e),s}})),this},each:function(e){let t=this;return(this.raw instanceof NodeList?[...this.raw.entries()]:[[0,this.raw]]).forEach((([n,s])=>{e(s,n,t)})),this},html:function(e){let t="";return(this.raw instanceof NodeList?[...this.raw.entries()]:[[0,this.raw]]).forEach((([n,s])=>{if(!e)return t=s.innerHTML;s.innerHTML=e})),t||this},text:function(e){let t="";return(this.raw instanceof NodeList?[...this.raw.entries()]:[[0,this.raw]]).forEach((([n,s])=>{if(!e)return t=s.textContent;s.textContent=e})),t||this},data:function(e,t){if(e){if(!t)return this.datacollection.get(e);this.datacollection.set(e,t)}return this},attr:function(e,t){let n="";return(this.raw instanceof NodeList?[...this.raw.entries()]:[[0,this.raw]]).forEach((([s,i])=>{if(0===e.indexOf("data-")){let[s,r]=e.split("-").map((e=>e.trim()));if(null==t)return n=i.dataset[r];i.dataset[r]=t}else if(e in i){if(null==t)return n=i[e];i[e]=t}else if("_"!=e[0]){if(null==t)return n=i.getAttribute(e);i.setAttribute(e,t)}})),n||this},class:function(e){let t="";return(this.raw instanceof NodeList?[...this.raw.entries()]:[[0,this.raw]]).forEach((([n,s])=>{if("number"==typeof e)return t=s.classList.item(e);e.split(" ").forEach((e=>{"-"==e[0]?s.classList.remove(e.substring(1,e.length)):"%"==e[0]?s.classList.toggle(e.substring(1,e.length)):"?"==e[0]?t=s.classList.contains(e.substring(1,e.length)):-1!=e.indexOf("/")?([v1,v2]=e.split("/"),s.classList.replace(v1,v2)):s.classList.add(e.substring(1,e.length))}))})),t||this},show:function(e){return(this.raw instanceof NodeList?[...this.raw.entries()]:[[0,this.raw]]).forEach((([t,n])=>{n.style.display=e??"inline-block"})),this},hide:function(e){return(this.raw instanceof NodeList?[...this.raw.entries()]:[[0,this.raw]]).forEach((([t,n])=>{e?n.style.opacity=0:n.style.display="none"})),this},append:function(e,t){let n=[];if((Array.isArray(e)?e:[e]).forEach((e=>{e instanceof EyeElement?n.push(e.raw):e instanceof HTMLElement&&n.push(e)})),this.raw instanceof NodeList)return console.warn("[EyeJS] beware while using .append with multi selected elements"),this.raw.forEach(((e,t)=>{n[t]&&e.append(n[t])})),this;if(t)switch(t){case"next":case"after":this.raw.after(...n);break;case"previous":case"before":this.raw.before(...n)}else this.raw.append(...n);return this},replaceWith:function(...e){let t=[];return(Array.isArray(e)?e:[e]).forEach((e=>{e instanceof EyeElement?t.push(e.raw):e instanceof HTMLElement&&t.push(e)})),this.raw instanceof NodeList?[...this.raw.entries()].forEach((([e,n])=>{t[e]&&n.replaceWith(t[e])})):this.raw.replaceWith(...t),this},parent:function(e){if(e){if(!(e instanceof HTMLElement||e instanceof EyeElement))throw new Error("[EyeJS] Unable to append current element to parent because it's not HTMLElement");return(this.raw instanceof NodeList?[...this.raw.entries()]:[[0,this.raw]]).forEach((([t,n])=>{e.append(n)})),this}return eye(this.raw instanceof NodeList?this.raw.item(0).parentElement:this.raw.parentElement)},is:function(e,t){if(e=e instanceof EyeElement?e.raw:e,this.raw instanceof NodeList)return console.warn("[EyeJS] .is is not functional with multi selected elements"),this;if("connected"===e)return this.raw.isConnected;switch(t){case"same":return this.raw.isSameNode(e);case"equal":return this.raw.isEqualNode(e);default:return console.error(`[EyeJS] Unknown check "${t}", possible values are ["same","equal","connected"]`),!1}},css:function(e,t){if(e){let n="";return e=flat(e),(this.raw instanceof NodeList?[...this.raw.entries()]:[[0,this.raw]]).forEach((([s,i])=>{if(void 0===t)return n=i.style[e];i.style[e]=t})),n||this}return console.error('[EyeJS] mission argument "attr" in function .css')},remove:function(){return(this.raw instanceof NodeList?[...this.raw.entries()]:[[0,this.raw]]).forEach((([e,t])=>{t.remove()})),this},on:function(e,t,n){e=e.split(" ");let s="string"==typeof t?t:null,i="function"==typeof t?t:n,r=this;if("function"!=typeof i)return console.error("[EyeJS] .on method is missing the actuall callback `cb` or not of type function");let a=this.raw instanceof NodeList?[...this.raw.entries()]:[[0,this.raw]],o=null;return e.forEach((e=>{if(s){if(!delegationEvents.includes(e))return o=e;r.dlgListeners.has(e)||r.dlgListeners.set(e,new Set),r.dlgListeners.get(e).add({callback:i,target:s})}else a.forEach((([t,n])=>{n.addEventListener(e,i)}))})),null!==o?console.error(`[EyeJS] trying to use delegation for an inappropriate event "${o}"`):this},off:function(e,t){let n=this.dlgListeners;if("function"!=typeof t)return console.error("[EyeJS] .off method is missing the actuall callback `cb` or not of type function");e=e.split(" "),(this.raw instanceof NodeList?[...this.raw.entries()]:[[0,this.raw]]).forEach((([n,s])=>{e.forEach((e=>s.removeEventListener(e,t)))})),e.forEach((e=>{if(n.has(e)){let s=n.get(e);for(const e of s)t===e.callback&&s.delete(e)}}))},trigger:function(e){return(this.raw instanceof NodeList?[...this.raw.entries()]:[[0,this.raw]]).forEach((([t,n])=>{n.dispatchEvent(getEvent(e))})),this},find:function(e,t){let n=[];return(this.raw instanceof NodeList?[...this.raw.entries()]:[[0,this.raw]]).forEach((([t,s])=>{s.querySelectorAll(e).forEach((e=>n.push(e)))})),!1===t?n.length>0?eye(n[0]):null:n.length>0?1==n.length?eye(n[0]):n.map((e=>eye(e))):null},clone:function(e){if(this.raw instanceof NodeList){let t=[];return this.raw.forEach((e=>{t.push(e.cloneNode(!0))})),(e instanceof HTMLElement||e instanceof EyeElement)&&t.forEach((t=>e.append(t))),t}{let t=this.raw.cloneNode(!0);return(e instanceof HTMLElement||e instanceof EyeElement)&&e.append(t),t}},compute:function(e){return"bounds"===(e=e||"bounds")?(this.raw instanceof NodeList?this.raw.item(0):this.raw).getBoundingClientRect():"style"==e?getComputedStyle(this.raw instanceof NodeList?this.raw.item(0):this.raw):void console.error(`[EyeJS] unkown type "${e}" in function .compute, possible values are "bounds" "style"`)},pointer:function(e,t,n){return(this.raw instanceof NodeList?[...this.raw.entries()]:[[0,this.raw]]).forEach((([s,i])=>{"capture"===e?!0===t?i.setPointerCapture(n):i.releasePointerCapture(n):"lock"===e&&(!0===t?i.requestPointerLock():document.exitPointerLock())})),this},child:function(e){let t=(this.raw instanceof NodeList?this.raw.item(0):this.raw).children[e];return t?eye(t):null},val:function(e){return e?((this.raw instanceof NodeList?[...this.raw.entries()]:[[0,this.raw]]).forEach((([t,n])=>n.value=e)),this):(this.raw instanceof NodeList?this.raw.item(0):this.raw).value},serialize:function(e){e=e||{};let{inputs:t=["input","textarea","select"]}=e;if(this.raw instanceof HTMLElement){let n={json:{},url:"",fd:new FormData};return this.raw.querySelectorAll(t.join(",")).forEach(((t,s)=>{let i=t.name||t.dataset.name,r=t.value||t.textContent;"function"==typeof e[i]&&(r=e[i](t)),"file"==t.type?t.files.forEach((e=>{n.fd.append(i,e)})):(n.json[i]=r,n.fd.append(i,r))})),n.url=new URLSearchParams(n.json).toString(),n}console.warn("[EyeJS] this is a multi selection, it's not serializable!")}},window.eye=eye;export default eye;