-
-
Notifications
You must be signed in to change notification settings - Fork 78
/
upcoming-media-card.js
1284 lines (1223 loc) · 52.3 KB
/
upcoming-media-card.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
class UpcomingMediaCard extends HTMLElement {
constructor() {
super();
this.uniqueId = 'umc-' + Math.random().toString(36).substr(2, 9);
this.adjustZIndex = this.adjustZIndex.bind(this);
this._boundClickListener;
this.deepLinkListeners = new Map();
this.tooltipListeners = new Map();
}
connectedCallback() {
this.adjustZIndex();
window.addEventListener('scroll', this.adjustZIndex);
}
disconnectedCallback() {
window.removeEventListener('scroll', this.adjustZIndex);
this.cleanupDeepLinkListeners();
}
cleanupDeepLinkListeners() {
this.deepLinkListeners.forEach((listener, element) => {
element.removeEventListener('click', listener);
});
this.deepLinkListeners.clear();
}
addDeepLinkListener(element, url, trailer) {
if (this.config.disable_hyperlinks) return;
const createOverlay = (videoId) => {
const overlay = document.createElement('div');
overlay.style.position = 'fixed';
overlay.style.top = '0';
overlay.style.left = '0';
overlay.style.width = '100%';
overlay.style.height = '100%';
overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.9)';
overlay.style.zIndex = '9999';
overlay.style.display = 'flex';
overlay.style.justifyContent = 'center';
overlay.style.alignItems = 'center';
const iframeContainer = document.createElement('div');
iframeContainer.style.width = '95%';
iframeContainer.style.height = '90%';
iframeContainer.style.maxWidth = '1600px';
iframeContainer.style.maxHeight = '900px';
iframeContainer.style.position = 'relative';
let checkVideoEndedInterval;
const closeOverlayAndCleanup = () => {
clearInterval(checkVideoEndedInterval);
window.removeEventListener('message', handleMessage);
window.removeEventListener('popstate', handlePopState);
closeOverlay();
};
const handleMessage = (event) => {
if (event.source === iframe.contentWindow) {
try {
const data = JSON.parse(event.data);
if (data.event === 'infoDelivery' && data.info && data.info.playerState === 0) {
closeOverlayAndCleanup();
}
} catch (e) {
console.error('Error parsing message:', e);
}
}
};
const handlePopState = (event) => {
closeOverlayAndCleanup();
};
window.addEventListener('message', handleMessage);
window.addEventListener('popstate', handlePopState);
const closeButton = document.createElement('button');
closeButton.innerHTML = '×';
closeButton.style.position = 'absolute';
closeButton.style.top = '-40px';
closeButton.style.right = '5px';
closeButton.style.zIndex = '10000';
closeButton.style.width = '40px';
closeButton.style.height = '40px';
closeButton.style.fontSize = '32px';
closeButton.style.fontWeight = 'bold';
closeButton.style.cursor = 'pointer';
closeButton.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
closeButton.style.color = 'white';
closeButton.style.border = 'none';
closeButton.style.borderRadius = '50%';
closeButton.style.display = 'flex';
closeButton.style.justifyContent = 'center';
closeButton.style.alignItems = 'center';
closeButton.style.padding = '0';
closeButton.style.lineHeight = '1';
closeButton.style.transition = 'background-color 0.3s ease';
closeButton.onmouseenter = () => {
closeButton.style.backgroundColor = 'rgba(255, 255, 255, 0.3)';
const tooltip = document.createElement('div');
tooltip.textContent = 'Close';
tooltip.style.position = 'absolute';
tooltip.style.top = '-30px';
tooltip.style.left = '50%';
tooltip.style.transform = 'translateX(-50%)';
tooltip.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
tooltip.style.color = 'white';
tooltip.style.padding = '5px 10px';
tooltip.style.borderRadius = '3px';
tooltip.style.fontSize = '14px';
tooltip.style.whiteSpace = 'nowrap';
closeButton.appendChild(tooltip);
};
closeButton.onmouseleave = () => {
closeButton.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
const tooltip = closeButton.querySelector('div');
if (tooltip) closeButton.removeChild(tooltip);
};
const iframe = document.createElement('iframe');
iframe.style.width = '100%';
iframe.style.height = '100%';
iframe.src = `https://www.youtube.com/embed/${videoId}?autoplay=1&controls=1&rel=0&fs=1&modestbranding=1&enablejsapi=1`;
iframe.frameBorder = '0';
iframe.allow = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture';
iframe.allowFullscreen = true;
checkVideoEndedInterval = setInterval(() => {
iframe.contentWindow.postMessage('{"event":"listening"}', '*');
}, 1000);
iframeContainer.appendChild(iframe);
iframeContainer.appendChild(closeButton);
overlay.appendChild(iframeContainer);
const closeOverlay = () => {
clearInterval(checkVideoEndedInterval);
window.removeEventListener('message', handleMessage);
window.removeEventListener('popstate', handlePopState);
document.body.removeChild(overlay);
document.body.style.overflow = '';
if (history.state && history.state.overlayOpen) {
history.back();
}
};
closeButton.onclick = closeOverlay;
const handleKeyPress = (event) => {
if (event.key === 'Escape') {
closeOverlay();
}
};
document.addEventListener('keydown', handleKeyPress);
overlay.addEventListener('remove', () => {
document.removeEventListener('keydown', handleKeyPress);
});
history.pushState({ overlayOpen: true }, '');
return overlay;
};
let touchStartTime;
const touchThreshold = 500;
let touchTimer;
let preventClick = false;
const handleTouchStart = () => {
touchStartTime = new Date().getTime();
preventClick = false;
touchTimer = setTimeout(() => {
preventClick = true;
}, touchThreshold);
};
const handleTouchEnd = (event) => {
clearTimeout(touchTimer);
const touchEndTime = new Date().getTime();
const touchDuration = touchEndTime - touchStartTime;
if (touchDuration < touchThreshold && !preventClick) {
handleClick(event);
}
};
const handleClick = (event) => {
if (preventClick) return;
event.preventDefault();
const videoUrl = this.config.enable_trailers && trailer ? trailer : url;
const videoId = this.getYouTubeVideoId(videoUrl);
if (videoId) {
const overlay = createOverlay(videoId);
document.body.appendChild(overlay);
document.body.style.overflow = 'hidden';
} else {
window.open(videoUrl, '_blank');
}
};
element.addEventListener('click', handleClick);
element.addEventListener('touchstart', handleTouchStart);
element.addEventListener('touchend', handleTouchEnd);
this.deepLinkListeners.set(element, {
click: handleClick,
touchstart: handleTouchStart,
touchend: handleTouchEnd
});
}
getYouTubeVideoId(url) {
const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
const match = url.match(regExp);
return (match && match[2].length === 11) ? match[2] : null;
}
removeDeepLinkListener(element) {
const listeners = this.deepLinkListeners.get(element);
if (listeners) {
element.removeEventListener('click', listeners.click);
element.removeEventListener('touchstart', listeners.touchstart);
element.removeEventListener('touchend', listeners.touchend);
this.deepLinkListeners.delete(element);
}
}
// Ensure HA's toolbar takes precedence over UMC's clickable elements if overlapped
adjustZIndex() {
clearTimeout(this.adjustZIndexTimer);
this.adjustZIndexTimer = setTimeout(() => {
const toolbar = document.querySelector('app-toolbar') || document.querySelector('.toolbar');
const cardTop = this.getBoundingClientRect().top;
const toolbarBottom = toolbar ? toolbar.getBoundingClientRect().bottom : 0;
this.style.zIndex = cardTop < toolbarBottom ? '1' : '';
}, 50);
}
set hass(hass) {
this.classList.add(this.uniqueId);
if (!this.content) {
const card = document.createElement("ha-card");
card.header = this.config.title;
this.content = document.createElement("div");
this.content.style.padding = "5px 10px";
card.appendChild(this.content);
this.appendChild(card);
}
const entity = this.config.entity;
if (!hass.states[entity]) return;
let service = this.config.entity.slice(7, 11);
let data = hass.states[entity].attributes.data;
let json;
// START: 'sort_by' and 'sort_ascending' features
try {
json = typeof(data) === "object" ? data : JSON.parse(data);
if (this.config && this.config.sort_by) {
const { sort_by, sort_ascending = true } = this.config;
let sortType = null;
const extractSortableValue = (item) => {
let str = item[sort_by];
if (str === undefined || str === null) {
console.log(`Item ${sort_by} is undefined or null:`, str); // Debugging statement
return null;
}
if (typeof str === 'number') {
sortType = 'numeric';
return str;
}
str = str.toString();
if (str === 'None' || str === 'none') {
return null;
}
if (sort_by === 'title') {
sortType = 'title';
return str.toLowerCase();
}
let cleanStr = str.replace(/<[^>]+>/g, '').replace(/&[^;]+;/g, '');
if (sort_by === 'airdate') {
let dateValue = Date.parse(cleanStr);
if (!isNaN(dateValue)) {
sortType = 'airdate';
return dateValue;
}
}
let numericValue = parseFloat(cleanStr);
if (!isNaN(numericValue) && isFinite(numericValue)) {
sortType = 'numeric';
return numericValue;
}
let complexNumericValue = cleanStr.match(/(?:\d+\u0336)+\d*\u0336*|\d+(\.\d+)?/g)?.map(n => n.replace(/[\u0336]/g, ''))
.filter(n => n.trim() !== '').map(n => parseFloat(n)).sort((a, b) => a - b)[0];
if (!isNaN(complexNumericValue)) {
sortType = 'numeric';
return complexNumericValue;
}
sortType = 'string';
return cleanStr.toLowerCase();
};
const templateItem = json[0];
const sortedItems = json.slice(1).sort((a, b) => {
let valA = extractSortableValue(a);
let valB = extractSortableValue(b);
if (valA === null && valB === null) {
return 0;
}
if (valA === null) {
return sort_ascending ? 1 : -1;
}
if (valB === null) {
return sort_ascending ? -1 : 1;
}
let comparison;
if (sortType === 'numeric') {
comparison = valA - valB;
} else if (sortType === 'airdate') {
comparison = valA - valB;
} else {
const strA = String(valA);
const strB = String(valB);
comparison = strA.localeCompare(strB, undefined, { numeric: true, sensitivity: 'base' });
}
return sort_ascending ? comparison : -comparison;
});
json = [templateItem, ...sortedItems];
}
} catch (e) {
console.error("Error sorting data:", e);
}
// END: 'sort_by' and 'sort_ascending' features
//Collapse filter (takes precedence over general filter)
let collapseProcessed = false;
let conditionalCollapse = typeof this.config.collapse === 'string' ? this.config.collapse.match(/(\w+)=(.*)/) : null;
if (conditionalCollapse) {
collapseProcessed = true; // Set flag to true if collapse condition is found
const attr = conditionalCollapse[1];
const value = conditionalCollapse[2].toLowerCase();
let filteredItems = json.slice(1).filter(item => String(item[attr]).toLowerCase().includes(value));
let unmatchedItems = json.slice(1).filter(item => !String(item[attr]).toLowerCase().includes(value));
json = [json[0], ...filteredItems, ...unmatchedItems];
this.collapse = filteredItems.length;
} else if (typeof this.config.collapse === 'number') {
collapseProcessed = true; // Set flag to true if collapse is a number
this.collapse = this.config.collapse;
} else {
this.collapse = Infinity;
}
// General filter
if (this.config.filter && !collapseProcessed) {
const filterParts = this.config.filter.split('=');
if (filterParts.length === 2) {
const filterKey = filterParts[0].trim();
const filterValue = filterParts[1].trim().toLowerCase();
const templateItem = json[0];
const filteredItems = json.slice(1).filter(item => {
const itemValue = item[filterKey];
if (typeof itemValue === 'string') {
return itemValue.toLowerCase().includes(filterValue);
} else if (itemValue !== null && itemValue !== undefined) {
return itemValue.toString().toLowerCase() === filterValue;
}
return false;
});
json = [templateItem, ...filteredItems];
}
}
if (!json[1] && this.config.hide_empty) this.style.display = "none";
if (!json || !json[1] || this.prev_json == JSON.stringify(json)) return;
this.prev_json = JSON.stringify(json);
const view = this.config.image_style || "poster";
const dateform = this.config.date || "mmdd";
const icon = this.config.icon || json[0]["icon"];
const icon_hide = this.config.icon == "none" ? "display:none;" : "";
const icon_color = this.config.icon_color || "white";
const flag_color = this.config.flag_color || "var(--primary-color)";
const flag = this.config.flag == undefined ? true : this.config.flag;
const timeform = {
hour12: this.config.clock != 24,
hour: "2-digit",
minute: "2-digit"
};
const title_text = this.config.title_text || json[0]["title_default"];
const line1_text = this.config.line1_text || json[0]["line1_default"];
const line2_text = this.config.line2_text || json[0]["line2_default"];
const line3_text = this.config.line3_text || json[0]["line3_default"];
const line4_text = this.config.line4_text || json[0]["line4_default"];
const title_size = this.config.title_size || "large";
const line1_size =
this.config.line1_size || this.config.line_size || "medium";
const line2_size =
this.config.line2_size || this.config.line_size || "small";
const line3_size =
this.config.line3_size || this.config.line_size || "small";
const line4_size =
this.config.line4_size || this.config.line_size || "small";
const tSize = size =>
size == "large" ? "18" : size == "medium" ? "14" : "12";
const size = [
tSize(title_size),
tSize(line1_size),
tSize(line2_size),
tSize(line3_size),
tSize(line4_size)
];
const defaultClr = (poster, fanart) => (view == "poster" ? poster : fanart);
const title_color =
this.config.title_color ||
defaultClr("var(--primary-text-color)", "#fff");
const line1_color =
this.config.line1_color ||
this.config.line_color ||
defaultClr("var(--primary-text-color)", "#fff");
const line2_color =
this.config.line2_color ||
this.config.line_color ||
defaultClr("var(--primary-text-color)", "#fff");
const line3_color =
this.config.line3_color ||
this.config.line_color ||
defaultClr("var(--primary-text-color)", "#fff");
const line4_color =
this.config.line4_color ||
this.config.line_color ||
defaultClr("var(--primary-text-color)", "#fff");
const accent =
this.config.accent_color || defaultClr("var(--primary-color)", "#000");
const border = this.config.border_color || defaultClr("#fff", "#000");
const shadows = conf =>
this.config.all_shadows == undefined
? conf == undefined
? true
: conf
: this.config.all_shadows;
const boxshdw = shadows(this.config.box_shadows)
? view == "poster"
? "5px 5px 10px"
: "3px 2px 25px"
: "";
const svgshdw = shadows(this.config.box_shadows) ? "url(#grad1)" : accent;
const txtshdw = shadows(this.config.text_shadows) ? "1px 1px 3px" : "";
const max = Math.min(json.length - 1, this.config.max || 5);
this.cardSize = max;
const createStyleElement = () => {
let style = document.createElement("style");
style.setAttribute("id", this.uniqueId + "_style");
return style;
};
let style = createStyleElement();
let existingStyle = this.querySelector(`[id="${this.uniqueId}_style"]`);
if (!existingStyle) {
if (view == "poster") {
style.textContent = `
.${this.uniqueId} .${service}_${view} {
width:100%;
margin-left: auto;
margin-right: auto;
margin-bottom: 10px;
position: relative;
display: inline-block;
overflow: hidden;
}
.${this.uniqueId} .${service}_${view} ha-icon {
top: -2px;
right: 3px;
z-index: 2;
width: 17%;
height: 17%;
position:absolute;
color:${icon_color};
filter: drop-shadow( 0px 0px 1px rgba(0,0,0,1));
${icon_hide};
}
.${this.uniqueId} .${service}_${view} img {
width:100%;
visibility:hidden;
}
.${this.uniqueId} .${service}_svg_${view} {
width:55%;
margin-top:5%;
margin-left:0;
vertical-align:top;
overflow:visible;
z-index:1;
}
.${this.uniqueId} .${service}_container_${view} {
position:relative;
outline: 5px solid #fff;
width:30%;
outline:5px solid ${border};
box-shadow:${boxshdw} rgba(0,0,0,.8);
float:left;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
margin:5px 0 15px 5px;
}
.${this.uniqueId} .${service}_flag_${view} {
z-index: 1;
height: 100%;
width: 100%;
position: absolute;
bottom: 0;
right: 0;
fill:${flag_color};
}
.${this.uniqueId} .${service}_flag_${view} svg{
float:right;
width: 100%;
height: 100%;
margin:0;
filter: drop-shadow( -1px 1px 1px rgba(0,0,0,.5));
}
.${this.uniqueId} .${service}_line0_${view} {
font-weight:600;
font-size:${size[0]}px;
text-shadow:${txtshdw} rgba(0,0,0,0.9);
fill:${title_color};
}
.${this.uniqueId} .${service}_line1_${view} {
font-size:${size[1]}px;
text-shadow:${txtshdw} rgba(0,0,0,0.9);
fill:${line1_color};
}
.${this.uniqueId} .${service}_line2_${view} {
font-size:${size[2]}px;
text-shadow:${txtshdw} rgba(0,0,0,0.9);
fill:${line2_color};
}
.${this.uniqueId} .${service}_line3_${view} {
font-size:${size[3]}px;
text-shadow:${txtshdw} rgba(0,0,0,0.9);
fill:${line3_color};
}
.${this.uniqueId} .${service}_line4_${view} {
font-size:${size[4]}px;
text-shadow:${txtshdw} rgba(0,0,0,0.9);
fill:${line4_color};
}
`;
} else {
style.textContent = `
.${this.uniqueId} .${service}_${view} {
width:100%;
overflow:hidden;
margin-left: auto;
margin-right: auto;
margin-bottom: 10px;
background-repeat:no-repeat;
background-size: var(--background-size);
box-shadow:${boxshdw} rgba(0,0,0,.8);
position:relative;
}
.${this.uniqueId} .${service}_${view} ha-icon {
top: 5px;
margin-right: -19px;
right:0;
z-index: 2;
width: 15%;
height: 15%;
position:absolute;
color:${icon_color};
filter: drop-shadow( 0px 0px 1px rgba(0,0,0,1));
${icon_hide};
}
.${this.uniqueId} .${service}_svg_${view} {
overflow:visible;
width:55%;
margin-top:1%;
margin-left:2.5%;
alignment-baseline:text-after-edge;
}
.${this.uniqueId} .${service}_fan_${view} {
width:100%;
background: ${this.config.enable_transparency ? `linear-gradient(to right, transparent 0%, ${accent} 47%, transparent 70%, ${accent} 100%)` : `linear-gradient(to right, ${accent} 47%, transparent 70%, ${accent} 100%)`};
margin:auto;
box-shadow:inset 0 0 0 3px ${border};
}
${this.config.enable_transparency ? `
.${this.uniqueId} .${service}_fan_${view}::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 50%;
height: 100%;
background: ${accent};
backdrop-filter: blur(1px);
-webkit-backdrop-filter: blur(1px);
opacity: 0.1;
z-index: 1;
}
.${this.uniqueId} .${service}_${view}.non-standard-aspect-ratio::before,
.${this.uniqueId} .${service}_${view}.non-standard-aspect-ratio::after {
content: '';
position: absolute;
left: 0;
right: 0;
z-index: 2;
}
.${this.uniqueId} .${service}_${view}.non-standard-aspect-ratio::before {
top: 0;
height: var(--gap-height);
background: linear-gradient(to right, transparent 0%, transparent 47%, ${border} 55%, ${border} 100%);
z-index: 2;
}
.${this.uniqueId} .${service}_${view}.non-standard-aspect-ratio::after {
bottom: 0;
height: var(--gap-height);
background: linear-gradient(to right, transparent 0%, transparent 47%, ${border} 55%, ${border} 100%);
z-index: 2;
}
.${this.uniqueId} .${service}_fan_${view} .text-content {
position: relative;
z-index: 3;
}` : ''}
.${this.uniqueId} .${service}_flag_${view} {
z-index: 1;
height: 100%;
width: 100%;
position: absolute;
margin-top:3px;
margin-right:3px;
right: 0;
fill:${flag_color};
}
.${this.uniqueId} .${service}_flag_${view} svg{
float:right;
width: 100%;
height: 100%;
margin:0;
filter: drop-shadow( -1px 1px 1px rgba(0,0,0,.5));
}
.${this.uniqueId} .${service}_line0_${view} {
font-weight:600;
font-size:${size[0]}px;
text-shadow:${txtshdw} rgba(0,0,0,0.9);
fill:${title_color};
}
.${this.uniqueId} .${service}_line1_${view} {
font-size:${size[1]}px;
text-shadow:${txtshdw} rgba(0,0,0,0.9);
fill:${line1_color};
}
.${this.uniqueId} .${service}_line2_${view} {
font-size:${size[2]}px;
text-shadow:${txtshdw} rgba(0,0,0,0.9);
fill:${line2_color};
}
.${this.uniqueId} .${service}_line3_${view} {
font-size:${size[3]}px;
text-shadow:${txtshdw} rgba(0,0,0,0.9);
fill:${line3_color};
}
.${this.uniqueId} .${service}_line4_${view} {
font-size:${size[4]}px;
text-shadow:${txtshdw} rgba(0,0,0,0.9);
fill:${line4_color};
}
:host {
cursor: pointer;
}
`;
}
this.appendChild(style);
}
this.content.innerHTML = "";
// Truncate text...
function truncate(text, chars) {
function decodeEntities(input) {
var textarea = document.createElement('textarea');
textarea.innerHTML = input;
return textarea.value;
}
// When to truncate depending on size
chars = chars == 'large' ? 23 : chars == 'medium' ? 25 : 32;
text = decodeEntities(text);
// Truncate only at whole word w/ no punctuation or space before ellipsis.
if (text.length > chars) {
for (let i = chars; i > 0; i--) {
if (text.charAt(i).match(/( |\s|:|-|;|"|'|,)/) && text.charAt(i - 1).match(/[^\s:;-;"',]/)) {
return `${text.substring(0, i)}...`;
}
}
// The cycle above had a really big single word, so we return it anyway
return `${text.substring(0, chars)}...`;
} else {
return text;
}
}
function format_date(input_date, format = "mm/dd/yy") {
let fd_day, fd_month, fd_year;
if (String(input_date).match(/[T]\d+[:]\d+[:]\d+[Z]/)) {
fd_day = new Date(input_date).toLocaleDateString([], { day: "2-digit" });
fd_month = new Date(input_date).toLocaleDateString([], { month: "2-digit" });
fd_year = new Date(input_date).toLocaleDateString([], { year: "2-digit" });
} else if (String(input_date).match(/\d+[-]\d+[-]\d+/)) {
input_date = input_date.split("-");
fd_month = input_date[1];
fd_day = input_date[2];
fd_year = input_date[0].slice(-2);
} else {
return "";
}
const formatMap = { dd: fd_day, mm: fd_month, yy: fd_year };
return format.replace(/dd|mm|yy/g, matched => formatMap[matched]).replace(/(\d{2})(?=\d)/g, '$1/');
}
// Hide card while we prepare to display the content
this.content.style.visibility = 'hidden';
this.content.style.position = 'absolute';
this.content.style.left = '-9999px';
//Begin of loop iterating through each item in for json data
for (let count = 1; count <= max; count++) {
const item = key => json[count][key];
if (!item("airdate")) continue;
if (this.config.hide_flagged && item("flag")) continue;
else if (this.config.hide_unflagged && !item("flag")) continue;
let airdate = new Date(item("airdate"));
let dflag = item("flag") && flag ? "" : "display:none;";
let image =
view == "poster" ? item("poster") : item("fanart") || item("poster");
if (typeof image === 'string' && !image.includes("http")) {
image = hass.hassUrl().substring(0, hass.hassUrl().length - 1) + image;
}
let daysBetween = Math.round(
Math.abs(
(new Date().getTime() - airdate.getTime()) / (24 * 60 * 60 * 1000)
)
);
let day =
daysBetween <= 7
? airdate.toLocaleDateString([], { weekday: "long" })
: airdate.toLocaleDateString([], { weekday: "short" });
// Convert 'runtime' to 'Xhr Ymin' format if it's a numeric value, otherwise exclude it.
let runtime = item("runtime");
if (runtime && /^\d+$/.test(runtime)) {
let totalMinutes = parseInt(runtime, 10);
let hrs = Math.floor(totalMinutes / 60);
runtime = (hrs > 0 ? `${hrs}hr ` : "") + (totalMinutes % 60 > 0 ? `${totalMinutes % 60}min` : "");
} else {
runtime = "";
}
// Shifting images for fanart view since we use poster as fallback image.
let shiftimg = item("fanart")
? "background-position:100% 0;"
: "background-size: 54% auto;background-position:100% 35%;";
// First item in card needs no top margin.
let top;
if (count == 1) top = "margin-top: 0px;";
else top = view == "poster" ? "margin-top: 20px;" : "margin-top: 10px;";
let line = [title_text, line1_text, line2_text, line3_text, line4_text];
let char = [title_size, line1_size, line2_size, line3_size, line4_size];
// Keyword map for replacement, return null if empty so we can hide empty sections
let keywords = /\$title|\$episode|\$genres|\$number|\$rating|\$release|\$runtime|\$studio|\$price|\$day|\$date|\$time|\$aired|\$album|\$artist|\$empty/g;
const format = this.config.date || "mm/dd/yy";
const releaseFormat = this.config.date || "mm/dd/yy";
let keys = {
$title: item("title") || null,
$episode: item("episode") || null,
$genres: item("genres") || null,
$number: item("number") || null,
$rating: item("rating") || null,
$release: (item("release") || '').replace("$date", format_date(item("airdate"), releaseFormat)).replace("$year", format_date(item("airdate"), "yy")).replace(" $time", " $time") || null,
$runtime: runtime || null,
$studio: item("studio") || null,
$price: item("price") || null,
$day: day || null,
$date: format_date(item("airdate"), format) || null,
$time: airdate.toLocaleTimeString([], timeform) || null,
$aired: format_date(item("aired"), format) || null,
$album: item("album") || null,
$artist: item("artist") || null,
$empty: ''
};
// Replace keywords in lines
for (let i = 0; i < line.length; i++) {
line[i] = line[i].replace(" - ", "-");
// Split at '-' so we can ignore entire contents if keyword returns null
let text = line[i].replace(keywords, val => keys[val]).split("-");
let filtered = [];
// Rebuild lines, ignoring null
for (let t = 0; t < text.length; t++) {
if (text[t].match(null)) continue;
else filtered.push(text[t]);
}
// Replacing twice to get keywords in component generated strings
text = filtered.join(" - ").replace(keywords, val => keys[val]).trim();
// Shifting header text around depending on view & size
let svgshift, y;
if (i == 0)
size[i].match(/18/)
? (y = "-5")
: size[i].match(/14/)
? (y = "-2")
: (y = "0");
if (view == "fanart")
svgshift = i == 0 ? `x="0" dy="1em" ` : `x="0" dy="1.3em" `;
else
svgshift =
i == 0 ? `x="15" y="${y}" dy="1.3em" ` : `x="15" dy="1.3em" `;
// Build lines HTML or empty line
line[i] = line[i].match("empty")
? `<tspan class="${service}_line${i}_${view}" style="fill:transparent;text-shadow:0 0 transparent;" ${svgshift}>.</tspan>`
: `<tspan class="${service}_line${i}_${view}" ${svgshift}>${truncate(
text,
char[i]
)}</tspan>`;
}
let deepLink = item("deep_link");
// Mouse & touch event listeners
function addDeepLinkListener(element, link) {
let startX = 0, startY = 0, moveThresholdPx = 10, longPressThresholdMs = 500;
let isMoving = false, timer, startTime;
element.addEventListener('touchstart', function(event) {
startX = event.touches[0].pageX; startY = event.touches[0].pageY;
isMoving = false; startTime = Date.now();
timer = setTimeout(() => { isMoving = true; }, longPressThresholdMs);
}, { passive: true });
element.addEventListener('touchmove', function(event) {
if (isMoving) return;
const moveX = event.touches[0].pageX, moveY = event.touches[0].pageY;
if (Math.abs(moveX - startX) > moveThresholdPx || Math.abs(moveY - startY) > moveThresholdPx) {
isMoving = true; clearTimeout(timer);
}
}, { passive: true });
element.addEventListener('touchend', function() {
clearTimeout(timer);
if (!isMoving && (Date.now() - startTime) < longPressThresholdMs) {
window.open(link, '_blank');
}
isMoving = false;
}, { passive: true });
element.style.cursor = 'pointer';
element.addEventListener('click', function() { window.open(link, '_blank'); });
}
if (view == "poster") {
let containerDiv = document.createElement('div');
if (this.config.enable_tooltips) {
this.addTooltipHandlers(containerDiv, item("summary"));
}
containerDiv.id = 'main';
containerDiv.className = `${service}_${view}`;
containerDiv.style.cssText = top;
let containerDivInnerHTML = `
<div class="${service}_container_${view}" style="background-image:url('${image}');">
<img src="${image}"/>
<ha-icon icon="${icon}" style="${dflag}"></ha-icon>
<div class="${service}_flag_${view}" style="${dflag}">
<svg style="${dflag}" preserveAspectRatio="none" viewBox="0 0 100 100">
<polygon points="100 25,65 0,100 0"></polygon>
</svg>
</div>
</div>
<svg class='${service}_svg_${view}' viewBox="0 0 200 100">
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(20,20,20,1);stop-opacity:1" />
<stop offset="2%" style="stop-color:${accent};stop-opacity:1" />
</linearGradient>
</defs>
<rect width="500px" height="23px" fill="${svgshdw}"/>
<text>
${line[0]}
<tspan dy="1.3em" style="font-size:3px;fill:transparent;text-shadow:0 0 transparent;">.</tspan>
${line[1]}${line[2]}${line[3]}${line[4]}
</text>
</svg>
`;
containerDiv.innerHTML = containerDivInnerHTML;
let clickableAreaDiv = document.createElement('div');
// Prevent clicking poster border
clickableAreaDiv.style.position = 'absolute';
clickableAreaDiv.style.top = '3px';
clickableAreaDiv.style.right = '3px';
clickableAreaDiv.style.bottom = '3px';
clickableAreaDiv.style.left = '3px';
clickableAreaDiv.style.borderRadius = '3px';
clickableAreaDiv.style.pointerEvents = 'auto';
clickableAreaDiv.style.zIndex = '5';
containerDiv.style.overflow = 'hidden';
containerDiv.appendChild(clickableAreaDiv);
if (!this.config.disable_hyperlinks && (this.url || deepLink || (this.config.enable_trailers && item("trailer")))) {
if (this.config.enable_trailers && item("trailer")) {
this.addDeepLinkListener(clickableAreaDiv, deepLink || this.url, item("trailer"));
} else if (this.url) {
this.addDeepLinkListener(clickableAreaDiv, this.url);
} else if (deepLink) {
this.addDeepLinkListener(clickableAreaDiv, deepLink);
}
clickableAreaDiv.style.cursor = 'pointer';
} else {
clickableAreaDiv.style.cursor = 'default';
}
if (count <= this.collapse) {
this.content.appendChild(containerDiv);
} else {
containerDiv.style.display = 'none';
containerDiv.classList.add('collapsed');
this.content.appendChild(containerDiv);
}
} else {
let fanartContainerDiv = document.createElement('div');
if (this.config.enable_tooltips) {
this.addTooltipHandlers(fanartContainerDiv, item("summary"));
}
fanartContainerDiv.className = `${service}_${view}`;
fanartContainerDiv.style.cssText = `${top} ${shiftimg}background-image:url('${image}');background-position:100% center;`;
// Code to handle non-standard aspect ratio fanart backgrounds
fanartContainerDiv.style.setProperty('--background-size', '53% auto');
let img = new Image();
img.onload = function() {
let aspectRatio = img.width / img.height;
if (aspectRatio > 1.78) {
fanartContainerDiv.classList.add('non-standard-aspect-ratio');
let heightAdjustmentFactor = (aspectRatio - 1.78) / 2;
let heightPercentage = 100 - (heightAdjustmentFactor * 100 / 1.78);
let backgroundSize = `54% ${Math.round(Math.max(heightPercentage, 50))}%`;
fanartContainerDiv.style.setProperty('--background-size', backgroundSize);
let gapHeightCalcExpression = `calc((100% - ${Math.round(Math.max(heightPercentage, 50))}%) / 2)`;
fanartContainerDiv.style.setProperty('--gap-height', gapHeightCalcExpression);
}
};
img.src = image;
let fanartContainerInnerHTML = `
<div class="${service}_fan_${view}">
<ha-icon icon="${icon}" style="${dflag}"></ha-icon>
<div class="${service}_flag_${view}" style="${dflag}">
<svg style="${dflag}" preserveAspectRatio="none" viewBox="0 0 100 100">
<polygon points="100 30,90 0,100 0"></polygon>
</svg>
</div>
<svg class="${service}_svg_${view}"viewBox="0 0 200 100">
<text>${line[0]}${line[1]}${line[2]}${line[3]}${line[4]}</text>
</svg>
</div>
`;
fanartContainerDiv.innerHTML = fanartContainerInnerHTML;
let fanartDeepLink = item("deep_link");
let clickableAreaDivFanart = document.createElement('div');
// Prevent clicking fanart border
clickableAreaDivFanart.style.position = 'absolute';
clickableAreaDivFanart.style.top = '3px';
clickableAreaDivFanart.style.right = '3px';
clickableAreaDivFanart.style.bottom = '3px';
clickableAreaDivFanart.style.left = '3px';
clickableAreaDivFanart.style.pointerEvents = 'auto';
clickableAreaDivFanart.style.zIndex = '5';
fanartContainerDiv.style.overflow = 'hidden';
fanartContainerDiv.appendChild(clickableAreaDivFanart);
if (!this.config.disable_hyperlinks && (this.url || fanartDeepLink || (this.config.enable_trailers && item("trailer")))) {
if (this.config.enable_trailers && item("trailer")) {
this.addDeepLinkListener(clickableAreaDivFanart, fanartDeepLink || this.url, item("trailer"));
} else if (this.url) {
this.addDeepLinkListener(clickableAreaDivFanart, this.url);
} else if (fanartDeepLink) {
this.addDeepLinkListener(clickableAreaDivFanart, fanartDeepLink);
}
clickableAreaDivFanart.style.cursor = 'pointer';
} else {
clickableAreaDivFanart.style.cursor = 'default';
}
// Gap-fill for fanart backgrounds with >1.78 aspect ratio
let gapWrapperDiv = document.createElement('div');
gapWrapperDiv.className = `${service}_gap_wrapper_${view}`;
this.content.appendChild(gapWrapperDiv);
gapWrapperDiv.appendChild(fanartContainerDiv);
if (count <= this.collapse) {
gapWrapperDiv.appendChild(fanartContainerDiv);
} else {
fanartContainerDiv.style.display = 'none';
fanartContainerDiv.classList.add('collapsed');
gapWrapperDiv.appendChild(fanartContainerDiv);
}
this.content.appendChild(gapWrapperDiv);
}
if (!this.querySelector(`[id="${this.uniqueId}_style"]`)) this.appendChild(style);
this.style.cursor = this.url && this.url.trim() !== '' ? 'pointer' : 'default';
this.removeEventListener('click', this._boundClickListener);
const hasDeepLinks = json.some(item => item.deep_link);