-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.js
More file actions
2145 lines (1917 loc) · 59.6 KB
/
lib.js
File metadata and controls
2145 lines (1917 loc) · 59.6 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
const currentVersion = "v0.1.1";
const projectReleasesUrl = "https://github.com/haxwithaxe/dashboard/releases/"
const projectLatestReleaseApiUrl = "https://api.github.com/repos/haxwithaxe/dashboard/releases/latest"
const proxyUrl = "https://corsproxy.io/";
const videoExtensions = [".mp4", ".webm", ".ogg", ".ogv"];
/* Create a new element from a template.
*
* Arguments:
* id: The template element ID.
*
* Returns:
* A clone of the template content.
*/
function createFromTemplate(id) {
const templateElem = document.getElementById(id);
// Strip leading and trailing whitespace to avoid extra empty text nodes
templateElem.innerHTML = templateElem.innerHTML
.replace(/^[ \t\n\r]+/, "")
.replace(/[ \t\n\r]+$/, "");
return templateElem.content.cloneNode(true);
}
// Check for updates on github.
async function checkForUpdates() {
const latestVersion = await getLatestVersion();
if (currentVersion != latestVersion) {
document.getElementById("update-button").style.display = "block";
} else {
document.getElementById("update-button").style.display = "none";
}
}
/* Generate a probably unique ID one way or another
*
* Arguments:
* uniquish: Some relatively unique within collection string just in case
* self.crypto isn't available.
*
* Returns:
* A probably unique string.
*/
function generateId(uniquish) {
if (self.crypto !== undefined && self.crypto.randomUUID !== undefined) {
return "id" + self.crypto.randomUUID();
}
let hash = 0;
for (const char of uniquish) {
hash = (hash << 5) - hash + char.charCodeAt(0);
hash |= 0; // Constrain to 32bit integer
}
return "id" + hash.toString() + randomInt(1000).toString();
}
/* Get a function that formats dates like C's strftime.
*
* Arguments:
* formatStr (string): A string with C strftime style format codes.
* timezone (string, optional): IANA time zone string. For example
* "America/New_York" or "Etc/UTC".
*
* Returns:
* A function that formats the time (Date object) given as the argument.
*/
function getDateFormatter(formatStr, timezone) {
return ((date) => {
const parts = getDateParts(date, timezone);
return (formatStr
.replace("%Y", parts.year4)
.replace("%y", parts.year2)
.replace("%m", parts.month)
.replace("%e", parts.monthNum)
.replace("%b", parts.monthNameAbrv)
.replace("%B", parts.monthName)
.replace("%A", parts.dayName)
.replace("%a", parts.dayNameAbrv)
.replace("%d", parts.day)
.replace("%e", parts.dayNum)
.replace("%H", parts.hours)
.replace("%k", parts.hoursNum)
.replace("%I", parts.hours12)
.replace("%l", parts.hours12Num)
.replace("%M", parts.minutes)
.replace("%S", parts.seconds)
.replace("%F", `${parts.year4}-${parts.month}-${parts.day}`)
.replace("%T", `${parts.hours}:${parts.minutes}:${parts.seconds}`)
.replace("%R", `${parts.hours12}:${parts.minutes}`)
.replace("%r", `${parts.hours12}:${parts.minutes}:${parts.seconds}`)
.replace("%p", parts.amPm)
.replace("%P", parts.amPm.toLowerCase())
.replace("%Z", parts.timezone));
});
}
/* Pad a string with 0's.
*
* Arguments:
* string (string): A string to pad with 0's.
* length (integer, optional): The full length of the padded string. Defaults
* to 2.
*
* Returns:
* A zero padded string of length `length`.
*/
function zeroPad(string, length) {
length = length !== undefined ? length : 2;
return string.padStart(length, "0");
}
/* Get the various parts of the date and time.
*
* Arguments:
* date (Date): A Date object.
* timezone (string, optional): IANA time zone string. For example
* "America/New_York" or "Etc/UTC".
*
* Returns:
* An object with date and time parts as strings.
*/
function getDateParts(date, timezone) {
const tzDate = new Date(date.toLocaleString(
"en-US",
{timeZone: timezone, timeZoneName: "short"}
));
const localeString = ((options, override) => tzDate.toLocaleString(
override !== undefined ? override : "en-US",
Object.assign({timeZone: timezone}, options)
));
const parts = {
year4: localeString({year: "numeric"}),
year2: localeString({year: "2-digit"}),
month: zeroPad(localeString({month: "2-digit"})),
monthNum: localeString({month: "numeric"}),
monthName: localeString({month: "long"}),
monthNameAbrv: localeString({month: "short"}),
day: zeroPad(localeString({day: "2-digit"})),
dayNum: localeString({day: "numeric"}),
dayName: localeString({weekday: "long"}),
dayNameAbrv: localeString({weekday: "short"}),
hours: zeroPad(localeString({hour: "2-digit", hour12: false})),
hoursNum: localeString({hour: "numeric", hour12: false}),
hours12: zeroPad(localeString({hour: "2-digit", hour12: true})),
hours12Num: localeString({hour: "numeric", hour12: true}),
minutes: zeroPad(localeString({minute: "2-digit"})),
seconds: zeroPad(localeString({second: "2-digit"})),
amPm: localeString({hour12: true}).split(" ").slice(-1)[0],
timezone: localeString({timeZoneName: "short"}, "en-US").slice(-3),
};
if (typeof timezone == "string" && timezone.toLowerCase().slice(-3) == "utc") {
parts.timezone = "UTC";
}
return parts;
}
// Get the latest version number of this application.
async function getLatestVersion() {
try {
const response = await fetch(projectLatestReleaseApiUrl);
const data = await response.json();
return data.tag_name;
} catch (error) {
console.error("Error fetching the latest version:", error);
return currentVersion; // Fallback to the current version if there's an error
}
}
// Hide the focused-container and reset its children.
function hideFocusedContainer() {
const container = document.getElementById("focused-container");
container.style.display = "none";
container.style.zIndex = -2;
const iframe = document.getElementById("focused-iframe");
iframe.style.display = "none";
iframe.style.zIndex = -2;
const tile = document.getElementById("focused-tile-parent");
tile.style.display = "none";
tile.style.zIndex = -2;
}
/* Parse an interval string and return the equivalent milliseconds
*
* Arguments:
* interval_string: An interval composed of a number and optionally a unit.
* Units:
* <none>: Milliseconds
* s: Seconds
* m: Minutes
* h: Hours
* d: Days
* w: Weeks
*
* Examples:
* 300000 = 300000 milliseconds (aka 5 minutes)
* 600s = 600 seconds
* 20m = 20 minutes
* 3h = 3 hours
* 4d = 4 days
* 2w0.5d11m = 2 weeks, 0.5 days, and 11 minutes (combined)
*/
function parseInterval(interval_string) {
if (interval_string == null) {
return 0;
}
if (Number.isInteger(interval_string)) {
return interval_string;
}
if (Number.isInteger(interval_string)) {
return Number.parseInteger(interval_string);
}
var re = /([0-9.]+)([wdhms])/g;
var matches = interval_string.toLowerCase().matchAll(re);
var interval = 0;
matches.forEach(
function(match) {
if (match.length < 3) {
console.debug("Got a match with less than 3 elements.", match);
return;
}
var quant = Number.parseFloat(match[1]);
var unit = match[2];
if (unit == "w") {
interval += quant * 1000 * 60 * 60 * 24 * 7;
} else if (unit == "d") {
interval += quant * 1000 * 60 * 60 * 24;
} else if (unit == "h") {
interval += quant * 1000 * 60 * 60;
} else if (unit == "m") {
interval += quant * 1000 * 60;
} else if (unit == "s") {
interval += quant * 1000;
}
}
);
return interval;
}
/* Get the pixel value of an element as a Float
*
* Arguments:
* elem (DOM element): The element to find the properties of.
* prop (string): The CSS property to convert.
*
* Returns:
* A Float of the number of pixels.
*/
function styleToNumber(elem, prop) {
const px = getComputedStyle(elem).getPropertyValue(prop);
if (px == null) {
return null;
}
return parseFloat(px.replace("px", ""));
}
// Recalculate the CSS sizes of important elements.
function recalculateCssVars() {
var tickerHeight = styleToNumber(document.getElementById("feed-ticker"), "height"); // px
var topBarHeight = styleToNumber(document.getElementById("top-bar-container"), "height"); // px
if (topBarHeight == null) {
topBarHeight = window.innerHeight * 0.06;
}
const tileWidth = window.innerWidth / dashboard.columns; // px
const dashboardHeight = window.innerHeight - topBarHeight - tickerHeight; // px
const tileHeight = dashboardHeight / dashboard.rows; // px
document.documentElement.style.setProperty(
"--dashboard-height",
`${dashboardHeight}px`,
);
document.documentElement.style.setProperty(
"--tile-height",
`${tileHeight}px`,
);
document.documentElement.style.setProperty(
"--tile-width",
`${tileWidth}px`,
);
document.documentElement.style.setProperty(
"--top-bar-height",
`${topBarHeight}px`,
);
}
// Show the focused-container.
function showFocusedContainer() {
const container = document.getElementById("focused-container");
container.style.display = "block";
container.style.zIndex = 2;
}
// Show the focused-container and focused-iframe.
function showFocusedIframe() {
showFocusedContainer();
const iframe = document.getElementById("focused-iframe");
iframe.style.display = "flex";
iframe.style.zIndex = 2;
const tile = document.getElementById("focused-tile-parent");
tile.style.display = "none";
tile.style.zIndex = -2;
}
// Show the focused-container and focused-tile-parent.
function showFocusedTile() {
showFocusedContainer();
iframe = document.getElementById("focused-iframe");
iframe.style.display = "none";
iframe.style.zIndex = -2;
const tile = document.getElementById("focused-tile-parent");
tile.style.display = "block";
tile.style.zIndex = 2;
}
/* Sort items by order.
*
* Negative values of `order` are treated like negative indexes.
*
* Arguments:
* a, b: The items to compare.
*/
function sortCompareOrder(a, b) {
if (a.order >= 0 && b.order < 0) {
return -1;
}
if (a.order < 0 && b.order >= 0) {
return 1;
}
return a.order - b.order;
}
// Base class that sort of mimics python's dataclass.
class Item {
/* Create a new Item
*
* Arguments:
* spec: The item spec.
* defaults (optional): Default values for the new Item.
*/
static create(spec, defaults) {
var values = {};
if (defaults !== undefined) {
values = Object.assign({}, defaults);
}
values = Object.assign(
Object.assign(values, spec),
{_defaults: defaults, _spec: spec}
);
const sealed = Object.assign(Object.create(this.prototype), new this(Item));
const newObj = Object.assign(sealed, values);
newObj.postConstructor();
return newObj;
}
constructor(values) {
if (!values instanceof Item) {
throw new Error(
`Use ${this.constructor.name}.create(...) instead of new operator`
);
}
}
// Runs at the end of the `create` method (after `constructor`).
postConstructor() {
if (this.id === undefined) {
this.id = generateId(this.constructor.name);
}
this.insert();
}
// Returns the outermost element of the Item.
get containerElem() {
return document.getElementById(this.id);
}
// Generic equality test.
equals(other) {
for (let key in this) {
let a = this[key];
let b = other[key];
if (!Object.is(a, b)) {
if (a == null || b == null) {
return false;
} else if (a instanceof Item && b instanceof Item) {
if (!a.equals(b)) {
return false;
}
} else if (!Object.is(a.valueOf(), b.valueOf())) {
return false;
}
}
}
return true;
}
// Insert the Item's element into the DOM.
insert() {
if (this.templateId === undefined) {
// No template required so skip this.
return;
}
this.fragment = createFromTemplate(this.templateId);
this.fragment.childNodes.forEach((child) => child.id = this.id);
this.fragment = this.populateTemplate(this.fragment);
this.setCallbacks(this.fragment);
if (this.containerElem == null || this.containerElem === undefined) {
document.getElementById(this.parentContainerId).appendChild(this.fragment);
} else {
this.containerElem.replaceWith(this.fragment);
}
}
/* Populates an HTML fragment with Item values.
*
* Arguments:
* fragment: An HTML fragment or element to modify.
*
* Returns:
* The modified fragment.
*/
populateTemplate(fragment) {
return fragment;
}
/* Set various callbacks on an HTML fragment.
*
* Arguments:
* fragment: An HTML fragment or element.
*
* Returns:
* The modified fragment.
*/
setCallbacks(fragment) {
return fragment;
}
}
// Base class for collections of Items.
class Collection extends Item {
childClass; // The class of the child Items.
childDefaults; // Default values for the child Items.
specs = []; // The input list of child Item specifications.
static create(spec, defaults) {
if (Array.isArray(spec)) {
spec = {specs: spec};
}
return super.create(spec, defaults);
}
postConstructor() {
this.children = [];
super.postConstructor();
if (this.childDefaults === undefined) {
this.childDefaults = this._defaults;
}
this.specs.forEach((childSpec) => {
this.children.push(this.childClass.create(childSpec, this.childDefaults));
});
}
// Returns the number of child Items.
get length() {
return this.children.length;
}
/* Append a child using child specifications
*
* Arguments:
* childSpec: An Object with specifications for a new child Item.
*/
append(childSpec) {
if (childSpec instanceof this.childClass) {
childSpec = childSpec.toSpec();
}
this.children.append(this.childClass.create(childSpec, this.childDefaults));
}
/* Filter child Items.
*
* Arguments:
* func: A function to filter the child Items.
*/
filter(func) {
return this.children.filter(func);
}
/* Find a child Item.
*
* Arguments:
* func: A function to use to find a child Item.
*/
find(func) {
return this.children.find(func);
}
/* Find a child element by ID.
*
* Arguments:
* childId:
*/
findIndexById(childId) {
if (childId instanceof this.childClass) {
childId = childId.id;
}
return this.children.findIndex(this.get(childId));
}
// Get a child Item by its ID.
get(childId) {
if (childId instanceof this.childClass) {
childId = childId.id;
}
return this.children.find((child) => child.id == childId);
}
// Insert the Collection into the DOM.
insert() {
document.getElementById(this.id).childNodes.forEach((child) =>
document.getElementById(this.id).removeChild(child)
);
this.children.sort(sortCompareOrder).forEach((child) => child.show());
}
// Map the children of the Collection.
map(func) {
return this.children.map(func);
}
// Push a new child Item onto the Collection.
push(child) {
this.children.push(child);
}
// Remove a child of the Collection.
pop(child) {
if (childId instanceof this.childClass) {
childId = childId.id;
}
return this.children.pop(this.findIndexById(child));
}
// Remove children from the Collection.
shift(children) {
return this.children.shift(children);
}
// Returns an Array of Objects representing the children of the Collection.
toSpec() {
return this.children.map((child) => child.toSpec());
}
// Add children to the Collection.
unshift(child) {
this.children.unshift(child);
}
}
/* Base class for Collections of URLs.
*
* Allows the spec to be a string, a Array of strings or an Array of Objects.
*
*/
class UrlCollection extends Collection {
static create(spec, defaults) {
if (typeof spec == "string") {
spec = {specs: [{url: spec}]};
} else if (Array.isArray(spec)) {
spec = {
specs: spec.map((s) => {
if (typeof s == "string") {
return {url: s};
}
if (s instanceof this) {
return s.toSpec();
}
return s;
})
};
}
return super.create(spec, defaults);
}
}
/* Dashboard class
*
* Attributes:
* columns (Integer): The number of columns in the tile grid. Defaults to 4.
* rows (Integer): The number of rows in the tile grid. Defaults to 3.
* feedScrollSpeed (Number): The scroll speed of the feed ticker in pixels
* per second. Defaults to 180.
* menu (Menu): The user defined menu items.
* feeds (Feeds): The Collection of feeds.
* tiles (Tiles): The Collection of tiles.
* topBar (TopBar): The top bar.
*/
class Dashboard extends Item {
columns = 4;
rows = 3;
feedScrollSpeed = 180;
menu = {};
feeds = {};
tiles = {};
topBar = {};
postConstructor() {
this.topBar = TopBar.create(this.topBar);
this.menu = Menu.create(this.menu);
this.feeds = Feeds.create(this.feeds, {scrollSpeed: this.feedScrollSpeed});
this.tiles = Tiles.create(this.tiles);
this._popup = PopUp.create();
}
popup(label, message) {
this._popup.show(label, message);
}
// Initialize the dashboard.
start() {
hideFocusedContainer();
this.topBar.show();
this.menu.hide();
recalculateCssVars();
this.tiles.start();
}
toSpec() {
return {
columns: this.columns,
defaultMenuSide: this.defaultMenuSide,
feedScrollSpeed: this.feedScrollSpeed,
rows: this.rows,
feeds: this.feeds.toSpec(),
menu: this.menu.toSpec(),
tiles: this.tiles.toSpec(),
topBar: this.topBar.toSpec(),
};
}
}
/* Individual feed class
*
* Attributes:
* url (string): RSS or Atom feed URL.
* bgColor (HTML color code, optional): Override the feed background color.
* refreshInterval (interval, optional): The interval between refreshing the
* feed. Defaults to "1h".
* textColor (HTML color code, optional): Override the feed text color.
* titleTextColor (HTML color code, optional): Override the feed title text
* color.
*/
class Feed extends Item {
bgColor = null;
refreshInterval = "1h";
textColor = null;
titleTextColor = null;
url;
parentContainerId = "feeds-container";
templateId = "feed-container";
postConstructor() {
this._writeLock = false;
if (this.url === undefined) {
console.error(
"Missing 'url' option in the following feed configuration",
this._spec,
);
}
this.id = generateId(this.url);
super.postConstructor();
this.refreshTimeoutRef = setInterval(
(() => this.fetch()),
parseInterval(this.refreshInterval)
);
this.fetch();
}
get locked() {
return this._writeLock;
}
// Asynchronously download the feed.
fetch() {
if (!this.lock()) {
return;
}
var url = proxyUrl + "?url=" + encodeURIComponent(this.url);
if (this.url.includes("://localhost")) {
url = this.url;
}
fetch(url)
.then((response) => response.text())
.then((data) => {
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(data, "text/xml");
this.parse(xmlDoc);
this.unlock();
}).catch((error) => {
console.error(`Error fetching feed from ${this.url}:`, error);
this.unlock();
});
}
insert() {
super.insert();
if (this.bgColor != null) {
this.containerElem.style.backgroundColor = this.bgColor;
}
}
lock() {
if (this.locked) {
return false;
}
this._writeLock = true;
return true;
}
// Parse the downloaded feed and display it.
parse(feedXml) {
this.containerElem.childNodes.forEach((child) => child.remove());
// Automatically detect whether the feed uses "item" or "entry" tags
let itemTag = "item"; // Default to RSS
if (feedXml.querySelector("entry")) {
itemTag = "entry"; // Switch to Atom if "entry" is found
}
const feedTitleText = feedXml.querySelector(
"channel > title, feed > title"
)?.textContent || "Unknown Feed";
const lastUpdated = feedXml.querySelector(
"channel > lastBuildDate, feed > updated"
)?.textContent || "Unknown Time";
const feedItems = feedXml.querySelectorAll(itemTag);
const feedTitle = createFromTemplate("feed-title").querySelector("span");
if (this.titleTextColor != null) {
feedTitle.style.color = this.titleTextColor;
}
feedTitle.textContent = `${feedTitleText} - Last Updated: ${lastUpdated} -`;
this.containerElem.appendChild(feedTitle);
feedItems.forEach((item, index) => {
// Handle both <link href="..."> and <link>...</link>
const linkElement = item.querySelector("link");
let link = "";
if (linkElement) {
if (linkElement.getAttribute("href")) {
// If <link href="...">
link = linkElement.getAttribute("href");
} else {
// If <link>...</link>
link = linkElement.textContent;
}
}
const feedItem = createFromTemplate("feed-item").querySelector("span");
const feedItemAnchor = feedItem.querySelector("a");
feedItemAnchor.href = link;
if (this.textColor != null) {
feedItemAnchor.style.color = this.textColor;
}
const itemTitle = item.querySelector("title").textContent;
feedItemAnchor.textContent = itemTitle;
this.containerElem.appendChild(feedItem);
});
var delimElem = createFromTemplate("feed-delim").querySelector("span");
if (this.textColor != null) {
delimElem.style.color = this.textColor;
}
this.containerElem.appendChild(delimElem);
// Detect a failure to load all feeds
// Do this here because the fetching is asynchronous
var globalEntries = 0;
if (document.getElementById(this.parentContainerId).childElementCount < 1) {
document.getElementById("feed-ticker-error").classList.remove("hidden");
} else {
document.getElementById("feed-ticker-error").classList.add("hidden");
}
}
toSpec() {
return {
bgColor: this.bgColor,
refreshInterval: this.refreshInterval,
textColor: this.textColor,
titleTextColor: this.titleTextColor,
url: this.url,
}
}
unlock() {
this._writeLock = false;
}
}
// Collection of Feed Items.
class Feeds extends UrlCollection {
childClass = Feed;
id = "feeds-container";
fetch() {
this.children.forEach((child) => child.fetch());
this.containerElem.style.setProperty(
"--ticker-duration",
`${this._defaults.scrollSpeed/2}s`,
);
}
}
/* A helper to manage image pan and zoom.
*
* Attributes:
* zoom (number): Zoom level increment. Defaults to 0.10 (10%).
* initialZoom (number): Initial zoom level. Defaults to 1 (100%).
* initialX (number): Initial X position. Defaults to 0.5.
* initialY (number): Initial Y position. 0.5;
* fit (string): Fit the image to "height", "width", "stretch" (to fit tile),
* or "preserve" (to preserve the aspect ratio). Defaults to "stretch".
* position: Value for CSS background-position when at default zoom. Defaults
* to "center".
*
* Arguments:
* imageId (string): HTML element ID of the target image.
* options (Object): Values for the attributes of the helper object.
*/
class ImageHelper {
zoom = 0.10;
initialZoom = 1;
initialX = 0.5;
initialY = 0.5;
fit = "stretch";
position = "center";
#height; // final height of image at 100% zoom
#width; // final width of image at 100% zoom
#bgHeight; // The current height of the background
#bgWidth; // The current width of the background
#posX; // X position of the background
#posY; // Y position of the background
#previousEvent; // The event used for zooming
#placeholder; // A placeholder image to stick in src
constructor(imageId, options) {
this.imageId = imageId;
this.update(options);
this.onload = this._onload.bind(this);
this.onmousedown = this._onmousedown.bind(this);
this.onmousemove = this._onmousemove.bind(this);
this.onmouseup = this._onmouseup.bind(this);
this.onwheel = this._onwheel.bind(this);
}
get image() {
return document.getElementById(this.imageId);
}
// Update the values of the public attributes.
update(options) {
this.zoom = options.zoom !== undefined ? options.zoom : this.zoom;
this.initialZoom = options.initialZoom !== undefined ? options.initialZoom : this.initialZoom;
this.initialX = options.initialX !== undefined ? options.initialX : this.initialX;
this.initialY = options.initialY !== undefined ? options.initialY : this.initialY;
this.fit = options.fit !== undefined ? options.fit : this.fit;
this.position = options.position !== undefined ? options.position : this.position;
}
// Figure out the exact dimensions of the background image.
calculateInitialDimensions() {
const initial = Math.max(this.initialZoom, 1);
const computedStyle = window.getComputedStyle(this.image, null);
const computedWidth = parseInt(computedStyle.width, 10);
const computedHeight = parseInt(computedStyle.height, 10);
const naturalWidth = parseInt(this.image.naturalWidth, 10);
const naturalHeight = parseInt(this.image.naturalHeight, 10);
const widthRatio = naturalWidth / computedWidth;
const heightRatio = naturalHeight / computedHeight;
const naturalAspectRatio = naturalWidth / naturalHeight;
const computedAspectRatio = computedWidth / computedHeight;
// Default behavior is to stretch to fit
this.#width = computedWidth;
this.#height = computedHeight;
if (computedAspectRatio >= 1) {
// Tile is wider than it is tall, or maybe perfectly square
if (this.fit == "width") {
this.#height = naturalHeight / widthRatio;
} else if (this.fit == "height") {
this.#width = naturalWidth / heightRatio;
} else if (this.fit == "preserve") {
// Preserve aspect ratio and fit in tile
if (naturalAspectRatio > 1) {
// Wider than tall - shrink height to fit width
this.#height = naturalHeight / widthRatio;
} else if (naturalAspectRatio < 1) {
// Taller than wide - shrink width to fit width
this.#width = naturalWidth / heightRatio;
} else {
// Perfectly square image - shrink width to fit width
this.#width = naturalWidth / heightRatio;
}
}
} else if (computedAspectRatio < 1) {
// Tile is taller than it is wide
if (this.fit == "width") {
this.#height = naturalHeight / widthRatio;
} else if (this.fit == "height") {
this.#width = naturalWidth / heightRatio;
} else if (this.fit == "preserve") {
// Preserve aspect ratio and fit in tile
if (naturalAspectRatio > 1) {
// Wider than tall - shrink width to fit height
this.#width = naturalWidth / heightRatio;
} else if (naturalAspectRatio < 1) {
// Taller than wide - shrink height to fit height
this.#height = naturalHeight / widthRatio;
} else {
// Perfectly square image - shrink height to fit height
this.#height = naturalHeight / widthRatio;
}
}
} // Default behavior is to stretch to fit
this.#bgWidth = this.#width * initial;
this.#bgHeight = this.#height * initial;
this.#posX = -(this.#bgWidth - this.#width) * 0.5;
this.#posY = -(this.#bgHeight - this.#height) * 0.5;
}
// Unbound onload callback
_onload(event) {
if (this.#placeholder !== undefined && this.image.src == this.#placeholder) {
return;
}
this.calculateInitialDimensions();
this.image.style.backgroundImage = `url("${this.image.src}")`;
this.#placeholder = "data:image/svg+xml;base64,"
+ window.btoa(
`<svg xmlns="http://www.w3.org/2000/svg" width="${this.image.naturalWidth}" height="${this.image.naturalHeight}"></svg>`
);
this.image.src = this.#placeholder;
this.updateStyle();
this.image.onmousedown = this.onmousedown;
this.image.onwheel = this.onwheel;
}
// Unbound onmousedown callback
_onmousedown(event) {
event.preventDefault();
this.previousEvent = event;
document.addEventListener("mousemove", this.onmousemove);
document.addEventListener("mouseup", this.onmouseup, {once: true});
}
// Unbound onmousemove callback
_onmousemove(event) {
event.preventDefault();
if (this.#previousEvent == undefined) {
this.#previousEvent = event;
return;
}
this.#posX += event.pageX - this.#previousEvent.pageX;
this.#posY += event.pageY - this.#previousEvent.pageY;
this.#previousEvent = event;
this.updateStyle();
}
// Unbound onmouseup callback
_onmouseup(event) {
document.removeEventListener('mousemove', this.onmousemove);
}
// Unbound onwheel callback
_onwheel(event) {
event.preventDefault();
var deltaY = 0;
if (event.deltaY) { // FireFox 17+ (IE9+, Chrome 31+?)
deltaY = event.deltaY;
} else if (event.wheelDelta) {
deltaY = -event.wheelDelta;
}