-
-
Notifications
You must be signed in to change notification settings - Fork 209
Expand file tree
/
Copy pathalmanac.js
More file actions
756 lines (647 loc) · 28.6 KB
/
almanac.js
File metadata and controls
756 lines (647 loc) · 28.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
/* global gtag */
// These are the core menu options
// Language, Year and ToC select switcher (mobile)
function handleSelectSwitchers() {
let languageYearSwitchers = document.querySelectorAll('.language-switcher select, .year-switcher select, .table-of-contents-switcher select');
for (let i = 0; i < languageYearSwitchers.length; i++) {
languageYearSwitchers[i].addEventListener('change', function (e) {
let selectedOption = this.options[this.selectedIndex];
if (e.target.dataset.label && selectedOption.dataset.event) {
gtag('event', selectedOption.dataset.event, {
'event_category': 'clicks',
'event_label': e.target.dataset.label,
'transport_type': 'beacon',
'value': 1
})
}
//Reset the selector back in case user uses Back button
let selectedValue = e.target.value;
if (selectedValue && selectedValue !== window.location.pathname) {
e.target.value = window.location.pathname;
window.location = selectedValue;
}
});
}
}
// Search, Language, Year and ToC menus (desktop)
function handleNavMenu() {
function closeAnyOtherOpenDropdown(e) {
// If the click was in a menu that's already open then ignore as just been opened.
if (e.target.classList.contains('dropdown-open')) {
return
}
// If the click was in search nav, then ignore as don't want to close search menu.
let searchNavs = document.querySelectorAll('.search-nav ul:not(hidden)');
for (let i = 0; i < searchNavs.length; i++) {
if (searchNavs[i].contains(e.target)) {
return
}
}
// Else a click elsewhere so close all the menus
let openDropdownBtn = document.querySelector('.nav-dropdown-btn.dropdown-open');
openDropdownBtn && openDropdownBtn.click();
}
function trapFocusInList(e) {
let list = e.currentTarget;
let isInFooter = list.classList.contains('footer-list');
if (e.key === "ArrowDown") {
let siblingElem = isInFooter ? e.target.parentElement.previousElementSibling : e.target.parentElement.nextElementSibling;
let focusableElem = siblingElem ? siblingElem.querySelector('a') : (isInFooter ? lastFocusableElementInList : firstFocusableElementInList);
e.preventDefault();
focusableElem.focus();
} else if (e.key === "ArrowUp") {
let siblingElem = isInFooter ? e.target.parentElement.nextElementSibling : e.target.parentElement.previousElementSibling;
let focusableElem = siblingElem ? siblingElem.querySelector('a') : (isInFooter ? firstFocusableElementInList : lastFocusableElementInList);
e.preventDefault();
focusableElem.focus();
} else if (e.key === "Escape") {
let navDropDown = e.currentTarget.closest('.nav-dropdown');
let navDropDownBtn = navDropDown.querySelector('.nav-dropdown-btn');
navDropDownBtn.click();
navDropDownBtn.focus();
}
}
let firstFocusableElementInList, lastFocusableElementInList;
function toggleDropdownVisibility(e) {
let dropdownBtn = e.currentTarget;
let dropdown = dropdownBtn.closest('.nav-dropdown');
let list = dropdown.querySelector('.nav-dropdown-list');
let isListVisible = !list.classList.toggle('hidden');
let dropdownOpen = dropdownBtn.classList.toggle('dropdown-open');
dropdownBtn.setAttribute('aria-expanded', dropdownOpen);
if (isListVisible) {
let btnBoundingRect = dropdownBtn.getBoundingClientRect();
let listBoundingRect = list.getBoundingClientRect();
if (listBoundingRect.width <= btnBoundingRect.width) {
list.classList.add("align-center");
} else if (btnBoundingRect.left + listBoundingRect.width > window.innerWidth) {
list.classList.add("align-right");
}
document.body.addEventListener('click', closeAnyOtherOpenDropdown, true);
let navItems = list.querySelectorAll('a');
firstFocusableElementInList = navItems[0];
lastFocusableElementInList = navItems[navItems.length - 1];
list.addEventListener('keydown', trapFocusInList);
if (e.currentTarget.classList.contains('search-button')) {
e.currentTarget.parentNode.querySelector('input').focus();
}
} else {
list.removeEventListener('keydown', trapFocusInList);
document.body.removeEventListener('click', closeAnyOtherOpenDropdown, true);
}
}
// Might need to change menu hanging direction on window resize to avoid overflow
function checkNavDropdown() {
let list = window.document.querySelector('.dropdown-open ~ .nav-dropdown-list');
let dropdownBtn = window.document.querySelector('button.dropdown-open');
// If no open menu, then we're done
if (!list || !dropdownBtn) {
return;
}
let btnBoundingRect = dropdownBtn.getBoundingClientRect();
let listBoundingRect = list.getBoundingClientRect();
if (listBoundingRect.width <= btnBoundingRect.width) {
list.classList.remove("align-right");
list.classList.add("align-center");
} else if (btnBoundingRect.left + listBoundingRect.width > window.innerWidth) {
list.classList.remove("align-center");
list.classList.add("align-right");
} else {
list.classList.remove("align-center");
list.classList.remove("align-right");
}
}
window.onresize = checkNavDropdown;
function navBtnKeyDownHandler(e) {
let dropdownList = e.currentTarget.nextElementSibling;
let isDropdownOpen = e.currentTarget.classList.contains('dropdown-open');
let isInFooter = dropdownList.classList.contains('footer-list');
if (e.key === "Escape") {
e.currentTarget.click();
} else if (e.key === "ArrowDown") {
e.preventDefault();
!isDropdownOpen && e.currentTarget.click();
(isInFooter ? dropdownList.lastElementChild : dropdownList.firstElementChild).querySelector('a').focus();
} else if (isInFooter && e.key === "ArrowUp") {
e.preventDefault();
!isDropdownOpen && e.currentTarget.click();
dropdownList.firstElementChild.querySelector('a').focus();
}
}
let navDropdownButtons = document.querySelectorAll('.nav-dropdown-btn');
for (let i = 0; i < navDropdownButtons.length; i++) {
navDropdownButtons[i].addEventListener('click', toggleDropdownVisibility);
navDropdownButtons[i].addEventListener('keydown', navBtnKeyDownHandler);
}
}
// The main mobile hamburger menu
function handleMobileMenu() {
let menuBtn = document.querySelector('.menu-btn');
let menuNav = document.querySelector('#menu');
let main = document.querySelector('main');
let footer = document.querySelector('footer');
function toggleNavMenu() {
let menuOpen = document.body.classList.toggle('menu-open');
menuBtn.classList.toggle("menu-btn-active");
menuBtn.setAttribute('aria-expanded', menuOpen);
let ariaLabel = menuOpen ? menuBtn.getAttribute('data-close-text') : menuBtn.getAttribute('data-open-text');
menuBtn.setAttribute('aria-label', ariaLabel);
// Toogle inert to keep focus in the menu and header
main.toggleAttribute('inert');
footer.toggleAttribute('inert');
/* When you open the menu, add an event listener to close it when clicking outside the menu area */
/* Remove it on closing the menu */
if (menuBtn.getAttribute('aria-expanded') === 'true') {
document.body.addEventListener('click', toggleNavMenu, false);
} else {
document.body.removeEventListener('click', toggleNavMenu, false);
}
}
menuBtn.addEventListener('click', function (event) {
toggleNavMenu();
event.stopPropagation();
});
/* Add a click listener to menu so when it's open it swallows click to avoid above click closing it */
menuNav.addEventListener('click', function (event) {
event.stopPropagation();
});
menuNav.addEventListener('keydown', function (event) {
if (event.key === 'Escape') {
if (menuBtn.getAttribute('aria-expanded') === 'true') {
toggleNavMenu();
menuBtn.focus();
}
}
});
}
// We can add click events to elements (e.g. ebook) and get event label from data-event attribute
function handleDataEvents() {
document.querySelectorAll('[data-event]').forEach(trackableElement => {
trackableElement.addEventListener('click', function (event) {
gtag('event', event.target.dataset.event, {
'event_category': 'clicks',
'event_label': event.target.dataset.label,
'transport_type': 'beacon',
'value': 1
})
});
});
}
// Now we're all set up, activate all the elements that depend on JavaScript.
// We do this in inline JS in the page after header loads to get those items displaying
// correctly and avoid the initial CLS (even before above runs which is a bit cheeky to be honest!)
// but need to do it again as other JS-elements will now have loaded further down the page
function activateJavaScriptElements() {
document.querySelectorAll('.js-hide').forEach(element => {
// Don't just hide it - delete it completely to avoid any specifity issues
element.parentNode.removeChild(element);
});
document.querySelectorAll('.js-enable').forEach(element => {
element.classList.remove('js-enable');
element.classList.remove('hidden');
element.disabled = false;
element.hidden = false;
});
}
//This function removes the lazy-loading attributes from all img and iframe tags
//Useful for print view for example (https://bugs.chromium.org/p/chromium/issues/detail?id=875403)
function removeLazyLoading() {
//If no Array.from then pretty sure there will be no native lazy-loading support to remove!
if (Array.from) {
console.log("Removing lazy loading...");
Array.from(document.querySelectorAll('img[loading], iframe[loading]')).forEach(function (element) {
element.removeAttribute('loading');
});
}
}
//Add an event handler to remove LazyLoading when entering print mode
function removeLazyLoadingOnPrint() {
if ("onbeforeprint" in window) {
window.onbeforeprint = removeLazyLoading;
}
}
//Check if in print mode so we can remove lazy loading and block interactive visuals
function isInPrintMode() {
let printMode = false;
if (window.URL && window.URLSearchParams) {
let url = new URL(window.location);
printMode = url.searchParams.has('print');
}
if (printMode) {
console.log("Print Mode");
removeLazyLoading();
}
gtag('event', 'print-mode', { 'event_category': 'user', 'event_label': '' + printMode, 'value': +printMode })
return printMode;
}
//Check if the screen meets minimum size requirements for Interactive figures
//At the moment we base it on 600px break point matching CSS but it does not need to be the same
function bigEnoughForInteractiveFigures() {
if (!(window.matchMedia('(max-width: 600px)').matches)) {
gtag('event', 'min-sheets-width', { 'event_category': 'user', 'event_label': 'true', 'value': 1 });
return true;
}
gtag('event', 'min-sheets-width', { 'event_category': 'user', 'event_label': 'false', 'value': 0 });
console.log('Screen too small for interactive visuals');
return false;
}
//Data Save can be set to on, so let's check it
function dataSaverEnabled() {
let dataSaver = false;
if ('connection' in navigator) {
dataSaver = navigator.connection.saveData;
if (dataSaver) {
console.log('DataSaver is enabled');
gtag('event', 'data-saver', { 'event_category': 'user', 'event_label': 'enabled', 'value': 1 });
} else {
gtag('event', 'data-saver', { 'event_category': 'user', 'event_label': 'not-enabled', 'value': 0 });
}
} else {
gtag('event', 'data-saver', { 'event_category': 'user', 'event_label': 'not-reported', 'value': 0 });
}
return dataSaver;
}
//Check if network API states this is a high bandwidth connection
//Assume it is for those browsers who do not support this (e.g. Safari and IE)
function highBandwidthConnection() {
let highBandwidth = true;
if ('connection' in navigator) {
const effectiveType = navigator.connection.effectiveType;
if (effectiveType == 'slow-2g' || effectiveType == '2g' || effectiveType == '3g') {
highBandwidth = false;
console.log('effectiveType ' + effectiveType + ' is low BandWidth');
gtag('event', 'connection-type', { 'event_category': 'user', 'event_label': effectiveType, 'value': 0 });
} else {
gtag('event', 'connection-type', { 'event_category': 'user', 'event_label': effectiveType, 'value': 1 });
}
} else {
gtag('event', 'connection-type', { 'event_category': 'user', 'event_label': 'not-reported', 'value': 1 });
}
return highBandwidth;
}
//iOS causes Google Sheets to create a 6000 by 3700 canvas, which annoyingly isn't supported by iOS!
//Let's check if we have large Canvas support (annoyingly no API for this!)
function highResolutionCanvasSupported() {
let largeCanvasSupported = false;
try {
// Set large sized canvas dimensions and draw test rectangle
let cvs = document ? document.createElement('canvas') : null;
let ctx = cvs && cvs.getContext ? cvs.getContext('2d') : null;
let scale = window.devicePixelRatio || 1;
if (scale > 1) {
cvs.width = 6000;
cvs.height = 3700;
ctx.fillRect(5999, 3699, 1, 1);
largeCanvasSupported = Boolean(ctx.getImageData(5999, 3699, 1, 1).data[3]) == 1;
} else {
cvs.width = 1200;
cvs.height = 742;
ctx.fillRect(1199, 741, 1, 1);
largeCanvasSupported = Boolean(ctx.getImageData(1199, 741, 1, 1).data[3]) == 1;
}
}
catch {
largeCanvasSupported = false;
}
if (largeCanvasSupported) {
gtag('event', 'hi-res-canvas', { 'event_category': 'user', 'event_label': 'supported', 'value': 1 });
} else {
console.log('High resolution canvas images are not supported');
gtag('event', 'hi-res-canvas', { 'event_category': 'user', 'event_label': 'not-supported', 'value': 0 });
}
return largeCanvasSupported;
}
//If google sheets test pixel works, then can assume interactive sheets work and can remove it
function googleSheetsPixelLoaded() {
this.parentElement.removeChild(this);
gtag('event', 'sheets-access', { 'event_category': 'user', 'event_label': 'successful', 'value': 1 });
gtag('event', 'interactive-figures', { 'event_category': 'user', 'event_label': 'enabled', 'value': 1 });
}
//If google sheets test pixel doesn't work, then revert back to static images
function googleSheetsPixelNotLoaded() {
console.error('Google Sheets cannot be loaded');
this.parentElement.removeChild(this);
let all_fig_imgs = document.querySelectorAll('figure .fig-mobile');
for (let index = 0; index < all_fig_imgs.length; ++index) {
let fig_img = all_fig_imgs[index];
fig_img.classList.remove("fig-mobile");
}
let all_fig_iframes = document.querySelectorAll('figure .fig-iframe');
for (let index = 0; index < all_fig_iframes.length; ++index) {
let fig_iframe = all_fig_iframes[index];
fig_iframe.parentElement.removeChild(fig_iframe);
}
gtag('event', 'sheets-access', { 'event_category': 'user', 'event_label': 'blocked', 'value': 0 });
gtag('event', 'interactive-figures', { 'event_category': 'user', 'event_label': 'not-enabled', 'value': 0 });
}
//We use Google Sheets for detailed visualisations
//Check for support and switch out images if supported
function upgradeInteractiveFigures() {
try {
if (!isInPrintMode() && bigEnoughForInteractiveFigures() && !dataSaverEnabled() && highBandwidthConnection() && highResolutionCanvasSupported()) {
//Find each image and create the iframe
let all_fig_imgs = document.querySelectorAll('figure img[data-iframe]');
//If no figures with a data-iframe, then we're done
if (all_fig_imgs.length == 0) {
return;
}
console.log('Upgrading to interactive figures');
for (let index = 0; index < all_fig_imgs.length; ++index) {
let fig_img = all_fig_imgs[index];
if (fig_img.getAttribute('data-iframe')) {
let iframe = document.createElement('iframe');
//Set up some default attributes
iframe.setAttribute('title', fig_img.getAttribute('alt'));
iframe.setAttribute('class', 'fig-iframe');
iframe.setAttribute('tabindex', '-1'); // Google embeds are currently not keyboard interactive so disable tabindex
if (fig_img.getAttribute('aria-labelledby')) {
iframe.setAttribute('aria-labelledby', fig_img.getAttribute('aria-labelledby'));
}
if (fig_img.getAttribute('aria-describedby')) {
iframe.setAttribute('aria-describedby', fig_img.getAttribute('aria-describedby'));
}
iframe.setAttribute('width', fig_img.dataset.width || "600");
iframe.setAttribute('height', fig_img.dataset.height || '371');
iframe.setAttribute('seamless', fig_img.dataset.seamless || '');
iframe.setAttribute('frameborder', fig_img.dataset.frameborder || '0');
iframe.setAttribute('scrolling', fig_img.dataset.scrolling || 'no');
iframe.setAttribute('loading', fig_img.dataset.loading || 'lazy');
iframe.setAttribute('src', fig_img.dataset.iframe);
// Set it to credentialless to avoid issues when it tries to embed the login screen
iframe.setAttribute('credentialless', true);
//The figure should have a link
let parentLink = fig_img.parentNode;
if (parentLink.nodeName == "A") {
//Insert the iframe before the link.
parentLink.parentNode.insertBefore(iframe, parentLink);
//Add the fig-mobile class to hide the img in desktop view
parentLink.classList.add("fig-mobile");
}
}
}
//Add a test image to check we can actually access Google Sheets
//as it's sometimes blocked by corporate proxies and the like
//have a fallback function to revert if this is the case
let google_sheets_pixel = document.createElement('img');
google_sheets_pixel.setAttribute('src', 'https://docs.google.com/favicon.ico');
google_sheets_pixel.setAttribute('height', '1');
google_sheets_pixel.setAttribute('width', '1');
google_sheets_pixel.addEventListener('load', googleSheetsPixelLoaded);
google_sheets_pixel.addEventListener('error', googleSheetsPixelNotLoaded);
window.document.body.appendChild(google_sheets_pixel);
} else {
gtag('event', 'interactive-figures', { 'event_category': 'user', 'event_label': 'not-enabled', 'value': 0 });
}
} catch (err) {
console.error('Error' + err);
gtag('event', 'interactive-figures', { 'event_category': 'user', 'event_label': 'not-enabled', 'value': 0 });
}
}
function setDiscussionCount() {
try {
if (window.discussion_url && window.fetch) {
fetch(window.discussion_url)
.then(function (response) { return response.json(); })
.then(function (response) {
if (!response) {
return;
}
let comments = + response.posts_count - 1;
if (isNaN(comments)) {
return;
}
document.querySelectorAll('.num-comments').forEach(el => {
el.textContent = comments;
});
if (comments === 1) {
document.querySelectorAll('.comment-singular').forEach(el => {
el.removeAttribute('data-translation');
});
} else {
document.querySelectorAll('.comment-plural').forEach(el => {
el.removeAttribute('data-translation');
});
}
document.querySelector('#cta-container').classList.remove('invisible');
document.querySelector('.discuss-cta').classList.remove('hidden');
gtag('event', 'discussion-count', { 'event_category': 'user', 'event_label': 'enabled', 'value': 1 });
})
.catch(function (err) {
console.error(err);
gtag('event', 'discussion-count', { 'event_category': 'user', 'event_label': 'not-enabled', 'value': 0 });
});
}
} catch (err) {
console.error('Error' + err);
gtag('event', 'discussion-count', { 'event_category': 'user', 'event_label': 'not-enabled', 'value': 0 });
}
}
function indexHighlighter() {
// Don't implement this on mobile as won't be used
// Note: do show on tablet in case needed when rotating into landscape
if (window.matchMedia('(max-width: 37.5em)').matches) {
return;
}
//Only activate this if IntersectionObserver is supported
if (!('IntersectionObserver' in window)) {
gtag('event', 'index-highlighter', { 'event_category': 'user', 'event_label': 'not-enabled', 'value': 0 });
return;
}
let chapterIndex = document.querySelector('.index-box');
// If no index - then nothing to do!
if (!chapterIndex) {
return;
}
// Check if user has set reduced motion and only continue if not
let hasOSReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
if (hasOSReducedMotion) {
console.log('User has set prefers-reduced-motion to ' + hasOSReducedMotion + ' so not highlighting the current section in chapter index');
gtag('event', 'prefers-reduced-motion', { 'event_category': 'user', 'event_label': 'reduce', 'value': 0 });
gtag('event', 'index-highlighter', { 'event_category': 'user', 'event_label': 'not-enabled', 'value': 0 });
return;
}
// Check if 'position:sticky' is supported (as this is not great UX when not so don't bother)
// Add the sticky class (which sets 'position:sticky') and then test if that stuck :-)
// Also use endsWith to support vendor prefixes (Safari v12 needs this)
chapterIndex.classList.add('sticky');
let chapterIndexStyles = getComputedStyle(chapterIndex);
if (!chapterIndexStyles || !chapterIndexStyles.position || !chapterIndexStyles.position.endsWith('sticky')) {
gtag('event', 'index-highlighter', { 'event_category': 'user', 'event_label': 'not-enabled', 'value': 0 });
return;
}
// Restrict the page height of the index to the page-height, as we're going to scroll this.
chapterIndex.classList.add('page-height');
// Create a function to handle highlighting a new index item
// that will be called by the IntersectionObserver
function highlightIndexEntry(link) {
let indexLink = document.querySelector('.index-box a[href="#' + link + '"]');
let oldIndexLink = document.querySelector('.index-box .active');
if (!indexLink || indexLink.isEqualNode(oldIndexLink)) {
return;
}
if (oldIndexLink) {
oldIndexLink.classList.remove('active');
}
indexLink.parentNode.classList.add('active');
// If the index is displayed in full then we're done!
if (chapterIndex.scrollHeight <= chapterIndex.clientHeight) {
return;
}
// Otherwise if too large to display in full then scroll to this element
// We'd love to use scrollIntoView but unfortunately won't work if user
// is still scrolling in main doc, so do it the old fashioned way
let currentPosition = indexLink.offsetTop;
let currentNode = indexLink;
// Walk the node back up to the index-scroller to get the total offset
// of this entry, relative to the full Index
while (currentNode && currentNode.parentNode != chapterIndex) {
currentPosition = currentPosition + currentNode.offsetTop;
currentNode = currentNode.parentNode;
}
// Show the current image in the middle of the screen
chapterIndex.scrollTop = currentPosition - (chapterIndex.clientHeight / 2);
}
// Set up a new Interstection Observer for when the title is 80% from the bottom of the page
let options = {
root: null,
rootMargin: "0px 0px -80% 0px",
threshold: null
};
let observer = new IntersectionObserver(function (entries) {
for (let index = 0; index < entries.length; ++index) {
let entry = entries[index];
if (entry.isIntersecting && entry.target && entry.target.id) {
highlightIndexEntry(entry.target.id);
}
}
}, options);
// Add an intersection observer to each heading
let all_headings = document.querySelectorAll('article h1, article h2, article h3, article h4, article h5, article h6');
for (let index = 0; index < all_headings.length; ++index) {
let heading = all_headings[index];
observer.observe(heading);
}
gtag('event', 'index-highlighter', { 'event_category': 'user', 'event_label': 'enabled', 'value': 0 });
}
function toggleDescription(event) {
let event_button = event.target;
if (!event_button) {
return;
}
let description_id = event_button.getAttribute('aria-controls');
if (!description_id) {
return;
}
let description = document.querySelector('#' + description_id);
if (!description) {
return;
}
description.hidden = !description.hidden;
event_button.setAttribute('aria-expanded', event_button.getAttribute('aria-expanded') == 'true' ? 'false' : 'true');
event_button.textContent = event_button.getAttribute('aria-expanded') == 'true' ? event_button.getAttribute('data-hide-text') : event_button.getAttribute('data-show-text');
}
function addShowDescription() {
let all_desc_buttons = document.querySelectorAll('.fig-description-button');
for (let index = 0; index < all_desc_buttons.length; ++index) {
let desc_button = all_desc_buttons[index];
desc_button.addEventListener('click', toggleDescription);
desc_button.classList.remove('novisibility-until-js');
let description = document.querySelector('#' + desc_button.getAttribute('aria-controls'));
if (description) {
description.classList.remove('hidden');
description.classList.add('fig-description');
description.hidden = true;
}
}
}
function addKeyboardScollableRegions() {
// If a table or code block is overflowing then should allow keyboard focus
// More details - https://adrianroselli.com/2020/11/under-engineered-responsive-tables.html
// Handle tables that have overflowed
let all_table_containers = document.querySelectorAll('.table-wrap-container');
for (let index = 0; index < all_table_containers.length; ++index) {
let table_container = all_table_containers[index];
if (table_container.scrollWidth > table_container.clientWidth) {
let figure = table_container.parentElement.parentElement;
if (figure && figure.nodeName == "FIGURE") {
let figid = figure.id;
let figcaption = figure.querySelector('figcaption');
if (figid && figcaption) {
figcaption.setAttribute('id', figid + '-caption');
table_container.setAttribute('tabindex', '0');
table_container.setAttribute('role', 'region');
table_container.setAttribute('aria-labelledby', figid + '-caption');
}
}
}
}
// Handle code blocks that have overflowed
let all_pre_elements = document.querySelectorAll('pre');
for (let index = 0; index < all_pre_elements.length; ++index) {
let pre_element = all_pre_elements[index];
if (pre_element.scrollWidth > pre_element.clientWidth) {
pre_element.setAttribute('tabindex', '0');
pre_element.setAttribute('role', 'region');
pre_element.setAttribute('aria-label', `Code ${index}`);
}
}
}
function addShortKeyEventListers() {
document.addEventListener("keyup", function onPress(event) {
// Prevent the search box and other inputs from processing these listeners.
if (event.target.nodeName == 'INPUT' || event.target.nodeName == 'TEXTAREA' || event.target.nodeName == 'SELECT') {
return;
}
if (event.key === 'p' || event.key === 'P' || event.key === ',' || event.key === '<') {
let previous = document.getElementById('previous-chapter');
if (previous) {
previous.click();
}
}
if (event.key === 'n' || event.key === 'N' || event.key === '.' || event.key === '>') {
let next = document.getElementById('next-chapter');
if (next) {
next.click();
}
}
if (event.key === 'd' || event.key === 'D') {
document.querySelectorAll('.fig-description-button').forEach(descButton => {
descButton.click();
});
}
});
}
function indexMenu() {
let indexBox = document.querySelector('.index-box');
let indexBoxTitle = document.querySelector('.index .index-btn');
if (!indexBox || !indexBoxTitle) {
return;
}
indexBoxTitle.addEventListener('click', function () {
let indexOpen = indexBox.classList.toggle('show');
indexBoxTitle.setAttribute('aria-expanded', indexOpen);
let ariaLabel = indexOpen ? indexBoxTitle.getAttribute('data-close-text') : indexBoxTitle.getAttribute('data-open-text');
indexBoxTitle.setAttribute('aria-label', ariaLabel);
});
indexBox.addEventListener("keydown", function onPress(event) {
if (event.key === 'Escape') {
if (indexBoxTitle.getAttribute('aria-expanded') === 'true') {
indexBoxTitle.click();
indexBoxTitle.focus();
}
}
});
}
handleSelectSwitchers();
handleMobileMenu();
handleNavMenu();
handleDataEvents();
activateJavaScriptElements();
indexMenu();
indexHighlighter();
addShowDescription();
removeLazyLoadingOnPrint();
upgradeInteractiveFigures();
addKeyboardScollableRegions();
setDiscussionCount();
addShortKeyEventListers();