forked from sachinchoolur/lightGallery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlightgallery.ts
2547 lines (2271 loc) · 85.1 KB
/
lightgallery.ts
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
import {
AfterAppendSlideEventDetail,
AfterAppendSubHtmlDetail,
BeforeSlideDetail,
lGEvents,
SlideItemLoadDetail,
} from './lg-events';
import {
LightGalleryAllSettings,
lightGalleryCoreSettings,
LightGallerySettings,
} from './lg-settings';
import utils, { GalleryItem, ImageSize } from './lg-utils';
import { $LG, lgQuery } from './lgQuery';
import {
Coords,
MediaContainerPosition,
SlideDirection,
VideoInfo,
} from './types';
declare let picturefill: any;
// @ref - https://stackoverflow.com/questions/3971841/how-to-resize-images-proportionally-keeping-the-aspect-ratio
// @ref - https://2ality.com/2017/04/setting-up-multi-platform-packages.html
// Unique id for each gallery
let lgId = 0;
export class LightGallery {
public settings!: LightGalleryAllSettings;
public galleryItems!: GalleryItem[];
// Current gallery item
public lgId!: number;
public el!: HTMLElement;
public LGel!: lgQuery;
public lgOpened = false;
public index = 0;
// lightGallery modules
public plugins: any[] = [];
// false when lightGallery load first slide content;
public lGalleryOn = false;
// True when a slide animation is in progress
public lgBusy = false;
// Type of touch action - {swipe, zoomSwipe, pinch}
public touchAction?: 'swipe' | 'zoomSwipe' | 'pinch';
// Direction of swipe/drag - {horizontal, vertical}
public swipeDirection?: 'horizontal' | 'vertical';
// Timeout function for hiding controls;
public hideBarTimeout: any;
public currentItemsInDom: string[] = [];
public outer!: lgQuery;
public items: any;
public $backdrop!: lgQuery;
public $lgComponents!: lgQuery;
public $container!: lgQuery;
public $inner!: lgQuery;
public $content!: lgQuery;
public $toolbar!: lgQuery;
// Scroll top value before lightGallery is opened
public prevScrollTop = 0;
public bodyPaddingRight = 0;
private zoomFromOrigin!: boolean;
private currentImageSize?: ImageSize;
private isDummyImageRemoved = false;
private dragOrSwipeEnabled = false;
public mediaContainerPosition = {
top: 0,
bottom: 0,
};
constructor(element: HTMLElement, options?: LightGallerySettings) {
if (!element) {
return this;
}
lgId++;
this.lgId = lgId;
this.el = element;
this.LGel = $LG(element);
this.generateSettings(options);
this.buildModules();
// When using dynamic mode, ensure dynamicEl is an array
if (
this.settings.dynamic &&
this.settings.dynamicEl !== undefined &&
!Array.isArray(this.settings.dynamicEl)
) {
throw 'When using dynamic mode, you must also define dynamicEl as an Array.';
}
this.galleryItems = this.getItems();
this.normalizeSettings();
// Gallery items
this.init();
this.validateLicense();
return this;
}
private generateSettings(options?: LightGallerySettings) {
// lightGallery settings
this.settings = {
...lightGalleryCoreSettings,
...options,
} as LightGalleryAllSettings;
if (
this.settings.isMobile &&
typeof this.settings.isMobile === 'function'
? this.settings.isMobile()
: utils.isMobile()
) {
const mobileSettings = {
...this.settings.mobileSettings,
...this.settings.mobileSettings,
};
this.settings = { ...this.settings, ...mobileSettings };
}
}
private normalizeSettings() {
if (this.settings.slideEndAnimation) {
this.settings.hideControlOnEnd = false;
}
if (!this.settings.closable) {
this.settings.swipeToClose = false;
}
// And reset it on close to get the correct value next time
this.zoomFromOrigin = this.settings.zoomFromOrigin;
// At the moment, Zoom from image doesn't support dynamic options
// @todo add zoomFromOrigin support for dynamic images
if (this.settings.dynamic) {
this.zoomFromOrigin = false;
}
if (this.settings.container) {
const { container } = this.settings;
if (typeof container === 'function') {
this.settings.container = container();
} else if (typeof container === 'string') {
const el = document.querySelector<HTMLElement>(container);
this.settings.container = el ?? document.body;
}
} else {
this.settings.container = document.body;
}
// settings.preload should not be grater than $item.length
this.settings.preload = Math.min(
this.settings.preload,
this.galleryItems.length,
);
}
init(): void {
this.addSlideVideoInfo(this.galleryItems);
this.buildStructure();
this.LGel.trigger(lGEvents.init, {
instance: this,
});
if (this.settings.keyPress) {
this.keyPress();
}
setTimeout(() => {
this.enableDrag();
this.enableSwipe();
this.triggerPosterClick();
}, 50);
this.arrow();
if (this.settings.mousewheel) {
this.mousewheel();
}
if (!this.settings.dynamic) {
this.openGalleryOnItemClick();
}
}
openGalleryOnItemClick(): void {
// Using for loop instead of using bubbling as the items can be any html element.
for (let index = 0; index < this.items.length; index++) {
const element = this.items[index];
const $element = $LG(element);
// Using different namespace for click because click event should not unbind if selector is same object('this')
// @todo manage all event listners - should have namespace that represent element
const uuid = lgQuery.generateUUID();
$element
.attr('data-lg-id', uuid)
.on(`click.lgcustom-item-${uuid}`, (e) => {
e.preventDefault();
const currentItemIndex = this.settings.index || index;
this.openGallery(currentItemIndex, element);
});
}
}
/**
* Module constructor
* Modules are build incrementally.
* Gallery should be opened only once all the modules are initialized.
* use moduleBuildTimeout to make sure this
*/
buildModules(): void {
this.settings.plugins.forEach((plugin) => {
this.plugins.push(new plugin(this, $LG));
});
}
validateLicense(): void {
if (!this.settings.licenseKey) {
console.error('Please provide a valid license key');
} else if (this.settings.licenseKey === '0000-0000-000-0000') {
console.warn(
`lightGallery: ${this.settings.licenseKey} license key is not valid for production use`,
);
}
}
getSlideItem(index: number): lgQuery {
return $LG(this.getSlideItemId(index));
}
getSlideItemId(index: number): string {
return `#lg-item-${this.lgId}-${index}`;
}
getIdName(id: string): string {
return `${id}-${this.lgId}`;
}
getElementById(id: string): lgQuery {
return $LG(`#${this.getIdName(id)}`);
}
manageSingleSlideClassName(): void {
if (this.galleryItems.length < 2) {
this.outer.addClass('lg-single-item');
} else {
this.outer.removeClass('lg-single-item');
}
}
buildStructure(): void {
const container = this.$container && this.$container.get();
if (container) {
return;
}
let controls = '';
let subHtmlCont = '';
// Create controls
if (this.settings.controls) {
controls = `<button type="button" id="${this.getIdName(
'lg-prev',
)}" aria-label="${
this.settings.strings['previousSlide']
}" class="lg-prev lg-icon"> ${this.settings.prevHtml} </button>
<button type="button" id="${this.getIdName(
'lg-next',
)}" aria-label="${
this.settings.strings['nextSlide']
}" class="lg-next lg-icon"> ${this.settings.nextHtml} </button>`;
}
if (this.settings.appendSubHtmlTo !== '.lg-item') {
subHtmlCont =
'<div class="lg-sub-html" role="status" aria-live="polite"></div>';
}
let addClasses = '';
if (this.settings.allowMediaOverlap) {
// Do not remove space before last single quote
addClasses += 'lg-media-overlap ';
}
const ariaLabelledby = this.settings.ariaLabelledby
? 'aria-labelledby="' + this.settings.ariaLabelledby + '"'
: '';
const ariaDescribedby = this.settings.ariaDescribedby
? 'aria-describedby="' + this.settings.ariaDescribedby + '"'
: '';
const containerClassName = `lg-container ${this.settings.addClass} ${
document.body !== this.settings.container ? 'lg-inline' : ''
}`;
const closeIcon =
this.settings.closable && this.settings.showCloseIcon
? `<button type="button" aria-label="${
this.settings.strings['closeGallery']
}" id="${this.getIdName(
'lg-close',
)}" class="lg-close lg-icon"></button>`
: '';
const maximizeIcon = this.settings.showMaximizeIcon
? `<button type="button" aria-label="${
this.settings.strings['toggleMaximize']
}" id="${this.getIdName(
'lg-maximize',
)}" class="lg-maximize lg-icon"></button>`
: '';
const template = `
<div class="${containerClassName}" id="${this.getIdName(
'lg-container',
)}" tabindex="-1" aria-modal="true" ${ariaLabelledby} ${ariaDescribedby} role="dialog"
>
<div id="${this.getIdName(
'lg-backdrop',
)}" class="lg-backdrop"></div>
<div id="${this.getIdName(
'lg-outer',
)}" class="lg-outer lg-use-css3 lg-css3 lg-hide-items ${addClasses} ">
<div id="${this.getIdName('lg-content')}" class="lg-content">
<div id="${this.getIdName('lg-inner')}" class="lg-inner">
</div>
${controls}
</div>
<div id="${this.getIdName(
'lg-toolbar',
)}" class="lg-toolbar lg-group">
${maximizeIcon}
${closeIcon}
</div>
${
this.settings.appendSubHtmlTo === '.lg-outer'
? subHtmlCont
: ''
}
<div id="${this.getIdName(
'lg-components',
)}" class="lg-components">
${
this.settings.appendSubHtmlTo === '.lg-sub-html'
? subHtmlCont
: ''
}
</div>
</div>
</div>
`;
$LG(this.settings.container).append(template);
if (document.body !== this.settings.container) {
$LG(this.settings.container).css('position', 'relative');
}
this.outer = this.getElementById('lg-outer');
this.$lgComponents = this.getElementById('lg-components');
this.$backdrop = this.getElementById('lg-backdrop');
this.$container = this.getElementById('lg-container');
this.$inner = this.getElementById('lg-inner');
this.$content = this.getElementById('lg-content');
this.$toolbar = this.getElementById('lg-toolbar');
this.$backdrop.css(
'transition-duration',
this.settings.backdropDuration + 'ms',
);
let outerClassNames = `${this.settings.mode} `;
this.manageSingleSlideClassName();
if (this.settings.enableDrag) {
outerClassNames += 'lg-grab ';
}
this.outer.addClass(outerClassNames);
this.$inner.css('transition-timing-function', this.settings.easing);
this.$inner.css('transition-duration', this.settings.speed + 'ms');
if (this.settings.download) {
this.$toolbar.append(
`<a id="${this.getIdName(
'lg-download',
)}" target="_blank" rel="noopener" aria-label="${
this.settings.strings['download']
}" download class="lg-download lg-icon"></a>`,
);
}
this.counter();
$LG(window).on(
`resize.lg.global${this.lgId} orientationchange.lg.global${this.lgId}`,
() => {
this.refreshOnResize();
},
);
this.hideBars();
this.manageCloseGallery();
this.toggleMaximize();
this.initModules();
}
refreshOnResize(): void {
if (this.lgOpened) {
const currentGalleryItem = this.galleryItems[this.index];
const { __slideVideoInfo } = currentGalleryItem;
this.mediaContainerPosition = this.getMediaContainerPosition();
const { top, bottom } = this.mediaContainerPosition;
this.currentImageSize = utils.getSize(
this.items[this.index],
this.outer,
top + bottom,
__slideVideoInfo && this.settings.videoMaxSize,
);
if (__slideVideoInfo) {
this.resizeVideoSlide(this.index, this.currentImageSize);
}
if (this.zoomFromOrigin && !this.isDummyImageRemoved) {
const imgStyle = this.getDummyImgStyles(this.currentImageSize);
this.outer
.find('.lg-current .lg-dummy-img')
.first()
.attr('style', imgStyle);
}
this.LGel.trigger(lGEvents.containerResize);
}
}
resizeVideoSlide(index: number, imageSize?: ImageSize): void {
const lgVideoStyle = this.getVideoContStyle(imageSize);
const currentSlide = this.getSlideItem(index);
currentSlide.find('.lg-video-cont').attr('style', lgVideoStyle);
}
/**
* Update slides dynamically.
* Add, edit or delete slides dynamically when lightGallery is opened.
* Modify the current gallery items and pass it via updateSlides method
* @note
* - Do not mutate existing lightGallery items directly.
* - Always pass new list of gallery items
* - You need to take care of thumbnails outside the gallery if any
* - user this method only if you want to update slides when the gallery is opened. Otherwise, use `refresh()` method.
* @param items Gallery items
* @param index After the update operation, which slide gallery should navigate to
* @category lGPublicMethods
* @example
* const plugin = lightGallery();
*
* // Adding slides dynamically
* let galleryItems = [
* // Access existing lightGallery items
* // galleryItems are automatically generated internally from the gallery HTML markup
* // or directly from galleryItems when dynamic gallery is used
* ...plugin.galleryItems,
* ...[
* {
* src: 'img/img-1.png',
* thumb: 'img/thumb1.png',
* },
* ],
* ];
* plugin.updateSlides(
* galleryItems,
* plugin.index,
* );
*
*
* // Remove slides dynamically
* galleryItems = JSON.parse(
* JSON.stringify(updateSlideInstance.galleryItems),
* );
* galleryItems.shift();
* updateSlideInstance.updateSlides(galleryItems, 1);
* @see <a href="/demos/update-slides/">Demo</a>
*/
updateSlides(items: GalleryItem[], index: number): void {
if (this.index > items.length - 1) {
this.index = items.length - 1;
}
if (items.length === 1) {
this.index = 0;
}
if (!items.length) {
this.closeGallery();
return;
}
const currentSrc = this.galleryItems[index].src;
this.galleryItems = items;
this.updateControls();
this.$inner.empty();
this.currentItemsInDom = [];
let _index = 0;
// Find the current index based on source value of the slide
this.galleryItems.some((galleryItem, itemIndex) => {
if (galleryItem.src === currentSrc) {
_index = itemIndex;
return true;
}
return false;
});
this.currentItemsInDom = this.organizeSlideItems(_index, -1);
this.loadContent(_index, true);
this.getSlideItem(_index).addClass('lg-current');
this.index = _index;
this.updateCurrentCounter(_index);
this.LGel.trigger(lGEvents.updateSlides);
}
// Get gallery items based on multiple conditions
getItems(): GalleryItem[] {
// Gallery items
this.items = [];
if (!this.settings.dynamic) {
if (this.settings.selector === 'this') {
this.items.push(this.el);
} else if (this.settings.selector) {
if (typeof this.settings.selector === 'string') {
if (this.settings.selectWithin) {
const selectWithin = $LG(this.settings.selectWithin);
this.items = selectWithin
.find(this.settings.selector)
.get();
} else {
this.items = this.el.querySelectorAll(
this.settings.selector,
);
}
} else {
this.items = this.settings.selector;
}
} else {
this.items = this.el.children;
}
return utils.getDynamicOptions(
this.items,
this.settings.extraProps,
this.settings.getCaptionFromTitleOrAlt,
this.settings.exThumbImage,
);
} else {
return this.settings.dynamicEl || [];
}
}
shouldHideScrollbar(): boolean {
return (
this.settings.hideScrollbar &&
document.body === this.settings.container
);
}
hideScrollbar(): void {
if (!this.shouldHideScrollbar()) {
return;
}
this.bodyPaddingRight = parseFloat($LG('body').style().paddingRight);
const bodyRect = document.documentElement.getBoundingClientRect();
const scrollbarWidth = window.innerWidth - bodyRect.width;
$LG(document.body).css(
'padding-right',
scrollbarWidth + this.bodyPaddingRight + 'px',
);
$LG(document.body).addClass('lg-overlay-open');
}
resetScrollBar(): void {
if (!this.shouldHideScrollbar()) {
return;
}
$LG(document.body).css('padding-right', this.bodyPaddingRight + 'px');
$LG(document.body).removeClass('lg-overlay-open');
}
/**
* Open lightGallery.
* Open gallery with specific slide by passing index of the slide as parameter.
* @category lGPublicMethods
* @param {Number} index - index of the slide
* @param {HTMLElement} element - Which image lightGallery should zoom from
*
* @example
* const $dynamicGallery = document.getElementById('dynamic-gallery-demo');
* const dynamicGallery = lightGallery($dynamicGallery, {
* dynamic: true,
* dynamicEl: [
* {
* src: 'img/1.jpg',
* thumb: 'img/thumb-1.jpg',
* subHtml: '<h4>Image 1 title</h4><p>Image 1 descriptions.</p>',
* },
* ...
* ],
* });
* $dynamicGallery.addEventListener('click', function () {
* // Starts with third item.(Optional).
* // This is useful if you want use dynamic mode with
* // custom thumbnails (thumbnails outside gallery),
* dynamicGallery.openGallery(2);
* });
*
*/
openGallery(index = this.settings.index, element?: HTMLElement): void {
// prevent accidental double execution
if (this.lgOpened) return;
this.lgOpened = true;
this.outer.removeClass('lg-hide-items');
this.hideScrollbar();
// Add display block, but still has opacity 0
this.$container.addClass('lg-show');
const itemsToBeInsertedToDom = this.getItemsToBeInsertedToDom(
index,
index,
);
this.currentItemsInDom = itemsToBeInsertedToDom;
let items = '';
itemsToBeInsertedToDom.forEach((item) => {
items = items + `<div id="${item}" class="lg-item"></div>`;
});
this.$inner.append(items);
this.addHtml(index);
let transform: string | undefined = '';
this.mediaContainerPosition = this.getMediaContainerPosition();
const { top, bottom } = this.mediaContainerPosition;
if (!this.settings.allowMediaOverlap) {
this.setMediaContainerPosition(top, bottom);
}
const { __slideVideoInfo } = this.galleryItems[index];
if (this.zoomFromOrigin && element) {
this.currentImageSize = utils.getSize(
element,
this.outer,
top + bottom,
__slideVideoInfo && this.settings.videoMaxSize,
);
transform = utils.getTransform(
element,
this.outer,
top,
bottom,
this.currentImageSize,
);
}
if (!this.zoomFromOrigin || !transform) {
this.outer.addClass(this.settings.startClass);
this.getSlideItem(index).removeClass('lg-complete');
}
const timeout = this.settings.zoomFromOrigin
? 100
: this.settings.backdropDuration;
setTimeout(() => {
this.outer.addClass('lg-components-open');
}, timeout);
this.index = index;
this.LGel.trigger(lGEvents.beforeOpen);
// add class lg-current to remove initial transition
this.getSlideItem(index).addClass('lg-current');
this.lGalleryOn = false;
// Store the current scroll top value to scroll back after closing the gallery..
this.prevScrollTop = $LG(window).scrollTop();
setTimeout(() => {
// Need to check both zoomFromOrigin and transform values as we need to set set the
// default opening animation if user missed to add the lg-size attribute
if (this.zoomFromOrigin && transform) {
const currentSlide = this.getSlideItem(index);
currentSlide.css('transform', transform);
setTimeout(() => {
currentSlide
.addClass('lg-start-progress lg-start-end-progress')
.css(
'transition-duration',
this.settings.startAnimationDuration + 'ms',
);
this.outer.addClass('lg-zoom-from-image');
});
setTimeout(() => {
currentSlide.css('transform', 'translate3d(0, 0, 0)');
}, 100);
}
setTimeout(() => {
this.$backdrop.addClass('in');
this.$container.addClass('lg-show-in');
}, 10);
setTimeout(() => {
if (
this.settings.trapFocus &&
document.body === this.settings.container
) {
this.trapFocus();
}
}, this.settings.backdropDuration + 50);
// lg-visible class resets gallery opacity to 1
if (!this.zoomFromOrigin || !transform) {
setTimeout(() => {
this.outer.addClass('lg-visible');
}, this.settings.backdropDuration);
}
// initiate slide function
this.slide(index, false, false, false);
this.LGel.trigger(lGEvents.afterOpen);
});
if (document.body === this.settings.container) {
$LG('html').addClass('lg-on');
}
}
/**
* Note - Changing the position of the media on every slide transition creates a flickering effect.
* Therefore, The height of the caption is calculated dynamically, only once based on the first slide caption.
* if you have dynamic captions for each media,
* you can provide an appropriate height for the captions via allowMediaOverlap option
*/
public getMediaContainerPosition(): MediaContainerPosition {
if (this.settings.allowMediaOverlap) {
return {
top: 0,
bottom: 0,
};
}
const top = this.$toolbar.get().clientHeight || 0;
const subHtml = this.outer.find('.lg-components .lg-sub-html').get();
const captionHeight =
this.settings.defaultCaptionHeight ||
(subHtml && subHtml.clientHeight) ||
0;
const thumbContainer = this.outer.find('.lg-thumb-outer').get();
const thumbHeight = thumbContainer ? thumbContainer.clientHeight : 0;
const bottom = thumbHeight + captionHeight;
return {
top,
bottom,
};
}
private setMediaContainerPosition(top = 0, bottom = 0): void {
this.$content.css('top', top + 'px').css('bottom', bottom + 'px');
}
hideBars(): void {
// Hide controllers if mouse doesn't move for some period
setTimeout(() => {
this.outer.removeClass('lg-hide-items');
if (this.settings.hideBarsDelay > 0) {
this.outer.on('mousemove.lg click.lg touchstart.lg', () => {
this.outer.removeClass('lg-hide-items');
clearTimeout(this.hideBarTimeout);
// Timeout will be cleared on each slide movement also
this.hideBarTimeout = setTimeout(() => {
this.outer.addClass('lg-hide-items');
}, this.settings.hideBarsDelay);
});
this.outer.trigger('mousemove.lg');
}
}, this.settings.showBarsAfter);
}
initPictureFill($img: lgQuery): void {
if (this.settings.supportLegacyBrowser) {
try {
picturefill({
elements: [$img.get()],
});
} catch (e) {
console.warn(
'lightGallery :- If you want srcset or picture tag to be supported for older browser please include picturefil javascript library in your document.',
);
}
}
}
/**
* @desc Create image counter
* Ex: 1/10
*/
counter(): void {
if (this.settings.counter) {
const counterHtml = `<div class="lg-counter" role="status" aria-live="polite">
<span id="${this.getIdName(
'lg-counter-current',
)}" class="lg-counter-current">${this.index + 1} </span> /
<span id="${this.getIdName(
'lg-counter-all',
)}" class="lg-counter-all">${
this.galleryItems.length
} </span></div>`;
this.outer.find(this.settings.appendCounterTo).append(counterHtml);
}
}
/**
* @desc add sub-html into the slide
* @param {Number} index - index of the slide
*/
addHtml(index: number): void {
let subHtml;
let subHtmlUrl;
if (this.galleryItems[index].subHtmlUrl) {
subHtmlUrl = this.galleryItems[index].subHtmlUrl;
} else {
subHtml = this.galleryItems[index].subHtml;
}
if (!subHtmlUrl) {
if (subHtml) {
// get first letter of sub-html
// if first letter starts with . or # get the html form the jQuery object
const fL = subHtml.substring(0, 1);
if (fL === '.' || fL === '#') {
if (
this.settings.subHtmlSelectorRelative &&
!this.settings.dynamic
) {
subHtml = $LG(this.items)
.eq(index)
.find(subHtml)
.first()
.html();
} else {
subHtml = $LG(subHtml).first().html();
}
}
} else {
subHtml = '';
}
}
if (this.settings.appendSubHtmlTo !== '.lg-item') {
if (subHtmlUrl) {
utils.fetchCaptionFromUrl(
subHtmlUrl,
this.outer.find('.lg-sub-html'),
'replace',
);
} else {
this.outer.find('.lg-sub-html').html(subHtml as string);
}
} else {
const currentSlide = $LG(this.getSlideItemId(index));
if (subHtmlUrl) {
utils.fetchCaptionFromUrl(subHtmlUrl, currentSlide, 'append');
} else {
currentSlide.append(
`<div class="lg-sub-html">${subHtml}</div>`,
);
}
}
// Add lg-empty-html class if title doesn't exist
if (typeof subHtml !== 'undefined' && subHtml !== null) {
if (subHtml === '') {
this.outer
.find(this.settings.appendSubHtmlTo)
.addClass('lg-empty-html');
} else {
this.outer
.find(this.settings.appendSubHtmlTo)
.removeClass('lg-empty-html');
}
}
this.LGel.trigger<AfterAppendSubHtmlDetail>(
lGEvents.afterAppendSubHtml,
{
index,
},
);
}
/**
* @desc Preload slides
* @param {Number} index - index of the slide
* @todo preload not working for the first slide, Also, should work for the first and last slide as well
*/
preload(index: number): void {
for (let i = 1; i <= this.settings.preload; i++) {
if (i >= this.galleryItems.length - index) {
break;
}
this.loadContent(index + i, false);
}
for (let j = 1; j <= this.settings.preload; j++) {
if (index - j < 0) {
break;
}
this.loadContent(index - j, false);
}
}
getDummyImgStyles(imageSize?: ImageSize): string {
if (!imageSize) return '';
return `width:${imageSize.width}px;
margin-left: -${imageSize.width / 2}px;
margin-top: -${imageSize.height / 2}px;
height:${imageSize.height}px`;
}
getVideoContStyle(imageSize?: ImageSize): string {
if (!imageSize) return '';
return `width:${imageSize.width}px;
height:${imageSize.height}px`;
}
getDummyImageContent(
$currentSlide: lgQuery,
index: number,
alt: string,
): HTMLImageElement | string {
let $currentItem;
if (!this.settings.dynamic) {
$currentItem = $LG(this.items).eq(index);
}
if ($currentItem) {
let _dummyImgSrc;
if (!this.settings.exThumbImage) {
_dummyImgSrc = $currentItem.find('img').first().attr('src');
} else {
_dummyImgSrc = $currentItem.attr(this.settings.exThumbImage);
}
if (!_dummyImgSrc) return '';
const imgStyle = this.getDummyImgStyles(this.currentImageSize);
const dummyImgContentImg = document.createElement('img');
dummyImgContentImg.alt = alt || '';
dummyImgContentImg.src = _dummyImgSrc;
dummyImgContentImg.className = `lg-dummy-img`;
dummyImgContentImg.style.cssText = imgStyle;
$currentSlide.addClass('lg-first-slide');
this.outer.addClass('lg-first-slide-loading');
return dummyImgContentImg;
}
return '';
}
setImgMarkup(src: string, $currentSlide: lgQuery, index: number): void {
const currentGalleryItem = this.galleryItems[index];
const { alt, srcset, sizes, sources } = currentGalleryItem;
// Use the thumbnail as dummy image which will be resized to actual image size and
// displayed on top of actual image
let imgContent: string | HTMLImageElement = '';
const altAttr = alt ? 'alt="' + alt + '"' : '';