@shoutem/ui 9.2.1 → 9.3.0-rc.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.
@@ -0,0 +1,40 @@
1
+ import {
2
+ getNearestSnapIndex,
3
+ getSnapInputRange,
4
+ resolveSnapOffsets,
5
+ } from '../components/ImageCarousel/helpers';
6
+
7
+ describe('ImageCarousel helpers', () => {
8
+ it('returns no offsets until the container is measured', () => {
9
+ expect(
10
+ resolveSnapOffsets({
11
+ itemCount: 3,
12
+ containerWidth: 0,
13
+ cardWidth: 100,
14
+ cardSpacing: 10,
15
+ }),
16
+ ).toEqual([]);
17
+ });
18
+
19
+ it('clamps first and last offsets to the scrollable range', () => {
20
+ const offsets = resolveSnapOffsets({
21
+ itemCount: 3,
22
+ containerWidth: 300,
23
+ cardWidth: 100,
24
+ cardSpacing: 10,
25
+ });
26
+
27
+ expect(offsets[0]).toBe(0);
28
+ expect(offsets[2]).toBe(30);
29
+ });
30
+
31
+ it('finds the nearest snap index', () => {
32
+ expect(getNearestSnapIndex([0, 110, 220], 100)).toBe(1);
33
+ expect(getNearestSnapIndex([], 100)).toBe(0);
34
+ });
35
+
36
+ it('builds a strictly increasing input range', () => {
37
+ expect(getSnapInputRange([0, 0, 50], 0, 110)).toEqual([-110, 0, 110]);
38
+ expect(getSnapInputRange([0, 50], 1, 110)).toEqual([0, 50, 160]);
39
+ });
40
+ });
@@ -0,0 +1,424 @@
1
+ import React, {
2
+ useCallback,
3
+ useEffect,
4
+ useMemo,
5
+ useRef,
6
+ useState,
7
+ } from 'react';
8
+ import { Animated } from 'react-native';
9
+ import _ from 'lodash';
10
+ import PropTypes from 'prop-types';
11
+ import { connectStyle } from '@shoutem/theme';
12
+ import { Icon } from '../Icon';
13
+ import { PageIndicators } from '../PageIndicators';
14
+ import { TouchableOpacity } from '../TouchableOpacity';
15
+ import { View } from '../View';
16
+ import {
17
+ getNearestSnapIndex,
18
+ getSnapInputRange,
19
+ resolveSnapOffsets,
20
+ } from './helpers';
21
+ import { ImageCarouselSlide } from './ImageCarouselSlide';
22
+
23
+ /**
24
+ * Default `keyExtractor` used when the caller doesn't provide one - falls back to
25
+ * the item's own `id`, then its index.
26
+ *
27
+ * @param {Object} item The slide data item.
28
+ * @param {number} index The item's index in `data`.
29
+ * @returns {string} A stable key for the slide.
30
+ */
31
+ const defaultKeyExtractor = (item, index) => item.id ?? String(index);
32
+
33
+ /**
34
+ * Default `getImageSource` used when the caller doesn't provide one - reads the
35
+ * item's `source` field.
36
+ *
37
+ * @param {Object} item The slide data item.
38
+ * @returns {Object|number} A React Native image source.
39
+ */
40
+ const defaultGetImageSource = item => item.source;
41
+
42
+ /**
43
+ * A horizontally-swipeable image carousel: pages through `data` as fixed-width
44
+ * image cards that snap one by one, with neighbouring cards peeking in and
45
+ * scaling/fading with the scroll position. The first and last slides rest
46
+ * against the list edges; every other slide rests centered. Also owns page
47
+ * indicator dots, arrows, and autoplay. Renders a placeholder until it has
48
+ * measured its own width, and nothing at all when `data` is empty. Callers
49
+ * customize slides through `renderOverlay` and `renderImagePlaceholder`.
50
+ *
51
+ * @param {Array} [data] The slides to render.
52
+ * @param {Function} [getImageSource] `(item) => imageSource`. Defaults to the
53
+ * item's `source` field.
54
+ * @param {Function} [keyExtractor] `(item, index) => string`. Defaults to the
55
+ * item's `id`, falling back to its index.
56
+ * @param {number} [cardAspectRatio] The shape of every slide as width / height.
57
+ * @param {number} [initialIndex] The 0-based slide index to open on, applied by
58
+ * scrolling once the carousel has measured its width.
59
+ * @param {boolean} [autoplay] Whether to automatically advance slides on a
60
+ * timer. Paused while the user is dragging.
61
+ * @param {number} [autoplayIntervalMs] The autoplay interval, in milliseconds.
62
+ * @param {boolean} [showPageIndicators] Whether to render the dot indicators.
63
+ * Hidden automatically when there's only one slide.
64
+ * @param {number} [maxPageIndicators] The maximum number of dots to render.
65
+ * @param {boolean} [showArrows] Whether to render left/right arrow buttons.
66
+ * Each arrow hides at its own end of the list, so there is no wrap-around.
67
+ * @param {Function} [renderOverlay] `(item, { index, isActive }) => JSX.Element`
68
+ * rendered inside the slide card, on top of the image.
69
+ * @param {Function} [renderImagePlaceholder] `(item, { index }) => JSX.Element`
70
+ * rendered over a slide's image until it has loaded.
71
+ * @param {Function} [renderPlaceholder] `({ cardAspectRatio }) => JSX.Element`
72
+ * rendered instead of the list until the width is measured. Defaults to an
73
+ * empty view with the height the loaded carousel will have.
74
+ * @param {Function} [onIndexChange] `(index) => void`, called when the active
75
+ * slide changes (not on mount).
76
+ * @param {Object} style Resolved styles, injected by connectStyle. Geometry is
77
+ * read from the `cardWidth`, `cardSpacing`, `inactiveScale` and
78
+ * `inactiveOpacity` scalars. A `style` prop passed by the caller is merged
79
+ * over the theme styles by connectStyle.
80
+ * @returns {JSX.Element|null}
81
+ */
82
+ const ImageCarousel = ({
83
+ data,
84
+ getImageSource,
85
+ keyExtractor,
86
+ cardAspectRatio,
87
+ initialIndex,
88
+ autoplay,
89
+ autoplayIntervalMs,
90
+ showPageIndicators,
91
+ maxPageIndicators,
92
+ showArrows,
93
+ renderOverlay,
94
+ renderImagePlaceholder,
95
+ renderPlaceholder,
96
+ onIndexChange,
97
+ style,
98
+ }) => {
99
+ const listRef = useRef(null);
100
+ const isFirstSnapRender = useRef(true);
101
+ const isFirstIndexRender = useRef(true);
102
+ const scrollX = useRef(new Animated.Value(0)).current;
103
+
104
+ const [containerWidth, setContainerWidth] = useState(0);
105
+ const [activeIndex, setActiveIndex] = useState(initialIndex);
106
+ const [isInteracting, setIsInteracting] = useState(false);
107
+
108
+ const { cardWidth, cardSpacing, inactiveScale, inactiveOpacity } = style;
109
+ const snapInterval = cardWidth + cardSpacing;
110
+ const snapOffsets = useMemo(
111
+ () =>
112
+ resolveSnapOffsets({
113
+ itemCount: data.length,
114
+ containerWidth,
115
+ cardWidth,
116
+ cardSpacing,
117
+ }),
118
+ [data.length, containerWidth, cardWidth, cardSpacing],
119
+ );
120
+
121
+ const itemWrapperStyle = useMemo(
122
+ () => ({
123
+ width: cardWidth,
124
+ marginHorizontal: cardSpacing / 2,
125
+ aspectRatio: cardAspectRatio,
126
+ }),
127
+ [cardWidth, cardSpacing, cardAspectRatio],
128
+ );
129
+
130
+ const scrollToIndex = useCallback(
131
+ index => {
132
+ listRef.current?.scrollToOffset({
133
+ offset: snapOffsets[index] ?? 0,
134
+ animated: true,
135
+ });
136
+ },
137
+ [snapOffsets],
138
+ );
139
+
140
+ useEffect(() => {
141
+ if (!autoplay || data.length < 2 || !snapInterval || isInteracting) {
142
+ return undefined;
143
+ }
144
+
145
+ const intervalId = setInterval(() => {
146
+ scrollToIndex((activeIndex + 1) % data.length);
147
+ }, autoplayIntervalMs);
148
+
149
+ return () => clearInterval(intervalId);
150
+ }, [
151
+ autoplay,
152
+ autoplayIntervalMs,
153
+ activeIndex,
154
+ isInteracting,
155
+ data.length,
156
+ snapInterval,
157
+ scrollToIndex,
158
+ ]);
159
+
160
+ useEffect(() => {
161
+ if (isFirstIndexRender.current) {
162
+ isFirstIndexRender.current = false;
163
+ return;
164
+ }
165
+
166
+ if (onIndexChange) {
167
+ onIndexChange(activeIndex);
168
+ }
169
+ // eslint-disable-next-line react-hooks/exhaustive-deps
170
+ }, [activeIndex]);
171
+
172
+ useEffect(() => {
173
+ if (isFirstSnapRender.current) {
174
+ isFirstSnapRender.current = false;
175
+ return;
176
+ }
177
+
178
+ if (!snapInterval || containerWidth === 0) {
179
+ return;
180
+ }
181
+
182
+ // Positions the list on the active slide whenever the measured width
183
+ // changes: the first measured render lands on `initialIndex` (the list
184
+ // deliberately has no `initialScrollIndex` - the list's own mount-time
185
+ // scroll pass renders a frame with the content shifted a full card before
186
+ // it self-corrects), and a device rotation re-snaps to the slide that was
187
+ // already active, read at fire time (as are the snap offsets).
188
+ listRef.current?.scrollToOffset({
189
+ offset: snapOffsets[activeIndex] ?? 0,
190
+ animated: false,
191
+ });
192
+ // eslint-disable-next-line react-hooks/exhaustive-deps
193
+ }, [containerWidth]);
194
+
195
+ const handleLayout = useCallback(event => {
196
+ setContainerWidth(event.nativeEvent.layout.width);
197
+ }, []);
198
+
199
+ const handleScroll = useCallback(
200
+ event => {
201
+ if (!snapInterval) {
202
+ return;
203
+ }
204
+
205
+ const nextIndex = getNearestSnapIndex(
206
+ snapOffsets,
207
+ event.nativeEvent.contentOffset.x,
208
+ );
209
+
210
+ setActiveIndex(prevIndex =>
211
+ prevIndex === nextIndex ? prevIndex : nextIndex,
212
+ );
213
+ },
214
+ [snapInterval, snapOffsets],
215
+ );
216
+
217
+ const handleScrollEvent = useMemo(
218
+ () =>
219
+ Animated.event([{ nativeEvent: { contentOffset: { x: scrollX } } }], {
220
+ useNativeDriver: true,
221
+ listener: handleScroll,
222
+ }),
223
+ [scrollX, handleScroll],
224
+ );
225
+
226
+ const handleScrollBeginDrag = useCallback(() => {
227
+ setIsInteracting(true);
228
+ }, []);
229
+
230
+ const handleScrollEndDrag = useCallback(() => {
231
+ setIsInteracting(false);
232
+ }, []);
233
+
234
+ const handleMomentumScrollEnd = useCallback(() => {
235
+ setIsInteracting(false);
236
+ }, []);
237
+
238
+ const handlePrevArrowPress = useCallback(() => {
239
+ scrollToIndex(Math.max(activeIndex - 1, 0));
240
+ }, [activeIndex, scrollToIndex]);
241
+
242
+ const handleNextArrowPress = useCallback(() => {
243
+ scrollToIndex(Math.min(activeIndex + 1, data.length - 1));
244
+ }, [activeIndex, data.length, scrollToIndex]);
245
+
246
+ const getItemLayout = useCallback(
247
+ (_data, index) => ({
248
+ length: snapInterval,
249
+ offset: snapInterval * index,
250
+ index,
251
+ }),
252
+ [snapInterval],
253
+ );
254
+
255
+ const renderSlide = useCallback(
256
+ ({ item, index }) => {
257
+ const inputRange = getSnapInputRange(snapOffsets, index, snapInterval);
258
+ // Scaling a card down leaves (1 - scale) * cardWidth / 2 of empty space
259
+ // on each of its sides, since the layout slot keeps the full width. The
260
+ // translate pulls a shrunken neighbour back toward the focused card by
261
+ // exactly that amount, so the visible gap stays `cardSpacing`.
262
+ const scaleShift = ((1 - inactiveScale) * cardWidth) / 2;
263
+ const animatedStyle = {
264
+ opacity: scrollX.interpolate({
265
+ inputRange,
266
+ outputRange: [inactiveOpacity, 1, inactiveOpacity],
267
+ extrapolate: 'clamp',
268
+ }),
269
+ transform: [
270
+ {
271
+ translateX: scrollX.interpolate({
272
+ inputRange,
273
+ outputRange: [-scaleShift, 0, scaleShift],
274
+ extrapolate: 'clamp',
275
+ }),
276
+ },
277
+ {
278
+ scale: scrollX.interpolate({
279
+ inputRange,
280
+ outputRange: [inactiveScale, 1, inactiveScale],
281
+ extrapolate: 'clamp',
282
+ }),
283
+ },
284
+ ],
285
+ };
286
+
287
+ return (
288
+ <Animated.View style={[itemWrapperStyle, animatedStyle]}>
289
+ <ImageCarouselSlide
290
+ item={item}
291
+ index={index}
292
+ isActive={index === activeIndex}
293
+ source={getImageSource(item)}
294
+ renderOverlay={renderOverlay}
295
+ renderImagePlaceholder={renderImagePlaceholder}
296
+ />
297
+ </Animated.View>
298
+ );
299
+ },
300
+ [
301
+ getImageSource,
302
+ renderOverlay,
303
+ renderImagePlaceholder,
304
+ itemWrapperStyle,
305
+ scrollX,
306
+ snapOffsets,
307
+ snapInterval,
308
+ cardWidth,
309
+ inactiveScale,
310
+ inactiveOpacity,
311
+ activeIndex,
312
+ ],
313
+ );
314
+
315
+ if (_.isEmpty(data)) {
316
+ return null;
317
+ }
318
+
319
+ const placeholderStyle = [
320
+ style.placeholder,
321
+ { height: cardWidth / cardAspectRatio },
322
+ ];
323
+ const placeholder = renderPlaceholder ? (
324
+ renderPlaceholder({ cardAspectRatio })
325
+ ) : (
326
+ <View style={placeholderStyle} />
327
+ );
328
+
329
+ return (
330
+ <View style={style.container} onLayout={handleLayout}>
331
+ {containerWidth === 0 && placeholder}
332
+ {containerWidth > 0 && (
333
+ <Animated.FlatList
334
+ ref={listRef}
335
+ horizontal
336
+ data={data}
337
+ renderItem={renderSlide}
338
+ keyExtractor={keyExtractor}
339
+ showsHorizontalScrollIndicator={false}
340
+ snapToOffsets={snapOffsets}
341
+ snapToAlignment="start"
342
+ decelerationRate="fast"
343
+ disableIntervalMomentum
344
+ getItemLayout={getItemLayout}
345
+ scrollEnabled={data.length > 1}
346
+ bounces={false}
347
+ scrollEventThrottle={16}
348
+ removeClippedSubviews={false}
349
+ onScroll={handleScrollEvent}
350
+ onScrollBeginDrag={handleScrollBeginDrag}
351
+ onScrollEndDrag={handleScrollEndDrag}
352
+ onMomentumScrollEnd={handleMomentumScrollEnd}
353
+ contentContainerStyle={style.listContent}
354
+ />
355
+ )}
356
+ {showPageIndicators && data.length > 1 && (
357
+ <PageIndicators
358
+ activeIndex={activeIndex}
359
+ count={data.length}
360
+ maxCount={maxPageIndicators}
361
+ style={style.pageIndicators}
362
+ />
363
+ )}
364
+ {showArrows && activeIndex > 0 && (
365
+ <TouchableOpacity
366
+ style={style.leftArrow}
367
+ onPress={handlePrevArrowPress}
368
+ >
369
+ <Icon name="left-arrow" style={style.arrowIcon} />
370
+ </TouchableOpacity>
371
+ )}
372
+ {showArrows && activeIndex < data.length - 1 && (
373
+ <TouchableOpacity
374
+ style={style.rightArrow}
375
+ onPress={handleNextArrowPress}
376
+ >
377
+ <Icon name="right-arrow" style={style.arrowIcon} />
378
+ </TouchableOpacity>
379
+ )}
380
+ </View>
381
+ );
382
+ };
383
+
384
+ ImageCarousel.propTypes = {
385
+ autoplay: PropTypes.bool,
386
+ autoplayIntervalMs: PropTypes.number,
387
+ cardAspectRatio: PropTypes.number,
388
+ data: PropTypes.array,
389
+ getImageSource: PropTypes.func,
390
+ initialIndex: PropTypes.number,
391
+ keyExtractor: PropTypes.func,
392
+ maxPageIndicators: PropTypes.number,
393
+ renderImagePlaceholder: PropTypes.func,
394
+ renderOverlay: PropTypes.func,
395
+ renderPlaceholder: PropTypes.func,
396
+ showArrows: PropTypes.bool,
397
+ showPageIndicators: PropTypes.bool,
398
+ style: PropTypes.object,
399
+ onIndexChange: PropTypes.func,
400
+ };
401
+
402
+ ImageCarousel.defaultProps = {
403
+ autoplay: false,
404
+ autoplayIntervalMs: 5000,
405
+ cardAspectRatio: 16 / 9,
406
+ data: [],
407
+ getImageSource: defaultGetImageSource,
408
+ initialIndex: 0,
409
+ keyExtractor: defaultKeyExtractor,
410
+ maxPageIndicators: 10,
411
+ renderImagePlaceholder: undefined,
412
+ renderOverlay: undefined,
413
+ renderPlaceholder: undefined,
414
+ showArrows: false,
415
+ showPageIndicators: true,
416
+ style: {},
417
+ onIndexChange: undefined,
418
+ };
419
+
420
+ const StyledImageCarousel = connectStyle('shoutem.ui.ImageCarousel')(
421
+ ImageCarousel,
422
+ );
423
+
424
+ export { StyledImageCarousel as ImageCarousel };
@@ -0,0 +1,84 @@
1
+ import React, { useCallback, useState } from 'react';
2
+ import PropTypes from 'prop-types';
3
+ import { connectStyle } from '@shoutem/theme';
4
+ import { Image } from '../Image';
5
+ import { View } from '../View';
6
+
7
+ /**
8
+ * A single ImageCarousel slide: a rounded card that fills its parent, holding a
9
+ * cover image and, on top of it, whatever the caller renders as overlay. While
10
+ * the image is loading, the caller's image placeholder is rendered above it.
11
+ *
12
+ * @param {Object} item The slide data item, forwarded to the render callbacks.
13
+ * @param {number} index The slide's index in the carousel data.
14
+ * @param {boolean} isActive Whether this slide is the carousel's active one.
15
+ * @param {Object} source A React Native image source for the slide's image.
16
+ * @param {Function} [renderOverlay] `(item, { index, isActive }) => JSX.Element`
17
+ * rendered on top of the image.
18
+ * @param {Function} [renderImagePlaceholder] `(item, { index }) => JSX.Element`
19
+ * rendered over the image until it finishes loading.
20
+ * @param {Object} style Resolved styles, injected by connectStyle.
21
+ * @returns {JSX.Element}
22
+ */
23
+ const ImageCarouselSlide = ({
24
+ item,
25
+ index,
26
+ isActive,
27
+ source,
28
+ renderOverlay,
29
+ renderImagePlaceholder,
30
+ style,
31
+ }) => {
32
+ const [isImageLoaded, setImageLoaded] = useState(false);
33
+
34
+ const handleImageLoadEnd = useCallback(() => {
35
+ setImageLoaded(true);
36
+ }, []);
37
+
38
+ const placeholder =
39
+ !isImageLoaded && renderImagePlaceholder
40
+ ? renderImagePlaceholder(item, { index })
41
+ : null;
42
+ const overlay = renderOverlay
43
+ ? renderOverlay(item, { index, isActive })
44
+ : null;
45
+
46
+ return (
47
+ <View style={style.card}>
48
+ <Image
49
+ source={source}
50
+ style={style.image}
51
+ resizeMode="cover"
52
+ onLoadEnd={handleImageLoadEnd}
53
+ />
54
+ {placeholder}
55
+ {overlay}
56
+ </View>
57
+ );
58
+ };
59
+
60
+ ImageCarouselSlide.propTypes = {
61
+ index: PropTypes.number,
62
+ isActive: PropTypes.bool,
63
+ item: PropTypes.object,
64
+ renderImagePlaceholder: PropTypes.func,
65
+ renderOverlay: PropTypes.func,
66
+ source: PropTypes.oneOfType([PropTypes.object, PropTypes.number]),
67
+ style: PropTypes.object,
68
+ };
69
+
70
+ ImageCarouselSlide.defaultProps = {
71
+ index: 0,
72
+ isActive: false,
73
+ item: undefined,
74
+ renderImagePlaceholder: undefined,
75
+ renderOverlay: undefined,
76
+ source: undefined,
77
+ style: {},
78
+ };
79
+
80
+ const StyledImageCarouselSlide = connectStyle('shoutem.ui.ImageCarouselSlide')(
81
+ ImageCarouselSlide,
82
+ );
83
+
84
+ export { StyledImageCarouselSlide as ImageCarouselSlide };
@@ -0,0 +1,88 @@
1
+ import _ from 'lodash';
2
+
3
+ /**
4
+ * Computes the scroll offset each slide snaps to. Every slide rests centered in
5
+ * the container, except that the offsets are clamped to the scrollable range, so
6
+ * the first slide rests against the left edge and the last against the right.
7
+ *
8
+ * @param {Object} options
9
+ * @param {number} options.itemCount The number of slides.
10
+ * @param {number} options.containerWidth The measured container width.
11
+ * @param {number} options.cardWidth The width of a card.
12
+ * @param {number} options.cardSpacing The total horizontal gap around a card.
13
+ * @param {number} [options.edgeInset] The list content's own horizontal padding.
14
+ * @returns {number[]} One snap offset per slide; empty until the container is
15
+ * measured or when there are no slides.
16
+ */
17
+ export function resolveSnapOffsets({
18
+ itemCount,
19
+ containerWidth,
20
+ cardWidth,
21
+ cardSpacing,
22
+ edgeInset = 0,
23
+ }) {
24
+ if (!containerWidth || !itemCount) {
25
+ return [];
26
+ }
27
+
28
+ const snapInterval = cardWidth + cardSpacing;
29
+ const contentWidth = itemCount * snapInterval + 2 * edgeInset;
30
+ const maxOffset = Math.max(contentWidth - containerWidth, 0);
31
+
32
+ return _.times(itemCount, index => {
33
+ const centeredOffset =
34
+ edgeInset +
35
+ index * snapInterval +
36
+ cardSpacing / 2 -
37
+ (containerWidth - cardWidth) / 2;
38
+
39
+ return _.clamp(centeredOffset, 0, maxOffset);
40
+ });
41
+ }
42
+
43
+ /**
44
+ * Finds the slide whose snap offset is closest to the given scroll offset.
45
+ *
46
+ * @param {number[]} snapOffsets The slides' snap offsets.
47
+ * @param {number} offsetX The current horizontal scroll offset.
48
+ * @returns {number} The nearest slide index (lowest on ties); 0 when empty.
49
+ */
50
+ export function getNearestSnapIndex(snapOffsets, offsetX) {
51
+ let nearestIndex = 0;
52
+ let nearestDistance = Infinity;
53
+
54
+ _.forEach(snapOffsets, (snapOffset, index) => {
55
+ const distance = Math.abs(snapOffset - offsetX);
56
+
57
+ if (distance < nearestDistance) {
58
+ nearestDistance = distance;
59
+ nearestIndex = index;
60
+ }
61
+ });
62
+
63
+ return nearestIndex;
64
+ }
65
+
66
+ /**
67
+ * Builds the strictly increasing `[previous, current, next]` input range used to
68
+ * animate a card as the scroll position approaches and leaves its snap offset.
69
+ * A missing or equal (clamped) neighbour is replaced by `current ∓ snapInterval`.
70
+ *
71
+ * @param {number[]} snapOffsets The slides' snap offsets.
72
+ * @param {number} index The card's slide index.
73
+ * @param {number} snapInterval Distance between two card centers.
74
+ * @returns {number[]} The three-value input range.
75
+ */
76
+ export function getSnapInputRange(snapOffsets, index, snapInterval) {
77
+ const current = snapOffsets[index] ?? index * snapInterval;
78
+ const previous = snapOffsets[index - 1];
79
+ const next = snapOffsets[index + 1];
80
+
81
+ return [
82
+ previous === undefined || previous >= current
83
+ ? current - snapInterval
84
+ : previous,
85
+ current,
86
+ next === undefined || next <= current ? current + snapInterval : next,
87
+ ];
88
+ }
@@ -0,0 +1 @@
1
+ export { ImageCarousel } from './ImageCarousel';
@@ -14,11 +14,25 @@ class PageIndicators extends PureComponent {
14
14
  autoBindReact(this);
15
15
  }
