react-spring-carousel 3.0.0-beta002 → 3.0.0-beta005

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/esm/index.js CHANGED
@@ -1,2 +1,8 @@
1
- export{useSpringCarousel,useSpringCarouselContext}from"./useSpringCarousel.js";import"react/jsx-runtime";import"@react-spring/web";import"react";import"./useThumbsModule-ce69c348.js";import"screenfull";import"@use-gesture/react";
1
+ export { useSpringCarousel, useSpringCarouselContext } from './useSpringCarousel.js';
2
+ import 'react/jsx-runtime';
3
+ import './useThumbsModule-dc12dd34.js';
4
+ import 'react';
5
+ import 'screenfull';
6
+ import 'react-dom';
7
+ import '@use-gesture/react';
2
8
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;"}
@@ -1,2 +1,6 @@
1
- export{u as useEventsModule,b as useFullscreenModule,a as useThumbsModule}from"./useThumbsModule-ce69c348.js";import"react";import"screenfull";import"react/jsx-runtime";import"@react-spring/web";
1
+ export { a as useEventsModule, c as useFullscreenModule, b as useThumbsModule } from './useThumbsModule-dc12dd34.js';
2
+ import 'react';
3
+ import 'screenfull';
4
+ import 'react/jsx-runtime';
5
+ import 'react-dom';
2
6
  //# sourceMappingURL=index2.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index2.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
