eyjs
Version:
Library that make document manipulation a lot easier
1 lines • 12.6 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()}const localdata=new WeakMap;function cmcl(t,n){let s=[];for(const r in n){const i=n[r],[a,o]=r.split(":"),[l,...c]=a.split(".");let[u=null,h=null]=(o||"").split("-").map((e=>e.trim())),d=e(l.trim(),{class:c,parent:t,data:o?{value:u}:void 0});o&&u&&s.push({name:u,set(e,t){e.find(`[data-value="${u}"]`).textContent=t??h}}),!i||"object"!=typeof i||i instanceof Array||(s=s.concat(cmcl(d,i)))}return s}let delegationEvents=["click","dblclick","submit","input","change","keydown","keyup","keypress","focusin","focusout","mousedown","mouseup","mousemove","contextmenu","auxclick","wheel","mouseover","mouseout","pointerdown","pointerup","pointermove","pointerover","pointerout","gotpointercapture","lostpointercapture","pointercancel"],normalSetterGetter=(e,t,n)=>t;export class EyeElement{#e=null;#t=new Map;#n={value:normalSetterGetter,text:normalSetterGetter};constructor(e,t,n){let s=this;if(e instanceof HTMLElement)this.#e=e;else if(htmlElements.includes(e))this.#e=document.createElement(e.substring(1,e.length-1));else{let t="!"===e.slice(-1);if(this.#e=document.querySelectorAll(t?e.slice(0,-1):e),0==this.#e.length)return null;(1==this.length||t)&&(this.#e=this.#e.item(0))}function r(e){let t=e.type,n=s.#t,r=e.target,i=this;if(n.has(t)){let s=n.get(t);s?.forEach((({callback:t,target:n})=>{r.closest(n)&&t(e,i)}))}}return this.each(((e,s)=>{let i=null;if(t)for(const n in t){const s=t[n];if("class"==n)e.classList.add.apply(e.classList,(s instanceof Array?s:s.split(" ")).filter((e=>""!=e)));else if("text"==n)e.textContent=s;else if("html"==n)e.innerHTML=s;else if("data"==n)for(const t in s)e.dataset[t]=s[t];else"parent"==n?i=s:n in e?e[n]=s:"_"!=n[0]&&e.setAttribute(n,e)}if(n)for(const t in n)-1!=t.indexOf("-")?e.style[t]=n[t]:e.style[flat(t)]=n[t];(i instanceof EyeElement||i instanceof HTMLElement)&&i.append(e),delegationEvents.forEach((t=>{e.addEventListener(t,r)}))})),events.forEach((e=>{s[e]=function(t){return t?"function"==typeof t&&s.on(e,t):s.trigger(e),s}})),this}get length(){return this.#e instanceof NodeList?this.#e.length:1}get raw(){return this.#e}each(e){let t=this.#e instanceof NodeList?[...this.#e.entries()]:[[0,this.#e]];for(let n=0;n<t.length;n++){const[s,r]=t[n];if(!1===e(r,s,this))break}return this}eachChild(e){let t=this;return this.each((function(n,s,r){let i=!0;for(let s=0;s<n.children.length&&(i=e(n.children[s],s,n,t),!1!==i);s++);}))}html(e){let t;return this.each(((n,s)=>{if(void 0===e)return t=n.innerHTML;n.innerHTML=e})),null!=t?t:this}text(e){let t;return this.each(((n,s)=>{if(void 0===e)return t=this.#n.text("get",n.textContent,n);n.textContent=this.#n.text("set",e,n)})),null!=t?t:this}data(e,t){if(localdata.has(this)||localdata.set(this,{}),e){if(null==t)return localdata.get(this)[e];localdata.get(this)[e]=t}return this}attr(e,t){let n="";return this.each(((s,r)=>{if(0===e.indexOf("data-")){let[r,i]=e.split("-").map((e=>e.trim()));if(null==t)return n=s.dataset[i];s.dataset[i]=t}else if(e in s){if(null==t)return n=s[e];s[e]=t}else if("_"!=e[0]){if(null==t)return n=s.getAttribute(e);s.setAttribute(e,t)}})),n||this}rAttr(e){return e&&this.each(((t,n)=>{t.removeAttribute(e)})),this}class(e){let t;return this.each(((n,s)=>{if("number"==typeof e)return t=n.classList.item(e);e.split(" ").forEach((e=>{if("-"==e[0])n.classList.remove(e.substring(1,e.length));else if("%"==e[0])n.classList.toggle(e.substring(1,e.length));else if("?"==e[0])t=n.classList.contains(e.substring(1,e.length));else if(-1!=e.indexOf("/")){let[t,s]=e.split("/");n.classList.replace(t,s)}else n.classList.add(e)}))})),null!=t?t:this}show(e){return this.each(((t,n)=>{t.style.display=e??"inline-block"})),this}hide(e){return this.each(((t,n)=>{e?t.style.opacity=0:t.style.display="none"})),this}append(e,t){let n=[];if((Array.isArray(e)?e:[e]).forEach((e=>{e instanceof EyeElement?n.push(e.#e):e instanceof HTMLElement&&n.push(e)})),this.#e instanceof NodeList)return console.warn("[EyeJS] beware while using .append with multi selected elements"),this.#e.forEach(((e,t)=>{n[t]&&e.append(n[t])})),this;if(t)switch(t){case"next":case"after":this.#e.after(...n);break;case"previous":case"before":this.#e.before(...n);break;case"afterbegin":case"first":this.#e.prepend(...n);break;case"beforeend":case"last":this.#e.append(...n)}else this.#e.append(...n);return this}after(e){return(this.#e instanceof NodeList?this.#e.item(0):this.#e).after(e instanceof EyeElement?e.raw:e),this}before(e){return(this.#e instanceof NodeList?this.#e.item(0):this.#e).before(e instanceof EyeElement?e.raw:e),this}replaceWith(...e){let t=[];return(Array.isArray(e)?e:[e]).forEach((e=>{e instanceof EyeElement?t.push(e.#e):e instanceof HTMLElement&&t.push(e)})),this.#e instanceof NodeList?[...this.#e.entries()].forEach((([e,n])=>{t[e]&&n.replaceWith(t[e])})):this.#e.replaceWith(...t),this}parent(t,n){if(t){if(!(t instanceof HTMLElement||t instanceof EyeElement))throw new Error("[EyeJS] Unable to append current element to parent because it's not HTMLElement");return this.each((e=>{t.append(!0===n?e.cloneNode(!0):e)})),this}return e(this.#e instanceof NodeList?this.#e.item(0).parentElement:this.#e.parentElement)}is(e,t){if(e=e instanceof EyeElement?e.#e:e,this.#e instanceof NodeList)return console.warn("[EyeJS] .is is not functional with multi selected elements"),this;if("connected"===e)return this.#e.isConnected;switch(t){case"same":return this.#e.isSameNode(e);case"equal":return this.#e.isEqualNode(e);default:return console.error(`[EyeJS] Unknown check "${t}", possible values are ["same","equal","connected"]`),!1}}css(e,t){if(e){let n;return e=flat(e),this.each(((s,r)=>{if(void 0===t)return n=s.style[e];s.style[e]=t})),null!=n?n:this}return console.error('[EyeJS] mission argument "attr" in function .css')}remove(){return this.each(((e,t)=>{e.remove()})),this}on(e,t,n){e=e.split(" ");let s="string"==typeof t?t:null,r="function"==typeof t?t:n,i=this;if("function"!=typeof r)return console.error("[EyeJS] .on method is missing the actuall callback `cb` or not of type function");let a=this.#e instanceof NodeList?[...this.#e.entries()]:[[0,this.#e]],o=null;return e.forEach((e=>{if(s){if(!delegationEvents.includes(e))return o=e;i.#t.has(e)||i.#t.set(e,new Set),i.#t.get(e).add({callback:r,target:s})}else a.forEach((([t,n])=>{n.addEventListener(e,r)}))})),null!==o?console.error(`[EyeJS] trying to use delegation for an inappropriate event "${o}"`):this}off(e,t){let n=this.#t;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.each(((n,s)=>{e.forEach((e=>n.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(e){return this.each(((t,n)=>{t.dispatchEvent(getEvent(e))})),this}find(e){let t=[];return this.each(((n,s)=>{n.querySelectorAll(e).forEach((e=>t.push(e)))})),1==t.length?t[0]:t}clone(e){if(this.#e instanceof NodeList){let t=[];return this.#e.forEach((e=>{t.push(e.cloneNode(!0))})),(e instanceof HTMLElement||e instanceof EyeElement)&&t.forEach((t=>e.append(t))),t}{let t=this.#e.cloneNode(!0);return(e instanceof HTMLElement||e instanceof EyeElement)&&e.append(t),t}}compute(e){return"bounds"===(e=e||"bounds")?(this.#e instanceof NodeList?this.#e.item(0):this.#e).getBoundingClientRect():"style"==e?getComputedStyle(this.#e instanceof NodeList?this.#e.item(0):this.#e):void console.error(`[EyeJS] unkown type "${e}" in function .compute, possible values are "bounds" "style"`)}client(e){return["width","height","left","top"].includes(e)?(this.#e instanceof NodeList?this.#e.item(0):this.#e)[`client${e[0].toUpperCase()}${e.substring(1,e.length)}`]:(console.error(`[EyeJS] Unknown client* attribute "${e}" in .client(attr)`),this)}pointer(e,t,n){return this.each(((s,r)=>{"capture"===e?!0===t?s.setPointerCapture(n):s.releasePointerCapture(n):"lock"===e&&(!0===t?s.requestPointerLock():document.exitPointerLock())})),this}get childlen(){return(this.#e instanceof NodeList?this.#e.item(0):this.#e)?.children.length}child(t){let n=this.#e instanceof NodeList?this.#e.item(0):this.#e;return void 0===t?n.children.length:n.children[t]?e(n.children[t]):null}val(e){if(null==e){let e=this.#e instanceof NodeList?this.#e.item(0):this.#e;return this.#n.value("get",e.value,e)}return(this.#e instanceof NodeList?[...this.#e.entries()]:[[0,this.#e]]).forEach((([t,n])=>n.value=this.#n.value("set",e,n))),this}serialize(e){e=e||{};let{inputs:t=["input","textarea","select"]}=e;if(this.#e instanceof HTMLElement){let n={json:{},url:"",fd:new FormData};return this.#e.querySelectorAll(t.join(",")).forEach(((t,s)=>{let r=t.name||t.dataset.name,i=t.value||t.textContent;"function"==typeof e[r]&&(i=e[r](t)),"file"==t.type?t.files.forEach((e=>{n.fd.append(r,e)})):(n.json[r]=i,n.fd.append(r,i))})),n.url=new URLSearchParams(n.json).toString(),n}console.warn("[EyeJS] this is a multi selection, it's not serializable!")}redefine(e,t){return["text","value"].includes(e)&&"function"==typeof t&&(this.#n[e]=t),this}animate(e,t){let n=[];return t.duration=t.duration||1e3,this.each(((s,r)=>{n.push(s.animate(e,t))})),1==n.length?n[0]:n}position(){let e=[];return this.each((t=>{for(let n=0;n<t.parentNode.children.length;n++){const s=t.parentNode.children[n];t.isSameNode(s)&&e.push(n)}})),0==e.length?e[0]:e}}function e(t,n,s){if("string"==typeof t&&0===t.indexOf("model:")||"model"===t){if(!n)return console.error("[EyeJS] Model creation requires parameter 'attr' as prototype, none delivered!");let s=["eye-model"];(t=t.split(":"))[1]&&(s=s.concat(t[1].split(" ").filter((e=>""!=e))));let r=e("<div>",{class:s.join(" ")}),i=cmcl(r,n);return t=>{let n=e(r.clone(t?.parent));return n.refresh=function(e={}){let t=!1!==e.default;return i.forEach((s=>{(!0===t||!t&&e.hasOwnProperty(s.name))&&s.set(n,e[s.name])})),this},n.refresh(t)}}{let e=new EyeElement(t,n,s);return 0===e.length?null:e}}window.e=e,window.EyeElement=EyeElement;export default e;