axentix
Version:
Axentix is a framework mixing fully customizable components & utility-first classes, leaving the design choice to the developer.
3 lines (2 loc) • 11.9 kB
JavaScript
(function(l,i){typeof exports=="object"&&typeof module!="undefined"?i(exports):typeof define=="function"&&define.amd?define(["exports"],i):(l=typeof globalThis!="undefined"?globalThis:l||self,i(l.Select={}))})(this,function(l){"use strict";var Ae=Object.defineProperty;var G=l=>{throw TypeError(l)};var Ce=(l,i,d)=>i in l?Ae(l,i,{enumerable:!0,configurable:!0,writable:!0,value:d}):l[i]=d;var C=(l,i,d)=>Ce(l,typeof i!="symbol"?i+"":i,d),D=(l,i,d)=>i.has(l)||G("Cannot "+d);var a=(l,i,d)=>(D(l,i,"read from private field"),d?d.call(l):i.get(l)),L=(l,i,d)=>i.has(l)?G("Cannot add the same private member more than once"):i instanceof WeakSet?i.add(l):i.set(l,d),g=(l,i,d,b)=>(D(l,i,"write to private field"),b?b.call(l,d):i.set(l,d),d),m=(l,i,d)=>(D(l,i,"access private method"),d);var h,x,p,E,v,u,Z,j,O,F,J,T,K;const i=[],d={components:[],plugins:[],prefix:"ax",mode:""},b=e=>`--${d.prefix}-${e}`,w=e=>d.components.find(t=>t.name===e).class,R=()=>{const e=d.components.filter(s=>s.dataDetection),t=d.plugins.filter(s=>s.dataDetection);return[...e,...t].map(s=>s.name)},Q=(e,t)=>{if(!e.name||!e.class){console.error(`[Axentix] Error registering ${t} : Missing required parameters.`);return}if(d[t].some(s=>s.name===e.name)){console.error(`[Axentix] Error registering ${t} : Already exist.`);return}e.autoInit&&(e.autoInit.selector=e.autoInit.selector+=":not(.no-axentix-init)"),d[t].push(e)},X=e=>{Q(e,"components")},Y=e=>e.replace(/[\w]([A-Z])/g,t=>t[0]+"-"+t[1]).toLowerCase(),_=(e,t="")=>{const s=Y(e);return t?t+"-"+s:s},ee=(e,t,s,n,r="")=>{const o=t[0].toUpperCase()+t.slice(1).toLowerCase();R().includes(o)&&s!=="Collapsible"&&o!=="Sidenav"&&(e[t]=w(o).getDefaultOptions());const c=r?r+"-"+t:t,f=M(e[t],s,n,c);if(!(Object.keys(f).length===0&&e.constructor===Object))return f},M=(e,t,s,n="")=>Object.keys(e).reduce((r,o)=>{if(typeof e[o]=="object"&&e[o]!==null){const c=ee(e,o,t,s,n);c&&(r[o]=c)}else if(e[o]!==null){const c="data-"+t.toLowerCase()+"-"+_(o,n);if(s.hasAttribute(c)){const f=s.getAttribute(c);r[o]=typeof e[o]=="number"?Number(f):f,typeof e[o]=="boolean"&&(r[o]=f==="true")}}return r},{}),te=(e,t)=>{const s=Object.assign({},w(e).getDefaultOptions());return M(s,e,t)},se=()=>{document.querySelectorAll("[data-ax]").forEach(t=>{let s=t.dataset.ax;if(s=s[0].toUpperCase()+s.slice(1).toLowerCase(),!R().includes(s)){console.error(`[Axentix] Error: ${s} component doesn't exist.
Did you forget to register him ?`,t);return}try{const n=w(s);new n(`#${t.id}`)}catch(n){console.error("[Axentix] Data: Unable to load "+s,n)}})},ne=()=>{try{new Axentix.Axentix("all")}catch(e){console.error("[Axentix] Unable to auto init.",e)}};document.addEventListener("DOMContentLoaded",()=>{document.documentElement.dataset.axentix&&ne(),se()});const q=(...e)=>e.reduce((t,s)=>{for(let n in s)t[n]=typeof s[n]=="object"&&s[n]!==null?q(t[n],s[n]):s[n];return t},{}),oe=(e,t,s)=>q(w(e).getDefaultOptions(),te(e,s),t),re=(e,t=document.createElement("div"))=>(e[0].parentElement.insertBefore(t,e[0]),e.forEach(n=>t.appendChild(n)),t),ie=e=>e.replaceWith(...e.childNodes),I=(e,t,s)=>{const n=new CustomEvent("ax."+t,{detail:{},bubbles:!0});e.dispatchEvent(n)},le=e=>{const t=i.find(s=>s.type!=="Toast"&&"#"+s.instance.el.id===e);return t?t.instance:!1},ae=()=>Math.random().toString().split(".")[1],ce=e=>e.checkValidity()||e.validationMessage,de=(e,t)=>{const s=document.createElement("div");s.axGenerated=!0,e.appendChild(s),s.classList.add("form-helper-invalid"),s.innerHTML=t},fe=e=>{const t=e.querySelector(".form-helper-invalid");t&&t.axGenerated&&t.remove()},ue=e=>{e.classList.remove("form-valid","form-invalid","form-no-helper"),fe(e)},pe=(e,t)=>{const s=e.getAttribute("data-form-validate");let n=!1;if(s){const c=s.toLowerCase().split(",");if(n=c.includes("auto"),c.includes("lazy")&&t==="input")return}const r=ce(e),o=e.closest(".form-field, .form-file");return ue(o),r!==!0?(n&&typeof r=="string"?de(o,r):o.querySelector(".form-helper-invalid")||o.classList.add("form-no-helper"),o.classList.add("form-invalid"),!1):(o.classList.add("form-valid"),o.querySelector(".form-helper-valid")||o.classList.add("form-no-helper"),!0)};let N=!0;const A=e=>{e.forEach(V)},$=e=>{if(N){N=!1;return}setTimeout(()=>{A(e)},10)},V=e=>{const t=e.closest(".form-field"),s=t.querySelector(".form-custom-select"),n=t.classList.contains("active"),r=["date","month","week","time"];let o=s&&e.tagName==="DIV"&&e.innerText.length>0;s||(o=e.value.length>0||e.tagName!=="SELECT"&&e.placeholder.length>0||e.tagName==="SELECT"||r.some(y=>e.matches(`[type="${y}"]`)));const c=document.activeElement===e,f=e.hasAttribute("disabled")||e.hasAttribute("readonly");e.firstInit?(B(e,n,o,c,t,s),e.firstInit=!1,e.isInit=!0):f||B(e,n,o,c,t,s)},B=(e,t,s,n,r,o)=>{const c=e.type==="textarea",f=r.querySelector("label:not(.form-check)");!t&&(s||n)?r.classList.add("active"):t&&!(s||n)&&r.classList.remove("active"),c?f&&(f.style.backgroundColor=P(f)):he(e,r,o,f),n&&!c?r.classList.add("is-focused"):o||r.classList.remove("is-focused"),n&&c?r.classList.add("is-textarea-focused"):r.classList.remove("is-textarea-focused")},he=(e,t,s,n)=>{const r=e.clientWidth,o=e.offsetLeft,c=e.clientHeight+(s?s.offsetTop:e.offsetTop)+"px",f=e.closest(".form-material").classList.contains("form-material-bordered");t.style.setProperty(b("form-material-position"),c);let y=o,U="left",we=r+"px",W=0;t.classList.contains("form-rtl")&&(U="right",y=t.clientWidth-r-o),t.style.setProperty(b(`form-material-${U}-offset`),y+"px"),y!=0&&(W=o),t.style.setProperty(b("form-material-width"),we),n&&(n.style.left=W+"px",f&&(n.style.backgroundColor=P(n)))},H=e=>{const t=window.getComputedStyle(e).backgroundColor;if(t&&!["transparent","rgba(0, 0, 0, 0)"].includes(t))return t},P=e=>{e.style.backgroundColor="";let t=e;for(;t.parentElement;){const n=H(t);if(n)return n;t=t.parentElement}const s=H(document.documentElement);return s||"white"},z=(e,t)=>{e.hasAttribute("data-form-validate")&&pe(e,t.type)},me=(e,t)=>{e.forEach(s=>{s===t.target&&V(s)})},ve=(e,t)=>{t.target.tagName==="FORM"&&t.target.classList.contains("form-material")&&$(e)},ye=e=>{e.forEach(o=>{o.firstInit=!0,o.validateRef=z.bind(null,o),o.addEventListener("input",o.validateRef),o.addEventListener("change",o.validateRef)}),A(e);const t=me.bind(null,e);document.addEventListener("focus",t,!0),document.addEventListener("blur",t,!0);const s=$.bind(null,e);window.addEventListener("pageshow",s);const n=ve.bind(null,e);document.addEventListener("reset",n);const r=A.bind(null,e);window.addEventListener("resize",r)},xe=(e,t)=>{const s=e.files;s.length>1?t.innerHTML=Array.from(s).map(n=>n.name).join(", "):s[0]&&(t.innerHTML=s[0].name)},ge=e=>{if(e.isInit)return;e.isInit=!0;const t=e.querySelector('input[type="file"]'),s=e.querySelector(".form-file-path");t.handleRef=xe.bind(null,t,s),t.validateRef=z.bind(null,t),t.addEventListener("change",t.handleRef),t.addEventListener("input",t.validateRef),t.addEventListener("change",t.validateRef)},Le=()=>{const e=Array.from(document.querySelectorAll(".form-file"));try{e.forEach(ge)}catch(t){console.error("[Axentix] Form file error",t)}},S=(e=document.querySelectorAll(".form-material .form-field:not(.form-default) .form-control:not(.form-custom-select)"))=>{const{setupInputs:t,detectInputs:s}=Array.from(e).reduce((n,r)=>(r.isInit?n.detectInputs.push(r):n.setupInputs.push(r),n),{setupInputs:[],detectInputs:[]});Le();try{t.length>0&&ye(t),s.length>0&&A(s)}catch(n){console.error("[Axentix] Material forms error",n)}};document.addEventListener("DOMContentLoaded",()=>S());class be{constructor(){C(this,"el")}removeListeners(){}setupListeners(){}setup(){}preventDbInstance(t){if(t&&le(t))throw new Error(`Instance already exist on ${t}`)}sync(){I(this.el,"component.sync"),this.removeListeners(),this.setupListeners()}reset(){I(this.el,"component.reset"),this.removeListeners(),this.setup()}destroy(){I(this.el,"component.destroy"),this.removeListeners();const t=i.findIndex(s=>s.instance.el.id===this.el.id);i.splice(t,1)}}const Ee={inputClasses:""};class k extends be{constructor(s,n){super();L(this,u);C(this,"options");L(this,h);L(this,x);L(this,p);L(this,E);L(this,v);try{this.preventDbInstance(s),i.push({type:"Select",instance:this}),this.el=document.querySelector(s),this.options=oe("Select",n,this.el),this.setup()}catch(r){console.error("[Axentix] Select init error",r)}}setup(){this.el.style.display="none",g(this,x,re([this.el])),a(this,x).className="form-custom-select",m(this,u,Z).call(this)}reset(){this.destroy(!0),super.reset()}destroy(s){s||super.destroy(),a(this,h)&&(a(this,h).el.removeEventListener("ax.dropdown.open",a(this,v)),a(this,h).el.removeEventListener("ax.dropdown.close",a(this,v)),g(this,v,null),a(this,h).destroy(),a(this,h).el.remove(),g(this,h,null)),ie(a(this,x)),this.el.classList.add("form-custom-select"),this.el.style.display=""}}h=new WeakMap,x=new WeakMap,p=new WeakMap,E=new WeakMap,v=new WeakMap,u=new WeakSet,Z=function(){const s=`dropdown-${ae()}`;g(this,p,document.createElement("div")),a(this,p).className=`form-control ${this.options.inputClasses}`,a(this,p).dataset.target=s;const n=document.createElement("div"),r=this.el.className.replace("form-control","");if(n.className=`dropdown-content ${r}`,this.el.disabled){a(this,p).setAttribute("disabled",""),a(this,x).append(a(this,p)),m(this,u,O).call(this,n);return}g(this,v,m(this,u,F).bind(this));const o=document.createElement("div");o.className="dropdown",o.id=s,o.addEventListener("ax.dropdown.open",a(this,v)),o.addEventListener("ax.dropdown.close",a(this,v)),Array.from(this.el.attributes).forEach(y=>{y.name.startsWith("data-dropdown")&&o.setAttribute(y.name,y.value)}),o.append(a(this,p)),o.append(n),a(this,x).append(o),m(this,u,O).call(this,n);const c=w("Dropdown");g(this,h,new c(`#${s}`,{closeOnClick:!this.el.multiple,preventViewport:!0}));const f=window.getComputedStyle(o).zIndex;g(this,E,this.el.closest(".form-field").querySelector("label:not(.form-check)")),a(this,E)&&(a(this,E).style.zIndex=f+5)},j=function(s,n){const r=document.createElement("div");r.className="form-field";const o=document.createElement("label");o.className="form-check";const c=document.createElement("input");c.type="checkbox",n&&c.setAttribute("disabled","");const f=document.createElement("span");return f.innerHTML=s,o.append(c,f),r.append(o),r},O=function(s){for(const n of this.el.options){const r=n.hasAttribute("disabled"),o=document.createElement("div");o.className="dropdown-item",o.innerHTML=this.el.multiple?m(this,u,j).call(this,n.text,r).innerHTML:n.text,o.axValue=n.value||n.text,r?o.classList.add("form-disabled"):(o.axClickRef=m(this,u,J).bind(this,o),o.addEventListener("click",o.axClickRef)),(n.hasAttribute("selected")||!this.el.multiple&&this.el.value===(n.value||n.text))&&m(this,u,T).call(this,o),s.append(o)}},F=function(){a(this,p).closest(".form-field").classList.toggle("is-focused")},J=function(s,n){n.preventDefault(),s.classList.contains("form-selected")?m(this,u,K).call(this,s):m(this,u,T).call(this,s)},T=function(s){const n=s.axValue;this.el.multiple?s.querySelector("input").checked=!0:a(this,h)&&a(this,h).el.querySelectorAll(".dropdown-item").forEach(o=>o.classList.remove("form-selected")),s.classList.add("form-selected");const r=this.el.multiple?[...a(this,p).innerText.split(", ").filter(Boolean),n].join(", "):n;a(this,p).innerText=r,this.el.value=r,S([a(this,p)])},K=function(s){const n=s.axValue;s.classList.remove("form-selected");let r="";if(this.el.multiple){s.querySelector("input").checked=!1;const o=a(this,p).innerText.split(", ").filter(Boolean),c=o.findIndex(f=>f===n);o.splice(c,1),r=o.join(", ")}a(this,p).innerText=r,this.el.value=r,S([a(this,p)])},C(k,"getDefaultOptions",()=>Ee),X({class:k,name:"Select",dataDetection:!0,autoInit:{enabled:!0,selector:".form-custom-select"}}),l.Select=k,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"})});