react-spring-carousel 3.0.0-beta010 → 3.0.0-beta016

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"),n=require("react"),r=require("@use-gesture/react"),i=require("screenfull");function s(){const e=n.useRef(null);return n.useEffect((()=>{e.current=document.createElement("div")}),[]),{useListenToCustomEvent:function(t){n.useEffect((()=>{function n(e){t(e.detail)}if(e.current)return e.current.addEventListener("RSC::Event",n,!1),()=>{var t;null===(t=e.current)||void 0===t||t.removeEventListener("RSC::Event",n,!1)}}),[])},emitEvent:function(t){if(e.current){const n=new CustomEvent("RSC::Event",{detail:t});e.current.dispatchEvent(n)}}}}function c({thumbsSlideAxis:r="x",withThumbs:i=!1,prepareThumbsData:s,items:c}){const o=n.useRef(null),[l,u]=t.useSpring((()=>({val:0})));function a(){var e;return Math.round(Number(null===(e=o.current)||void 0===e?void 0:e["x"===r?"scrollWidth":"scrollHeight"])-o.current.getBoundingClientRect()["x"===r?"width":"height"])}return{thumbsFragment:i?e.jsx("div",Object.assign({className:"use-spring-carousel-thumbs-wrapper",ref:o,onWheel:()=>l.val.stop(),style:Object.assign({display:"flex",flex:"1",position:"relative",width:"100%",height:"100%",flexDirection:"x"===r?"row":"column"},"x"===r?{overflowX:"auto"}:{overflowY:"auto",maxHeight:"100%"})},{children:function(){function e(e){return e.map((e=>({id:e.id,renderThumb:e.renderThumb})))}return s?s(e(c)):e(c)}().map((({id:t,renderThumb:n})=>{const r=`thumb-item-${t}`;return e.jsx("div",Object.assign({id:r,className:"thumb-item"},{children:n}),r)}))})):null,handleScroll:function(e){var t,n;const i=o.current?o.current.querySelector(`#thumb-item-${c[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,s=e>a()?a():e;u.start({from:{val:null!==(n=null===(t=o.current)||void 0===t?void 0:t["x"===r?"scrollLeft":"scrollTop"])&&void 0!==n?n:0},to:{val:s},onChange:({value:e})=>{o.current&&(o.current["x"===r?"scrollLeft":"scrollTop"]=Math.abs(e.val))}})}}}}const o=n.createContext(void 0);const l={initial:{opacity:1,position:"relative"},from:{opacity:0,position:"relative"},enter:{position:"relative",opacity:1},leave:{opacity:1,position:"absolute"}};exports.useSpringCarousel=function({items:o,init:l=!0,withThumbs:u,thumbsSlideAxis:a="x",itemsPerSlide:d=1,slideType:f="fixed",gutter:g=0,withLoop:h=!1,startEndGutter:v=0,carouselSlideAxis:m="x",disableGestures:p=!1,draggingSlideTreshold:x,slideWhenThresholdIsReached:b=!1,freeScroll:y,enableFreeScrollDrag:w,initialStartingPosition:T,prepareThumbsData:j,initialActiveItem:E=0}){const O=d>o.length?o.length:d,R=n.useRef(0),S=n.useRef(null!=x?x:0),I=n.useRef("initial"),C=n.useRef("initial"),M=n.useRef(0),[F,L]=t.useSpring((()=>({val:0,pause:!l,onChange({value:e}){y&&k.current?("x"===m?k.current.scrollLeft=Math.abs(e.val):k.current.scrollTop=Math.abs(e.val),ne()):W.current&&(W.current.style.transform="x"===m?`translate3d(${e.val}px, 0px,0px)`:`translate3d(0px,${e.val}px,0px)`)}}))),N=n.useRef(E),$=n.useRef(0===E),A=n.useRef(!1),k=n.useRef(null),W=n.useRef(null),q=n.useCallback((()=>h?[...o.map((e=>Object.assign(Object.assign({},e),{id:`prev-repeated-item-${e.id}`}))),...o,...o.map((e=>Object.assign(Object.assign({},e),{id:`next-repeated-item-${e.id}`})))]:[...o]),[o,h])(),{emitEvent:P,useListenToCustomEvent:D}=s(),{thumbsFragment:B,handleScroll:H}=c({withThumbs:!!u,thumbsSlideAxis:a,prepareThumbsData:j,items:o}),{enterFullscreen:z,exitFullscreen:G,getIsFullscreen:X}=function({mainCarouselWrapperRef:e,onFullScreenChange:t,handleResize:r}){const s=n.useRef(!1);function c(e){s.current=e}return n.useEffect((()=>{function e(){document.fullscreenElement&&(c(!0),t(!0),r&&r()),document.fullscreenElement||(c(!1),t(!1),r&&r())}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 s.current}}}({mainCarouselWrapperRef:k,handleResize:()=>U(),onFullScreenChange:e=>{P({eventName:"onFullscreenChange",isFullscreen:e})}});function Y(){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"===m?"width":"height"]+g}function J({from:e,to:n,nextActiveItem:r,immediate:i=!1,slideMode:s}){C.current=s,"number"==typeof r&&(y||(N.current=r),P({eventName:"onSlideStartChange",slideActionType:I.current,slideMode:C.current,nextItem:{startReached:$.current,endReached:A.current,index:y?-1:N.current,id:y?"":o[N.current].id}})),M.current=n,L.start({immediate:i,from:{val:e},to:{val:n},config:Object.assign(Object.assign({},t.config.default),{velocity:F.val.velocity}),onRest(e){!i&&e.finished&&P({eventName:"onSlideChange",slideActionType:I.current,slideMode:C.current,currentItem:{startReached:$.current,endReached:A.current,index:y?-1:N.current,id:y?"":o[N.current].id}})}}),u&&!i&&H(N.current)}function K(){var e;return h?Y()*o.length:Math.round(Number(null===(e=W.current)||void 0===e?void 0:e["x"===m?"scrollWidth":"scrollHeight"])-W.current.getBoundingClientRect()["x"===m?"width":"height"]-2*v)}function Q(){var e;const t=null===(e=W.current)||void 0===e?void 0:e.querySelector(".use-spring-carousel-item");if(!t)throw Error("No carousel items available!");return t.getBoundingClientRect()["x"===m?"width":"height"]+g}function U(){const e="x"===m?"left":"top";function t(t){const n=W.current;n&&(h?(n.style.top="0px",n.style.left="0px",n.style[e]=`-${t-v}px`):(n.style.left="0px",n.style.top="0px"))}const n=Math.abs(V());if(n<K()&&A.current&&(A.current=!1),n>K()){const e=-K();return A.current=!0,M.current=e,void L.start({immediate:!0,val:e})}if(t("center"===T?Q()*o.length-Y()*Math.round((O-1)/2):"end"===T?Q()*o.length-Y()*Math.round(O-1):Q()*o.length),!y&&"fixed"===f){const e=-Y()*N.current;M.current=e,L.start({immediate:!0,val:e})}}function V(){return y&&k.current?k.current["x"===m?"scrollLeft":"scrollTop"]:F.val.get()}function Z(e,t){if(y&&"next"===e){const e=M.current+Y();return e>K()?K():e}if(y&&"prev"===e){const e=M.current-Y();return e<0?0:e}return"next"===e?t?-t*Y():M.current-Y():t?-t*Y():M.current+Y()}function _(e="click",t){if(!l||$.current&&!h)return;I.current="prev",A.current=!1;const n=t||N.current-1;if(!h){const n=y?Z("prev",t)-Y()/3<0:Z("prev",t)+Y()/3>0;if($.current)return;if(n)return $.current=!0,A.current=!1,void J({slideMode:e,from:V(),to:0,nextActiveItem:0})}if(h&&$.current)return $.current=!1,A.current=!0,void J({slideMode:e,from:V()-Y()*o.length,to:-Y()*o.length+Y(),nextActiveItem:o.length-1});0===n&&($.current=!0),n!==o.length-1&&-1!==n||(A.current=!0),J({slideMode:e,from:V(),to:Z("prev",t),nextActiveItem:n})}function ee(e="click",t){if(!l||A.current&&!h)return;I.current="next",$.current=!1;const n=t||N.current+1;if(!h){const r=Math.abs(Z("next",t))>K()-Y()/3;if(A.current)return;if(r)return $.current=!1,A.current=!0,void J({slideMode:e,from:V(),to:y?K():-K(),nextActiveItem:n})}if(h&&A.current)return A.current=!1,$.current=!0,void J({slideMode:e,from:V()+Y()*o.length,to:0,nextActiveItem:0});0===n&&($.current=!0),n===o.length-1&&(A.current=!0),J({slideMode:e,from:V(),to:Z("next",t),nextActiveItem:n})}n.useEffect((()=>{if(l){if(E>o.length-1)throw new Error(`initialActiveItem (${E}) is greater than the total quantity available items (${o.length}).`);O>o.length&&console.warn(`itemsPerSlide (${O}) is greater than the total quantity available items (${o.length}). Fallback to ${o.length})`)}}),[E,o,O,l]),n.useEffect((()=>{R.current=window.innerWidth}),[]),n.useEffect((()=>{U()}),[T,O,h,v,g,y,f,l]),n.useLayoutEffect((()=>{W.current&&U()}),[]),n.useEffect((()=>{S.current=x||Math.floor(Y()/2/2)}),[x]),n.useEffect((()=>{function e(){window.innerWidth!==R.current&&(R.current=window.innerWidth,U())}return window.addEventListener("resize",e),()=>{window.removeEventListener("resize",e)}}),[]);const te=r.useDrag((e=>{const n=e.dragging,r=e.offset["x"===m?0:1],i=e.movement["x"===m?0:1],s=e.direction["x"===m?0:1],c=i>S.current,o=i<-S.current;if(n)return I.current=s>0?"prev":"next",P(Object.assign(Object.assign({},e),{eventName:"onDrag",slideActionType:I.current})),y?"prev"===I.current&&r>0?(e.cancel(),void L.start({from:{val:V()},to:{val:0},config:{velocity:e.velocity,friction:50,tension:1e3}})):void L.start({from:{val:V()},to:{val:-r},config:{velocity:e.velocity,friction:50,tension:1e3}}):(L.start({val:r,config:{velocity:e.velocity,friction:50,tension:1e3}}),void(b&&o?(ee("drag"),e.cancel()):b&&c&&(_("drag"),e.cancel())));e.last&&!e.canceled&&y&&("prev"===I.current&&_("drag"),"next"===I.current&&ee("drag")),!e.last||e.canceled||y||(o?!h&&A.current?L.start({val:-K(),config:Object.assign(Object.assign({},t.config.default),{velocity:e.velocity})}):ee("drag"):c?!h&&$.current?L.start({val:0,config:Object.assign(Object.assign({},t.config.default),{velocity:e.velocity})}):_("drag"):L.start({val:M.current,config:Object.assign(Object.assign({},t.config.default),{velocity:e.velocity})}))}),{enabled:l&&!p&&!y||!!y&&!!w,axis:m,from:()=>y&&k.current?[-k.current.scrollLeft,-k.current.scrollTop]:[F.val.get(),F.val.get()]});function ne(){k.current&&(M.current=k.current["x"===m?"scrollLeft":"scrollTop"],0===k.current["x"===m?"scrollLeft":"scrollTop"]&&($.current=!0,A.current=!1),k.current["x"===m?"scrollLeft":"scrollTop"]>0&&k.current["x"===m?"scrollLeft":"scrollTop"]<K()&&($.current=!1,A.current=!1),k.current["x"===m?"scrollLeft":"scrollTop"]===K()&&($.current=!1,A.current=!0))}function re(e,t){let n=0;if(n="string"==typeof e?o.findIndex((t=>t.id===e)):e,n<0||n>=o.length){if(t)throw new Error(t);console.error(`The item doesn't exist; check that the id provided - ${e} - is correct.`),n=-1}return n}const ie=e.jsx("div",Object.assign({ref:k},y?{onWheel(){F.val.stop(),ne()}}:{},{style:Object.assign({display:"flex",position:"relative",width:"100%",height:"100%"},y?"x"===m?{overflowX:"auto"}:{overflowY:"auto"}:{})},{children:e.jsxs("div",Object.assign({ref:W},te(),{style:Object.assign({position:"relative",display:"flex",flexDirection:"x"===m?"row":"column",touchAction:"none"},function(){const e=`calc(100% - ${2*v}px)`;return{width:"x"===m?e:"100%",height:"y"===m?e:"100%"}}())},{children:[y&&v?e.jsx("div",{style:{flexShrink:0,width:v}}):null,q.map(((t,n)=>{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"},(r=!!y&&n===o.length-1,"fixed"!==f||y?Object.assign({marginRight:`${r?0:g}px`}):{marginRight:`${r?0:g}px`,flex:`1 0 calc(100% / ${O} - ${g*(O-1)/O}px)`}))},{children:t.renderItem}),`${t.id}-${n}`);var r})),y&&v?e.jsx("div",{style:{flexShrink:0,width:v}}):null]}))}));return y?{useListenToCustomEvent:D,carouselFragment:ie,enterFullscreen:z,exitFullscreen:G,getIsFullscreen:X,thumbsFragment:B,slideToPrevItem:()=>_(),slideToNextItem:()=>ee()}:{useListenToCustomEvent:D,carouselFragment:ie,enterFullscreen:z,exitFullscreen:G,getIsFullscreen:X,thumbsFragment:B,slideToPrevItem:()=>_(),slideToNextItem:()=>ee(),slideToItem:function(e){if(!l)return;$.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===N.current)return;const n=re(o[N.current].id),r=re(o[t].id);r>n?ee("click",r):_("click",r)},getIsNextItem:function(e){const t=re(e,"The item doesn't exist; check the provided id."),n=N.current;return h&&n===o.length-1?0===t:t===n+1},getIsPrevItem:function(e){const t=re(e,"The item doesn't exist; check the provided id."),n=N.current;return h&&0===n?t===o.length-1:t===n-1},getIsActiveItem:e=>re(e,"The item you want to check doesn't exist; check the provided id.")===N.current}},exports.useSpringCarouselContext=function(){const e=n.useContext(o);if(!e)throw new Error("useSpringCarouselContext must be used within the carousel.");return e},exports.useTransitionCarousel=function({init:i=!0,disableGestures:c=!1,items:o,springConfig:u=t.config.default,exitBeforeEnter:a=!1,trail:d,withLoop:f=!1,activeItem:g,toPrevItemSpringProps:h=l,toNextItemSpringProps:v=l,draggingSlideTreshold:m=50}){const p=n.useRef("next"),x=n.useRef("initial"),b=n.useRef(null),[y,w]=n.useState(null!=g?g:0),{emitEvent:T,useListenToCustomEvent:j}=s();function E({to:e,slideType:t,slideMode:n}){p.current=t,x.current=n,T({eventName:"onSlideStartChange",slideActionType:p.current,slideMode:x.current,nextItem:{index:e,id:o[e].id,startReached:0===e,endReached:e===o.length-1}}),w(e)}function O(e){if(!i)return;const t=0===y;!f&&t||E(f&&t?{to:o.length-1,slideType:"prev",slideMode:e}:{to:y-1,slideType:"prev",slideMode:e})}function R(e){if(!i)return;const t=y===o.length-1;!f&&t||E(f&&t?{to:0,slideType:"next",slideMode:e}:{to:y+1,slideType:"next",slideMode:e})}n.useEffect((()=>{"number"==typeof g&&g!==y&&w(g)}),[g]);const S=t.useTransition(y,Object.assign(Object.assign({config:u,key:null,trail:d,exitBeforeEnter:a},"prev"===p.current?{initial:Object.assign({},h.initial),from:Object.assign({},h.from),enter:Object.assign({},h.enter),leave:Object.assign({},h.leave)}:"next"===p.current?{initial:Object.assign({},v.initial),from:Object.assign({},v.from),enter:Object.assign({},v.enter),leave:Object.assign({},v.leave)}:{initial:Object.assign({},l.initial),from:Object.assign({},l.from),enter:Object.assign({},l.enter),leave:Object.assign({},l.leave)}),{onRest(e,t,n){e.finished&&n===y&&T({eventName:"onSlideChange",slideActionType:p.current,slideMode:x.current,currentItem:{index:y,id:o[y].id,startReached:0===y,endReached:y===o.length-1}})}})),I=r.useDrag((({last:e,movement:[t]})=>{if(e){const e=t>m,n=t<-m,r=0===y,i=y===o.length-1;if(n){if(!f&&i)return;T({eventName:"onLeftSwipe"}),R("swipe")}else if(e){if(!f&&r)return;T({eventName:"onRightSwipe"}),O("swipe")}}}),{enabled:!c}),C=S(((n,r,i,s)=>e.jsx(t.a.div,Object.assign({id:`use-transition-carousel-item-${s}`,className:"use-transition-carousel-item",style:Object.assign(Object.assign({},n),{flex:"1 0 100%",width:"100%",height:"100%"})},{children:o[r].renderItem}))));return{useListenToCustomEvent:j,carouselFragment:e.jsx("div",Object.assign({ref:b},I(),{style:{display:"flex",position:"relative",width:"100%",height:"100%",overflow:"hidden"}},{children:C})),slideToPrevItem:()=>O("click"),slideToNextItem:()=>R("click")}};
779
2
  //# sourceMappingURL=index.js.map