@twistedandy/better-carousel 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +839 -2
- package/dist/better-carousel.css +1 -0
- package/dist/better-carousel.js +3373 -0
- package/dist/better-carousel.min.js +1 -0
- package/package.json +55 -5
- package/src/index.js +49 -0
- package/src/scripts/autoplay.js +322 -0
- package/src/scripts/carousel.js +870 -0
- package/src/scripts/geometry.js +432 -0
- package/src/scripts/input.js +484 -0
- package/src/scripts/layout.js +258 -0
- package/src/scripts/loop.js +83 -0
- package/src/scripts/markup.js +288 -0
- package/src/scripts/motion.js +232 -0
- package/src/scripts/navigation.js +209 -0
- package/src/scripts/options.js +153 -0
- package/src/styles/better-carousel.scss +323 -0
- package/src/types/better-carousel.d.ts +309 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var BetterCarousel=(()=>{"use strict";function t(t,e,n){e&&t.classList.contains(e)!==!!n&&t.classList.toggle(e,!!n)}function e(t,e,n){t.getAttribute(e)!==(n||null)&&(n?t.setAttribute(e,n):t.removeAttribute(e))}function n(t,e,n){t.style[e]!==n&&(t.style[e]=n)}function o(t){""===t.getAttribute("style")&&t.removeAttribute("style")}function r(t,e){const n=document.createElement(t);return e&&(n.className=e),n}function i(t,e){if("string"==typeof t){for(let n=e;n;n=n.parentElement){const e=n.querySelector(t);if(e)return e}return null}return!0===t?e:t||null}const s=new WeakMap,a=new WeakMap;function l(t,e,n){const o=s.get(t)||new Set;!o.has(e)&&t.hasAttribute(e)||(o.add(e),s.set(t,o),t.getAttribute(e)!==n&&t.setAttribute(e,n))}function c(t,e){if(e&&!t.classList.contains(e)){const n=a.get(t)||new Set;t.classList.add(e),n.add(e),a.set(t,n)}}const d=new WeakSet;let u=0;const p=new Set(["template","script","style"]);function f(t,e){return[...e?t.querySelectorAll(e):t.children].filter(t=>!d.has(t)&&!p.has(t.localName))}function h(t){for(const e of[t,...t.querySelectorAll("[id]")])e.removeAttribute("id")}function g(t,e){const n=e.cloneNode(!0);h(n),t.replaceChildren(...n.childNodes)}const m={delay:4e3,stopOnInteraction:!0,pauseOnHover:!1,pauseOnFocus:!0,stopOnLastSnap:!1,playOnInit:!0,instant:!1,timer:null},v={speed:120,direction:"next",startDelay:1e3,stopOnInteraction:!0,pauseOnHover:!1,pauseOnFocus:!0,playOnInit:!0};function b(t,e,n){return{...t,..."number"==typeof n?{[e]:n}:n}}function y(n,o,i,s){const{api:a,root:c,container:d,cls:u,emit:p}=n,f=n.options.labels,h=r("button",u.button+" "+u.playButton);let g=!1,m=null,v=!0;function b(){e(h,"aria-label",g?f.pause:f.play),t(c,u.playing,g),l(d,"aria-live",g?"off":"polite")}function y(){a.isFit()?h.remove():h.isConnected||c.append(h),v&&(v=!1,g?s.play():(n.playing?.[o]??(i.playOnInit&&!matchMedia("(prefers-reduced-motion: reduce)").matches))&&x.play())}h.type="button",h.setAttribute("aria-controls",d.id),h.addEventListener("click",()=>g?x.stop():x.play());const x={play(){g||(g=!0,m=((t,e)=>{const n=new Set,o=(t,e)=>{const o=n.size;n[e?"add":"delete"](t),!o!=!n.size&&s.pause(m.paused())},r=new IntersectionObserver(([t])=>o("view",!t.isIntersecting)),i=[[document,"visibilitychange",()=>o("tab",document.hidden)],[t,"pointerenter",t=>o("mouse",e.pauseOnHover&&"mouse"===t.pointerType)],[t,"pointerleave",()=>o("mouse",!1)],[t,"focusin",t=>o("focus",e.pauseOnFocus&&t.target.matches(":focus-visible"))],[t,"focusout",e=>o("focus",t.contains(e.relatedTarget)&&n.has("focus"))]];return r.observe(t),i.forEach(([t,e,n])=>t.addEventListener(e,n)),{paused:()=>n.size>0,remove(){r.disconnect(),i.forEach(([t,e,n])=>t.removeEventListener(e,n))}}})(c,i),b(),s.play(),p(o.toLowerCase()+":play"))},stop(){g&&(g=!1,m.remove(),b(),s.stop(),p(o.toLowerCase()+":stop"))},isPlaying(){return g},paused(){return!g||m.paused()},remove(){x.stop(),h.remove(),delete a[o]}};return[["init",y],["reinit",y],["resize",y],...s.events].forEach(([t,e])=>n.on(t,e)),b(),a[o]=x,x}function x(t,e,n,o,r,i=0){return t.map(t=>{const s=(i+n/2-e-(t.start+t.end)/2)/o,a=Math.round(s);return{k:a,offset:r>0?a+.5-s:s-a+.5}})}function w(t,e){return t-Math.ceil(t/e)*e}function M(t,e,n){return Math.min(n,Math.max(e,t))}function E(t,e,n){return n?(t%e+e)%e:M(t,0,e-1)}function S(t,e,n,o){return"function"==typeof t?t(e,n,o):"center"===t?(e-n)/2:"end"===t?e-n:0}function L(t){let e=1/0,n=-1/0,o=0;for(const r of t)r.hidden||(e=Math.min(e,r.start),n=Math.max(n,r.end),o=Math.max(o,r.end-r.start));return{start:e,end:n,size:n-e,max:o}}function T(t,e,n){const o=t-e;return n?o-Math.round(o/n)*n:o}function k(t,e,n,o,r,i=0,s=t.length){let a=-1,l=1/0;return t.forEach((t,c)=>{const d=Math.abs(T(t.start+e,S(o,n,t.end-t.start,c),r));c>=i&&s>c&&!t.hidden&&l-.5>d&&(l=d,a=c)}),a}function z(t,e,n){let o=0,r=1/0;return t.forEach((t,i)=>{const s=Math.abs(T(t.location,e,n));r>s&&(r=s,o=i)}),o}function A(t,e,n,o=0){return n?o>0?t+(Math.ceil((e-.5-t)/n)-1)*n:0>o?t+(Math.floor((e+.5-t)/n)+1)*n:e+T(t,e,n):t}function O(t,{min:e,max:n,period:o}){if(o){const e=(n-t)/o;return e-Math.floor(e)}return n>e?M((n-t)/(n-e),0,1):0}function P(t,e,n,o,r){const i=[];return t.forEach((t,s)=>{const a=t.end-t.start,l=r?T(t.start+e+a/2,n/2,r)+n/2-a/2:t.start+e,c=Math.min(l+a,n)-Math.max(l,0);t.hidden||0>=c||o*a-.5>c||i.push(s)}),i}function F(t){return"x"===t?document.documentElement.clientWidth:innerHeight}const C=new WeakMap,N=new WeakMap,I=new WeakMap;let _;function W(t,e){_||=new ResizeObserver(t=>{const e=[...new Set(t.filter(t=>{const{inlineSize:e,blockSize:n}=t.borderBoxSize[0],o=e+","+n,r=I.get(t.target)===o;return I.set(t.target,o),!r&&!C.get(t.target)?.skip(t)}).map(t=>C.get(t.target)))].filter(t=>t&&t.read());e.forEach(t=>t.write()),e.length&&(e.forEach(t=>N.get(t)?.forEach(t=>_.unobserve(t))),requestAnimationFrame(()=>e.forEach(t=>N.get(t)?.forEach(e=>C.get(e)===t&&_.observe(e)))))}),e&&N.set(e,t);for(const n of t)I.delete(n),e?(C.set(n,e),_.observe(n)):(C.delete(n),_.unobserve(n))}const B=new Map,H=new WeakMap,R=new WeakMap,D=[.25,1,.5,1],j=[.2,.6,.35,1];function G([t,e,n,o]){const r=(t,e,n)=>((1+3*t-3*e)*n+3*e-6*t)*n*n+3*t*n;return i=>{if(0>=i||i>=1)return i>0?1:0;let s=i;for(let a=0;6>a;a++){const a=r(t,n,s)-i,l=3*(1+3*t-3*n)*s*s+2*(3*n-6*t)*s+3*t;if(1e-5>Math.abs(a))return r(e,o,s);if(1e-6>Math.abs(l))break;s-=a/l}let a=0,l=1;for(s=i;l-a>1e-5;)r(t,n,s)<i?a=s:l=s,s=(a+l)/2;return r(e,o,s)}}const q={axis:"auto",align:"auto",dir:"auto",loop:!1,dragFree:!1,dragFriction:1,containScroll:"trimSnaps",slidesPerSnap:1,skipSnaps:!0,dragThreshold:10,duration:400,startSnap:0,lazy:!1,drag:!0,wheel:!0,keys:!0,resize:!0,slideChanges:!0,focus:!0,inViewThreshold:0,active:!0,breakpoints:{},container:null,slides:null,wrapper:!0,arrows:!0,dots:!0,dotsStyle:"zoom",labels:{carousel:"Carousel",slide:"%d of %n",prev:"Previous slide",next:"Next slide",dot:"Go to slide %d",play:"Start the slide show",pause:"Stop the slide show"},classes:null,state:"",sync:null,clones:"auto",autoplay:!1,autoScroll:!1,autoHeight:!1,progress:!1,offset:!1},V=t=>({root:t,viewport:t+"_viewport",container:t+"_container",fit:t+"_fit",horizontal:t+"_horizontal",vertical:t+"_vertical",autoHeight:t+"_auto_height",button:t+"_button",prevButton:t+"_prev",nextButton:t+"_next",dots:t+"_dots",dotsTrack:t+"_dots_track",dotsMarker:t+"_dots_marker",dotsAll:t+"_dots_all",dot:t+"_dot",playButton:t+"_play",clone:"clone",selected:"selected",inView:"",dragging:"dragging",playing:"playing",first:"first",prev:"prev",current:"current",next:"next",last:"last"}),X=["selected","inView","dragging","playing","first","prev","current","next","last"];function K(...t){const e={};for(const n of t)for(const t in n){const o=n[t],r=e[t];e[t]=o&&r&&"object"==typeof o&&"object"==typeof r&&o.constructor===Object&&r.constructor===Object?{...r,...o}:o}return e}function Y(t,...e){let n={};try{n=JSON.parse(t.dataset.carousel||"{}")}catch{}return K(q,...e,n)}const U=new WeakMap,J=t=>U.get(t),$="input,textarea,select,[contenteditable]",Q=new WeakSet,Z=[t=>{const{viewport:e,options:n}=t;if(!n.drag)return;let o,r,i,s=null,a=!1,l=[],c=0;const d=t=>["pointermove","pointerup","pointercancel"].forEach(e=>window[t](e,p));function u(e){a=!1;const n=t.geo();null!==s||e.button||!n||n.fit||Q.has(e)||e.target.closest($)||(Q.add(e),"mouse"===e.pointerType&&e.preventDefault(),s=e.pointerId,i={x:"x"===n.axis,sign:n.sign,scale:n.scale},o=[e.clientX,e.clientY],l=[],d("addEventListener"))}function p(a){if(a.pointerId!==s)return;if("pointermove"!==a.type)return l.length&&l.push([l[l.length-1][0],a.timeStamp]),f("pointerup"===a.type);const d=(a.clientX-o[0])/i.scale,u=(a.clientY-o[1])/i.scale,p=i.x?d*i.sign:u,h=i.x?u:d;if(!t.dragging()){if("mouse"!==a.pointerType&&Math.abs(h)>Math.abs(p))return f();if(n.dragThreshold>Math.abs(p))return;r=t.halt(),c=t.selected(),t.drag(!0),e.setPointerCapture(s)}const g=t.geo(),m=r+p,v=M(m,g.min,g.max);t.hold(g.period?m:v+(m-v)/4,!0),l.push([p,a.timeStamp]),l.length>10&&l.shift()}function f(e){if(d("removeEventListener"),s=null,!t.dragging())return;const o=t.geo(),i=t.location(),u=e?(t=>{const e=t[t.length-1],n=t.find(t=>100>=e[1]-t[1]),o=e[1]-n[1];return o>0?(e[0]-n[0])/o:0})(l):0,p=(({location:t,from:e,velocity:n,current:o,snaps:r,min:i,max:s,period:a,skipSnaps:l,dragFree:c,dragFriction:d=1})=>{const u=r.length;let p=t+325*n/d;if(a||(p=M(p,i,s)),"number"==typeof l&&l>0&&u-1+!a>l){const t=t=>A(r[E(o+t*l,u,a)].location,e,a,t);p=M(p,t(1),t(-1))}if(!0===c)return{location:p,snap:z(r,p,a)};if(c||l){const t=z(r,p,a);return{location:A(r[t].location,p,a),snap:t}}const f=t-e;let h=0;Math.abs(n)>.3?h=0>n?1:-1:Math.abs(f)>20&&(h=0>f?1:-1);const g=E(o+h,u,a),m=r[g].location;return{location:a?A(m,h?e:t,a,g===o?0:h):m,snap:g}})({location:i,from:r,velocity:u,current:c,snaps:o.snaps,min:o.min,max:o.max,period:o.period,skipSnaps:n.skipSnaps,dragFree:n.dragFree,dragFriction:n.dragFriction}),f=!0===n.dragFree?j:D;a=!0,t.drag(!1),t.move(p.snap,p.location,((t,e,n,o)=>Math.sign(t)!==Math.sign(e)||.05>Math.abs(e)?o:M(Math.abs(t)*n[1]/n[0]/Math.abs(e),200,1200))(p.location-i,u,f,n.duration),f)}function h(t){a&&(a=!1,t.preventDefault(),t.stopPropagation())}const g=t=>t.preventDefault(),m=e=>t.dragging()&&e.preventDefault();return e.addEventListener("pointerdown",u),e.addEventListener("click",h,!0),e.addEventListener("dragstart",g),e.addEventListener("selectstart",m),{remove(){d("removeEventListener"),e.removeEventListener("pointerdown",u),e.removeEventListener("click",h,!0),e.removeEventListener("dragstart",g),e.removeEventListener("selectstart",m)}}},t=>{const{viewport:e,options:n}=t,o=!0===n.dragFree;if(!n.wheel)return;let r=0,i=0,s=!1,a=!1,l=0,c=0,d=0;function u(n){const u=t.geo(),f="x"===u.axis&&Math.abs(n.deltaX)>Math.abs(n.deltaY),h=f?n.deltaX*u.sign:n.deltaY;if(n.ctrlKey||!h||t.dragging())return;const g=n.timeStamp,m=200>g-r,v=Math.abs(h),b=m&&i>=v;if(i=v,m||(s=!1),m&&a||((t,e,n,o)=>{const[r,i,s,a]="x"===n?["scrollWidth","clientWidth","scrollLeft","overflowX"]:["scrollHeight","clientHeight","scrollTop","overflowY"];for(;t&&t!==e;t=t.parentElement)if(t[r]>t[i]&&/auto|scroll/.test(getComputedStyle(t)[a])){const e=Math.abs(t[s]);if(o>0?t[r]-1>e+t[i]:e>0)return!0}return!1})(n.target,e,f?"x":"y",f?n.deltaX:h))return a=!0,void(r=g);a=!1;const y=t.location(),x=h*(1===n.deltaMode?40:n.deltaMode?u.view:1);let w=y-x;u.period||(w=M(w,u.min,u.max)),r=g,.5>Math.abs(w-y)?s&&b&&n.preventDefault():(n.preventDefault(),t.emit("interact"),l||(c=t.selected()),s=!0,d=x>0?1:-1,t.move(z(u.snaps,w,u.period),w,180,D),clearTimeout(l),o||(l=setTimeout(p,150)))}function p(){l=0;const e=t.geo(),n=t.current(),o=z(e.snaps,n,e.period),r=Math.abs(A(e.snaps[o].location,n,e.period)-n)>10;t.step(o,o===c&&r?d:0)}function f(){const o=t.geo();e[o.fit||"y"!==o.axis&&"both"!==n.wheel?"removeEventListener":"addEventListener"]("wheel",u,{passive:!1})}return["init","reinit","resize"].forEach(e=>t.on(e,f)),{remove(){e.removeEventListener("wheel",u),clearTimeout(l)}}},t=>{const{api:e,root:n,options:o}=t;if(o.keys)return n.addEventListener("keydown",r),{remove(){n.removeEventListener("keydown",r)}};function r(n){const o=t.geo(),{key:r,target:i}=n,s=o&&!o.fit&&("y"===o.axis?{ArrowUp:-1,ArrowDown:1}:{ArrowLeft:-o.sign,ArrowRight:o.sign})[r],a=s>0?"Next":"Prev";s&&!(n.altKey||n.ctrlKey||n.metaKey||n.shiftKey||i.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(i.tagName))&&e["canGoTo"+a]()&&(n.preventDefault(),e["goTo"+a]())}},t=>{const{api:e,container:n,options:o}=t;let r=-1e4;function i(t){t.target.closest($)||(r=t.timeStamp)}function s(n){const i=t.geo(),s=e.slideNodes().findIndex(t=>t.contains(n.target));!i||0>s||600>n.timeStamp-r||(o.focus&&!P(i.slides,t.location(),i.view,1,i.period).map(t=>t%i.count).includes(s)&&e.goToSlide(s),t.emit("slidefocus"))}return n.addEventListener("pointerdown",i),n.addEventListener("focusin",s),{remove(){n.removeEventListener("pointerdown",i),n.removeEventListener("focusin",s)}}},n=>{const{api:o,root:s,cls:a,options:l}=n,c=l.labels,d=i(l.arrows,s),u=i(l.dots,s),p=[],f=[],h="all"!==l.dotsStyle,g=u&&r("div",h?a.dots:a.dots+" "+a.dotsAll),m=g&&r("div",a.dotsTrack);let v=new Map;if(d||u)return g&&(m.append(r("span",a.dotsMarker)),g.append(m),u.append(g)),d&&[["prev","goToPrev"],["next","goToNext"]].forEach(([t,e])=>{const i=r("button",a.button+" "+a[t+"Button"]);i.type="button",i.setAttribute("aria-label",c[t]),i.setAttribute("aria-controls",n.container.id),i.addEventListener("click",()=>o[e]()),p.push(i)}),["init","reinit","resize","select","slideschanged"].forEach(t=>n.on(t,b)),{remove(){p.forEach(t=>t.remove()),g?.remove()}};function b(){const i=o.isFit(),s=i?0:o.snapProgress().length,l=o.selectedSnap();if(p.forEach((t,e)=>{if(i)t.remove();else{t.isConnected||(g?.parentNode===d?g.before(t):d.append(t));const n=!(e?o.canGoToNext():o.canGoToPrev());t.disabled!==n&&(t.disabled=n)}}),!g)return;if(2>s)return void g.remove();for(;f.length>s;)f.pop().remove(),v.delete(f.length);for(;s>f.length;){const t=r("button",a.dot),e=f.length;t.type="button",t.setAttribute("aria-label",c.dot.replace("%d",e+1)),t.setAttribute("aria-controls",n.container.id),h&&(t.tabIndex=-1),t.addEventListener("click",()=>o.goToSnap(e)),f.push(t),m.append(t)}g.isConnected||u.append(g);const b=new Map;["first","prev","current","next","last"].forEach((t,e)=>{f[l+e-2]&&b.set(l+e-2,a[t])}),v.forEach((n,o)=>{b.get(o)!==n&&(t(f[o],n,!1),e(f[o],"aria-current",!1),f[o].tabIndex=h?-1:0)}),b.forEach((n,o)=>{t(f[o],n,!0),e(f[o],"aria-current",o===l&&"true"),f[o].tabIndex=0}),v=b,h&&y("--better-shift",2-(Math.max(0,l-2)+Math.min(s-1,l+2))/2),y("--better-dot",l)}function y(t,e){g.style.getPropertyValue(t)!==e+""&&g.style.setProperty(t,e)}},t=>{if(!t.options.autoplay)return;const e=t.api,n=b(m,"delay",t.options.autoplay);let o=0,r=null,i=!1;function s(){clearTimeout(o),r?.(),r=null}function a(){if(s(),!c.paused()&&!e.isFit()){const t=e.slideNodes()[e.selectedSlide()]?.dataset.delay||n.delay,i=+(Array.isArray(t)?t[e.selectedSnap()]:t);o=setTimeout(l,i),r=n.timer?.(i,e)}}function l(){s(),i=!0,e.canGoToNext()?e.goToNext(n.instant):n.stopOnLastSnap?c.stop():e.goToSnap(0,n.instant),i=!1}const c=y(t,"autoplay",n,{play:a,stop:s,pause:a,events:[["settle",a],["interact",()=>{i||(s(),n.stopOnInteraction&&c.stop())}]]});return c.reset=a,c},t=>{if(!t.options.autoScroll)return;const e=b(v,"speed",t.options.autoScroll);let n=0,o=!1;const r=y(t,"autoScroll",e,{play:i,stop(){i(-1),t.halt()},pause(e){e?t.halt():n||s()},events:[["settle",()=>r.isPlaying()&&i()],["resize",()=>r.isPlaying()&&!n&&s()],["interact",()=>{r.isPlaying()&&(i(-1),e.stopOnInteraction&&r.stop())}]]});function i(t){clearTimeout(n),n=t?0:setTimeout(s,e.startDelay)}function s(){n=0;const i=t.geo();!i||i.fit||o||t.dragging()||r.paused()||t.scroll("prev"===e.direction?-1:1,e.speed/1e3)}const a=t=>["pointerup","pointercancel"].forEach(e=>window[t](e,c));function l(e){e.button||!r.isPlaying()||o||(o=!0,i(-1),t.halt(),a("addEventListener"))}function c(){o=!1,a("removeEventListener"),r.isPlaying()&&!t.dragging()&&i()}const{viewport:d}=t,u=r.remove;return d.addEventListener("pointerdown",l),r.remove=()=>{d.removeEventListener("pointerdown",l),a("removeEventListener"),u()},r},t=>{const{api:e,container:n}=t,o=t.options.sync;let r=null;if(o)return t.on("init",l),t.on("reinit",l),n.addEventListener("click",a),{remove(){r?.off("select",s),n.removeEventListener("click",a)}};function s(n){const o=r.selectedSlide();t.follow(o),e.goToSlide(o,!0===n)}function a(n){const o=t.nodes().findIndex(t=>t.contains(n.target));r&&o>-1&&r.goToSlide(o%e.slideNodes().length)}function l(){r||(r=o.goToSnap?o:J("string"==typeof o?i(o,t.root):o),r&&(r.on("select",s),s(!0)))}}];function tt(e,i={}){return((e,i,p,m)=>{const v=U.get(e);if(v)return v;let b,y,C,N,I,_,j,q,J=[],$=[],Q=[],Z=[],tt=[],et=null,nt=!1,ot=!1,rt=!1,it=[],st=0,at=-1,lt=0,ct=null,dt=0,ut=0,pt=0,ft=-1,ht=-1,gt=[],mt={axis:"",container:0,slides:[]},vt=!1,bt=!1;const yt={goToSnap:(t,e)=>Jt(_t(t),e),goToNext:t=>ct?yt.canGoToNext()&&Ut(ut,1,t):Jt(ut+1,t),goToPrev:t=>ct?yt.canGoToPrev()&&Ut(ut,-1,t):Jt(ut-1,t),goToSlide:(t,e)=>Jt(_t(yt.snapOfSlide(t)),e,t),canGoToNext:()=>!(!ct||ct.fit||!ct.period&&ut>=ct.snaps.length-1),canGoToPrev:()=>!(!ct||ct.fit||!ct.period&&0>=ut),selectedSnap:()=>It(ut),previousSnap:()=>It(pt),selectedSlide:Wt,snapOfSlide:t=>ct?It(((t,e,n,o,r,i)=>{const s=t.findIndex(t=>t.slide===n),a=e[n];return s>-1||!a?Math.max(s,0):z(t,S(r,o,a.end-a.start,n)-a.start,i)})(ct.snaps,ct.slides,t,ct.view,ct.align,ct.period)):t,snapProgress:()=>ct?ct.logical.map(t=>O(ct.snaps[t].location,ct)):[],progress:()=>ct?O(Bt(),ct):0,slideNodes:()=>J.slice(),slidesInView:()=>gt.slice(),rootNode:()=>C,viewportNode:()=>N,containerNode:()=>I,isFit:()=>!ct||ct.fit,options:()=>b,reinit:At,destroy(){zt(!1),xt.emit("destroy")}},xt=(t=>{const e={},n={},o=(t,e,n)=>(t[e]||=new Set).add(n);return{on:(n,r)=>(o(e,n,r),t),off:(n,o)=>(e[n]?.delete(o),t),listen(t,e){return o(n,t,e)},clear(){return Object.values(n).forEach(t=>t.clear())},emit(o){n[o]?.forEach(e=>e(t,o)),e[o]?.forEach(e=>e(t,o))},has(t){return!!e[t]?.size}}})(yt),wt={read:Ht,write:Dt,skip({target:t,contentRect:{width:e}}){if(t!==N)return!1;const n=e===st;return st=e,n&&b.autoHeight&&"x"===ct?.axis}},Mt={progress:0,snap:0},Et={node:null,index:0,offset:0,distance:0,size:0,visible:0},St={api:yt,emit:xt.emit,on:xt.listen,geo:()=>ct,nodes:()=>Q,selected:()=>ut,dragging:()=>vt,location:()=>bt?Bt():dt,current:Bt,hold(t,e){dt=t,(e?te:Vt)(t),Zt()},halt:ne,step:Ut,scroll(t,e){const n=ne(),o=t>0?ct.min:ct.max;ct.period?(bt=!0,dt=w(n,ct.period),q.loop(dt,t,ct.period/e,ct,Q)):Math.abs(o-n)>1&&(bt=!0,dt=o,q.run(n,o,Math.abs(o-n)/e,[0,0,1,1],xt.has("scroll")))},move(t,e,n,o){ft=-1,$t(t,e,n,o)},drag(e){vt=e,t(C,y.dragging,e),e?(xt.emit("interact"),xt.emit("dragstart")):xt.emit("dragend")},follow(t){ht=t}};yt.on=xt.on,yt.off=xt.off;let Lt=Y(e,p,i),Tt=Lt.lazy?((t,e,n)=>{const o=!0===e?innerHeight:e,r=R.get(t)||t.getBoundingClientRect(),i=!0===e?"100%":e+"px";if(R.delete(t),r.height&&r.bottom>=-o&&r.top<=innerHeight+o)return null;let s=B.get(i);return s||(s=new IntersectionObserver(t=>t.forEach(t=>t.isIntersecting&&H.get(t.target)?.()),{rootMargin:i}),B.set(i,s)),H.set(t,n),s.observe(t),()=>{s.unobserve(t),H.delete(t)}})(e,Lt.lazy,At):null;return Tt?U.set(e,yt):kt(),yt;function kt(){if(et=((t,e)=>{const n=Object.entries(t.breakpoints||{}).map(([t,e])=>[matchMedia(t),e]);return n.forEach(([t])=>t.addEventListener("change",e)),{options:K(t,...n.filter(([t])=>t.matches).map(([,t])=>t)),remove(){return n.forEach(([t])=>t.removeEventListener("change",e))}}})(Lt||Y(e,p,i),()=>At()),Lt=null,b=et.options,b.active){y=((t,e)=>{const n="string"==typeof t?V(t):{...V(t?.prefix||"better"),...t};for(const t of X)n[t]&&(n[t]=e+n[t]);return n})(b.classes,b.state),({root:C,viewport:N,container:I}=((t,e,n)=>{let o=e.container?t.querySelector(e.container):t;o.classList.contains(n.viewport)&&(o=o.firstElementChild);let i=o.parentElement,s=i.parentElement;return d.has(i)||i.classList.contains(n.viewport)||!e.wrapper||(s=r("div"),i=r("div"),d.add(s).add(i),o.before(s),s.append(i),i.append(o)),c(s,n.root),c(i,n.viewport),c(o,n.container),l(s,"role","region"),l(s,"aria-roledescription","carousel"),s.hasAttribute("aria-labelledby")||l(s,"aria-label",e.labels.carousel),l(o,"id",o.id||"carousel-"+ ++u),l(o,"aria-live","polite"),{root:s,viewport:i,container:o}})(e,b,y));for(const t of[C,N,I])U.set(t,yt);J=f(I,b.slides),Q=J,ut=b.startSnap,Ft(!0),Object.assign(St,{root:C,viewport:N,container:I,cls:y,options:b}),Z=m.map(t=>t(St)).filter(Boolean),q=((t,e,n,o,r)=>{let i=null;const s=()=>i.animations?i.animations[0].currentTime||0:performance.now()-i.start,a=()=>i&&i.from+(i.to-i.from)*i.ease(s()/i.duration);function l(){if(!i.animations&&s()>=i.duration)return c();i.raf=requestAnimationFrame(l),(i.animations?r:n)(a())}function c(){const t=i.to;d(),n(t),o()}function d(){const t=a();return i&&(i.animations?.forEach(t=>t.cancel()),cancelAnimationFrame(i.raf),i=null),t}function u(n){const o=t.animate([{translate:e(i.from)},{translate:e(i.to)}],{duration:i.duration,easing:"cubic-bezier("+i.curve+")",fill:"forwards"});o.currentTime=n,o.onfinish=c,i.animations=[o]}function p(n,o){if(d(),i=n,n.list){const r={duration:n.duration,iterations:1/0},i=document.timeline.currentTime,{from:s,to:a,length:l,direction:c}=n;n.animations=[t.animate([{translate:e(s)},{translate:e(a)}],r),...o.map((t,o)=>{const{k:i,offset:s}=n.list[o],a=e(i*l),d=e((i+c)*l);return t.animate([{translate:a},{translate:a,offset:s},{translate:d,offset:s},{translate:d}],r)})],n.animations.forEach(t=>t.startTime=i)}else n.script?n.start=performance.now():u(0);(n.script||r)&&(n.raf=requestAnimationFrame(l))}return{run(t,e,n,o,r){return p({from:t,to:e,duration:n,curve:o,script:r,ease:G(o)})},loop(t,e,n,o,r){return p({from:t,to:t-e*o.period,duration:n,direction:e,length:o.period,list:x(o.slides,t,o.area.size,o.period,e,o.area.start),ease(t){return t%1}},r)},retarget(t){if(!i||i.list)return!1;if(t!==i.to&&(i.to=t,i.animations)){const t=s();i.animations[0].cancel(),u(t)}return!0},stop:d,current:a,shifts(t){if(!i?.list)return null;const e=s()/i.duration%1;return i.list.map(({k:n,offset:o})=>t*(o>e?n:n+i.direction)*i.length)}}})(I,Yt,te,ee,(b.progress||b.offset)&&(t=>Xt(t,q.shifts(ct.sign)||mt.slides))),b.autoHeight&&c(C,y.autoHeight),N.addEventListener("scroll",oe),b.loop&&"fill"===b.clones&&addEventListener("resize",Rt),b.slideChanges&&(_=new MutationObserver(Ct),_.observe(I,{childList:!0}))}}function zt(r){if(Tt?.(),Tt=null,U.delete(e),Ft(!1),_?.disconnect(),et?.remove(),et=null,y){q.stop(),Z.forEach(t=>t.remove()),xt.clear(),Z=[],ht=-1,vt=bt=!1,Ot(0),N.removeEventListener("scroll",oe),removeEventListener("resize",Rt);for(const e of Q)n(e,"translate",""),e.style.removeProperty("--better-offset"),t(e,y.selected,!1),t(e,y.inView,!1),o(e);n(I,"translate",""),n(I,"willChange",""),n(N,"touchAction",""),n(N,"height",""),C.style.removeProperty("--better-progress");for(const e of["horizontal","vertical","fit","dragging"])t(C,y[e],!1);for(const t of[C,N,I])o(t),U.delete(t);((t,e,n,o,r)=>{for(const r of[t,e,n,...o])s.get(r)?.forEach(t=>r.removeAttribute(t)),a.get(r)?.forEach(t=>r.classList.remove(t)),s.delete(r),a.delete(r),""===r.getAttribute("class")&&r.removeAttribute("class");!r&&d.has(t)&&(t.before(n),t.remove())})(C,N,I,J,r),y=ct=null,nt=!1,dt=0,gt=[],it=[],st=0,mt={axis:"",container:0,slides:[]}}}function At(t){t&&(i=K(i,t),Lt=null);const e=ct?Wt():ft;St.playing=t?null:{autoplay:yt.autoplay?.isPlaying(),autoScroll:yt.autoScroll?.isPlaying()},zt(!0),kt(),ft=e}function Ot(e){$.length!==e*J.length&&($.forEach(t=>t.remove()),$=((e,n,r)=>{const i=[];for(let s=0;n>s;s++)for(const n of e){const e=n.cloneNode(!0);h(e),e.setAttribute("aria-hidden","true"),e.inert=!0,e.style.translate="",t(e,r,!0),o(e),d.add(e),i.push(e)}return i})(J,e,y.clone),I.append(...$),Q=J.concat($),mt.slides.length=J.length,_?.takeRecords(),j?.disconnect(),$.length&&(j||=new MutationObserver(Pt),J.forEach(t=>j.observe(t,{childList:!0,characterData:!0,subtree:!0,attributeFilter:["class","src","srcset","href","value"]}))))}function Pt(t){new Set(t.filter(t=>"attributes"!==t.type||!J.includes(t.target)).map(({target:t})=>J.find(e=>e.contains(t)))).forEach(t=>{for(let e=J.indexOf(t);t&&$.length>e;e+=J.length)g($[e],t)})}function Ft(t){W(tt),tt=t?[N,I,...Q]:[],W(tt,wt)}function Ct(){const t=nt?Wt():-1,e=J[t];if(J=f(I,b.slides),t>-1){const n=J.indexOf(e);ft=n>-1?n:Math.min(t,J.length-1)}Ot(0),Q=J,rt=!0,Ft(!0)}function Nt(t){return t%J.length}function It(t){return ct?ct.map[t]??0:t}function _t(t){return ct?((t,e,n)=>{let o=-1,r=1/0;return t.snaps.forEach((i,s)=>{const a=Math.abs(T(i.location,n,t.period));t.map[s]===e&&r>a&&(r=a,o=s)}),0>o?M(e,0,t.snaps.length-1):o})(ct,t,Bt()):t}function Wt(){return ht>-1?ht:ct?0>ft||yt.snapOfSlide(ft)!==It(ut)?Nt(ct.snaps[ut].slide):ft:Math.max(ft,0)}function Bt(){return q.current()??dt}function Ht(){const t=ct?.sign||1,e=q.current(),n=((t,e)=>{const n=getComputedStyle(t),o=n.display,r=n.justifyContent;let i=e.axis;"auto"===i&&(i="x",o.includes("grid")?i=n.gridAutoFlow.startsWith("column")?"x":"y":o.includes("flex")&&n.flexDirection.startsWith("column")&&"nowrap"===n.flexWrap&&(i="y"));let s=e.align;"auto"===s&&(s="center"===r?"center":"flex-end"===r||"end"===r||"x"===i&&"right"===r?"end":"start");const a="x"===i&&("auto"===e.dir?"rtl"===n.direction:"rtl"===e.dir);return{axis:i,align:s,rtl:a,sign:a?-1:1,gap:parseFloat("x"===i?n.columnGap:n.rowGap)||0}})(I,b),o=((t,e,n,o)=>{const r=t.getBoundingClientRect(),i="x"===n.axis,s=n.sign,a=o.axis===n.axis,l=a?o.container:0,c=t.offsetWidth,d=t.offsetHeight,u=c&&d&&(Math.abs(r.width-c)>=1||Math.abs(r.height-d)>=1),p=u?Math.abs(c-d)>1?(c*r.width-d*r.height)/(c*c-d*d):r.width/c:1,f=u?i?c:d:i?r.width:r.height,h=getComputedStyle(t),[g,m]=i?n.rtl?["Right","Left"]:["Left","Right"]:["Top","Bottom"],v={start:parseFloat(h["padding"+g])||0,end:parseFloat(h["padding"+m])||0},b=e.map((t,e)=>{const c=t.getBoundingClientRect(),d=(i?n.rtl?r.right-c.right:c.left-r.left:c.top-r.top)/p-v.start-s*(l+(a&&o.slides[e]||0));return{start:d,end:d+(i?c.width:c.height)/p,cross:(i?c.height:c.width)/p,hidden:!c.width&&!c.height}});let y=b.find(t=>!t.hidden)?.start||0;for(const t of b)t.hidden?t.start=t.end=y:y=t.end;let x=Math.max(0,b.findIndex(t=>!t.hidden)),w=x;b.forEach((t,e)=>{t.hidden||(b[x].start>t.start&&(x=e),t.end>b[w].end&&(w=e))});let M=n.gap;if(b.length){const t=i?n.rtl?["Right","Left"]:["Left","Right"]:["Top","Bottom"];M+=(parseFloat(getComputedStyle(e[x])["margin"+t[0]])||0)+(parseFloat(getComputedStyle(e[w])["margin"+t[1]])||0)}return{view:f-v.start-v.end,slides:b,gap:M,scale:p,pad:v}})(N,Q,n,null===e?mt:{axis:mt.axis,container:t*e,slides:q.shifts(t)||mt.slides});lt=b.loop&&"fill"===b.clones?F(n.axis):0;const r=((t,e,n,o,r)=>{if(!r)return{start:-o.start,size:o.start+n+o.end};const i=t.getBoundingClientRect(),s=Math.max(0,Math.round("x"===e.axis?e.rtl?r-i.right:i.left:i.top))+o.start;return{start:-s,size:s+Math.max(n+o.end,Math.round(r-s))}})(N,n,o.view,o.pad,lt),i=[n.axis,n.rtl,"string"==typeof n.align&&n.align,o.view,o.gap,r.start,r.size,...o.slides.flatMap(t=>[t.start,t.end,t.cross])];if(nt&&i.length===it.length&&i.every((t,e)=>t===it[e]||.5>Math.abs(t-it[e])))return!1;it=i;const s=nt&&!rt?Wt():ft,a=function(t,e,n,o,r){const i=L(e.slides.slice(0,o)),s=!(i.size>e.view+1||r.autoScroll&&r.loop),a=r.loop&&!s&&o,l=a?L(e.slides).size+e.gap:0,c=a&&r.clones&&(d=i.size+e.gap)>0?Math.max(0,Math.ceil((n.size+i.max)/d)-1):0;var d;if(c*o!==e.slides.length-o)return{copies:c};const u={...t,...e,area:n,fit:s,count:o,period:l,min:0,max:0};s?u.snaps=[{location:0,slide:Math.max(0,k(e.slides,0,e.view,t.align))}]:Object.assign(u,(({slides:t,view:e,align:n,slidesPerSnap:o,containScroll:r,period:i=0})=>{const s=L(t);let a=-s.start||0,l=e-s.end,c=((t,e,n)=>{const o=[];let r,i=0;for(const s of t)r&&("auto"===n?r&&e+1>=s.end-r.start:n>i)?(r.end=Math.max(r.end,s.end),i++):(r={start:s.start,end:s.end},o.push(r),i=1);return o})((t=>{const e=t.map((t,e)=>e).filter(e=>!t[e].hidden).sort((e,n)=>t[e].start-t[n].start||e-n),n=[];let o;for(const r of e){const e=t[r];o&&1>=e.start-o.start?o.end=Math.max(o.end,e.end):(o={start:e.start,end:e.end},n.push(o))}return n})(t),e,o).map((t,o)=>S(n,e,t.end-t.start,o)-t.start);i||(r?c=c.map(t=>M(t,l,a)):(a=Math.max(...c),l=Math.min(...c))),(i||"keepSnaps"!==r)&&(c=c.filter((t,e)=>!e||Math.abs(T(t,c[e-1],i))>1),i&&c.length>1&&1>=Math.abs(T(c[0],c[c.length-1],i))&&c.pop());const d=c.map(o=>({location:o,slide:k(t,o,e,n,i)})),u=(o,r,i)=>{const s=k(t,o.location,e,n,0,r,i);o.slide=s>-1?s:o.slide};if(!i&&d.length>1){const e=d[0],n=d[d.length-1];d[1].slide>e.slide||u(e,0,d[1].slide),n.slide>d[d.length-2].slide||u(n,d[d.length-2].slide+1,t.length)}return{snaps:d,min:l,max:i?c[0]:a}})({...e,align:t.align,slidesPerSnap:r.slidesPerSnap,containScroll:r.containScroll,period:l}));const p=u.snaps.map((t,e)=>e).filter(t=>!c||o>u.snaps[t].slide);return u.logical=p,u.map=u.snaps.map((t,e)=>c?Math.max(0,p.findIndex(e=>u.snaps[e].slide%o===t.slide%o)):e),u}(n,o,r,J.length,b);if(!a.snaps)return at=a.copies,!0;ct=a;const l=ct.snaps.length,c=ct.logical.length;return ut=0>s?Math.min(l-1,nt?ut:_t(ct.period?(ut%c+c)%c:Math.max(ut,0))):_t(yt.snapOfSlide(s)),pt=Math.min(pt,l-1),ft=s,vt||(dt=A(ct.snaps[ut].location,dt,ct.period)),!0}function Rt(){ct&&F(ct.axis)!==lt&&Ht()&&Dt()}function Dt(){if(at>=0)return Ot(at),at=-1,it=[],void Ft(!0);bt&&ne();const t=q.current();null!==t&&mt.axis===ct.axis&&!ct.fit&&q.retarget(dt)?(Kt(t,dt),jt(!0)):(q.stop(),jt(vt)),((t,e)=>{t.forEach((n,o)=>{n.matches("a[href],button,input,select,textarea,[tabindex],[role]")&&!s.get(n)?.has("role")||(n.matches("div,span,section")&&l(n,"role","group"),l(n,"aria-roledescription","slide"),l(n,"aria-label",e.replace("%d",o+1).replace("%n",t.length)))})})(J,b.labels.slide),b.resize||Ft(!1),nt?xt.emit("resize"):(nt=!0,xt.emit(ot?"reinit":"init"),ot=!0),rt&&(rt=!1,xt.emit("slideschanged"))}function jt(e){const o="x"===ct.axis;t(C,y.horizontal,o),t(C,y.vertical,!o),t(C,y.fit,ct.fit),n(N,"touchAction",ct.fit?"":o?"pan-y pinch-zoom":"pan-x pinch-zoom"),n(I,"willChange",ct.fit?"":"translate"),e||Vt(ct.fit?0:dt),b.autoHeight&&n(N,"height",o?Math.max(...P(ct.slides,dt,ct.view,0,ct.period).map(t=>ct.slides[t].cross))+"px":"");const r=Wt(),i=[...new Set(P(ct.slides,dt,ct.view,b.inViewThreshold,ct.period).map(Nt))].sort((t,e)=>t-e);Q.forEach((e,n)=>t(e,y.selected,Nt(n)===r)),i.join()!==gt.join()&&(gt=i,Q.forEach((e,n)=>t(e,y.inView,i.includes(Nt(n)))),xt.emit("slidesinview"))}function Gt(t){const e=devicePixelRatio||1;return Math.round(t*e)/e*ct.sign}function qt(t){return t?"x"===ct.axis?t+"px":"0 "+t+"px":""}function Vt(t){mt.axis!==ct.axis&&(Q.forEach(t=>n(t,"translate","")),mt={axis:ct.axis,container:0,slides:[]}),mt.container=Gt(t),n(I,"translate",qt(mt.container)),Kt(t,t),(b.progress||b.offset)&&Xt(t,mt.slides)}function Xt(t,e){if(!0===b.progress)C.style.setProperty("--better-progress",O(t,ct));else if(b.progress){const e=((t,e,n)=>{const o=t.length-1,r=t[0].location,i=n?r-((r-e)%n+n)%n:M(e,t[o].location,r);let s=0;for(;o>s&&t[s+1].location>=i;)s++;const a=t[s].location,l=o>s?t[s+1].location:r-n;return s+(a>l?(a-i)/(a-l):0)})(ct.snaps,t,ct.period),n=Math.floor(e);Mt.progress=O(t,ct),Mt.snap=It(n)+e-n,b.progress(Mt,yt)}b.offset&&Q.forEach((n,o)=>{const r=ct.slides[o],i=r.end-r.start,s=r.start+ct.sign*(e[o]||0)+t,a=s-S(ct.align,ct.view,i,o),l=a/(i+ct.gap);!0===b.offset?n.style.setProperty("--better-offset",l):(Et.node=n,Et.index=Nt(o),Et.offset=l,Et.distance=ct.sign*a,Et.size=i,Et.visible=M((Math.min(s+i,ct.view)-Math.max(s,0))/i,0,1)||0,b.offset(Et,yt))})}function Kt(t,e){const o=ct.period?((t,e,n,o,r,i=0)=>{const s=i+(o-e-n)/2;return t.map(t=>Math.round((s-(t.start+t.end)/2)/r)||0)})(ct.slides,t,e,ct.area.size,ct.period,ct.area.start):[];Q.forEach((t,e)=>{const r=o.length?Gt(o[e]*ct.period):0;(mt.slides[e]||0)!==r&&(mt.slides[e]=r,n(t,"translate",qt(r)))})}function Yt(t){return qt(Gt(t))||"0px"}function Ut(t,e,n){Jt(E(t+e,ct.snaps.length,ct.period),n,-1,e)}function Jt(t,e,n=-1,o=0){if(Tt&&At(),xt.emit("interact"),ft=n,!ct)return void(ut=t);const r=A(ct.snaps[t].location,Bt(),ct.period,o),i=Math.abs(t-ut);var s,a;$t(t,r,e?0:(s=b.duration,(a=ct.period?Math.min(i,ct.snaps.length-i):i)>1?Math.min(2*s,s*(1+Math.log2(a))):s),D)}function $t(t,e,n,o){const r=ne(),i=Qt(t),s=!n||ct.fit||.5>Math.abs(e-r);if(dt=e,s)jt();else{const t=xt.has("scroll")||!!ct.period&&!((t,e,n,o,r)=>{const i=o+Math.abs(n-e);return t.every(t=>r>=i+t.end-t.start)})(ct.slides,r,e,ct.area.size,ct.period);jt(!0),t||Kt(r,e),q.run(r,e,n,o,t)}i&&xt.emit("select"),s&&ee()}function Qt(t){return t!==ut&&(pt=ut,ut=t,!0)}function Zt(){Qt(z(ct.snaps,dt,ct.period))&&(jt(!0),xt.emit("select"))}function te(t){Vt(t),xt.emit("scroll")}function ee(){bt&&(bt=!1,Zt()),ct.period&&(dt=w(dt,ct.period)),jt(),xt.emit("settle")}function ne(){const t=q.stop();return null!==t&&(dt=t,Vt(t),bt&&Zt()),bt=!1,dt}function oe(){N.scrollLeft=N.scrollTop=0}})(e,i,tt.defaults,Z)}return tt.defaults={},tt.get=J,tt.initAll=(t,e)=>{const n=[...document.querySelectorAll(t)];return(t=>{t.forEach(t=>R.set(t,t.getBoundingClientRect()))})(n.filter(t=>!J(t)&&Y(t,tt.defaults,e).lazy)),n.map(t=>tt(t,e))},tt})();
|
package/package.json
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@twistedandy/better-carousel",
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "A small and fast carousel that takes all sizes, gaps and the layout from CSS.",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/TwistedAndy/better-carousel.git"
|
|
8
|
+
},
|
|
9
|
+
"homepage": "https://twistedandy.github.io/better-carousel/",
|
|
10
|
+
"bugs": "https://github.com/TwistedAndy/better-carousel/issues",
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public"
|
|
13
|
+
},
|
|
14
|
+
"type": "module",
|
|
15
|
+
"main": "./dist/better-carousel.js",
|
|
16
|
+
"module": "./dist/better-carousel.js",
|
|
17
|
+
"types": "./src/types/better-carousel.d.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./src/types/better-carousel.d.ts",
|
|
21
|
+
"import": "./dist/better-carousel.js",
|
|
22
|
+
"default": "./dist/better-carousel.js"
|
|
23
|
+
},
|
|
24
|
+
"./css": "./dist/better-carousel.css",
|
|
25
|
+
"./scss": "./src/styles/better-carousel.scss"
|
|
26
|
+
},
|
|
27
|
+
"sideEffects": [
|
|
28
|
+
"*.css",
|
|
29
|
+
"*.scss"
|
|
30
|
+
],
|
|
31
|
+
"files": [
|
|
32
|
+
"dist",
|
|
33
|
+
"src"
|
|
34
|
+
],
|
|
35
|
+
"scripts": {
|
|
36
|
+
"build": "rollup -c",
|
|
37
|
+
"dev": "rollup -c -w",
|
|
38
|
+
"docs": "node scripts/docs.mjs",
|
|
39
|
+
"test": "node --test tests/",
|
|
40
|
+
"e2e": "node tests/e2e.mjs",
|
|
41
|
+
"bench": "npm run build && npm install --prefix bench --no-audit --no-fund && npm start --prefix bench --"
|
|
42
|
+
},
|
|
43
|
+
"keywords": [
|
|
44
|
+
"carousel",
|
|
45
|
+
"slider",
|
|
46
|
+
"css"
|
|
47
|
+
],
|
|
48
|
+
"license": "MIT",
|
|
49
|
+
"author": "Andrii Toniievych",
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@rollup/plugin-terser": "^1.0.2",
|
|
52
|
+
"puppeteer-core": "^25.17.0",
|
|
53
|
+
"rollup": "^4.68.4",
|
|
54
|
+
"sass": "^1.108.2"
|
|
55
|
+
}
|
|
56
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Entry point: the BetterCarousel function, its features, and its static members defaults, get() and initAll().
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { autoplay, autoScroll } from './scripts/autoplay.js';
|
|
6
|
+
import carousel, { find } from './scripts/carousel.js';
|
|
7
|
+
import { drag, focus, keys, wheel } from './scripts/input.js';
|
|
8
|
+
import { readBoxes } from './scripts/layout.js';
|
|
9
|
+
import { nav, sync } from './scripts/navigation.js';
|
|
10
|
+
import { resolve } from './scripts/options.js';
|
|
11
|
+
|
|
12
|
+
// The features. Their event handlers run in this order.
|
|
13
|
+
const features = [drag, wheel, keys, focus, nav, autoplay, autoScroll, sync];
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Make a carousel, or get the carousel of an element that has one.
|
|
17
|
+
*
|
|
18
|
+
* @param {HTMLElement} element The container of the slides, or its viewport.
|
|
19
|
+
* @param {object} [options]
|
|
20
|
+
* @returns {object} The carousel API.
|
|
21
|
+
*/
|
|
22
|
+
export default function BetterCarousel(element, options = {}) {
|
|
23
|
+
return carousel(element, options, BetterCarousel.defaults, features);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// The site defaults. They merge over the library defaults.
|
|
27
|
+
BetterCarousel.defaults = {};
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Get the instance of a root, a viewport or a container.
|
|
31
|
+
*
|
|
32
|
+
* @param {Element} element
|
|
33
|
+
* @returns {object|undefined}
|
|
34
|
+
*/
|
|
35
|
+
BetterCarousel.get = find;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Make a carousel for each element that matches a selector and has no carousel.
|
|
39
|
+
*
|
|
40
|
+
* @param {string} selector
|
|
41
|
+
* @param {object} [options]
|
|
42
|
+
* @returns {object[]}
|
|
43
|
+
*/
|
|
44
|
+
BetterCarousel.initAll = (selector, options) => {
|
|
45
|
+
const elements = [...document.querySelectorAll(selector)];
|
|
46
|
+
// Read the boxes of the lazy carousels before the first setup() writes. Then the reads cause one layout, not one for each carousel.
|
|
47
|
+
readBoxes(elements.filter((element) => !find(element) && resolve(element, BetterCarousel.defaults, options).lazy));
|
|
48
|
+
return elements.map((element) => BetterCarousel(element, options));
|
|
49
|
+
};
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Autoplay: the autoplay, the auto scroll, and the play control that they share.
|
|
3
|
+
*
|
|
4
|
+
* Each feature takes the context of a carousel (see carousel.js). It returns nothing if its option is off, or an object with remove().
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { create, own, setAttribute, setClass } from './markup.js';
|
|
8
|
+
|
|
9
|
+
// The defaults of the "autoplay" option
|
|
10
|
+
const autoplayDefaults = { delay: 4000, stopOnInteraction: true, pauseOnHover: false, pauseOnFocus: true, stopOnLastSnap: false, playOnInit: true, instant: false, timer: null };
|
|
11
|
+
|
|
12
|
+
// The defaults of the "autoScroll" option
|
|
13
|
+
const autoScrollDefaults = { speed: 120, direction: 'next', startDelay: 1000, stopOnInteraction: true, pauseOnHover: false, pauseOnFocus: true, playOnInit: true };
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Merge the value of the "autoplay" or the "autoScroll" option over the defaults of the feature.
|
|
17
|
+
*
|
|
18
|
+
* @param {object} base The defaults.
|
|
19
|
+
* @param {string} key The setting that a number sets: 'delay' or 'speed'.
|
|
20
|
+
* @param {boolean|number|object} value true, a number or an object.
|
|
21
|
+
* @returns {object}
|
|
22
|
+
*/
|
|
23
|
+
export function settings(base, key, value) {
|
|
24
|
+
return { ...base, ...(typeof value === 'number' ? { [key]: value } : value) };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Watch the reasons to pause: the root is out of view, the tab is hidden, the mouse is on the root, or the keyboard focus is in the root.
|
|
29
|
+
* Make it only while a feature plays, so that a carousel at rest has no listeners on the document.
|
|
30
|
+
*
|
|
31
|
+
* @param {HTMLElement} root
|
|
32
|
+
* @param {{pauseOnHover: boolean, pauseOnFocus: boolean}} options
|
|
33
|
+
* @param {() => void} change Called when the paused state changes.
|
|
34
|
+
* @returns {{paused: () => boolean, remove: () => void}}
|
|
35
|
+
*/
|
|
36
|
+
function pauser(root, options, change) {
|
|
37
|
+
const reasons = new Set(),
|
|
38
|
+
set = (reason, on) => {
|
|
39
|
+
const before = reasons.size;
|
|
40
|
+
reasons[on ? 'add' : 'delete'](reason);
|
|
41
|
+
if (!before !== !reasons.size) {
|
|
42
|
+
change();
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
observer = new IntersectionObserver(([entry]) => set('view', !entry.isIntersecting)),
|
|
46
|
+
listeners = [
|
|
47
|
+
[document, 'visibilitychange', () => set('tab', document.hidden)],
|
|
48
|
+
[root, 'pointerenter', (event) => set('mouse', options.pauseOnHover && event.pointerType === 'mouse')],
|
|
49
|
+
[root, 'pointerleave', () => set('mouse', false)],
|
|
50
|
+
// A mouse click also moves the focus to a button. Only the keyboard focus pauses.
|
|
51
|
+
[root, 'focusin', (event) => set('focus', options.pauseOnFocus && event.target.matches(':focus-visible'))],
|
|
52
|
+
[root, 'focusout', (event) => set('focus', root.contains(event.relatedTarget) && reasons.has('focus'))]
|
|
53
|
+
];
|
|
54
|
+
|
|
55
|
+
observer.observe(root);
|
|
56
|
+
listeners.forEach(([node, name, handler]) => node.addEventListener(name, handler));
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
paused: () => reasons.size > 0,
|
|
60
|
+
remove() {
|
|
61
|
+
observer.disconnect();
|
|
62
|
+
listeners.forEach(([node, name, handler]) => node.removeEventListener(name, handler));
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The part that autoplay and auto scroll share: the play and pause button (WCAG 2.2.2), the "playing" class, aria-live, the pause reasons and the events.
|
|
69
|
+
* The control goes into the API of the carousel, and remove() removes it.
|
|
70
|
+
*
|
|
71
|
+
* @param {object} context What the features share. See carousel.js.
|
|
72
|
+
* @param {string} key The API key of the control: 'autoplay' or 'autoScroll'. Its lowercase form is the prefix of the events.
|
|
73
|
+
* @param {object} options The feature options.
|
|
74
|
+
* @param {{play: () => void, stop: () => void, pause: (paused: boolean) => void, events: Array<[string, Function]>}} hooks
|
|
75
|
+
* events: more handlers of carousel events.
|
|
76
|
+
* @returns {{play: () => void, stop: () => void, isPlaying: () => boolean, paused: () => boolean, remove: () => void}}
|
|
77
|
+
*/
|
|
78
|
+
function controller(context, key, options, hooks) {
|
|
79
|
+
const { api, root, container, cls, emit } = context,
|
|
80
|
+
labels = context.options.labels,
|
|
81
|
+
button = create('button', cls.button + ' ' + cls.playButton);
|
|
82
|
+
|
|
83
|
+
let playing = false,
|
|
84
|
+
watch = null,
|
|
85
|
+
// true until the first init
|
|
86
|
+
first = true;
|
|
87
|
+
|
|
88
|
+
button.type = 'button';
|
|
89
|
+
button.setAttribute('aria-controls', container.id);
|
|
90
|
+
button.addEventListener('click', () => playing ? control.stop() : control.play());
|
|
91
|
+
|
|
92
|
+
function update() {
|
|
93
|
+
setAttribute(button, 'aria-label', playing ? labels.pause : labels.play);
|
|
94
|
+
setClass(root, cls.playing, playing);
|
|
95
|
+
// A screen reader does not read each automatic change
|
|
96
|
+
own(container, 'aria-live', playing ? 'off' : 'polite');
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function show() {
|
|
100
|
+
if (api.isFit()) {
|
|
101
|
+
button.remove();
|
|
102
|
+
} else if (!button.isConnected) {
|
|
103
|
+
root.append(button);
|
|
104
|
+
}
|
|
105
|
+
// Start at the first init, unless the user prefers less motion. After a breakpoint change, the play state stays.
|
|
106
|
+
// A play() before the first init starts now, because the carousel had no size before.
|
|
107
|
+
if (first) {
|
|
108
|
+
first = false;
|
|
109
|
+
if (playing) {
|
|
110
|
+
hooks.play();
|
|
111
|
+
} else if (context.playing?.[key] ?? (options.playOnInit && !matchMedia('(prefers-reduced-motion: reduce)').matches)) {
|
|
112
|
+
control.play();
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const control = {
|
|
118
|
+
play() {
|
|
119
|
+
if (!playing) {
|
|
120
|
+
playing = true;
|
|
121
|
+
watch = pauser(root, options, () => hooks.pause(watch.paused()));
|
|
122
|
+
update();
|
|
123
|
+
hooks.play();
|
|
124
|
+
emit(key.toLowerCase() + ':play');
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
stop() {
|
|
128
|
+
if (playing) {
|
|
129
|
+
playing = false;
|
|
130
|
+
watch.remove();
|
|
131
|
+
update();
|
|
132
|
+
hooks.stop();
|
|
133
|
+
emit(key.toLowerCase() + ':stop');
|
|
134
|
+
}
|
|
135
|
+
},
|
|
136
|
+
isPlaying: () => playing,
|
|
137
|
+
paused: () => !playing || watch.paused(),
|
|
138
|
+
remove() {
|
|
139
|
+
control.stop();
|
|
140
|
+
button.remove();
|
|
141
|
+
delete api[key];
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
[['init', show], ['reinit', show], ['resize', show], ...hooks.events].forEach(([event, handler]) => context.on(event, handler));
|
|
146
|
+
update();
|
|
147
|
+
api[key] = control;
|
|
148
|
+
|
|
149
|
+
return control;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Go to the next snap after a delay. The timer starts at "settle", so that a slow motion does not make the delay shorter.
|
|
154
|
+
*
|
|
155
|
+
* @param {object} context What the features share. See carousel.js.
|
|
156
|
+
* @returns {object|undefined} The control: play(), stop(), reset(), isPlaying(), remove().
|
|
157
|
+
*/
|
|
158
|
+
export function autoplay(context) {
|
|
159
|
+
if (!context.options.autoplay) {
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const api = context.api,
|
|
164
|
+
options = settings(autoplayDefaults, 'delay', context.options.autoplay);
|
|
165
|
+
|
|
166
|
+
let timer = 0,
|
|
167
|
+
// The function that the "timer" callback returned for the timer
|
|
168
|
+
done = null,
|
|
169
|
+
// true while the autoplay goes to the next slide, so that its own goToSnap() is not an interaction
|
|
170
|
+
self = false;
|
|
171
|
+
|
|
172
|
+
// Stop the timer, and call the function that the "timer" callback returned
|
|
173
|
+
function clear() {
|
|
174
|
+
clearTimeout(timer);
|
|
175
|
+
done?.();
|
|
176
|
+
done = null;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function reset() {
|
|
180
|
+
clear();
|
|
181
|
+
if (!control.paused() && !api.isFit()) {
|
|
182
|
+
// The delay: data-delay on the selected slide, one value for each snap, or one value
|
|
183
|
+
const value = api.slideNodes()[api.selectedSlide()]?.dataset.delay || options.delay,
|
|
184
|
+
delay = +(Array.isArray(value) ? value[api.selectedSnap()] : value);
|
|
185
|
+
timer = setTimeout(next, delay);
|
|
186
|
+
done = options.timer?.(delay, api);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function next() {
|
|
191
|
+
clear();
|
|
192
|
+
self = true;
|
|
193
|
+
if (api.canGoToNext()) {
|
|
194
|
+
api.goToNext(options.instant);
|
|
195
|
+
} else if (options.stopOnLastSnap) {
|
|
196
|
+
control.stop();
|
|
197
|
+
} else {
|
|
198
|
+
api.goToSnap(0, options.instant);
|
|
199
|
+
}
|
|
200
|
+
self = false;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// A drag, a wheel step, an arrow, a dot or the keyboard stops the autoplay. With stopOnInteraction: false, the timer starts again at "settle".
|
|
204
|
+
function interact() {
|
|
205
|
+
if (!self) {
|
|
206
|
+
clear();
|
|
207
|
+
if (options.stopOnInteraction) {
|
|
208
|
+
control.stop();
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const control = controller(context, 'autoplay', options, {
|
|
214
|
+
play: reset,
|
|
215
|
+
stop: clear,
|
|
216
|
+
pause: reset,
|
|
217
|
+
events: [['settle', reset], ['interact', interact]]
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
control.reset = reset;
|
|
221
|
+
|
|
222
|
+
return control;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Move the slides at a constant speed: with loop, without an end; without loop, to the end. The carousel makes the motion,
|
|
227
|
+
* and this feature starts it, stops it and pauses it.
|
|
228
|
+
*
|
|
229
|
+
* @param {object} context What the features share. See carousel.js.
|
|
230
|
+
* @returns {object|undefined} The control: play(), stop(), isPlaying(), remove().
|
|
231
|
+
*/
|
|
232
|
+
export function autoScroll(context) {
|
|
233
|
+
if (!context.options.autoScroll) {
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const options = settings(autoScrollDefaults, 'speed', context.options.autoScroll);
|
|
238
|
+
|
|
239
|
+
// The start delay, and true while a pointer presses the viewport
|
|
240
|
+
let timer = 0,
|
|
241
|
+
pressed = false;
|
|
242
|
+
|
|
243
|
+
const control = controller(context, 'autoScroll', options, {
|
|
244
|
+
play: wait,
|
|
245
|
+
stop() {
|
|
246
|
+
wait(-1);
|
|
247
|
+
context.halt();
|
|
248
|
+
},
|
|
249
|
+
pause(paused) {
|
|
250
|
+
if (paused) {
|
|
251
|
+
context.halt();
|
|
252
|
+
} else if (!timer) {
|
|
253
|
+
run();
|
|
254
|
+
}
|
|
255
|
+
},
|
|
256
|
+
events: [
|
|
257
|
+
// A motion stopped: start again after the delay
|
|
258
|
+
['settle', () => control.isPlaying() && wait()],
|
|
259
|
+
// A measure pass stopped the motion: start again now
|
|
260
|
+
['resize', () => control.isPlaying() && !timer && run()],
|
|
261
|
+
// A drag, a wheel step or a goToSnap() stops the auto scroll, or makes it wait until the next "settle"
|
|
262
|
+
['interact', () => {
|
|
263
|
+
if (control.isPlaying()) {
|
|
264
|
+
wait(-1);
|
|
265
|
+
if (options.stopOnInteraction) {
|
|
266
|
+
control.stop();
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}]
|
|
270
|
+
]
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Start the auto scroll after its delay.
|
|
275
|
+
*
|
|
276
|
+
* @param {number} [cancel] With -1, only stop the timer.
|
|
277
|
+
*/
|
|
278
|
+
function wait(cancel) {
|
|
279
|
+
clearTimeout(timer);
|
|
280
|
+
timer = cancel ? 0 : setTimeout(run, options.startDelay);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function run() {
|
|
284
|
+
timer = 0;
|
|
285
|
+
const geo = context.geo();
|
|
286
|
+
if (geo && !geo.fit && !pressed && !context.dragging() && !control.paused()) {
|
|
287
|
+
context.scroll(options.direction === 'prev' ? -1 : 1, options.speed / 1000);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// A press stops the slides under the pointer. A release without a drag starts them again after the delay. A drag is an interaction.
|
|
292
|
+
const listen = (method) => ['pointerup', 'pointercancel'].forEach((name) => window[method](name, release));
|
|
293
|
+
|
|
294
|
+
function press(event) {
|
|
295
|
+
if (!event.button && control.isPlaying() && !pressed) {
|
|
296
|
+
pressed = true;
|
|
297
|
+
wait(-1);
|
|
298
|
+
context.halt();
|
|
299
|
+
listen('addEventListener');
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function release() {
|
|
304
|
+
pressed = false;
|
|
305
|
+
listen('removeEventListener');
|
|
306
|
+
if (control.isPlaying() && !context.dragging()) {
|
|
307
|
+
wait();
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
const { viewport } = context,
|
|
312
|
+
remove = control.remove;
|
|
313
|
+
|
|
314
|
+
viewport.addEventListener('pointerdown', press);
|
|
315
|
+
control.remove = () => {
|
|
316
|
+
viewport.removeEventListener('pointerdown', press);
|
|
317
|
+
listen('removeEventListener');
|
|
318
|
+
remove();
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
return control;
|
|
322
|
+
}
|