16
16
 
17
- renderPageIndicator(index, count, activeIndex, indicatorStyle) {
17
+ /**
18
+ * Renders a single dot. The dot reads its look from the explicit
19
+ * `indicator` / `selectedIndicator` style keys; the legacy `selected`
20
+ * styleName is still applied so themes that target the dot through an
21
+ * `indicatorContainer['shoutem.ui.View']` selector keep working.
22
+ *
23
+ * @param {number} index The dot's index.
24
+ * @param {boolean} isSelected Whether the dot represents the active page.
25
+ * @returns {JSX.Element}
26
+ */
27
+ renderPageIndicator(index, isSelected) {
18
28
  const { style } = this.props;
29
+ const indicatorStyle = isSelected
30
+ ? { ...style.indicator, ...style.selectedIndicator }
31
+ : style.indicator;
32
+
19
33
  return (
20
34
  <View style={style.indicatorContainer} key={`pageIndicator${index}`}>
21
- <View styleName={indicatorStyle} />
35
+ <View styleName={isSelected ? 'selected' : ''} style={indicatorStyle} />
22
36
  </View>
23
37
  );
24
38
  }
@@ -30,26 +44,12 @@ class PageIndicators extends PureComponent {
30
44
  const maxIndicatorsCount = Math.min(count, maxCount);
31
45
 
32
46
  for (let i = 0; i < maxIndicatorsCount; i += 1) {
33
- let indicatorStyle = '';
34
-
35
- if (activeIndex === i) {
36
- // If currently selected index matches index of page indicator that is rendered
37
- // then we should apply different styling
38
- indicatorStyle = 'selected';
39
- } else if (activeIndex >= i && maxIndicatorsCount - 1 === i) {
40
- // If currently selected index exceeds over number of indicators,
41
- // we should treat last indicator as selected one
42
- indicatorStyle = 'selected';
43
- }
47
+ // The dot matching the active index is selected; when the active index
48
+ // exceeds the number of rendered dots, the last dot stands in for it.
49
+ const isSelected =
50
+ activeIndex === i || (activeIndex >= i && maxIndicatorsCount - 1 === i);
44
51
 
45
- pageIndicators.push(
46
- this.renderPageIndicator(
47
- i,
48
- maxIndicatorsCount,
49
- activeIndex,
50
- indicatorStyle,
51
- ),
52
- );
52
+ pageIndicators.push(this.renderPageIndicator(i, isSelected));
53
53
  }
54
54
 
55
55
  return <View style={style.container}>{pageIndicators}</View>;
package/index.js CHANGED
@@ -17,6 +17,7 @@ export {
17
17
 
18
18
  // Services
19
19
  export {
20
+ createLayeredResolver,
20
21
  createScopedResolver,
21
22
  resolveVariable,
22
23
  ThemeVariableResolver,
@@ -40,6 +41,7 @@ export { HorizontalPager } from './components/HorizontalPager';
40
41
  export { Icon, registerIcons } from './components/Icon';
41
42
  export { Image } from './components/Image';
42
43
  export { ImageBackground } from './components/ImageBackground';
44
+ export { ImageCarousel } from './components/ImageCarousel';
43
45
  export { ImageGallery } from './components/ImageGallery';
44
46
  export { ImageGalleryOverlay } from './components/ImageGalleryOverlay';
45
47
  export { ImagePreview } from './components/ImagePreview';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shoutem/ui",
3
- "version": "9.2.1",
3
+ "version": "9.3.0-rc.0",
4
4
  "description": "Styleable set of components for React Native applications",
5
5
  "scripts": {
6
6
  "lint": "eslint .",
package/services/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  export { isAndroid, isIos, isWeb } from './platform';
2
2
  export { unavailableInWeb } from './unavailableInWeb';
3
3
  export {
4
+ createLayeredResolver,
4
5
  createScopedResolver,
5
6
  defaultResolver,
6
7
  resolveVariable,
@@ -3,6 +3,41 @@ import autoBind from 'auto-bind';
3
3
 
4
4
  const THEME_EXTENSION_SCOPE = 'shoutem.theme';
5
5
 
6
+ // A theme value starting with this prefix is a reference to another theme
7
+ // variable (e.g. `@paperColor`, `@text.fontFamily`), not a literal.
8
+ const REFERENCE_PREFIX = '@';
9
+
10
+ // How many references may be followed in a row before resolution gives up,
11
+ // which also stops reference cycles (`a -> b -> a`).
12
+ const MAX_REFERENCE_DEPTH = 5;
13
+
14
+ // How deep nested theme objects are scanned for references. Real theme
15
+ // variables are shallow; the cap only guards against self-referencing objects.
16
+ const MAX_OBJECT_DEPTH = 10;
17
+
18
+ /**
19
+ * Checks whether a value is a reference to another theme variable.
20
+ *
21
+ * @param {*} value The value to check.
22
+ * @returns {boolean} True for strings like `@paperColor`.
23
+ */
24
+ const isReference = value =>
25
+ _.isString(value) &&
26
+ value.length > REFERENCE_PREFIX.length &&
27
+ _.startsWith(value, REFERENCE_PREFIX);
28
+
29
+ /**
30
+ * Merges plain objects into a fresh one. Unlike a plain `_.merge`, arrays from
31
+ * a later source replace the earlier array instead of being merged by index.
32
+ *
33
+ * @param {...Object} sources The objects to merge, later ones win.
34
+ * @returns {Object} The merged object.
35
+ */
36
+ const mergeReplacingArrays = (...sources) =>
37
+ _.mergeWith({}, ...sources, (objValue, srcValue) =>
38
+ _.isArray(srcValue) ? srcValue : undefined,
39
+ );
40
+
6
41
  export class ThemeVariableResolver {
7
42
  constructor(variables) {
8
43
  this.variables = { ...variables };
@@ -14,6 +49,102 @@ export class ThemeVariableResolver {
14
49
  this.variables = { ...variables };
15
50
  }
16
51
 
52
+ /**
53
+ * Reads a variable without dereferencing it: first from the given scope,
54
+ * then from the theme root.
55
+ *
56
+ * @param {string} scope Dotted extension scope, e.g. `shoutem.widgets`.
57
+ * @param {string} variable Dotted variable path, e.g. `titleFont.color`.
58
+ * @returns {*} The stored value, tokens such as `@paperColor` untouched.
59
+ */
60
+ getRawScopedVariable(scope, variable) {
61
+ const scopePath = _.split(scope, '.');
62
+ const variablePath = _.split(variable, '.');
63
+
64
+ return _.get(
65
+ this.variables,
66
+ [...scopePath, ...variablePath],
67
+ _.get(this.variables, variablePath),
68
+ );
69
+ }
70
+
71
+ /**
72
+ * Follows a reference token (`@name`) through the scope tier and then the
73
+ * theme root, following further references up to `MAX_REFERENCE_DEPTH` hops.
74
+ *
75
+ * @param {string} scope Dotted extension scope the lookup starts from.
76
+ * @param {string} reference The reference token, including the `@` prefix.
77
+ * @param {number} depth How many references were followed already.
78
+ * @returns {*} The resolved value, or `undefined` when the reference cannot
79
+ * be resolved (missing variable, or the depth limit was hit).
80
+ */
81
+ resolveReference(scope, reference, depth) {
82
+ if (depth >= MAX_REFERENCE_DEPTH) {
83
+ return undefined;
84
+ }
85
+
86
+ const target = this.getRawScopedVariable(
87
+ scope,
88
+ reference.slice(REFERENCE_PREFIX.length),
89
+ );
90
+
91
+ return this.dereferenceValue(scope, target, depth + 1, false);
92
+ }
93
+
94
+ /**
95
+ * Replaces reference tokens in a value. A string token is resolved, a plain
96
+ * object gets its leaves dereferenced. Objects are copied only when a leaf
97
+ * actually changed, so untouched theme objects keep their identity.
98
+ *
99
+ * @param {string} scope Dotted extension scope references are resolved from.
100
+ * @param {*} value The value to dereference.
101
+ * @param {number} depth How many references were followed already.
102
+ * @param {boolean} keepUnresolved When true an unresolvable token stays as
103
+ * it is (backwards compatible reads); when false it is dropped (becomes
104
+ * `undefined`, or is removed from its parent object).
105
+ * @param {number} level How deep inside nested objects the value is.
106
+ * @returns {*} The dereferenced value.
107
+ */
108
+ dereferenceValue(scope, value, depth = 0, keepUnresolved = true, level = 0) {
109
+ if (isReference(value)) {
110
+ const resolved = this.resolveReference(scope, value, depth);
111
+
112
+ return resolved === undefined && keepUnresolved ? value : resolved;
113
+ }
114
+
115
+ if (!_.isPlainObject(value) || level >= MAX_OBJECT_DEPTH) {
116
+ return value;
117
+ }
118
+
119
+ let _result = value;
120
+
121
+ _.forOwn(value, (leaf, key) => {
122
+ const resolved = this.dereferenceValue(
123
+ scope,
124
+ leaf,
125
+ depth,
126
+ keepUnresolved,
127
+ level + 1,
128
+ );
129
+
130
+ if (resolved === leaf) {
131
+ return;
132
+ }
133
+
134
+ if (_result === value) {
135
+ _result = { ...value };
136
+ }
137
+
138
+ if (resolved === undefined) {
139
+ delete _result[key];
140
+ } else {
141
+ _result[key] = resolved;
142
+ }
143
+ });
144
+
145
+ return _result;
146
+ }
147
+
17
148
  getScopedVariable(scope, variable) {
18
149
  if (!this.variables || _.isEmpty(this.variables)) {
19
150
  throw new Error(
@@ -21,13 +152,9 @@ export class ThemeVariableResolver {
21
152
  );
22
153
  }
23
154
 
24
- const scopePath = _.split(scope, '.');
25
- const variablePath = _.split(variable, '.');
26
-
27
- return _.get(
28
- this.variables,
29
- [...scopePath, ...variablePath],
30
- _.get(this.variables, variablePath)
155
+ return this.dereferenceValue(
156
+ scope,
157
+ this.getRawScopedVariable(scope, variable),
31
158
  );
32
159
  }
33
160
 
@@ -63,6 +190,121 @@ export class ThemeVariableResolver {
63
190
  return undefined;
64
191
  };
65
192
  }
193
+
194
+ /**
195
+ * Resolves an override value read from a layer: a reference token is
196
+ * followed, a plain object has its leaves resolved and its unset (`null` /
197
+ * `undefined`) or unresolvable leaves removed, so it can be merged over an
198
+ * inherited object without wiping fields.
199
+ *
200
+ * @param {string} scope Dotted extension scope references are resolved from.
201
+ * @param {*} value The raw override value.
202
+ * @param {number} level How deep inside nested objects the value is.
203
+ * @returns {*} The resolved override; `undefined` when a reference cannot be
204
+ * resolved.
205
+ */
206
+ resolveOverrideValue(scope, value, level = 0) {
207
+ if (isReference(value)) {
208
+ return this.resolveReference(scope, value, 0);
209
+ }
210
+
211
+ if (!_.isPlainObject(value) || level >= MAX_OBJECT_DEPTH) {
212
+ return value;
213
+ }
214
+
215
+ const result = {};
216
+
217
+ _.forOwn(value, (leaf, key) => {
218
+ const resolved = this.resolveOverrideValue(scope, leaf, level + 1);
219
+
220
+ if (!_.isNil(resolved)) {
221
+ result[key] = resolved;
222
+ }
223
+ });
224
+
225
+ return result;
226
+ }
227
+
228
+ /**
229
+ * Resolves one variable through the override layers on top of the scoped
230
+ * lookup. Layers are applied from the lowest to the highest priority: the
231
+ * inherited (scope, then theme root) value is the base, every layer that has
232
+ * a value for the variable replaces it - or, when both are plain objects,
233
+ * is merged over it.
234
+ *
235
+ * @param {string} scope Dotted extension scope the variable belongs to.
236
+ * @param {string} name Dotted variable path, e.g. `titleFont.color`.
237
+ * @param {Array<Object>} layers Override objects, highest priority first.
238
+ * @returns {*} The resolved value.
239
+ */
240
+ resolveLayeredVariable(scope, name, layers) {
241
+ const path = _.split(name, '.');
242
+
243
+ let _current = this.getScopedVariable(scope, name);
244
+
245
+ _.forEachRight(layers, layer => {
246
+ const resolved = this.resolveOverrideValue(scope, _.get(layer, path));
247
+
248
+ if (_.isNil(resolved)) {
249
+ return;
250
+ }
251
+
252
+ _current =
253
+ _.isPlainObject(resolved) && _.isPlainObject(_current)
254
+ ? mergeReplacingArrays(_current, resolved)
255
+ : resolved;
256
+ });
257
+
258
+ return _current;
259
+ }
260
+
261
+ /**
262
+ * Creates a resolver that layers sparse overrides on top of a scoped
263
+ * resolver, with the same signature: `resolve(name)` or `resolve(scope,
264
+ * name)`. For a variable the cascade is: `overrides[group]`, then
265
+ * `overrides` itself, then the extension scope, then the theme root. A
266
+ * `null`/`undefined` override means "not set" and falls through to the next
267
+ * tier. A string override starting with `@` is a reference to another theme
268
+ * variable and is resolved like the theme values are; a plain object
269
+ * override is merged over the inherited object, field by field.
270
+ *
271
+ * Group and variable keys may contain dots (a group is a canonical screen
272
+ * type), so overrides are always read with array paths, never dotted strings.
273
+ * Overrides apply only to variables read from `scope`; a 2-argument call for
274
+ * another scope is a plain scoped lookup.
275
+ *
276
+ * @param {string} scope Dotted extension scope, e.g. `shoutem.widgets`.
277
+ * @param {Object} [overrides] Sparse override object: root keys are shared
278
+ * variables, a key equal to `group` holds that group's variables.
279
+ * @param {string} [group] Key of the override group to apply on top of the
280
+ * shared root keys.
281
+ * @returns {Function} The layered resolver.
282
+ */
283
+ createLayeredResolver(scope, overrides, group) {
284
+ const root = _.isPlainObject(overrides) ? overrides : undefined;
285
+ const groupOverrides =
286
+ root && group && _.isPlainObject(root[group]) ? root[group] : undefined;
287
+ const layers = _.compact([groupOverrides, root]);
288
+
289
+ const resolve = (requestScope, name) => {
290
+ if (requestScope !== scope || _.isEmpty(layers)) {
291
+ return this.getScopedVariable(requestScope, name);
292
+ }
293
+
294
+ return this.resolveLayeredVariable(requestScope, name, layers);
295
+ };
296
+
297
+ return (...params) => {
298
+ if (params.length === 1) {
299
+ return resolve(scope, params[0]);
300
+ }
301
+ if (params.length === 2) {
302
+ return resolve(params[0], params[1]);
303
+ }
304
+
305
+ return undefined;
306
+ };
307
+ }
66
308
  }
67
309
 
68
310
  // Expose both, the resolver service, and the default resolver working with
@@ -71,3 +313,4 @@ export class ThemeVariableResolver {
71
313
  export const defaultResolver = new ThemeVariableResolver();
72
314
  export const resolveVariable = defaultResolver.resolveVariable;
73
315
  export const createScopedResolver = defaultResolver.createScopedResolver;
316
+ export const createLayeredResolver = defaultResolver.createLayeredResolver;
package/theme.js CHANGED
@@ -2162,6 +2162,112 @@ export default () => {
2162
2162
  nextPageInsetSize: 20,
2163
2163
  },
2164
2164
 
2165
+ 'shoutem.ui.ImageCarousel': {
2166
+ container: {
2167
+ width: '100%',
2168
+ overflow: 'hidden',
2169
+ backgroundColor: resolveVariable('paperColor'),
2170
+ },
2171
+ listContent: {},
2172
+ // Geometry / animation scalars read by the component, not applied as styles.
2173
+ cardWidth: responsiveWidth(236),
2174
+ cardSpacing: responsiveWidth(10),
2175
+ inactiveScale: 0.85,
2176
+ inactiveOpacity: 0.7,
2177
+ pageIndicators: {
2178
+ container: {
2179
+ position: 'absolute',
2180
+ left: 0,
2181
+ right: 0,
2182
+ bottom: 0,
2183
+ paddingTop: resolveVariable('largeGutter'),
2184
+ paddingBottom: resolveVariable('mediumGutter'),
2185
+ // A bottom-anchored scrim behind the dots — without it, white dots on
2186
+ // a light or similarly-colored part of the image become invisible.
2187
+ // Reaches full darkness within the first 20% (same quick-ramp as the
2188
+ // overlay text zones) so the dots themselves always sit on the fully
2189
+ // dark portion, not partway through the fade.
2190
+ backgroundGradient: {
2191
+ colors: [
2192
+ 'rgba(0, 0, 0, 0)',
2193
+ 'rgba(0, 0, 0, 0.05)',
2194
+ 'rgba(0, 0, 0, 0.1)',
2195
+ ],
2196
+ locations: [0, 0.2, 1],
2197
+ },
2198
+ },
2199
+ // White dots so they read on top of photos, mirroring
2200
+ // shoutem.ui.PageIndicators' own `.overlay-bottom` variant.
2201
+ indicator: {
2202
+ backgroundColor: '#ffffff',
2203
+ },
2204
+ selectedIndicator: {
2205
+ backgroundColor: changeColorAlpha('#ffffff', 0.7),
2206
+ },
2207
+ },
2208
+ // 36×36 circular buttons vertically centered over the slide edges; the
2209
+ // marginTop is exactly half the button's own height (not a gutter) so it
2210
+ // centers regardless of slide height, and a fixed dark scrim (not a theme
2211
+ // color) keeps the icon legible over any photo.
2212
+ leftArrow: {
2213
+ position: 'absolute',
2214
+ top: '50%',
2215
+ left: resolveVariable('mediumGutter'),
2216
+ width: responsiveWidth(36),
2217
+ height: responsiveWidth(36),
2218
+ marginTop: -responsiveWidth(18),
2219
+ borderRadius: responsiveWidth(18),
2220
+ alignItems: 'center',
2221
+ justifyContent: 'center',
2222
+ backgroundColor: changeColorAlpha('#000000', 0.4),
2223
+ },
2224
+ rightArrow: {
2225
+ position: 'absolute',
2226
+ top: '50%',
2227
+ right: resolveVariable('mediumGutter'),
2228
+ width: responsiveWidth(36),
2229
+ height: responsiveWidth(36),
2230
+ marginTop: -responsiveWidth(18),
2231
+ borderRadius: responsiveWidth(18),
2232
+ alignItems: 'center',
2233
+ justifyContent: 'center',
2234
+ backgroundColor: changeColorAlpha('#000000', 0.4),
2235
+ },
2236
+ arrowIcon: {
2237
+ color: resolveVariable('imageOverlayTextColor'),
2238
+ width: responsiveWidth(20),
2239
+ height: responsiveWidth(20),
2240
+ },
2241
+ placeholder: {},
2242
+ },
2243
+
2244
+ 'shoutem.ui.ImageCarouselSlide': {
2245
+ // Fills the carousel's per-slide wrapper, which owns the width and the
2246
+ // aspect ratio.
2247
+ card: {
2248
+ flex: 1,
2249
+ borderRadius: responsiveWidth(16),
2250
+ overflow: 'hidden',
2251
+ backgroundColor: resolveVariable('lineColor'),
2252
+ },
2253
+ image: {
2254
+ position: 'absolute',
2255
+ top: 0,
2256
+ left: 0,
2257
+ right: 0,
2258
+ bottom: 0,
2259
+ },
2260
+ // Covers the image while it downloads; the card's overflow clipping keeps
2261
+ // it inside the rounded corners.
2262
+ imagePlaceholder: {
2263
+ position: 'absolute',
2264
+ top: 0,
2265
+ left: 0,
2266
+ right: 0,
2267
+ bottom: 0,
2268
+ },
2269
+ },
2270
+
2165
2271
  //
2166
2272
  // PageIndicators
2167
2273
  //