-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathindex.js
1431 lines (1210 loc) · 38.4 KB
/
index.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
/**
* Tobii
*
* @author midzer
* @version 2.6.4
* @url https://github.com/midzer/tobii
*
* MIT License
*/
import ImageType from './types/image'
import IframeType from './types/iframe'
import HtmlType from './types/html'
import YoutubeType from './types/youtube'
export default function Tobii (userOptions) {
/**
* Global variables
*
*/
const SUPPORTED_ELEMENTS = {
image: new ImageType(), // default
html: new HtmlType(),
iframe: new IframeType(),
youtube: new YoutubeType()
}
const FOCUSABLE_ELEMENTS = [
'a[href]:not([tabindex^="-"]):not([inert])',
'area[href]:not([tabindex^="-"]):not([inert])',
'input:not([disabled]):not([inert])',
'select:not([disabled]):not([inert])',
'textarea:not([disabled]):not([inert])',
'button:not([disabled]):not([inert])',
'iframe:not([tabindex^="-"]):not([inert])',
'audio:not([tabindex^="-"]):not([inert])',
'video:not([tabindex^="-"]):not([inert])',
'[contenteditable]:not([tabindex^="-"]):not([inert])',
'[tabindex]:not([tabindex^="-"]):not([inert])'
]
let userSettings = {}
const WAITING_ELS = []
const GROUP_ATTS = {
gallery: [],
slider: null,
sliderElements: [],
elementsLength: 0,
currentIndex: 0,
x: 0
}
let lightbox = null
let prevButton = null
let nextButton = null
let closeButton = null
let counter = null
let lastFocus = null
let offset = null
let isYouTubeDependencyLoaded = false
let groups = {}
let activeGroup = null
let pointerDownCache = []
let lastTapTime = 0
const MIN_SCALE = 1
const MAX_SCALE = 4
const DOUBLE_TAP_TIME = 500 // milliseconds
const SCALE_SENSITIVITY = 10
const TRANSFORM = {
element: null,
originX: 0,
originY: 0,
translateX: 0,
translateY: 0,
scale: MIN_SCALE
}
const DRAG = {
startX: 0,
startY: 0,
x: 0,
y: 0,
distance: 0
}
/**
* Merge default options with user options
*
* @param {Object} userOptions - Optional user options
* @returns {Object} - Custom options
*/
const mergeOptions = (userOptions) => {
// Default options
const OPTIONS = {
selector: '.lightbox',
captions: true,
captionsSelector: 'img',
captionAttribute: 'alt',
captionText: null,
captionHTML: false,
nav: 'auto',
navText: [
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path stroke="none" d="M0 0h24v24H0z"/><polyline points="15 6 9 12 15 18" /></svg>',
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path stroke="none" d="M0 0h24v24H0z"/><polyline points="9 6 15 12 9 18" /></svg>'
],
navLabel: [
'Previous image',
'Next image'
],
close: true,
closeText: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path stroke="none" d="M0 0h24v24H0z"/><line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" /></svg>',
closeLabel: 'Close lightbox',
loadingIndicatorLabel: 'Image loading',
counter: true,
download: false, // TODO
downloadText: '', // TODO
downloadLabel: 'Download image', // TODO
keyboard: true,
zoom: true,
zoomText: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path stroke="none" d="M0 0h24v24H0z"/><polyline points="16 4 20 4 20 8" /><line x1="14" y1="10" x2="20" y2="4" /><polyline points="8 20 4 20 4 16" /><line x1="4" y1="20" x2="10" y2="14" /><polyline points="16 20 20 20 20 16" /><line x1="14" y1="14" x2="20" y2="20" /><polyline points="8 4 4 4 4 8" /><line x1="4" y1="4" x2="10" y2="10" /></svg>',
docClose: true,
swipeClose: true,
hideScrollbar: true,
draggable: true,
threshold: 100,
rtl: false, // TODO
loop: false, // TODO
autoplayVideo: false,
modal: false,
theme: 'tobii--theme-default'
}
return {
...OPTIONS, ...userOptions
}
}
/**
* Init
*
*/
const init = (userOptions) => {
if (document.querySelector('div.tobii')) {
console.log('Multiple lightbox instances not supported.')
return
}
// Merge user options into defaults
userSettings = mergeOptions(userOptions)
// Check if the lightbox already exists
if (!lightbox) {
createLightbox()
}
// Get a list of all elements within the document
const LIGHTBOX_TRIGGER_ELS = document.querySelectorAll(userSettings.selector)
if (!LIGHTBOX_TRIGGER_ELS) {
throw new Error(`Ups, I can't find the selector ${userSettings.selector} on this website.`)
}
// Execute a few things once per element
const uniqueMap = []
LIGHTBOX_TRIGGER_ELS.forEach((lightboxTriggerEl) => {
const group = lightboxTriggerEl.hasAttribute('data-group') ? lightboxTriggerEl.getAttribute('data-group') : 'default'
let uid = lightboxTriggerEl.href
if (lightboxTriggerEl.hasAttribute('data-target')) {
uid = lightboxTriggerEl.getAttribute('data-target')
}
uid += '__' + group
if (typeof uniqueMap[uid] !== 'undefined') {
// duplicate - skip, but still open lightbox on click
lightboxTriggerEl.addEventListener('click', (event) => {
selectGroup(group)
open()
event.preventDefault()
})
} else {
// new element
uniqueMap[uid] = 1
checkDependencies(lightboxTriggerEl)
}
})
}
/**
* Check dependencies
*
* @param {HTMLElement} el - Element to add
*/
const checkDependencies = (el) => {
// Check if there is a YouTube video and if the YouTube iframe-API is ready
if (document.querySelector('[data-type="youtube"]') !== null && !isYouTubeDependencyLoaded) {
if (document.getElementById('iframe_api') === null) {
const TAG = document.createElement('script')
const FIRST_SCRIPT_TAG = document.getElementsByTagName('script')[0]
TAG.id = 'iframe_api'
TAG.src = 'https://www.youtube.com/iframe_api'
FIRST_SCRIPT_TAG.parentNode.insertBefore(TAG, FIRST_SCRIPT_TAG)
}
if (WAITING_ELS.indexOf(el) === -1) {
WAITING_ELS.push(el)
}
window.onYouTubePlayerAPIReady = () => {
WAITING_ELS.forEach((waitingEl) => {
add(waitingEl)
})
isYouTubeDependencyLoaded = true
}
} else {
add(el)
}
}
/**
* Get group name from element
*
* @param {HTMLElement} el
* @return {string}
*/
const getGroupName = (el) => {
return el.hasAttribute('data-group') ? el.getAttribute('data-group') : 'default'
}
/**
* Copy an object. (The secure way)
*
* @param {object} object
* @return {object}
*/
const copyObject = (object) => {
return JSON.parse(JSON.stringify(object))
}
/**
* Add element
*
* @param {HTMLElement} el - Element to add
*/
const add = (el) => {
const newGroup = getGroupName(el)
if (!Object.prototype.hasOwnProperty.call(groups, newGroup)) {
groups[newGroup] = copyObject(GROUP_ATTS)
// Create slider
groups[newGroup].slider = document.createElement('div')
groups[newGroup].slider.className = 'tobii__slider'
// Hide slider
groups[newGroup].slider.setAttribute('aria-hidden', 'true')
lightbox.appendChild(groups[newGroup].slider)
}
// Check if element already exists
if (groups[newGroup].gallery.indexOf(el) === -1) {
groups[newGroup].gallery.push(el)
groups[newGroup].elementsLength++
// Set zoom icon if necessary
if ((userSettings.zoom && el.querySelector('img') && el.getAttribute('data-zoom') !== 'false') ||
el.getAttribute('data-zoom') === 'true') {
const TOBII_ZOOM = document.createElement('div')
TOBII_ZOOM.className = 'tobii-zoom__icon'
TOBII_ZOOM.innerHTML = userSettings.zoomText
el.classList.add('tobii-zoom')
el.appendChild(TOBII_ZOOM)
}
// Bind click event handler
el.addEventListener('click', triggerTobii)
const model = getModel(el)
// Create slide
const SLIDER_ELEMENT = document.createElement('div')
const SLIDER_ELEMENT_CONTENT = document.createElement('div')
SLIDER_ELEMENT.className = 'tobii__slide'
SLIDER_ELEMENT.style.position = 'absolute'
SLIDER_ELEMENT.style.left = `${groups[newGroup].x * 100}%`
// Hide slide
SLIDER_ELEMENT.setAttribute('aria-hidden', 'true')
// Create type elements
model.init(el, SLIDER_ELEMENT_CONTENT, userSettings)
// Add slide content container to slider element
SLIDER_ELEMENT.appendChild(SLIDER_ELEMENT_CONTENT)
// Add slider element to slider
groups[newGroup].slider.appendChild(SLIDER_ELEMENT)
groups[newGroup].sliderElements.push(SLIDER_ELEMENT)
++groups[newGroup].x
if (isOpen() && newGroup === activeGroup) {
updateConfig()
updateLightbox()
}
} else {
throw new Error('Ups, element already added.')
}
}
/**
* Remove element
*
* @param {HTMLElement} el - Element to remove
*/
const remove = (el) => {
const GROUP_NAME = getGroupName(el)
// Check if element exists
if (groups[GROUP_NAME].gallery.indexOf(el) === -1) {
throw new Error(`Ups, I can't find a slide for the element ${el}.`)
} else {
const SLIDE_INDEX = groups[GROUP_NAME].gallery.indexOf(el)
const SLIDE_EL = groups[GROUP_NAME].sliderElements[SLIDE_INDEX]
// If the element to be removed is the currently visible slide
if (isOpen() && GROUP_NAME === activeGroup && SLIDE_INDEX === groups[GROUP_NAME].currentIndex) {
if (groups[GROUP_NAME].elementsLength === 1) {
close()
throw new Error('Ups, I\'ve closed. There are no slides more to show.')
} else {
// TODO If there is only one slide left, deactivate horizontal dragging/ swiping
// TODO Set new absolute position per slide
// If the first slide is displayed
if (groups[GROUP_NAME].currentIndex === 0) {
next()
} else {
previous()
}
updateConfig()
updateLightbox()
}
}
groups[GROUP_NAME].gallery.splice(groups[GROUP_NAME].gallery.indexOf(el))
groups[GROUP_NAME].sliderElements.splice(groups[GROUP_NAME].gallery.indexOf(el))
groups[GROUP_NAME].elementsLength--
--groups[GROUP_NAME].x
// Remove zoom icon if necessary
if (userSettings.zoom && el.querySelector('.tobii-zoom__icon')) {
const ZOOM_ICON = el.querySelector('.tobii-zoom__icon')
ZOOM_ICON.parentNode.classList.remove('tobii-zoom')
ZOOM_ICON.parentNode.removeChild(ZOOM_ICON)
}
// Unbind click event handler
el.removeEventListener('click', triggerTobii)
// Remove slide
SLIDE_EL.parentNode.removeChild(SLIDE_EL)
}
}
/**
* Create the lightbox
*
*/
const createLightbox = () => {
// Create the lightbox container
lightbox = document.createElement('div')
lightbox.setAttribute('role', 'dialog')
lightbox.setAttribute('aria-hidden', 'true')
lightbox.classList.add('tobii')
// Adc theme class
lightbox.classList.add(userSettings.theme)
// Create the previous button
prevButton = document.createElement('button')
prevButton.className = 'tobii__btn tobii__btn--previous'
prevButton.setAttribute('type', 'button')
prevButton.setAttribute('aria-label', userSettings.navLabel[0])
prevButton.innerHTML = userSettings.navText[0]
lightbox.appendChild(prevButton)
// Create the next button
nextButton = document.createElement('button')
nextButton.className = 'tobii__btn tobii__btn--next'
nextButton.setAttribute('type', 'button')
nextButton.setAttribute('aria-label', userSettings.navLabel[1])
nextButton.innerHTML = userSettings.navText[1]
lightbox.appendChild(nextButton)
// Create the close button
closeButton = document.createElement('button')
closeButton.className = 'tobii__btn tobii__btn--close'
closeButton.setAttribute('type', 'button')
closeButton.setAttribute('aria-label', userSettings.closeLabel)
closeButton.innerHTML = userSettings.closeText
lightbox.appendChild(closeButton)
// Create the counter
counter = document.createElement('div')
counter.className = 'tobii__counter'
lightbox.appendChild(counter)
document.body.appendChild(lightbox)
}
const getModel = (el) => {
const type = el.getAttribute('data-type')
if (SUPPORTED_ELEMENTS[type] !== undefined) {
return SUPPORTED_ELEMENTS[type]
} else {
// unknown - use default
if (el.hasAttribute('data-type')) {
console.log('Unknown lightbox element type: ' + type)
}
return SUPPORTED_ELEMENTS.image
}
}
/**
* Open Tobii
*
* @param {number} index - Index to load
*/
const open = (index = 0) => {
if (isOpen()) {
throw new Error('Ups, I\'m aleady open.')
}
if (index === -1 || index >= groups[activeGroup].elementsLength) {
throw new Error(`Ups, I can't find slide ${index}.`)
}
document.documentElement.classList.add('tobii-is-open')
document.body.classList.add('tobii-is-open')
document.body.classList.add('tobii-is-open-' + activeGroup)
updateConfig()
// Hide close if necessary
if (!userSettings.close) {
closeButton.disabled = false
closeButton.setAttribute('aria-hidden', 'true')
}
// Save user’s focus
lastFocus = document.activeElement
// Use `history.pushState()` to make sure the "Back" button behavior
// that aligns with the user's expectations
const stateObj = {
tobii: 'close'
}
const url = window.location.href
window.history.pushState(stateObj, 'Image', url)
// Set current index
groups[activeGroup].currentIndex = index
bindEvents()
// Load slide
load(groups[activeGroup].currentIndex)
// Show slider
groups[activeGroup].slider.setAttribute('aria-hidden', 'false')
// Show lightbox
lightbox.setAttribute('aria-hidden', 'false')
updateLightbox()
// Preload previous and next slide
preload(groups[activeGroup].currentIndex + 1)
preload(groups[activeGroup].currentIndex - 1)
groups[activeGroup].slider.classList.add('tobii__slider--animate')
// Create and dispatch a new event
const openEvent = new window.CustomEvent('open', {
detail: {
group: activeGroup
}
})
lightbox.dispatchEvent(openEvent)
}
/**
* Close Tobii
*
*/
const close = () => {
if (!isOpen()) {
throw new Error('Ups, I\'m already closed.')
}
document.documentElement.classList.remove('tobii-is-open')
document.body.classList.remove('tobii-is-open')
document.body.classList.remove('tobii-is-open-' + activeGroup)
unbindEvents()
// Remove entry in browser history
if (window.history.state !== null) {
if (window.history.state.tobii === 'close') {
window.history.back()
}
}
// Reenable the user’s focus
lastFocus.focus()
// Don't forget to cleanup our current element
leave(groups[activeGroup].currentIndex)
cleanup(groups[activeGroup].currentIndex)
// Hide lightbox
lightbox.setAttribute('aria-hidden', 'true')
// Hide slider
groups[activeGroup].slider.setAttribute('aria-hidden', 'true')
// Reset current index
groups[activeGroup].currentIndex = 0
// Remove the hack to prevent animation during opening
groups[activeGroup].slider.classList.remove('tobii__slider--animate')
// Create and dispatch a new event
const closeEvent = new window.CustomEvent('close', {
detail: {
group: activeGroup
}
})
lightbox.dispatchEvent(closeEvent)
}
/**
* Preload slide
*
* @param {number} index - Index to preload
*/
const preload = (index) => {
if (groups[activeGroup].sliderElements[index] === undefined) {
return
}
const CONTAINER = groups[activeGroup].sliderElements[index].querySelector('[data-type]')
const model = getModel(CONTAINER)
model.onPreload(CONTAINER)
}
/**
* Load slide
* Will be called when opening the lightbox or moving index
*
* @param {number} index - Index to load
*/
const load = (index) => {
if (groups[activeGroup].sliderElements[index] === undefined) {
return
}
const CONTAINER = groups[activeGroup].sliderElements[index].querySelector('[data-type]')
const model = getModel(CONTAINER)
// Add active slide class
groups[activeGroup].sliderElements[index].classList.add('tobii__slide--is-active')
groups[activeGroup].sliderElements[index].setAttribute('aria-hidden', 'false')
model.onLoad(CONTAINER, activeGroup)
}
/**
* Select a slide
*
* @param {number} index - Index to select
*/
const select = (index) => {
const currIndex = groups[activeGroup].currentIndex
if (!isOpen()) {
throw new Error('Ups, I\'m closed.')
}
if (isOpen()) {
if (!index && index !== 0) {
throw new Error('Ups, no slide specified.')
}
if (index === groups[activeGroup].currentIndex) {
throw new Error(`Ups, slide ${index} is already selected.`)
}
if (index === -1 || index >= groups[activeGroup].elementsLength) {
throw new Error(`Ups, I can't find slide ${index}.`)
}
}
// Set current index
groups[activeGroup].currentIndex = index
leave(currIndex)
load(index)
if (index < currIndex) {
updateLightbox('left')
cleanup(currIndex)
preload(index - 1)
}
if (index > currIndex) {
updateLightbox('right')
cleanup(currIndex)
preload(index + 1)
}
}
/**
* Select the previous slide
*
*/
const previous = () => {
if (!isOpen()) {
throw new Error('Ups, I\'m closed.')
}
if (groups[activeGroup].currentIndex > 0) {
leave(groups[activeGroup].currentIndex)
load(--groups[activeGroup].currentIndex)
updateLightbox('left')
cleanup(groups[activeGroup].currentIndex + 1)
preload(groups[activeGroup].currentIndex - 1)
}
// Create and dispatch a new event
const previousEvent = new window.CustomEvent('previous', {
detail: {
group: activeGroup
}
})
lightbox.dispatchEvent(previousEvent)
}
/**
* Select the next slide
*
*/
const next = () => {
if (!isOpen()) {
throw new Error('Ups, I\'m closed.')
}
if (groups[activeGroup].currentIndex < groups[activeGroup].elementsLength - 1) {
leave(groups[activeGroup].currentIndex)
load(++groups[activeGroup].currentIndex)
updateLightbox('right')
cleanup(groups[activeGroup].currentIndex - 1)
preload(groups[activeGroup].currentIndex + 1)
}
// Create and dispatch a new event
const nextEvent = new window.CustomEvent('next', {
detail: {
group: activeGroup
}
})
lightbox.dispatchEvent(nextEvent)
}
/**
* Select a group
*
* @param {string} name - Name of the group to select
*/
const selectGroup = (name) => {
if (isOpen()) {
throw new Error('Ups, I\'m open.')
}
if (!name) {
throw new Error('Ups, no group specified.')
}
if (name && !Object.prototype.hasOwnProperty.call(groups, name)) {
throw new Error(`Ups, I don't have a group called "${name}".`)
}
activeGroup = name
}
/**
* Leave slide
* Will be called before moving index
*
* @param {number} index - Index to leave
*/
const leave = (index) => {
if (groups[activeGroup].sliderElements[index] === undefined) {
return
}
const CONTAINER = groups[activeGroup].sliderElements[index].querySelector('[data-type]')
const model = getModel(CONTAINER)
// Remove active slide class
groups[activeGroup].sliderElements[index].classList.remove('tobii__slide--is-active')
groups[activeGroup].sliderElements[index].setAttribute('aria-hidden', 'true')
model.onLeave(CONTAINER)
}
/**
* Cleanup slide
* Will be called after moving index
*
* @param {number} index - Index to cleanup
*/
const cleanup = (index) => {
if (groups[activeGroup].sliderElements[index] === undefined) {
return
}
const CONTAINER = groups[activeGroup].sliderElements[index].querySelector('[data-type]')
const model = getModel(CONTAINER)
model.onCleanup(CONTAINER)
DRAG.startX = 0
DRAG.startY = 0
DRAG.x = 0
DRAG.y = 0
DRAG.distance = 0
lastTapTime = 0
if (isZoomed()) resetZoom()
}
/**
* Update offset
*
*/
const updateOffset = () => {
offset = -groups[activeGroup].currentIndex * lightbox.offsetWidth
groups[activeGroup].slider.style.transform = `translate(${offset}px, 0)`
}
/**
* Update counter
*
*/
const updateCounter = () => {
counter.textContent = `${groups[activeGroup].currentIndex + 1}/${groups[activeGroup].elementsLength}`
}
/**
* Update focus
*
* @param {string|null} dir - Current slide direction
*/
const updateFocus = (dir) => {
if ((userSettings.nav === true || userSettings.nav === 'auto') &&
!isTouchDevice() && groups[activeGroup].elementsLength > 1) {
prevButton.setAttribute('aria-hidden', 'true')
prevButton.disabled = true
nextButton.setAttribute('aria-hidden', 'true')
nextButton.disabled = true
// If there is only one slide
if (groups[activeGroup].elementsLength === 1) {
if (userSettings.close) {
closeButton.focus()
}
} else {
// If the first slide is displayed
if (groups[activeGroup].currentIndex === 0) {
nextButton.setAttribute('aria-hidden', 'false')
nextButton.disabled = false
nextButton.focus()
// If the last slide is displayed
} else if (groups[activeGroup].currentIndex === groups[activeGroup].elementsLength - 1) {
prevButton.setAttribute('aria-hidden', 'false')
prevButton.disabled = false
prevButton.focus()
} else {
prevButton.setAttribute('aria-hidden', 'false')
prevButton.disabled = false
nextButton.setAttribute('aria-hidden', 'false')
nextButton.disabled = false
if (dir === 'left') {
prevButton.focus()
} else {
nextButton.focus()
}
}
}
} else if (userSettings.close) {
closeButton.focus()
}
}
/**
* Resize event
*
*/
const resizeHandler = () => {
updateOffset()
}
/**
* Click event handler to trigger Tobii
*
*/
const triggerTobii = (event) => {
event.preventDefault()
activeGroup = getGroupName(event.currentTarget)
open(groups[activeGroup].gallery.indexOf(event.currentTarget))
}
/**
* Click event handler
*
*/
const clickHandler = (event) => {
if (event.target === prevButton) {
previous()
} else if (event.target === nextButton) {
next()
} else if (event.target === closeButton ||
(event.target.classList.contains('tobii__slide') && userSettings.docClose)) {
close()
}
event.stopPropagation()
}
/**
* Get the focusable children of the given element
*
* @return {Array<Element>}
*/
const getFocusableChildren = () => {
return Array.prototype.slice.call(
lightbox.querySelectorAll(
`.tobii__btn:not([disabled]), .tobii__slide--is-active ${FOCUSABLE_ELEMENTS.join(', .tobii__slide--is-active ')}`
)
).filter((child) => {
return !!(
child.offsetWidth ||
child.offsetHeight ||
child.getClientRects().length
)
})
}
/**
* Keydown event handler
*
* @TODO: Remove the deprecated event.keyCode when Edge support event.code and we drop f*cking IE
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
*/
const keydownHandler = (event) => {
const FOCUSABLE_CHILDREN = getFocusableChildren()
const FOCUSED_ITEM_INDEX = FOCUSABLE_CHILDREN.indexOf(document.activeElement)
if (event.keyCode === 9 || event.code === 'Tab') {
// If the SHIFT key is being pressed while tabbing (moving backwards) and
// the currently focused item is the first one, move the focus to the last
// focusable item from the slide
if (event.shiftKey && FOCUSED_ITEM_INDEX === 0) {
FOCUSABLE_CHILDREN[FOCUSABLE_CHILDREN.length - 1].focus()
event.preventDefault()
// If the SHIFT key is not being pressed (moving forwards) and the currently
// focused item is the last one, move the focus to the first focusable item
// from the slide
} else if (!event.shiftKey && FOCUSED_ITEM_INDEX === FOCUSABLE_CHILDREN.length - 1) {
FOCUSABLE_CHILDREN[0].focus()
event.preventDefault()
}
} else if (event.keyCode === 27 || event.code === 'Escape') {
// `ESC` Key: Close Tobii
event.preventDefault()
close()
} else if (event.keyCode === 37 || event.code === 'ArrowLeft') {
// `PREV` Key: Show the previous slide
event.preventDefault()
previous()
} else if (event.keyCode === 39 || event.code === 'ArrowRight') {
// `NEXT` Key: Show the next slide
event.preventDefault()
next()
}
}
/**
* Contextmenu event handler
* This is a fix for chromium based browser on mac.
* The 'contextmenu' terminates a mouse event sequence.
* https://bugs.chromium.org/p/chromium/issues/detail?id=506801
*
*/
const contextmenuHandler = () => {
pointerDownCache = []
updateOffset()
groups[activeGroup].slider.classList.remove('tobii__slider--is-' + (isZoomed() ? 'moving' : 'dragging'))
}
/**
* Pointerdown event handler
*
*/
const pointerdownHandler = (event) => {
// Prevent dragging / swiping on textareas, inputs and selects
if (isIgnoreElement(event.target)) {
return
}
event.preventDefault()
event.stopPropagation()
DRAG.startX = DRAG.x = event.clientX
DRAG.startY = DRAG.y = event.clientY
DRAG.distance = 0
// This event is cached to support 2-finger gestures
pointerDownCache.push(event)
if (pointerDownCache.length === 2) {
const { x, y } = midPoint(
pointerDownCache[0].clientX, pointerDownCache[0].clientY,
pointerDownCache[1].clientX, pointerDownCache[1].clientY
)
DRAG.startX = DRAG.x = x
DRAG.startY = DRAG.y = y
DRAG.distance = distance(
pointerDownCache[0].clientX - pointerDownCache[1].clientX, pointerDownCache[0].clientY - pointerDownCache[1].clientY
) / TRANSFORM.scale
}
}
/**
* Pointermove event handler
*
*/
const pointermoveHandler = (event) => {
if (!pointerDownCache.length) return
groups[activeGroup].slider.classList.add('tobii__slider--is-' + (isZoomed() ? 'moving' : 'dragging'))
// Find this event in the cache and update its record with this event
const index = pointerDownCache.findIndex(
(cachedEv) => cachedEv.pointerId === event.pointerId
)
pointerDownCache[index] = event
if (pointerDownCache.length === 2) {
// 2-pointer horizontal pinch/zoom gesture
const { x, y } = midPoint(
pointerDownCache[0].clientX, pointerDownCache[0].clientY,
pointerDownCache[1].clientX, pointerDownCache[1].clientY
)
const scale = distance(
pointerDownCache[0].clientX - pointerDownCache[1].clientX, pointerDownCache[0].clientY - pointerDownCache[1].clientY
) / DRAG.distance
zoomPan(
clamp(scale, MIN_SCALE, MAX_SCALE),
x, y,
x - DRAG.x, y - DRAG.y
)
DRAG.x = x
DRAG.y = y
return
}
if (isZoomed()) {