-
Notifications
You must be signed in to change notification settings - Fork 0
/
pageStuff.js
600 lines (498 loc) · 25.9 KB
/
pageStuff.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
/*
Copyright 2022 James D. Miller
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// Page Stuff (pS) module
// pageStuff.js
console.log('pS _*-*_');
// 2:13 PM Tue January 2, 2024
/*
*/
window.pS = (function() {
"use strict";
// Globals
var m_closer, m_opener;
var m_navMenu;
var m_scrollAdjust;
var m_scrollContainer;
var m_dialog, m_cookieLink;
var m_generalDialog;
var m_scrollHistory = {}; // this is revealed below, so MUST do this here and not in initialize.
var m_keyStates;
var m_keyMap;
function scroll( targetID, pars={}) {
let mode = uT.setDefault( pars.mode, 'jump');
let addToHistory = uT.setDefault( pars.addToHistory, true);
let scrollDuration = uT.setDefault( pars.scrollDuration, 300);
let toPageTop = false;
m_scrollHistory.currentTarget = targetID;
// If can't find ID, search for a named anchor element
var scrollTarget = $('#' + targetID);
if (scrollTarget.length == 0) {
var anchorSearchString = "a[name='" + targetID + "']";
var scrollTarget = $( anchorSearchString);
if (scrollTarget.length == 0) {
// if trying to scroll to a non-existent top target
if (['top','TOP','very-top','scroll-to-very-top'].includes( targetID)) {
toPageTop = true;
} else {
console.log('found nothing');
return null;
}
} else {
console.log('found name');
}
} else {
console.log('found ID');
}
// Must have found the ID. Now, scroll the page.
if (scrollTarget.offset()) {
if (addToHistory) m_scrollHistory.index = m_scrollHistory.targets.push( targetID) - 1;
let scroll_px = scrollTarget.offset().top;
let totalScroll_px = scroll_px + m_scrollAdjust;
// If the container is a div that can scroll independent of the main page (e.g. index.html),
// then must account for that scroll position.
if (m_scrollContainer.attr('data-divType') == "scroll") {
let scrollPosition = m_scrollContainer.scrollTop();
totalScroll_px += scrollPosition;
}
// debug help...
/*
console.log("----before movement to " + targetID + "---");
console.log( "sT.offset=" + scrollTarget.offset().top.toFixed(0) +
", sT.position=" + scrollTarget.position().top.toFixed(0) +
", adjust=" + m_scrollAdjust.toFixed(0) +
", c.scrollTop=" + m_scrollContainer.scrollTop().toFixed(0));
console.log("total="+totalScroll_px.toFixed(0));
*/
if (mode == 'pageReload') {
// Do a fast scroll to the top, wait, then slowly scroll to the target.
m_scrollContainer.animate( {'scrollTop':'0px'}, 0);
window.setTimeout( function() {
console.log('top, then scroll to target,' + totalScroll_px);
m_scrollContainer.animate( { 'scrollTop': totalScroll_px }, scrollDuration); // 1000
}, 700);
} else if (mode == 'jump') {
// This mode is used for scrolling to targets on the same page.
// e.g. put this in the anchor element: onclick="pS.scroll('pygame');"
console.log('scroll to target, ' + totalScroll_px);
m_scrollContainer.animate( { 'scrollTop': totalScroll_px }, scrollDuration); // 1000
}
// Ok, to the top of the page you go.
} else if (toPageTop) {
m_scrollContainer.animate( {'scrollTop': 0}, scrollDuration);
} else {
console.log("should not be seeing this");
}
// Prevent default behavior that scrolls to the top.
return false;
}
function logEntry( eventDescription, mode='normal') {
// If this page is coming from the production server...
var pageURL = window.location.href;
if (pageURL.includes("triquence")) {
var sheetURL = 'https://script.google.com/macros/s/AKfycbzfivtrNUyClOX6_6UA2HTWhtk6dmqsbE1sLTUXoC8gSC5zQdZq0uF75hQfIHlSpaQm/exec';
// AJAX
var xhttp = new XMLHttpRequest();
xhttp.open('GET', sheetURL + '?mode=' + mode + '&eventDesc=' + eventDescription, true);
xhttp.send();
} else {
console.log("Event = " + eventDescription);
}
}
function openNav() {
m_navMenu.style.height = "100%";
}
function closeNav() {
m_navMenu.style.height = "0%";
}
// https://javascript.info/cookie
// https://www.w3schools.com/js/js_cookies.asp
// https://github.com/js-cookie/js-cookie/tree/latest
function cookieSet() {
// 2592000 = 30 * 24 * 3600 (30 days in seconds)
// 7776000 = 90 * 24 * 3600 (90 days in seconds)
document.cookie = "youtube-consent=accept; max-age=7776000; samesite=strict";
}
function cookieRemove() {
document.cookie = "youtube-consent=reject; max-age=0; samesite=strict";
}
function cookieCheck() {
return document.cookie.includes("youtube-consent");
}
function viewGeneralDialog( pars={}) {
let message = uT.setDefault( pars.message, "something to say...");
let title = uT.setDefault( pars.title, "HEADS UP");
let label_accept = uT.setDefault( pars.label_accept, null);
let label_reject = uT.setDefault( pars.label_reject, null);
let label_close = uT.setDefault( pars.label_close, null);
let purpose = uT.setDefault( pars.purpose, null);
document.getElementById('gD-purpose').innerHTML = purpose;
if (m_generalDialog) {
let button_accept = document.getElementById("gD-accept");
if (label_accept) {
button_accept.innerHTML = label_accept;
button_accept.style.display = "inline";
} else {
button_accept.style.display = "none";
}
let button_reject = document.getElementById("gD-reject");
if (label_reject) {
button_reject.innerHTML = label_reject;
button_reject.style.display = "inline";
} else {
button_reject.style.display = "none";
}
let button_close = document.getElementById("gD-close");
if (label_close) {
button_close.innerHTML = label_close;
button_close.style.display = "inline";
} else {
button_close.style.display = "none";
}
jQuery("#title").html( title);
jQuery("#dialogMessage").html( message);
m_generalDialog.showModal();
}
}
function viewDialog( pars={}) {
let alwaysShowDialog = uT.setDefault( pars.alwaysShowDialog, true);
let statusMessage;
if (m_dialog) {
if (alwaysShowDialog) m_dialog.showModal();
if ( cookieCheck()) {
statusMessage = " \u2713"; // a check mark
} else {
statusMessage = "";
if ( ! alwaysShowDialog) m_dialog.showModal();
}
jQuery("#dialog-status").text( statusMessage);
}
// When the page loads, if the dialog is needed, the first button get focus (by default).
// So, this counters that native behavior.
document.getElementById("firstDialogButton").blur();
}
function getTopicTitle( videoDivElement) {
// Find the sibling <p> elements containing the <strong> element with class "title_2"
var siblingParagraphs = videoDivElement.siblings("p").filter(function() {
return $(this).find("strong.title_2").length > 0;
});
// Get the text within the <strong> element of the first matching sibling <p> element
var title = siblingParagraphs.first().find("strong.title_2").text();
return title;
}
function loadLargeImage( img, fileName=null) {
if (fileName) {
img.src = "screenshots/" + fileName;
} else {
let srcString = img.src;
img.src = srcString.replace("_550w","");
}
}
function checkForAbsoluteLinks() {
// check for absolute links... https://triquence.org, pet.triquence, waconia.triquence
$('a').each( function( index, value) {
let href = $(this).attr("href");
let finalHref = null;
if (href && (href != "")) {
// IP address on local network
if (window.location.href.includes("192.168.1.106")) {
if (href.includes("https://triquence.org")) {
finalHref = href.replace( "https://triquence.org", "http://192.168.1.106/ttc-root");
} else if (href.includes("pet.triquence")) {
finalHref = href.replace( "https://pet.triquence.org", "http://192.168.1.106/pet-dev");
} else if (href.includes("waconia.triquence")) {
finalHref = href.replace( "https://waconia.triquence.org", "http://192.168.1.106/waconia-50webs-dev");
} else {
// nothing yet...
}
// nuc on local network
} else if (window.location.href.includes("nuc/")) {
if (href.includes("https://triquence.org")) {
finalHref = href.replace( "https://triquence.org", "http://nuc/ttc-root");
} else if (href.includes("pet.triquence")) {
finalHref = href.replace( "https://pet.triquence.org", "http://nuc/pet-dev");
} else if (href.includes("waconia.triquence")) {
finalHref = href.replace( "https://waconia.triquence.org", "http://nuc/waconia-50webs-dev");
} else {
// nothing yet...
}
// secure localhost only on local server
} else if (window.location.href.includes("localhost")) {
if (href.includes("https://triquence.org")) {
finalHref = href.replace( "https://triquence.org", "https://localhost/ttc-root");
} else if (href.includes("pet.triquence")) {
finalHref = href.replace( "https://pet.triquence.org", "https://localhost/pet-dev");
} else if (href.includes("waconia.triquence")) {
finalHref = href.replace( "https://waconia.triquence.org", "https://localhost/waconia-50webs-dev");
} else {
// nothing yet...
}
// github server
} else if (window.location.href.includes("m-jim-d")) {
if (href.includes("https://triquence.org")) {
finalHref = href.replace( "https://triquence.org", "https://m-jim-d.github.io/springsandpucks");
} else if (href.includes("pet.triquence")) {
finalHref = href.replace( "https://pet.triquence.org", "https://m-jim-d.github.io/pet");
} else if (href.includes("waconia.triquence")) {
finalHref = href.replace( "https://waconia.triquence.org", "https://m-jim-d.github.io/waconia");
} else {
// nothing yet...
}
// firebase server (web.app)
} else if (window.location.href.includes("web.app")) {
if (href.includes("https://triquence.org")) {
finalHref = href.replace( "https://triquence.org", "https://ttcorg-64150.web.app");
} else if (href.includes("pet.triquence")) {
finalHref = href.replace( "https://pet.triquence.org", "https://pet-ttc.web.app");
} else if (href.includes("waconia.triquence")) {
finalHref = href.replace( "https://waconia.triquence.org", "https://waconia-ttc.web.app");
} else {
// nothing yet...
}
// firebase server (firebaseapp.com)
} else if (window.location.href.includes("firebaseapp.com")) {
if (href.includes("https://triquence.org")) {
finalHref = href.replace( "https://triquence.org", "https://ttcorg-64150.firebaseapp.com");
} else if (href.includes("pet.triquence")) {
finalHref = href.replace( "https://pet.triquence.org", "https://pet-ttc.firebaseapp.com");
} else if (href.includes("waconia.triquence")) {
finalHref = href.replace( "https://waconia.triquence.org", "https://waconia-ttc.firebaseapp.com");
} else {
// nothing yet...
}
// some other server...
} else {
// nothing yet
}
// If an absolute link was found, use the edited version, finalHref.
if (finalHref) $(this).attr("href", finalHref);
}
});
}
function initialize( pars={}) {
let dialogOptions = uT.setDefault( pars.dialogOptions, false);
let generalDialog = uT.setDefault( pars.generalDialog, false);
let navMenu = uT.setDefault( pars.navMenu, true);
let navDivName = uT.setDefault( pars.navDiv, "navDiv");
let pageDesc = uT.setDefault( pars.pageDesc, null);
let logPage = uT.setDefault( pars.logPage, true);
let pathSiteMap = uT.setDefault( pars.pathSiteMap, "sitemap.html?v7"); // changing the version overrides cache
let scrollAtLoad = uT.setDefault( pars.scrollAtLoad, true);
m_scrollAdjust = uT.setDefault( pars.scrollAdjust, 0);
// Currently using the helpScroller id to reference the container.
m_scrollContainer = $('#helpScroller'); // note: the html element may use this ID.
// As a backup, use the method below to reference the full page. This does not work for the index.html (S&P) page where the left panel scrolls.
if (m_scrollContainer.length == 0) {
console.log("warning: expecting helpScroller ID. Will use html tag.");
m_scrollContainer = $('html, body');
}
// Tempting to initialize, make m_scrollHistory an object here (={}). But MUST NOT since it is revealed below. Read comments
// in gwModule.js above the revealing section.
m_scrollHistory.targets = ['top'];
m_scrollHistory.currentTarget = 'top';
m_scrollHistory.index = 0;
m_keyStates = {};
m_keyMap = {
'ShiftLeft':'key_shift', 'ShiftRight':'key_shift',
'ControlLeft':'key_ctrl', 'ControlRight':'key_ctrl',
'AltLeft':'key_alt', 'AltRight':'key_alt',
'ArrowLeft':'key_leftArrow', 'ArrowUp':'key_upArrow', 'ArrowRight':'key_rightArrow', 'ArrowDown':'key_downArrow',
};
for (let key in m_keyMap) m_keyStates[ m_keyMap[ key]] = 'U';
// Take note...
if (logPage) logEntry( pageDesc);
if (navMenu) {
// put the navigation menu into the div
let navDiv = document.getElementById( navDivName);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if ((xhr.readyState === 4) && (xhr.status === 200)) {
navDiv.innerHTML = xhr.responseText;
m_navMenu = document.getElementById("myNav");
m_closer = document.getElementById("closer");
m_closer.addEventListener("click", function(event) {
event.preventDefault();
closeNav();
});
// Note that the opener is not an anchor element, so no need for preventDefault.
m_opener = document.getElementById("opener");
m_opener.addEventListener('click', openNav);
m_opener.title = "Site Menu";
// Now that navigation menu has loaded, check the page for absolute links. Note: of course, this only runs
// on pages that load the navigation menu.
checkForAbsoluteLinks();
}
};
function handleXHR_error() {
let theMessage = "The navigation menu (hamburger icon) depends on a webserver. " +
"If you're opening this page directly, without a webserver, try navigating using any available links.";
window.alert( theMessage);
}
xhr.addEventListener('error', handleXHR_error);
xhr.open("GET", pathSiteMap, true);
xhr.send();
}
// This section is intended for use on pages other than index.html and client.html.
// The scrollAtLoad parameter should be set to false in the init call for pageStuff on index.html (and client.html).
// index.html uses the startup-scrolling functionality that is in gwModule.js (see scrollTargetAtStart variable).
if (scrollAtLoad) {
// This zero delay seems necessary for Chrome to behave as expected on page refresh (should jump to the top, then scroll to the target)
window.setTimeout( function() {
// The ready approach does not work well with a page having many auto-sizing images. Rather, better to wait
// until EVERYTHING is done loading, including images, as is done in the 'load' method above.
//$(document).ready( function() {});
// Bailed on using hash parameter in URL. Native jumps to anchors are confusing. So sidestepping that mess by using query parameters.
//var hashID = window.location.hash;
// Discard everything after the "&". Don't usually need this unless something (unwanted) gets appended to the URL by a server.
var queryStringInURL = window.location.search.split("&")[0];
// Then use the part after the "?".
var queryID = queryStringInURL.slice(1);
if (queryID) {
console.log("queryID=" + queryID);
scroll( queryID, {'mode':'pageReload'});
};
}, 0);
}
// click-event listener for scroll links
$('.scroll-link').click( function( event) {
event.preventDefault();
let target = $(this).attr('data-scroll-target');
scroll( target);
})
// event listener for keyboard operations with the scrolling history
document.addEventListener("keydown", function(e) {
if (e.code in m_keyMap) {
let key = m_keyMap[ e.code];
if (m_keyStates[ key] == 'U') { // inhibit key repeats
m_keyStates[ key] = 'D';
if ((m_keyStates['key_ctrl']=='D') && (m_keyStates['key_shift']=='D')) {
if (key == "key_leftArrow") {
if (m_scrollHistory.index > 0) m_scrollHistory.index--;
scroll( m_scrollHistory.targets[ m_scrollHistory.index], {'addToHistory':false, 'scrollDuration':0});
} else if (key == "key_rightArrow") {
if (m_scrollHistory.index < (m_scrollHistory.targets.length-1)) m_scrollHistory.index++;
scroll( m_scrollHistory.targets[ m_scrollHistory.index], {'addToHistory':false, 'scrollDuration':0});
} else if (key == "key_upArrow") {
scroll("TOP", {'addToHistory':false, 'scrollDuration':0});
} else if (key == "key_downArrow") {
// nothing yet
//console.log("current container.scrollTop() = " + m_scrollContainer.scrollTop().toFixed(0));
}
}
}
}
}, {capture: false}); //This "false" makes this fire in the bubbling phase (not capturing phase).
document.addEventListener("keyup", function(e) {
if (e.code in m_keyMap) {
m_keyStates[ m_keyMap[ e.code]] = 'U';
}
}, {capture: false});
if (generalDialog) {
m_generalDialog = document.getElementById("generalDialog");
m_generalDialog.addEventListener("close", function() {
const value = m_generalDialog.returnValue;
const purpose = document.getElementById('gD-purpose').innerHTML;
//console.log("purpose = " + purpose);
if (value == "accept") {
//console.log('gd = accept');
if (purpose == "post-normal") {
cR.postCaptureToCF({'action':'postOne', 'actionType':'normal'});
} else if (purpose == "post-update") {
cR.postCaptureToCF({'action':'postOne', 'actionType':'update'});
} else if (purpose == "post-delete") {
cR.postCaptureToCF({'action':'postOne', 'actionType':'delete'});
}
} else if (value == "reject") {
//console.log('gd = reject');
} else if (value == "close") {
//console.log('gd = close');
}
});
}
// dialogOptions is True for all the pages with YouTube videos.
if (dialogOptions) {
m_dialog = document.getElementById("cookieConsent");
m_cookieLink = document.getElementById("cookieLink");
// Check for prior consent. If not there, display the dialog.
viewDialog({'alwaysShowDialog':false});
m_dialog.addEventListener("close", function() {
const value = m_dialog.returnValue;
if (value == "accept") {
cookieSet();
//console.log("cookie = " + document.cookie);
} else if (value == "reject") {
cookieRemove();
} else if (value == "close") {
console.log('Cookies stay the same.');
}
});
m_cookieLink.addEventListener("click", function(event) {
event.preventDefault();
viewDialog();
});
// Define event handlers for each video container.
$('.video-container').click( function() {
logEntry( "Video: " + getTopicTitle($(this)) );
if ( ! cookieCheck()) { // (Cookies.get('youtube-consent') == 'accept')
console.log('url = ' + "https://youtu.be/" + $(this).attr('data-videoID'));
window.open( "https://youtu.be/" + $(this).attr('data-videoID'), '_blank');
} else {
if ( ! $(this).children("img.playButton").is(":hidden")) {
// ?autoplay=1&mute=1 an autoplay with mute works, but apparently YouTube does not count these as user-initiated plays.
// ?rel=0 limit the follow-up videos to the same youtube channel
var video = '<iframe src="' + '//www.youtube.com/embed/' + $(this).attr('data-videoID') + '?rel=0' + '"' +
' width="' + $(this).children("img.frameCapture").width() + '"' +
' height="' + $(this).children("img.frameCapture").height() + '"' +
' frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>';
$(this).find("img").hide();
$(this).append( video);
}
}
}).mouseenter( function() {
$(this).children("img.playButton").css('opacity', "1.0");
}).mouseleave( function() {
$(this).children("img.playButton").css('opacity', "0.7");
});
// Loop through all the video containers...
$('.video-container').each( function(i, item) {
var imageSource = $(item).children("img.frameCapture").attr('src');
// Use the YouTube default image if an src for a screen-shot isn't given.
if (imageSource == "") {
var linkToYTImage = "https://i.ytimg.com/vi/" + $(this).attr('data-videoID') + "/hqdefault.jpg"; // mqdefault hqdefault maxresdefault
$(item).children("img.frameCapture").attr('src', linkToYTImage);
}
// Add an alt attribute to the image.
$(item).children("img.frameCapture").attr('alt', getTopicTitle($(this)) );
// Add a play-button image as an overlay.
$(item).append('<img class="playButton" src="screenshots/play_button.png" alt="play button">');
});
}
}
return {
// Objects
'scrollHistory': m_scrollHistory,
// Variables
// Methods
'init': initialize,
'logEntry': logEntry,
'scroll': scroll,
'viewDialog': viewDialog,
'viewGeneralDialog': viewGeneralDialog,
'loadLargeImage': loadLargeImage
};
})();