@salutejs/plasma-new-hope 0.321.1-canary.1945.14661970912.0 → 0.321.1-canary.1946.14663041744.0

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.
Files changed (105) hide show
  1. package/cjs/index.css +0 -7
  2. package/cjs/index.js +0 -7
  3. package/cjs/index.js.map +1 -1
  4. package/emotion/cjs/index.js +0 -11
  5. package/emotion/es/index.js +1 -2
  6. package/es/index.css +0 -7
  7. package/es/index.js +0 -3
  8. package/es/index.js.map +1 -1
  9. package/package.json +4 -4
  10. package/styled-components/cjs/index.js +0 -11
  11. package/styled-components/es/index.js +1 -2
  12. package/types/index.d.ts +0 -1
  13. package/types/index.d.ts.map +1 -1
  14. package/cjs/components/Carousel/Carousel.css +0 -4
  15. package/cjs/components/Carousel/Carousel.js +0 -80
  16. package/cjs/components/Carousel/Carousel.js.map +0 -1
  17. package/cjs/components/Carousel/Carousel.styles.js +0 -67
  18. package/cjs/components/Carousel/Carousel.styles.js.map +0 -1
  19. package/cjs/components/Carousel/Carousel.styles_1lyqijv.css +0 -4
  20. package/cjs/components/Carousel/CarouselItem.js +0 -53
  21. package/cjs/components/Carousel/CarouselItem.js.map +0 -1
  22. package/cjs/components/Carousel/CarouselItem_cqjszm.css +0 -1
  23. package/cjs/components/Carousel/useCarousel.js +0 -487
  24. package/cjs/components/Carousel/useCarousel.js.map +0 -1
  25. package/cjs/components/Carousel/useDragScroll.js +0 -62
  26. package/cjs/components/Carousel/useDragScroll.js.map +0 -1
  27. package/emotion/cjs/components/Carousel/Carousel.js +0 -77
  28. package/emotion/cjs/components/Carousel/Carousel.styles.js +0 -49
  29. package/emotion/cjs/components/Carousel/Carousel.types.js +0 -5
  30. package/emotion/cjs/components/Carousel/CarouselItem.js +0 -38
  31. package/emotion/cjs/components/Carousel/index.js +0 -32
  32. package/emotion/cjs/components/Carousel/useCarousel.js +0 -478
  33. package/emotion/cjs/components/Carousel/useDragScroll.js +0 -65
  34. package/emotion/cjs/examples/plasma_b2c/components/Carousel/Carousel.config.js +0 -10
  35. package/emotion/cjs/examples/plasma_b2c/components/Carousel/Carousel.js +0 -18
  36. package/emotion/cjs/examples/plasma_b2c/components/Carousel/Carousel.stories.tsx +0 -80
  37. package/emotion/cjs/examples/plasma_web/components/Carousel/Carousel.config.js +0 -10
  38. package/emotion/cjs/examples/plasma_web/components/Carousel/Carousel.js +0 -18
  39. package/emotion/cjs/examples/plasma_web/components/Carousel/Carousel.stories.tsx +0 -80
  40. package/emotion/es/components/Carousel/Carousel.js +0 -69
  41. package/emotion/es/components/Carousel/Carousel.styles.js +0 -42
  42. package/emotion/es/components/Carousel/Carousel.types.js +0 -1
  43. package/emotion/es/components/Carousel/CarouselItem.js +0 -31
  44. package/emotion/es/components/Carousel/index.js +0 -3
  45. package/emotion/es/components/Carousel/useCarousel.js +0 -468
  46. package/emotion/es/components/Carousel/useDragScroll.js +0 -59
  47. package/emotion/es/examples/plasma_b2c/components/Carousel/Carousel.config.js +0 -4
  48. package/emotion/es/examples/plasma_b2c/components/Carousel/Carousel.js +0 -6
  49. package/emotion/es/examples/plasma_b2c/components/Carousel/Carousel.stories.tsx +0 -80
  50. package/emotion/es/examples/plasma_web/components/Carousel/Carousel.config.js +0 -4
  51. package/emotion/es/examples/plasma_web/components/Carousel/Carousel.js +0 -6
  52. package/emotion/es/examples/plasma_web/components/Carousel/Carousel.stories.tsx +0 -80
  53. package/es/components/Carousel/Carousel.css +0 -4
  54. package/es/components/Carousel/Carousel.js +0 -71
  55. package/es/components/Carousel/Carousel.js.map +0 -1
  56. package/es/components/Carousel/Carousel.styles.js +0 -60
  57. package/es/components/Carousel/Carousel.styles.js.map +0 -1
  58. package/es/components/Carousel/Carousel.styles_1lyqijv.css +0 -4
  59. package/es/components/Carousel/CarouselItem.js +0 -45
  60. package/es/components/Carousel/CarouselItem.js.map +0 -1
  61. package/es/components/Carousel/CarouselItem_cqjszm.css +0 -1
  62. package/es/components/Carousel/useCarousel.js +0 -472
  63. package/es/components/Carousel/useCarousel.js.map +0 -1
  64. package/es/components/Carousel/useDragScroll.js +0 -58
  65. package/es/components/Carousel/useDragScroll.js.map +0 -1
  66. package/styled-components/cjs/components/Carousel/Carousel.js +0 -77
  67. package/styled-components/cjs/components/Carousel/Carousel.styles.js +0 -38
  68. package/styled-components/cjs/components/Carousel/Carousel.types.js +0 -5
  69. package/styled-components/cjs/components/Carousel/CarouselItem.js +0 -37
  70. package/styled-components/cjs/components/Carousel/index.js +0 -32
  71. package/styled-components/cjs/components/Carousel/useCarousel.js +0 -478
  72. package/styled-components/cjs/components/Carousel/useDragScroll.js +0 -65
  73. package/styled-components/cjs/examples/plasma_b2c/components/Carousel/Carousel.config.js +0 -10
  74. package/styled-components/cjs/examples/plasma_b2c/components/Carousel/Carousel.js +0 -18
  75. package/styled-components/cjs/examples/plasma_b2c/components/Carousel/Carousel.stories.tsx +0 -80
  76. package/styled-components/cjs/examples/plasma_web/components/Carousel/Carousel.config.js +0 -10
  77. package/styled-components/cjs/examples/plasma_web/components/Carousel/Carousel.js +0 -18
  78. package/styled-components/cjs/examples/plasma_web/components/Carousel/Carousel.stories.tsx +0 -80
  79. package/styled-components/es/components/Carousel/Carousel.js +0 -69
  80. package/styled-components/es/components/Carousel/Carousel.styles.js +0 -30
  81. package/styled-components/es/components/Carousel/Carousel.types.js +0 -1
  82. package/styled-components/es/components/Carousel/CarouselItem.js +0 -30
  83. package/styled-components/es/components/Carousel/index.js +0 -3
  84. package/styled-components/es/components/Carousel/useCarousel.js +0 -468
  85. package/styled-components/es/components/Carousel/useDragScroll.js +0 -59
  86. package/styled-components/es/examples/plasma_b2c/components/Carousel/Carousel.config.js +0 -4
  87. package/styled-components/es/examples/plasma_b2c/components/Carousel/Carousel.js +0 -6
  88. package/styled-components/es/examples/plasma_b2c/components/Carousel/Carousel.stories.tsx +0 -80
  89. package/styled-components/es/examples/plasma_web/components/Carousel/Carousel.config.js +0 -4
  90. package/styled-components/es/examples/plasma_web/components/Carousel/Carousel.js +0 -6
  91. package/styled-components/es/examples/plasma_web/components/Carousel/Carousel.stories.tsx +0 -80
  92. package/types/components/Carousel/Carousel.d.ts +0 -22
  93. package/types/components/Carousel/Carousel.d.ts.map +0 -1
  94. package/types/components/Carousel/Carousel.styles.d.ts +0 -16
  95. package/types/components/Carousel/Carousel.styles.d.ts.map +0 -1
  96. package/types/components/Carousel/Carousel.types.d.ts +0 -111
  97. package/types/components/Carousel/Carousel.types.d.ts.map +0 -1
  98. package/types/components/Carousel/CarouselItem.d.ts +0 -4
  99. package/types/components/Carousel/CarouselItem.d.ts.map +0 -1
  100. package/types/components/Carousel/index.d.ts +0 -5
  101. package/types/components/Carousel/index.d.ts.map +0 -1
  102. package/types/components/Carousel/useCarousel.d.ts +0 -63
  103. package/types/components/Carousel/useCarousel.d.ts.map +0 -1
  104. package/types/components/Carousel/useDragScroll.d.ts +0 -3
  105. package/types/components/Carousel/useDragScroll.d.ts.map +0 -1
