-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.tsx
482 lines (404 loc) · 12.7 KB
/
index.tsx
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
import { Children, ReactChildren, ReactNode, PureComponent, HTMLProps } from 'react';
import { classNames } from '@tolkam/lib-utils-ui';
import { throttle } from '@tolkam/lib-utils';
import { getLongestDuration } from '@tolkam/lib-css-events';
import * as Hammer from 'hammerjs';
import './defaults.scss';
const WIN = window;
const WIN_EVENTS = 'load resize';
const LOCAL_CLASS_NAME = 'rAgXf';
export default class Frames extends PureComponent<IProps, any> {
/**
* Default props
* @type {IProps}
*/
public static defaultProps = {
startFrame: 0,
frameBoundary: 0.25,
loop: false,
clonesCount: 2,
draggingClass: 'is-dragging',
transitionClass: 'is-moving',
};
/**
* Pointer event names
* @type {string}
*/
public readonly SWIPE_PREV: string = 'swipeleft';
public readonly SWIPE_NEXT: string = 'swiperight';
public readonly PAN_PREV: string = 'panleft';
public readonly PAN_NEXT: string = 'panright';
public readonly PAN_START: string = 'panstart';
public readonly PAN_END: string = 'panend';
public readonly PAN_CANCEL: string = 'pancancel';
/**
* Hammer instance
* @type {HammerManager}
*/
protected hammer: HammerManager;
/**
* Scrolling element
* @type {HTMLDivElement}
*/
protected parent: HTMLDivElement;
/**
* Frames container
* @type {NodeList}
*/
protected container: HTMLDivElement;
/**
* Frame elements
* @type {NodeList}
*/
protected frames: NodeListOf<HTMLDivElement>;
/**
* Current frames size
* @type {number}
*/
protected frameSize = 0;
/**
* Index of current active frame
* @type {number}
*/
protected activeIndex = 0;
/**
* @param {IProps} props
*/
public constructor(props: IProps) {
super(props);
// throttled, so fires every N ms at most
this.onWindowChanges = throttle(this.onWindowChanges, 100);
// adjust axis
if (props.isVertical) {
this.SWIPE_PREV = 'swipeup';
this.SWIPE_NEXT = 'swipedown';
this.PAN_PREV = 'panup';
this.PAN_NEXT = 'pandown';
}
this.activeIndex = props.startFrame!;
}
/**
* {@inheritDoc}
*/
public componentDidMount() {
const that = this;
const props = that.props;
const isVertical = props.isVertical;
// setup Hammer
// @see https://github.com/hammerjs/hammer.js/issues/1050
const direction = Hammer.DIRECTION_ALL;
const touchAction = 'pan-' + (isVertical ? 'x' : 'y');
that.hammer = new Hammer.Manager(that.parent, {
recognizers: [
[Hammer.Swipe, { direction }],
[Hammer.Pan, { direction, threshold: 5, pointers: 0 }, ['swipe']],
],
touchAction,
});
const events = [];
if (props.swipeable) {
events.push(that.SWIPE_PREV, that.SWIPE_NEXT);
}
if (props.draggable) {
events.push(that.PAN_START, that.PAN_PREV, that.PAN_NEXT, that.PAN_END, that.PAN_CANCEL);
}
that.hammer.on(events.join(' '), that.onEvents);
Hammer.on(WIN, WIN_EVENTS, that.onWindowChanges);
// calculate sizes and populate values
that.init();
}
/**
* {@inheritDoc}
*/
public componentDidUpdate() {
this.init();
}
/**
* {@inheritDoc}
*/
public componentWillUnmount() {
this.hammer.destroy();
Hammer.off(WIN, WIN_EVENTS, this.onWindowChanges);
}
/**
* {@inheritDoc}
*/
public render() {
const that = this;
const { props } = that;
const framesProps = {
className: props.frameClass,
};
return <div
ref={(r: HTMLDivElement) => that.parent = r}
className={classNames(props.className, LOCAL_CLASS_NAME)}
>
<div className={props.containerClass}>
{that.getChildren(props.children, framesProps, (props.loop! ? that.getClonesCount() : 0))}
</div>
</div>;
}
/**
* Moves to next item
*
* @return void
*/
public next() {
this.goToFrame(this.getNextIndex(true));
}
/**
* Moves to previous item
*
* @return void
*/
public prev() {
this.goToFrame(this.getNextIndex(false));
}
/**
* Goes to specified index
*
* @param {number} index
*/
public goTo(index: number) {
const that = this;
// compensate 'public' index and internal one (with clones)
that.goToFrame(that.props.loop ? index + that.getClonesCount() : index);
}
/**
* Recalculates sizes and positions
*
* @return void
*/
public recalculate() {
this.init();
}
/**
* Gets parent HTMLElement
*
* @return {HTMLDivElement}
*/
public get parentElement(): HTMLDivElement {
return this.parent;
}
/**
* Renders children, optionally with clones
*
* @return {any}
*/
protected getChildren(children: ReactChildren | ReactNode, childrenProps: any, clonesCount: number) {
const childrenArr = Children.toArray(children);
const childrenCount = childrenArr.length;
const withClones = childrenArr.slice();
if (!childrenCount) {
return null;
}
if (clonesCount) {
// pre clones
for (let i = childrenCount - 1; i >= (childrenCount - clonesCount); i--) {
withClones.unshift(childrenArr[i]);
}
// post clones
for (let i = 0; i < clonesCount; i++) {
withClones.push(childrenArr[i]);
}
}
return withClones.map((child: any, i) => {
return <div {...childrenProps} key={i}>{child}</div>;
});
}
/**
* Initializes elements and sizes
*
* @return void
*/
protected init() {
const that = this;
// collect children
that.container = that.parent.firstChild as HTMLDivElement;
that.frames = that.container.childNodes as NodeListOf<HTMLDivElement>;
// set element sizes store current frame size
that.frameSize = that.setSizes();
// activate current frame
that.goToFrame(that.activeIndex, false);
}
/**
* Handles pointer events
*
* @param {HammerInput} e
*/
protected onEvents = (e: HammerInput) => {
const that = this;
const { hammer, activeIndex, frameSize, props } = that;
let delta = e['delta' + (props.isVertical ? 'Y' : 'X')];
// @see https://github.com/hammerjs/hammer.js/issues/1050
if (e.srcEvent.type === 'pointercancel') {
return;
}
switch (e.type) {
case(that.PAN_PREV) :
case(that.PAN_NEXT) :
const framePos = -activeIndex * frameSize;
// switch to next frame as soon as panned to it
if (Math.abs(delta) > frameSize) {
delta > 0 ? that.prev() : that.next();
hammer.stop(true);
break;
}
// slow down when not in loop mode and no frames left
if (that.isOutOfBounds(framePos + delta) && !props.loop) {
delta *= 0.15;
}
that.moveContainerBy(framePos + delta);
break;
case(that.SWIPE_PREV) :
case(that.SWIPE_NEXT) :
delta > 0 ? that.prev() : that.next();
hammer.stop(true);
break;
case(that.PAN_END) :
case(that.PAN_CANCEL) :
if (Math.abs(delta) > frameSize * props.frameBoundary!) {
delta > 0 ? that.prev() : that.next();
} else {
that.goToFrame(activeIndex);
}
break;
}
};
/**
* Handles window size changes
*
* return void
*/
protected onWindowChanges = () => {
this.init();
};
/**
* Shows frame by index
*
* @param {number} index
* @param {boolean} animate
*/
protected goToFrame(index: number, animate: boolean = true) {
const that = this;
const { frames, props } = that;
const { onFrameUpdate, loop } = props;
const framesCount = frames.length;
if (!framesCount || index < 0 || index > framesCount) {
return;
}
that.moveContainerBy(-index * that.frameSize, animate, () => {
const clonesCount = that.getClonesCount();
const firstRealIndex = clonesCount;
const lastRealIndex = (framesCount - 1) - clonesCount;
// if loop - skip clone to next frame without animation
if (loop && (index < firstRealIndex || index > lastRealIndex)) {
const isForward = that.activeIndex <= index; // treat same indexes as forward
that.goToFrame(isForward ? firstRealIndex : lastRealIndex, false);
} else {
that.activeIndex = index;
// compensate 'public' index and internal one (with clones)
onFrameUpdate && onFrameUpdate(loop ? index - clonesCount : index);
}
});
}
/**
* Moves container by specified amount
*
* @param {number} pixels
* @param {boolean} animate
* @param {() => any} done
*/
protected moveContainerBy(pixels: number, animate: boolean = false, done?: () => any) {
const that = this;
const { props, container, parent } = that;
const classList = parent.classList;
const transitionClass = props.transitionClass!;
container.style['transform'] = `translate${(props.isVertical ? 'Y' : 'X')}(${pixels}px)`;
if (animate) {
classList.add(transitionClass);
setTimeout(() => {
classList.remove(transitionClass);
done && done();
}, getLongestDuration(container));
} else {
done && done();
}
}
/**
* Calculates next valid frame index
*
* @param {boolean} forward
* @return {number}
*/
protected getNextIndex(forward: boolean) {
const that = this;
const current = that.activeIndex;
return forward ? Math.min(current + 1, that.frames.length - 1) : Math.max(current - 1, 0);
}
/**
* Ensures that clones count is not higher than children count
*
* @return {number}
*/
protected getClonesCount(): number {
const props = this.props;
return Math.min(props.clonesCount!, Children.count(props.children));
}
/**
* Checks if container position is out of bounds
*
* @return {boolean}
*/
protected isOutOfBounds(position: number) {
const that = this;
const { frameSize, frames, activeIndex } = that;
const last = frames.length - 1;
return (activeIndex === 0 && position >= 0) || (activeIndex === last && position <= -frameSize * last);
}
/**
* Sets container and frames sizes
*
* @return number
*/
protected setSizes(): number {
const that = this;
const { parent, container, frames, props } = that;
const isVertical = props.isVertical;
const dimension = !isVertical ? 'Width' : 'Height';
const dimensionLower = dimension.toLowerCase();
const framesCount = frames.length;
container.style[dimensionLower] = (framesCount * 100) + '%';
frames.forEach((child) => {
if ((child instanceof HTMLElement)) {
child.style[dimensionLower] = (100 / framesCount) + '%';
}
});
// return parent['client' + dimension];
// fractional value to move with a less than one pixel precision
return parent.getBoundingClientRect()[dimensionLower];
}
}
interface IProps extends HTMLProps<Frames> {
// dragging enabled
draggable?: boolean;
// swiping enabled
swipeable?: boolean;
// move direction
isVertical?: boolean;
// number between 0 and 1 - percentage of visible frame to consider as active
frameBoundary?: number;
// frame to start from, starting from 0
startFrame?: number;
// cycle frames
loop?: boolean;
// number of clones in loop mode
clonesCount?: number;
// class names
containerClass?: string;
frameClass?: string;
draggingClass?: string;
transitionClass?: string;
// frame update callback
onFrameUpdate?: (activeIndex: number) => void;
}