@twistedandy/better-carousel 0.0.0-stage → 1.0.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 +838 -2
- package/dist/better-carousel.css +1 -0
- package/dist/better-carousel.js +3175 -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 +288 -0
- package/src/scripts/carousel.js +834 -0
- package/src/scripts/geometry.js +429 -0
- package/src/scripts/input.js +432 -0
- package/src/scripts/layout.js +205 -0
- package/src/scripts/loop.js +83 -0
- package/src/scripts/markup.js +268 -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;function p(t,e){return[...e?t.querySelectorAll(e):t.children].filter(t=>!d.has(t))}const f={delay:4e3,stopOnInteraction:!0,pauseOnHover:!1,pauseOnFocus:!0,stopOnLastSnap:!1,playOnInit:!0,instant:!1,timer:null},g={speed:120,direction:"next",startDelay:1e3,stopOnInteraction:!0,pauseOnHover:!1,pauseOnFocus:!0,playOnInit:!0};function h(t,e,n){return{...t,..."number"==typeof n?{[e]:n}:n}}function m(n,o,i,s){const{api:a,root:c,container:d,cls:u,emit:p}=n,f=n.options.labels,g=r("button",u.button+" "+u.playButton);let h=!1,m=null,v=!0;function b(){e(g,"aria-label",h?f.pause:f.play),t(c,u.playing,h),l(d,"aria-live",h?"off":"polite")}function x(){a.isFit()?g.remove():g.isConnected||c.append(g),v&&(v=!1,i.playOnInit&&!matchMedia("(prefers-reduced-motion: reduce)").matches&&y.play())}g.type="button",g.setAttribute("aria-controls",d.id),g.addEventListener("click",()=>h?y.stop():y.play());const y={play(){h||(h=!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(){h&&(h=!1,m.remove(),b(),s.stop(),p(o.toLowerCase()+":stop"))},isPlaying(){return h},paused(){return!h||m.paused()},remove(){y.stop(),g.remove(),delete a[o]}};return[["init",x],["reinit",x],["resize",x],...s.events].forEach(([t,e])=>n.on(t,e)),b(),a[o]=y,y}function v(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 b(t,e){return t-Math.ceil(t/e)*e}function x(t,e,n){return Math.min(n,Math.max(e,t))}function y(t,e,n){return n?(t%e+e)%e:x(t,0,e-1)}function w(t,e,n,o){return"function"==typeof t?t(e,n,o):"center"===t?(e-n)/2:"end"===t?e-n:0}function M(t){let e=1/0,n=-1/0,o=0;for(const r of t)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 E(t,e,n){const o=t-e;return n?o-Math.round(o/n)*n:o}function S(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(E(t.start+e,w(o,n,t.end-t.start,c),r));c>=i&&s>c&&l-.5>d&&(l=d,a=c)}),a}function L(t,e,n){let o=0,r=1/0;return t.forEach((t,i)=>{const s=Math.abs(E(t.location,e,n));r>s&&(r=s,o=i)}),o}function T(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+E(t,e,n):t}function k(t,{min:e,max:n,period:o}){if(o){const e=(n-t)/o;return e-Math.floor(e)}return n>e?x((n-t)/(n-e),0,1):0}function z(t,e,n,o,r){const i=[];return t.forEach((t,s)=>{const a=t.end-t.start,l=r?E(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);c>0&&c>=o*a-.5&&i.push(s)}),i}function A(t){return"x"===t?document.documentElement.clientWidth:innerHeight}const O=new WeakMap;let P;function C(t,e){P||=new ResizeObserver(t=>{[...new Set(t.filter(t=>!O.get(t.target)?.skip(t)).map(t=>O.get(t.target)))].filter(t=>t&&t.read()).forEach(t=>t.write())});for(const n of t)e?(O.set(n,e),P.observe(n)):(O.delete(n),P.unobserve(n))}const F=new Map,I=new WeakMap,N=new WeakMap,_=[.25,1,.5,1],B=[.2,.6,.35,1];function R([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 H={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},j=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"}),D=["selected","inView","dragging","playing","first","prev","current","next","last"];function G(...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 W(t,...e){let n={};try{n=JSON.parse(t.dataset.carousel||"{}")}catch{}return G(H,...e,n)}const V=new WeakMap,q=t=>V.get(t),K="input,textarea,select,[contenteditable]",X=[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||e.target.closest(K)||("mouse"===e.pointerType&&e.preventDefault(),s=e.pointerId,i={x:"x"===n.axis,sign:n.sign},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],u=a.clientY-o[1],p=i.x?d*i.sign:u,g=i.x?u:d;if(!t.dragging()){if("mouse"!==a.pointerType&&Math.abs(g)>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 h=t.geo(),m=r+p,v=x(m,h.min,h.max);t.hold(h.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=x(p,i,s)),"number"==typeof l&&l>0&&u-1+!a>l){const t=t=>T(r[y(o+t*l,u,a)].location,e,a,t);p=x(p,t(1),t(-1))}if(!0===c)return{location:p,snap:L(r,p,a)};if(c||l){const t=L(r,p,a);return{location:T(r[t].location,p,a),snap:t}}const f=t-e;let g=0;Math.abs(n)>.3?g=0>n?1:-1:Math.abs(f)>20&&(g=0>f?1:-1);const h=y(o+g,u,a),m=r[h].location;return{location:a?T(m,g?e:t,a,h===o?0:g):m,snap:h}})({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?B:_;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:x(Math.abs(t)*n[1]/n[0]/Math.abs(e),200,1200))(p.location-i,u,f,n.duration),f)}function g(t){a&&(a=!1,t.preventDefault(),t.stopPropagation())}const h=t=>t.preventDefault(),m=e=>t.dragging()&&e.preventDefault();return e.addEventListener("pointerdown",u),e.addEventListener("click",g,!0),e.addEventListener("dragstart",h),e.addEventListener("selectstart",m),{remove(){d("removeEventListener"),e.removeEventListener("pointerdown",u),e.removeEventListener("click",g,!0),e.removeEventListener("dragstart",h),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=0,a=0,l=0;function c(e){const n=t.geo(),c="x"===n.axis&&Math.abs(e.deltaX)>Math.abs(e.deltaY)?e.deltaX*n.sign:e.deltaY;if(e.ctrlKey||!c||t.dragging())return;const u=e.timeStamp,p=200>u-r,f=t.location(),g=c*(1===e.deltaMode?40:e.deltaMode?n.view:1);let h=f-g;n.period||(h=x(h,n.min,n.max)),r=u,.5>Math.abs(h-f)?p&&1e3>u-i&&e.preventDefault():(e.preventDefault(),t.emit("interact"),s||(a=t.selected()),i=u,l=g>0?1:-1,t.move(L(n.snaps,h,n.period),h,180,_),clearTimeout(s),o||(s=setTimeout(d,150)))}function d(){s=0;const e=t.geo(),n=t.current(),o=L(e.snaps,n,e.period),r=Math.abs(T(e.snaps[o].location,n,e.period)-n)>10;t.step(o,o===a&&r?l:0)}function u(){const o=t.geo();e[o.fit||"y"!==o.axis&&"both"!==n.wheel?"removeEventListener":"addEventListener"]("wheel",c,{passive:!1})}return["init","reinit","resize"].forEach(e=>t.on(e,u)),{remove(){e.removeEventListener("wheel",c),clearTimeout(s)}}},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(K)||(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&&!z(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=[],g="all"!==l.dotsStyle,h=u&&r("div",g?a.dots:a.dots+" "+a.dotsAll),m=h&&r("div",a.dotsTrack);let v=new Map;if(d||u)return h&&(m.append(r("span",a.dotsMarker)),h.append(m),u.append(h)),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()),h?.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||(h?.parentNode===d?h.before(t):d.append(t));const n=!(e?o.canGoToNext():o.canGoToPrev());t.disabled!==n&&(t.disabled=n)}}),!h)return;if(2>s)return void h.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),g&&(t.tabIndex=-1),t.addEventListener("click",()=>o.goToSnap(e)),f.push(t),m.append(t)}h.isConnected||u.append(h);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=g?-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,g&&x("--better-shift",2-(Math.max(0,l-2)+Math.min(s-1,l+2))/2),x("--better-dot",l)}function x(t,e){h.style.getPropertyValue(t)!==e+""&&h.style.setProperty(t,e)}},t=>{if(!t.options.autoplay)return;const e=t.api,n=h(f,"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=m(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=h(g,"speed",t.options.autoScroll);let n=0;const o=m(t,"autoScroll",e,{play:r,stop(){r(-1),t.halt()},pause(e){e?t.halt():n||i()},events:[["settle",()=>o.isPlaying()&&r()],["resize",()=>o.isPlaying()&&!n&&i()],["interact",()=>{o.isPlaying()&&(r(-1),e.stopOnInteraction&&o.stop())}]]});function r(t){clearTimeout(n),n=t?0:setTimeout(i,e.startDelay)}function i(){n=0;const r=t.geo();!r||r.fit||t.dragging()||o.paused()||t.scroll("prev"===e.direction?-1:1,e.speed/1e3)}return o},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:q("string"==typeof o?i(o,t.root):o),r&&(r.on("select",s),s(!0)))}}];function Y(e,i={}){return((e,i,f,g)=>{const h=V.get(e);if(h)return h;let m,O,P,B,H,q,K,X=[],Y=[],U=[],J=[],$=[],Q=null,Z=!1,tt=!1,et=!1,nt=[],ot=0,rt=-1,it=0,st=null,at=0,lt=0,ct=0,dt=-1,ut=-1,pt=[],ft={axis:"",container:0,slides:[]},gt=!1,ht=!1;const mt={goToSnap:(t,e)=>Kt(Ct(t),e),goToNext:t=>mt.canGoToNext()&&qt(lt,1,t),goToPrev:t=>mt.canGoToPrev()&&qt(lt,-1,t),goToSlide:(t,e)=>Kt(Ct(mt.snapOfSlide(t)),e,t),canGoToNext:()=>!(!st||st.fit||!st.period&<>=st.snaps.length-1),canGoToPrev:()=>!(!st||st.fit||!st.period&&0>=lt),selectedSnap:()=>Pt(lt),previousSnap:()=>Pt(ct),selectedSlide:Ft,snapOfSlide:t=>st?Pt(((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):L(t,w(r,o,a.end-a.start,n)-a.start,i)})(st.snaps,st.slides,t,st.view,st.align,st.period)):t,snapProgress:()=>st?st.logical.map(t=>k(st.snaps[t].location,st)):[],progress:()=>st?k(It(),st):0,slideNodes:()=>X.slice(),slidesInView:()=>pt.slice(),rootNode:()=>P,viewportNode:()=>B,containerNode:()=>H,isFit:()=>!st||st.fit,options:()=>m,reinit:Tt,destroy(){Lt(!1),vt.emit("destroy")}},vt=(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}}})(mt),bt={read:Nt,write:Bt,skip({target:t,contentRect:{width:e}}){if(t!==B)return!1;const n=e===ot;return ot=e,n&&m.autoHeight&&"x"===st?.axis}},xt={progress:0,snap:0},yt={node:null,index:0,offset:0,distance:0,size:0,visible:0},wt={api:mt,emit:vt.emit,on:vt.listen,geo:()=>st,nodes:()=>U,selected:()=>lt,dragging:()=>gt,location:()=>ht?It():at,current:It,hold(t,e){at=t,(e?Jt:Dt)(t),Ut()},halt:Qt,step:qt,scroll(t,e){const n=Qt(),o=t>0?st.min:st.max;st.period?(ht=!0,at=b(n,st.period),K.loop(at,t,st.period/e,st,U)):Math.abs(o-n)>1&&(ht=!0,at=o,K.run(n,o,Math.abs(o-n)/e,[0,0,1,1],vt.has("scroll")))},move(t,e,n,o){dt=-1,Xt(t,e,n,o)},drag(e){gt=e,t(P,O.dragging,e),e?(vt.emit("interact"),vt.emit("dragstart")):vt.emit("dragend")},follow(t){ut=t}};mt.on=vt.on,mt.off=vt.off;let Mt=W(e,f,i),Et=Mt.lazy?((t,e,n)=>{const o=!0===e?innerHeight:e,r=N.get(t)||t.getBoundingClientRect(),i=!0===e?"100%":e+"px";if(N.delete(t),r.height&&r.bottom>=-o&&r.top<=innerHeight+o)return null;let s=F.get(i);return s||(s=new IntersectionObserver(t=>t.forEach(t=>t.isIntersecting&&I.get(t.target)?.()),{rootMargin:i}),F.set(i,s)),I.set(t,n),s.observe(t),()=>{s.unobserve(t),I.delete(t)}})(e,Mt.lazy,Tt):null;return Et?V.set(e,mt):St(),mt;function St(){if(Q=((t,e)=>{const n=Object.entries(t.breakpoints||{}).map(([t,e])=>[matchMedia(t),e]);return n.forEach(([t])=>t.addEventListener("change",e)),{options:G(t,...n.filter(([t])=>t.matches).map(([,t])=>t)),remove(){return n.forEach(([t])=>t.removeEventListener("change",e))}}})(Mt||W(e,f,i),()=>Tt()),Mt=null,m=Q.options,m.active){O=((t,e)=>{const n="string"==typeof t?j(t):{...j(t?.prefix||"better"),...t};for(const t of D)n[t]&&(n[t]=e+n[t]);return n})(m.classes,m.state),({root:P,viewport:B,container:H}=((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,m,O));for(const t of[P,B,H])V.set(t,mt);X=p(H,m.slides),U=X,lt=m.startSnap,zt(!0),Object.assign(wt,{root:P,viewport:B,container:H,cls:O,options:m}),J=g.map(t=>t(wt)).filter(Boolean),K=((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:R(o)})},loop(t,e,n,o,r){return p({from:t,to:t-e*o.period,duration:n,direction:e,length:o.period,list:v(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)}}})(H,Vt,Jt,$t,(m.progress||m.offset)&&(t=>Gt(t,K.shifts(st.sign)||ft.slides))),m.autoHeight&&c(P,O.autoHeight),B.addEventListener("scroll",Zt),m.loop&&"fill"===m.clones&&addEventListener("resize",_t),m.slideChanges&&(q=new MutationObserver(At),q.observe(H,{childList:!0}))}}function Lt(r){if(Et?.(),Et=null,V.delete(e),zt(!1),q?.disconnect(),Q?.remove(),Q=null,O){K.stop(),J.forEach(t=>t.remove()),vt.clear(),J=[],ut=-1,gt=ht=!1,kt(0),B.removeEventListener("scroll",Zt),removeEventListener("resize",_t);for(const e of U)n(e,"translate",""),e.style.removeProperty("--better-offset"),t(e,O.selected,!1),t(e,O.inView,!1),o(e);n(H,"translate",""),n(H,"willChange",""),n(B,"touchAction",""),n(B,"height",""),P.style.removeProperty("--better-progress");for(const e of["horizontal","vertical","fit","dragging"])t(P,O[e],!1);for(const t of[P,B,H])o(t),V.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())})(P,B,H,X,r),O=st=null,Z=!1,at=0,pt=[],nt=[],ot=0,ft={axis:"",container:0,slides:[]}}}function Tt(t){t&&(i=G(i,t),Mt=null);const e=st?Ft():dt;Lt(!0),St(),dt=e}function kt(e){Y.length!==e*X.length&&(Y.forEach(t=>t.remove()),Y=((e,n,r)=>{const i=[];for(let s=0;n>s;s++)for(const n of e){const e=n.cloneNode(!0);for(const t of[e,...e.querySelectorAll("[id]")])t.removeAttribute("id");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})(X,e,O.clone),H.append(...Y),U=X.concat(Y),ft.slides.length=X.length,q?.takeRecords())}function zt(t){C($),$=t?[B,H,...U]:[],C($,bt)}function At(){X=p(H,m.slides),kt(0),U=X,et=!0,zt(!0)}function Ot(t){return t%X.length}function Pt(t){return st?st.map[t]??0:t}function Ct(t){return st?((t,e,n)=>{let o=-1,r=1/0;return t.snaps.forEach((i,s)=>{const a=Math.abs(E(i.location,n,t.period));t.map[s]===e&&r>a&&(r=a,o=s)}),0>o?x(e,0,t.snaps.length-1):o})(st,t,It()):t}function Ft(){return ut>-1?ut:st?0>dt||mt.snapOfSlide(dt)!==Pt(lt)?Ot(st.snaps[lt].slide):dt:Math.max(dt,0)}function It(){return K.current()??at}function Nt(){const t=st?.sign||1,e=K.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}})(H,m),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;let c=0,d=0;const u=e.map((t,e)=>{const c=t.getBoundingClientRect(),d=(i?n.rtl?r.right-c.right:c.left-r.left:c.top-r.top)-s*(l+(a&&o.slides[e]||0));return{start:d,end:d+(i?c.width:c.height),cross:i?c.height:c.width}});u.forEach((t,e)=>{u[c].start>t.start&&(c=e),t.end>u[d].end&&(d=e)});let p=n.gap;if(u.length){const t=i?n.rtl?["Right","Left"]:["Left","Right"]:["Top","Bottom"];p+=(parseFloat(getComputedStyle(e[c])["margin"+t[0]])||0)+(parseFloat(getComputedStyle(e[d])["margin"+t[1]])||0)}return{view:i?r.width:r.height,slides:u,gap:p}})(B,U,n,null===e?ft:{axis:ft.axis,container:t*e,slides:K.shifts(t)||ft.slides});it=m.loop&&"fill"===m.clones?A(n.axis):0;const r=((t,e,n,o)=>{if(!o)return{start:0,size:n};const r=t.getBoundingClientRect(),i=Math.max(0,Math.round("x"===e.axis?e.rtl?o-r.right:r.left:r.top));return{start:-i,size:i+Math.max(n,Math.round(o-i))}})(B,n,o.view,it),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(Z&&i.length===nt.length&&i.every((t,e)=>t===nt[e]||.5>Math.abs(t-nt[e])))return!1;nt=i;const s=Z?Ft():dt,a=function(t,e,n,o,r){const i=M(e.slides.slice(0,o)),s=!(i.size>e.view+1||r.autoScroll&&r.loop),a=r.loop&&!s&&o,l=a?M(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:S(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=M(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).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)=>w(n,e,t.end-t.start,o)-t.start);i||(r?c=c.map(t=>x(t,l,a)):(a=Math.max(...c),l=Math.min(...c))),(i||"keepSnaps"!==r)&&(c=c.filter((t,e)=>!e||Math.abs(E(t,c[e-1],i))>1),i&&c.length>1&&1>=Math.abs(E(c[0],c[c.length-1],i))&&c.pop());const d=c.map(o=>({location:o,slide:S(t,o,e,n,i)})),u=(o,r,i)=>{const s=S(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,X.length,m);if(!a.snaps)return rt=a.copies,!0;st=a;const l=st.snaps.length;return lt=0>s?Math.min(l-1,Z?lt:Ct(lt)):Ct(mt.snapOfSlide(s)),ct=Math.min(ct,l-1),dt=s,gt||(at=T(st.snaps[lt].location,at,st.period)),!0}function _t(){st&&A(st.axis)!==it&&Nt()&&Bt()}function Bt(){if(rt>=0)return kt(rt),rt=-1,nt=[],void zt(!0);ht&&Qt();const t=K.current();null!==t&&ft.axis===st.axis&&!st.fit&&K.retarget(at)?(Wt(t,at),Rt(!0)):(K.stop(),Rt(gt)),((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)))})})(X,m.labels.slide),m.resize||zt(!1),Z?vt.emit("resize"):(Z=!0,vt.emit(tt?"reinit":"init"),tt=!0),et&&(et=!1,vt.emit("slideschanged"))}function Rt(e){const o="x"===st.axis;t(P,O.horizontal,o),t(P,O.vertical,!o),t(P,O.fit,st.fit),n(B,"touchAction",st.fit?"":o?"pan-y pinch-zoom":"pan-x pinch-zoom"),n(H,"willChange",st.fit?"":"translate"),e||Dt(st.fit?0:at),m.autoHeight&&n(B,"height",o?Math.max(...z(st.slides,at,st.view,0,st.period).map(t=>st.slides[t].cross))+"px":"");const r=Ft(),i=[...new Set(z(st.slides,at,st.view,m.inViewThreshold,st.period).map(Ot))].sort((t,e)=>t-e);U.forEach((e,n)=>t(e,O.selected,Ot(n)===r)),i.join()!==pt.join()&&(pt=i,U.forEach((e,n)=>t(e,O.inView,i.includes(Ot(n)))),vt.emit("slidesinview"))}function Ht(t){const e=devicePixelRatio||1;return Math.round(t*e)/e*st.sign}function jt(t){return t?"x"===st.axis?t+"px":"0 "+t+"px":""}function Dt(t){ft.axis!==st.axis&&(U.forEach(t=>n(t,"translate","")),ft={axis:st.axis,container:0,slides:[]}),ft.container=Ht(t),n(H,"translate",jt(ft.container)),Wt(t,t),(m.progress||m.offset)&&Gt(t,ft.slides)}function Gt(t,e){if(!0===m.progress)P.style.setProperty("--better-progress",k(t,st));else if(m.progress){const e=((t,e,n)=>{const o=t.length-1,r=t[0].location,i=n?r-((r-e)%n+n)%n:x(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)})(st.snaps,t,st.period),n=Math.floor(e);xt.progress=k(t,st),xt.snap=Pt(n)+e-n,m.progress(xt,mt)}m.offset&&U.forEach((n,o)=>{const r=st.slides[o],i=r.end-r.start,s=r.start+st.sign*(e[o]||0)+t,a=s-w(st.align,st.view,i,o),l=a/(i+st.gap);!0===m.offset?n.style.setProperty("--better-offset",l):(yt.node=n,yt.index=Ot(o),yt.offset=l,yt.distance=st.sign*a,yt.size=i,yt.visible=x((Math.min(s+i,st.view)-Math.max(s,0))/i,0,1)||0,m.offset(yt,mt))})}function Wt(t,e){const o=st.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)})(st.slides,t,e,st.area.size,st.period,st.area.start):[];U.forEach((t,e)=>{const r=o.length?Ht(o[e]*st.period):0;(ft.slides[e]||0)!==r&&(ft.slides[e]=r,n(t,"translate",jt(r)))})}function Vt(t){return jt(Ht(t))||"0px"}function qt(t,e,n){Kt(y(t+e,st.snaps.length,st.period),n,-1,e)}function Kt(t,e,n=-1,o=0){if(Et&&Tt(),vt.emit("interact"),dt=n,!st)return void(lt=t);const r=T(st.snaps[t].location,It(),st.period,o),i=Math.abs(t-lt);var s,a;Xt(t,r,e?0:(s=m.duration,(a=st.period?Math.min(i,st.snaps.length-i):i)>1?Math.min(2*s,s*(1+Math.log2(a))):s),_)}function Xt(t,e,n,o){const r=Qt(),i=Yt(t),s=!n||st.fit||.5>Math.abs(e-r);if(at=e,s)Rt();else{const t=vt.has("scroll")||!!st.period&&!((t,e,n,o,r)=>{const i=o+Math.abs(n-e);return t.every(t=>r>=i+t.end-t.start)})(st.slides,r,e,st.area.size,st.period);Rt(!0),t||Wt(r,e),K.run(r,e,n,o,t)}i&&vt.emit("select"),s&&$t()}function Yt(t){return t!==lt&&(ct=lt,lt=t,!0)}function Ut(){Yt(L(st.snaps,at,st.period))&&(Rt(!0),vt.emit("select"))}function Jt(t){Dt(t),vt.emit("scroll")}function $t(){ht&&(ht=!1,Ut()),st.period&&(at=b(at,st.period)),Rt(),vt.emit("settle")}function Qt(){const t=K.stop();return null!==t&&(at=t,Dt(t),ht&&Ut()),ht=!1,at}function Zt(){B.scrollLeft=B.scrollTop=0}})(e,i,Y.defaults,X)}return Y.defaults={},Y.get=q,Y.initAll=(t,e)=>{const n=[...document.querySelectorAll(t)];return(t=>{t.forEach(t=>N.set(t,t.getBoundingClientRect()))})(n.filter(t=>!q(t)&&W(t,Y.defaults,e).lazy)),n.map(t=>Y(t,e))},Y})();
|
package/package.json
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@twistedandy/better-carousel",
|
|
3
|
+
"version": "1.0.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,288 @@
|
|
|
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
|
|
106
|
+
if (first) {
|
|
107
|
+
first = false;
|
|
108
|
+
if (options.playOnInit && !matchMedia('(prefers-reduced-motion: reduce)').matches) {
|
|
109
|
+
control.play();
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const control = {
|
|
115
|
+
play() {
|
|
116
|
+
if (!playing) {
|
|
117
|
+
playing = true;
|
|
118
|
+
watch = pauser(root, options, () => hooks.pause(watch.paused()));
|
|
119
|
+
update();
|
|
120
|
+
hooks.play();
|
|
121
|
+
emit(key.toLowerCase() + ':play');
|
|
122
|
+
}
|
|
123
|
+
},
|
|
124
|
+
stop() {
|
|
125
|
+
if (playing) {
|
|
126
|
+
playing = false;
|
|
127
|
+
watch.remove();
|
|
128
|
+
update();
|
|
129
|
+
hooks.stop();
|
|
130
|
+
emit(key.toLowerCase() + ':stop');
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
isPlaying: () => playing,
|
|
134
|
+
paused: () => !playing || watch.paused(),
|
|
135
|
+
remove() {
|
|
136
|
+
control.stop();
|
|
137
|
+
button.remove();
|
|
138
|
+
delete api[key];
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
[['init', show], ['reinit', show], ['resize', show], ...hooks.events].forEach(([event, handler]) => context.on(event, handler));
|
|
143
|
+
update();
|
|
144
|
+
api[key] = control;
|
|
145
|
+
|
|
146
|
+
return control;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Go to the next snap after a delay. The timer starts at "settle", so that a slow motion does not make the delay shorter.
|
|
151
|
+
*
|
|
152
|
+
* @param {object} context What the features share. See carousel.js.
|
|
153
|
+
* @returns {object|undefined} The control: play(), stop(), reset(), isPlaying(), remove().
|
|
154
|
+
*/
|
|
155
|
+
export function autoplay(context) {
|
|
156
|
+
if (!context.options.autoplay) {
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const api = context.api,
|
|
161
|
+
options = settings(autoplayDefaults, 'delay', context.options.autoplay);
|
|
162
|
+
|
|
163
|
+
let timer = 0,
|
|
164
|
+
// The function that the "timer" callback returned for the timer
|
|
165
|
+
done = null,
|
|
166
|
+
// true while the autoplay goes to the next slide, so that its own goToSnap() is not an interaction
|
|
167
|
+
self = false;
|
|
168
|
+
|
|
169
|
+
// Stop the timer, and call the function that the "timer" callback returned
|
|
170
|
+
function clear() {
|
|
171
|
+
clearTimeout(timer);
|
|
172
|
+
done?.();
|
|
173
|
+
done = null;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function reset() {
|
|
177
|
+
clear();
|
|
178
|
+
if (!control.paused() && !api.isFit()) {
|
|
179
|
+
// The delay: data-delay on the selected slide, one value for each snap, or one value
|
|
180
|
+
const value = api.slideNodes()[api.selectedSlide()]?.dataset.delay || options.delay,
|
|
181
|
+
delay = +(Array.isArray(value) ? value[api.selectedSnap()] : value);
|
|
182
|
+
timer = setTimeout(next, delay);
|
|
183
|
+
done = options.timer?.(delay, api);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function next() {
|
|
188
|
+
clear();
|
|
189
|
+
self = true;
|
|
190
|
+
if (api.canGoToNext()) {
|
|
191
|
+
api.goToNext(options.instant);
|
|
192
|
+
} else if (options.stopOnLastSnap) {
|
|
193
|
+
control.stop();
|
|
194
|
+
} else {
|
|
195
|
+
api.goToSnap(0, options.instant);
|
|
196
|
+
}
|
|
197
|
+
self = false;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// A drag, a wheel step, an arrow, a dot or the keyboard stops the autoplay. With stopOnInteraction: false, the timer starts again at "settle".
|
|
201
|
+
function interact() {
|
|
202
|
+
if (!self) {
|
|
203
|
+
clear();
|
|
204
|
+
if (options.stopOnInteraction) {
|
|
205
|
+
control.stop();
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const control = controller(context, 'autoplay', options, {
|
|
211
|
+
play: reset,
|
|
212
|
+
stop: clear,
|
|
213
|
+
pause: reset,
|
|
214
|
+
events: [['settle', reset], ['interact', interact]]
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
control.reset = reset;
|
|
218
|
+
|
|
219
|
+
return control;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Move the slides at a constant speed: with loop, without an end; without loop, to the end. The carousel makes the motion,
|
|
224
|
+
* and this feature starts it, stops it and pauses it.
|
|
225
|
+
*
|
|
226
|
+
* @param {object} context What the features share. See carousel.js.
|
|
227
|
+
* @returns {object|undefined} The control: play(), stop(), isPlaying(), remove().
|
|
228
|
+
*/
|
|
229
|
+
export function autoScroll(context) {
|
|
230
|
+
if (!context.options.autoScroll) {
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const options = settings(autoScrollDefaults, 'speed', context.options.autoScroll);
|
|
235
|
+
|
|
236
|
+
// The start delay
|
|
237
|
+
let timer = 0;
|
|
238
|
+
|
|
239
|
+
const control = controller(context, 'autoScroll', options, {
|
|
240
|
+
play: wait,
|
|
241
|
+
stop() {
|
|
242
|
+
wait(-1);
|
|
243
|
+
context.halt();
|
|
244
|
+
},
|
|
245
|
+
pause(paused) {
|
|
246
|
+
if (paused) {
|
|
247
|
+
context.halt();
|
|
248
|
+
} else if (!timer) {
|
|
249
|
+
run();
|
|
250
|
+
}
|
|
251
|
+
},
|
|
252
|
+
events: [
|
|
253
|
+
// A motion stopped: start again after the delay
|
|
254
|
+
['settle', () => control.isPlaying() && wait()],
|
|
255
|
+
// A measure pass stopped the motion: start again now
|
|
256
|
+
['resize', () => control.isPlaying() && !timer && run()],
|
|
257
|
+
// A drag, a wheel step or a goToSnap() stops the auto scroll, or makes it wait until the next "settle"
|
|
258
|
+
['interact', () => {
|
|
259
|
+
if (control.isPlaying()) {
|
|
260
|
+
wait(-1);
|
|
261
|
+
if (options.stopOnInteraction) {
|
|
262
|
+
control.stop();
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}]
|
|
266
|
+
]
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Start the auto scroll after its delay.
|
|
271
|
+
*
|
|
272
|
+
* @param {number} [cancel] With -1, only stop the timer.
|
|
273
|
+
*/
|
|
274
|
+
function wait(cancel) {
|
|
275
|
+
clearTimeout(timer);
|
|
276
|
+
timer = cancel ? 0 : setTimeout(run, options.startDelay);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function run() {
|
|
280
|
+
timer = 0;
|
|
281
|
+
const geo = context.geo();
|
|
282
|
+
if (geo && !geo.fit && !context.dragging() && !control.paused()) {
|
|
283
|
+
context.scroll(options.direction === 'prev' ? -1 : 1, options.speed / 1000);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
return control;
|
|
288
|
+
}
|