swipefeed 1.2.0 → 1.2.1

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/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export{p as useWindowSize,n as useSwipeItem,o as useSwipeDeck,S as SwipeDeck};
1
+ import{useCallback as _,useEffect as ie,useMemo as ce,useRef as A,useState as Re}from"react";function Y(n,t,o){if(Number.isNaN(n))return t;return Math.min(Math.max(n,t),o)}var ue=!1,Ge=!1;function Be(){if(Ge)return ue;if(Ge=!0,typeof window>"u"||typeof window.matchMedia!=="function")return ue=!1,ue;let n=window.matchMedia("(prefers-reduced-motion: reduce)");return ue=n.matches,n.addEventListener("change",(t)=>{ue=t.matches}),ue}function Ee(n=0){let t=Number.isFinite(n)?Math.max(0,Math.floor(n)):0;return{scrollOffset:0,viewportSize:0,position:t,index:t,offset:0,offsetRatio:0,direction:"none",isSettled:!0}}function Xe({scrollOffset:n,viewportSize:t,itemCount:o,previousScrollOffset:w,settleTolerance:v=1}){if(!Number.isFinite(t)||t<=0||!Number.isFinite(o)||o<=0)return Ee();let k=Math.floor(o),D=(k-1)*t,i=Number.isFinite(n)?Math.max(0,Math.min(D,n)):0,b=i/t,y=Math.max(0,Math.min(k-1,Math.round(b))),S=y*t-i,I=Number.isFinite(w)?Math.max(0,Math.min(D,w??0)):i,d=i>I?"forward":i<I?"backward":"none";return{scrollOffset:i,viewportSize:t,position:b,index:y,offset:S,offsetRatio:S/t,direction:d,isSettled:Math.abs(S)<=Math.max(0,v)}}import{useCallback as oe,useRef as pt,useState as gt,useMemo as ht}from"react";function Ze(n,t){return t==="vertical"?n.clientY:n.clientX}function qe(n){let{orientation:t,direction:o,threshold:w,flickVelocity:v,lockAxis:k,ignoreWhileAnimating:D,loop:i,getIndex:b,maxIndex:y,onRequestIndexChange:S,setAnimating:I,isAnimating:d,onDragStart:c,onDrag:f,onDragEnd:m}=n,[R,C]=gt(!1),a=pt({isDragging:!1,start:0,last:0,delta:0,startTime:0}),l=oe((u)=>{u.currentTarget.setPointerCapture?.(u.pointerId);let M=Ze(u,t);a.current={isDragging:!0,start:M,last:M,delta:0,startTime:performance.now()},C(!0),c?.(u)},[t,c]),L=oe((u)=>{if(!a.current.isDragging)return;let M=Ze(u,t),z=M-a.current.start;a.current.delta=z,a.current.last=M,f?.(z,u)},[t,f]),G=oe(()=>{if(!a.current.isDragging)return;let u=performance.now(),M=Math.max(u-a.current.startTime,1),z=Math.abs(a.current.delta),X=z/M,Z=(()=>{let te=a.current.delta;if(t==="vertical")return te<0;return(o==="rtl"?te*-1:te)<0})(),W=b(),Q=Z?1:-1,ee=X>v,se=z>w,N=W;if(ee||se)N=W+Q;if(i)N=(N+(y+1))%(y+1);else N=Y(N,0,y);I(!0),S(N),a.current.isDragging=!1,a.current.delta=0,C(!1),m?.()},[o,v,b,y,S,t,i,I,w,m]),g=oe(()=>{a.current.isDragging=!1,a.current.delta=0,C(!1)},[]),B=oe((u)=>{if(D&&d)return;if(u.button!==0)return;l(u)},[D,d,l]),P=oe((u)=>{if(!k&&!a.current.isDragging)return;if(a.current.isDragging)L(u)},[k,L]),V=oe(()=>{G()},[G]),x=oe(()=>{g()},[g]);return ht(()=>({isDragging:R,handlers:{onPointerDown:B,onPointerMove:P,onPointerUp:V,onPointerCancel:x}}),[R,B,P,V,x])}import{useCallback as st,useRef as J,useEffect as vt}from"react";var $e=250,Ye=400,je=600,Je=1500,Qe=150,et=50,tt=100,be=5,nt=0.1,rt=120,ot=40,it=1.2,ct=20,De=0.8,pe=800;function at(n){let{orientation:t,direction:o,discretePaging:w,threshold:v,debounce:k,cooldown:D=500,onRequestIndexChange:i,viewport:b,onDragStart:y,onDrag:S,onDragEnd:I}=n,d=J(0),c=J(null),f=J(0),m=J(!1),R=J(0),C=J(null),a=J(0),l=J(!1),L=J(0),G=st(()=>{l.current=!1,d.current=0,C.current=null,a.current=0,L.current=0,I?.()},[I]),g=st(()=>{if(c.current)clearTimeout(c.current);c.current=setTimeout(()=>{G()},k)},[k,G]);vt(()=>{let B=b;if(!B)return;let P=(V)=>{if(!w)return;V.preventDefault(),V.stopPropagation();let x=performance.now();if(m.current){if(x-f.current<D){if(l.current)l.current=!1,d.current=0,C.current=null,a.current=0,L.current=0;return}m.current=!1}let u=t==="vertical"?V.deltaY:V.deltaX,M=t==="horizontal"&&o==="rtl"?-u:u,z=M>0?1:-1;if(C.current!==null&&C.current!==z)d.current=0,a.current=0;if(C.current=z,!l.current)l.current=!0,y?.();let X=x-R.current;R.current=x,a.current++;let Z=Math.sign(M)*Math.min(Math.abs(M),rt),W=Math.sign(M)*Math.min(Math.abs(M),ot),Q=X>0&&X<100?Math.abs(Z/X):0;L.current=L.current*De+Q*(1-De),d.current+=Z,S?.(-W),g();let ee=Math.abs(d.current)>=v,se=L.current>it&&Math.abs(d.current)>ct;if(ee||se){let N=d.current>0?1:-1;if(l.current=!1,d.current=0,C.current=null,a.current=0,L.current=0,f.current=x,m.current=!0,c.current)clearTimeout(c.current);i(N)}};return B.addEventListener("wheel",P,{passive:!1}),()=>{if(B.removeEventListener("wheel",P),c.current)clearTimeout(c.current)}},[t,o,w,v,D,i,g,b,y,S])}import{useCallback as bt,useEffect as St}from"react";var wt={prev:["ArrowUp"],next:["ArrowDown"],first:["Home"],last:["End"],altPrev:["PageUp"],altNext:["PageDown"]},xt={prev:["ArrowLeft"],next:["ArrowRight"],first:["Home"],last:["End"],altPrev:["PageUp"],altNext:["PageDown"]};function lt(n){let{orientation:t,direction:o,config:w,onPrev:v,onNext:k,onFirst:D,onLast:i}=n,b=w?.enabled??!0,y=w?.global??!1,S=w?.bindings??(t==="vertical"?wt:xt),I=bt((d)=>{if(!b)return;let c=d.key,f=[...S.prev??[],...S.altPrev??[]],m=[...S.next??[],...S.altNext??[]],R=t==="horizontal",C=o==="rtl",a=()=>{if(y)d.stopPropagation()};if(f.includes(c)){if(d.preventDefault(),a(),R&&C)k();else v();return}if(m.includes(c)){if(d.preventDefault(),a(),R&&C)v();else k();return}if(S.first?.includes(c)){d.preventDefault(),a(),D?.();return}if(S.last?.includes(c)){d.preventDefault(),a(),i?.();return}},[S,o,b,y,D,i,k,v,t]);return St(()=>{if(!b||!y)return;return window.addEventListener("keydown",I),()=>{window.removeEventListener("keydown",I)}},[b,y,I]),{onKeyDown:I}}import{useEffect as yt,useLayoutEffect as It,useState as Tt,useMemo as ut,useCallback as Et}from"react";import{useVirtualizer as Dt}from"@tanstack/react-virtual";var Rt=typeof window<"u"?It:yt;function dt(n){let{items:t,virtual:o,getScrollElement:w,orientation:v="vertical"}=n,k=t.length,[D,i]=Tt(()=>({size:typeof window<"u"?v==="vertical"?window.innerHeight:window.innerWidth:pe,measured:!1}));Rt(()=>{let c=w();if(!c)return;let f=()=>{let R=v==="vertical"?c.clientHeight:c.clientWidth;if(R>0)i((C)=>{if(C.size!==R||!C.measured)return{size:R,measured:!0};return C})};f();let m=new ResizeObserver(f);return m.observe(c),()=>{m.disconnect()}},[w,v]);let b=D.size,y=Et((c)=>{let f=o?.estimatedSize;if(typeof f==="function")return f(t[c],c);if(b>0)return b;return typeof f==="number"?f:pe},[o?.estimatedSize,t,b]),S=ut(()=>{if(typeof window>"u")return{width:pe,height:pe};return{width:window.innerWidth,height:window.innerHeight}},[]),I=ut(()=>{if(!o?.getItemKey)return;return(c)=>o.getItemKey?.(t[c],c)??c},[o?.getItemKey,t]),d=Dt({count:k,getScrollElement:w,estimateSize:y,overscan:o?.overscan??5,horizontal:v==="horizontal",getItemKey:I,initialRect:S});return{virtualItems:d.getVirtualItems().map((c)=>({index:c.index,key:c.key,offset:c.start,size:c.size,measureElement:d.measureElement})),totalSize:d.getTotalSize(),getItemOffset:(c)=>{let f=d.getVirtualItems().find((m)=>m.index===c);return f?f.start:0},getItemSize:(c)=>{let f=d.getVirtualItems().find((m)=>m.index===c);return f?f.size:0},scrollToIndex:(c,f)=>{d.scrollToIndex(c,{align:f?.align,behavior:f?.behavior})},containerSize:b}}var F={orientation:"vertical",direction:"ltr",loop:!1,defaultIndex:0,gesture:{threshold:10,flickVelocity:0.1,lockAxis:!0,ignoreWhileAnimating:!0},wheel:{discretePaging:!0,threshold:100,debounce:120,cooldown:800},keyboard:{enabled:!0},visibility:{strategy:"position",intersectionRatio:0.6,debounce:100},virtual:{overscan:5},endReachedThreshold:3,ariaLabel:"Swipe feed",keyboardNavigation:!0};function Ce(n){let t=n.items??[],o=n.orientation??F.orientation,w=n.direction??F.direction,v=n.loop??F.loop,k=n.defaultIndex??F.defaultIndex,D=n.preload??0,i=n.preloadPrevious??0,b=ce(()=>({...F.gesture,...n.gesture??{}}),[n.gesture]),y=ce(()=>({...F.wheel,...n.wheel??{}}),[n.wheel]),S=ce(()=>({...F.keyboard,...n.keyboard??{}}),[n.keyboard]),I=ce(()=>({...F.visibility,...n.visibility??{}}),[n.visibility]),d=ce(()=>{let e={...F.virtual,...n.virtual??{}},r=Math.max(D,i);return{...e,overscan:Math.max(e.overscan??0,r)}},[n.virtual,D,i]),c=n.endReachedThreshold??F.endReachedThreshold,f=n.ariaLabel??F.ariaLabel,m=n.keyboardNavigation??!0,R=typeof n.index==="number",[C,a]=Re(()=>Y(k,0,Math.max(t.length-1,0))),l=R?Y(n.index??0,0,Math.max(t.length-1,0)):C,[L,G]=Re(!1),[g,B]=Re(null),P=A("snap"),V=A(0),x=A(!1),u=A(null),M=A(0),z=A(-1),X=A(0),Z=A(Ee(l)),W=A(null),Q=A(null),ee=A(new Map),se=A(new Map),N=A(null),te=A(new Map),ne=A(null);ie(()=>{let e=Y(l,0,Math.max(t.length-1,0));if(!R)a(e)},[l,R,t.length]);let ae=dt({items:t,virtual:d,getScrollElement:_(()=>g,[g]),orientation:o}),T=A({index:l,items:t,isControlled:R,options:n,virtualizer:ae,loop:v,orientation:o,setInternalIndex:a,setIsAnimating:G,viewport:g});T.current={index:l,items:t,isControlled:R,options:n,virtualizer:ae,loop:v,orientation:o,setInternalIndex:a,setIsAnimating:G,viewport:g};let ge=_((e)=>{let{index:r,isControlled:s,options:p,setInternalIndex:E,setIsAnimating:h}=T.current;if(e===r)return;if(!s)E(e);p.onIndexChange?.(e,P.current??"snap"),h(!1),P.current="snap"},[]);ie(()=>{let r=l>=0&&l<t.length?{item:t[l],index:l}:null,s=Q.current;if(!(s?.index!==r?.index||s?.item!==r?.item))return;if(s)T.current.options.onItemInactive?.(s.item,s.index);if(Q.current=r,r)T.current.options.onItemActive?.(r.item,r.index)},[l,t]),ie(()=>()=>{let e=Q.current;if(e)T.current.options.onItemInactive?.(e.item,e.index),Q.current=null},[]);let le=_((e=!1,r)=>{let{viewport:s,orientation:p,items:E,options:h}=T.current;if(!s)return;let O=r?.orientation??p,q=r?.itemCount??E.length,U=Z.current,re=Xe({scrollOffset:O==="vertical"?s.scrollTop:s.scrollLeft,viewportSize:O==="vertical"?s.clientHeight:s.clientWidth,itemCount:q,previousScrollOffset:U.scrollOffset,settleTolerance:be});Z.current=re;let me=Object.keys(re).some((K)=>{let ve=K;return re[ve]!==U[ve]});if(e||me)h.onMotionChange?.(re)},[]),he=_(()=>{if(W.current!==null)return;W.current=-1;let e=requestAnimationFrame(()=>{W.current=null,le()});if(W.current!==null)W.current=e},[le]);ie(()=>{if(!g)return;le(!0,{orientation:o,itemCount:t.length})},[le,t.length,o,g]),ie(()=>()=>{if(W.current!==null)cancelAnimationFrame(W.current)},[]);let Oe=_((e)=>{let r=se.current.get(e);if(r)return r;let s=(p)=>{let E=ee.current.get(e);if(E&&E!==p)N.current?.unobserve(E);if(!p){ee.current.delete(e),te.current.delete(e);return}ee.current.set(e,p),N.current?.observe(p)};return se.current.set(e,s),s},[]);ie(()=>{if(!g||I.strategy!=="intersection"||typeof IntersectionObserver>"u")return;let e=Y(I.intersectionRatio,0,1),r=Math.max(0,I.debounce),s=()=>{ne.current=null;let E=T.current.index,h=-1,O=-1;for(let[q,U]of te.current){let re=U>O,me=U===O&&Math.abs(q-E)<Math.abs(h-E);if(U>=e&&(re||me))h=q,O=U}if(h<0||h===T.current.index)return;P.current="visibility",ge(h)},p=new IntersectionObserver((E)=>{for(let h of E){let O=Number(h.target.dataset.index);if(!Number.isInteger(O))continue;te.current.set(O,h.isIntersecting?h.intersectionRatio:0)}if(ne.current)clearTimeout(ne.current);if(r===0)s();else ne.current=setTimeout(s,r)},{root:g,threshold:Array.from(new Set([0,e,1]))});N.current=p;for(let E of ee.current.values())p.observe(E);return()=>{if(p.disconnect(),N.current===p)N.current=null;if(te.current.clear(),ne.current)clearTimeout(ne.current),ne.current=null}},[ge,g,I.debounce,I.intersectionRatio,I.strategy]);let H=_((e,r,s)=>{let{items:p,loop:E,index:h,isControlled:O,options:q,orientation:U,virtualizer:re,setInternalIndex:me,viewport:K}=T.current;if(p.length===0)return;let ve=p.length-1,j=e;if(E)j=(j+p.length)%p.length;else j=Y(j,0,ve);if(j===h&&r!=="snap")return;let ye=Date.now();if(x.current&&ye-M.current>je)x.current=!1;if(x.current&&r!=="snap"&&r!=="programmatic")return;if(ye-X.current<$e&&r!=="snap"&&r!=="programmatic")return;if(z.current=j,X.current=ye,P.current=r,x.current=!0,!O)me(j);if(q.onIndexChange?.(j,r),!K)return;if(u.current)clearTimeout(u.current),u.current=null;K.style.scrollSnapType="none",K.style.scrollBehavior="auto";let Ie=s??(r==="user:wheel"||r==="programmatic"||Be()?"instant":"smooth"),Fe=j*re.containerSize;if(M.current=Date.now(),U==="vertical")K.scrollTo({top:Fe,behavior:Ie});else K.scrollTo({left:Fe,behavior:Ie});let Te=()=>{if(x.current=!1,u.current)clearTimeout(u.current),u.current=null;if(K)K.style.scrollSnapType=U==="vertical"?"y mandatory":"x mandatory"};if("onscrollend"in window){let fe=()=>{Te(),K.removeEventListener("scrollend",fe)};K.addEventListener("scrollend",fe,{once:!0}),u.current=setTimeout(()=>{K.removeEventListener("scrollend",fe),Te()},Ye)}else{let fe=Ie==="smooth"?500:50;u.current=setTimeout(Te,fe)}},[]),Le=_(()=>{let{viewport:e,orientation:r}=T.current;if(e)e.style.scrollBehavior="auto",V.current=r==="vertical"?e.scrollTop:e.scrollLeft},[]),Ae=_((e)=>{let{viewport:r,orientation:s}=T.current;if(r){let p=V.current-e;if(s==="vertical")r.scrollTop=p;else r.scrollLeft=p}},[]),ft=_(()=>{let{viewport:e,orientation:r,items:s,virtualizer:p}=T.current;if(!e||s.length===0)return T.current.index;let E=r==="vertical"?e.scrollTop:e.scrollLeft,h=p.containerSize||e.clientHeight;if(h<=0)return T.current.index;let O=Math.round(E/h);return Y(O,0,s.length-1)},[]),Pt=at({orientation:o,direction:w,discretePaging:y.discretePaging??!0,threshold:y.threshold??80,debounce:y.debounce??120,cooldown:y.cooldown??400,onRequestIndexChange:(e)=>H(T.current.index+e,"user:wheel"),viewport:g,onDragStart:Le,onDrag:Ae,onDragEnd:()=>{let e=ft();H(e,"snap")}}),ke=qe({orientation:o,direction:w,threshold:b.threshold??50,flickVelocity:b.flickVelocity??0.5,lockAxis:b.lockAxis??!0,ignoreWhileAnimating:b.ignoreWhileAnimating??!0,loop:v,getIndex:()=>T.current.index,maxIndex:Math.max(t.length-1,0),onRequestIndexChange:(e)=>H(e,"user:gesture"),setAnimating:G,isAnimating:L,onDragStart:Le,onDrag:Ae}),_e=lt({orientation:o,direction:w,config:m?S:{enabled:!1},onPrev:()=>H(T.current.index-1,"user:keyboard"),onNext:()=>H(T.current.index+1,"user:keyboard"),onFirst:()=>H(0,"user:keyboard"),onLast:()=>H(t.length-1,"user:keyboard")}),we=A(null),xe=A(null),Ne=_(()=>{if(he(),x.current&&Date.now()-M.current>Je)x.current=!1;if(x.current)return;if(xe.current)clearTimeout(xe.current);if(xe.current=setTimeout(()=>{if(x.current)return;let{viewport:e,orientation:r,index:s}=T.current;if(!e)return;let p=r==="vertical"?e.scrollTop:e.scrollLeft,E=r==="vertical"?e.clientHeight:e.clientWidth,h=s*E,O=typeof window<"u"?window.devicePixelRatio:1,q=Math.max(be,Math.ceil(be*O));if(Math.abs(p-h)>q)e.scrollTo({top:r==="vertical"?h:0,left:r==="horizontal"?h:0,behavior:"smooth"})},Qe),we.current!==null)return;we.current=requestAnimationFrame(()=>{if(we.current=null,x.current)return;let{viewport:e,orientation:r,items:s,options:p}=T.current;if(!e)return;if(p.visibility?.strategy==="intersection"&&typeof IntersectionObserver<"u")return;let h=r==="vertical"?e.scrollTop:e.scrollLeft,O=r==="vertical"?e.clientHeight:e.clientWidth;if(O>0&&s.length>0){let q=Math.round(h/O),U=Y(q,0,s.length-1);ge(U)}})},[ge,he]);ie(()=>{if(t.length===0)return;let r=t.length-1-l;if(r<=c)n.onEndReached?.({distanceFromEnd:r,direction:"forward"});if(l<=c)n.onEndReached?.({distanceFromEnd:l,direction:"backward"})},[c,l,t.length,n]);let Pe=ce(()=>({index:l,isAnimating:L,canPrev:v||l>0,canNext:v||l<t.length-1}),[l,L,t.length,v]),de=A(null);ie(()=>{if(!g)return;let r=new ResizeObserver(()=>{if(he(),de.current)clearTimeout(de.current);de.current=setTimeout(()=>{let{orientation:s,index:p}=T.current;if(!g)return;let E=s==="vertical"?g.clientHeight:g.clientWidth,h=p*E,O=s==="vertical"?g.scrollTop:g.scrollLeft;if(Math.abs(O-h)>E*nt)if(s==="vertical")g.scrollTop=h;else g.scrollLeft=h;le()},et)});return r.observe(g),()=>{if(r.disconnect(),de.current)clearTimeout(de.current)}},[le,he,g]);let ze=_(()=>{let{viewport:e,orientation:r}=T.current;if(e)e.style.scrollSnapType=r==="vertical"?"y mandatory":"x mandatory"},[]),He=_(()=>{let e={position:"relative",overflow:"auto",scrollSnapType:o==="vertical"?"y mandatory":"x mandatory",touchAction:o==="vertical"?"pan-y":"pan-x",willChange:"scroll-position"};return{ref:B,role:"feed","aria-label":f,"aria-busy":L,tabIndex:0,onScroll:Ne,onKeyDown:S.global?void 0:_e.onKeyDown,onTouchStart:ze,...ke.handlers,style:e}},[f,Ne,ze,L,_e.onKeyDown,S.global,o,ke.handlers]),Ve=_((e)=>{let r=l===e,s=o==="vertical"?"100dvh":"100dvw";return{ref:Oe(e),"data-index":e,"data-active":r,style:{position:"absolute",top:0,left:0,transform:o==="vertical"?`translateY(calc(${e} * ${s}))`:`translateX(calc(${e} * ${s}))`,height:o==="vertical"?s:"100%",width:o==="horizontal"?s:"100%",willChange:"transform",scrollSnapAlign:"start",scrollSnapStop:"always"}}},[Oe,l,o]),We=_(()=>H(T.current.index-1,"programmatic"),[H]),Ue=_(()=>H(T.current.index+1,"programmatic"),[H]),Ke=_(()=>Z.current,[]);return ce(()=>({...Pe,prev:We,next:Ue,scrollTo:(e,r)=>H(e,"programmatic",r?.behavior),getViewportProps:He,getItemProps:Ve,virtualItems:ae.virtualItems,totalSize:ae.totalSize,items:t,orientation:o,viewport:g,getMotion:Ke}),[Pe,We,Ue,H,He,Ve,ae.virtualItems,ae.totalSize,t,o,g,Ke])}import{useState as Ct,useEffect as Mt}from"react";function Ot(){let[n,t]=Ct({width:typeof window<"u"?window.innerWidth:0,height:typeof window<"u"?window.innerHeight:0});return Mt(()=>{if(typeof window>"u")return;let o,w=()=>{clearTimeout(o),o=setTimeout(()=>{t({width:window.innerWidth,height:window.innerHeight})},tt)};return window.addEventListener("resize",w),()=>{window.removeEventListener("resize",w),clearTimeout(o)}},[]),n}import{createContext as Lt,useContext as At}from"react";var Me=Lt(void 0);function kt(){let n=At(Me);if(!n)throw Error("useSwipeItem must be used within a SwipeDeck item");return n}import{useImperativeHandle as _t,useMemo as mt}from"react";import{jsx as Se}from"react/jsx-runtime";function Nt(n){let{as:t="div",children:o,className:w,style:v,ref:k,...D}=n,i=Ce(D);_t(k,()=>({prev:i.prev,next:i.next,scrollTo:i.scrollTo,getMotion:i.getMotion,getState:()=>({index:i.index,isAnimating:i.isAnimating,canPrev:i.canPrev,canNext:i.canNext}),viewport:i.viewport}),[i]);let{style:b,...y}=i.getViewportProps(),S=n.fullscreen?{height:"100dvh",width:"100%",position:"absolute",top:0,left:0}:{},I=mt(()=>({...b,...S,...v}),[b,S,v]),d=mt(()=>({height:i.orientation==="vertical"?`calc(${i.items.length} * 100dvh)`:"100%",width:i.orientation==="horizontal"?`calc(${i.items.length} * 100dvw)`:"100%",position:"relative"}),[i.orientation,i.items.length]);return Se(t,{...y,className:w,style:I,children:Se("div",{style:d,children:i.virtualItems.map((f)=>{let m=f.index,R=i.items[m];if(!R)return null;let C=i.getItemProps(m),a=D.preload??0,l=D.preloadPrevious??0,L=!1;if(a>0||l>0){let x=i.index;if(!D.loop){let u=m>x&&m<=x+a,M=m<x&&m>=x-l;L=u||M}else{let u=i.items.length,M=(m-x+u)%u,z=(x-m+u)%u,X=M>0&&M<=a,Z=z>0&&z<=l;L=X||Z}}let{style:G,ref:g,...B}=C,P={item:R,index:m,isActive:i.index===m,shouldPreload:L,props:B},V=f.key??(D.virtual?.getItemKey?.(R,m)??m);return Se("article",{...C,"aria-label":`Item ${m+1} of ${i.items.length}`,children:Se(Me.Provider,{value:P,children:o(P)})},V)})})})}export{Nt as SwipeDeck,Ce as useSwipeDeck,kt as useSwipeItem,Ot as useWindowSize};
2
2
 
