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.
package/dist/cjs/index.js CHANGED
@@ -1,2 +1,779 @@
1
- "use strict";var e=require("react/jsx-runtime"),t=require("@react-spring/web"),r=require("react"),n=require("@use-gesture/react"),i=require("screenfull");function c({thumbsSlideAxis:n="x",withThumbs:i=!1,prepareThumbsData:c,items:u}){const o=r.useRef(null),[s,l]=t.useSpring((()=>({val:0})));function a(){var e;return Math.round(Number(null===(e=o.current)||void 0===e?void 0:e["x"===n?"scrollWidth":"scrollHeight"])-o.current.getBoundingClientRect()["x"===n?"width":"height"])}return{thumbsFragment:i?e.jsx("div",Object.assign({className:"use-spring-carousel-thumbs-wrapper",ref:o,onWheel:()=>s.val.stop(),style:Object.assign({display:"flex",flex:"1",position:"relative",width:"100%",height:"100%",flexDirection:"x"===n?"row":"column"},"x"===n?{overflowX:"auto"}:{overflowY:"auto",maxHeight:"100%"})},{children:function(){function e(e){return e.map((e=>({id:e.id,renderThumb:e.renderThumb})))}return c?c(e(u)):e(u)}().map((({id:t,renderThumb:r})=>{const n=`thumb-item-${t}`;return e.jsx("div",Object.assign({id:n,className:"thumb-item"},{children:r}),n)}))})):null,handleScroll:function(e){var t,r;const i=o.current?o.current.querySelector(`#thumb-item-${u[e].id}`):null;if(i&&o.current&&!function(e){const t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}(i)){const e=i.offsetLeft,c=e>a()?a():e;l.start({from:{val:null!==(r=null===(t=o.current)||void 0===t?void 0:t["x"===n?"scrollLeft":"scrollTop"])&&void 0!==r?r:0},to:{val:c},onChange:({value:e})=>{o.current&&(o.current["x"===n?"scrollLeft":"scrollTop"]=Math.abs(e.val))}})}}}}const u=r.createContext(void 0);exports.useSpringCarousel=function({items:u,init:o=!0,withThumbs:s,thumbsSlideAxis:l="x",itemsPerSlide:a=1,slideType:d="fixed",gutter:f=0,withLoop:v=!1,startEndGutter:m=0,carouselSlideAxis:g="x",disableGestures:h=!1,draggingSlideTreshold:x,slideWhenThresholdIsReached:p=!1,freeScroll:b,enableFreeScrollDrag:w,initialStartingPosition:y,prepareThumbsData:E,initialActiveItem:R=0}){const T=r.useRef(0),j=r.useRef(null!=x?x:0),C=r.useRef("initial"),I=r.useRef("initial"),S=r.useRef(0),[O,L]=t.useSpring((()=>({val:0,pause:!o,onChange({value:e}){b&&N.current?(ee(),"x"===g?N.current.scrollLeft=Math.abs(e.val):N.current.scrollTop=Math.abs(e.val)):$.current&&($.current.style.transform="x"===g?`translate3d(${e.val}px, 0px,0px)`:`translate3d(0px,${e.val}px,0px)`)}}))),M=r.useRef(R),F=r.useRef(0===R),A=r.useRef(!1),N=r.useRef(null),$=r.useRef(null),W=r.useCallback((()=>v?[...u.map((e=>Object.assign(Object.assign({},e),{id:`prev-repeated-item-${e.id}`}))),...u,...u.map((e=>Object.assign(Object.assign({},e),{id:`next-repeated-item-${e.id}`})))]:[...u]),[u,v])(),{emitEvent:q,useListenToCustomEvent:D}=function(){const e=r.useRef(null);return r.useEffect((()=>{e.current=document.createElement("div")}),[]),{useListenToCustomEvent:function(t){r.useEffect((()=>{function r(e){t(e.detail)}if(e.current)return e.current.addEventListener("RSC::Event",r,!1),()=>{var t;null===(t=e.current)||void 0===t||t.removeEventListener("RSC::Event",r,!1)}}),[])},emitEvent:function(t){if(e.current){const r=new CustomEvent("RSC::Event",{detail:t});e.current.dispatchEvent(r)}}}}(),{thumbsFragment:k,handleScroll:B}=c({withThumbs:!!s,thumbsSlideAxis:l,prepareThumbsData:E,items:u}),{enterFullscreen:H,exitFullscreen:z,getIsFullscreen:P}=function({mainCarouselWrapperRef:e,emitEvent:t,handleResize:n}){const c=r.useRef(!1);function u(e){c.current=e}return r.useEffect((()=>{function e(){document.fullscreenElement&&(u(!0),t({eventName:"onFullscreenChange",isFullscreen:!0}),n&&n()),document.fullscreenElement||(u(!1),t({eventName:"onFullscreenChange",isFullscreen:!1}),n&&n())}if(i.isEnabled)return i.on("change",e),()=>{i.isEnabled&&i.off("change",e)}}),[]),{enterFullscreen:function(t){i.isEnabled&&i.request(t||e.current)},exitFullscreen:function(){i.isEnabled&&i.exit()},getIsFullscreen:function(){return c.current}}}({mainCarouselWrapperRef:N,emitEvent:q,handleResize:()=>K()});function G(){var e;const t=null===(e=N.current)||void 0===e?void 0:e.querySelector(".use-spring-carousel-item");if(!t)throw Error("No carousel items available!");return t.getBoundingClientRect()["x"===g?"width":"height"]+f}function X({from:e,to:r,nextActiveItem:n,immediate:i=!1,slideMode:c}){I.current=c,"number"==typeof n&&(b||(M.current=n),q({eventName:"onSlideStartChange",slideActionType:C.current,slideMode:I.current,nextItem:{startReached:F.current,endReached:A.current,index:b?-1:M.current,id:b?"":u[M.current].id}})),S.current=r,L.start({immediate:i,from:{val:e},to:{val:r},config:Object.assign(Object.assign({},t.config.default),{velocity:O.val.velocity}),onRest(e){!i&&e.finished&&q({eventName:"onSlideChange",slideActionType:C.current,slideMode:I.current,currentItem:{startReached:F.current,endReached:A.current,index:b?-1:M.current,id:b?"":u[M.current].id}})}}),s&&!i&&B(M.current)}function Y(){var e;return v?G()*u.length:Math.round(Number(null===(e=$.current)||void 0===e?void 0:e["x"===g?"scrollWidth":"scrollHeight"])-$.current.getBoundingClientRect()["x"===g?"width":"height"])}function J(){var e;const t=null===(e=$.current)||void 0===e?void 0:e.querySelector(".use-spring-carousel-item");if(!t)throw Error("No carousel items available!");return t.getBoundingClientRect()["x"===g?"width":"height"]+f}function K(){const e="x"===g?"left":"top";function t(t){const r=$.current;r&&(v?(r.style.top="0px",r.style.left="0px",r.style[e]=`-${t-m}px`):(r.style.left="0px",r.style.top="0px"))}const r=Math.abs(Q());if(r<Y()&&A.current&&(A.current=!1),r>Y()){const e=-Y();return A.current=!0,S.current=e,void L.start({immediate:!0,val:e})}if(t("center"===y?J()*u.length-G()*Math.round((a-1)/2):"end"===y?J()*u.length-G()*Math.round(a-1):J()*u.length),!b&&"fixed"===d){const e=-G()*M.current;S.current=e,L.start({immediate:!0,val:e})}}function Q(){return b&&N.current?N.current["x"===g?"scrollLeft":"scrollTop"]:O.val.get()}function U(e,t){if(b&&"next"===e){const e=S.current+G();return e>Y()?Y():e}if(b&&"prev"===e){const e=S.current-G();return e<0?0:e}return"next"===e?t?-t*G():S.current-G():t?-t*G():S.current+G()}function V(e="click",t){if(!o||F.current&&!v)return;C.current="prev",A.current=!1;const r=t||M.current-1;if(!v){const r=U("prev",t)+G()/3>0;if(F.current)return;if(r)return F.current=!0,A.current=!1,void X({slideMode:e,from:Q(),to:0,nextActiveItem:0})}if(v&&F.current)return F.current=!1,A.current=!0,void X({slideMode:e,from:Q()-G()*u.length,to:-G()*u.length+G(),nextActiveItem:u.length-1});0===r&&(F.current=!0),r!==u.length-1&&-1!==r||(A.current=!0),X({slideMode:e,from:Q(),to:U("prev",t),nextActiveItem:r})}function Z(e="click",t){if(!o||A.current&&!v)return;C.current="next",F.current=!1;const r=t||M.current+1;if(!v){const n=Math.abs(U("next",t))>Y()-G()/3;if(A.current)return;if(n)return F.current=!1,A.current=!0,void X({slideMode:e,from:Q(),to:-Y(),nextActiveItem:r})}if(v&&A.current)return A.current=!1,F.current=!0,void X({slideMode:e,from:Q()+G()*u.length,to:0,nextActiveItem:0});0===r&&(F.current=!0),r===u.length-1&&(A.current=!0),X({slideMode:e,from:Q(),to:U("next",t),nextActiveItem:r})}r.useEffect((()=>{T.current=window.innerWidth}),[]),r.useEffect((()=>{K()}),[y,a,v,m,f,b,d,o]),r.useLayoutEffect((()=>{$.current&&K()}),[]),r.useEffect((()=>{j.current=x||Math.floor(G()/2/2)}),[x]),r.useEffect((()=>{function e(){window.innerWidth!==T.current&&(T.current=window.innerWidth,K())}return window.addEventListener("resize",e),()=>{window.removeEventListener("resize",e)}}),[]);const _=n.useDrag((e=>{const r=e.dragging,n=e.offset["x"===g?0:1],i=e.movement["x"===g?0:1],c=e.direction["x"===g?0:1],u=i>j.current,o=i<-j.current;if(r)return C.current=c>0?"prev":"next",q(Object.assign(Object.assign({},e),{eventName:"onDrag",slideActionType:C.current})),b?"prev"===C.current&&n>0?(e.cancel(),void L.start({from:{val:Q()},to:{val:0},config:{velocity:e.velocity,friction:50,tension:1e3}})):void L.start({from:{val:Q()},to:{val:-n},config:{velocity:e.velocity,friction:50,tension:1e3}}):(L.start({val:n,config:{velocity:e.velocity,friction:50,tension:1e3}}),void(p&&o?(Z("drag"),e.cancel()):p&&u&&(V("drag"),e.cancel())));e.last&&!e.canceled&&b&&("prev"===C.current&&V("drag"),"next"===C.current&&Z("drag")),!e.last||e.canceled||b||(o?!v&&A.current?L.start({val:-Y(),config:Object.assign(Object.assign({},t.config.default),{velocity:e.velocity})}):Z("drag"):u?!v&&F.current?L.start({val:0,config:Object.assign(Object.assign({},t.config.default),{velocity:e.velocity})}):V("drag"):L.start({val:S.current,config:Object.assign(Object.assign({},t.config.default),{velocity:e.velocity})}))}),{enabled:o&&!h&&!b||!!b&&!!w,axis:g,from:()=>b&&N.current?[-N.current.scrollLeft,-N.current.scrollTop]:[O.val.get(),O.val.get()]});function ee(){N.current&&(S.current=N.current["x"===g?"scrollLeft":"scrollTop"],0===N.current["x"===g?"scrollLeft":"scrollTop"]&&(F.current=!0,A.current=!1),N.current["x"===g?"scrollLeft":"scrollTop"]>0&&N.current["x"===g?"scrollLeft":"scrollTop"]<Y()&&(F.current=!1,A.current=!1),N.current["x"===g?"scrollLeft":"scrollTop"]===Y()&&(F.current=!1,A.current=!0))}function te(e){return u.findIndex((t=>t.id===e))}function re(e,t){let r=0;if(r="string"==typeof e?u.findIndex((t=>t.id===e)):e,r<0||r>=u.length)throw new Error(t);return r}return{useListenToCustomEvent:D,carouselFragment:e.jsx("div",Object.assign({ref:N},b?{onWheel(){O.val.stop(),ee()}}:{},{style:Object.assign({display:"flex",position:"relative",width:"100%",height:"100%"},b?"x"===g?{overflowX:"auto"}:{overflowY:"auto"}:{})},{children:e.jsx("div",Object.assign({ref:$},_(),{style:Object.assign({position:"relative",display:"flex",flexDirection:"x"===g?"row":"column",touchAction:"none"},function(){const e=`calc(100% - ${2*m}px)`;return{width:"x"===g?e:"100%",height:"y"===g?e:"100%"}}())},{children:W.map(((t,r)=>e.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"},"fixed"!==d||b?Object.assign({marginRight:`${f}px`}):{marginRight:`${f}px`,flex:`1 0 calc(100% / ${a} - ${f*(a-1)/a}px)`})},{children:t.renderItem}),`${t.id}-${r}`)))}))})),enterFullscreen:H,exitFullscreen:z,getIsFullscreen:P,thumbsFragment:k,slideToItem:function(e){if(!o)return;F.current=!1,A.current=!1;const t=re(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===M.current)return;const r=te(u[M.current].id),n=te(u[t].id);n>r?Z("click",n):V("click",n)},getIsNextItem:function(e){const t=te(e),r=M.current;return v&&r===u.length-1?0===t:t===r+1},getIsPrevItem:function(e){const t=te(e),r=M.current;return v&&0===r?t===u.length-1:t===r-1},slideToPrevItem:()=>V(),slideToNextItem:()=>Z(),getIsActiveItem:e=>re(e,"The item you want to check doesn't exist")===M.current}},exports.useSpringCarouselContext=function(){const e=r.useContext(u);if(!e)throw new Error("useSpringCarouselContext must be used within the carousel.");return e};
1
+ 'use strict';
2
+
3
+ var jsxRuntime = require('react/jsx-runtime');
4
+ var web = require('@react-spring/web');
5
+ var react = require('react');
6
+ var react$1 = require('@use-gesture/react');
7
+ var screenfull = require('screenfull');
8
+
9
+ const eventLabel = "RSC::Event";
10
+ function useEventsModule() {
11
+ const targetEvent = react.useRef(null);
12
+ react.useEffect(() => {
13
+ targetEvent.current = document.createElement("div");
14
+ }, []);
15
+ function useListenToCustomEvent(eventHandler) {
16
+ react.useEffect(() => {
17
+ function handleEvent(event) {
18
+ eventHandler(event.detail);
19
+ }
20
+ if (targetEvent.current) {
21
+ // @ts-ignore
22
+ targetEvent.current.addEventListener(eventLabel, handleEvent, false);
23
+ return () => {
24
+ var _a;
25
+ // @ts-ignore
26
+ (_a = targetEvent.current) === null || _a === void 0 ? void 0 : _a.removeEventListener(eventLabel, handleEvent, false);
27
+ };
28
+ }
29
+ }, []);
30
+ }
31
+ function emitEvent(event) {
32
+ if (targetEvent.current) {
33
+ const newEvent = new CustomEvent(eventLabel, {
34
+ detail: event,
35
+ });
36
+ targetEvent.current.dispatchEvent(newEvent);
37
+ }
38
+ }
39
+ return {
40
+ useListenToCustomEvent,
41
+ emitEvent,
42
+ };
43
+ }
44
+
45
+ function useFullscreenModule({ mainCarouselWrapperRef, emitEvent, handleResize, }) {
46
+ const isFullscreen = react.useRef(false);
47
+ react.useEffect(() => {
48
+ function handleFullscreenChange() {
49
+ if (document.fullscreenElement) {
50
+ setIsFullscreen(true);
51
+ emitEvent({
52
+ eventName: "onFullscreenChange",
53
+ isFullscreen: true,
54
+ });
55
+ handleResize && handleResize();
56
+ }
57
+ if (!document.fullscreenElement) {
58
+ setIsFullscreen(false);
59
+ emitEvent({
60
+ eventName: "onFullscreenChange",
61
+ isFullscreen: false,
62
+ });
63
+ handleResize && handleResize();
64
+ }
65
+ }
66
+ if (screenfull.isEnabled) {
67
+ screenfull.on("change", handleFullscreenChange);
68
+ return () => {
69
+ if (screenfull.isEnabled) {
70
+ screenfull.off("change", handleFullscreenChange);
71
+ }
72
+ };
73
+ }
74
+ }, []);
75
+ function setIsFullscreen(_isFullscreen) {
76
+ isFullscreen.current = _isFullscreen;
77
+ }
78
+ function getIsFullscreen() {
79
+ return isFullscreen.current;
80
+ }
81
+ function enterFullscreen(elementRef) {
82
+ if (screenfull.isEnabled) {
83
+ screenfull.request((elementRef || mainCarouselWrapperRef.current));
84
+ }
85
+ }
86
+ function exitFullscreen() {
87
+ screenfull.isEnabled && screenfull.exit();
88
+ }
89
+ return {
90
+ enterFullscreen,
91
+ exitFullscreen,
92
+ getIsFullscreen,
93
+ };
94
+ }
95
+
96
+ function isInViewport(el) {
97
+ const rect = el.getBoundingClientRect();
98
+ return (rect.top >= 0 &&
99
+ rect.left >= 0 &&
100
+ rect.bottom <=
101
+ (window.innerHeight || document.documentElement.clientHeight) &&
102
+ rect.right <= (window.innerWidth || document.documentElement.clientWidth));
103
+ }
104
+ function useThumbsModule({ thumbsSlideAxis = "x", withThumbs = false, prepareThumbsData, items, }) {
105
+ const wrapperRef = react.useRef(null);
106
+ const [spring, setSpring] = web.useSpring(() => ({
107
+ val: 0,
108
+ }));
109
+ function getTotalScrollValue() {
110
+ var _a;
111
+ return Math.round(Number((_a = wrapperRef.current) === null || _a === void 0 ? void 0 : _a[thumbsSlideAxis === "x" ? "scrollWidth" : "scrollHeight"]) -
112
+ wrapperRef.current.getBoundingClientRect()[thumbsSlideAxis === "x" ? "width" : "height"]);
113
+ }
114
+ function handleScroll(activeItem) {
115
+ var _a, _b;
116
+ function getThumbNode() {
117
+ if (wrapperRef.current) {
118
+ return wrapperRef.current.querySelector(`#thumb-item-${items[activeItem].id}`);
119
+ }
120
+ return null;
121
+ }
122
+ const thumbNode = getThumbNode();
123
+ if (thumbNode && wrapperRef.current) {
124
+ if (!isInViewport(thumbNode)) {
125
+ const offset = thumbNode.offsetLeft;
126
+ const val = offset > getTotalScrollValue() ? getTotalScrollValue() : offset;
127
+ setSpring.start({
128
+ from: {
129
+ val: (_b = (_a = wrapperRef.current) === null || _a === void 0 ? void 0 : _a[thumbsSlideAxis === "x" ? "scrollLeft" : "scrollTop"]) !== null && _b !== void 0 ? _b : 0,
130
+ },
131
+ to: {
132
+ val,
133
+ },
134
+ onChange: ({ value }) => {
135
+ if (wrapperRef.current) {
136
+ wrapperRef.current[thumbsSlideAxis === "x" ? "scrollLeft" : "scrollTop"] = Math.abs(value.val);
137
+ }
138
+ },
139
+ });
140
+ }
141
+ }
142
+ }
143
+ function handlePrepareThumbsData() {
144
+ function getPreparedItems(_items) {
145
+ return _items.map((i) => ({
146
+ id: i.id,
147
+ renderThumb: i.renderThumb,
148
+ }));
149
+ }
150
+ if (prepareThumbsData) {
151
+ return prepareThumbsData(getPreparedItems(items));
152
+ }
153
+ return getPreparedItems(items);
154
+ }
155
+ const thumbsFragment = withThumbs ? (jsxRuntime.jsx("div", Object.assign({ className: "use-spring-carousel-thumbs-wrapper", ref: wrapperRef, onWheel: () => spring.val.stop(), style: Object.assign({ display: "flex", flex: "1", position: "relative", width: "100%", height: "100%", flexDirection: thumbsSlideAxis === "x" ? "row" : "column" }, (thumbsSlideAxis === "x"
156
+ ? { overflowX: "auto" }
157
+ : {
158
+ overflowY: "auto",
159
+ maxHeight: "100%",
160
+ })) }, { children: handlePrepareThumbsData().map(({ id, renderThumb }) => {
161
+ const thumbId = `thumb-item-${id}`;
162
+ return (jsxRuntime.jsx("div", Object.assign({ id: thumbId, className: "thumb-item" }, { children: renderThumb }), thumbId));
163
+ }) }))) : null;
164
+ return {
165
+ thumbsFragment,
166
+ handleScroll,
167
+ };
168
+ }
169
+
170
+ 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, }) {
171
+ const prevWindowWidth = react.useRef(0);
172
+ const draggingSlideTreshold = react.useRef(_draggingSlideTreshold !== null && _draggingSlideTreshold !== void 0 ? _draggingSlideTreshold : 0);
173
+ const slideActionType = react.useRef("initial");
174
+ const slideModeType = react.useRef("initial");
175
+ const prevSlidedValue = react.useRef(0);
176
+ const [spring, setSpring] = web.useSpring(() => ({
177
+ val: 0,
178
+ pause: !init,
179
+ onChange({ value }) {
180
+ if (freeScroll && mainCarouselWrapperRef.current) {
181
+ setStartEndItemReachedOnFreeScroll();
182
+ if (carouselSlideAxis === "x") {
183
+ mainCarouselWrapperRef.current.scrollLeft = Math.abs(value.val);
184
+ }
185
+ else {
186
+ mainCarouselWrapperRef.current.scrollTop = Math.abs(value.val);
187
+ }
188
+ }
189
+ else if (carouselTrackWrapperRef.current) {
190
+ if (carouselSlideAxis === "x") {
191
+ carouselTrackWrapperRef.current.style.transform = `translate3d(${value.val}px, 0px,0px)`;
192
+ }
193
+ else {
194
+ carouselTrackWrapperRef.current.style.transform = `translate3d(0px,${value.val}px,0px)`;
195
+ }
196
+ }
197
+ },
198
+ }));
199
+ const activeItem = react.useRef(initialActiveItem);
200
+ const firstItemReached = react.useRef(initialActiveItem === 0);
201
+ const lastItemReached = react.useRef(false);
202
+ const mainCarouselWrapperRef = react.useRef(null);
203
+ const carouselTrackWrapperRef = react.useRef(null);
204
+ const getItems = react.useCallback(() => {
205
+ if (withLoop) {
206
+ return [
207
+ ...items.map((i) => (Object.assign(Object.assign({}, i), { id: `prev-repeated-item-${i.id}` }))),
208
+ ...items,
209
+ ...items.map((i) => (Object.assign(Object.assign({}, i), { id: `next-repeated-item-${i.id}` }))),
210
+ ];
211
+ }
212
+ return [...items];
213
+ }, [items, withLoop]);
214
+ const internalItems = getItems();
215
+ const { emitEvent, useListenToCustomEvent } = useEventsModule();
216
+ const { thumbsFragment, handleScroll } = useThumbsModule({
217
+ withThumbs: !!withThumbs,
218
+ thumbsSlideAxis,
219
+ prepareThumbsData,
220
+ items: items,
221
+ });
222
+ const { enterFullscreen, exitFullscreen, getIsFullscreen } = useFullscreenModule({
223
+ mainCarouselWrapperRef,
224
+ emitEvent,
225
+ handleResize: () => adjustCarouselWrapperPosition(),
226
+ });
227
+ function getItemStyles() {
228
+ if (slideType === "fixed" && !freeScroll) {
229
+ return {
230
+ marginRight: `${gutter}px`,
231
+ flex: `1 0 calc(100% / ${itemsPerSlide} - ${(gutter * (itemsPerSlide - 1)) / itemsPerSlide}px)`,
232
+ };
233
+ }
234
+ return Object.assign({ marginRight: `${gutter}px` });
235
+ }
236
+ function getSlideValue() {
237
+ var _a;
238
+ const carouselItem = (_a = mainCarouselWrapperRef.current) === null || _a === void 0 ? void 0 : _a.querySelector(".use-spring-carousel-item");
239
+ if (!carouselItem) {
240
+ throw Error("No carousel items available!");
241
+ }
242
+ return (carouselItem.getBoundingClientRect()[carouselSlideAxis === "x" ? "width" : "height"] + gutter);
243
+ }
244
+ function slideToItem({ from, to, nextActiveItem, immediate = false, slideMode, }) {
245
+ slideModeType.current = slideMode;
246
+ if (typeof nextActiveItem === "number") {
247
+ if (!freeScroll) {
248
+ activeItem.current = nextActiveItem;
249
+ }
250
+ emitEvent({
251
+ eventName: "onSlideStartChange",
252
+ slideActionType: slideActionType.current,
253
+ slideMode: slideModeType.current,
254
+ nextItem: {
255
+ startReached: firstItemReached.current,
256
+ endReached: lastItemReached.current,
257
+ index: freeScroll ? -1 : activeItem.current,
258
+ id: freeScroll ? "" : items[activeItem.current].id,
259
+ },
260
+ });
261
+ }
262
+ prevSlidedValue.current = to;
263
+ setSpring.start({
264
+ immediate,
265
+ from: {
266
+ val: from,
267
+ },
268
+ to: {
269
+ val: to,
270
+ },
271
+ config: Object.assign(Object.assign({}, web.config.default), { velocity: spring.val.velocity }),
272
+ onRest(value) {
273
+ if (!immediate && value.finished) {
274
+ emitEvent({
275
+ eventName: "onSlideChange",
276
+ slideActionType: slideActionType.current,
277
+ slideMode: slideModeType.current,
278
+ currentItem: {
279
+ startReached: firstItemReached.current,
280
+ endReached: lastItemReached.current,
281
+ index: freeScroll ? -1 : activeItem.current,
282
+ id: freeScroll ? "" : items[activeItem.current].id,
283
+ },
284
+ });
285
+ }
286
+ },
287
+ });
288
+ if (withThumbs && !immediate) {
289
+ handleScroll(activeItem.current);
290
+ }
291
+ }
292
+ function getTotalScrollValue() {
293
+ var _a;
294
+ if (withLoop) {
295
+ return getSlideValue() * items.length;
296
+ }
297
+ return Math.round(Number((_a = carouselTrackWrapperRef.current) === null || _a === void 0 ? void 0 : _a[carouselSlideAxis === "x" ? "scrollWidth" : "scrollHeight"]) -
298
+ carouselTrackWrapperRef.current.getBoundingClientRect()[carouselSlideAxis === "x" ? "width" : "height"]);
299
+ }
300
+ function getAnimatedWrapperStyles() {
301
+ const percentValue = `calc(100% - ${startEndGutter * 2}px)`;
302
+ return {
303
+ width: carouselSlideAxis === "x" ? percentValue : "100%",
304
+ height: carouselSlideAxis === "y" ? percentValue : "100%",
305
+ };
306
+ }
307
+ function getCarouselItemWidth() {
308
+ var _a;
309
+ const carouselItem = (_a = carouselTrackWrapperRef.current) === null || _a === void 0 ? void 0 : _a.querySelector(".use-spring-carousel-item");
310
+ if (!carouselItem) {
311
+ throw Error("No carousel items available!");
312
+ }
313
+ return (carouselItem.getBoundingClientRect()[carouselSlideAxis === "x" ? "width" : "height"] + gutter);
314
+ }
315
+ function adjustCarouselWrapperPosition() {
316
+ const positionProperty = carouselSlideAxis === "x" ? "left" : "top";
317
+ function setPosition(v) {
318
+ const ref = carouselTrackWrapperRef.current;
319
+ if (!ref)
320
+ return;
321
+ if (withLoop) {
322
+ ref.style.top = "0px";
323
+ ref.style.left = "0px";
324
+ ref.style[positionProperty] = `-${v - startEndGutter}px`;
325
+ }
326
+ else {
327
+ ref.style.left = "0px";
328
+ ref.style.top = "0px";
329
+ }
330
+ }
331
+ const currentFromValue = Math.abs(getFromValue());
332
+ if (currentFromValue < getTotalScrollValue() && lastItemReached.current) {
333
+ lastItemReached.current = false;
334
+ }
335
+ if (currentFromValue > getTotalScrollValue()) {
336
+ const val = -getTotalScrollValue();
337
+ lastItemReached.current = true;
338
+ prevSlidedValue.current = val;
339
+ setSpring.start({
340
+ immediate: true,
341
+ val,
342
+ });
343
+ return;
344
+ }
345
+ if (initialStartingPosition === "center") {
346
+ setPosition(getCarouselItemWidth() * items.length -
347
+ getSlideValue() * Math.round((itemsPerSlide - 1) / 2));
348
+ }
349
+ else if (initialStartingPosition === "end") {
350
+ setPosition(getCarouselItemWidth() * items.length -
351
+ getSlideValue() * Math.round(itemsPerSlide - 1));
352
+ }
353
+ else {
354
+ setPosition(getCarouselItemWidth() * items.length);
355
+ }
356
+ if (!freeScroll && slideType === "fixed") {
357
+ const val = -(getSlideValue() * activeItem.current);
358
+ prevSlidedValue.current = val;
359
+ setSpring.start({
360
+ immediate: true,
361
+ val,
362
+ });
363
+ }
364
+ }
365
+ function getFromValue() {
366
+ if (freeScroll && mainCarouselWrapperRef.current) {
367
+ return mainCarouselWrapperRef.current[carouselSlideAxis === "x" ? "scrollLeft" : "scrollTop"];
368
+ }
369
+ return spring.val.get();
370
+ }
371
+ function getToValue(type, index) {
372
+ if (freeScroll && type === "next") {
373
+ const next = prevSlidedValue.current + getSlideValue();
374
+ if (next > getTotalScrollValue()) {
375
+ return getTotalScrollValue();
376
+ }
377
+ return next;
378
+ }
379
+ if (freeScroll && type === "prev") {
380
+ const next = prevSlidedValue.current - getSlideValue();
381
+ if (next < 0) {
382
+ return 0;
383
+ }
384
+ return next;
385
+ }
386
+ if (type === "next") {
387
+ if (index) {
388
+ return -(index * getSlideValue());
389
+ }
390
+ return prevSlidedValue.current - getSlideValue();
391
+ }
392
+ if (index) {
393
+ return -(index * getSlideValue());
394
+ }
395
+ return prevSlidedValue.current + getSlideValue();
396
+ }
397
+ function slideToPrevItem(type = "click", index) {
398
+ if (!init || (firstItemReached.current && !withLoop))
399
+ return;
400
+ slideActionType.current = "prev";
401
+ lastItemReached.current = false;
402
+ const nextItem = index || activeItem.current - 1;
403
+ if (!withLoop) {
404
+ const nextItemWillExceed = getToValue("prev", index) + getSlideValue() / 3 > 0;
405
+ if (firstItemReached.current)
406
+ return;
407
+ if (nextItemWillExceed) {
408
+ firstItemReached.current = true;
409
+ lastItemReached.current = false;
410
+ slideToItem({
411
+ slideMode: type,
412
+ from: getFromValue(),
413
+ to: 0,
414
+ nextActiveItem: 0,
415
+ });
416
+ return;
417
+ }
418
+ }
419
+ if (withLoop && firstItemReached.current) {
420
+ firstItemReached.current = false;
421
+ lastItemReached.current = true;
422
+ slideToItem({
423
+ slideMode: type,
424
+ from: getFromValue() - getSlideValue() * items.length,
425
+ to: -(getSlideValue() * items.length) + getSlideValue(),
426
+ nextActiveItem: items.length - 1,
427
+ });
428
+ return;
429
+ }
430
+ if (nextItem === 0) {
431
+ firstItemReached.current = true;
432
+ }
433
+ if (nextItem === items.length - 1 || nextItem === -1) {
434
+ lastItemReached.current = true;
435
+ }
436
+ slideToItem({
437
+ slideMode: type,
438
+ from: getFromValue(),
439
+ to: getToValue("prev", index),
440
+ nextActiveItem: nextItem,
441
+ });
442
+ }
443
+ function slideToNextItem(type = "click", index) {
444
+ if (!init || (lastItemReached.current && !withLoop))
445
+ return;
446
+ slideActionType.current = "next";
447
+ firstItemReached.current = false;
448
+ const nextItem = index || activeItem.current + 1;
449
+ if (!withLoop) {
450
+ const nextItemWillExceed = Math.abs(getToValue("next", index)) >
451
+ getTotalScrollValue() - getSlideValue() / 3;
452
+ if (lastItemReached.current)
453
+ return;
454
+ if (nextItemWillExceed) {
455
+ firstItemReached.current = false;
456
+ lastItemReached.current = true;
457
+ slideToItem({
458
+ slideMode: type,
459
+ from: getFromValue(),
460
+ to: -getTotalScrollValue(),
461
+ nextActiveItem: nextItem,
462
+ });
463
+ return;
464
+ }
465
+ }
466
+ if (withLoop && lastItemReached.current) {
467
+ lastItemReached.current = false;
468
+ firstItemReached.current = true;
469
+ slideToItem({
470
+ slideMode: type,
471
+ from: getFromValue() + getSlideValue() * items.length,
472
+ to: 0,
473
+ nextActiveItem: 0,
474
+ });
475
+ return;
476
+ }
477
+ if (nextItem === 0) {
478
+ firstItemReached.current = true;
479
+ }
480
+ if (nextItem === items.length - 1) {
481
+ lastItemReached.current = true;
482
+ }
483
+ slideToItem({
484
+ slideMode: type,
485
+ from: getFromValue(),
486
+ to: getToValue("next", index),
487
+ nextActiveItem: nextItem,
488
+ });
489
+ }
490
+ react.useEffect(() => {
491
+ prevWindowWidth.current = window.innerWidth;
492
+ }, []);
493
+ react.useEffect(() => {
494
+ adjustCarouselWrapperPosition();
495
+ }, [
496
+ initialStartingPosition,
497
+ itemsPerSlide,
498
+ withLoop,
499
+ startEndGutter,
500
+ gutter,
501
+ freeScroll,
502
+ slideType,
503
+ init,
504
+ ]);
505
+ react.useLayoutEffect(() => {
506
+ /**
507
+ * Set initial track position
508
+ */
509
+ if (carouselTrackWrapperRef.current) {
510
+ adjustCarouselWrapperPosition();
511
+ }
512
+ }, []);
513
+ react.useEffect(() => {
514
+ if (_draggingSlideTreshold) {
515
+ draggingSlideTreshold.current = _draggingSlideTreshold;
516
+ }
517
+ else {
518
+ draggingSlideTreshold.current = Math.floor(getSlideValue() / 2 / 2);
519
+ }
520
+ }, [_draggingSlideTreshold]);
521
+ react.useEffect(() => {
522
+ function handleResize() {
523
+ if (window.innerWidth === prevWindowWidth.current)
524
+ return;
525
+ prevWindowWidth.current = window.innerWidth;
526
+ adjustCarouselWrapperPosition();
527
+ }
528
+ window.addEventListener("resize", handleResize);
529
+ return () => {
530
+ window.removeEventListener("resize", handleResize);
531
+ };
532
+ }, []);
533
+ const bindDrag = react$1.useDrag((state) => {
534
+ const isDragging = state.dragging;
535
+ const movement = state.offset[carouselSlideAxis === "x" ? 0 : 1];
536
+ const currentMovement = state.movement[carouselSlideAxis === "x" ? 0 : 1];
537
+ const direction = state.direction[carouselSlideAxis === "x" ? 0 : 1];
538
+ const prevItemTreshold = currentMovement > draggingSlideTreshold.current;
539
+ const nextItemTreshold = currentMovement < -draggingSlideTreshold.current;
540
+ if (isDragging) {
541
+ if (direction > 0) {
542
+ slideActionType.current = "prev";
543
+ }
544
+ else {
545
+ slideActionType.current = "next";
546
+ }
547
+ emitEvent(Object.assign(Object.assign({}, state), { eventName: "onDrag", slideActionType: slideActionType.current }));
548
+ if (freeScroll) {
549
+ if (slideActionType.current === "prev" && movement > 0) {
550
+ state.cancel();
551
+ setSpring.start({
552
+ from: {
553
+ val: getFromValue(),
554
+ },
555
+ to: {
556
+ val: 0,
557
+ },
558
+ config: {
559
+ velocity: state.velocity,
560
+ friction: 50,
561
+ tension: 1000,
562
+ },
563
+ });
564
+ return;
565
+ }
566
+ setSpring.start({
567
+ from: {
568
+ val: getFromValue(),
569
+ },
570
+ to: {
571
+ val: -movement,
572
+ },
573
+ config: {
574
+ velocity: state.velocity,
575
+ friction: 50,
576
+ tension: 1000,
577
+ },
578
+ });
579
+ return;
580
+ }
581
+ setSpring.start({
582
+ val: movement,
583
+ config: {
584
+ velocity: state.velocity,
585
+ friction: 50,
586
+ tension: 1000,
587
+ },
588
+ });
589
+ if (slideWhenThresholdIsReached && nextItemTreshold) {
590
+ slideToNextItem("drag");
591
+ state.cancel();
592
+ }
593
+ else if (slideWhenThresholdIsReached && prevItemTreshold) {
594
+ slideToPrevItem("drag");
595
+ state.cancel();
596
+ }
597
+ return;
598
+ }
599
+ if (state.last && !state.canceled && freeScroll) {
600
+ if (slideActionType.current === "prev") {
601
+ slideToPrevItem("drag");
602
+ }
603
+ if (slideActionType.current === "next") {
604
+ slideToNextItem("drag");
605
+ }
606
+ }
607
+ if (state.last && !state.canceled && !freeScroll) {
608
+ if (nextItemTreshold) {
609
+ if (!withLoop && lastItemReached.current) {
610
+ setSpring.start({
611
+ val: -getTotalScrollValue(),
612
+ config: Object.assign(Object.assign({}, web.config.default), { velocity: state.velocity }),
613
+ });
614
+ }
615
+ else {
616
+ slideToNextItem("drag");
617
+ }
618
+ }
619
+ else if (prevItemTreshold) {
620
+ if (!withLoop && firstItemReached.current) {
621
+ setSpring.start({
622
+ val: 0,
623
+ config: Object.assign(Object.assign({}, web.config.default), { velocity: state.velocity }),
624
+ });
625
+ }
626
+ else {
627
+ slideToPrevItem("drag");
628
+ }
629
+ }
630
+ else {
631
+ setSpring.start({
632
+ val: prevSlidedValue.current,
633
+ config: Object.assign(Object.assign({}, web.config.default), { velocity: state.velocity }),
634
+ });
635
+ }
636
+ }
637
+ }, {
638
+ enabled: (init && !disableGestures && !freeScroll) ||
639
+ (!!freeScroll && !!enableFreeScrollDrag),
640
+ axis: carouselSlideAxis,
641
+ from: () => {
642
+ if (freeScroll && mainCarouselWrapperRef.current) {
643
+ return [
644
+ -mainCarouselWrapperRef.current.scrollLeft,
645
+ -mainCarouselWrapperRef.current.scrollTop,
646
+ ];
647
+ }
648
+ if (carouselSlideAxis === "x") {
649
+ return [spring.val.get(), spring.val.get()];
650
+ }
651
+ return [spring.val.get(), spring.val.get()];
652
+ },
653
+ });
654
+ function getWrapperOverflowStyles() {
655
+ if (freeScroll) {
656
+ if (carouselSlideAxis === "x") {
657
+ return {
658
+ overflowX: "auto",
659
+ };
660
+ }
661
+ return {
662
+ overflowY: "auto",
663
+ };
664
+ }
665
+ return {};
666
+ }
667
+ function setStartEndItemReachedOnFreeScroll() {
668
+ if (mainCarouselWrapperRef.current) {
669
+ prevSlidedValue.current =
670
+ mainCarouselWrapperRef.current[carouselSlideAxis === "x" ? "scrollLeft" : "scrollTop"];
671
+ if (mainCarouselWrapperRef.current[carouselSlideAxis === "x" ? "scrollLeft" : "scrollTop"] === 0) {
672
+ firstItemReached.current = true;
673
+ lastItemReached.current = false;
674
+ }
675
+ if (mainCarouselWrapperRef.current[carouselSlideAxis === "x" ? "scrollLeft" : "scrollTop"] > 0 &&
676
+ mainCarouselWrapperRef.current[carouselSlideAxis === "x" ? "scrollLeft" : "scrollTop"] < getTotalScrollValue()) {
677
+ firstItemReached.current = false;
678
+ lastItemReached.current = false;
679
+ }
680
+ if (mainCarouselWrapperRef.current[carouselSlideAxis === "x" ? "scrollLeft" : "scrollTop"] === getTotalScrollValue()) {
681
+ firstItemReached.current = false;
682
+ lastItemReached.current = true;
683
+ }
684
+ }
685
+ }
686
+ function getScrollHandlers() {
687
+ if (freeScroll) {
688
+ return {
689
+ onWheel() {
690
+ spring.val.stop();
691
+ setStartEndItemReachedOnFreeScroll();
692
+ },
693
+ };
694
+ }
695
+ return {};
696
+ }
697
+ function findItemIndex(id) {
698
+ return items.findIndex((item) => item.id === id);
699
+ }
700
+ function findItemIndexById(id, error) {
701
+ let itemIndex = 0;
702
+ if (typeof id === "string") {
703
+ itemIndex = items.findIndex((_item) => _item.id === id);
704
+ }
705
+ else {
706
+ itemIndex = id;
707
+ }
708
+ if (itemIndex < 0 || itemIndex >= items.length) {
709
+ throw new Error(error);
710
+ }
711
+ return itemIndex;
712
+ }
713
+ function internalSlideToItem(id) {
714
+ if (!init)
715
+ return;
716
+ firstItemReached.current = false;
717
+ lastItemReached.current = false;
718
+ 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.");
719
+ if (itemIndex === activeItem.current) {
720
+ return;
721
+ }
722
+ const currentItem = findItemIndex(items[activeItem.current].id);
723
+ const newActiveItem = findItemIndex(items[itemIndex].id);
724
+ if (newActiveItem > currentItem) {
725
+ slideToNextItem("click", newActiveItem);
726
+ }
727
+ else {
728
+ slideToPrevItem("click", newActiveItem);
729
+ }
730
+ }
731
+ function getIsNextItem(id) {
732
+ const itemIndex = findItemIndex(id);
733
+ const _activeItem = activeItem.current;
734
+ if (withLoop && _activeItem === items.length - 1) {
735
+ return itemIndex === 0;
736
+ }
737
+ return itemIndex === _activeItem + 1;
738
+ }
739
+ function getIsPrevItem(id) {
740
+ const itemIndex = findItemIndex(id);
741
+ const _activeItem = activeItem.current;
742
+ if (withLoop && _activeItem === 0) {
743
+ return itemIndex === items.length - 1;
744
+ }
745
+ return itemIndex === _activeItem - 1;
746
+ }
747
+ const carouselFragment = (jsxRuntime.jsx("div", Object.assign({ ref: mainCarouselWrapperRef }, getScrollHandlers(), { style: Object.assign({ display: "flex", position: "relative", width: "100%", height: "100%" }, getWrapperOverflowStyles()) }, { children: jsxRuntime.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) => {
748
+ return (jsxRuntime.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}`));
749
+ }) })) })));
750
+ return {
751
+ useListenToCustomEvent,
752
+ carouselFragment,
753
+ enterFullscreen,
754
+ exitFullscreen,
755
+ getIsFullscreen,
756
+ thumbsFragment,
757
+ slideToItem: internalSlideToItem,
758
+ getIsNextItem,
759
+ getIsPrevItem,
760
+ slideToPrevItem: () => slideToPrevItem(),
761
+ slideToNextItem: () => slideToNextItem(),
762
+ getIsActiveItem: (id) => {
763
+ return (findItemIndexById(id, "The item you want to check doesn't exist") ===
764
+ activeItem.current);
765
+ },
766
+ };
767
+ }
768
+ const Context = react.createContext(undefined);
769
+ function useSpringCarouselContext() {
770
+ const context = react.useContext(Context);
771
+ if (!context) {
772
+ throw new Error("useSpringCarouselContext must be used within the carousel.");
773
+ }
774
+ return context;
775
+ }
776
+
777
+ exports.useSpringCarousel = useSpringCarousel;
778
+ exports.useSpringCarouselContext = useSpringCarouselContext;
2
779
  //# sourceMappingURL=index.js.map