@carbon/utilities
Version:
Utilities and helpers to drive consistency across software products using the Carbon Design System
2 lines (1 loc) • 2.58 kB
JavaScript
import{registerSwipeEvents as b}from"./swipeEvents";const Y=(l,x)=>{const r="carousel";let s=[0],c=[0];const a={},p=10,{onViewChangeStart:S,onViewChangeEnd:M,excludeSwipeSupport:g}=x||{},v=(e,t)=>{a[e]=t},C=(e,t)=>{if(e.querySelector(`.${t}`))return;const n=document.createElement("div");for(n.classList.add(`${t}`);e.firstChild;)n.appendChild(e.firstChild);e.appendChild(n)},k=()=>s.map(e=>({id:e,elem:a[e]})),h=()=>{const e=Object.keys(a).length,t=a[e-1],n=k();return{currentIndex:s[0],lastIndex:parseInt(t?.dataset.index||s[0].toString(),10),totalViews:e,historyStack:n}},E=()=>{c=[...s];const e=h();S?.(e)},L=e=>{if(!e)return;const t=e.dataset.index;if(t&&s[0]===parseInt(t,10)){const n=h();M?.(n)}},$=e=>{const n=Object.keys(a).length-1;return Math.max(0,Math.min(e,n))},y=e=>{const t=$(e);s[0]!==t&&(E(),s=[t,...s],d(!1))},V=e=>{L(e)},w=(e,t,n,o,m)=>{e.classList.add(`${r}__view`),e.classList.toggle(`${r}__view-in-stack`,t&&!n),e.classList.toggle(`${r}__view-active`,t&&n),m&&!o&&e.classList.add(`${r}__view-recycle-in`),!m&&o&&e.classList.add(`${r}__view-recycle-out`)},R=e=>{e.classList.remove(`${r}__view-recycle-in`,`${r}__view-recycle-out`)},H=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),A=e=>{const t=H(p);if(l.clientHeight<t){e<t&&(e=t);const o=l.querySelector(`.${r}__itemsWrapper`);o&&(o.style.blockSize=`${e}px`)}},d=e=>{let t=0;Array.from(_).forEach((n,o)=>{const m=s.findIndex(i=>i===o),T=c.filter(i=>i===o).length,O=c.length>s.length&&c[0]===o&&T>0,F=c.length<s.length&&s[0]===o&&T>0,N=m>-1,P=o===s[0];if(w(n,N,P,O,F),e){v(o,n),setTimeout(()=>{(!t||n.offsetHeight<t&&t>H(p))&&(t=n.offsetHeight),n.style.position="absolute",A(t)});const i=B=>{R(n),B.target===a[s[0]]&&V(n)};n._carouselListener=i,n.addEventListener("animationend",i),n.addEventListener("transitionend",i),n.setAttribute("data-index",o.toString())}}),e&&L(Array.from(_)[0])},u=()=>{const e=s[0]+1;y(e)},f=()=>{s.length-1>=1&&(E(),s=s.slice(1),d(!1))},I=e=>{y(e)},W=()=>({index:s[0],item:a[s[0]]}),q=()=>{s=[0],d(!1)},z=()=>{Object.values(a).forEach(e=>{e&&e._carouselListener&&(e.removeEventListener("animationend",e._carouselListener),e.removeEventListener("transitionend",e._carouselListener))}),g||b(l,u,f,!0)},j=e=>{const t=e.querySelector("slot");return t?t.assignedElements({flatten:!0}):Array.from(e.children)};C(l,`${r}__itemsWrapper`);const D=l.querySelector(`.${r}__itemsWrapper`),_=j(D);return l.classList.add(`${r}__view-stack`),d(!0),g||b(l,u,f,!1),{next:u,prev:f,reset:q,goToIndex:I,getActiveItem:W,destroyEvents:z,allViews:a}};export{Y as initCarousel};