File size: 8,969 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import clsx from 'clsx';
import { useRtl } from 'i18n-calypso';
import { Children, useState, useLayoutEffect, useRef, useCallback } from 'react';

import './style.scss';

const OFFSET_THRESHOLD_PERCENTAGE = 0.35; // Percentage of width to travel before we trigger the slider to move to the desired slide.
const VELOCITY_THRESHOLD = 0.2; // Speed of drag above, before we trigger the slider to move to the desired slide.
const VERTICAL_THRESHOLD_ANGLE = 55;
const TRANSITION_DURATION = '300ms';

function useResizeObserver() {
	const [ observerEntry, setObserverEntry ] = useState( {} );
	const [ node, setNode ] = useState( null );
	const observer = useRef( null );

	const disconnect = useCallback( () => observer.current?.disconnect(), [] );

	const observe = useCallback( () => {
		observer.current = new ResizeObserver( ( [ entry ] ) => setObserverEntry( entry ) );
		if ( node ) {
			observer.current.observe( node );
		}
	}, [ node ] );

	useLayoutEffect( () => {
		observe();
		return () => disconnect();
	}, [ disconnect, observe ] );

	return [ setNode, observerEntry ];
}

function getDragPositionAndTime( event ) {
	const { timeStamp } = event;
	if ( event.hasOwnProperty( 'clientX' ) ) {
		return { x: event.clientX, y: event.clientY, timeStamp };
	}

	if ( event.targetTouches[ 0 ] ) {
		return {
			x: event.targetTouches[ 0 ].clientX,
			y: event.targetTouches[ 0 ].clientY,
			timeStamp,
		};
	}

	const touch = event.changedTouches[ 0 ];
	return { x: touch.clientX, y: touch.clientY, timeStamp };
}

function getPagesWidth( pageWidth, numPages ) {
	if ( ! pageWidth ) {
		return null;
	}
	return pageWidth * numPages;
}

