react-native-gesture-image-viewer 1.2.2 → 1.3.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-gesture-image-viewer",
3
- "version": "1.2.2",
3
+ "version": "1.3.0",
4
4
  "description": "🖼️ A highly customizable and easy-to-use React Native image viewer with gesture support and external controls",
5
5
  "main": "./lib/module/index.js",
6
6
  "types": "./lib/typescript/src/index.d.ts",
@@ -14,6 +14,7 @@
14
14
  },
15
15
  "files": [
16
16
  "lib",
17
+ "src",
17
18
  "android",
18
19
  "ios",
19
20
  "cpp",
@@ -0,0 +1,171 @@
1
+ import { useCallback, useEffect, useMemo } from 'react';
2
+ import { type FlatList, Platform, type ScrollViewProps, StyleSheet, useWindowDimensions, View } from 'react-native';
3
+ import { Gesture, GestureDetector, GestureHandlerRootView } from 'react-native-gesture-handler';
4
+ import Animated from 'react-native-reanimated';
5
+ import { registry } from './GestureViewerRegistry';
6
+ import type { GestureViewerProps } from './types';
7
+ import { useGestureViewer } from './useGestureViewer';
8
+ import { isFlashListLike, isFlatListLike, isScrollViewLike } from './utils';
9
+ import WebPagingFixStyle from './WebPagingFixStyle';
10
+
11
+ export function GestureViewer<T = any, LC = typeof FlatList>({
12
+ id = 'default',
13
+ data,
14
+ renderItem: renderItemProp,
15
+ renderContainer,
16
+ ListComponent,
17
+ width: customWidth,
18
+ listProps,
19
+ backdropStyle: backdropStyleProps,
20
+ containerStyle,
21
+ initialIndex = 0,
22
+ itemSpacing = 0,
23
+ useSnap = false,
24
+ ...props
25
+ }: GestureViewerProps<T, LC>) {
26
+ const Component = ListComponent as React.ComponentType<any>;
27
+
28
+ const { width: screenWidth } = useWindowDimensions();
29
+
30
+ const width = useSnap ? customWidth || screenWidth : screenWidth;
31
+
32
+ const { listRef, isZoomed, dismissGesture, zoomGesture, onMomentumScrollEnd, animatedStyle, backdropStyle } =
33
+ useGestureViewer({
34
+ id,
35
+ data,
36
+ width,
37
+ initialIndex,
38
+ itemSpacing,
39
+ useSnap,
40
+ ...props,
41
+ });
42
+
43
+ const renderItem = useCallback(
44
+ ({ item, index }: { item: T; index: number }) => {
45
+ return (
46
+ <View
47
+ key={typeof item === 'string' ? item : index}
48
+ style={[
49
+ {
50
+ width,
51
+ height: '100%',
52
+ justifyContent: 'center',
53
+ alignItems: 'center',
54
+ marginHorizontal: itemSpacing / 2,
55
+ },
56
+ ]}
57
+ >
58
+ {renderItemProp(item, index)}
59
+ </View>
60
+ );
61
+ },
62
+ [width, itemSpacing, renderItemProp],
63
+ );
64
+
65
+ const getItemLayout = useCallback(
66
+ (_: ArrayLike<T> | null | undefined, index: number) => ({
67
+ length: width + itemSpacing,
68
+ offset: (width + itemSpacing) * index,
69
+ index,
70
+ }),
71
+ [width, itemSpacing],
72
+ );
73
+
74
+ const keyExtractor = useCallback(
75
+ (item: T, index: number) => (typeof item === 'string' ? item : `image-${index}`),
76
+ [],
77
+ );
78
+
79
+ const gesture = useMemo(() => {
80
+ return Gesture.Race(dismissGesture, zoomGesture);
81
+ }, [zoomGesture, dismissGesture]);
82
+
83
+ useEffect(() => {
84
+ registry.createManager(id);
85
+
86
+ return () => registry.deleteManager(id);
87
+ }, [id]);
88
+
89
+ const commonProps: ScrollViewProps = useMemo(
90
+ () => ({
91
+ horizontal: true,
92
+ scrollEnabled: !isZoomed,
93
+ showsHorizontalScrollIndicator: false,
94
+ onMomentumScrollEnd: onMomentumScrollEnd,
95
+ ...(useSnap
96
+ ? {
97
+ snapToInterval: width + itemSpacing,
98
+ snapToAlignment: 'center',
99
+ decelerationRate: 'fast',
100
+ }
101
+ : {
102
+ pagingEnabled: true,
103
+ }),
104
+ scrollEventThrottle: 16,
105
+ removeClippedSubviews: true,
106
+ }),
107
+ [width, itemSpacing, isZoomed, onMomentumScrollEnd, useSnap],
108
+ );
109
+
110
+ const listComponent = (
111
+ <GestureHandlerRootView>
112
+ <GestureDetector gesture={gesture}>
113
+ <View style={[styles.container, containerStyle]}>
114
+ <Animated.View style={[styles.background, backdropStyleProps, backdropStyle]} />
115
+ <Animated.View
116
+ style={[styles.content, animatedStyle]}
117
+ {...(Platform.OS === 'web' &&
118
+ isFlashListLike(Component) && { dataSet: { 'flash-list-paging-enabled-fix': true } })}
119
+ >
120
+ {isScrollViewLike(Component) ? (
121
+ <Component ref={listRef} {...commonProps} {...listProps}>
122
+ {data.map((item, index) => renderItem({ item, index }))}
123
+ </Component>
124
+ ) : (
125
+ isFlatListLike(Component) && (
126
+ <Component
127
+ ref={listRef}
128
+ {...commonProps}
129
+ data={data}
130
+ renderItem={renderItem}
131
+ initialScrollIndex={initialIndex}
132
+ keyExtractor={keyExtractor}
133
+ windowSize={3}
134
+ maxToRenderPerBatch={3}
135
+ getItemLayout={getItemLayout}
136
+ {...(isFlashListLike(Component) && { estimatedItemSize: width + itemSpacing })}
137
+ // NOTE - https://github.com/necolas/react-native-web/issues/1299
138
+ {...(Platform.OS === 'web' &&
139
+ isFlatListLike(Component) && { dataSet: { 'flat-list-paging-enabled-fix': true } })}
140
+ {...listProps}
141
+ />
142
+ )
143
+ )}
144
+ </Animated.View>
145
+ <WebPagingFixStyle Component={Component} />
146
+ </View>
147
+ </GestureDetector>
148
+ </GestureHandlerRootView>
149
+ );
150
+
151
+ return renderContainer ? renderContainer(listComponent) : listComponent;
152
+ }
153
+
154
+ const styles = StyleSheet.create({
155
+ container: {
156
+ flex: 1,
157
+ },
158
+ content: {
159
+ flex: 1,
160
+ width: '100%',
161
+ height: '100%',
162
+ },
163
+ background: {
164
+ position: 'absolute',
165
+ top: 0,
166
+ left: 0,
167
+ right: 0,
168
+ bottom: 0,
169
+ backgroundColor: 'black',
170
+ },
171
+ });
@@ -0,0 +1,201 @@
1
+ import { type SharedValue, withTiming } from 'react-native-reanimated';
2
+ import { createBoundsConstraint } from './utils';
3
+
4
+ export type GestureViewerManagerState = {
5
+ currentIndex: number;
6
+ dataLength: number;
7
+ };
8
+
9
+ class GestureViewerManager {
10
+ private currentIndex = 0;
11
+ private dataLength = 0;
12
+ private width = 0;
13
+ private height = 0;
14
+ private scale: SharedValue<number> | null = null;
15
+ private translateX: SharedValue<number> | null = null;
16
+ private translateY: SharedValue<number> | null = null;
17
+ private maxZoomScale = 2;
18
+ private listRef: any | null = null;
19
+ private enableSwipeGesture = true;
20
+ private listeners = new Set<(state: GestureViewerManagerState) => void>();
21
+
22
+ private notifyListeners() {
23
+ const state = this.getState();
24
+
25
+ this.listeners.forEach((listener) => listener(state));
26
+ }
27
+
28
+ subscribe(listener: (state: GestureViewerManagerState) => void) {
29
+ this.listeners.add(listener);
30
+
31
+ return () => {
32
+ this.listeners.delete(listener);
33
+ };
34
+ }
35
+
36
+ getState() {
37
+ return {
38
+ currentIndex: this.currentIndex,
39
+ dataLength: this.dataLength,
40
+ };
41
+ }
42
+
43
+ setWidth(width: number) {
44
+ this.width = width;
45
+ }
46
+
47
+ setHeight(height: number) {
48
+ this.height = height;
49
+ }
50
+
51
+ setListRef(ref: any) {
52
+ this.listRef = ref;
53
+ }
54
+
55
+ setDataLength(length: number) {
56
+ this.dataLength = length;
57
+ }
58
+
59
+ setEnableSwipeGesture(enabled: boolean) {
60
+ this.enableSwipeGesture = enabled;
61
+ }
62
+
63
+ setCurrentIndex(index: number) {
64
+ if (index !== this.currentIndex) {
65
+ this.currentIndex = index;
66
+ }
67
+ }
68
+
69
+ setZoomSharedValues(
70
+ scale: SharedValue<number>,
71
+ translateX: SharedValue<number>,
72
+ translateY: SharedValue<number>,
73
+ maxZoomScale: number,
74
+ ) {
75
+ this.scale = scale;
76
+ this.translateX = translateX;
77
+ this.translateY = translateY;
78
+ this.maxZoomScale = maxZoomScale;
79
+ }
80
+
81
+ notifyStateChange() {
82
+ this.notifyListeners();
83
+ }
84
+
85
+ /**
86
+ * @param multiplier - The multiplier to zoom in.
87
+ * @range 0.01 - 1
88
+ * @default 0.25
89
+ */
90
+ zoomIn = (multiplier = 0.25) => {
91
+ if (!this.scale || !this.translateX || !this.translateY || multiplier < 0.01 || multiplier > 1) {
92
+ return;
93
+ }
94
+
95
+ const nextScale = Math.min(this.scale.value * (1 + multiplier), this.maxZoomScale);
96
+
97
+ this.scale.value = withTiming(nextScale);
98
+
99
+ const { translateX, translateY } = createBoundsConstraint({
100
+ width: this.width,
101
+ height: this.height,
102
+ })({
103
+ translateX: this.translateX.value,
104
+ translateY: this.translateY.value,
105
+ scale: nextScale,
106
+ });
107
+
108
+ this.translateX.value = withTiming(translateX);
109
+ this.translateY.value = withTiming(translateY);
110
+ };
111
+
112
+ /**
113
+ * @param multiplier - The multiplier to zoom out.
114
+ * @range 0.01 - 1
115
+ * @default 0.25
116
+ */
117
+ zoomOut = (multiplier = 0.25) => {
118
+ if (!this.scale || !this.translateX || !this.translateY || multiplier < 0.01 || multiplier > 1) {
119
+ return;
120
+ }
121
+
122
+ const nextScale = Math.max(this.scale.value / (1 + multiplier), 1);
123
+
124
+ this.scale.value = withTiming(nextScale);
125
+
126
+ if (nextScale === 1) {
127
+ this.translateX.value = withTiming(0);
128
+ this.translateY.value = withTiming(0);
129
+ return;
130
+ }
131
+
132
+ const { translateX, translateY } = createBoundsConstraint({
133
+ width: this.width,
134
+ height: this.height,
135
+ })({
136
+ translateX: this.translateX.value,
137
+ translateY: this.translateY.value,
138
+ scale: nextScale,
139
+ });
140
+
141
+ this.translateX.value = withTiming(translateX);
142
+ this.translateY.value = withTiming(translateY);
143
+ };
144
+
145
+ /**
146
+ * @param scale - The scale to reset to.
147
+ * @default 1
148
+ */
149
+ resetZoom = (scale = 1) => {
150
+ if (!this.scale || !this.translateX || !this.translateY || scale <= 0 || scale > this.maxZoomScale) {
151
+ return;
152
+ }
153
+
154
+ this.scale.value = withTiming(scale);
155
+ this.translateX.value = withTiming(0);
156
+ this.translateY.value = withTiming(0);
157
+ };
158
+
159
+ goToIndex = (index: number) => {
160
+ if (index < 0 || index >= this.dataLength || !this.enableSwipeGesture || !this.listRef) {
161
+ return;
162
+ }
163
+
164
+ this.currentIndex = index;
165
+
166
+ if (this.listRef.scrollToIndex) {
167
+ this.listRef.scrollToIndex({ index, animated: true });
168
+ } else if (this.listRef.scrollTo) {
169
+ this.listRef.scrollTo({ x: index * this.width, animated: true });
170
+ }
171
+
172
+ this.notifyListeners();
173
+ };
174
+
175
+ goToPrevious = () => {
176
+ if (this.currentIndex > 0) {
177
+ this.goToIndex(this.currentIndex - 1);
178
+ }
179
+ };
180
+
181
+ goToNext = () => {
182
+ if (this.currentIndex < this.dataLength - 1) {
183
+ this.goToIndex(this.currentIndex + 1);
184
+ }
185
+ };
186
+
187
+ cleanUp() {
188
+ this.listeners.clear();
189
+ this.listRef = null;
190
+ this.enableSwipeGesture = true;
191
+ this.currentIndex = 0;
192
+ this.dataLength = 0;
193
+
194
+ this.maxZoomScale = 2;
195
+ this.scale = null;
196
+ this.translateX = null;
197
+ this.translateY = null;
198
+ }
199
+ }
200
+
201
+ export default GestureViewerManager;
@@ -0,0 +1,66 @@
1
+ import GestureViewerManager from './GestureViewerManager';
2
+
3
+ class GestureViewerRegistry {
4
+ private managers = new Map<string, GestureViewerManager>();
5
+ private subscribers = new Map<string, Set<(manager: GestureViewerManager | null) => void>>();
6
+
7
+ subscribeToManager(id: string, callback: (manager: GestureViewerManager | null) => void) {
8
+ if (!this.subscribers.has(id)) {
9
+ this.subscribers.set(id, new Set());
10
+ }
11
+
12
+ this.subscribers.get(id)?.add(callback);
13
+
14
+ const manager = this.managers.get(id) || null;
15
+
16
+ callback(manager);
17
+
18
+ return () => {
19
+ const subscribers = this.subscribers.get(id);
20
+
21
+ subscribers?.delete(callback);
22
+
23
+ if (subscribers && subscribers.size === 0) {
24
+ this.subscribers.delete(id);
25
+ }
26
+ };
27
+ }
28
+
29
+ createManager(id: string): GestureViewerManager | null {
30
+ if (this.managers.has(id)) {
31
+ return this.managers.get(id) || null;
32
+ }
33
+
34
+ const manager = new GestureViewerManager();
35
+ this.managers.set(id, manager);
36
+
37
+ this.notifySubscribers(id, manager);
38
+
39
+ return manager;
40
+ }
41
+
42
+ getManager(id: string): GestureViewerManager | null {
43
+ return this.managers.get(id) || null;
44
+ }
45
+
46
+ deleteManager(id: string) {
47
+ const manager = this.managers.get(id);
48
+
49
+ if (manager) {
50
+ manager.cleanUp();
51
+ this.managers.delete(id);
52
+
53
+ this.notifySubscribers(id, null);
54
+ }
55
+ }
56
+
57
+ notifySubscribers(id: string, manager: GestureViewerManager | null) {
58
+ const listeners = this.subscribers.get(id);
59
+
60
+ if (listeners) {
61
+ [...listeners].forEach((callback) => callback(manager));
62
+ }
63
+ }
64
+ }
65
+
66
+ export const registry = new GestureViewerRegistry();
@@ -0,0 +1,24 @@
1
+ import { Platform } from 'react-native';
2
+ import { isFlashListLike, isFlatListLike } from './utils';
3
+
4
+ type WebPagingFixStyleProps = {
5
+ Component: React.ComponentType<any>;
6
+ };
7
+
8
+ function WebPagingFixStyle({ Component }: WebPagingFixStyleProps) {
9
+ if (Platform.OS !== 'web') {
10
+ return null;
11
+ }
12
+
13
+ if (isFlashListLike(Component)) {
14
+ return <style>{`[data-flash-list-paging-enabled-fix] > div {height: 100%;}`}</style>;
15
+ }
16
+
17
+ if (isFlatListLike(Component)) {
18
+ return <style>{`[data-flat-list-paging-enabled-fix] > div > div > div {height: 100%;}`}</style>;
19
+ }
20
+
21
+ return null;
22
+ }
23
+
24
+ export default WebPagingFixStyle;
package/src/index.tsx ADDED
@@ -0,0 +1,3 @@
1
+ export { GestureViewer } from './GestureViewer';
2
+ export type { GestureViewerProps } from './types';
3
+ export { useGestureViewerController } from './useGestureViewerController';
package/src/types.ts ADDED
@@ -0,0 +1,144 @@
1
+ import type React from 'react';
2
+ import type { FlatList as RNFlatList, ScrollView as RNScrollView, StyleProp, ViewStyle } from 'react-native';
3
+ import type { FlatList as GHFlatList, ScrollView as GHScrollView } from 'react-native-gesture-handler';
4
+
5
+ export type FlatListComponent = typeof RNFlatList | typeof GHFlatList;
6
+ export type ScrollViewComponent = typeof RNScrollView | typeof GHScrollView;
7
+
8
+ type GetComponentProps<T> = T extends React.ComponentType<infer P> ? P : never;
9
+
10
+ type ConditionalListProps<LC> = LC extends FlatListComponent
11
+ ? React.ComponentProps<LC>
12
+ : LC extends ScrollViewComponent
13
+ ? React.ComponentProps<LC>
14
+ : GetComponentProps<LC>;
15
+
16
+ export interface GestureViewerProps<T = any, LC = typeof RNFlatList> {
17
+ /**
18
+ * When you want to efficiently manage multiple `GestureViewer` instances, you can use the `id` prop to use multiple `GestureViewer` components.
19
+ * @remark `GestureViewer` automatically removes instances from memory when components are unmounted, so no manual memory management is required.
20
+ * @default 'default'
21
+ */
22
+ id?: string;
23
+ /**
24
+ * The data to display in the `GestureViewer`.
25
+ */
26
+ data: T[];
27
+ /**
28
+ * The index of the item to display in the `GestureViewer` when the component is mounted.
29
+ * @default 0
30
+ */
31
+ initialIndex?: number;
32
+ /**
33
+ * A callback function that is called when the index of the item changes.
34
+ */
35
+ onIndexChange?: (index: number) => void;
36
+ /**
37
+ * A callback function that is called when the `GestureViewer` is dismissed.
38
+ */
39
+ onDismiss?: () => void;
40
+ /**
41
+ * A callback function that is called to render the item.
42
+ */
43
+ renderItem: (item: T, index: number) => React.ReactElement;
44
+ /**
45
+ * A callback function that is called to render the container.
46
+ */
47
+ renderContainer?: (children: React.ReactElement) => React.ReactElement;
48
+ /**
49
+ * Support for any list component like `ScrollView`, `FlatList`, `FlashList` through the `ListComponent` prop.
50
+ */
51
+ ListComponent: LC;
52
+ /**
53
+ * The width of the `GestureViewer`.
54
+ * @remark If you don't set this prop, the width of the `GestureViewer` will be the same as the width of the screen.
55
+ * @default screen width
56
+ */
57
+ width?: number;
58
+ /**
59
+ * Enables snap scrolling mode.
60
+ *
61
+ * @remark
62
+ * **`false` (default)**: Paging mode (`pagingEnabled: true`)
63
+ * - Scrolls by full screen size increments
64
+ *
65
+ * **`true`**: Snap mode (`snapToInterval` auto-calculated)
66
+ * - `snapToInterval` is automatically calculated based on `width` and `itemSpacing` values
67
+ * - Use this option when you need item spacing
68
+ * @default false
69
+ *
70
+ */
71
+ useSnap?: boolean;
72
+ /**
73
+ * `dismissThreshold` controls when `onDismiss` is called by applying a threshold value during vertical gestures.
74
+ * @default 80
75
+ */
76
+ dismissThreshold?: number;
77
+ // swipeThreshold?: number;
78
+ // velocityThreshold?: number;
79
+ /**
80
+ * Calls `onDismiss` function when swiping down.
81
+ * @remark Useful for closing modals with downward swipe gestures.
82
+ * @default true
83
+ */
84
+ enableDismissGesture?: boolean;
85
+ /**
86
+ * Controls left/right swipe gestures.
87
+ * @remark When `false`, horizontal gestures are disabled.
88
+ * @default true
89
+ */
90
+ enableSwipeGesture?: boolean;
91
+ /**
92
+ * `resistance` controls the range of vertical movement by applying resistance during vertical gestures.
93
+ * @default 2
94
+ */
95
+ resistance?: number;
96
+ /**
97
+ * The props to pass to the list component.
98
+ * @remark The `listProps` provides **type inference based on the selected list component**, ensuring accurate autocompletion and type safety in your IDE.
99
+ */
100
+ listProps?: Partial<ConditionalListProps<LC>>;
101
+ /**
102
+ * The style of the backdrop.
103
+ */
104
+ backdropStyle?: StyleProp<ViewStyle>;
105
+ /**
106
+ * The style of the container.
107
+ */
108
+ containerStyle?: StyleProp<ViewStyle>;
109
+ /**
110
+ * By default, the background `opacity` gradually decreases from 1 to 0 during downward swipe gestures.
111
+ * @remark When `false`, this animation is disabled.
112
+ * @default true
113
+ */
114
+ animateBackdrop?: boolean;
115
+ /**
116
+ * Only works when zoom is active, allows moving item position when zoomed.
117
+ * @remark When `false`, gesture movement is disabled during zoom.
118
+ * @default true
119
+ */
120
+ enableZoomPanGesture?: boolean;
121
+ /**
122
+ * Controls two-finger pinch gestures.
123
+ * @remark When `false`, two-finger zoom gestures are disabled.
124
+ * @default true
125
+ */
126
+ enableZoomGesture?: boolean;
127
+ /**
128
+ * Controls double-tap zoom gestures.
129
+ * @remark When `false`, double-tap zoom gestures are disabled.
130
+ * @default true
131
+ */
132
+ enableDoubleTapGesture?: boolean;
133
+ /**
134
+ * The maximum zoom scale.
135
+ * @default 2
136
+ */
137
+ maxZoomScale?: number;
138
+ /**
139
+ * The spacing between items in pixels.
140
+ * @remark Only applied when `useSnap` is `true`.
141
+ * @default 0
142
+ */
143
+ itemSpacing?: number;
144
+ }