@@ -1,468 +0,0 @@
1
- import { useEffect, useCallback, useRef, useMemo } from 'react';
2
- import throttle from 'lodash.throttle';
3
- /**
4
- * Подсчет смещения из-за паддингов.
5
- */
6
- export var getCalculatedOffset = function getCalculatedOffset(scrollEl, trackEl, axis) {
7
- var paddingProp = axis === 'x' ? 'paddingLeft' : 'paddingTop';
8
- return parseInt(getComputedStyle(scrollEl)[paddingProp], 10) + parseInt(getComputedStyle(trackEl)[paddingProp], 10);
9
- };
10
- var positionModByScrollAlign = function positionModByScrollAlign(_ref) {
11
- var scrollAlign = _ref.scrollAlign,
12
- position = _ref.position,
13
- carouselSize = _ref.carouselSize,
14
- itemSize = _ref.itemSize,
15
- offset = _ref.offset,
16
- scrollStart = _ref.scrollStart,
17
- axis = _ref.axis;
18
- if (scrollAlign === 'start') {
19
- var inaccuracy = 1;
20
- var paddingOffset = axis === 'y' ? offset - itemSize / 2 + inaccuracy : 0;
21
- return position + paddingOffset;
22
- }
23
- if (scrollAlign === 'center') {
24
- return position - carouselSize / 2 + itemSize / 2;
25
- }
26
- if (scrollAlign === 'end') {
27
- return position - carouselSize + itemSize + offset;
28
- }
29
- if (scrollAlign === 'activeDirection') {
30
- if (position >= scrollStart + carouselSize - itemSize) {
31
- return position - carouselSize + itemSize + offset;
32
- }
33
- if (position > scrollStart) {
34
- return scrollStart;
35
- }
36
- }
37
- return position;
38
- };
39
-
40
- /**
41
- * Подсчет скролла до переданного индекса.
42
- */
43
- export var getCalculatedPos = function getCalculatedPos(_ref2) {
44
- var scrollEl = _ref2.scrollEl,
45
- items = _ref2.items,
46
- axis = _ref2.axis,
47
- index = _ref2.index,
48
- offset = _ref2.offset,
49
- scrollAlign = _ref2.scrollAlign;
50
- var position = scrollAlign === 'center' ? offset : 0;
51
- var carouselSize;
52
- var itemSize;
53
- var scrollStart;
54
- if (items.item(index) === null) {
55
- return position;
56
- }
57
- for (var i = 0; i < index; i++) {
58
- if (axis === 'x') {
59
- var _items$item$offsetWid, _items$item;
60
- position += (_items$item$offsetWid = (_items$item = items.item(i)) === null || _items$item === void 0 ? void 0 : _items$item.offsetWidth) !== null && _items$item$offsetWid !== void 0 ? _items$item$offsetWid : 0;
61
- } else {
62
- var _items$item$offsetHei, _items$item2;
63
- position += (_items$item$offsetHei = (_items$item2 = items.item(i)) === null || _items$item2 === void 0 ? void 0 : _items$item2.offsetHeight) !== null && _items$item$offsetHei !== void 0 ? _items$item$offsetHei : 0;
64
- }
65
- }
66
- if (axis === 'x') {
67
- var _items$item$offsetWid2, _items$item3;
68
- carouselSize = scrollEl.offsetWidth;
69
- itemSize = (_items$item$offsetWid2 = (_items$item3 = items.item(index)) === null || _items$item3 === void 0 ? void 0 : _items$item3.offsetWidth) !== null && _items$item$offsetWid2 !== void 0 ? _items$item$offsetWid2 : 0;
70
- scrollStart = scrollEl.scrollLeft;
71
- } else {
72
- var _items$item$offsetHei2, _items$item4;
73
- carouselSize = scrollEl.offsetHeight;
74
- itemSize = (_items$item$offsetHei2 = (_items$item4 = items.item(index)) === null || _items$item4 === void 0 ? void 0 : _items$item4.offsetHeight) !== null && _items$item$offsetHei2 !== void 0 ? _items$item$offsetHei2 : 0;
75
- scrollStart = scrollEl.scrollTop;
76
- }
77
- return positionModByScrollAlign({
78
- scrollAlign: scrollAlign,
79
- position: position,
80
- carouselSize: carouselSize,
81
- itemSize: itemSize,
82
- offset: offset,
83
- scrollStart: scrollStart,
84
- axis: axis
85
- });
86
- };
87
- var DEFAULT_DURATION = 300;
88
-
89
- // https://css-tricks.com/emulating-css-timing-functions-javascript/
90
- var tfs = {
91
- linear: function linear(t) {
92
- return t;
93
- },
94
- // eslint-disable-next-line
95
- easeIn: function easeIn(t) {
96
- return Math.pow(t, 1.675);
97
- },
98
- // eslint-disable-next-line
99
- easeOut: function easeOut(t) {
100
- return 1 - Math.pow(1 - t, 1.675);
101
- },
102
- easeInOut: function easeInOut(t) {
103
- return 0.5 * (Math.sin((t - 0.5) * Math.PI) + 1);
104
- }
105
- };
106
- /**
107
- * Плавная прокрутка по горизонтали
108
- * @param {Element} elem
109
- * @param {number} pos
110
- * @param {number} duration
111
- * @param {string} timingFunction
112
- */
113
- export var animatedScrollToX = function animatedScrollToX(elem, pos) {
114
- var duration = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_DURATION;
115
- var timingFunction = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'easeInOut';
116
- var startTime;
117
- var startX = elem.scrollLeft;
118
- var endX = Math.max(0, Math.min(elem.scrollWidth - elem.clientWidth, pos));
119
- var handleNewAnimationFrame = function handleNewAnimationFrame() {
120
- startTime = startTime || Date.now();
121
- var timePos = Math.min(1, Math.max(1, Date.now() - startTime) / duration);
122
- var scrollPos = tfs[timingFunction](timePos);
123
- var left = startX + (endX - startX) * scrollPos;
124
- elem.scrollTo({
125
- left: left
126
- });
127
- if (timePos !== 1) window.requestAnimationFrame(handleNewAnimationFrame);
128
- };
129
- window.requestAnimationFrame(handleNewAnimationFrame);
130
- };
131
-
132
- /**
133
- * Прокрутка к указанной позиции с анимацией или без.
134
- */
135
- export var scrollToPos = function scrollToPos(_ref3) {
136
- var scrollEl = _ref3.scrollEl,
137
- pos = _ref3.pos,
138
- axis = _ref3.axis,
139
- animated = _ref3.animated,
140
- duration = _ref3.duration,
141
- timingFunction = _ref3.timingFunction;
142
- if (axis === 'x' && Math.abs(pos - scrollEl.scrollLeft) > 1) {
143
- if (animated) {
144
- animatedScrollToX(scrollEl, pos, duration, timingFunction);
145
- } else {
146
- scrollEl.scrollTo({
147
- left: pos
148
- });
149
- }
150
- }
151
- };
152
- var round = function round(n) {
153
- return Math.round(n * 100) / 100;
154
- };
155
-
156
- /**
157
- * Получить позицию (слот) айтема в каруселе.
158
- * Каждый айтем имеет свой слот относительно вьюпорта карусели.
159
- */
160
- export var getItemSlot = function getItemSlot(itemIndex, itemEnd, itemSize, scrollStart, scrollSize, scrollAlign) {
161
- var prevIndex = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0;
162
- var offset = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0;
163
- /**
164
- * Граница и центр скролла (видимой части).
165
- * Смещение + размер.
166
- */
167
- var scrollEnd = scrollStart + scrollSize;
168
- var scrollCenter = scrollStart + scrollSize / 2;
169
- var itemCenter = itemEnd - itemSize / 2;
170
- if (scrollAlign === 'center') {
171
- return round((itemCenter - scrollCenter) / itemSize);
172
- }
173
- if (scrollAlign === 'start') {
174
- return round((itemEnd - itemSize - scrollStart) / itemSize);
175
- }
176
- if (scrollAlign === 'end') {
177
- return round((itemEnd - (scrollSize + scrollStart)) / itemSize);
178
- }
179
- if (scrollAlign === 'activeDirection') {
180
- var prevStart = offset + itemSize * prevIndex;
181
- var prevEnd = prevStart + itemSize;
182
- var prevVisible = prevEnd > scrollStart && prevStart < scrollEnd;
183
- if (!prevVisible) {
184
- if (prevIndex < itemIndex) {
185
- return round((itemEnd - (scrollSize + scrollStart)) / itemSize);
186
- }
187
- return round((itemEnd - itemSize - scrollStart) / itemSize);
188
- }
189
- }
190
- return null;
191
- };
192
- export function getCarouselItems(track) {
193
- return track.children;
194
- }
195
- export function useDebouncedFunction(func, delay, cleanUp) {
196
- var timeoutRef = useRef();
197
-
198
- /**
199
- * Очистка таймера
200
- */
201
- function clearTimer() {
202
- if (timeoutRef.current) {
203
- clearTimeout(timeoutRef.current);
204
- timeoutRef.current = undefined;
205
- }
206
- }
207
-
208
- /**
209
- * Очищаем таймер при анмаунте компонента, если cleanUp выставлен в true
210
- * и тем самым отменяем последний запланированный вызов
211
- */
212
- useEffect(function () {
213
- return cleanUp ? clearTimer : undefined;
214
- }, [cleanUp]);
215
- return function () {
216
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
217
- args[_key] = arguments[_key];
218
- }
219
- clearTimer();
220
- timeoutRef.current = setTimeout(function () {
221
- return func.apply(void 0, args);
222
- }, delay);
223
- };
224
- }
225
- var THROTTLE_DEFAULT_MS = 100;
226
- var DEBOUNCE_DEFAULT_MS = 150;
227
- export var useCarousel = function useCarousel(_ref4) {
228
- var index = _ref4.index,
229
- _ref4$axis = _ref4.axis,
230
- axis = _ref4$axis === void 0 ? 'x' : _ref4$axis,
231
- _ref4$detectActive = _ref4.detectActive,
232
- detectActive = _ref4$detectActive === void 0 ? false : _ref4$detectActive,
233
- _ref4$detectThreshold = _ref4.detectThreshold,
234
- detectThreshold = _ref4$detectThreshold === void 0 ? 0.5 : _ref4$detectThreshold,
235
- _ref4$scrollAlign = _ref4.scrollAlign,
236
- scrollAlign = _ref4$scrollAlign === void 0 ? 'center' : _ref4$scrollAlign,
237
- scaleCallback = _ref4.scaleCallback,
238
- scaleResetCallback = _ref4.scaleResetCallback,
239
- onIndexChange = _ref4.onIndexChange,
240
- onDetectActiveItem = _ref4.onDetectActiveItem,
241
- _ref4$animatedScrollB = _ref4.animatedScrollByIndex,
242
- animatedScrollByIndex = _ref4$animatedScrollB === void 0 ? false : _ref4$animatedScrollB,
243
- _ref4$throttleMs = _ref4.throttleMs,
244
- throttleMs = _ref4$throttleMs === void 0 ? THROTTLE_DEFAULT_MS : _ref4$throttleMs,
245
- _ref4$debounceMs = _ref4.debounceMs,
246
- debounceMs = _ref4$debounceMs === void 0 ? DEBOUNCE_DEFAULT_MS : _ref4$debounceMs;
247
- var prevIndex = useRef(null);
248
- var direction = useRef(null);
249
- var offset = useRef(0);
250
- var scrollRef = useRef(null);
251
- var trackRef = useRef(null);
252
-
253
- /**
254
- * Для того, чтобы не спамить изменениями индекса.
255
- * Задержка дебаунса слегка больше, чем у тротлинга.
256
- * Таким образом, событие срабатывает при завершении скролла.
257
- */
258
- var debouncedOnIndexChange = useDebouncedFunction(function (i) {
259
- return onIndexChange === null || onIndexChange === void 0 ? void 0 : onIndexChange(i);
260
- }, debounceMs);
261
-
262
- /**
263
- * Вычисление центрального элемента.
264
- * Подсчет: от 0 до 1, какое количество ширины/высоты
265
- * каждого элемента находится по центру скролла.
266
- */
267
- var throttledDetectActiveItem = useMemo(function () {
268
- return throttle(function () {
269
- if (!detectActive || scrollRef.current === null || trackRef.current === null) {
270
- return;
271
- }
272
-
273
- /**
274
- * Правая (или нижняя для Оу) граница элемента.
275
- */
276
- var itemEdge = offset.current;
277
-
278
- /**
279
- * Смещение (отрицательный или положительный отступ)
280
- * и размер карусели (для Ox - ширина, для Oy - высота).
281
- */
282
- var scrollPos = scrollRef.current[axis === 'x' ? 'scrollLeft' : 'scrollTop'];
283
- var scrollSize = scrollRef.current[axis === 'x' ? 'offsetWidth' : 'offsetHeight'];
284
-
285
- /**
286
- * Граница скролла (видимой части).
287
- * Смещение + размер.
288
- */
289
- var scrollEdge = scrollPos + scrollSize;
290
-
291
- /**
292
- * Элементы перед, после и в видимой части.
293
- * перед [ ВИДИМЫЕ ] после
294
- */
295
- var prevItems = [];
296
- var nextItems = [];
297
- var count = 0;
298
- var items = getCarouselItems(trackRef.current);
299
-
300
- /**
301
- * Проходим по всему списку, суммируя ширины элементов,
302
- * пока не найдем один элемент, чей центр будет в центре карусели.
303
- */
304
- for (var itemIndex = 0; itemIndex < items.length; itemIndex++) {
305
- var _prevIndex$current;
306
- var item = items.item(itemIndex);
307
- if (item === null) {
308
- // eslint-disable-next-line no-continue
309
- continue;
310
- }
311
-
312
- /**
313
- * Для Ox - ширина, для Oy - высота.
314
- */
315
- var itemSize = item[axis === 'x' ? 'offsetWidth' : 'offsetHeight'];
316
-
317
- /**
318
- * Все элементы правее вьюпорта выпадают из процедуры.
319
- * Сравниваем по предыдущему элементу.
320
- * [ ... ] ...|n| <- Левый край элемента за пределами начала видимой части
321
- */
322
- if (itemEdge > scrollEdge) {
323
- if (scaleCallback && scaleResetCallback) {
324
- nextItems.push(item);
325
- }
326
- // eslint-disable-next-line no-continue
327
- continue;
328
- }
329
- itemEdge += itemSize;
330
-
331
- /**
332
- * Все элементы левее вьюпорта выпадают из процедуры.
333
- * Сравниваем по текущему элементу.
334
- * Правый край элемента за пределами начала видимой части -> |p|... [ ... ]
335
- */
336
- if (scrollPos > itemEdge) {
337
- if (scaleCallback && scaleResetCallback) {
338
- prevItems.push(item);
339
- }
340
- // eslint-disable-next-line no-continue
341
- continue;
342
- }
343
- var itemSlot = getItemSlot(itemIndex, itemEdge, itemSize, scrollPos, scrollSize, scrollAlign, (_prevIndex$current = prevIndex.current) !== null && _prevIndex$current !== void 0 ? _prevIndex$current : 0, offset.current);
344
- if (itemSlot !== null) {
345
- if (detectThreshold && Math.abs(itemSlot) <= detectThreshold) {
346
- onDetectActiveItem === null || onDetectActiveItem === void 0 || onDetectActiveItem(itemIndex);
347
- debouncedOnIndexChange === null || debouncedOnIndexChange === void 0 || debouncedOnIndexChange(itemIndex);
348
- }
349
- if (scaleCallback) {
350
- scaleCallback(item, itemSlot);
351
- /**
352
- * Количество айтемов в видимой части.
353
- */
354
- count++;
355
- }
356
- }
357
- }
358
- if (scaleCallback && scaleResetCallback) {
359
- window.requestAnimationFrame(function () {
360
- if (direction.current) {
361
- if (nextItems.length) {
362
- nextItems.splice(0, count).forEach(function (elem) {
363
- return scaleCallback(elem, count);
364
- });
365
- if (nextItems.length) {
366
- nextItems.splice(0, count).forEach(function (elem) {
367
- return scaleResetCallback(elem);
368
- });
369
- }
370
- }
371
- } else if (prevItems.length) {
372
- var prItemsRev = prevItems.reverse();
373
- prItemsRev.splice(0, count).forEach(function (elem) {
374
- return scaleCallback(elem, count * -1);
375
- });
376
- if (prItemsRev.length) {
377
- prItemsRev.splice(0, count).forEach(function (elem) {
378
- return scaleResetCallback(elem);
379
- });
380
- }
381
- }
382
- });
383
- }
384
- }, throttleMs);
385
- }, [axis, debouncedOnIndexChange, detectActive, detectThreshold, onDetectActiveItem, scaleCallback, scaleResetCallback, scrollAlign, throttleMs]);
386
-
387
- /**
388
- * Прокрутка до нужной позиции индекса.
389
- */
390
- var toIndex = useCallback(function (i) {
391
- var scrollEl = scrollRef.current;
392
- var items = trackRef.current ? getCarouselItems(trackRef.current) : null;
393
- if (scrollEl && items && items.length > 0 && i >= 0) {
394
- scrollToPos({
395
- scrollEl: scrollEl,
396
- pos: getCalculatedPos({
397
- scrollEl: scrollEl,
398
- items: items,
399
- axis: axis,
400
- index: i,
401
- offset: offset.current,
402
- scrollAlign: scrollAlign
403
- }),
404
- axis: axis,
405
- /**
406
- * Без анимации при переходе на другой конец списка
407
- */
408
- animated: animatedScrollByIndex && (prevIndex.current === null || Math.abs(i - prevIndex.current) !== items.length - 1)
409
- });
410
- prevIndex.current = i;
411
- }
412
- }, [animatedScrollByIndex, axis, scrollAlign]);
413
- useEffect(function () {
414
- if (scrollRef.current && trackRef.current) {
415
- offset.current = getCalculatedOffset(scrollRef.current, trackRef.current, axis);
416
- }
417
- }, [axis]);
418
-
419
- /**
420
- * Операции на маунте/анмаунте компонента.
421
- * Создать слушатели событи и т.п.
422
- */
423
- useEffect(function () {
424
- var carouselElement = scrollRef.current;
425
- if (carouselElement) {
426
- carouselElement.addEventListener('scroll', throttledDetectActiveItem);
427
- }
428
- return function () {
429
- if (carouselElement) {
430
- carouselElement.removeEventListener('scroll', throttledDetectActiveItem);
431
- }
432
- };
433
- }, [throttledDetectActiveItem]);
434
-
435
- /**
436
- * Нужно вызвать только при первом рендере
437
- */
438
- useEffect(function () {
439
- requestAnimationFrame(function () {
440
- /**
441
- * Прокрутка до начального индекса.
442
- */
443
- toIndex(index);
444
-
445
- /**
446
- * Если на момент запуска карусель уже находится на нужной позиции,
447
- * событие скролла не произойдет, не сработает и определение центра,
448
- * необходимо вызвать его вручную.
449
- */
450
- throttledDetectActiveItem();
451
- });
452
-
453
- // eslint-disable-next-line react-hooks/exhaustive-deps
454
- }, []);
455
-
456
- /**
457
- * Прокрутка до нужной позиции индекса, если индекс изменился.
458
- */
459
- useEffect(function () {
460
- if (index !== prevIndex.current) {
461
- toIndex(index);
462
- }
463
- }, [index, toIndex]);
464
- return {
465
- scrollRef: scrollRef,
466
- trackRef: trackRef
467
- };
468
- };
@@ -1,59 +0,0 @@
1
- function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
2
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
3
- function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
4
- function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
5
- function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
6
- function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
7
- import { useCallback, useEffect, useState } from 'react';
8
- var SCROLL_SPEED = 2;
9
- export var useDragScroll = function useDragScroll(scrollRef, isDragScrollDisabled) {
10
- var _useState = useState(false),
11
- _useState2 = _slicedToArray(_useState, 2),
12
- isDragging = _useState2[0],
13
- setDragging = _useState2[1];
14
- var _useState3 = useState(0),
15
- _useState4 = _slicedToArray(_useState3, 2),
16
- startX = _useState4[0],
17
- setStartX = _useState4[1];
18
- var _useState5 = useState(0),
19
- _useState6 = _slicedToArray(_useState5, 2),
20
- scrollLeft = _useState6[0],
21
- setScrollLeft = _useState6[1];
22
- var handleMouseMove = useCallback(function (e) {
23
- if (isDragging && scrollRef && scrollRef.current) {
24
- var dx = (e.clientX - startX) * SCROLL_SPEED;
25
- scrollRef.current.scrollLeft = scrollLeft - dx;
26
- }
27
- }, [scrollRef, scrollLeft, isDragging, startX]);
28
- var handleMouseUp = useCallback(function () {
29
- setDragging(false);
30
- if (scrollRef && scrollRef.current) {
31
- scrollRef.current.style.cursor = 'grab';
32
- }
33
- }, [scrollRef, setDragging]);
34
- var handleMouseDown = useCallback(function (e) {
35
- setDragging(true);
36
- if (scrollRef && scrollRef.current) {
37
- setStartX(e.clientX);
38
- setScrollLeft(scrollRef.current.scrollLeft);
39
- scrollRef.current.style.cursor = 'grabbing';
40
- }
41
- }, [scrollRef, setDragging, setStartX, setScrollLeft, handleMouseUp, handleMouseMove]);
42
- useEffect(function () {
43
- if (scrollRef && scrollRef.current && !isDragScrollDisabled) {
44
- scrollRef.current.style.userSelect = 'none';
45
- scrollRef.current.addEventListener('mousedown', handleMouseDown);
46
- scrollRef.current.addEventListener('mouseup', handleMouseUp);
47
- scrollRef.current.addEventListener('mouseleave', handleMouseUp);
48
- scrollRef.current.addEventListener('mousemove', handleMouseMove);
49
- }
50
- return function () {
51
- if (scrollRef && scrollRef.current && !isDragScrollDisabled) {
52
- scrollRef.current.removeEventListener('mousedown', handleMouseDown);
53
- scrollRef.current.removeEventListener('mouseup', handleMouseUp);
54
- scrollRef.current.removeEventListener('mouseleave', handleMouseUp);
55
- scrollRef.current.removeEventListener('mousemove', handleMouseMove);
56
- }
57
- };
58
- }, [scrollRef, handleMouseDown, handleMouseUp, handleMouseMove, isDragScrollDisabled]);
59
- };
@@ -1,4 +0,0 @@
1
- export var config = {
2
- defaults: {},
3
- variations: {}
4
- };
@@ -1,6 +0,0 @@
1
- import { carouselConfig, CarouselItem } from "../../../../components/Carousel";
2
- import { component, mergeConfig } from "../../../../engines";
3
- import { config } from "./Carousel.config";
4
- export var mergedConfig = /*#__PURE__*/mergeConfig(carouselConfig, config);
5
- export var Carousel = /*#__PURE__*/component(mergedConfig);
6
- export { CarouselItem };
@@ -1,80 +0,0 @@
1
- import * as React from 'react';
2
- import type { ComponentProps } from 'react';
3
- import type { Meta, StoryObj } from '@storybook/react';
4
- import styled from 'styled-components';
5
-
6
- import { WithTheme } from '../../../_helpers';
7
-
8
- import { Carousel, CarouselItem } from './Carousel';
9
-
10
- type StoryCarouselProps = ComponentProps<typeof Carousel>;
11
-
12
- const meta: Meta<StoryCarouselProps> = {
13
- title: 'b2c/Data Display/Carousel',
14
- component: Carousel,
15
- decorators: [WithTheme],
16
- argTypes: {
17
- align: {
18
- options: ['center', 'start', 'end'],
19
- control: {
20
- type: 'inline-radio',
21
- },
22
- },
23
- isDragScrollDisabled: {
24
- control: 'boolean',
25
- },
26
- },
27
- args: {
28
- align: 'center',
29
- isDragScrollDisabled: false,
30
- },
31
- parameters: {
32
- controls: {
33
- include: ['align', 'isDragScrollDisabled'],
34
- },
35
- },
36
- };
37
-
38
- export default meta;
39
-
40
- const items = Array(25)
41
- .fill({
42
- title: 'Заголовок',
43
- })
44
- .map(({ title }, i) => ({
45
- id: i,
46
- title: `${title} ${i}`,
47
- }));
48
-
49
- const StyledCard = styled.div`
50
- position: relative;
51
- border-radius: 8px;
52
- width: 350px;
53
- height: 50px;
54
- padding: 8px;
55
- background-color: #add8e6;
56
- `;
57
-
58
- const StoryDefault = ({ align, isDragScrollDisabled }: StoryCarouselProps) => {
59
- const [index, setIndex] = React.useState(0);
60
-
61
- return (
62
- <Carousel
63
- index={index}
64
- detectActive
65
- onIndexChange={setIndex}
66
- scrollAlign={align}
67
- isDragScrollDisabled={isDragScrollDisabled}
68
- >
69
- {items.map((item, i) => (
70
- <CarouselItem key={i} style={{ padding: '0 0.5rem' }} scrollSnapAlign={align}>
71
- <StyledCard>{item.title}</StyledCard>
72
- </CarouselItem>
73
- ))}
74
- </Carousel>
75
- );
76
- };
77
-
78
- export const Default: StoryObj<StoryCarouselProps> = {
79
- render: (args) => <StoryDefault {...args} />,
80
- };
@@ -1,4 +0,0 @@
1
- export var config = {
2
- defaults: {},
3
- variations: {}
4
- };
@@ -1,6 +0,0 @@
1
- import { carouselConfig, CarouselItem } from "../../../../components/Carousel";
2
- import { component, mergeConfig } from "../../../../engines";
3
- import { config } from "./Carousel.config";
4
- export var mergedConfig = /*#__PURE__*/mergeConfig(carouselConfig, config);
5
- export var Carousel = /*#__PURE__*/component(mergedConfig);
6
- export { CarouselItem };