export const Swipeable = ( {
	hasDynamicHeight = false,
	children,
	currentPage = 0,
	onPageSelect,
	pageClassName,
	containerClassName,
	isClickEnabled,
	...otherProps
} ) => {
	const [ swipeableArea, setSwipeableArea ] = useState();
	const isRtl = useRtl();

	const [ resizeObserverRef, entry ] = useResizeObserver();

	const [ pagesStyle, setPagesStyle ] = useState( {
		transitionDuration: TRANSITION_DURATION,
	} );

	const [ dragData, setDragData ] = useState( null );

	const pagesRef = useRef();
	const numPages = Children.count( children );
	const containerWidth = entry?.contentRect?.width;

	const getOffset = useCallback(
		( index ) => {
			const offset = containerWidth * index;
			return isRtl ? offset : -offset;
		},
		[ isRtl, containerWidth ]
	);

	const updateEnabled = hasDynamicHeight && numPages > 1;

	// Generate a property that denotes the order of the cards, in order to recalculate height whenever the card order changes.
	const childrenOrder = children.reduce( ( acc, child ) => acc + child.key, '' );

	useLayoutEffect( () => {
		if ( ! updateEnabled ) {
			// This is a fix for a bug when you have >1 pages and it update the component to just one but the height is still
			// Related to https://github.com/Automattic/dotcom-forge/issues/2033
			if ( pagesStyle?.height ) {
				setPagesStyle( { ...pagesStyle, height: undefined } );
			}
			return;
		}
		const targetHeight = pagesRef.current?.querySelector( '.is-current' )?.offsetHeight;

		if ( targetHeight && pagesStyle?.height !== targetHeight ) {
			setPagesStyle( { ...pagesStyle, height: targetHeight } );
		}
	}, [ pagesRef, currentPage, pagesStyle, updateEnabled, containerWidth, childrenOrder ] );

	const resetDragData = useCallback( () => {
		delete pagesStyle.transform;
		setPagesStyle( {
			...pagesStyle,
			transitionDuration: TRANSITION_DURATION,
		} );
		setDragData( null );
	}, [ pagesStyle, setPagesStyle, setDragData ] );

	const handleDragStart = useCallback(
		( event ) => {
			const position = getDragPositionAndTime( event );
			setSwipeableArea( pagesRef.current?.getBoundingClientRect() );
			setDragData( { start: position } );
			setPagesStyle( { ...pagesStyle, transitionDuration: `0ms` } ); // Set transition Duration to 0 for smooth dragging.
		},
		[ pagesStyle ]
	);

	const hasSwipedToNextPage = useCallback(
		( delta ) => ( isRtl ? delta > 0 : delta < 0 ),
		[ isRtl ]
	);
	const hasSwipedToPreviousPage = useCallback(
		( delta ) => ( isRtl ? delta < 0 : delta > 0 ),
		[ isRtl ]
	);

	const handleDragEnd = useCallback(
		( event ) => {
			if ( ! dragData ) {
				return; // End early if we are not dragging any more.
			}

			let dragPosition = getDragPositionAndTime( event );

			if ( dragPosition.x === 0 ) {
				dragPosition = dragData.last;
			}

			const delta = dragPosition.x - dragData.start.x;
			const absoluteDelta = Math.abs( delta );
			const velocity = absoluteDelta / ( dragPosition.timeStamp - dragData.start.timeStamp );

			const verticalAbsoluteDelta = Math.abs( dragPosition.y - dragData.start.y );
			const angle = ( Math.atan2( verticalAbsoluteDelta, absoluteDelta ) * 180 ) / Math.PI;

			// Is click or tap?
			if ( velocity === 0 && isClickEnabled ) {
				if ( numPages !== currentPage + 1 ) {
					onPageSelect( currentPage + 1 );
				} else {
					onPageSelect( 0 );
				}
				resetDragData();
				return;
			}

			// Is vertical scroll detected?
			if ( angle > VERTICAL_THRESHOLD_ANGLE ) {
				resetDragData();
				return;
			}

			const hasMetThreshold =
				absoluteDelta > OFFSET_THRESHOLD_PERCENTAGE * containerWidth ||
				velocity > VELOCITY_THRESHOLD;

			let newIndex = currentPage;
			if ( hasSwipedToNextPage( delta ) && hasMetThreshold && numPages !== currentPage + 1 ) {
				newIndex = currentPage + 1;
			}

			if ( hasSwipedToPreviousPage( delta ) && hasMetThreshold && currentPage !== 0 ) {
				newIndex = currentPage - 1;
			}

			delete pagesStyle.transform;

			setPagesStyle( {
				...pagesStyle,
				transitionDuration: TRANSITION_DURATION,
			} );
			onPageSelect( newIndex );
			setDragData( null );
		},
		[
			currentPage,
			dragData,
			hasSwipedToNextPage,
			hasSwipedToPreviousPage,
			numPages,
			onPageSelect,
			pagesStyle,
			containerWidth,
			isClickEnabled,
		]
	);

	const handleDrag = useCallback(
		( event ) => {
			if ( ! dragData ) {
				return;
			}

			const dragPosition = getDragPositionAndTime( event );
			const delta = dragPosition.x - dragData.start.x;
			const absoluteDelta = Math.abs( delta );
			const offset = getOffset( currentPage ) + delta;
			setDragData( { ...dragData, last: dragPosition } );
			// The user needs to swipe horizontally more then 2 px in order for the canvase to be dragging.
			// We do this so that the user can scroll vertically smother.
			if ( absoluteDelta < 3 ) {
				return;
			}

			// Allow for swipe left or right
			if (
				( numPages !== currentPage + 1 && hasSwipedToNextPage( delta ) ) ||
				( currentPage !== 0 && hasSwipedToPreviousPage( delta ) )
			) {
				setPagesStyle( {
					...pagesStyle,
					transform: `translate3d(${ offset }px, 0px, 0px)`,
					transitionDuration: `0ms`,
				} );
			}

			if ( ! swipeableArea ) {
				return;
			}
			// Did the user swipe out of the swipeable area?
			if (
				dragPosition.x < swipeableArea.left ||
				dragPosition.x > swipeableArea.right ||
				dragPosition.y > swipeableArea.bottom ||
				dragPosition.y < swipeableArea.top
			) {
				handleDragEnd( event );
			}
		},
		[
			dragData,
			getOffset,
			currentPage,
			numPages,
			hasSwipedToNextPage,
			hasSwipedToPreviousPage,
			swipeableArea,
			pagesStyle,
			handleDragEnd,
		]
	);

	const getTouchEvents = useCallback( () => {
		if ( 'onpointerup' in document ) {
			return {
				onPointerDown: handleDragStart,
				onPointerMove: handleDrag,
				onPointerUp: handleDragEnd,
				onPointerLeave: handleDragEnd,
			};
		}

		if ( 'ondragend' in document ) {
			return {
				onDragStart: handleDragStart,
				onDrag: handleDrag,
				onDragEnd: handleDragEnd,
				onDragExit: handleDragEnd,
			};
		}

		if ( 'ontouchend' in document ) {
			return {
				onTouchStart: handleDragStart,
				onTouchMove: handleDrag,
				onTouchEnd: handleDragEnd,
				onTouchCancel: handleDragEnd,
			};
		}

		return null;
	}, [ handleDragStart, handleDrag, handleDragEnd ] );

	const offset = getOffset( currentPage );

	return (
		<>
			<div
				{ ...getTouchEvents() }
				className="swipeable__container"
				ref={ pagesRef }
				{ ...otherProps }
			>
				<div
					className={ clsx( 'swipeable__pages', containerClassName ) }
					style={ {
						transform: `translate3d(${ offset }px, 0px, 0px)`,
						...pagesStyle,
						width: getPagesWidth( containerWidth, numPages ),
					} }
				>
					{ Children.map( children, ( child, index ) => (
						<div
							style={ { width: `${ containerWidth }px` } } // Setting the page width is important for iOS browser.
							className={ clsx( 'swipeable__page', pageClassName, {
								'is-current': index === currentPage,
								'is-prev': index < currentPage,
								'is-next': index > currentPage,
							} ) }
							key={ `page-${ index }` }
						>
							{ child }
						</div>
					) ) }
				</div>
			</div>
			<div ref={ resizeObserverRef } className="swipeable__resize-observer"></div>
		</>
	);
};

export default Swipeable;