-
Notifications
You must be signed in to change notification settings - Fork 0
/
coarse.min.js
1 lines (1 loc) · 2.03 KB
/
coarse.min.js
1
export default class Coarse{constructor(e,{renderControls:t=!0,renderDots:s=!0,selectedClass:a='selected',swipeSensitivity:i=.2,align:r='center',wrap:l=!0}={}){let n,o='next',d='previous',c='data-coarse',u='coarse-controls',p=`.${u}.${o}`,g=`.${u}.${d}`,m=!1,h=0,b=[],f=Array.from(e.children),$=f.length,A=e.querySelector(`.${a}`),w=e.parentElement,y=e=>`slide ${e+1} of ${$}`,L=e=>parseFloat(e.replace('px','')),v=(e,t)=>L(getComputedStyle(e)[t]),x=e=>e.target.closest(`[${c}]`),E=(e,t,s=window)=>s.addEventListener(e,t),S=e=>{n=parseFloat(e),f.map((t,s)=>t.classList.toggle(a,s==e)),b.map((t,s)=>t.classList.toggle(a,s==e))},q=e=>{let t=e.changedTouches?e.changedTouches[0]:e;m=!0,h=t.clientX},C=e=>{if(!m)return;let t=(e.changedTouches?e.changedTouches[0]:e).clientX-h;t<100*i-100&&T(n+1),t>100-100*i&&T(n-1)},T=s=>{m=!1;let a=s==$,i=s<0;if((i||a)&&!l)return;i?s=$-1:a&&(s=0);let o=f[s],d=w.querySelector(p),u=w.querySelector(g),h=v(o,'width'),b=v(o,'marginLeft'),A=v(o,'marginRight'),L=v(w,'width')-v(w,'paddingLeft')-v(w,'paddingRight'),x=v(e,'width'),E=s*(h+b+A),q=-1*b;/center/i.test(r)&&(q=.5*(L-h-A-A)),/right/i.test(r)&&(q=L-h-A),l||(d.disabled=!1,u.disabled=!1,s<=0&&(u.disabled=!0),s==$-1&&(d.disabled=!0)),S(s);let C=(E-q)/x;if(e.style.transform=`translate3d(${-100*C}%, 0, 0)`,t){let e=n+1;d.setAttribute(c,e),d.title=`Go to ${y(e==$?0:e)}`;let t=n-1;u.setAttribute(c,t),u.title=`Go to ${y(n?t:$-1)}`}};if(t&&[d,o].map((e,t)=>{let s=document.createElement('button');s.title=e,s.classList.add(u,e),s.setAttribute(c,n+(t||-1)),w.append(s)}),s){let e=document.createElement('div');e.classList.add('coarse-dot-navigation'),f.map((t,s)=>{let a=document.createElement('button');a.title=`Jump to ${y(s)}`,a.setAttribute(c,s),b.push(a),e.append(a)}),w.append(e)}T(A?f.indexOf(A):0),f.map((e,t)=>e.setAttribute(c,t)),E('resize',()=>requestAnimationFrame(()=>T(n))),E('focusin',e=>{let t=x(e);f.indexOf(t)>-1&&T(t.getAttribute(c))},w),E('click',e=>{let t=x(e);t&&T(t.getAttribute(c))},w),i>0&&(E('mousedown',q,w),E('touchstart',q,w),E('mouseup',C,w),E('touchend',C,w))}}