3
- //# debugId=0FD04F832BA4D05B64756E2164756E21
3
+ //# debugId=3ADEFBB0F912DD0264756E2164756E21
4
4
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1,9 +1,21 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": [],
3
+ "sources": ["../src/hooks/useSwipeDeck.ts", "../src/utils/clamp.ts", "../src/utils/prefersReducedMotion.ts", "../src/motion.ts", "../src/hooks/useGestures.ts", "../src/hooks/useWheel.ts", "../src/constants.ts", "../src/hooks/useKeyboard.ts", "../src/hooks/useVirtualizer.ts", "../src/hooks/useWindowSize.ts", "../src/hooks/useSwipeItem.ts", "../src/components/SwipeDeck.tsx"],
4
4
  "sourcesContent": [
5
+ "import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type React from \"react\";\nimport { clamp } from \"../utils/clamp\";\nimport { prefersReducedMotion } from \"../utils/prefersReducedMotion\";\nimport { calculateSwipeDeckMotion, createInitialSwipeDeckMotion } from \"../motion\";\nimport { useGestures } from \"./useGestures\";\nimport { useWheel } from \"./useWheel\";\nimport { useKeyboard } from \"./useKeyboard\";\nimport { useVirtualizer } from \"./useVirtualizer\";\nimport type {\n Direction,\n IndexChangeSource,\n Orientation,\n ScrollBehavior,\n SwipeDeckAPI,\n SwipeDeckOptions,\n SwipeDeckState,\n} from \"../types\";\nimport {\n NAVIGATION_COOLDOWN_MS,\n SCROLLEND_FALLBACK_TIMEOUT_MS,\n STUCK_NAVIGATION_TIMEOUT_MS,\n NAVIGATION_LOCK_TIMEOUT_MS,\n SNAP_CORRECTION_DEBOUNCE_MS,\n RESIZE_CORRECTION_DEBOUNCE_MS,\n SNAP_ALIGNMENT_TOLERANCE_PX,\n RESIZE_MISALIGNMENT_THRESHOLD,\n} from \"../constants\";\n\nconst DEFAULTS = {\n orientation: \"vertical\" as Orientation,\n direction: \"ltr\" as Direction,\n loop: false,\n defaultIndex: 0,\n gesture: {\n threshold: 10,\n flickVelocity: 0.1,\n lockAxis: true,\n ignoreWhileAnimating: true,\n },\n wheel: {\n discretePaging: true,\n threshold: 100,\n debounce: 120,\n cooldown: 800,\n },\n keyboard: {\n enabled: true,\n },\n visibility: {\n strategy: \"position\" as const,\n intersectionRatio: 0.6,\n debounce: 100,\n },\n virtual: {\n overscan: 5,\n },\n endReachedThreshold: 3,\n ariaLabel: \"Swipe feed\",\n keyboardNavigation: true,\n};\n\nexport function useSwipeDeck<T>(options: SwipeDeckOptions<T>): SwipeDeckAPI<T> {\n const items = options.items ?? [];\n const orientation = options.orientation ?? DEFAULTS.orientation;\n const direction = options.direction ?? DEFAULTS.direction;\n const loop = options.loop ?? DEFAULTS.loop;\n const defaultIndex = options.defaultIndex ?? DEFAULTS.defaultIndex;\n const preload = options.preload ?? 0;\n const preloadPrevious = options.preloadPrevious ?? 0;\n\n const gestureCfg = useMemo(() => ({ ...DEFAULTS.gesture, ...(options.gesture ?? {}) }), [options.gesture]);\n const wheelCfg = useMemo(() => ({ ...DEFAULTS.wheel, ...(options.wheel ?? {}) }), [options.wheel]);\n const keyboardCfg = useMemo(() => ({ ...DEFAULTS.keyboard, ...(options.keyboard ?? {}) }), [options.keyboard]);\n const visibilityCfg = useMemo(\n () => ({ ...DEFAULTS.visibility, ...(options.visibility ?? {}) }),\n [options.visibility],\n );\n const virtualCfg = useMemo(() => {\n const base = { ...DEFAULTS.virtual, ...(options.virtual ?? {}) };\n // Ensure overscan is at least as large as preload + preloadPrevious to ensure all preloaded items are rendered\n const minOverscan = Math.max(preload, preloadPrevious);\n return {\n ...base,\n overscan: Math.max(base.overscan ?? 0, minOverscan),\n };\n }, [options.virtual, preload, preloadPrevious]);\n const endReachedThreshold = options.endReachedThreshold ?? DEFAULTS.endReachedThreshold;\n const ariaLabel = options.ariaLabel ?? DEFAULTS.ariaLabel;\n const keyboardNavigation = options.keyboardNavigation ?? true;\n\n const isControlled = typeof options.index === \"number\";\n const [internalIndex, setInternalIndex] = useState(() => clamp(defaultIndex, 0, Math.max(items.length - 1, 0)));\n const index = isControlled ? clamp(options.index ?? 0, 0, Math.max(items.length - 1, 0)) : internalIndex;\n\n const [isAnimating, setIsAnimating] = useState(false);\n\n // Use state for viewport to ensure hooks like useVirtualizer/useWheel know when it's ready\n const [viewport, setViewport] = useState<HTMLElement | null>(null);\n\n const sourceRef = useRef<IndexChangeSource>(\"snap\");\n const dragStartScrollRef = useRef<number>(0);\n const isNavigatingRef = useRef(false); // Track programmatic navigation to prevent scroll handler interference\n const snapRestoreTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null); // Track snap restore timeout\n const navigationStartRef = useRef<number>(0); // Track when navigation started for safety timeout\n const lastNavigationIndexRef = useRef<number>(-1); // Prevent duplicate navigations to same index\n const lastNavigationTimeRef = useRef<number>(0); // Cooldown between navigations\n const motionRef = useRef(createInitialSwipeDeckMotion(index));\n const motionRafRef = useRef<number | null>(null);\n const activeItemRef = useRef<{ item: T; index: number } | null>(null);\n const itemElementsRef = useRef(new Map<number, HTMLElement>());\n const itemRefCallbacksRef = useRef(new Map<number, React.RefCallback<HTMLElement>>());\n const visibilityObserverRef = useRef<IntersectionObserver | null>(null);\n const visibilityRatiosRef = useRef(new Map<number, number>());\n const visibilityDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n // Clamp index when items change\n const clamped = clamp(index, 0, Math.max(items.length - 1, 0));\n if (!isControlled) setInternalIndex(clamped);\n }, [index, isControlled, items.length]);\n\n const virtualizer = useVirtualizer({\n items,\n virtual: virtualCfg,\n getScrollElement: useCallback(() => viewport, [viewport]),\n orientation,\n });\n\n // Stabilize callbacks using a ref for latest state\n const latest = useRef({\n index,\n items,\n isControlled,\n options,\n virtualizer,\n loop,\n orientation,\n setInternalIndex,\n setIsAnimating,\n viewport, // Add viewport to latest ref\n });\n\n // Update ref on every render\n latest.current = {\n index,\n items,\n isControlled,\n options,\n virtualizer,\n loop,\n orientation,\n setInternalIndex,\n setIsAnimating,\n viewport,\n };\n\n const applyIndexChange = useCallback(\n (nextIndex: number) => {\n const { index, isControlled, options, setInternalIndex, setIsAnimating } = latest.current;\n if (nextIndex === index) {\n // Already at this index, no need to update\n return;\n }\n if (!isControlled) setInternalIndex(nextIndex);\n options.onIndexChange?.(nextIndex, sourceRef.current ?? \"snap\");\n setIsAnimating(false);\n sourceRef.current = \"snap\";\n },\n []\n );\n\n useEffect(() => {\n const hasActiveItem = index >= 0 && index < items.length;\n const nextActive = hasActiveItem ? { item: items[index] as T, index } : null;\n const previousActive = activeItemRef.current;\n const didChange = previousActive?.index !== nextActive?.index\n || previousActive?.item !== nextActive?.item;\n\n if (!didChange) return;\n if (previousActive) {\n latest.current.options.onItemInactive?.(previousActive.item, previousActive.index);\n }\n activeItemRef.current = nextActive;\n if (nextActive) {\n latest.current.options.onItemActive?.(nextActive.item, nextActive.index);\n }\n }, [index, items]);\n\n useEffect(() => () => {\n const activeItem = activeItemRef.current;\n if (activeItem) {\n latest.current.options.onItemInactive?.(activeItem.item, activeItem.index);\n activeItemRef.current = null;\n }\n }, []);\n\n const emitMotion = useCallback((\n force = false,\n geometry?: { orientation: Orientation; itemCount: number },\n ) => {\n const { viewport, orientation: currentOrientation, items, options } = latest.current;\n if (!viewport) return;\n const motionOrientation = geometry?.orientation ?? currentOrientation;\n const itemCount = geometry?.itemCount ?? items.length;\n\n const previousMotion = motionRef.current;\n const nextMotion = calculateSwipeDeckMotion({\n scrollOffset: motionOrientation === \"vertical\" ? viewport.scrollTop : viewport.scrollLeft,\n viewportSize: motionOrientation === \"vertical\" ? viewport.clientHeight : viewport.clientWidth,\n itemCount,\n previousScrollOffset: previousMotion.scrollOffset,\n settleTolerance: SNAP_ALIGNMENT_TOLERANCE_PX,\n });\n motionRef.current = nextMotion;\n\n const didChange = Object.keys(nextMotion).some((key) => {\n const motionKey = key as keyof typeof nextMotion;\n return nextMotion[motionKey] !== previousMotion[motionKey];\n });\n if (force || didChange) options.onMotionChange?.(nextMotion);\n }, []);\n\n const scheduleMotion = useCallback(() => {\n if (motionRafRef.current !== null) return;\n motionRafRef.current = -1;\n const animationFrame = requestAnimationFrame(() => {\n motionRafRef.current = null;\n emitMotion();\n });\n // Synchronous requestAnimationFrame test doubles may run the callback\n // before returning an id. Preserve the callback's cleared state in that case.\n if (motionRafRef.current !== null) motionRafRef.current = animationFrame;\n }, [emitMotion]);\n\n useEffect(() => {\n if (!viewport) return;\n emitMotion(true, { orientation, itemCount: items.length });\n }, [emitMotion, items.length, orientation, viewport]);\n\n useEffect(() => () => {\n if (motionRafRef.current !== null) cancelAnimationFrame(motionRafRef.current);\n }, []);\n\n const getItemRef = useCallback((itemIndex: number): React.RefCallback<HTMLElement> => {\n const cached = itemRefCallbacksRef.current.get(itemIndex);\n if (cached) return cached;\n\n const callback: React.RefCallback<HTMLElement> = (element) => {\n const previousElement = itemElementsRef.current.get(itemIndex);\n if (previousElement && previousElement !== element) {\n visibilityObserverRef.current?.unobserve(previousElement);\n }\n\n if (!element) {\n itemElementsRef.current.delete(itemIndex);\n visibilityRatiosRef.current.delete(itemIndex);\n return;\n }\n\n itemElementsRef.current.set(itemIndex, element);\n visibilityObserverRef.current?.observe(element);\n };\n itemRefCallbacksRef.current.set(itemIndex, callback);\n return callback;\n }, []);\n\n useEffect(() => {\n if (\n !viewport\n || visibilityCfg.strategy !== \"intersection\"\n || typeof IntersectionObserver === \"undefined\"\n ) return;\n\n const intersectionRatio = clamp(visibilityCfg.intersectionRatio, 0, 1);\n const debounce = Math.max(0, visibilityCfg.debounce);\n\n const commitVisibleIndex = () => {\n visibilityDebounceRef.current = null;\n const currentIndex = latest.current.index;\n let nextIndex = -1;\n let nextRatio = -1;\n\n for (const [itemIndex, ratio] of visibilityRatiosRef.current) {\n const isBetterRatio = ratio > nextRatio;\n const isCloserTie = ratio === nextRatio\n && Math.abs(itemIndex - currentIndex) < Math.abs(nextIndex - currentIndex);\n if (ratio >= intersectionRatio && (isBetterRatio || isCloserTie)) {\n nextIndex = itemIndex;\n nextRatio = ratio;\n }\n }\n\n if (nextIndex < 0 || nextIndex === latest.current.index) return;\n sourceRef.current = \"visibility\";\n applyIndexChange(nextIndex);\n };\n\n const observer = new IntersectionObserver((entries) => {\n for (const entry of entries) {\n const itemIndex = Number((entry.target as HTMLElement).dataset.index);\n if (!Number.isInteger(itemIndex)) continue;\n visibilityRatiosRef.current.set(\n itemIndex,\n entry.isIntersecting ? entry.intersectionRatio : 0,\n );\n }\n\n if (visibilityDebounceRef.current) clearTimeout(visibilityDebounceRef.current);\n if (debounce === 0) commitVisibleIndex();\n else visibilityDebounceRef.current = setTimeout(commitVisibleIndex, debounce);\n }, {\n root: viewport,\n threshold: Array.from(new Set([0, intersectionRatio, 1])),\n });\n\n visibilityObserverRef.current = observer;\n for (const element of itemElementsRef.current.values()) observer.observe(element);\n\n return () => {\n observer.disconnect();\n if (visibilityObserverRef.current === observer) visibilityObserverRef.current = null;\n visibilityRatiosRef.current.clear();\n if (visibilityDebounceRef.current) {\n clearTimeout(visibilityDebounceRef.current);\n visibilityDebounceRef.current = null;\n }\n };\n }, [\n applyIndexChange,\n viewport,\n visibilityCfg.debounce,\n visibilityCfg.intersectionRatio,\n visibilityCfg.strategy,\n ]);\n\n\n const navigateTo = useCallback(\n (targetIndex: number, source: IndexChangeSource, behavior?: ScrollBehavior) => {\n const { items, loop, index, isControlled, options, orientation, virtualizer, setInternalIndex, viewport } = latest.current;\n\n if (items.length === 0) return;\n const maxIndex = items.length - 1;\n let next = targetIndex;\n if (loop) {\n next = (next + items.length) % items.length;\n } else {\n next = clamp(next, 0, maxIndex);\n }\n\n // Don't navigate to same index unless it's a snap/correction\n if (next === index && source !== \"snap\") return;\n\n const now = Date.now();\n\n // Safety reset: Clear stuck navigation state if it's been too long\n // This prevents isNavigatingRef from permanently blocking navigation\n if (isNavigatingRef.current && now - navigationStartRef.current > STUCK_NAVIGATION_TIMEOUT_MS) {\n if (process.env.NODE_ENV !== 'production') console.warn('[SwipeDeck] Clearing stuck navigation state');\n isNavigatingRef.current = false;\n }\n\n // Block ALL navigation while one is in progress (except snap corrections and programmatic)\n if (isNavigatingRef.current && source !== \"snap\" && source !== \"programmatic\") {\n return;\n }\n\n // Minimum cooldown between ANY navigations (prevents multi-swipe)\n // Programmatic navigation bypasses cooldown since it's explicit API usage\n if (now - lastNavigationTimeRef.current < NAVIGATION_COOLDOWN_MS && source !== \"snap\" && source !== \"programmatic\") {\n return;\n }\n\n lastNavigationIndexRef.current = next;\n lastNavigationTimeRef.current = now;\n\n sourceRef.current = source;\n\n // Mark as navigating to prevent handleScroll from interfering\n isNavigatingRef.current = true;\n\n // Update index immediately\n if (!isControlled) setInternalIndex(next);\n options.onIndexChange?.(next, source);\n\n if (!viewport) {\n if (process.env.NODE_ENV !== 'production') console.warn('[SwipeDeck] No viewport, skipping scroll');\n return;\n }\n\n // Clear any pending snap restore timeout\n if (snapRestoreTimeoutRef.current) {\n clearTimeout(snapRestoreTimeoutRef.current);\n snapRestoreTimeoutRef.current = null;\n }\n\n // CRITICAL: Temporarily disable scroll-snap during programmatic navigation\n // This prevents CSS from fighting with our scroll position\n viewport.style.scrollSnapType = 'none';\n viewport.style.scrollBehavior = 'auto';\n\n // Use instant scroll for wheel and programmatic navigation to avoid timing issues\n // Smooth scroll can cause scrollend to fire late, keeping isNavigatingRef stuck\n // Only gestures get smooth scroll since they have visual drag feedback\n const targetBehavior = behavior ?? (\n source === \"user:wheel\" || source === \"programmatic\" || prefersReducedMotion() ? \"instant\" : \"smooth\"\n );\n\n // Manual scroll calculation\n const targetScroll = next * virtualizer.containerSize;\n\n // Track navigation start time for safety timeout\n navigationStartRef.current = Date.now();\n\n if (orientation === 'vertical') {\n viewport.scrollTo({ top: targetScroll, behavior: targetBehavior });\n } else {\n viewport.scrollTo({ left: targetScroll, behavior: targetBehavior });\n }\n\n // Handler to restore scroll-snap after navigation completes\n const handleScrollEnd = () => {\n isNavigatingRef.current = false;\n if (snapRestoreTimeoutRef.current) {\n clearTimeout(snapRestoreTimeoutRef.current);\n snapRestoreTimeoutRef.current = null;\n }\n if (viewport) {\n viewport.style.scrollSnapType = orientation === 'vertical' ? 'y mandatory' : 'x mandatory';\n }\n };\n\n // Use scrollend event if available (modern browsers), with fallback timeout\n if ('onscrollend' in window) {\n const scrollEndHandler = () => {\n handleScrollEnd();\n viewport.removeEventListener('scrollend', scrollEndHandler);\n };\n viewport.addEventListener('scrollend', scrollEndHandler, { once: true });\n // Safety fallback in case scrollend never fires\n snapRestoreTimeoutRef.current = setTimeout(() => {\n viewport.removeEventListener('scrollend', scrollEndHandler);\n handleScrollEnd();\n }, SCROLLEND_FALLBACK_TIMEOUT_MS);\n } else {\n // Fallback for browsers without scrollend support\n const restoreDelay = targetBehavior === 'smooth' ? 500 : 50;\n snapRestoreTimeoutRef.current = setTimeout(handleScrollEnd, restoreDelay);\n }\n },\n []\n );\n\n const onDragStart = useCallback(() => {\n const { viewport, orientation } = latest.current;\n if (viewport) {\n // Optimization: Force auto behavior immediately on drag start\n viewport.style.scrollBehavior = 'auto';\n dragStartScrollRef.current = orientation === \"vertical\" ? viewport.scrollTop : viewport.scrollLeft;\n }\n }, []);\n\n const onDrag = useCallback((delta: number) => {\n const { viewport, orientation } = latest.current;\n if (viewport) {\n const newScroll = dragStartScrollRef.current - delta;\n if (orientation === \"vertical\") {\n viewport.scrollTop = newScroll;\n } else {\n viewport.scrollLeft = newScroll;\n }\n }\n }, []);\n\n // Calculate target index from current scroll position (for snap correction)\n const getSnapTargetIndex = useCallback(() => {\n const { viewport, orientation, items, virtualizer } = latest.current;\n if (!viewport || items.length === 0) return latest.current.index;\n\n const scrollOffset = orientation === \"vertical\" ? viewport.scrollTop : viewport.scrollLeft;\n const itemSize = virtualizer.containerSize || viewport.clientHeight;\n\n if (itemSize <= 0) return latest.current.index;\n\n const targetIndex = Math.round(scrollOffset / itemSize);\n return clamp(targetIndex, 0, items.length - 1);\n }, []);\n\n const wheel = useWheel({\n orientation,\n direction,\n discretePaging: wheelCfg.discretePaging ?? true,\n threshold: wheelCfg.threshold ?? 80,\n debounce: wheelCfg.debounce ?? 120,\n cooldown: wheelCfg.cooldown ?? 400,\n onRequestIndexChange: delta => navigateTo(latest.current.index + delta, \"user:wheel\"),\n viewport,\n onDragStart,\n onDrag,\n onDragEnd: () => {\n // Calculate correct target from scroll position, not from state\n const targetIndex = getSnapTargetIndex();\n navigateTo(targetIndex, \"snap\");\n },\n });\n\n const gestures = useGestures({\n orientation,\n direction,\n threshold: gestureCfg.threshold ?? 50,\n flickVelocity: gestureCfg.flickVelocity ?? 0.5,\n lockAxis: gestureCfg.lockAxis ?? true,\n ignoreWhileAnimating: gestureCfg.ignoreWhileAnimating ?? true,\n loop,\n getIndex: () => latest.current.index,\n maxIndex: Math.max(items.length - 1, 0),\n onRequestIndexChange: next => navigateTo(next, \"user:gesture\"),\n setAnimating: setIsAnimating,\n isAnimating,\n onDragStart,\n onDrag,\n });\n\n const keyboard = useKeyboard({\n orientation,\n direction,\n config: keyboardNavigation ? keyboardCfg : { enabled: false },\n onPrev: () => navigateTo(latest.current.index - 1, \"user:keyboard\"),\n onNext: () => navigateTo(latest.current.index + 1, \"user:keyboard\"),\n onFirst: () => navigateTo(0, \"user:keyboard\"),\n onLast: () => navigateTo(items.length - 1, \"user:keyboard\"),\n });\n\n // Calculate visibility based on scroll\n const rafId = useRef<number | null>(null);\n const scrollEndTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const handleScroll = useCallback(() => {\n scheduleMotion();\n\n // Safety: Force unlock if navigation has been stuck for too long\n if (isNavigatingRef.current && Date.now() - navigationStartRef.current > NAVIGATION_LOCK_TIMEOUT_MS) {\n isNavigatingRef.current = false;\n if (process.env.NODE_ENV !== 'production') console.warn('[SwipeDeck] Navigation lock timeout - forcing unlock');\n }\n\n // Skip scroll-based index calculation during programmatic navigation\n if (isNavigatingRef.current) return;\n\n // Safety Snap: If scrolling stops and we are misaligned, snap to current index\n if (scrollEndTimeoutRef.current) clearTimeout(scrollEndTimeoutRef.current);\n scrollEndTimeoutRef.current = setTimeout(() => {\n if (isNavigatingRef.current) return;\n const { viewport, orientation, index } = latest.current;\n if (!viewport) return;\n\n const scrollOffset = orientation === \"vertical\" ? viewport.scrollTop : viewport.scrollLeft;\n const computedSize = orientation === \"vertical\" ? viewport.clientHeight : viewport.clientWidth;\n const idealOffset = index * computedSize;\n\n // Use device pixel ratio for tolerance to handle high-DPI displays\n const dpr = typeof window !== 'undefined' ? window.devicePixelRatio : 1;\n const tolerance = Math.max(SNAP_ALIGNMENT_TOLERANCE_PX, Math.ceil(SNAP_ALIGNMENT_TOLERANCE_PX * dpr));\n if (Math.abs(scrollOffset - idealOffset) > tolerance) {\n // We are stuck between frames. Snap to the current detected index.\n viewport.scrollTo({\n top: orientation === \"vertical\" ? idealOffset : 0,\n left: orientation === \"horizontal\" ? idealOffset : 0,\n behavior: 'smooth'\n });\n }\n }, SNAP_CORRECTION_DEBOUNCE_MS);\n\n if (rafId.current !== null) return;\n\n rafId.current = requestAnimationFrame(() => {\n rafId.current = null;\n\n // Double-check we're not navigating\n if (isNavigatingRef.current) return;\n\n const { viewport, orientation, items, options } = latest.current;\n if (!viewport) return;\n\n const intersectionVisibilityAvailable = options.visibility?.strategy === \"intersection\"\n && typeof IntersectionObserver !== \"undefined\";\n if (intersectionVisibilityAvailable) return;\n\n const scrollOffset = orientation === \"vertical\" ? viewport.scrollTop : viewport.scrollLeft;\n const viewportSize = orientation === \"vertical\" ? viewport.clientHeight : viewport.clientWidth;\n\n // Simple geometric calculation - works with CSS viewport units\n // Each item is 100dvh tall, so index = scrollOffset / viewportSize\n if (viewportSize > 0 && items.length > 0) {\n const estimatedIndex = Math.round(scrollOffset / viewportSize);\n const newIndex = clamp(estimatedIndex, 0, items.length - 1);\n applyIndexChange(newIndex);\n }\n });\n }, [applyIndexChange, scheduleMotion]);\n\n // onEndReached\n useEffect(() => {\n if (items.length === 0) return;\n const maxIndex = items.length - 1;\n const distanceFromEnd = maxIndex - index;\n if (distanceFromEnd <= endReachedThreshold) {\n options.onEndReached?.({ distanceFromEnd, direction: \"forward\" });\n }\n if (index <= endReachedThreshold) {\n options.onEndReached?.({ distanceFromEnd: index, direction: \"backward\" });\n }\n }, [endReachedThreshold, index, items.length, options]);\n\n const apiState: SwipeDeckState = useMemo(\n () => ({\n index,\n isAnimating,\n canPrev: loop || index > 0,\n canNext: loop || index < items.length - 1,\n }),\n [index, isAnimating, items.length, loop],\n );\n\n // ═══════════════════════════════════════════════════════════════════════════\n // RESIZE HANDLING: Scroll Position Correction\n // ═══════════════════════════════════════════════════════════════════════════\n // CSS viewport units handle item sizing automatically.\n // But scroll position (in pixels) becomes invalid on resize.\n // We use the current index state to correct scroll position after resize settles.\n const resizeTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n if (!viewport) return;\n\n const handleResize = () => {\n scheduleMotion();\n\n // Clear any pending correction\n if (resizeTimeoutRef.current) {\n clearTimeout(resizeTimeoutRef.current);\n }\n\n // After resize settles, snap scroll to current index\n resizeTimeoutRef.current = setTimeout(() => {\n const { orientation, index: currentIndex } = latest.current;\n if (!viewport) return;\n\n const size = orientation === 'vertical' ? viewport.clientHeight : viewport.clientWidth;\n const targetScroll = currentIndex * size;\n\n // Only correct if significantly off (avoid fighting with scroll-snap)\n const currentScroll = orientation === 'vertical' ? viewport.scrollTop : viewport.scrollLeft;\n if (Math.abs(currentScroll - targetScroll) > size * RESIZE_MISALIGNMENT_THRESHOLD) {\n if (orientation === 'vertical') {\n viewport.scrollTop = targetScroll;\n } else {\n viewport.scrollLeft = targetScroll;\n }\n }\n emitMotion();\n }, RESIZE_CORRECTION_DEBOUNCE_MS);\n };\n\n const resizeObserver = new ResizeObserver(handleResize);\n resizeObserver.observe(viewport);\n\n return () => {\n resizeObserver.disconnect();\n if (resizeTimeoutRef.current) {\n clearTimeout(resizeTimeoutRef.current);\n }\n };\n }, [emitMotion, scheduleMotion, viewport]);\n\n // Re-enable scroll-snap when user touches the screen\n const handleTouchStart = useCallback(() => {\n const { viewport, orientation } = latest.current;\n if (viewport) {\n viewport.style.scrollSnapType = orientation === 'vertical' ? 'y mandatory' : 'x mandatory';\n }\n }, []);\n\n const getViewportProps = useCallback(() => {\n const virtualStyles: React.CSSProperties = {\n position: \"relative\",\n overflow: \"auto\",\n // Native Scroll Snap - handles touch swipe automatically\n scrollSnapType: orientation === \"vertical\" ? \"y mandatory\" : \"x mandatory\",\n // Allow native touch scrolling - this works with scroll-snap for smooth swipe experience\n touchAction: orientation === \"vertical\" ? \"pan-y\" : \"pan-x\",\n willChange: \"scroll-position\",\n };\n\n return {\n ref: setViewport,\n role: \"feed\",\n \"aria-label\": ariaLabel,\n \"aria-busy\": isAnimating,\n tabIndex: 0,\n onScroll: handleScroll,\n // onWheel: wheel.onWheel, // REMOVED: Managed internally by useWheel\n onKeyDown: keyboardCfg.global ? undefined : keyboard.onKeyDown,\n onTouchStart: handleTouchStart,\n ...gestures.handlers,\n style: virtualStyles,\n } satisfies React.HTMLAttributes<HTMLElement> & { ref: React.RefCallback<HTMLElement> };\n }, [ariaLabel, handleScroll, handleTouchStart, isAnimating, keyboard.onKeyDown, keyboardCfg.global, orientation, gestures.handlers]);\n\n const getItemProps = useCallback(\n (itemIndex: number) => {\n const isActive = index === itemIndex;\n\n // Use CSS viewport units for positioning - these automatically update on rotation!\n // This is much simpler and more reliable than trying to correct pixel offsets.\n const sizeUnit = orientation === 'vertical' ? '100dvh' : '100dvw';\n\n return {\n ref: getItemRef(itemIndex),\n \"data-index\": itemIndex,\n \"data-active\": isActive,\n style: {\n position: \"absolute\" as const,\n top: 0,\n left: 0,\n // Use CSS calc with viewport units - browser handles rotation automatically!\n transform: orientation === 'vertical'\n ? `translateY(calc(${itemIndex} * ${sizeUnit}))`\n : `translateX(calc(${itemIndex} * ${sizeUnit}))`,\n height: orientation === 'vertical' ? sizeUnit : '100%',\n width: orientation === 'horizontal' ? sizeUnit : '100%',\n willChange: \"transform\",\n // Native Snap Item Styles\n scrollSnapAlign: \"start\",\n scrollSnapStop: \"always\" satisfies React.CSSProperties[\"scrollSnapStop\"],\n } satisfies React.CSSProperties,\n };\n },\n [getItemRef, index, orientation],\n );\n\n const prev = useCallback(() => navigateTo(latest.current.index - 1, \"programmatic\"), [navigateTo]);\n const next = useCallback(() => navigateTo(latest.current.index + 1, \"programmatic\"), [navigateTo]);\n const getMotion = useCallback(() => motionRef.current, []);\n\n const api: SwipeDeckAPI<T> = useMemo(() => ({\n ...apiState,\n prev,\n next,\n scrollTo: (target, opts) => navigateTo(target, \"programmatic\", opts?.behavior),\n getViewportProps,\n getItemProps,\n virtualItems: virtualizer.virtualItems,\n totalSize: virtualizer.totalSize,\n items,\n orientation,\n viewport,\n getMotion,\n }), [apiState, prev, next, navigateTo, getViewportProps, getItemProps, virtualizer.virtualItems, virtualizer.totalSize, items, orientation, viewport, getMotion]);\n\n return api;\n}\n",
6
+ "export function clamp(value: number, min: number, max: number): number {\n if (Number.isNaN(value)) return min;\n return Math.min(Math.max(value, min), max);\n}\n\n",
7
+ "let cached = false;\nlet initialized = false;\n\nexport function prefersReducedMotion(): boolean {\n if (initialized) return cached;\n\n initialized = true;\n\n if (typeof window === \"undefined\" || typeof window.matchMedia !== \"function\") {\n cached = false;\n return cached;\n }\n\n const mql = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n cached = mql.matches;\n\n mql.addEventListener(\"change\", (event) => {\n cached = event.matches;\n });\n\n return cached;\n}\n",
8
+ "import type { SwipeDeckMotion } from \"./types\";\n\ntype CalculateSwipeDeckMotionOptions = {\n scrollOffset: number;\n viewportSize: number;\n itemCount: number;\n previousScrollOffset?: number;\n settleTolerance?: number;\n};\n\nconst DEFAULT_SETTLE_TOLERANCE_PX = 1;\n\nexport function createInitialSwipeDeckMotion(index = 0): SwipeDeckMotion {\n const normalizedIndex = Number.isFinite(index) ? Math.max(0, Math.floor(index)) : 0;\n return {\n scrollOffset: 0,\n viewportSize: 0,\n position: normalizedIndex,\n index: normalizedIndex,\n offset: 0,\n offsetRatio: 0,\n direction: \"none\",\n isSettled: true,\n };\n}\n\nexport function calculateSwipeDeckMotion({\n scrollOffset,\n viewportSize,\n itemCount,\n previousScrollOffset,\n settleTolerance = DEFAULT_SETTLE_TOLERANCE_PX,\n}: CalculateSwipeDeckMotionOptions): SwipeDeckMotion {\n if (!Number.isFinite(viewportSize) || viewportSize <= 0 || !Number.isFinite(itemCount) || itemCount <= 0) {\n return createInitialSwipeDeckMotion();\n }\n\n const normalizedItemCount = Math.floor(itemCount);\n const maxScrollOffset = (normalizedItemCount - 1) * viewportSize;\n const normalizedScrollOffset = Number.isFinite(scrollOffset)\n ? Math.max(0, Math.min(maxScrollOffset, scrollOffset))\n : 0;\n const position = normalizedScrollOffset / viewportSize;\n const index = Math.max(0, Math.min(normalizedItemCount - 1, Math.round(position)));\n const offset = index * viewportSize - normalizedScrollOffset;\n const normalizedPreviousOffset = Number.isFinite(previousScrollOffset)\n ? Math.max(0, Math.min(maxScrollOffset, previousScrollOffset ?? 0))\n : normalizedScrollOffset;\n const direction = normalizedScrollOffset > normalizedPreviousOffset\n ? \"forward\"\n : normalizedScrollOffset < normalizedPreviousOffset\n ? \"backward\"\n : \"none\";\n\n return {\n scrollOffset: normalizedScrollOffset,\n viewportSize,\n position,\n index,\n offset,\n offsetRatio: offset / viewportSize,\n direction,\n isSettled: Math.abs(offset) <= Math.max(0, settleTolerance),\n };\n}\n",
9
+ "import { useCallback, useRef, useState, useMemo } from \"react\";\nimport { clamp } from \"../utils/clamp\";\nimport type { Direction, Orientation } from \"../types\";\n\ntype GestureState = {\n isDragging: boolean;\n start: number;\n last: number;\n delta: number;\n startTime: number;\n};\n\ntype UseGesturesParams = {\n orientation: Orientation;\n direction: Direction;\n threshold: number;\n flickVelocity: number;\n lockAxis: boolean;\n ignoreWhileAnimating: boolean;\n loop: boolean;\n getIndex: () => number;\n maxIndex: number;\n onRequestIndexChange: (nextIndex: number) => void;\n setAnimating: (value: boolean) => void;\n isAnimating: boolean;\n onDragStart?: (evt: React.PointerEvent) => void;\n onDrag?: (delta: number, evt: React.PointerEvent) => void;\n onDragEnd?: () => void;\n};\n\nfunction primaryCoord(evt: PointerEvent | React.PointerEvent, orientation: Orientation) {\n return orientation === \"vertical\" ? evt.clientY : evt.clientX;\n}\n\n/**\n * Pointer/touch gestures (drag + flick). Mirrors the spec:\n * IDLE -> DRAGGING -> SETTLING with threshold + velocity decision.\n */\nexport function useGestures(params: UseGesturesParams) {\n const {\n orientation,\n direction,\n threshold,\n flickVelocity,\n lockAxis,\n ignoreWhileAnimating,\n loop,\n getIndex,\n maxIndex,\n onRequestIndexChange,\n setAnimating,\n isAnimating,\n onDragStart,\n onDrag,\n onDragEnd,\n } = params;\n\n const [isDragging, setIsDragging] = useState(false);\n const state = useRef<GestureState>({\n isDragging: false,\n start: 0,\n last: 0,\n delta: 0,\n startTime: 0,\n });\n\n const startDrag = useCallback((evt: React.PointerEvent) => {\n evt.currentTarget.setPointerCapture?.(evt.pointerId);\n const coord = primaryCoord(evt, orientation);\n state.current = {\n isDragging: true,\n start: coord,\n last: coord,\n delta: 0,\n startTime: performance.now(),\n };\n setIsDragging(true);\n onDragStart?.(evt);\n }, [orientation, onDragStart]);\n\n const updateDrag = useCallback((evt: React.PointerEvent) => {\n if (!state.current.isDragging) return;\n\n const coord = primaryCoord(evt, orientation);\n const delta = coord - state.current.start;\n state.current.delta = delta;\n state.current.last = coord;\n onDrag?.(delta, evt);\n }, [orientation, onDrag]);\n\n const endDrag = useCallback(() => {\n if (!state.current.isDragging) return;\n\n const now = performance.now();\n const duration = Math.max(now - state.current.startTime, 1);\n const distance = Math.abs(state.current.delta);\n const velocity = distance / duration; // px/ms\n\n const isForward = (() => {\n const raw = state.current.delta;\n if (orientation === \"vertical\") return raw < 0;\n // horizontal respects text direction\n const normalized = direction === \"rtl\" ? raw * -1 : raw;\n return normalized < 0;\n })();\n\n const current = getIndex();\n const deltaSign = isForward ? 1 : -1;\n const meetsFlick = velocity > flickVelocity;\n const meetsDistance = distance > threshold;\n\n let next = current;\n if (meetsFlick || meetsDistance) {\n next = current + deltaSign;\n }\n\n if (loop) {\n next = (next + (maxIndex + 1)) % (maxIndex + 1);\n } else {\n next = clamp(next, 0, maxIndex);\n }\n\n setAnimating(true);\n onRequestIndexChange(next);\n\n state.current.isDragging = false;\n state.current.delta = 0;\n setIsDragging(false);\n onDragEnd?.();\n }, [direction, flickVelocity, getIndex, maxIndex, onRequestIndexChange, orientation, loop, setAnimating, threshold, onDragEnd]);\n\n const cancelDrag = useCallback(() => {\n state.current.isDragging = false;\n state.current.delta = 0;\n setIsDragging(false);\n }, []);\n\n const onPointerDown = useCallback((evt: React.PointerEvent) => {\n if (ignoreWhileAnimating && isAnimating) return;\n if (evt.button !== 0) return;\n startDrag(evt);\n }, [ignoreWhileAnimating, isAnimating, startDrag]);\n\n const onPointerMove = useCallback((evt: React.PointerEvent) => {\n if (!lockAxis && !state.current.isDragging) return;\n if (state.current.isDragging) {\n updateDrag(evt);\n }\n }, [lockAxis, updateDrag]);\n\n const onPointerUp = useCallback(() => {\n endDrag();\n }, [endDrag]);\n\n const onPointerCancel = useCallback(() => {\n cancelDrag();\n }, [cancelDrag]);\n\n return useMemo(() => ({\n isDragging,\n handlers: { onPointerDown, onPointerMove, onPointerUp, onPointerCancel },\n }), [isDragging, onPointerDown, onPointerMove, onPointerUp, onPointerCancel]);\n}\n\n",
10
+ "import { useCallback, useRef, useEffect } from \"react\";\nimport type { Direction, Orientation } from \"../types\";\nimport {\n WHEEL_MAX_DELTA_ACCUMULATION,\n WHEEL_MAX_VISUAL_DELTA,\n WHEEL_FLICK_VELOCITY_THRESHOLD,\n WHEEL_FLICK_DISTANCE_THRESHOLD,\n WHEEL_VELOCITY_SMOOTHING_WEIGHT,\n} from \"../constants\";\n\nexport type UseWheelParams = {\n orientation: Orientation;\n direction: Direction;\n discretePaging: boolean;\n threshold: number;\n debounce: number;\n cooldown?: number; // Cooldown period after navigation (ms)\n onRequestIndexChange: (delta: 1 | -1) => void;\n viewport: HTMLElement | null;\n onDragStart?: () => void;\n onDrag?: (delta: number) => void;\n onDragEnd?: () => void;\n};\n\n/**\n * Wheel handler supporting discrete paging (TikTok-like) or continuous tracking.\n * \n * Aggressively prevents multi-video scrolling:\n * - Long cooldown period after each navigation\n * - Capped delta per event to prevent large jumps (smooths jerky mouse wheels)\n * - Direction locking during a scroll gesture\n */\nexport function useWheel(params: UseWheelParams) {\n const {\n orientation,\n direction,\n discretePaging,\n threshold,\n debounce,\n cooldown = 500,\n onRequestIndexChange,\n viewport,\n onDragStart,\n onDrag,\n onDragEnd,\n } = params;\n\n const accumulated = useRef(0);\n const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const lastNavigationTime = useRef(0);\n const isInCooldown = useRef(false);\n const lastEventTime = useRef(0);\n const gestureDirection = useRef<1 | -1 | null>(null);\n const eventCount = useRef(0);\n const isTracking = useRef(false);\n const velocityRef = useRef(0);\n\n\n const endGesture = useCallback(() => {\n isTracking.current = false;\n accumulated.current = 0;\n gestureDirection.current = null;\n eventCount.current = 0;\n velocityRef.current = 0;\n onDragEnd?.();\n }, [onDragEnd]);\n\n const resetAccumulated = useCallback(() => {\n if (timeoutRef.current) clearTimeout(timeoutRef.current);\n timeoutRef.current = setTimeout(() => {\n endGesture();\n }, debounce);\n }, [debounce, endGesture]);\n\n useEffect(() => {\n const element = viewport;\n if (!element) return;\n\n const onWheel = (evt: WheelEvent) => {\n if (!discretePaging) return;\n\n evt.preventDefault();\n evt.stopPropagation();\n\n const now = performance.now();\n\n // Strict cooldown check - during cooldown, ignore events WITHOUT triggering snap\n if (isInCooldown.current) {\n if (now - lastNavigationTime.current < cooldown) {\n // Reset tracking state WITHOUT calling onDragEnd (which triggers snap navigation)\n // We don't want snap to fight with the navigation that just happened\n if (isTracking.current) {\n isTracking.current = false;\n accumulated.current = 0;\n gestureDirection.current = null;\n eventCount.current = 0;\n velocityRef.current = 0;\n // NOTE: NOT calling onDragEnd here to avoid triggering snap\n }\n return;\n }\n isInCooldown.current = false;\n }\n\n const rawDelta = orientation === \"vertical\" ? evt.deltaY : evt.deltaX;\n // RTL flips horizontal direction\n const adjusted = orientation === \"horizontal\" && direction === \"rtl\" ? -rawDelta : rawDelta;\n\n // Determine scroll direction\n const currentDirection: 1 | -1 = adjusted > 0 ? 1 : -1;\n\n // Direction locking: reset if direction changes\n if (gestureDirection.current !== null && gestureDirection.current !== currentDirection) {\n accumulated.current = 0;\n eventCount.current = 0;\n }\n gestureDirection.current = currentDirection;\n\n if (!isTracking.current) {\n isTracking.current = true;\n onDragStart?.();\n }\n\n // Calculate time since last event\n const timeDelta = now - lastEventTime.current;\n lastEventTime.current = now;\n eventCount.current++;\n\n // 1. Calculate delta for ACCUMULATION (Threshold Check)\n // Allow fairly large steps so mouse wheel (100) triggers threshold quickly if repeated\n const accumDelta = Math.sign(adjusted) * Math.min(Math.abs(adjusted), WHEEL_MAX_DELTA_ACCUMULATION);\n\n // 2. Calculate delta for VISUAL DRAG (Smoothing)\n // Cap at WHEEL_MAX_VISUAL_DELTA so 100px jumps become 40px nudges\n const visualDelta = Math.sign(adjusted) * Math.min(Math.abs(adjusted), WHEEL_MAX_VISUAL_DELTA);\n\n // Flick detection velocity\n const instantVelocity = (timeDelta > 0 && timeDelta < 100) ? Math.abs(accumDelta / timeDelta) : 0;\n velocityRef.current = velocityRef.current * WHEEL_VELOCITY_SMOOTHING_WEIGHT + instantVelocity * (1 - WHEEL_VELOCITY_SMOOTHING_WEIGHT);\n\n accumulated.current += accumDelta;\n\n // Visual Tracking: Move the slide, but smoothed\n onDrag?.(-visualDelta);\n\n resetAccumulated();\n\n const matchesThreshold = Math.abs(accumulated.current) >= threshold;\n const isFlick = velocityRef.current > WHEEL_FLICK_VELOCITY_THRESHOLD && Math.abs(accumulated.current) > WHEEL_FLICK_DISTANCE_THRESHOLD;\n\n if (matchesThreshold || isFlick) {\n const navDelta: 1 | -1 = accumulated.current > 0 ? 1 : -1;\n\n // Reset tracking state without calling onDragEnd\n // onDragEnd is for when gesture ends WITHOUT navigation (snap back)\n // Here we ARE navigating, so we skip onDragEnd to avoid a competing snap navigation\n isTracking.current = false;\n accumulated.current = 0;\n gestureDirection.current = null;\n eventCount.current = 0;\n velocityRef.current = 0;\n\n lastNavigationTime.current = now;\n isInCooldown.current = true;\n if (timeoutRef.current) clearTimeout(timeoutRef.current);\n\n onRequestIndexChange(navDelta);\n }\n };\n\n element.addEventListener(\"wheel\", onWheel, { passive: false });\n\n return () => {\n element.removeEventListener(\"wheel\", onWheel);\n if (timeoutRef.current) clearTimeout(timeoutRef.current);\n };\n }, [\n orientation,\n direction,\n discretePaging,\n threshold,\n // debounce, // REMOVED: Used in resetAccumulated, not here directly\n cooldown,\n onRequestIndexChange,\n resetAccumulated,\n viewport,\n onDragStart,\n onDrag\n ]);\n}\n",
11
+ "// ═══════════════════════════════════════════════════════════════════════════\n// Timing Constants (milliseconds)\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Minimum time between successive navigations to prevent multi-swipe.\n * Programmatic and snap navigations bypass this cooldown.\n */\nexport const NAVIGATION_COOLDOWN_MS = 250;\n\n/**\n * Fallback timeout for scrollend event. If the browser's native scrollend\n * event never fires (e.g., due to interrupted scroll), this ensures the\n * navigation lock is released and scroll-snap is restored.\n */\nexport const SCROLLEND_FALLBACK_TIMEOUT_MS = 400;\n\n/**\n * Safety timeout to clear a stuck isNavigatingRef flag. If a navigation\n * has been in progress for longer than this, the lock is force-released\n * to prevent permanently blocking subsequent navigations.\n */\nexport const STUCK_NAVIGATION_TIMEOUT_MS = 600;\n\n/**\n * Safety timeout for handleScroll. If the navigation lock has been held\n * for longer than this, force-unlock so scroll events can update the index.\n * Longer than STUCK_NAVIGATION_TIMEOUT_MS since it's a last-resort check.\n */\nexport const NAVIGATION_LOCK_TIMEOUT_MS = 1500;\n\n/**\n * Debounce delay for snap-correction after scroll stops. After this idle\n * period, the viewport checks alignment and snaps to the current index\n * if misaligned.\n */\nexport const SNAP_CORRECTION_DEBOUNCE_MS = 150;\n\n/**\n * Debounce delay for resize-based scroll correction. After viewport resize\n * settles, correct scroll position to maintain the current index.\n */\nexport const RESIZE_CORRECTION_DEBOUNCE_MS = 50;\n\n/**\n * Debounce delay for the useWindowSize hook resize handler.\n */\nexport const WINDOW_RESIZE_DEBOUNCE_MS = 100;\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Scroll/Snap Tolerance\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Base pixel tolerance for snap alignment checks. Scaled by devicePixelRatio\n * at runtime to handle high-DPI displays correctly.\n */\nexport const SNAP_ALIGNMENT_TOLERANCE_PX = 5;\n\n/**\n * Minimum fraction of item size that scroll must be off by before resize\n * correction triggers. Prevents fighting with CSS scroll-snap.\n */\nexport const RESIZE_MISALIGNMENT_THRESHOLD = 0.1;\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Wheel Constants\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Maximum delta accumulated from a single wheel event for threshold checking.\n * Allows reasonable fast scrolls while dampening extreme values from\n * high-resolution or accelerated scroll wheels.\n */\nexport const WHEEL_MAX_DELTA_ACCUMULATION = 120;\n\n/**\n * Maximum visual delta per wheel event. Clamps the visual drag so that\n * large mouse wheel jumps (e.g., 100px) appear as smooth nudges (~40px)\n * while continuous trackpad events (usually < 20px) pass through unaffected.\n */\nexport const WHEEL_MAX_VISUAL_DELTA = 40;\n\n/**\n * Velocity threshold (px/ms) for flick detection on wheel input.\n * When the smoothed velocity exceeds this value, a navigation is triggered\n * even if the accumulated delta hasn't reached the full threshold.\n */\nexport const WHEEL_FLICK_VELOCITY_THRESHOLD = 1.2;\n\n/**\n * Minimum accumulated delta (px) for a flick to trigger navigation.\n * Prevents accidental flick detection from tiny high-velocity events.\n */\nexport const WHEEL_FLICK_DISTANCE_THRESHOLD = 20;\n\n/**\n * Exponential moving average weight for velocity smoothing.\n * Higher values (closer to 1) weight historical velocity more.\n * Current: 80% previous + 20% instantaneous.\n */\nexport const WHEEL_VELOCITY_SMOOTHING_WEIGHT = 0.8;\n\n// ═══════════════════════════════════════════════════════════════════════════\n// Virtualizer Constants\n// ═══════════════════════════════════════════════════════════════════════════\n\n/**\n * Fallback item size in pixels when viewport cannot be measured and no\n * explicit estimatedSize is provided. Only used during SSR or before\n * the scroll element is available.\n */\nexport const VIRTUALIZER_FALLBACK_SIZE_PX = 800;\n",
12
+ "import type React from \"react\";\nimport { useCallback, useEffect } from \"react\";\nimport type { Direction, KeyboardConfig, Orientation } from \"../types\";\n\ntype UseKeyboardParams = {\n orientation: Orientation;\n direction: Direction;\n config?: KeyboardConfig;\n onPrev: () => void;\n onNext: () => void;\n onFirst?: () => void;\n onLast?: () => void;\n};\n\nconst DEFAULT_BINDINGS_VERTICAL = {\n prev: [\"ArrowUp\"],\n next: [\"ArrowDown\"],\n first: [\"Home\"],\n last: [\"End\"],\n altPrev: [\"PageUp\"],\n altNext: [\"PageDown\"],\n};\n\nconst DEFAULT_BINDINGS_HORIZONTAL = {\n prev: [\"ArrowLeft\"],\n next: [\"ArrowRight\"],\n first: [\"Home\"],\n last: [\"End\"],\n altPrev: [\"PageUp\"],\n altNext: [\"PageDown\"],\n};\n\n/**\n * Keyboard navigation: arrow keys, Home/End, PageUp/PageDown.\n */\nexport function useKeyboard(params: UseKeyboardParams) {\n const { orientation, direction, config, onPrev, onNext, onFirst, onLast } = params;\n\n const enabled = config?.enabled ?? true;\n const isGlobal = config?.global ?? false;\n const bindings = config?.bindings ?? (orientation === \"vertical\" ? DEFAULT_BINDINGS_VERTICAL : DEFAULT_BINDINGS_HORIZONTAL);\n\n const handleKeyDown = useCallback(\n (evt: KeyboardEvent | React.KeyboardEvent) => {\n if (!enabled) return;\n\n const key = evt.key;\n\n const prevKeys = [...(bindings.prev ?? []), ...(bindings.altPrev ?? [])];\n const nextKeys = [...(bindings.next ?? []), ...(bindings.altNext ?? [])];\n\n const isHorizontal = orientation === \"horizontal\";\n const rtl = direction === \"rtl\";\n const stopIfGlobal = () => {\n if (isGlobal) evt.stopPropagation();\n };\n\n if (prevKeys.includes(key)) {\n evt.preventDefault();\n stopIfGlobal();\n if (isHorizontal && rtl) onNext();\n else onPrev();\n return;\n }\n\n if (nextKeys.includes(key)) {\n evt.preventDefault();\n stopIfGlobal();\n if (isHorizontal && rtl) onPrev();\n else onNext();\n return;\n }\n\n if (bindings.first?.includes(key)) {\n evt.preventDefault();\n stopIfGlobal();\n onFirst?.();\n return;\n }\n\n if (bindings.last?.includes(key)) {\n evt.preventDefault();\n stopIfGlobal();\n onLast?.();\n return;\n }\n },\n [bindings, direction, enabled, isGlobal, onFirst, onLast, onNext, onPrev, orientation],\n );\n\n // Global listener support\n useEffect(() => {\n if (!enabled || !isGlobal) return;\n\n window.addEventListener(\"keydown\", handleKeyDown);\n return () => {\n window.removeEventListener(\"keydown\", handleKeyDown);\n };\n }, [enabled, isGlobal, handleKeyDown]);\n\n return { onKeyDown: handleKeyDown };\n}\n",
13
+ "import { useEffect, useLayoutEffect, useState, useMemo, useCallback } from \"react\";\nimport { useVirtualizer as useTanStackVirtualizer } from \"@tanstack/react-virtual\";\nimport type { VirtualConfig, SwipeDeckVirtualItem, Orientation } from \"../types\";\nimport { VIRTUALIZER_FALLBACK_SIZE_PX } from \"../constants\";\n\n// Use useLayoutEffect on client, useEffect on server (SSR safety)\nconst useIsomorphicLayoutEffect = typeof window !== \"undefined\" ? useLayoutEffect : useEffect;\n\ntype UseVirtualizerParams<T> = {\n items: readonly T[];\n virtual: VirtualConfig | undefined;\n getScrollElement: () => HTMLElement | null;\n orientation?: Orientation;\n};\n\ntype VirtualizerResult = {\n virtualItems: SwipeDeckVirtualItem[];\n totalSize: number;\n getItemOffset: (index: number) => number;\n getItemSize: (index: number) => number;\n scrollToIndex: (index: number, options?: { align?: 'start' | 'center' | 'end' | 'auto', behavior?: 'auto' | 'smooth' }) => void;\n containerSize: number;\n};\n\n/**\n * Simplified adapter using @tanstack/react-virtual\n * Auto-detects viewport size when estimatedSize is not provided.\n */\nexport function useVirtualizer<T>(params: UseVirtualizerParams<T>): VirtualizerResult {\n const { items, virtual, getScrollElement, orientation = \"vertical\" } = params;\n const count = items.length;\n\n // Auto-detect viewport size when estimatedSize is not provided\n // Use state with a \"generation\" counter to force re-render when element is measured\n const [sizeState, setSizeState] = useState<{ size: number; measured: boolean }>(() => {\n // Initial fallback: use window size if available, else 800\n const fallback = typeof window !== \"undefined\"\n ? (orientation === \"vertical\" ? window.innerHeight : window.innerWidth)\n : VIRTUALIZER_FALLBACK_SIZE_PX;\n return { size: fallback, measured: false };\n });\n\n // Use useLayoutEffect to measure BEFORE paint - this fixes the black screen on initial load\n useIsomorphicLayoutEffect(() => {\n const scrollElement = getScrollElement();\n if (!scrollElement) return;\n\n const updateSize = () => {\n const size = orientation === \"vertical\"\n ? scrollElement.clientHeight\n : scrollElement.clientWidth;\n\n if (size > 0) {\n setSizeState(prev => {\n // Only update if size changed or first measurement\n if (prev.size !== size || !prev.measured) {\n return { size, measured: true };\n }\n return prev;\n });\n }\n };\n\n // Measure immediately (synchronously before paint)\n updateSize();\n\n // Watch for resizes\n const resizeObserver = new ResizeObserver(updateSize);\n resizeObserver.observe(scrollElement);\n\n return () => {\n resizeObserver.disconnect();\n };\n }, [getScrollElement, orientation]);\n\n const measuredSize = sizeState.size;\n\n // Always prioritize measured size for consistency - explicit estimatedSize is only used\n // if it's a function (for dynamic item sizes) or if we haven't measured yet\n const getEstimatedSize = useCallback((i: number): number => {\n const explicitSize = virtual?.estimatedSize;\n\n // If explicit size is a function, use it (supports dynamic item sizing)\n if (typeof explicitSize === 'function') {\n return explicitSize(items[i], i);\n }\n\n // Use measured size if available and valid, otherwise fall back to explicit or default\n if (measuredSize > 0) {\n return measuredSize;\n }\n\n // Fall back to explicit size or default\n return typeof explicitSize === 'number' ? explicitSize : VIRTUALIZER_FALLBACK_SIZE_PX;\n }, [virtual?.estimatedSize, items, measuredSize]);\n\n // Compute initialRect from window size for first render (before scroll element is available)\n const initialRect = useMemo(() => {\n if (typeof window === \"undefined\") {\n return { width: VIRTUALIZER_FALLBACK_SIZE_PX, height: VIRTUALIZER_FALLBACK_SIZE_PX };\n }\n return {\n width: window.innerWidth,\n height: window.innerHeight,\n };\n }, []);\n\n // Memoize getItemKey wrapper to prevent infinite re-renders\n const getItemKey = useMemo(() => {\n if (!virtual?.getItemKey) return undefined;\n return (index: number) => virtual.getItemKey?.(items[index], index) ?? index;\n }, [virtual?.getItemKey, items]);\n\n const rowVirtualizer = useTanStackVirtualizer({\n count,\n getScrollElement,\n estimateSize: getEstimatedSize,\n overscan: virtual?.overscan ?? 5,\n horizontal: orientation === \"horizontal\",\n getItemKey,\n // CRITICAL: Provide initialRect so virtualizer can calculate items on first render\n // even when getScrollElement() returns null\n initialRect,\n });\n\n // NOTE: Do NOT wrap this in useMemo! The rowVirtualizer object is stable,\n // but getVirtualItems() returns different results on each scroll event.\n // Wrapping in useMemo causes stale virtualItems that don't update on scroll.\n return {\n virtualItems: rowVirtualizer.getVirtualItems().map(item => ({\n index: item.index,\n key: item.key as string | number,\n offset: item.start,\n size: item.size,\n measureElement: rowVirtualizer.measureElement,\n })),\n totalSize: rowVirtualizer.getTotalSize(),\n getItemOffset: (index: number) => {\n const found = rowVirtualizer.getVirtualItems().find(v => v.index === index);\n return found ? found.start : 0;\n },\n getItemSize: (index: number) => {\n const found = rowVirtualizer.getVirtualItems().find(v => v.index === index);\n return found ? found.size : 0;\n },\n scrollToIndex: (index: number, options?: { align?: 'start' | 'center' | 'end' | 'auto', behavior?: 'auto' | 'smooth' }) => {\n rowVirtualizer.scrollToIndex(index, {\n align: options?.align,\n behavior: options?.behavior,\n });\n },\n containerSize: measuredSize,\n };\n}\n",
14
+ "import { useState, useEffect } from \"react\";\nimport { WINDOW_RESIZE_DEBOUNCE_MS } from \"../constants\";\n\nexport function useWindowSize() {\n const [size, setSize] = useState<{ width: number; height: number }>({\n width: typeof window !== \"undefined\" ? window.innerWidth : 0,\n height: typeof window !== \"undefined\" ? window.innerHeight : 0,\n });\n\n useEffect(() => {\n if (typeof window === \"undefined\") return;\n\n let timeoutId: ReturnType<typeof setTimeout>;\n\n const handleResize = () => {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(() => {\n setSize({ width: window.innerWidth, height: window.innerHeight });\n }, WINDOW_RESIZE_DEBOUNCE_MS);\n };\n\n window.addEventListener(\"resize\", handleResize);\n return () => {\n window.removeEventListener(\"resize\", handleResize);\n clearTimeout(timeoutId);\n };\n }, []);\n\n return size;\n}\n",
15
+ "import { createContext, useContext } from 'react';\nimport type { SwipeDeckRenderContext } from '../types';\n\n// biome-ignore lint/suspicious/noExplicitAny: Context defaults to any\nexport const SwipeItemContext = createContext<SwipeDeckRenderContext<any> | undefined>(undefined);\n\n// biome-ignore lint/suspicious/noExplicitAny: Generic defaults to any\nexport function useSwipeItem<T = any>(): SwipeDeckRenderContext<T> {\n const context = useContext(SwipeItemContext);\n if (!context) {\n throw new Error(\"useSwipeItem must be used within a SwipeDeck item\");\n }\n return context;\n}\n",
16
+ "\nimport type React from \"react\";\nimport { useImperativeHandle, useMemo } from \"react\";\nimport { useSwipeDeck } from \"../hooks/useSwipeDeck\";\nimport { SwipeItemContext } from \"../hooks/useSwipeItem\";\nimport type { SwipeDeckHandle, SwipeDeckProps } from \"../types\";\n\nexport function SwipeDeck<T>(\n props: SwipeDeckProps<T> & { ref?: React.Ref<SwipeDeckHandle> },\n) {\n const {\n as: As = \"div\",\n children,\n className,\n style,\n ref,\n ...options\n } = props;\n\n const deck = useSwipeDeck(options);\n\n useImperativeHandle(\n ref,\n () => ({\n prev: deck.prev,\n next: deck.next,\n scrollTo: deck.scrollTo,\n getMotion: deck.getMotion,\n getState: () => ({\n index: deck.index,\n isAnimating: deck.isAnimating,\n canPrev: deck.canPrev,\n canNext: deck.canNext,\n }),\n viewport: deck.viewport,\n }),\n [deck],\n );\n\n const { style: virtualStyle, ...restViewportProps } = deck.getViewportProps();\n\n /* Fullscreen styles if enabled */\n const fullscreenStyle: React.CSSProperties = props.fullscreen\n ? {\n height: \"100dvh\",\n width: \"100%\",\n position: \"absolute\",\n top: 0,\n left: 0,\n }\n : {};\n\n const viewportStyle = useMemo(\n () => ({ ...virtualStyle, ...fullscreenStyle, ...style }),\n [virtualStyle, fullscreenStyle, style],\n );\n\n const contentStyle = useMemo<React.CSSProperties>(\n () => ({\n // Use CSS viewport units for total size - automatically updates on rotation!\n height: deck.orientation === \"vertical\"\n ? `calc(${deck.items.length} * 100dvh)`\n : \"100%\",\n width: deck.orientation === \"horizontal\"\n ? `calc(${deck.items.length} * 100dvw)`\n : \"100%\",\n position: \"relative\",\n }),\n [deck.orientation, deck.items.length],\n );\n\n // Cast As to ElementType to avoid TS issues with polymorphic string/component\n const Comp = As as React.ElementType;\n\n return (\n <Comp\n {...restViewportProps}\n className={className}\n style={viewportStyle}\n >\n <div style={contentStyle}>\n {/* Use virtualItems for windowed rendering - only renders visible + overscan items */}\n {deck.virtualItems.map((virtualItem) => {\n const itemIndex = virtualItem.index;\n const item = deck.items[itemIndex];\n if (!item) return null;\n\n const itemProps = deck.getItemProps(itemIndex);\n const preload = options.preload ?? 0;\n const preloadPrevious = options.preloadPrevious ?? 0;\n\n let shouldPreload = false;\n // Check if we should preload (either next items or previous items)\n if (preload > 0 || preloadPrevious > 0) {\n const currentIndex = deck.index;\n if (!options.loop) {\n // Non-loop: simple index comparison\n const isNext = itemIndex > currentIndex && itemIndex <= currentIndex + preload;\n const isPrev = itemIndex < currentIndex && itemIndex >= currentIndex - preloadPrevious;\n shouldPreload = isNext || isPrev;\n } else {\n // Loop: calculate distance in both directions\n const len = deck.items.length;\n // Forward distance (0 to len-1)\n const forwardDist = (itemIndex - currentIndex + len) % len;\n // Backward distance (0 to len-1)\n const backwardDist = (currentIndex - itemIndex + len) % len;\n\n const isNext = forwardDist > 0 && forwardDist <= preload;\n const isPrev = backwardDist > 0 && backwardDist <= preloadPrevious;\n shouldPreload = isNext || isPrev;\n }\n }\n\n // Don't pass style to children - the article wrapper already handles positioning\n // Children should use inset: 0 to fill the parent\n const {\n style: _positioningStyle,\n ref: _internalItemRef,\n ...propsWithoutStyle\n } = itemProps;\n\n const contextValue = {\n item,\n index: itemIndex,\n isActive: deck.index === itemIndex,\n shouldPreload,\n props: propsWithoutStyle,\n };\n\n // Use virtualItem.key for stable keys\n const itemKey = virtualItem.key ?? (options.virtual?.getItemKey?.(item, itemIndex) ?? itemIndex);\n\n return (\n <article\n key={itemKey}\n {...itemProps}\n aria-label={`Item ${itemIndex + 1} of ${deck.items.length}`}\n >\n <SwipeItemContext.Provider value={contextValue}>\n {children(contextValue)}\n </SwipeItemContext.Provider>\n </article>\n );\n })}\n </div>\n </Comp>\n );\n}\n"
5
17
  ],