1
+ {"version":3,"file":"index2.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;"}
@@ -1,2 +1,615 @@
1
- import{jsx as e}from"react/jsx-runtime";import{useSpring as t,config as r}from"@react-spring/web";import{createContext as n,useRef as i,useCallback as c,useEffect as o,useLayoutEffect as s,useContext as l}from"react";import{u,a,b as d}from"./useThumbsModule-ce69c348.js";import{useDrag as f}from"@use-gesture/react";import"screenfull";function g({items:n,init:l=!0,withThumbs:g,thumbsSlideAxis:m="x",itemsPerSlide:v=1,slideType:h="fixed",gutter:x=0,withLoop:p=!1,startEndGutter:b=0,carouselSlideAxis:y="x",disableGestures:w=!1,draggingSlideTreshold:T,slideWhenThresholdIsReached:I=!1,freeScroll:j,enableFreeScrollDrag:O,initialStartingPosition:M,prepareThumbsData:A,initialActiveItem:S=0}){const L=i(0),R=i(null!=T?T:0),$=i("initial"),C=i("initial"),E=i(0),[F,N]=t((()=>({val:0,pause:!l,onChange({value:e}){j&&P.current?(ce(),"x"===y?P.current.scrollLeft=Math.abs(e.val):P.current.scrollTop=Math.abs(e.val)):z.current&&(z.current.style.transform="x"===y?`translate3d(${e.val}px, 0px,0px)`:`translate3d(0px,${e.val}px,0px)`)}}))),W=i(S),k=i(0===S),D=i(!1),P=i(null),z=i(null),B=c((()=>p?[...n.map((e=>Object.assign(Object.assign({},e),{id:`prev-repeated-item-${e.id}`}))),...n,...n.map((e=>Object.assign(Object.assign({},e),{id:`next-repeated-item-${e.id}`})))]:[...n]),[n,p])(),{emitEvent:q,useListenToCustomEvent:G}=u(),{thumbsFragment:H,handleScroll:X}=a({withThumbs:!!g,thumbsSlideAxis:m,prepareThumbsData:A,items:n}),{enterFullscreen:Y,exitFullscreen:J,getIsFullscreen:K}=d({mainCarouselWrapperRef:P,emitEvent:q,handleResize:()=>_()});function Q(){var e;const t=null===(e=P.current)||void 0===e?void 0:e.querySelector(".use-spring-carousel-item");if(!t)throw Error("No carousel items available!");return t.getBoundingClientRect()["x"===y?"width":"height"]+x}function U({from:e,to:t,nextActiveItem:i,immediate:c=!1,slideMode:o}){C.current=o,"number"==typeof i&&(j||(W.current=i),q({eventName:"onSlideStartChange",slideActionType:$.current,slideMode:C.current,nextItem:{startReached:k.current,endReached:D.current,index:j?-1:W.current,id:j?"":n[W.current].id}})),E.current=t,N.start({immediate:c,from:{val:e},to:{val:t},config:Object.assign(Object.assign({},r.default),{velocity:F.val.velocity}),onRest(e){!c&&e.finished&&q({eventName:"onSlideChange",slideActionType:$.current,slideMode:C.current,currentItem:{startReached:k.current,endReached:D.current,index:j?-1:W.current,id:j?"":n[W.current].id}})}}),g&&!c&&X(W.current)}function V(){var e;return p?Q()*n.length:Math.round(Number(null===(e=z.current)||void 0===e?void 0:e["x"===y?"scrollWidth":"scrollHeight"])-z.current.getBoundingClientRect()["x"===y?"width":"height"])}function Z(){var e;const t=null===(e=z.current)||void 0===e?void 0:e.querySelector(".use-spring-carousel-item");if(!t)throw Error("No carousel items available!");return t.getBoundingClientRect()["x"===y?"width":"height"]+x}function _(){const e="x"===y?"left":"top";function t(t){const r=z.current;r&&(p?(r.style.top="0px",r.style.left="0px",r.style[e]=`-${t-b}px`):(r.style.left="0px",r.style.top="0px"))}const r=Math.abs(ee());if(r<V()&&D.current&&(D.current=!1),r>V()){const e=-V();return D.current=!0,E.current=e,void N.start({immediate:!0,val:e})}if(t("center"===M?Z()*n.length-Q()*Math.round((v-1)/2):"end"===M?Z()*n.length-Q()*Math.round(v-1):Z()*n.length),!j&&"fixed"===h){const e=-Q()*W.current;E.current=e,N.start({immediate:!0,val:e})}}function ee(){return j&&P.current?P.current["x"===y?"scrollLeft":"scrollTop"]:F.val.get()}function te(e,t){if(j&&"next"===e){const e=E.current+Q();return e>V()?V():e}if(j&&"prev"===e){const e=E.current-Q();return e<0?0:e}return"next"===e?t?-t*Q():E.current-Q():t?-t*Q():E.current+Q()}function re(e="click",t){if(!l||k.current&&!p)return;$.current="prev",D.current=!1;const r=t||W.current-1;if(!p){const r=te("prev",t)+Q()/3>0;if(k.current)return;if(r)return k.current=!0,D.current=!1,void U({slideMode:e,from:ee(),to:0,nextActiveItem:0})}if(p&&k.current)return k.current=!1,D.current=!0,void U({slideMode:e,from:ee()-Q()*n.length,to:-Q()*n.length+Q(),nextActiveItem:n.length-1});0===r&&(k.current=!0),r!==n.length-1&&-1!==r||(D.current=!0),U({slideMode:e,from:ee(),to:te("prev",t),nextActiveItem:r})}function ne(e="click",t){if(!l||D.current&&!p)return;$.current="next",k.current=!1;const r=t||W.current+1;if(!p){const n=Math.abs(te("next",t))>V()-Q()/3;if(D.current)return;if(n)return k.current=!1,D.current=!0,void U({slideMode:e,from:ee(),to:-V(),nextActiveItem:r})}if(p&&D.current)return D.current=!1,k.current=!0,void U({slideMode:e,from:ee()+Q()*n.length,to:0,nextActiveItem:0});0===r&&(k.current=!0),r===n.length-1&&(D.current=!0),U({slideMode:e,from:ee(),to:te("next",t),nextActiveItem:r})}o((()=>{L.current=window.innerWidth}),[]),o((()=>{_()}),[M,v,p,b,x,j,h,l]),s((()=>{z.current&&_()}),[]),o((()=>{R.current=T||Math.floor(Q()/2/2)}),[T]),o((()=>{function e(){window.innerWidth!==L.current&&(L.current=window.innerWidth,_())}return window.addEventListener("resize",e),()=>{window.removeEventListener("resize",e)}}),[]);const ie=f((e=>{const t=e.dragging,n=e.offset["x"===y?0:1],i=e.movement["x"===y?0:1],c=e.direction["x"===y?0:1],o=i>R.current,s=i<-R.current;if(t)return $.current=c>0?"prev":"next",q(Object.assign(Object.assign({},e),{eventName:"onDrag",slideActionType:$.current})),j?"prev"===$.current&&n>0?(e.cancel(),void N.start({from:{val:ee()},to:{val:0},config:{velocity:e.velocity,friction:50,tension:1e3}})):void N.start({from:{val:ee()},to:{val:-n},config:{velocity:e.velocity,friction:50,tension:1e3}}):(N.start({val:n,config:{velocity:e.velocity,friction:50,tension:1e3}}),void(I&&s?(ne("drag"),e.cancel()):I&&o&&(re("drag"),e.cancel())));e.last&&!e.canceled&&j&&("prev"===$.current&&re("drag"),"next"===$.current&&ne("drag")),!e.last||e.canceled||j||(s?!p&&D.current?N.start({val:-V(),config:Object.assign(Object.assign({},r.default),{velocity:e.velocity})}):ne("drag"):o?!p&&k.current?N.start({val:0,config:Object.assign(Object.assign({},r.default),{velocity:e.velocity})}):re("drag"):N.start({val:E.current,config:Object.assign(Object.assign({},r.default),{velocity:e.velocity})}))}),{enabled:l&&!w&&!j||!!j&&!!O,axis:y,from:()=>j&&P.current?[-P.current.scrollLeft,-P.current.scrollTop]:[F.val.get(),F.val.get()]});function ce(){P.current&&(E.current=P.current["x"===y?"scrollLeft":"scrollTop"],0===P.current["x"===y?"scrollLeft":"scrollTop"]&&(k.current=!0,D.current=!1),P.current["x"===y?"scrollLeft":"scrollTop"]>0&&P.current["x"===y?"scrollLeft":"scrollTop"]<V()&&(k.current=!1,D.current=!1),P.current["x"===y?"scrollLeft":"scrollTop"]===V()&&(k.current=!1,D.current=!0))}function oe(e){return n.findIndex((t=>t.id===e))}function se(e,t){let r=0;if(r="string"==typeof e?n.findIndex((t=>t.id===e)):e,r<0||r>=n.length)throw new Error(t);return r}return{useListenToCustomEvent:G,carouselFragment:e("div",Object.assign({ref:P},j?{onWheel(){F.val.stop(),ce()}}:{},{style:Object.assign({display:"flex",position:"relative",width:"100%",height:"100%"},j?"x"===y?{overflowX:"auto"}:{overflowY:"auto"}:{})},{children:e("div",Object.assign({ref:z},ie(),{style:Object.assign({position:"relative",display:"flex",flexDirection:"x"===y?"row":"column",touchAction:"none"},function(){const e=`calc(100% - ${2*b}px)`;return{width:"x"===y?e:"100%",height:"y"===y?e:"100%"}}())},{children:B.map(((t,r)=>e("div",Object.assign({className:"use-spring-carousel-item","data-testid":"use-spring-carousel-item-wrapper",style:Object.assign({display:"flex",position:"relative",flex:"1"},"fixed"!==h||j?Object.assign({marginRight:`${x}px`}):{marginRight:`${x}px`,flex:`1 0 calc(100% / ${v} - ${x*(v-1)/v}px)`})},{children:t.renderItem}),`${t.id}-${r}`)))}))})),enterFullscreen:Y,exitFullscreen:J,getIsFullscreen:K,thumbsFragment:H,slideToItem:function(e){if(!l)return;k.current=!1,D.current=!1;const t=se(e,"The item you want to slide to doesn't exist; please check che item id or the index you're passing to.");if(t===W.current)return;const r=oe(n[W.current].id),i=oe(n[t].id);i>r?ne("click",i):re("click",i)},getIsNextItem:function(e){const t=oe(e),r=W.current;return p&&r===n.length-1?0===t:t===r+1},getIsPrevItem:function(e){const t=oe(e),r=W.current;return p&&0===r?t===n.length-1:t===r-1},slideToPrevItem:()=>re(),slideToNextItem:()=>ne(),getIsActiveItem:e=>se(e,"The item you want to check doesn't exist")===W.current}}const m=n(void 0);function v(){const e=l(m);if(!e)throw new Error("useSpringCarouselContext must be used within the carousel.");return e}export{g as useSpringCarousel,v as useSpringCarouselContext};
1
+ import { jsx } from 'react/jsx-runtime';
2
+ import { u as useSpring, a as useEventsModule, b as useThumbsModule, c as useFullscreenModule, d as config } from './useThumbsModule-dc12dd34.js';
3
+ import { createContext, useRef, useCallback, useEffect, useLayoutEffect, useContext } from 'react';
4
+ import { useDrag } from '@use-gesture/react';
5
+ import 'screenfull';
6
+ import 'react-dom';
7
+
8
+ function useSpringCarousel({ items, init = true, withThumbs, thumbsSlideAxis = 'x', itemsPerSlide = 1, slideType = 'fixed', gutter = 0, withLoop = false, startEndGutter = 0, carouselSlideAxis = 'x', disableGestures = false, draggingSlideTreshold: _draggingSlideTreshold, slideWhenThresholdIsReached = false, freeScroll, enableFreeScrollDrag, initialStartingPosition, prepareThumbsData, initialActiveItem = 0, }) {
9
+ const prevWindowWidth = useRef(0);
10
+ const draggingSlideTreshold = useRef(_draggingSlideTreshold !== null && _draggingSlideTreshold !== void 0 ? _draggingSlideTreshold : 0);
11
+ const slideActionType = useRef('initial');
12
+ const slideModeType = useRef('initial');
13
+ const prevSlidedValue = useRef(0);
14
+ const [spring, setSpring] = useSpring(() => ({
15
+ val: 0,
16
+ pause: !init,
17
+ onChange({ value }) {
18
+ if (freeScroll && mainCarouselWrapperRef.current) {
19
+ setStartEndItemReachedOnFreeScroll();
20
+ if (carouselSlideAxis === 'x') {
21
+ mainCarouselWrapperRef.current.scrollLeft = Math.abs(value.val);
22
+ }
23
+ else {
24
+ mainCarouselWrapperRef.current.scrollTop = Math.abs(value.val);
25
+ }
26
+ }
27
+ else if (carouselTrackWrapperRef.current) {
28
+ if (carouselSlideAxis === 'x') {
29
+ carouselTrackWrapperRef.current.style.transform = `translate3d(${value.val}px, 0px,0px)`;
30
+ }
31
+ else {
32
+ carouselTrackWrapperRef.current.style.transform = `translate3d(0px,${value.val}px,0px)`;
33
+ }
34
+ }
35
+ },
36
+ }));
37
+ const activeItem = useRef(initialActiveItem);
38
+ const firstItemReached = useRef(initialActiveItem === 0);
39
+ const lastItemReached = useRef(false);
40
+ const mainCarouselWrapperRef = useRef(null);
41
+ const carouselTrackWrapperRef = useRef(null);
42
+ const getItems = useCallback(() => {
43
+ if (withLoop) {
44
+ return [
45
+ ...items.map(i => (Object.assign(Object.assign({}, i), { id: `prev-repeated-item-${i.id}` }))),
46
+ ...items,
47
+ ...items.map(i => (Object.assign(Object.assign({}, i), { id: `next-repeated-item-${i.id}` }))),
48
+ ];
49
+ }
50
+ return [...items];
51
+ }, [items, withLoop]);
52
+ const internalItems = getItems();
53
+ const { emitEvent, useListenToCustomEvent } = useEventsModule();
54
+ const { thumbsFragment, handleScroll } = useThumbsModule({
55
+ withThumbs: !!withThumbs,
56
+ thumbsSlideAxis,
57
+ prepareThumbsData,
58
+ items: items,
59
+ });
60
+ const { enterFullscreen, exitFullscreen, getIsFullscreen } = useFullscreenModule({
61
+ mainCarouselWrapperRef,
62
+ emitEvent,
63
+ handleResize: () => adjustCarouselWrapperPosition(),
64
+ });
65
+ function getItemStyles() {
66
+ if (slideType === 'fixed' && !freeScroll) {
67
+ return {
68
+ marginRight: `${gutter}px`,
69
+ flex: `1 0 calc(100% / ${itemsPerSlide} - ${(gutter * (itemsPerSlide - 1)) / itemsPerSlide}px)`,
70
+ };
71
+ }
72
+ return Object.assign({ marginRight: `${gutter}px` });
73
+ }
74
+ function getSlideValue() {
75
+ var _a;
76
+ const carouselItem = (_a = mainCarouselWrapperRef.current) === null || _a === void 0 ? void 0 : _a.querySelector('.use-spring-carousel-item');
77
+ if (!carouselItem) {
78
+ throw Error('No carousel items available!');
79
+ }
80
+ return (carouselItem.getBoundingClientRect()[carouselSlideAxis === 'x' ? 'width' : 'height'] + gutter);
81
+ }
82
+ function slideToItem({ from, to, nextActiveItem, immediate = false, slideMode, }) {
83
+ slideModeType.current = slideMode;
84
+ if (typeof nextActiveItem === 'number') {
85
+ if (!freeScroll) {
86
+ activeItem.current = nextActiveItem;
87
+ }
88
+ emitEvent({
89
+ eventName: 'onSlideStartChange',
90
+ slideActionType: slideActionType.current,
91
+ slideMode: slideModeType.current,
92
+ nextItem: {
93
+ startReached: firstItemReached.current,
94
+ endReached: lastItemReached.current,
95
+ index: freeScroll ? -1 : activeItem.current,
96
+ id: freeScroll ? '' : items[activeItem.current].id,
97
+ },
98
+ });
99
+ }
100
+ prevSlidedValue.current = to;
101
+ setSpring.start({
102
+ immediate,
103
+ from: {
104
+ val: from,
105
+ },
106
+ to: {
107
+ val: to,
108
+ },
109
+ config: Object.assign(Object.assign({}, config.default), { velocity: spring.val.velocity }),
110
+ onRest(value) {
111
+ if (!immediate && value.finished) {
112
+ emitEvent({
113
+ eventName: 'onSlideChange',
114
+ slideActionType: slideActionType.current,
115
+ slideMode: slideModeType.current,
116
+ currentItem: {
117
+ startReached: firstItemReached.current,
118
+ endReached: lastItemReached.current,
119
+ index: freeScroll ? -1 : activeItem.current,
120
+ id: freeScroll ? '' : items[activeItem.current].id,
121
+ },
122
+ });
123
+ }
124
+ },
125
+ });
126
+ if (withThumbs && !immediate) {
127
+ handleScroll(activeItem.current);
128
+ }
129
+ }
130
+ function getTotalScrollValue() {
131
+ var _a;
132
+ if (withLoop) {
133
+ return getSlideValue() * items.length;
134
+ }
135
+ return Math.round(Number((_a = carouselTrackWrapperRef.current) === null || _a === void 0 ? void 0 : _a[carouselSlideAxis === 'x' ? 'scrollWidth' : 'scrollHeight']) -
136
+ carouselTrackWrapperRef.current.getBoundingClientRect()[carouselSlideAxis === 'x' ? 'width' : 'height']);
137
+ }
138
+ function getAnimatedWrapperStyles() {
139
+ const percentValue = `calc(100% - ${startEndGutter * 2}px)`;
140
+ return {
141
+ width: carouselSlideAxis === 'x' ? percentValue : '100%',
142
+ height: carouselSlideAxis === 'y' ? percentValue : '100%',
143
+ };
144
+ }
145
+ function getCarouselItemWidth() {
146
+ var _a;
147
+ const carouselItem = (_a = carouselTrackWrapperRef.current) === null || _a === void 0 ? void 0 : _a.querySelector('.use-spring-carousel-item');
148
+ if (!carouselItem) {
149
+ throw Error('No carousel items available!');
150
+ }
151
+ return (carouselItem.getBoundingClientRect()[carouselSlideAxis === 'x' ? 'width' : 'height'] + gutter);
152
+ }
153
+ function adjustCarouselWrapperPosition() {
154
+ const positionProperty = carouselSlideAxis === 'x' ? 'left' : 'top';
155
+ function setPosition(v) {
156
+ const ref = carouselTrackWrapperRef.current;
157
+ if (!ref)
158
+ return;
159
+ if (withLoop) {
160
+ ref.style.top = '0px';
161
+ ref.style.left = '0px';
162
+ ref.style[positionProperty] = `-${v - startEndGutter}px`;
163
+ }
164
+ else {
165
+ ref.style.left = '0px';
166
+ ref.style.top = '0px';
167
+ }
168
+ }
169
+ const currentFromValue = Math.abs(getFromValue());
170
+ if (currentFromValue < getTotalScrollValue() && lastItemReached.current) {
171
+ lastItemReached.current = false;
172
+ }
173
+ if (currentFromValue > getTotalScrollValue()) {
174
+ const val = -getTotalScrollValue();
175
+ lastItemReached.current = true;
176
+ prevSlidedValue.current = val;
177
+ setSpring.start({
178
+ immediate: true,
179
+ val,
180
+ });
181
+ return;
182
+ }
183
+ if (initialStartingPosition === 'center') {
184
+ setPosition(getCarouselItemWidth() * items.length -
185
+ getSlideValue() * Math.round((itemsPerSlide - 1) / 2));
186
+ }
187
+ else if (initialStartingPosition === 'end') {
188
+ setPosition(getCarouselItemWidth() * items.length -
189
+ getSlideValue() * Math.round(itemsPerSlide - 1));
190
+ }
191
+ else {
192
+ setPosition(getCarouselItemWidth() * items.length);
193
+ }
194
+ if (!freeScroll && slideType === 'fixed') {
195
+ const val = -(getSlideValue() * activeItem.current);
196
+ prevSlidedValue.current = val;
197
+ setSpring.start({
198
+ immediate: true,
199
+ val,
200
+ });
201
+ }
202
+ }
203
+ function getFromValue() {
204
+ if (freeScroll && mainCarouselWrapperRef.current) {
205
+ return mainCarouselWrapperRef.current[carouselSlideAxis === 'x' ? 'scrollLeft' : 'scrollTop'];
206
+ }
207
+ return spring.val.get();
208
+ }
209
+ function getToValue(type, index) {
210
+ if (freeScroll && type === 'next') {
211
+ const next = prevSlidedValue.current + getSlideValue();
212
+ if (next > getTotalScrollValue()) {
213
+ return getTotalScrollValue();
214
+ }
215
+ return next;
216
+ }
217
+ if (freeScroll && type === 'prev') {
218
+ const next = prevSlidedValue.current - getSlideValue();
219
+ if (next < 0) {
220
+ return 0;
221
+ }
222
+ return next;
223
+ }
224
+ if (type === 'next') {
225
+ if (index) {
226
+ return -(index * getSlideValue());
227
+ }
228
+ return prevSlidedValue.current - getSlideValue();
229
+ }
230
+ if (index) {
231
+ return -(index * getSlideValue());
232
+ }
233
+ return prevSlidedValue.current + getSlideValue();
234
+ }
235
+ function slideToPrevItem(type = 'click', index) {
236
+ if (!init || (firstItemReached.current && !withLoop))
237
+ return;
238
+ slideActionType.current = 'prev';
239
+ lastItemReached.current = false;
240
+ const nextItem = index || activeItem.current - 1;
241
+ if (!withLoop) {
242
+ const nextItemWillExceed = getToValue('prev', index) + getSlideValue() / 3 > 0;
243
+ if (firstItemReached.current)
244
+ return;
245
+ if (nextItemWillExceed) {
246
+ firstItemReached.current = true;
247
+ lastItemReached.current = false;
248
+ slideToItem({
249
+ slideMode: type,
250
+ from: getFromValue(),
251
+ to: 0,
252
+ nextActiveItem: 0,
253
+ });
254
+ return;
255
+ }
256
+ }
257
+ if (withLoop && firstItemReached.current) {
258
+ firstItemReached.current = false;
259
+ lastItemReached.current = true;
260
+ slideToItem({
261
+ slideMode: type,
262
+ from: getFromValue() - getSlideValue() * items.length,
263
+ to: -(getSlideValue() * items.length) + getSlideValue(),
264
+ nextActiveItem: items.length - 1,
265
+ });
266
+ return;
267
+ }
268
+ if (nextItem === 0) {
269
+ firstItemReached.current = true;
270
+ }
271
+ if (nextItem === items.length - 1 || nextItem === -1) {
272
+ lastItemReached.current = true;
273
+ }
274
+ slideToItem({
275
+ slideMode: type,
276
+ from: getFromValue(),
277
+ to: getToValue('prev', index),
278
+ nextActiveItem: nextItem,
279
+ });
280
+ }
281
+ function slideToNextItem(type = 'click', index) {
282
+ if (!init || (lastItemReached.current && !withLoop))
283
+ return;
284
+ slideActionType.current = 'next';
285
+ firstItemReached.current = false;
286
+ const nextItem = index || activeItem.current + 1;
287
+ if (!withLoop) {
288
+ const nextItemWillExceed = Math.abs(getToValue('next', index)) > getTotalScrollValue() - getSlideValue() / 3;
289
+ if (lastItemReached.current)
290
+ return;
291
+ if (nextItemWillExceed) {
292
+ firstItemReached.current = false;
293
+ lastItemReached.current = true;
294
+ slideToItem({
295
+ slideMode: type,
296
+ from: getFromValue(),
297
+ to: -getTotalScrollValue(),
298
+ nextActiveItem: nextItem,
299
+ });
300
+ return;
301
+ }
302
+ }
303
+ if (withLoop && lastItemReached.current) {
304
+ lastItemReached.current = false;
305
+ firstItemReached.current = true;
306
+ slideToItem({
307
+ slideMode: type,
308
+ from: getFromValue() + getSlideValue() * items.length,
309
+ to: 0,
310
+ nextActiveItem: 0,
311
+ });
312
+ return;
313
+ }
314
+ if (nextItem === 0) {
315
+ firstItemReached.current = true;
316
+ }
317
+ if (nextItem === items.length - 1) {
318
+ lastItemReached.current = true;
319
+ }
320
+ slideToItem({
321
+ slideMode: type,
322
+ from: getFromValue(),
323
+ to: getToValue('next', index),
324
+ nextActiveItem: nextItem,
325
+ });
326
+ }
327
+ useEffect(() => {
328
+ prevWindowWidth.current = window.innerWidth;
329
+ }, []);
330
+ useEffect(() => {
331
+ adjustCarouselWrapperPosition();
332
+ }, [
333
+ initialStartingPosition,
334
+ itemsPerSlide,
335
+ withLoop,
336
+ startEndGutter,
337
+ gutter,
338
+ freeScroll,
339
+ slideType,
340
+ init,
341
+ ]);
342
+ useLayoutEffect(() => {
343
+ /**
344
+ * Set initial track position
345
+ */
346
+ if (carouselTrackWrapperRef.current) {
347
+ adjustCarouselWrapperPosition();
348
+ }
349
+ }, []);
350
+ useEffect(() => {
351
+ if (_draggingSlideTreshold) {
352
+ draggingSlideTreshold.current = _draggingSlideTreshold;
353
+ }
354
+ else {
355
+ draggingSlideTreshold.current = Math.floor(getSlideValue() / 2 / 2);
356
+ }
357
+ }, [_draggingSlideTreshold]);
358
+ useEffect(() => {
359
+ function handleResize() {
360
+ if (window.innerWidth === prevWindowWidth.current)
361
+ return;
362
+ prevWindowWidth.current = window.innerWidth;
363
+ adjustCarouselWrapperPosition();
364
+ }
365
+ window.addEventListener('resize', handleResize);
366
+ return () => {
367
+ window.removeEventListener('resize', handleResize);
368
+ };
369
+ }, []);
370
+ const bindDrag = useDrag(state => {
371
+ const isDragging = state.dragging;
372
+ const movement = state.offset[carouselSlideAxis === 'x' ? 0 : 1];
373
+ const currentMovement = state.movement[carouselSlideAxis === 'x' ? 0 : 1];
374
+ const direction = state.direction[carouselSlideAxis === 'x' ? 0 : 1];
375
+ const prevItemTreshold = currentMovement > draggingSlideTreshold.current;
376
+ const nextItemTreshold = currentMovement < -draggingSlideTreshold.current;
377
+ if (isDragging) {
378
+ if (direction > 0) {
379
+ slideActionType.current = 'prev';
380
+ }
381
+ else {
382
+ slideActionType.current = 'next';
383
+ }
384
+ emitEvent(Object.assign(Object.assign({}, state), { eventName: 'onDrag', slideActionType: slideActionType.current }));
385
+ if (freeScroll) {
386
+ if (slideActionType.current === 'prev' && movement > 0) {
387
+ state.cancel();
388
+ setSpring.start({
389
+ from: {
390
+ val: getFromValue(),
391
+ },
392
+ to: {
393
+ val: 0,
394
+ },
395
+ config: {
396
+ velocity: state.velocity,
397
+ friction: 50,
398
+ tension: 1000,
399
+ },
400
+ });
401
+ return;
402
+ }
403
+ setSpring.start({
404
+ from: {
405
+ val: getFromValue(),
406
+ },
407
+ to: {
408
+ val: -movement,
409
+ },
410
+ config: {
411
+ velocity: state.velocity,
412
+ friction: 50,
413
+ tension: 1000,
414
+ },
415
+ });
416
+ return;
417
+ }
418
+ setSpring.start({
419
+ val: movement,
420
+ config: {
421
+ velocity: state.velocity,
422
+ friction: 50,
423
+ tension: 1000,
424
+ },
425
+ });
426
+ if (slideWhenThresholdIsReached && nextItemTreshold) {
427
+ slideToNextItem('drag');
428
+ state.cancel();
429
+ }
430
+ else if (slideWhenThresholdIsReached && prevItemTreshold) {
431
+ slideToPrevItem('drag');
432
+ state.cancel();
433
+ }
434
+ return;
435
+ }
436
+ if (state.last && !state.canceled && freeScroll) {
437
+ if (slideActionType.current === 'prev') {
438
+ slideToPrevItem('drag');
439
+ }
440
+ if (slideActionType.current === 'next') {
441
+ slideToNextItem('drag');
442
+ }
443
+ }
444
+ if (state.last && !state.canceled && !freeScroll) {
445
+ if (nextItemTreshold) {
446
+ if (!withLoop && lastItemReached.current) {
447
+ setSpring.start({
448
+ val: -getTotalScrollValue(),
449
+ config: Object.assign(Object.assign({}, config.default), { velocity: state.velocity }),
450
+ });
451
+ }
452
+ else {
453
+ slideToNextItem('drag');
454
+ }
455
+ }
456
+ else if (prevItemTreshold) {
457
+ if (!withLoop && firstItemReached.current) {
458
+ setSpring.start({
459
+ val: 0,
460
+ config: Object.assign(Object.assign({}, config.default), { velocity: state.velocity }),
461
+ });
462
+ }
463
+ else {
464
+ slideToPrevItem('drag');
465
+ }
466
+ }
467
+ else {
468
+ setSpring.start({
469
+ val: prevSlidedValue.current,
470
+ config: Object.assign(Object.assign({}, config.default), { velocity: state.velocity }),
471
+ });
472
+ }
473
+ }
474
+ }, {
475
+ enabled: (init && !disableGestures && !freeScroll) ||
476
+ (!!freeScroll && !!enableFreeScrollDrag),
477
+ axis: carouselSlideAxis,
478
+ from: () => {
479
+ if (freeScroll && mainCarouselWrapperRef.current) {
480
+ return [
481
+ -mainCarouselWrapperRef.current.scrollLeft,
482
+ -mainCarouselWrapperRef.current.scrollTop,
483
+ ];
484
+ }
485
+ if (carouselSlideAxis === 'x') {
486
+ return [spring.val.get(), spring.val.get()];
487
+ }
488
+ return [spring.val.get(), spring.val.get()];
489
+ },
490
+ });
491
+ function getWrapperOverflowStyles() {
492
+ if (freeScroll) {
493
+ if (carouselSlideAxis === 'x') {
494
+ return {
495
+ overflowX: 'auto',
496
+ };
497
+ }
498
+ return {
499
+ overflowY: 'auto',
500
+ };
501
+ }
502
+ return {};
503
+ }
504
+ function setStartEndItemReachedOnFreeScroll() {
505
+ if (mainCarouselWrapperRef.current) {
506
+ prevSlidedValue.current =
507
+ mainCarouselWrapperRef.current[carouselSlideAxis === 'x' ? 'scrollLeft' : 'scrollTop'];
508
+ if (mainCarouselWrapperRef.current[carouselSlideAxis === 'x' ? 'scrollLeft' : 'scrollTop'] === 0) {
509
+ firstItemReached.current = true;
510
+ lastItemReached.current = false;
511
+ }
512
+ if (mainCarouselWrapperRef.current[carouselSlideAxis === 'x' ? 'scrollLeft' : 'scrollTop'] > 0 &&
513
+ mainCarouselWrapperRef.current[carouselSlideAxis === 'x' ? 'scrollLeft' : 'scrollTop'] < getTotalScrollValue()) {
514
+ firstItemReached.current = false;
515
+ lastItemReached.current = false;
516
+ }
517
+ if (mainCarouselWrapperRef.current[carouselSlideAxis === 'x' ? 'scrollLeft' : 'scrollTop'] === getTotalScrollValue()) {
518
+ firstItemReached.current = false;
519
+ lastItemReached.current = true;
520
+ }
521
+ }
522
+ }
523
+ function getScrollHandlers() {
524
+ if (freeScroll) {
525
+ return {
526
+ onWheel() {
527
+ spring.val.stop();
528
+ setStartEndItemReachedOnFreeScroll();
529
+ },
530
+ };
531
+ }
532
+ return {};
533
+ }
534
+ function findItemIndex(id) {
535
+ return items.findIndex(item => item.id === id);
536
+ }
537
+ function findItemIndexById(id, error) {
538
+ let itemIndex = 0;
539
+ if (typeof id === 'string') {
540
+ itemIndex = items.findIndex(_item => _item.id === id);
541
+ }
542
+ else {
543
+ itemIndex = id;
544
+ }
545
+ if (itemIndex < 0 || itemIndex >= items.length) {
546
+ throw new Error(error);
547
+ }
548
+ return itemIndex;
549
+ }
550
+ function internalSlideToItem(id) {
551
+ if (!init)
552
+ return;
553
+ firstItemReached.current = false;
554
+ lastItemReached.current = false;
555
+ const itemIndex = findItemIndexById(id, "The item you want to slide to doesn't exist; please check che item id or the index you're passing to.");
556
+ if (itemIndex === activeItem.current) {
557
+ return;
558
+ }
559
+ const currentItem = findItemIndex(items[activeItem.current].id);
560
+ const newActiveItem = findItemIndex(items[itemIndex].id);
561
+ if (newActiveItem > currentItem) {
562
+ slideToNextItem('click', newActiveItem);
563
+ }
564
+ else {
565
+ slideToPrevItem('click', newActiveItem);
566
+ }
567
+ }
568
+ function getIsNextItem(id) {
569
+ const itemIndex = findItemIndex(id);
570
+ const _activeItem = activeItem.current;
571
+ if (withLoop && _activeItem === items.length - 1) {
572
+ return itemIndex === 0;
573
+ }
574
+ return itemIndex === _activeItem + 1;
575
+ }
576
+ function getIsPrevItem(id) {
577
+ const itemIndex = findItemIndex(id);
578
+ const _activeItem = activeItem.current;
579
+ if (withLoop && _activeItem === 0) {
580
+ return itemIndex === items.length - 1;
581
+ }
582
+ return itemIndex === _activeItem - 1;
583
+ }
584
+ const carouselFragment = (jsx("div", Object.assign({ ref: mainCarouselWrapperRef }, getScrollHandlers(), { style: Object.assign({ display: 'flex', position: 'relative', width: '100%', height: '100%' }, getWrapperOverflowStyles()) }, { children: jsx("div", Object.assign({ ref: carouselTrackWrapperRef }, bindDrag(), { style: Object.assign({ position: 'relative', display: 'flex', flexDirection: carouselSlideAxis === 'x' ? 'row' : 'column', touchAction: 'none' }, getAnimatedWrapperStyles()) }, { children: internalItems.map((item, index) => {
585
+ return (jsx("div", Object.assign({ className: "use-spring-carousel-item", "data-testid": "use-spring-carousel-item-wrapper", style: Object.assign({ display: 'flex', position: 'relative', flex: '1' }, getItemStyles()) }, { children: item.renderItem }), `${item.id}-${index}`));
586
+ }) })) })));
587
+ return {
588
+ useListenToCustomEvent,
589
+ carouselFragment,
590
+ enterFullscreen,
591
+ exitFullscreen,
592
+ getIsFullscreen,
593
+ thumbsFragment,
594
+ slideToItem: internalSlideToItem,
595
+ getIsNextItem,
596
+ getIsPrevItem,
597
+ slideToPrevItem: () => slideToPrevItem(),
598
+ slideToNextItem: () => slideToNextItem(),
599
+ getIsActiveItem: (id) => {
600
+ return (findItemIndexById(id, "The item you want to check doesn't exist") ===
601
+ activeItem.current);
602
+ },
603
+ };
604
+ }
605
+ const Context = createContext(undefined);
606
+ function useSpringCarouselContext() {
607
+ const context = useContext(Context);
608
+ if (!context) {
609
+ throw new Error('useSpringCarouselContext must be used within the carousel.');
610
+ }
611
+ return context;
612
+ }
613
+
614
+ export { useSpringCarousel, useSpringCarouselContext };
2
615
  //# sourceMappingURL=useSpringCarousel.js.map