-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcbx.min.js
More file actions
1 lines (1 loc) · 2.24 KB
/
Copy pathcbx.min.js
File metadata and controls
1 lines (1 loc) · 2.24 KB
1
function cbx(e={},t=10){const a="cbx",n=(e,t)=>[...(t||document).querySelectorAll(e)],r=(e,...t)=>e.bind(null,...t),l=e=>{switch(e){case"<":return(e,t)=>e<t;case">":return(e,t)=>e>t;case"!=":return(e,t)=>e!=t}},s=e=>e&&s(e.parentNode.closest(`.${a}`))||e,c=e=>n(`.${a}`).filter((t=>e.matches((t.dataset.triggers||t.dataset.selectors).replace(";",",")))).flatMap((e=>{return t=s(e),n(`.${a}`,t).concat(t);var t})),o=Object.fromEntries([].concat([["regex",(e,t)=>{return[!!(a=e.find((e=>!e.value.match(new RegExp(t))))),a?.value];var a}]],[["Set",(e,t,a)=>{return[e(n=[].filter.call(t[0]?.options||t,(({value:e,checked:t,selected:a})=>e&&(t||a))).length,+a),n];var n}],["Empty",(e,t,a)=>{return[e(n=t.filter((e=>!e.value)).length,+a),n];var n}],["TextLength",(e,t,a)=>{return[e(n=t.reduce(((e,t)=>e+t.value.length),0),+a),n];var n}],["Value",(e,[t,...a],n)=>[void 0!==n&&e(n,t.value)||a.some((a=>e(a.value,t.value))),t.value]],["Number",(e,[t,...a],n)=>[void 0!==n&&e(+n,+t.value)||a.some((a=>e(+a.value,+t.value))),t.value]]].flatMap((([e,t])=>[[`min${e}`,r(t,l("<"))],[`max${e}`,r(t,l(">"))],[`eq${e}`,r(t,l("!="))]]))));function i(t,r){const{selectors:l,constraint:s,param:c,message:i}=r.dataset,[u,p]=(e[s]||o[s]||(()=>null))(l.split(";").flatMap((e=>n(e))),c)||(console.log("Unsupported constraint requested for: ",r),[!0]);return u&&i&&(r.innerHTML=i.replace("%value%",p)),u&&!r.matches(`.${a}--insta`)&&"input"===t.type||r.classList.toggle(`${a}--visible`,u),r}let u,p;function m(e){const a=e.target;u==a&&p&&clearTimeout(p),u=a,p=setTimeout((()=>(p=u=null,Array.from(new Set(("radio"!==a.type?[a]:[...a.form[a.name]]).flatMap(c))).map(r(i,e)))),t)}function d(e,t){const n=Array.from(new Set(t.flatMap(c))).map(r(i,e)).filter((e=>e.offsetParent&&e.matches(`.${a}--error`))).map((e=>e.getBoundingClientRect().top));n.length&&(e.stopPropagation(),e.preventDefault(),window.scroll(0,Math.min(...n)))}Object.entries({input:m,change:m,submit:e=>d(e,n("input, textarea, select",e.target)),click:e=>void 0===e.target.dataset.clickValidates||d(e,n(e.target.dataset.clickValidates))}).map((([e,t])=>document.addEventListener(e,t,!0))),n(`.${a}--initial`).map(r(i,{})),(new CSSStyleSheet).replace(`.${a}:not(.${a}--visible){display:none !important;}`).then((e=>document.adoptedStyleSheets.push(e)))}