6
- "mappings": "",
7
- "debugId": "0FD04F832BA4D05B64756E2164756E21",
18
+ "mappings": "AAAA,sBAAS,eAAa,cAAW,aAAS,cAAQ,eCA3C,SAAS,CAAK,CAAC,EAAe,EAAa,EAAqB,CACrE,GAAI,OAAO,MAAM,CAAK,EAAG,OAAO,EAChC,OAAO,KA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K,aAAa,CAAS,EACvC,EAAU,EAAQ,SAAW,EAC7B,EAAkB,EAAQ,iBAAmB,EAE/C,EAAgB,GAEpB,GAAI,EAAU,GAAK,EAAkB,EAAG,CACtC,IAAM,EAAe,EAAK,MAC1B,GAAI,CAAC,EAAQ,KAAM,CAEjB,IAAM,EAAS,EAAY,GAAgB,GAAa,EAAe,EACjE,EAAS,EAAY,GAAgB,GAAa,EAAe,EACvE,EAAgB,GAAU,EACrB,KAEL,IAAM,EAAM,EAAK,MAAM,OAEjB,GAAe,EAAY,EAAe,GAAO,EAEjD,GAAgB,EAAe,EAAY,GAAO,EAElD,EAAS,EAAc,GAAK,GAAe,EAC3C,EAAS,EAAe,GAAK,GAAgB,EACnD,EAAgB,GAAU,GAM9B,IACE,MAAO,EACP,IAAK,KACF,GACD,EAEE,EAAe,CACnB,OACA,MAAO,EACP,SAAU,EAAK,QAAU,EACzB,gBACA,MAAO,CACT,EAGM,EAAU,EAAY,MAAQ,EAAQ,SAAS,aAAa,EAAM,CAAS,GAAK,GAEtF,OACE,GAQE,UARF,IAEM,EACJ,aAAY,QAAQ,EAAY,QAAQ,EAAK,MAAM,SAHrD,SAKE,GAEE,GAAiB,SAFnB,CAA2B,MAAO,EAAlC,SACG,EAAS,CAAY,EACtB,GANG,CAOL,EAEL,EACD,EACF",
19
+ "debugId": "3ADEFBB0F912DD0264756E2164756E21",
8
20
  "names": []
