-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmediaviewer.js
More file actions
3711 lines (3415 loc) · 192 KB
/
Copy pathmediaviewer.js
File metadata and controls
3711 lines (3415 loc) · 192 KB
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
// ===== MediaViewer FULL BUILD (with timeline fixes merged) =====
import { clipboard, color, videoData, genID, fileName, GenerateQRCode, finalizeURL} from "./mediaviewer-tools.js";
/**
* @package MediaViewer
* @version 1.4.0
* @description A javascript library to create a media viewing experience
* @license MIT
* @author XHiddenProjects
* @repository [XHiddenProjects/MediaViewer](https://github.com/XHiddenProjects/MediaViewer)
*/
/**
* Starts up the media viewer
*/
export const startup = ()=>{
const icons = document.createElement('link'),
fonts = document.createElement('link'),
main = document.createElement('link'),
mobile = document.createElement('link'),
qr = document.createElement('script');
icons.href = `./css/all.min.css`;
icons.rel = `stylesheet`;
document.head.appendChild(icons);
fonts.href = `//fonts.googleapis.com/css2?family=Cedarville+Cursive&family=Cutive+Mono&family=Dancing+Script:wght@400..700&family=Handlee&family=PT+Mono&family=PT+Sans+Caption:wght@400;700&family=PT+Serif+Caption:ital@0;1&display=swap`;
fonts.rel = 'stylesheet';
document.head.appendChild(fonts);
main.href = `./css/mediaviewer.css`;
main.rel = 'stylesheet';
document.head.appendChild(main);
mobile.rel = 'stylesheet';
mobile.href = `./css/mediaviewer-mobile.css`;
document.head.appendChild(mobile);
qr.src = `https://cdn.jsdelivr.net/gh/ushelp/EasyQRCodeJS@master/src/easy.qrcode.js`;
document.head.appendChild(qr);
document.documentElement.setAttribute('media-viewer-enabled','');
}
/**
* Checks if the startup has been triggered
* @returns {boolean}
*/
const isLoaded = ()=>{return document.documentElement.hasAttribute('media-viewer-enabled')};
export class Carousel{
#callback;
/**
* Create a touch/keyboard‑friendly image carousel. Wires autoplay, indicators,
* captions and optional controls; driven via API or CSS custom properties.
*
* @constructor
* @param {string|HTMLElement} container - CSS selector or DOM element that will host the carousel root.
* @param {{
* speed?: number,
* interval?: number,
* autoplay?: boolean,
* loop?: boolean,
* slides?: string[],
* captions?: string[],
* start?: number,
* controls?: boolean,
* indicator?: boolean,
* transition?: 'slide'|'fade'|'none'
* }} [config] - Carousel configuration object. Fields:
* • **speed** (ms): transition animation duration; affects CSS timing classes.
* • **interval** (ms): delay between automatic slide advances when `autoplay` is enabled.
* • **autoplay**: start advancing slides automatically after init.
* • **loop**: wrap from the last slide back to the first.
* • **slides**: array of image URLs to render as slides (order is preserved).
* • **captions**: per‑slide captions; index‑aligned with `slides`.
* • **start**: zero‑based initial slide index.
* • **controls**: render previous/next buttons and bind click handlers.
* • **indicator**: render dot indicators and bind click/wheel navigation.
* • **transition**: visual effect used between slides.
* @param {{ 'control-color'?: string, 'indicator-color'?: string, 'captions-color'?: string, 'captions-bg'?: string }} [styles] - Style overrides mapped to CSS variables (e.g., `--carousel-control-color`). Use valid CSS color strings.
* @param {boolean} [trigger=true] - When `true`, the carousel mounts immediately; pass `false` to call `init()` later.
* @example
* const carousel = new Carousel('#heroCarousel', {
* slides: ['/img/1.jpg','/img/2.jpg','/img/3.jpg'],
* captions: ['One','Two','Three'],
* autoplay: true, transition: 'fade', controls: true, indicator: true
* }, { 'control-color': '#fff' }).getInstance();
*/
constructor(container, config, styles,trigger=true){
if(!isLoaded()) return;
this.container = (typeof container === 'string')
? document.querySelector(container)
: container;
this.config = {
speed: 500,
interval: 5000,
autoplay: true,
loop: true,
slides: [],
captions: [],
start: 0,
controls: false,
indicator: false,
transition: 'none' //slide, fade, none
};
this.styles = {};
this.interval=null;
this.#callback = null;
this.lastSlide = 0;
Object.assign(this.config, config);
Object.assign(this.styles, styles);
if (this.container instanceof HTMLElement&&trigger) this.init();
}
/**
* Render and attach the component’s DOM and listeners. Called automatically
* when `trigger` is true; call manually to mount later.
* @example
* const g = new Gallery('#g', { images:['/1.jpg'] }, {}, false);
* g.init();
*/
init(){
this.currentSlide = this.config.start;
this.container.classList.add(this.config.transition);
this.container.classList.add('carousel');
Object.keys(this.styles).forEach(i=>{
this.container.style.setProperty(`--carousel-${i}`,this.styles[i]);
});
this.container.innerHTML += '<div class="carousel-inner">'+this.config.slides.map((slide, index) => `
<div class="carousel-slide${index === this.currentSlide ? ' active' : ''}">
<img class="image" src="${slide}" alt="${this.config.captions[index]??'img_'+(index+1)}"/>
</div>
`).join('')+"</div>";
if (this.config.autoplay) {
this.#startAutoplay();
}
if (this.config.controls) {
this.#createControls();
}
if (this.config.indicator) {
this.#createIndicators();
}
if(this.config.captions.length>0) this.#createCaptions();
}
getInstance(){
return this;
}
/**
* Subscribe to slide changes—great for syncing captions, analytics, or custom UI.
* @param {(info:{last:number,current:number,total:number,index:number,caption?:string})=>void} callback - Function invoked after each transition with metadata for the previous and current slide.
* @param {boolean} [async=false] - When `true`, immediately invokes `callback` once with the current state after registration.
* @example
* const c = new Carousel('#c', { slides:['/a.jpg','/b.jpg'] });
* c.onSlideChange(({ current, total }) => console.log(`Slide ${current}/${total}`));
*/
onSlideChange(callback,async=false) {
this.#callback = callback;
if(async)
this.#callback({last: this.lastSlide, current: this.currentSlide+1, total: this.config.slides.length, index: this.currentSlide,caption: this.config.captions[this.currentSlide]});
}
/**
* Starts the autoplay functionality
*/
#startAutoplay() {
this.interval = setInterval(() => {
this.#nextSlide();
}, this.config.interval);
}
/**
* Moves to the next slide
*/
#nextSlide() {
this.lastSlide = this.currentSlide;
if (this.currentSlide + 1 < this.config.slides.length) {
this.currentSlide++;
} else if (this.config.loop) {
this.currentSlide = 0;
}
this.#updateSlides();
this.#updateIndicators();
}
/**
* Updates the slides display
*/
#updateSlides() {
const slides = this.container.querySelectorAll('.carousel-slide');
slides.forEach((slide, index) => {
if (index === this.currentSlide) {
slide.classList.add('active');
slide.classList.add('carousel-slide-next');
const prevSlideIndex = this.lastSlide;
slides[prevSlideIndex].classList.add('carousel-slide-prev');
setTimeout(() => {
slide.classList.remove('carousel-slide-next');
slides[prevSlideIndex].classList.remove('carousel-slide-prev');
}, this.config.speed);
} else {
slide.classList.remove('active');
}
});
if(this.#callback)
this.#callback({last: this.lastSlide,current:this.currentSlide+1,total:this.config.slides.length, index: this.currentSlide, caption: this.config.captions[this.currentSlide]});
}
/**
* Creates the carousel controls
*/
#createControls() {
const prevButton = document.createElement('button');
prevButton.innerHTML = '<i class="fa-solid fa-caret-left"></i>';
prevButton.classList.add('carousel-prev');
prevButton.addEventListener('click', () => {
this.#prevSlide();
});
const nextButton = document.createElement('button');
nextButton.innerHTML = '<i class="fa-solid fa-caret-right"></i>';
nextButton.classList.add('carousel-next');
nextButton.addEventListener('click', () => {
this.#nextSlide();
});
this.container.appendChild(prevButton);
this.container.appendChild(nextButton);
}
/**
* Creates the carousel captions
*/
#createCaptions() {
const slides = this.container.querySelectorAll('.carousel-slide');
slides.forEach((slide, index) => {
const caption = document.createElement('caption');
caption.classList.add('carousel-caption');
caption.innerText = this.config.captions[index] || '';
slide.appendChild(caption);
});
}
/**
* Creates the carousel indicators
*/
#createIndicators() {
const indicatorContainer = document.createElement('div');
indicatorContainer.classList.add('carousel-indicators');
indicatorContainer.addEventListener('wheel',(event)=>{
if(event.deltaY<0)this.#nextSlide();
else this.#prevSlide();
});
this.config.slides.forEach((_, index) => {
const indicator = document.createElement('span');
indicator.classList.add('carousel-indicator');
if (index === this.currentSlide) {
indicator.classList.add('active');
}
indicator.addEventListener('click', () => {
this.currentSlide = index;
this.#updateSlides();
this.#updateIndicators();
});
indicatorContainer.appendChild(indicator);
});
this.container.appendChild(indicatorContainer);
}
/**
* Updates the indicators display
*/
#updateIndicators() {
const indicators = this.container.querySelectorAll('.carousel-indicator');
indicators.forEach((indicator, index) => {
indicator.classList.toggle('active', index === this.currentSlide);
});
}
#prevSlide() {
this.lastSlide = this.currentSlide;
if (this.currentSlide - 1 >= 0) {
this.currentSlide--;
} else if (this.config.loop) {
this.currentSlide = this.config.slides.length - 1;
}
this.#updateSlides();
this.#updateIndicators();
}
};
export class Gallery{
/**
* Build a responsive, Masonry‑like gallery grid with optional zoom overlay and captions.
* Column count auto‑adapts based on container width and intrinsic image sizes unless overridden.
*
* @constructor
* @param {string|HTMLElement} container - CSS selector or DOM element for the gallery root.
* @param {{ images?: string[], captions?: string[], zoom?: boolean, gap?: string, autoResize?: boolean, static?: boolean, minColWidth?: number }} [config] - Gallery settings. Fields:
* • **images**: array of image URLs to display in grid order.
* • **captions**: optional array of captions; index‑aligned with `images`.
* • **zoom**: enable click‑to‑zoom overlay with close affordances.
* • **gap**: CSS length for grid gaps (e.g., `12px`, `1rem`).
* • **autoResize**: recompute column count on container/viewport resize.
* • **static**: when `true`, disables overlay click‑to‑close (kiosk mode).
* • **minColWidth** (px): fallback width used to estimate columns when sizes are unknown.
* @param {{ 'max-cols'?: string|number, 'gap'?: string, 'captions-bg'?: string, 'captions-color'?: string, 'backdrop'?: string, 'close-btn'?: string, 'box-shadow'?: string }} [styles] - CSS variable overrides for the gallery (e.g., `--gallery-gap`).
* @param {boolean} [trigger=true] - Auto‑mount control; set `false` to call `init()` yourself after async work.
* @example
* new Gallery('#shots', { images:['/a.jpg','/b.jpg'], zoom:true }, { 'max-cols': 3 });
*/
constructor(container, config = {}, styles = {}, trigger = true) {
if (!isLoaded()) return;
this.container = (typeof container === 'string')
? document.querySelector(container)
: container;
// Defaults
this.config = {
images: [],
captions: [],
zoom: false,
gap: '12px', // sensible default (not 0)
autoResize: true, // enable unless explicitly disabled
static: false,
minColWidth: 240 // fallback min column width if we can't infer from images
};
// CSS var-backed styles (numbers/lengths, not '1fr')
this.styles = {
'max-cols': '1', // must be an integer string
'gap': this.config.gap
};
Object.assign(this.config, config);
Object.assign(this.styles, styles);
// ---- Priority fix: JS styles win; only fall back to element's INLINE CSS var ----
const hasStyleCols =
this.styles &&
this.styles['max-cols'] != null &&
String(this.styles['max-cols']).trim() !== '';
// Only read the element's own inline style, not computed stylesheet defaults
const inlineCols = (this.container instanceof HTMLElement)
? this.container.style.getPropertyValue('--gallery-max-cols')
: '';
this.userDefinedCols = hasStyleCols || (!!inlineCols && inlineCols.trim() !== '');
// If the caller didn't supply JS styles but the element has an inline var, use it
if (!hasStyleCols && inlineCols && inlineCols.trim()) {
this.styles['max-cols'] = inlineCols.trim();
}
// Sanitize gap
if (!/^\d+(\.\d+)?(px|rem|em|%)$/.test(String(this.styles['gap']))) {
this.styles['gap'] = '12px';
}
// Load images, compute columns, then apply styles and init
this.loadImages().then(() => {
this.applyStyles();
if (this.container instanceof HTMLElement && trigger) this.init?.();
});
// Auto-resize: recalc cols on container resize (preferred) or window resize
if (this.config.autoResize && this.container instanceof HTMLElement) {
const recalc = this._debounce(async () => {
if (!this.userDefinedCols) {
await this.loadImages();
}
this.applyStyles();
}, 120);
if ('ResizeObserver' in window) {
this._ro = new ResizeObserver(() => recalc());
this._ro.observe(this.container);
} else {
window.addEventListener('resize', recalc);
}
}
}
/**
* Loads images (if provided) and computes a safe column count (>= 1).
* Returns the computed column count.
*/
async loadImages() {
// Respect explicit user-defined column count and skip auto-compute
if (this.userDefinedCols) {
const n = parseInt(String(this.styles['max-cols'] ?? '1'), 10);
const safe = Number.isFinite(n) && n > 0 ? n : 1;
this.styles['max-cols'] = String(safe);
return safe;
}
const urls = Array.isArray(this.config.images) ? this.config.images : [];
const containerWidth =
(this.container?.clientWidth) ||
document.documentElement.clientWidth ||
window.innerWidth ||
1024; // robust fallback
// No images provided -> derive cols from minColWidth
if (urls.length === 0) {
const cols = Math.max(1, Math.floor(containerWidth / Math.max(1, this.config.minColWidth)));
this.styles['max-cols'] = String(cols);
return cols;
}
// Load images safely
const images = await Promise.all(
urls.map(src => new Promise(resolve => {
const img = new Image();
img.src = src;
img.onload = () => resolve(img);
img.onerror = () => resolve(img); // keep pipeline moving even if one fails
}))
);
const widths = images.map(img => img.naturalWidth || 0);
const count = Math.max(1, widths.length);
const totalWidth = widths.reduce((a, b) => a + b, 0);
// Average width fallback -> minColWidth if images lack sizes
const avgWidth = totalWidth > 0 ? (totalWidth / count) : this.config.minColWidth;
// Compute columns and clamp to >= 1
const cols = Math.max(1, Math.floor(containerWidth / Math.max(1, avgWidth)));
this.styles['max-cols'] = String(cols);
return cols;
}
/** Applies CSS custom properties to the container */
applyStyles() {
if (!(this.container instanceof HTMLElement)) return;
// Clamp to a safe integer >= 1
const n = parseInt(String(this.styles['max-cols'] ?? '1'), 10);
const safe = Number.isFinite(n) && n > 0 ? n : 1;
this.container.style.setProperty('--gallery-max-cols', String(safe));
this.container.style.setProperty('--gallery-gap', String(this.styles['gap']));
}
/** Small debounce helper */
_debounce(fn, delay = 120) {
let t;
return (...args) => {
clearTimeout(t);
t = setTimeout(() => fn.apply(this, args), delay);
};
}
init(){
this.container.classList.add('gallery');
Object.keys(this.styles).forEach(i=>{
this.container.style.setProperty(`--gallery-${i}`,this.styles[i]);
});
this.container.innerHTML += '<div class="gallery-grid">'+this.config.images.map((image, index) => `
<div class="gallery-item">
<img class="image" src="${image}" alt="${this.config.captions[index]??'img_'+(index+1)}"/>
</div>
`).join('')+"</div>";
if(this.config.zoom) this.#createZoom();
if(this.config.captions.length>0) this.#createCaptions();
}
getInstance(){
return this;
}
#createZoom(){
if(this.config.static) this.container.classList.add('static');
this.container.classList.add('zoom');
const overlay = document.createElement('div');
overlay.classList.add('gallery-overlay');
if(!this.config.static){
overlay.addEventListener('click',()=>{
overlay.classList.remove('opened');
const caption = overlay.querySelector('.gallery-zoom-caption');
if (caption) caption.remove();
});
}
const closeButton = document.createElement('button');
closeButton.innerText = 'x';
closeButton.classList.add('gallery-close-button');
closeButton.addEventListener('click', () => {
overlay.classList.remove('opened');
const caption = overlay.querySelector('.gallery-zoom-caption');
if (caption) caption.remove();
});
overlay.appendChild(closeButton);
const image = document.createElement('img');
image.classList.add('gallery-zoom-image');
overlay.appendChild(image);
this.container.appendChild(overlay);
const images = this.container.querySelectorAll('.gallery-item');
images.forEach((img, index) => {
img.addEventListener('click', () => {
overlay.classList.add('opened');
image.src = this.config.images[index];
if (this.config.captions.length > 0) {
const caption = document.createElement('div');
caption.classList.add('gallery-zoom-caption');
caption.innerText = this.config.captions[index] || '';
overlay.appendChild(caption);
}
});
});
}
#createCaptions() {
const items = this.container.querySelectorAll('.gallery-item');
items.forEach((item, index) => {
const caption = document.createElement('caption');
caption.classList.add('gallery-caption');
caption.innerText = this.config.captions[index] || '';
item.appendChild(caption);
});
}
};
export class VideoPlayer{
#videoList;
/**
* Feature‑rich HTML5 video player: playlists, quality selection, CC settings,
* thumbnails, keyboard shortcuts, PiP/theater/fullscreen and share tools.
*
* @constructor
* @param {string|HTMLElement} container - Player wrapper element or CSS selector.
* @param {{
* autoplay?: boolean,
* preloaded?: 'auto'|'metadata'|'none',
* controls?: boolean,
* playlists?: Array<{ poster?: string, title: string, author?: string, src: Array<{ quality: string|number, path: string }>, tracks?: Array<{ src: string, kind: string, srclang: string, label: string }> }>,
* start?: number,
* skipRate?: number,
* embed?: boolean
* }} [config] - Player configuration. Highlights:
* • **autoplay**: attempt to start playback automatically (subject to browser policies).
* • **preloaded**: preload strategy for the `<video>` element.
* • **controls**: render the custom control bar (progress, CC, gear, etc.).
* • **playlists**: list of playable items; each has `src` sources by quality and optional `tracks`.
* • **start** (seconds): initial timestamp to seek after metadata is loaded.
* • **skipRate** (seconds): amount to seek with arrow keys.
* • **embed**: adjusts layout/menus for embedded usage.
* @param {{
* 'progress-background'?: string,
* 'progress'?: string,
* 'controls-color'?: string,
* 'volume-thumb'?: string,
* 'volume-border'?: string,
* 'volume-track-before'?: string,
* 'volume-track-after'?: string,
* 'bg'?: string,
* 'checkpoint'?: string,
* 'buffer'?: string,
* 'autoplay-checked'?: string,
* 'autoplay-bg'?: string,
* 'autoplay-thumb'?: string,
* 'cc-active'?: string,
* 'preview-timestamp'?: string,
* 'settings-bg'?: string,
* 'settings-color'?: string,
* 'settings-hover'?: string,
* 'pip-overlay'?: string,
* 'pip-overlay-color'?: string,
* 'playlist'?: string,
* 'playlist-time'?: string,
* 'playlist-time-bg'?: string,
* 'error-bg'?: string,
* 'error-color'?: string,
* 'title-color'?: string,
* 'playlist-title'?: string,
* 'playlist-author'?: string,
* 'cue-font'?: string,
* 'cue-font-color'?: string|number,
* 'cue-font-size'?: string,
* 'cue-bg'?: string|number,
* 'cue-bg-opacity'?: string|number,
* 'cue-window-color'?: string|number,
* 'cue-window-opacity'?: string|number,
* 'cue-font-opacity'?: string|number
* }} [styles] - Visual tokens mapped to video CSS variables (e.g., `--video-progress`). Use CSS colors/lengths or raw numbers where noted.
* @param {boolean} [trigger=true] - Auto‑mount behavior; set `false` for manual `init()`.
* @example
* const vp = new VideoPlayer('#player', {
* playlists: [{ title:'Demo', poster:'/poster.jpg', src:[{ quality:'auto', path:'/video.mp4' }], tracks:[{ src:'/captions.vtt', kind:'subtitles', srclang:'en', label:'English' }] }],
* controls: true
* }).getInstance();
*/
constructor(container, config, styles, trigger=true){
if(!isLoaded()) return;
this.params = new URLSearchParams(window.location.search);
this.container = (typeof container === 'string')
? document.querySelector(container)
: container;
this.config = {
embed: false,
autoplay: false,
controls: true,
start: (this.params.get('t') ? parseInt(this.params.get('t')) : 0),
playlists: [],
skipRate: 5,
defaultLang: 'en',
availableColors: ['white','yellow','green','cyan','blue','magenta','red','black'],
availableSize: [50,75,100,150,200,300,400],
availableOpacity: [0,25,50,75,100],
availablePlayback: [0.25,0.5,0.75,1,1.25,1.5,1.75,2],
preloaded: 'auto',
embedURL: `${window.location.origin+window.location.pathname}embed.html`
}
this.styles={};
this.debug ={};
this.eventTracker = {};
this.#videoList = [];
Object.assign(this.config,config);
Object.assign(this.styles,styles);
// Safely parse the stored config (falls back to empty object)
const storedConfig = JSON.parse(window.localStorage.getItem('mediaViewer_video_config') || '{}');
// Use optional chaining + nullish coalescing to preserve the current default if missing
this.config.autoplay = storedConfig?.autoplay ?? this.config.autoplay;
// Build video id list deterministically before init
const buildListPromises = this.config.playlists.map(async (i) => {
const name = fileName(i.src[0].path);
const id = await genID(name);
return { videoName: name, videoID: id };
});
Promise.all(buildListPromises)
.then((list) => {
// de-duplicate by videoName while preserving order
const seen = new Set();
this.#videoList = list.filter((it) => {
if (seen.has(it.videoName)) return false;
seen.add(it.videoName);
return true;
});
// Generate poster screenshots for all playlists before calling init
const posterPromises = this.config.playlists.map((e) => {
return new Promise((resolve) => {
if (typeof e.poster === 'string' && e.poster.trim() !== '') {
resolve();
} else {
videoData(e.src[0]['path'], 1, (p) => {
if (p && p.poster && p.duration) {
e.poster = p.poster;
e.duration = p.duration;
}
resolve();
});
}
});
});
return Promise.all(posterPromises);
})
.then(() => {
if (this.container instanceof HTMLElement && trigger) this.init();
});
return this;
}
#getVideoType(src){
const extension = src.split('.').pop().toLowerCase();
switch (extension) {
case 'mp4':
return 'video/mp4';
case 'webm':
return 'video/webm';
case 'ogg':
return 'video/ogg';
default:
return 'video/mp4';
}
}
init(){
this.container.tabIndex = 0;
this.container.classList.add('video');
if(this.config.embed) this.container.classList.add('embed');
Object.keys(this.styles).forEach(i=>{
this.container.style.setProperty(`--video-${i}`,this.styles[i]);
});
if(this.container.hasAttribute('video')) return;
this.container.innerHTML=`<div class="video-player"></div>`;
this.container.querySelector('.video-player').innerHTML = `${window.QRCode ? `<div class="QRcode"><span class="close"><i class="fa-solid fa-x"></i> <i class="fa-solid fa-spinner-third qr-spinner"></i></span></div>` : ''}<div class="playpauseUI" data-status="isPaused">
<span class="uiPlayPause"></span>
</div>
<div class="videoNotFound">
<span class="videoNotFoundTxt">Video not found</span>
</div><div class="overlay">
<i class="fa-solid fa-arrow-up-right-from-square fa-rotate-270 pip-expand" title="Expand (i)"></i>
<i class="fa-solid fa-play pip-play-pause"></i>
</div>
<div class="content-menu-controls">
<ul class="controls-menu">
<li class="controls-menu-item" data-action="loop"><i class="fa-solid fa-repeat"></i> Loop</li>
<li class="controls-menu-item" data-action="copyURL"><i class="fa-solid fa-link"></i> Copy URL</li>
<li class="controls-menu-item" data-action="copyTimeURL"><i class="fa-solid fa-link"></i> Copy URL at current time</li>
<li class="controls-menu-item" data-action="copyEmbed"><i class="fa-solid fa-code-simple"></i> Copy Embed Code</li>
${window.QRCode ? `<li class="controls-menu-item" data-action="openQRCode"><i class="fa-solid fa-qrcode"></i> Generate QRCode</li>` : ``}
</ul>
</div>
<div class="video-placeholder">
<div class="closed-captions-bar">
<span class="closed-captions-text"></span>
</div>
<i class="fa-solid fa-loader bufferLoader"></i>
</div>`;
this.container.innerHTML+=`<div class="playlists${this.config.playlists.length<2 ? ' noShow' : ''}">
${
Array.from(this.config.playlists).map(e => {
return `<div class="playlist-item" tab-index="0" data-video="${this.#videoList.find(v => v.videoName === fileName(e.src[0].path))?.videoID}">
<div style="position: relative;">
<img src="${e.poster}" class="playlist-img"/>
<span data-video-src="${this.#videoList.find(v => v.videoName === fileName(e.src[0].path))?.videoID}" class="playlist-timeDur" data-video-duration="${this.#sec2time(e.duration)}">${this.#sec2time(e.duration)}</span>
</div>
<div>
<p class="playlist-title">${e.title}</p>
<p class="playlist-author">${e.author??''}</p>
</div>
</div>`;
}).join('')
}
</div>`;
let videoID = new URLSearchParams(window.location.search).get('v');
if (!videoID && this.config.playlists.length > 0) {
videoID = this.#videoList[0]?.videoID;
const separator = window.location.href.includes('?') ? '&' : '?';
const url = new URL(window.location.href);
url.searchParams.set('v', videoID);
const newUrl = url.pathname + url.search;
window.history.pushState({}, '', newUrl);
}
const playlistItem = this.config.playlists.find(item =>
this.#videoList.some(video => video.videoID === videoID && fileName(item.src[0].path) === video.videoName)
);
const title = playlistItem ? playlistItem.title : this.config.title;
this.container.innerHTML+=`<div class="video-title"><h1>${title}</h1></div>`;
this.#createVideoFrame();
if(this.config.controls){
this.#createControls();
this.#createVolumeBtn();
this.#createVolume();
this.#pausePlay();
this.#videoEvents();
this.#triggerVideo();
this.#triggerSettings();
}
this.#playlists();
}
getInstance(){
return this;
}
#createControls(){
this.container.querySelector('.video-player').innerHTML+=`<div class="controls">
<div class="preview-container">
<div class="preview-frame"></div>
<div class="information">
<span class="chapter"></span>
<span class="timestamp"></span>
</div>
</div>
<div class="section progress">
<div class="progress-buffer"></div>
<div class="progress-checkpoint"></div>
<div class="progress-bar"><span class="circle"></span></div>
</div>
<div class="section">
<div class="controller-1">
<i class="fa-solid fa-play btn play-pause" title="Play (k)"></i>
<i class="fa-solid fa-forward-step btn next-video"></i>
<div class="container volume-container">
<div class="volume-holder">
</div>
</div>
<div class="container time-container">
<span class="current-time">00:00</span> / <span class="total-time">00:00</span>
</div>
</div>
<div class="controller-2">
<label class="toggle-switch" title="Autoplay is off">
<input type="checkbox" class="autoplay" ${this.config.autoplay ? ' checked="checked"' : ''}>
<span class="slider"></span>
</label>
<i class="fa-solid fa-closed-captioning btn cc" title="close captions (c)"></i>
<div class="setting-container btn">
<i class="fa-solid fa-gear settings" tabindex="0" title="Settings"></i>
<div class="settings-menu">
<ul class="settings-menu-list">
${this.container.querySelector('track[kind="subtitles"]') ? '<li class="settings-menu-list-item" data-settings="option-cc"><span><i class="fa-regular fa-closed-captioning"></i> Closed Captions</span></li>' : ''}
<li class="settings-menu-list-item" data-settings="option-playback"><span><i class="fa-regular fa-circle-play"></i> Playback Speed</span></li>
<li class="settings-menu-list-item" data-settings="option-quality"><span><i class="fa-regular fa-sliders"></i> Quality</span></li>
<li class="settings-menu-list-item" data-settings="option-cc"><span><i class="fa-solid fa-closed-captioning"></i> Closed Captions</span></li>
</ul>
<div class="options option-cc">
<div class="options-header">
<div>
<span class="settings-back"></span>
<span>Subtitles/CC</span>
</div>
<span class="cc-options">Options</span>
</div>
<ul class="settings-menu-list">
${
(() => {
const generateSubtitleMenu = () => {
const tracks = Array.from(this.container.querySelectorAll('track[kind="subtitles"]'));
if (tracks.length === 0) return '<li class="settings-menu-list-item disabled"><span>No subtitles available</span></li>';
return tracks.map((e) => {
const isChecked = e.track && e.track.mode === 'hidden';
return `<li class="settings-menu-list-item${isChecked ? ' checked' : ''}" data-subtitle="${e.getAttribute('srclang')}"><span>${e.getAttribute('label')}</span></li>`;
}).join('');
};
setTimeout(() => {
const x = this.container.querySelector('.option-cc .settings-menu-list');
if (x) x.innerHTML = generateSubtitleMenu();
}, 0);
return generateSubtitleMenu();
})()
}
</ul>
</div>
<div class="options option-playback">
<div class="options-header">
<div>
<span class="settings-back"></span>
<span>Playback</span>
</div>
</div>
<ul class="settings-menu-list">
${
Array.from(this.config.availablePlayback).map((e) =>
`<li class="settings-menu-list-item${e==1 ? ' checked' : ''}" data-speed="${e}"><span>${e==1 ? 'Normal' : `${e}x`}</span></li>`
).join('')
}
</ul>
</div>
<div class="options option-quality">
<div class="options-header">
<div>
<span class="settings-back"></span>
<span>Quality</span>
</div>
</div>
<ul class="settings-menu-list">
${
(() => {
const urlParams = new URLSearchParams(window.location.search);
const videoID = urlParams.get('v');
const playlist = this.config.playlists.find(item =>
this.#videoList.some(video => video.videoID === videoID && fileName(item.src[0].path) === video.videoName)
);
if (!playlist) return '';
// Remove duplicate qualities
const uniqueSources = playlist.src.filter((src, idx, arr) =>
arr.findIndex(s => s.quality === src.quality) === idx
);
return uniqueSources
.sort((a, b) => {
const qualityA = a.quality === 'auto' ? -1 : parseInt(a.quality || 0, 10);
const qualityB = b.quality === 'auto' ? -1 : parseInt(b.quality || 0, 10);
return qualityA - qualityB;
})
.map((src) =>
`<li class="settings-menu-list-item${src.quality === 'auto' ? ' checked' : ''}" data-quality="${src.quality}"><span>${src.quality !== 'auto' ? `${src.quality.charAt(0).toUpperCase() + src.quality.slice(1)}p` : `${src.quality.charAt(0).toUpperCase() + src.quality.slice(1)}`}</span></li>`
).join('');
})()
}
</ul>
</div>
<div class="options option-cc-more">
<div class="options-header">
<div>
<span class="settings-back-more"></span>
<span>Options</span>
</div>
</div>
<ul class="settings-menu-list">
<li class="settings-menu-list-item">Font Family:
<select class="settings-menu-select font-family">
<option value="--family-monospaced-serif">Monospaced Serif</option>
<option value="--family-proportional-serif">Proportional Serif</option>
<option value="--family-monospaced-sans-serif">Monospaced Sans Serif</option>
<option value="--family-proportional-sans-serif" selected="selected">Proportional Sans Serif</option>
<option value="--family-casual">Casual</option>
<option value="--family-cursive">Cursive</option>
<option value="--family-small-capitals">Small Capitals</option>
</select>
</li>
<li class="settings-menu-list-item">Font Color:
<select class="settings-menu-select font-color">
${Array.from(this.config.availableColors).map((e) =>
`<option value="${e}">${e.charAt(0).toUpperCase() + e.slice(1)}</option>`
).join('')}
</select>
</li>
<li class="settings-menu-list-item">Font Size:
<select class="settings-menu-select font-size">
${Array.from(this.config.availableSize).map((e) =>{
return `<option value="${e}"${e==100 ? ' selected="selected"' : ''}>${e}%</option>`;
}).join('')}
</select>
</li>
<li class="settings-menu-list-item">Background Color:
<select class="settings-menu-select bg-color">
${Array.from(this.config.availableColors).map((e) =>
`<option value="${e}">${e.charAt(0).toUpperCase() + e.slice(1)}</option>`
).join('')}
</select>
</li>
<li class="settings-menu-list-item">Background Opacity:
<select class="settings-menu-select bg-opacity">
${Array.from(this.config.availableOpacity).map((e) =>
`<option value="${e/100}"${e==75 ? ' selected="selected"' : ''}>${e}%</option>`
).join('')}
</select>
</li>
<li class="settings-menu-list-item">Window Color:
<select class="settings-menu-select window-color">
${Array.from(this.config.availableColors).map((e) =>
`<option value="${e}">${e.charAt(0).toUpperCase() + e.slice(1)}</option>`
).join('')}
</select>
</li>
<li class="settings-menu-list-item">Window Opacity:
<select class="settings-menu-select window-opacity">
${Array.from(this.config.availableOpacity).map((e) =>
`<option value="${e/100}"${e==0 ? ' selected="selected"' : ''}>${e}%</option>`
).join('')}
</select>
</li>
<li class="settings-menu-list-item">Font Opacity:
<select class="settings-menu-select font-opacity">
${Array.from(this.config.availableOpacity).map((e) =>
`<option value="${e/100}"${e==100 ? ' selected="selected"' : ''}>${e}%</option>`
).join('')}
</select>
</li>
</ul>
</div>
</div>
</div>
<i class="fa-solid fa-arrow-up-right-from-square btn pip" title="Miniplayer (i)"></i>
<i class="fa-regular fa-expand-wide btn theaterMode" title="Theater Mode (t)"></i>
<i class="fa-solid fa-expand fullscreen btn" title="Fullscreen (f)"></i>
</div>
</div>
</div>`;
setTimeout(() => {
const x = document.querySelector('.option-quality .settings-menu-list');
if (x.innerText.trim() === '') {
x.innerHTML = Array.from(this.container.querySelectorAll('.video-frame source[data-quality]'))
.sort((a, b) => {
const qualityA = a.getAttribute('data-quality') === 'auto' ? -1 : parseInt(a.getAttribute('data-quality') || 0, 10);
const qualityB = b.getAttribute('data-quality') === 'auto' ? -1 : parseInt(b.getAttribute('data-quality') || 0, 10);
return qualityA - qualityB;
})
.map((e) =>
`<li class="settings-menu-list-item${e.getAttribute('data-quality') === 'auto' ? ' checked' : ''}" data-quality="${e.getAttribute('data-quality')}"><span>${e.getAttribute('data-quality') !== 'auto' ? `${e.getAttribute('data-quality').charAt(0).toUpperCase() + e.getAttribute('data-quality').slice(1)}p` : `${e.getAttribute('data-quality').charAt(0).toUpperCase() + e.getAttribute('data-quality').slice(1)}`}</span></li>`
).join('');
}
}, 100);
}
#createVideoFrame(){
const video = document.createElement('video');
video.setAttribute('preload', this.config.preloaded);
video.classList.add('video-frame');
video.tabIndex = 0;
this.config.playlists.map((s)=>{
s.src.map((src) =>{
const source = document.createElement('source');
source.src = src['path'];
source.setAttribute('data-quality', src['quality']??'auto');
source.type = this.#getVideoType(src['path']);
const currentVideoID = new URLSearchParams(window.location.search).get('v');
const currentPlaylist = this.config.playlists.find(playlist =>
this.#videoList.some(video => video.videoID === currentVideoID && fileName(playlist.src[0].path) === video.videoName)
);
video.poster = currentPlaylist ? currentPlaylist.poster : this.config.poster;
if(src['quality']==='auto') video.src = src['path'];
video.appendChild(source);
});
});
this.config.tracks?.map((tracks)=>{
const track = document.createElement('track');
track.src = tracks['src'];