react-spring-carousel 3.0.0-beta009 → 3.0.0-beta015

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,779 +1,2 @@
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 <= (window.innerHeight || document.documentElement.clientHeight) &&
101
- rect.right <= (window.innerWidth || document.documentElement.clientWidth));
102
- }
103
- function useThumbsModule({ thumbsSlideAxis = 'x', withThumbs = false, prepareThumbsData, items, }) {
104
- const wrapperRef = react.useRef(null);
105
- const [spring, setSpring] = web.useSpring(() => ({
106
- val: 0,
107
- }));
108
- function getTotalScrollValue() {
109
- var _a;
110
- return Math.round(Number((_a = wrapperRef.current) === null || _a === void 0 ? void 0 : _a[thumbsSlideAxis === 'x' ? 'scrollWidth' : 'scrollHeight']) -
111
- wrapperRef.current.getBoundingClientRect()[thumbsSlideAxis === 'x' ? 'width' : 'height']);
112
- }
113
- function handleScroll(activeItem) {
114
- var _a, _b;
115
- function getThumbNode() {
116
- if (wrapperRef.current) {
117
- return wrapperRef.current.querySelector(`#thumb-item-${items[activeItem].id}`);
118
- }
119
- return null;
120
- }
121
- const thumbNode = getThumbNode();
122
- if (thumbNode && wrapperRef.current) {
123
- if (!isInViewport(thumbNode)) {
124
- const offset = thumbNode.offsetLeft;
125
- const val = offset > getTotalScrollValue() ? getTotalScrollValue() : offset;
126
- setSpring.start({
127
- from: {
128
- val: (_b = (_a = wrapperRef.current) === null || _a === void 0 ? void 0 : _a[thumbsSlideAxis === 'x' ? 'scrollLeft' : 'scrollTop']) !== null && _b !== void 0 ? _b : 0,
129
- },
130
- to: {
131
- val,
132
- },
133
- onChange: ({ value }) => {
134
- if (wrapperRef.current) {
135
- wrapperRef.current[thumbsSlideAxis === 'x' ? 'scrollLeft' : 'scrollTop'] =
136
- 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)) > getTotalScrollValue() - getSlideValue() / 3;
451
- if (lastItemReached.current)
452
- return;
453
- if (nextItemWillExceed) {
454
- firstItemReached.current = false;
455
- lastItemReached.current = true;
456
- slideToItem({
457
- slideMode: type,
458
- from: getFromValue(),
459
- to: -getTotalScrollValue(),
460
- nextActiveItem: nextItem,
461
- });
462
- return;
463
- }
464
- }
465
- if (withLoop && lastItemReached.current) {
466
- lastItemReached.current = false;
467
- firstItemReached.current = true;
468
- slideToItem({
469
- slideMode: type,
470
- from: getFromValue() + getSlideValue() * items.length,
471
- to: 0,
472
- nextActiveItem: 0,
473
- });
474
- return;
475
- }
476
- if (nextItem === 0) {
477
- firstItemReached.current = true;
478
- }
479
- if (nextItem === items.length - 1) {
480
- lastItemReached.current = true;
481
- }
482
- slideToItem({
483
- slideMode: type,
484
- from: getFromValue(),
485
- to: getToValue('next', index),
486
- nextActiveItem: nextItem,
487
- });
488
- }
489
- react.useEffect(() => {
490
- prevWindowWidth.current = window.innerWidth;
491
- }, []);
492
- react.useEffect(() => {
493
- adjustCarouselWrapperPosition();
494
- }, [
495
- initialStartingPosition,
496
- itemsPerSlide,
497
- withLoop,
498
- startEndGutter,
499
- gutter,
500
- freeScroll,
501
- slideType,
502
- init,
503
- ]);
504
- react.useLayoutEffect(() => {
505
- /**
506
- * Set initial track position
507
- */
508
- if (carouselTrackWrapperRef.current) {
509
- adjustCarouselWrapperPosition();
510
- }
511
- // eslint-disable-next-line react-hooks/exhaustive-deps
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;
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 s=r.useRef(null),[l,o]=t.useSpring((()=>({val:0})));function a(){var e;return Math.round(Number(null===(e=s.current)||void 0===e?void 0:e["x"===n?"scrollWidth":"scrollHeight"])-s.current.getBoundingClientRect()["x"===n?"width":"height"])}return{thumbsFragment:i?e.jsx("div",Object.assign({className:"use-spring-carousel-thumbs-wrapper",ref:s,onWheel:()=>l.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=s.current?s.current.querySelector(`#thumb-item-${u[e].id}`):null;if(i&&s.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;o.start({from:{val:null!==(r=null===(t=s.current)||void 0===t?void 0:t["x"===n?"scrollLeft":"scrollTop"])&&void 0!==r?r:0},to:{val:c},onChange:({value:e})=>{s.current&&(s.current["x"===n?"scrollLeft":"scrollTop"]=Math.abs(e.val))}})}}}}const u=r.createContext(void 0);exports.useSpringCarousel=function({items:u,init:s=!0,withThumbs:l,thumbsSlideAxis:o="x",itemsPerSlide:a=1,slideType:d="fixed",gutter:f=0,withLoop:h=!1,startEndGutter:v=0,carouselSlideAxis:g="x",disableGestures:m=!1,draggingSlideTreshold:x,slideWhenThresholdIsReached:p=!1,freeScroll:b,enableFreeScrollDrag:w,initialStartingPosition:y,prepareThumbsData:E,initialActiveItem:T=0}){const R=a>u.length?u.length:a,j=r.useRef(0),C=r.useRef(null!=x?x:0),S=r.useRef("initial"),I=r.useRef("initial"),F=r.useRef(0),[O,L]=t.useSpring((()=>({val:0,pause:!s,onChange({value:e}){b&&k.current?("x"===g?k.current.scrollLeft=Math.abs(e.val):k.current.scrollTop=Math.abs(e.val),te()):N.current&&(N.current.style.transform="x"===g?`translate3d(${e.val}px, 0px,0px)`:`translate3d(0px,${e.val}px,0px)`)}}))),$=r.useRef(T),M=r.useRef(0===T),A=r.useRef(!1),k=r.useRef(null),N=r.useRef(null),W=r.useCallback((()=>h?[...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,h])(),{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:P,handleScroll:B}=c({withThumbs:!!l,thumbsSlideAxis:o,prepareThumbsData:E,items:u}),{enterFullscreen:H,exitFullscreen:z,getIsFullscreen:G}=function({mainCarouselWrapperRef:e,onFullScreenChange:t,handleResize:n}){const c=r.useRef(!1);function u(e){c.current=e}return r.useEffect((()=>{function e(){document.fullscreenElement&&(u(!0),t(!0),n&&n()),document.fullscreenElement||(u(!1),t(!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:k,handleResize:()=>Q(),onFullScreenChange:e=>{q({eventName:"onFullscreenChange",isFullscreen:e})}});function X(){var e;const t=null===(e=k.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 Y({from:e,to:r,nextActiveItem:n,immediate:i=!1,slideMode:c}){I.current=c,"number"==typeof n&&(b||($.current=n),q({eventName:"onSlideStartChange",slideActionType:S.current,slideMode:I.current,nextItem:{startReached:M.current,endReached:A.current,index:b?-1:$.current,id:b?"":u[$.current].id}})),F.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:S.current,slideMode:I.current,currentItem:{startReached:M.current,endReached:A.current,index:b?-1:$.current,id:b?"":u[$.current].id}})}}),l&&!i&&B($.current)}function J(){var e;return h?X()*u.length:Math.round(Number(null===(e=N.current)||void 0===e?void 0:e["x"===g?"scrollWidth":"scrollHeight"])-N.current.getBoundingClientRect()["x"===g?"width":"height"]-2*v)}function K(){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 Q(){const e="x"===g?"left":"top";function t(t){const r=N.current;r&&(h?(r.style.top="0px",r.style.left="0px",r.style[e]=`-${t-v}px`):(r.style.left="0px",r.style.top="0px"))}const r=Math.abs(U());if(r<J()&&A.current&&(A.current=!1),r>J()){const e=-J();return A.current=!0,F.current=e,void L.start({immediate:!0,val:e})}if(t("center"===y?K()*u.length-X()*Math.round((R-1)/2):"end"===y?K()*u.length-X()*Math.round(R-1):K()*u.length),!b&&"fixed"===d){const e=-X()*$.current;F.current=e,L.start({immediate:!0,val:e})}}function U(){return b&&k.current?k.current["x"===g?"scrollLeft":"scrollTop"]:O.val.get()}function V(e,t){if(b&&"next"===e){const e=F.current+X();return e>J()?J():e}if(b&&"prev"===e){const e=F.current-X();return e<0?0:e}return"next"===e?t?-t*X():F.current-X():t?-t*X():F.current+X()}function Z(e="click",t){if(!s||M.current&&!h)return;S.current="prev",A.current=!1;const r=t||$.current-1;if(!h){const r=b?V("prev",t)-X()/3<0:V("prev",t)+X()/3>0;if(M.current)return;if(r)return M.current=!0,A.current=!1,void Y({slideMode:e,from:U(),to:0,nextActiveItem:0})}if(h&&M.current)return M.current=!1,A.current=!0,void Y({slideMode:e,from:U()-X()*u.length,to:-X()*u.length+X(),nextActiveItem:u.length-1});0===r&&(M.current=!0),r!==u.length-1&&-1!==r||(A.current=!0),Y({slideMode:e,from:U(),to:V("prev",t),nextActiveItem:r})}function _(e="click",t){if(!s||A.current&&!h)return;S.current="next",M.current=!1;const r=t||$.current+1;if(!h){const n=Math.abs(V("next",t))>J()-X()/3;if(A.current)return;if(n)return M.current=!1,A.current=!0,void Y({slideMode:e,from:U(),to:b?J():-J(),nextActiveItem:r})}if(h&&A.current)return A.current=!1,M.current=!0,void Y({slideMode:e,from:U()+X()*u.length,to:0,nextActiveItem:0});0===r&&(M.current=!0),r===u.length-1&&(A.current=!0),Y({slideMode:e,from:U(),to:V("next",t),nextActiveItem:r})}r.useEffect((()=>{if(s){if(T>u.length-1)throw new Error(`initialActiveItem (${T}) is greater than the total quantity available items (${u.length}).`);R>u.length&&console.warn(`itemsPerSlide (${R}) is greater than the total quantity available items (${u.length}). Fallback to ${u.length})`)}}),[T,u,R,s]),r.useEffect((()=>{j.current=window.innerWidth}),[]),r.useEffect((()=>{Q()}),[y,R,h,v,f,b,d,s]),r.useLayoutEffect((()=>{N.current&&Q()}),[]),r.useEffect((()=>{C.current=x||Math.floor(X()/2/2)}),[x]),r.useEffect((()=>{function e(){window.innerWidth!==j.current&&(j.current=window.innerWidth,Q())}return window.addEventListener("resize",e),()=>{window.removeEventListener("resize",e)}}),[]);const ee=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>C.current,s=i<-C.current;if(r)return S.current=c>0?"prev":"next",q(Object.assign(Object.assign({},e),{eventName:"onDrag",slideActionType:S.current})),b?"prev"===S.current&&n>0?(e.cancel(),void L.start({from:{val:U()},to:{val:0},config:{velocity:e.velocity,friction:50,tension:1e3}})):void L.start({from:{val:U()},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&&s?(_("drag"),e.cancel()):p&&u&&(Z("drag"),e.cancel())));e.last&&!e.canceled&&b&&("prev"===S.current&&Z("drag"),"next"===S.current&&_("drag")),!e.last||e.canceled||b||(s?!h&&A.current?L.start({val:-J(),config:Object.assign(Object.assign({},t.config.default),{velocity:e.velocity})}):_("drag"):u?!h&&M.current?L.start({val:0,config:Object.assign(Object.assign({},t.config.default),{velocity:e.velocity})}):Z("drag"):L.start({val:F.current,config:Object.assign(Object.assign({},t.config.default),{velocity:e.velocity})}))}),{enabled:s&&!m&&!b||!!b&&!!w,axis:g,from:()=>b&&k.current?[-k.current.scrollLeft,-k.current.scrollTop]:[O.val.get(),O.val.get()]});function te(){k.current&&(F.current=k.current["x"===g?"scrollLeft":"scrollTop"],0===k.current["x"===g?"scrollLeft":"scrollTop"]&&(M.current=!0,A.current=!1),k.current["x"===g?"scrollLeft":"scrollTop"]>0&&k.current["x"===g?"scrollLeft":"scrollTop"]<J()&&(M.current=!1,A.current=!1),k.current["x"===g?"scrollLeft":"scrollTop"]===J()&&(M.current=!1,A.current=!0))}function re(e,t){let r=0;if(r="string"==typeof e?u.findIndex((t=>t.id===e)):e,r<0||r>=u.length){if(t)throw new Error(t);console.error(`The item doesn't exist; check that the id provided - ${e} - is correct.`),r=-1}return r}const ne=e.jsx("div",Object.assign({ref:k},b?{onWheel(){O.val.stop(),te()}}:{},{style:Object.assign({display:"flex",position:"relative",width:"100%",height:"100%"},b?"x"===g?{overflowX:"auto"}:{overflowY:"auto"}:{})},{children:e.jsxs("div",Object.assign({ref:N},ee(),{style:Object.assign({position:"relative",display:"flex",flexDirection:"x"===g?"row":"column",touchAction:"none"},function(){const e=`calc(100% - ${2*v}px)`;return{width:"x"===g?e:"100%",height:"y"===g?e:"100%"}}())},{children:[b&&v?e.jsx("div",{style:{flexShrink:0,width:v}}):null,W.map(((t,r)=>{return 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"},(n=!!b&&r===u.length-1,"fixed"!==d||b?Object.assign({marginRight:`${n?0:f}px`}):{marginRight:`${n?0:f}px`,flex:`1 0 calc(100% / ${R} - ${f*(R-1)/R}px)`}))},{children:t.renderItem}),`${t.id}-${r}`);var n})),b&&v?e.jsx("div",{style:{flexShrink:0,width:v}}):null]}))}));return b?{useListenToCustomEvent:D,carouselFragment:ne,enterFullscreen:H,exitFullscreen:z,getIsFullscreen:G,thumbsFragment:P,slideToPrevItem:()=>Z(),slideToNextItem:()=>_()}:{useListenToCustomEvent:D,carouselFragment:ne,enterFullscreen:H,exitFullscreen:z,getIsFullscreen:G,thumbsFragment:P,slideToPrevItem:()=>Z(),slideToNextItem:()=>_(),slideToItem:function(e){if(!s)return;M.current=!1,A.current=!1;const t=re(e,"The item you want to slide to doesn't exist; check the provided id.");if(t===$.current)return;const r=re(u[$.current].id),n=re(u[t].id);n>r?_("click",n):Z("click",n)},getIsNextItem:function(e){const t=re(e,"The item doesn't exist; check the provided id."),r=$.current;return h&&r===u.length-1?0===t:t===r+1},getIsPrevItem:function(e){const t=re(e,"The item doesn't exist; check the provided id."),r=$.current;return h&&0===r?t===u.length-1:t===r-1},getIsActiveItem:e=>re(e,"The item you want to check doesn't exist; check the provided id.")===$.current}},exports.useSpringCarouselContext=function(){const e=r.useContext(u);if(!e)throw new Error("useSpringCarouselContext must be used within the carousel.");return e};
779
2
  //# sourceMappingURL=index.js.map