9
21
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "swipefeed",
3
- "version": "1.2.0",
3
+ "version": "1.2.1",
4
4
  "license": "MIT",
5
5
  "private": false,
6
6
  "type": "module",
@@ -23,7 +23,7 @@
23
23
  "module": "./dist/index.js",
24
24
  "exports": {
25
25
  ".": {
26
- "bun": "./src/index.ts",
26
+ "bun": "./dist/index.js",
27
27
  "types": "./dist/index.d.ts",
28
28
  "import": "./dist/index.js",
29
29
  "default": "./dist/index.js"
@@ -31,7 +31,7 @@
31
31
  },
32
32
  "types": "./dist/index.d.ts",
33
33
  "scripts": {
34
- "build": "bun build src/index.ts --target=browser --outdir=dist --sourcemap --production --external react --external react-dom --external @tanstack/react-virtual && tsc --declaration --emitDeclarationOnly --outDir dist --noEmit false",
34
+ "build": "rm -rf dist && bun build src/index.ts --target=browser --format=esm --outdir=dist --sourcemap --production --external react --external react-dom --external @tanstack/react-virtual && tsc -p tsconfig.build.json && bun scripts/verify-dist.ts",
35
35
  "link:peers": "bun scripts/link-peers.ts",
36
36
  "prepublishOnly": "bun run build",
37
37
  "docs:api": "typedoc",
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- import "@testing-library/jest-dom";
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1 +0,0 @@
1
- export {};
@@ -1,20 +0,0 @@
1
- import type { StoryObj } from "@storybook/react";
2
- import React from "react";
3
- import type { SwipeDeckProps } from "../types";
4
- type DemoItem = {
5
- id: string;
6
- title: string;
7
- };
8
- declare const meta: {
9
- title: string;
10
- component: React.ComponentType<SwipeDeckProps<DemoItem>>;
11
- parameters: {
12
- layout: string;
13
- };
14
- };
15
- export default meta;
16
- type Story = StoryObj<typeof meta>;
17
- export declare const VerticalNative: Story;
18
- export declare const VirtualizedFeed: Story;
19
- export declare const HorizontalStories: Story;
20
- export declare const Controlled: Story;