react-spring-carousel 3.0.0-beta002 → 3.0.0-beta003

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.
@@ -1,2 +1,616 @@
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 { useSpring, config } from '@react-spring/web';
3
+ import { createContext, useRef, useCallback, useEffect, useLayoutEffect, useContext } from 'react';
4
+ import { u as useEventsModule, a as useThumbsModule, b as useFullscreenModule } from './useThumbsModule-12c81348.js';
5
+ import { useDrag } from '@use-gesture/react';
6
+ import 'screenfull';
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)) >
289
+ getTotalScrollValue() - getSlideValue() / 3;
290
+ if (lastItemReached.current)
291
+ return;
292
+ if (nextItemWillExceed) {
293
+ firstItemReached.current = false;
294
+ lastItemReached.current = true;
295
+ slideToItem({
296
+ slideMode: type,
297
+ from: getFromValue(),
298
+ to: -getTotalScrollValue(),
299
+ nextActiveItem: nextItem,
300
+ });
301
+ return;
302
+ }
303
+ }
304
+ if (withLoop && lastItemReached.current) {
305
+ lastItemReached.current = false;
306
+ firstItemReached.current = true;
307
+ slideToItem({
308
+ slideMode: type,
309
+ from: getFromValue() + getSlideValue() * items.length,
310
+ to: 0,
311
+ nextActiveItem: 0,
312
+ });
313
+ return;
314
+ }
315
+ if (nextItem === 0) {
316
+ firstItemReached.current = true;
317
+ }
318
+ if (nextItem === items.length - 1) {
319
+ lastItemReached.current = true;
320
+ }
321
+ slideToItem({
322
+ slideMode: type,
323
+ from: getFromValue(),
324
+ to: getToValue("next", index),
325
+ nextActiveItem: nextItem,
326
+ });
327
+ }
328
+ useEffect(() => {
329
+ prevWindowWidth.current = window.innerWidth;
330
+ }, []);
331
+ useEffect(() => {
332
+ adjustCarouselWrapperPosition();
333
+ }, [
334
+ initialStartingPosition,
335
+ itemsPerSlide,
336
+ withLoop,
337
+ startEndGutter,
338
+ gutter,
339
+ freeScroll,
340
+ slideType,
341
+ init,
342
+ ]);
343
+ useLayoutEffect(() => {
344
+ /**
345
+ * Set initial track position
346
+ */
347
+ if (carouselTrackWrapperRef.current) {
348
+ adjustCarouselWrapperPosition();
349
+ }
350
+ }, []);
351
+ useEffect(() => {
352
+ if (_draggingSlideTreshold) {
353
+ draggingSlideTreshold.current = _draggingSlideTreshold;
354
+ }
355
+ else {
356
+ draggingSlideTreshold.current = Math.floor(getSlideValue() / 2 / 2);
357
+ }
358
+ }, [_draggingSlideTreshold]);
359
+ useEffect(() => {
360
+ function handleResize() {
361
+ if (window.innerWidth === prevWindowWidth.current)
362
+ return;
363
+ prevWindowWidth.current = window.innerWidth;
364
+ adjustCarouselWrapperPosition();
365
+ }
366
+ window.addEventListener("resize", handleResize);
367
+ return () => {
368
+ window.removeEventListener("resize", handleResize);
369
+ };
370
+ }, []);
371
+ const bindDrag = useDrag((state) => {
372
+ const isDragging = state.dragging;
373
+ const movement = state.offset[carouselSlideAxis === "x" ? 0 : 1];
374
+ const currentMovement = state.movement[carouselSlideAxis === "x" ? 0 : 1];
375
+ const direction = state.direction[carouselSlideAxis === "x" ? 0 : 1];
376
+ const prevItemTreshold = currentMovement > draggingSlideTreshold.current;
377
+ const nextItemTreshold = currentMovement < -draggingSlideTreshold.current;
378
+ if (isDragging) {
379
+ if (direction > 0) {
380
+ slideActionType.current = "prev";
381
+ }
382
+ else {
383
+ slideActionType.current = "next";
384
+ }
385
+ emitEvent(Object.assign(Object.assign({}, state), { eventName: "onDrag", slideActionType: slideActionType.current }));
386
+ if (freeScroll) {
387
+ if (slideActionType.current === "prev" && movement > 0) {
388
+ state.cancel();
389
+ setSpring.start({
390
+ from: {
391
+ val: getFromValue(),
392
+ },
393
+ to: {
394
+ val: 0,
395
+ },
396
+ config: {
397
+ velocity: state.velocity,
398
+ friction: 50,
399
+ tension: 1000,
400
+ },
401
+ });
402
+ return;
403
+ }
404
+ setSpring.start({
405
+ from: {
406
+ val: getFromValue(),
407
+ },
408
+ to: {
409
+ val: -movement,
410
+ },
411
+ config: {
412
+ velocity: state.velocity,
413
+ friction: 50,
414
+ tension: 1000,
415
+ },
416
+ });
417
+ return;
418
+ }
419
+ setSpring.start({
420
+ val: movement,
421
+ config: {
422
+ velocity: state.velocity,
423
+ friction: 50,
424
+ tension: 1000,
425
+ },
426
+ });
427
+ if (slideWhenThresholdIsReached && nextItemTreshold) {
428
+ slideToNextItem("drag");
429
+ state.cancel();
430
+ }
431
+ else if (slideWhenThresholdIsReached && prevItemTreshold) {
432
+ slideToPrevItem("drag");
433
+ state.cancel();
434
+ }
435
+ return;
436
+ }
437
+ if (state.last && !state.canceled && freeScroll) {
438
+ if (slideActionType.current === "prev") {
439
+ slideToPrevItem("drag");
440
+ }
441
+ if (slideActionType.current === "next") {
442
+ slideToNextItem("drag");
443
+ }
444
+ }
445
+ if (state.last && !state.canceled && !freeScroll) {
446
+ if (nextItemTreshold) {
447
+ if (!withLoop && lastItemReached.current) {
448
+ setSpring.start({
449
+ val: -getTotalScrollValue(),
450
+ config: Object.assign(Object.assign({}, config.default), { velocity: state.velocity }),
451
+ });
452
+ }
453
+ else {
454
+ slideToNextItem("drag");
455
+ }
456
+ }
457
+ else if (prevItemTreshold) {
458
+ if (!withLoop && firstItemReached.current) {
459
+ setSpring.start({
460
+ val: 0,
461
+ config: Object.assign(Object.assign({}, config.default), { velocity: state.velocity }),
462
+ });
463
+ }
464
+ else {
465
+ slideToPrevItem("drag");
466
+ }
467
+ }
468
+ else {
469
+ setSpring.start({
470
+ val: prevSlidedValue.current,
471
+ config: Object.assign(Object.assign({}, config.default), { velocity: state.velocity }),
472
+ });
473
+ }
474
+ }
475
+ }, {
476
+ enabled: (init && !disableGestures && !freeScroll) ||
477
+ (!!freeScroll && !!enableFreeScrollDrag),
478
+ axis: carouselSlideAxis,
479
+ from: () => {
480
+ if (freeScroll && mainCarouselWrapperRef.current) {
481
+ return [
482
+ -mainCarouselWrapperRef.current.scrollLeft,
483
+ -mainCarouselWrapperRef.current.scrollTop,
484
+ ];
485
+ }
486
+ if (carouselSlideAxis === "x") {
487
+ return [spring.val.get(), spring.val.get()];
488
+ }
489
+ return [spring.val.get(), spring.val.get()];
490
+ },
491
+ });
492
+ function getWrapperOverflowStyles() {
493
+ if (freeScroll) {
494
+ if (carouselSlideAxis === "x") {
495
+ return {
496
+ overflowX: "auto",
497
+ };
498
+ }
499
+ return {
500
+ overflowY: "auto",
501
+ };
502
+ }
503
+ return {};
504
+ }
505
+ function setStartEndItemReachedOnFreeScroll() {
506
+ if (mainCarouselWrapperRef.current) {
507
+ prevSlidedValue.current =
508
+ mainCarouselWrapperRef.current[carouselSlideAxis === "x" ? "scrollLeft" : "scrollTop"];
509
+ if (mainCarouselWrapperRef.current[carouselSlideAxis === "x" ? "scrollLeft" : "scrollTop"] === 0) {
510
+ firstItemReached.current = true;
511
+ lastItemReached.current = false;
512
+ }
513
+ if (mainCarouselWrapperRef.current[carouselSlideAxis === "x" ? "scrollLeft" : "scrollTop"] > 0 &&
514
+ mainCarouselWrapperRef.current[carouselSlideAxis === "x" ? "scrollLeft" : "scrollTop"] < getTotalScrollValue()) {
515
+ firstItemReached.current = false;
516
+ lastItemReached.current = false;
517
+ }
518
+ if (mainCarouselWrapperRef.current[carouselSlideAxis === "x" ? "scrollLeft" : "scrollTop"] === getTotalScrollValue()) {
519
+ firstItemReached.current = false;
520
+ lastItemReached.current = true;
521
+ }
522
+ }
523
+ }
524
+ function getScrollHandlers() {
525
+ if (freeScroll) {
526
+ return {
527
+ onWheel() {
528
+ spring.val.stop();
529
+ setStartEndItemReachedOnFreeScroll();
530
+ },
531
+ };
532
+ }
533
+ return {};
534
+ }
535
+ function findItemIndex(id) {
536
+ return items.findIndex((item) => item.id === id);
537
+ }
538
+ function findItemIndexById(id, error) {
539
+ let itemIndex = 0;
540
+ if (typeof id === "string") {
541
+ itemIndex = items.findIndex((_item) => _item.id === id);
542
+ }
543
+ else {
544
+ itemIndex = id;
545
+ }
546
+ if (itemIndex < 0 || itemIndex >= items.length) {
547
+ throw new Error(error);
548
+ }
549
+ return itemIndex;
550
+ }
551
+ function internalSlideToItem(id) {
552
+ if (!init)
553
+ return;
554
+ firstItemReached.current = false;
555
+ lastItemReached.current = false;
556
+ 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.");
557
+ if (itemIndex === activeItem.current) {
558
+ return;
559
+ }
560
+ const currentItem = findItemIndex(items[activeItem.current].id);
561
+ const newActiveItem = findItemIndex(items[itemIndex].id);
562
+ if (newActiveItem > currentItem) {
563
+ slideToNextItem("click", newActiveItem);
564
+ }
565
+ else {
566
+ slideToPrevItem("click", newActiveItem);
567
+ }
568
+ }
569
+ function getIsNextItem(id) {
570
+ const itemIndex = findItemIndex(id);
571
+ const _activeItem = activeItem.current;
572
+ if (withLoop && _activeItem === items.length - 1) {
573
+ return itemIndex === 0;
574
+ }
575
+ return itemIndex === _activeItem + 1;
576
+ }
577
+ function getIsPrevItem(id) {
578
+ const itemIndex = findItemIndex(id);
579
+ const _activeItem = activeItem.current;
580
+ if (withLoop && _activeItem === 0) {
581
+ return itemIndex === items.length - 1;
582
+ }
583
+ return itemIndex === _activeItem - 1;
584
+ }
585
+ 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) => {
586
+ 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}`));
587
+ }) })) })));
588
+ return {
589
+ useListenToCustomEvent,
590
+ carouselFragment,
591
+ enterFullscreen,
592
+ exitFullscreen,
593
+ getIsFullscreen,
594
+ thumbsFragment,
595
+ slideToItem: internalSlideToItem,
596
+ getIsNextItem,
597
+ getIsPrevItem,
598
+ slideToPrevItem: () => slideToPrevItem(),
599
+ slideToNextItem: () => slideToNextItem(),
600
+ getIsActiveItem: (id) => {
601
+ return (findItemIndexById(id, "The item you want to check doesn't exist") ===
602
+ activeItem.current);
603
+ },
604
+ };
605
+ }
606
+ const Context = createContext(undefined);
607
+ function useSpringCarouselContext() {
608
+ const context = useContext(Context);
609
+ if (!context) {
610
+ throw new Error("useSpringCarouselContext must be used within the carousel.");
611
+ }
612
+ return context;
613
+ }
614
+
615
+ export { useSpringCarousel, useSpringCarouselContext };
2
616
  //# sourceMappingURL=useSpringCarousel.js.map