This repository has been archived by the owner on Jan 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 354
/
react-image-lightbox.js
1709 lines (1469 loc) · 58.5 KB
/
react-image-lightbox.js
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* react-image-lightbox
* Copyright 2016 Chris Fritz All rights reserved.
* @license Open source under the MIT License
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Modal from 'react-modal';
import {
translate,
getWindowWidth,
getWindowHeight,
isInSameOriginIframe,
getIEVersion,
} from './util';
import {
KEYS,
MIN_ZOOM_LEVEL,
MAX_ZOOM_LEVEL,
ZOOM_RATIO,
WHEEL_MOVE_X_THRESHOLD,
WHEEL_MOVE_Y_THRESHOLD,
ZOOM_BUTTON_INCREMENT_SIZE,
ACTION_NONE,
ACTION_MOVE,
ACTION_SWIPE,
ACTION_PINCH,
SOURCE_ANY,
SOURCE_MOUSE,
SOURCE_TOUCH,
SOURCE_POINTER,
MIN_SWIPE_DISTANCE
} from './constant';
import baseStyles from './style.scss';
// Add fallback classes for browsers without flexbox support
let styles = baseStyles;
const _ieVersion = getIEVersion();
if (_ieVersion < 10) {
styles = {
...styles,
toolbarSide: `${styles.toolbarSide} ${styles.toolbarSideNoFlex}`,
toolbarLeftSide: `${styles.toolbarLeftSide} ${styles.toolbarLeftSideNoFlex}`,
toolbarRightSide: `${styles.toolbarRightSide} ${styles.toolbarRightSideNoFlex}`,
};
}
class ReactImageLightbox extends Component {
constructor(props) {
super(props);
this.state = {
//-----------------------------
// Animation
//-----------------------------
// Lightbox is closing
// When Lightbox is mounted, if animation is enabled it will open with the reverse of the closing animation
isClosing: !props.animationDisabled,
// Component parts should animate (e.g., when images are moving, or image is being zoomed)
shouldAnimate: false,
//-----------------------------
// Zoom settings
//-----------------------------
// Zoom level of image
zoomLevel: MIN_ZOOM_LEVEL,
//-----------------------------
// Image position settings
//-----------------------------
// Horizontal offset from center
offsetX: 0,
// Vertical offset from center
offsetY: 0,
};
this.closeIfClickInner = this.closeIfClickInner.bind(this);
this.handleImageDoubleClick = this.handleImageDoubleClick.bind(this);
this.handleImageMouseWheel = this.handleImageMouseWheel.bind(this);
this.handleKeyInput = this.handleKeyInput.bind(this);
this.handleMouseUp = this.handleMouseUp.bind(this);
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.handleOuterMousewheel = this.handleOuterMousewheel.bind(this);
this.handleTouchStart = this.handleTouchStart.bind(this);
this.handleTouchMove = this.handleTouchMove.bind(this);
this.handleTouchEnd = this.handleTouchEnd.bind(this);
this.handlePointerEvent = this.handlePointerEvent.bind(this);
this.handleCaptionMousewheel = this.handleCaptionMousewheel.bind(this);
this.handleWindowResize = this.handleWindowResize.bind(this);
this.handleZoomInButtonClick = this.handleZoomInButtonClick.bind(this);
this.handleZoomOutButtonClick = this.handleZoomOutButtonClick.bind(this);
this.requestClose = this.requestClose.bind(this);
this.requestMoveNext = this.requestMoveNext.bind(this);
this.requestMovePrev = this.requestMovePrev.bind(this);
}
componentWillMount() {
// Timeouts - always clear it before umount
this.timeouts = [];
// Current action
this.currentAction = ACTION_NONE;
// Events source
this.eventsSource = SOURCE_ANY;
// Empty pointers list
this.pointerList = [];
// Prevent inner close
this.preventInnerClose = false;
this.preventInnerCloseTimeout = null;
// Whether event listeners for keyboard and mouse input have been attached or not
this.listenersAttached = false;
// Used to disable animation when changing props.mainSrc|nextSrc|prevSrc
this.keyPressed = false;
// Used to store load state / dimensions of images
this.imageCache = {};
// Time the last keydown event was called (used in keyboard action rate limiting)
this.lastKeyDownTime = 0;
// Used for debouncing window resize event
this.resizeTimeout = null;
// Used to determine when actions are triggered by the scroll wheel
this.wheelActionTimeout = null;
this.resetScrollTimeout = null;
this.scrollX = 0;
this.scrollY = 0;
// Used in panning zoomed images
this.moveStartX = 0;
this.moveStartY = 0;
this.moveStartOffsetX = 0;
this.moveStartOffsetY = 0;
// Used to swipe
this.swipeStartX = 0;
this.swipeStartY = 0;
this.swipeEndX = 0;
this.swipeEndY = 0;
// Used to pinch
this.pinchTouchList = null;
this.pinchDistance = 0;
// Used to differentiate between images with identical src
this.keyCounter = 0;
// Used to detect a move when all src's remain unchanged (four or more of the same image in a row)
this.moveRequested = false;
if (!this.props.animationDisabled) {
// Make opening animation play
this.setState({ isClosing: false });
}
}
componentDidMount() {
this.mounted = true;
ReactImageLightbox.loadStyles();
this.attachListeners();
this.loadAllImages();
}
shouldComponentUpdate() {
// Wait for move...
return !this.moveRequested;
}
componentWillReceiveProps(nextProps) {
// Iterate through the source types for prevProps and nextProps to
// determine if any of the sources changed
let sourcesChanged = false;
const prevSrcDict = {};
const nextSrcDict = {};
this.getSrcTypes().forEach((srcType) => {
if (this.props[srcType.name] !== nextProps[srcType.name]) {
sourcesChanged = true;
prevSrcDict[this.props[srcType.name]] = true;
nextSrcDict[nextProps[srcType.name]] = true;
}
});
if (sourcesChanged || this.moveRequested) {
// Reset the loaded state for images not rendered next
Object.keys(prevSrcDict).forEach((prevSrc) => {
if (!(prevSrc in nextSrcDict) && (prevSrc in this.imageCache)) {
this.imageCache[prevSrc].loaded = false;
}
});
this.moveRequested = false;
// Load any new images
this.loadAllImages(nextProps);
}
}
componentWillUnmount() {
this.mounted = false;
this.detachListeners();
this.timeouts.forEach(tid => clearTimeout(tid));
}
setTimeout(func, time) {
const id = setTimeout(() => {
this.timeouts = this.timeouts.filter(tid => tid !== id);
func();
}, time);
this.timeouts.push(id);
return id;
}
clearTimeout(id) {
this.timeouts = this.timeouts.filter(tid => tid !== id);
clearTimeout(id);
}
// Attach key and mouse input events
attachListeners() {
if (!this.listenersAttached && typeof window !== 'undefined') {
window.addEventListener('resize', this.handleWindowResize);
window.addEventListener('mouseup', this.handleMouseUp);
window.addEventListener('touchend', this.handleTouchEnd);
window.addEventListener('touchcancel', this.handleTouchEnd);
window.addEventListener('pointerdown', this.handlePointerEvent);
window.addEventListener('pointermove', this.handlePointerEvent);
window.addEventListener('pointerup', this.handlePointerEvent);
window.addEventListener('pointercancel', this.handlePointerEvent);
// Have to add an extra mouseup handler to catch mouseup events outside of the window
// if the page containing the lightbox is displayed in an iframe
if (isInSameOriginIframe()) {
window.top.addEventListener('mouseup', this.handleMouseUp);
window.top.addEventListener('touchend', this.handleTouchEnd);
window.top.addEventListener('touchcancel', this.handleTouchEnd);
window.top.addEventListener('pointerdown', this.handlePointerEvent);
window.top.addEventListener('pointermove', this.handlePointerEvent);
window.top.addEventListener('pointerup', this.handlePointerEvent);
window.top.addEventListener('pointercancel', this.handlePointerEvent);
}
this.listenersAttached = true;
}
}
// Change zoom level
changeZoom(zoomLevel, clientX, clientY) {
// Ignore if zoom disabled
if (!this.props.enableZoom) {
return;
}
// Constrain zoom level to the set bounds
const nextZoomLevel = Math.max(MIN_ZOOM_LEVEL, Math.min(MAX_ZOOM_LEVEL, zoomLevel));
// Ignore requests that don't change the zoom level
if (nextZoomLevel === this.state.zoomLevel) {
return;
} else if (nextZoomLevel === MIN_ZOOM_LEVEL) {
// Snap back to center if zoomed all the way out
return this.setState({
zoomLevel: nextZoomLevel,
offsetX: 0,
offsetY: 0,
});
}
const imageBaseSize = this.getBestImageForType('mainSrc');
if (imageBaseSize === null) {
return;
}
const currentZoomMultiplier = this.getZoomMultiplier();
const nextZoomMultiplier = this.getZoomMultiplier(nextZoomLevel);
// Default to the center of the image to zoom when no mouse position specified
const boxRect = this.getLightboxRect();
const pointerX = typeof clientX !== 'undefined' ? clientX - boxRect.left : boxRect.width / 2;
const pointerY = typeof clientY !== 'undefined' ? clientY - boxRect.top : boxRect.height / 2;
const currentImageOffsetX = ((boxRect.width - (imageBaseSize.width * currentZoomMultiplier)) / 2);
const currentImageOffsetY = ((boxRect.height - (imageBaseSize.height * currentZoomMultiplier)) / 2);
const currentImageRealOffsetX = currentImageOffsetX - this.state.offsetX;
const currentImageRealOffsetY = currentImageOffsetY - this.state.offsetY;
const currentPointerXRelativeToImage = (pointerX - currentImageRealOffsetX) / currentZoomMultiplier;
const currentPointerYRelativeToImage = (pointerY - currentImageRealOffsetY) / currentZoomMultiplier;
const nextImageRealOffsetX = pointerX - (currentPointerXRelativeToImage * nextZoomMultiplier);
const nextImageRealOffsetY = pointerY - (currentPointerYRelativeToImage * nextZoomMultiplier);
const nextImageOffsetX = ((boxRect.width - (imageBaseSize.width * nextZoomMultiplier)) / 2);
const nextImageOffsetY = ((boxRect.height - (imageBaseSize.height * nextZoomMultiplier)) / 2);
let nextOffsetX = nextImageOffsetX - nextImageRealOffsetX;
let nextOffsetY = nextImageOffsetY - nextImageRealOffsetY;
// When zooming out, limit the offset so things don't get left askew
if (this.currentAction !== ACTION_PINCH) {
const maxOffsets = this.getMaxOffsets();
if (this.state.zoomLevel > nextZoomLevel) {
nextOffsetX = Math.max(maxOffsets.minX, Math.min(maxOffsets.maxX, nextOffsetX));
nextOffsetY = Math.max(maxOffsets.minY, Math.min(maxOffsets.maxY, nextOffsetY));
}
}
this.setState({
zoomLevel: nextZoomLevel,
offsetX: nextOffsetX,
offsetY: nextOffsetY,
});
}
closeIfClickInner(event) {
if (!this.preventInnerClose && event.target.className.search(/\bril-inner\b/) > -1) {
this.requestClose(event);
}
}
setPreventInnerClose() {
if (this.preventInnerCloseTimeout) {
this.clearTimeout(this.preventInnerCloseTimeout);
}
this.preventInnerClose = true;
this.preventInnerCloseTimeout = this.setTimeout(() => {
this.preventInnerClose = false;
this.preventInnerCloseTimeout = null;
}, 100);
}
// Detach key and mouse input events
detachListeners() {
if (this.listenersAttached) {
window.removeEventListener('resize', this.handleWindowResize);
window.removeEventListener('mouseup', this.handleMouseUp);
window.removeEventListener('touchend', this.handleTouchEnd);
window.removeEventListener('touchcancel', this.handleTouchEnd);
window.removeEventListener('pointerdown', this.handlePointerEvent);
window.removeEventListener('pointermove', this.handlePointerEvent);
window.removeEventListener('pointerup', this.handlePointerEvent);
window.removeEventListener('pointercancel', this.handlePointerEvent);
if (isInSameOriginIframe()) {
window.top.removeEventListener('mouseup', this.handleMouseUp);
window.top.removeEventListener('touchend', this.handleTouchEnd);
window.top.removeEventListener('touchcancel', this.handleTouchEnd);
window.top.removeEventListener('pointerdown', this.handlePointerEvent);
window.top.removeEventListener('pointermove', this.handlePointerEvent);
window.top.removeEventListener('pointerup', this.handlePointerEvent);
window.top.removeEventListener('pointercancel', this.handlePointerEvent);
}
this.listenersAttached = false;
}
}
// Get info for the best suited image to display with the given srcType
getBestImageForType(srcType) {
let imageSrc = this.props[srcType];
let fitSizes = {};
if (this.isImageLoaded(imageSrc)) {
// Use full-size image if available
fitSizes = this.getFitSizes(this.imageCache[imageSrc].width, this.imageCache[imageSrc].height);
} else if (this.isImageLoaded(this.props[`${srcType}Thumbnail`])) {
// Fall back to using thumbnail if the image has not been loaded
imageSrc = this.props[`${srcType}Thumbnail`];
fitSizes = this.getFitSizes(this.imageCache[imageSrc].width, this.imageCache[imageSrc].height, true);
} else {
return null;
}
return {
src: imageSrc,
height: fitSizes.height,
width: fitSizes.width,
};
}
// Get sizing for when an image is larger than the window
getFitSizes(width, height, stretch) {
const boxSize = this.getLightboxRect();
let maxHeight = boxSize.height - (this.props.imagePadding * 2);
let maxWidth = boxSize.width - (this.props.imagePadding * 2);
if (!stretch) {
maxHeight = Math.min(maxHeight, height);
maxWidth = Math.min(maxWidth, width);
}
const maxRatio = maxWidth / maxHeight;
const srcRatio = width / height;
if (maxRatio > srcRatio) { // height is the constraining dimension of the photo
return {
width: width * maxHeight / height,
height: maxHeight,
};
}
return {
width: maxWidth,
height: height * maxWidth / width,
};
}
getMaxOffsets(zoomLevel = this.state.zoomLevel) {
const currentImageInfo = this.getBestImageForType('mainSrc');
if (currentImageInfo === null) {
return { maxX: 0, minX: 0, maxY: 0, minY: 0 };
}
const boxSize = this.getLightboxRect();
const zoomMultiplier = this.getZoomMultiplier(zoomLevel);
let maxX = 0;
if ((zoomMultiplier * currentImageInfo.width) - boxSize.width < 0) {
// if there is still blank space in the X dimension, don't limit except to the opposite edge
maxX = (boxSize.width - (zoomMultiplier * currentImageInfo.width)) / 2;
} else {
maxX = ((zoomMultiplier * currentImageInfo.width) - boxSize.width) / 2;
}
let maxY = 0;
if ((zoomMultiplier * currentImageInfo.height) - boxSize.height < 0) {
// if there is still blank space in the Y dimension, don't limit except to the opposite edge
maxY = (boxSize.height - (zoomMultiplier * currentImageInfo.height)) / 2;
} else {
maxY = ((zoomMultiplier * currentImageInfo.height) - boxSize.height) / 2;
}
return {
maxX,
maxY,
minX: -1 * maxX,
minY: -1 * maxY,
};
}
// Get image src types
getSrcTypes() {
return [
{
name: 'mainSrc',
keyEnding: `i${this.keyCounter}`,
},
{
name: 'mainSrcThumbnail',
keyEnding: `t${this.keyCounter}`,
},
{
name: 'nextSrc',
keyEnding: `i${this.keyCounter + 1}`,
},
{
name: 'nextSrcThumbnail',
keyEnding: `t${this.keyCounter + 1}`,
},
{
name: 'prevSrc',
keyEnding: `i${this.keyCounter - 1}`,
},
{
name: 'prevSrcThumbnail',
keyEnding: `t${this.keyCounter - 1}`,
},
];
}
/**
* Get sizing when the image is scaled
*/
getZoomMultiplier(zoomLevel = this.state.zoomLevel) {
return ZOOM_RATIO ** zoomLevel;
}
/**
* Get the size of the lightbox in pixels
*/
getLightboxRect() {
if (this.outerEl) {
return this.outerEl.getBoundingClientRect();
}
return {
width: getWindowWidth(),
height: getWindowHeight(),
top: 0,
right: 0,
bottom: 0,
left: 0,
};
}
/**
* Handle user keyboard actions
*/
handleKeyInput(event) {
event.stopPropagation();
// Ignore key input during animations
if (this.isAnimating()) {
return;
}
// Allow slightly faster navigation through the images when user presses keys repeatedly
if (event.type === 'keyup') {
this.lastKeyDownTime -= this.props.keyRepeatKeyupBonus;
return;
}
const keyCode = event.which || event.keyCode;
// Ignore key presses that happen too close to each other (when rapid fire key pressing or holding down the key)
// But allow it if it's a lightbox closing action
const currentTime = new Date();
if ((currentTime.getTime() - this.lastKeyDownTime) < this.props.keyRepeatLimit &&
keyCode !== KEYS.ESC
) {
return;
}
this.lastKeyDownTime = currentTime.getTime();
switch (keyCode) {
// ESC key closes the lightbox
case KEYS.ESC:
event.preventDefault();
this.requestClose(event);
break;
// Left arrow key moves to previous image
case KEYS.LEFT_ARROW:
if (!this.props.prevSrc) {
return;
}
event.preventDefault();
this.keyPressed = true;
this.requestMovePrev(event);
break;
// Right arrow key moves to next image
case KEYS.RIGHT_ARROW:
if (!this.props.nextSrc) {
return;
}
event.preventDefault();
this.keyPressed = true;
this.requestMoveNext(event);
break;
default:
}
}
/**
* Handle a mouse wheel event over the lightbox container
*/
handleOuterMousewheel(event) {
// Prevent scrolling of the background
event.preventDefault();
event.stopPropagation();
const xThreshold = WHEEL_MOVE_X_THRESHOLD;
let actionDelay = 0;
const imageMoveDelay = 500;
this.clearTimeout(this.resetScrollTimeout);
this.resetScrollTimeout = this.setTimeout(() => {
this.scrollX = 0;
this.scrollY = 0;
}, 300);
// Prevent rapid-fire zoom behavior
if (this.wheelActionTimeout !== null || this.isAnimating()) {
return;
}
if (Math.abs(event.deltaY) < Math.abs(event.deltaX)) {
// handle horizontal scrolls with image moves
this.scrollY = 0;
this.scrollX += event.deltaX;
const bigLeapX = xThreshold / 2;
// If the scroll amount has accumulated sufficiently, or a large leap was taken
if (this.scrollX >= xThreshold || event.deltaX >= bigLeapX) {
// Scroll right moves to next
this.requestMoveNext(event);
actionDelay = imageMoveDelay;
this.scrollX = 0;
} else if (this.scrollX <= -1 * xThreshold || event.deltaX <= -1 * bigLeapX) {
// Scroll left moves to previous
this.requestMovePrev(event);
actionDelay = imageMoveDelay;
this.scrollX = 0;
}
}
// Allow successive actions after the set delay
if (actionDelay !== 0) {
this.wheelActionTimeout = this.setTimeout(() => {
this.wheelActionTimeout = null;
}, actionDelay);
}
}
handleImageMouseWheel(event) {
event.preventDefault();
const yThreshold = WHEEL_MOVE_Y_THRESHOLD;
if (Math.abs(event.deltaY) >= Math.abs(event.deltaX)) {
event.stopPropagation();
// If the vertical scroll amount was large enough, perform a zoom
if (Math.abs(event.deltaY) < yThreshold) {
return;
}
this.scrollX = 0;
this.scrollY += event.deltaY;
this.changeZoom(
this.state.zoomLevel - event.deltaY,
event.clientX,
event.clientY
);
}
}
/**
* Handle a double click on the current image
*/
handleImageDoubleClick(event) {
if (this.state.zoomLevel > MIN_ZOOM_LEVEL) {
// A double click when zoomed in zooms all the way out
this.changeZoom(
MIN_ZOOM_LEVEL,
event.clientX,
event.clientY
);
} else {
// A double click when zoomed all the way out zooms in
this.changeZoom(
this.state.zoomLevel + ZOOM_BUTTON_INCREMENT_SIZE,
event.clientX,
event.clientY
);
}
}
static isTargetMatchImage(target) {
return target && /ril-image-current/.test(target.className);
}
shouldHandleEvent(source) {
if (this.eventsSource === source) {
return true;
}
if (this.eventsSource === SOURCE_ANY) {
this.eventsSource = source;
return true;
}
switch (source) {
case SOURCE_MOUSE:
return false;
case SOURCE_TOUCH:
this.eventsSource = SOURCE_TOUCH;
this.filterPointersBySource();
return true;
case SOURCE_POINTER:
if (this.eventsSource === SOURCE_MOUSE) {
this.eventsSource = SOURCE_POINTER;
this.filterPointersBySource();
return true;
}
return false;
default:
return false;
}
}
static parseMouseEvent(mouseEvent) {
return {
id: 'mouse',
source: SOURCE_MOUSE,
x: parseInt(mouseEvent.clientX, 10),
y: parseInt(mouseEvent.clientY, 10)
};
}
static parseTouchPointer(touchPointer) {
return {
id: touchPointer.identifier,
source: SOURCE_TOUCH,
x: parseInt(touchPointer.clientX, 10),
y: parseInt(touchPointer.clientY, 10)
};
}
static parsePointerEvent(pointerEvent) {
return {
id: pointerEvent.pointerId,
source: SOURCE_POINTER,
x: parseInt(pointerEvent.clientX, 10),
y: parseInt(pointerEvent.clientY, 10)
};
}
addPointer(pointer) {
this.pointerList.push(pointer);
}
removePointer(pointer) {
this.pointerList = this.pointerList.filter(({id}) => id !== pointer.id);
}
filterPointersBySource() {
this.pointerList = this.pointerList.filter(({source}) => source === this.eventsSource);
}
handleMouseDown(event) {
if (this.shouldHandleEvent(SOURCE_MOUSE) && ReactImageLightbox.isTargetMatchImage(event.target)) {
this.addPointer(ReactImageLightbox.parseMouseEvent(event));
this.multiPointerStart(event);
}
}
handleMouseMove(event) {
if (this.shouldHandleEvent(SOURCE_MOUSE)) {
this.multiPointerMove(event, [ReactImageLightbox.parseMouseEvent(event)]);
}
}
handleMouseUp(event) {
if (this.shouldHandleEvent(SOURCE_MOUSE)) {
this.removePointer(ReactImageLightbox.parseMouseEvent(event));
this.multiPointerEnd(event);
}
}
handlePointerEvent(event) {
if (this.shouldHandleEvent(SOURCE_POINTER)) {
switch (event.type) {
case 'pointerdown':
if (ReactImageLightbox.isTargetMatchImage(event.target)) {
this.addPointer(ReactImageLightbox.parsePointerEvent(event));
this.multiPointerStart(event);
}
break;
case 'pointermove':
this.multiPointerMove(event, [ReactImageLightbox.parsePointerEvent(event)]);
break;
case 'pointerup':
case 'pointercancel':
this.removePointer(ReactImageLightbox.parsePointerEvent(event));
this.multiPointerEnd(event);
break;
default:
break;
}
}
}
handleTouchStart(event) {
if (this.shouldHandleEvent(SOURCE_TOUCH) && ReactImageLightbox.isTargetMatchImage(event.target)) {
[].forEach.call(event.changedTouches,
eventTouch => this.addPointer(ReactImageLightbox.parseTouchPointer(eventTouch)));
this.multiPointerStart(event);
}
}
handleTouchMove(event) {
if (this.shouldHandleEvent(SOURCE_TOUCH)) {
this.multiPointerMove(event, [].map.call(event.changedTouches,
eventTouch => ReactImageLightbox.parseTouchPointer(eventTouch)));
}
}
handleTouchEnd(event) {
if (this.shouldHandleEvent(SOURCE_TOUCH)) {
[].map.call(event.changedTouches,
touch => this.removePointer(ReactImageLightbox.parseTouchPointer(touch)));
this.multiPointerEnd(event);
}
}
decideMoveOrSwipe(pointer) {
if (this.state.zoomLevel <= MIN_ZOOM_LEVEL) {
this.handleSwipeStart(pointer);
} else {
this.handleMoveStart(pointer);
}
}
multiPointerStart(event) {
this.handleEnd(null);
switch (this.pointerList.length) {
case 1: {
event.preventDefault();
this.decideMoveOrSwipe(this.pointerList[0]);
break;
}
case 2: {
event.preventDefault();
this.handlePinchStart(this.pointerList);
break;
}
default:
break;
}
}
multiPointerMove(event, pointerList) {
switch (this.currentAction) {
case ACTION_MOVE: {
event.preventDefault();
this.handleMove(pointerList[0]);
break;
}
case ACTION_SWIPE: {
event.preventDefault();
this.handleSwipe(pointerList[0]);
break;
}
case ACTION_PINCH: {
event.preventDefault();
this.handlePinch(pointerList);
break;
}
default:
break;
}
}
multiPointerEnd(event) {
if (this.currentAction !== ACTION_NONE) {
this.setPreventInnerClose();
this.handleEnd(event);
}
switch (this.pointerList.length) {
case 0: {
this.eventsSource = SOURCE_ANY;
break;
}
case 1: {
event.preventDefault();
this.decideMoveOrSwipe(this.pointerList[0]);
break;
}
case 2: {
event.preventDefault();
this.handlePinchStart(this.pointerList);
break;
}
default:
break;
}
}
handleEnd(event) {
switch (this.currentAction) {
case ACTION_MOVE:
this.handleMoveEnd(event);
break;
case ACTION_SWIPE:
this.handleSwipeEnd(event);
break;
case ACTION_PINCH:
this.handlePinchEnd(event);
break;
default:
break;
}
}
// Handle move start over the lightbox container
// This happens:
// - On a mouseDown event
// - On a touchstart event
handleMoveStart({x: clientX, y: clientY}) {
if (!this.props.enableZoom) {
return;
}
this.currentAction = ACTION_MOVE;
this.moveStartX = clientX;
this.moveStartY = clientY;
this.moveStartOffsetX = this.state.offsetX;
this.moveStartOffsetY = this.state.offsetY;
}
// Handle dragging over the lightbox container
// This happens:
// - After a mouseDown and before a mouseUp event
// - After a touchstart and before a touchend event
handleMove({x: clientX, y: clientY}) {
const newOffsetX = (this.moveStartX - clientX) + this.moveStartOffsetX;
const newOffsetY = (this.moveStartY - clientY) + this.moveStartOffsetY;
if (this.state.offsetX !== newOffsetX || this.state.offsetY !== newOffsetY) {
this.setState({
offsetX: newOffsetX,
offsetY: newOffsetY,
});
}
}
handleMoveEnd() {
this.currentAction = ACTION_NONE;
this.moveStartX = 0;
this.moveStartY = 0;
this.moveStartOffsetX = 0;
this.moveStartOffsetY = 0;
// Snap image back into frame if outside max offset range
const maxOffsets = this.getMaxOffsets();
const nextOffsetX = Math.max(maxOffsets.minX, Math.min(maxOffsets.maxX, this.state.offsetX));
const nextOffsetY = Math.max(maxOffsets.minY, Math.min(maxOffsets.maxY, this.state.offsetY));
if (nextOffsetX !== this.state.offsetX || nextOffsetY !== this.state.offsetY) {
this.setState({
offsetX: nextOffsetX,
offsetY: nextOffsetY,
shouldAnimate: true,
});
this.setTimeout(() => {
this.setState({ shouldAnimate: false });
}, this.props.animationDuration);
}
}
handleSwipeStart({x: clientX, y: clientY}) {
this.currentAction = ACTION_SWIPE;
this.swipeStartX = clientX;
this.swipeStartY = clientY;
this.swipeEndX = clientX;
this.swipeEndY = clientY;
}
handleSwipe({x: clientX, y: clientY}) {
this.swipeEndX = clientX;
this.swipeEndY = clientY;
}
handleSwipeEnd(event) {
const xDiff = this.swipeEndX - this.swipeStartX;
const xDiffAbs = Math.abs(xDiff);
const yDiffAbs = Math.abs(this.swipeEndY - this.swipeStartY);
this.currentAction = ACTION_NONE;
this.swipeStartX = 0;
this.swipeStartY = 0;
this.swipeEndX = 0;
this.swipeEndY = 0;
if (!event || this.isAnimating() || xDiffAbs < yDiffAbs * 1.5) {
return;
}
if (xDiffAbs < MIN_SWIPE_DISTANCE) {
const boxRect = this.getLightboxRect();
if (xDiffAbs < boxRect.width / 4) {
return;
}
}
if (xDiff > 0 && this.props.prevSrc) {
event.preventDefault();
this.requestMovePrev();
} else if (xDiff < 0 && this.props.nextSrc) {
event.preventDefault();
this.requestMoveNext();
}
}
calculatePinchDistance([a, b] = this.pinchTouchList) {
return Math.sqrt(((a.x - b.x) ** 2) + ((a.y - b.y) ** 2));
}
calculatePinchCenter([a, b] = this.pinchTouchList) {
return {
x: a.x - ((a.x - b.x) / 2),
y: a.y - ((a.y - b.y) / 2)
};
}
handlePinchStart(pointerList) {
if (!this.props.enableZoom) {
return;
}
this.currentAction = ACTION_PINCH;