-
-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathapp.js
7584 lines (7331 loc) · 408 KB
/
app.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
/*!
* app.js : The main Kiwix User Interface implementation
* This file handles the interaction between the Kiwix JS back end and the user
*
* Copyright 2013-2024 Jaifroid, Mossroy and contributors
* Licence GPL v3:
*
* This file is part of Kiwix.
*
* Kiwix is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public Licence as published by
* the Free Software Foundation, either version 3 of the Licence, or
* (at your option) any later version.
*
* Kiwix is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public Licence for more details.
*
* You should have received a copy of the GNU General Public Licence
* along with Kiwix (file LICENSE-GPLv3.txt). If not, see <http://www.gnu.org/licenses/>
*/
'use strict';
/* eslint-disable indent, eqeqeq */
// import styles from '../css/app.css' assert { type: "css" };
// import bootstrap from '../css/bootstrap.min.css' assert { type: "css" };
import zimArchiveLoader from './lib/zimArchiveLoader.js';
import uiUtil from './lib/uiUtil.js';
import popovers from './lib/popovers.js';
import util from './lib/util.js';
import utf8 from './lib/utf8.js';
import cache from './lib/cache.js';
import images from './lib/images.js';
import settingsStore from './lib/settingsStore.js';
import transformStyles from './lib/transformStyles.js';
import transformZimit from './lib/transformZimit.js';
import kiwixServe from './lib/kiwixServe.js';
import updater from './lib/updater.js';
import resetApp from './lib/resetApp.js';
// Import stylesheets programmatically
// document.adoptedStyleSheets = [styles, bootstrap];
/**
* Define global state variables:
*/
// The global parameter and app state objects are defined in init.js
/* global params, appstate, assetsCache, nw, electronAPI, Windows, webpMachine, dialog, LaunchParams, launchQueue, abstractFilesystemAccess, MSApp */
// Placeholders for the article container, the article window, the article DOM and some UI elements
var articleContainer = document.getElementById('articleContent');
articleContainer.kiwixType = 'iframe';
var articleWindow = articleContainer.contentWindow;
var articleDocument;
var scrollbox = document.getElementById('scrollbox');
var prefix = document.getElementById('prefix');
// The following variables are used to store the current article and its state
var messageChannelWaiting = false;
var transformedHTML = '';
var transDirEntry = null;
/**
* @type ZIMArchive
*/
appstate.selectedArchive = null;
// An object to hold the current search and its state (allows cancellation of search across modules)
appstate['search'] = {
prefix: '', // A field to hold the original search string
status: '', // The status of the search: ''|'init'|'interim'|'cancelled'|'complete'
type: '' // The type of the search: 'basic'|'full' (set automatically in search algorithm)
};
// A parameter to determine the Settings Store API in use (we need to nullify before testing
// because params.storeType is also set in a preliminary way in init.js)
params['storeType'] = null;
params['storeType'] = settingsStore.getBestAvailableStorageAPI();
// A parameter to determine whether the webkitdirectory API is available
params['webkitdirectory'] = util.webkitdirectorySupported();
// Retrieve UWP launch arguments when the app is started by double-clicking on a file
if (typeof Windows !== 'undefined' && Windows.UI && Windows.UI.WebUI && Windows.UI.WebUI.WebUIApplication) {
Windows.UI.WebUI.WebUIApplication.addEventListener('activated', function (eventArgs) {
if (eventArgs.kind === Windows.ApplicationModel.Activation.ActivationKind.file) {
params.storedFile = eventArgs.files[0].name || '';
if (params.storedFile) {
params.pickedFile = eventArgs.files[0];
params.storedFilePath = eventArgs.files[0].path;
console.log('App was activated with a file: ' + params.storedFile);
processPickedFileUWP(params.pickedFile);
}
}
}, false);
}
// At launch, we set the correct content injection mode
if (params.contentInjectionMode === 'serviceworker' && window.nw) {
// Failsafe for Windows XP version: reset app to Restricted mode because it cannot run in SW mode in Windows XP
if (nw.process.versions.nw === '0.14.7') setContentInjectionMode('jquery');
} else {
setContentInjectionMode(params.contentInjectionMode);
}
// Test caching capability
cache.test(function () {});
// Unique identifier of the article expected to be displayed
appstate.expectedArticleURLToBeDisplayed = '';
// Check if we have managed to switch to PWA mode (if running UWP app)
// DEV: we do this in init.js, but sometimes it doesn't seem to register, so we do it again once the app has fully launched
if (/UWP\|PWA/.test(params.appType) && /^http/i.test(window.location.protocol)) {
// We are in a PWA, so signal success
params.localUWPSettings.PWA_launch = 'success';
}
// Make Configuration headings collapsible
uiUtil.setupConfigurationToggles();
/**
* Resize the IFrame height, so that it fills the whole available height in the window
* @param {Boolean} reload Allows reload of the app on resize
*/
function resizeIFrame (reload) {
// console.debug('Resizing iframe...');
// Re-enable top-level scrolling
var configuration = document.getElementById('configuration');
var about = document.getElementById('about');
if (configuration.style.display === 'none' && about.style.display === 'none' && prefix !== document.activeElement) {
scrollbox.style.height = 0;
} else {
scrollbox.style.height = window.innerHeight - document.getElementById('top').getBoundingClientRect().height + 'px';
}
uiUtil.showSlidingUIElements();
var ToCList = document.getElementById('ToCList');
if (typeof ToCList !== 'undefined') {
ToCList.style.maxHeight = ~~(window.innerHeight * 0.75) + 'px';
ToCList.style.marginLeft = ~~(window.innerWidth / 2) - ~~(window.innerWidth * 0.16) + 'px';
}
if (window.outerWidth <= 470) {
document.getElementById('dropup').classList.remove('col-xs-4');
document.getElementById('dropup').classList.add('col-xs-3');
if (window.outerWidth <= 360) {
document.getElementById('btnTop').classList.remove('col-xs-2');
document.getElementById('btnTop').classList.add('col-xs-1');
} else {
document.getElementById('btnTop').classList.remove('col-xs-1');
document.getElementById('btnTop').classList.add('col-xs-2');
}
} else {
document.getElementById('dropup').classList.remove('col-xs-3');
document.getElementById('dropup').classList.add('col-xs-4');
}
if (settingsStore.getItem('reloadDispatched') === 'true') {
setTimeout(function () {
settingsStore.removeItem('reloadDispatched');
}, 1000);
} else if (reload && params.resetDisplayOnResize) {
settingsStore.setItem('reloadDispatched', true, Infinity);
window.location.reload();
console.log('So long, and thanks for all the fish!');
return;
}
removePageMaxWidth();
checkToolbar();
}
window.onresize = function () {
resizeIFrame(true);
// Check whether fullscreen icon needs to be updated
setDynamicIcons();
// We need to load any images exposed by the resize
var scrollFunc = document.getElementById('articleContent').contentWindow;
scrollFunc = scrollFunc ? scrollFunc.onscroll : null;
if (scrollFunc) scrollFunc();
};
// Define behavior of HTML elements
if (params.navButtonsPos === 'top') {
// User has requested navigation buttons should be at top, so we need to swap them
var btnBack = document.getElementById('btnBack');
var btnBackAlt = document.getElementById('btnBackAlt');
btnBack.id = 'btnBackAlt';
btnBackAlt.id = 'btnBack';
btnBackAlt.style.display = 'inline';
btnBack.style.display = 'none';
var btnForward = document.getElementById('btnForward');
var btnForwardAlt = document.getElementById('btnForwardAlt');
btnForward.id = 'btnForwardAlt';
btnForwardAlt.id = 'btnForward';
btnForwardAlt.style.display = 'inline';
btnForward.style.display = 'none';
var btnRandom = document.getElementById('btnRandomArticle');
var btnRandomAlt = document.getElementById('btnRandomArticleAlt');
btnRandom.id = 'btnRandomArticleAlt';
btnRandomAlt.id = 'btnRandomArticle';
btnRandom.style.display = 'none';
btnRandomAlt.style.display = 'inline';
var btnToggleTheme = document.getElementById('btnToggleTheme');
var btnToggleThemeAlt = document.getElementById('btnToggleThemeAlt');
btnToggleTheme.id = 'btnToggleThemeAlt';
btnToggleThemeAlt.id = 'btnToggleTheme';
btnToggleTheme.style.display = 'none';
btnToggleThemeAlt.style.display = 'inline';
}
// Process pointerup events (used for checking if mouse back / forward buttons have been clicked)
function onPointerUp (e) {
if (typeof e === 'object') {
if (e.button === 3) {
document.getElementById('btnBack').click();
}
if (e.button === 4) {
document.getElementById('btnForward').click();
}
}
}
if (/UWP/.test(params.appType)) document.body.addEventListener('pointerup', onPointerUp);
var searchArticlesFocused = false;
document.getElementById('searchArticles').addEventListener('click', function () {
var val = prefix.value;
// Do not initiate the same search if it is already in progress
if (appstate.search.prefix === val && !/^(cancelled|complete)$/.test(appstate.search.status)) return;
document.getElementById('welcomeText').style.display = 'none';
document.querySelectorAll('.alert').forEach(function (el) {
el.style.display = 'none';
});
uiUtil.pollSpinner();
pushBrowserHistoryState(null, val);
// Initiate the search
searchDirEntriesFromPrefix(val);
clearFindInArticle();
// Re-enable top-level scrolling
var headerHeight = document.getElementById('top').getBoundingClientRect().height;
var footerHeight = document.getElementById('footer').getBoundingClientRect().height;
scrollbox.style.height = window.innerHeight - headerHeight - footerHeight + 'px';
// This flag is set to true in the mousedown event below
searchArticlesFocused = false;
});
document.getElementById('formArticleSearch').addEventListener('submit', function () {
document.getElementById('searchArticles').click();
});
// Handle keyboard events in the prefix (article search) field
var keyPressHandled = false;
prefix.addEventListener('keydown', function (e) {
// If user presses Escape...
// IE11 returns "Esc" and the other browsers "Escape"; regex below matches both
if (/^Esc/.test(e.key)) {
// Hide the article list
e.preventDefault();
e.stopPropagation();
document.getElementById('articleListWithHeader').style.display = 'none';
document.getElementById('articleContent').focus();
document.getElementById('mycloseMessage').click(); // This is in case the modal box is showing with an index search
keyPressHandled = true;
}
// Arrow-key selection code adapted from https://stackoverflow.com/a/14747926/9727685
// IE11 produces "Down" instead of "ArrowDown" and "Up" instead of "ArrowUp"
if (/^((Arrow)?Down|(Arrow)?Up|Enter)$/.test(e.key)) {
// User pressed Down arrow or Up arrow or Enter
e.preventDefault();
e.stopPropagation();
// This is needed to prevent processing in the keyup event : https://stackoverflow.com/questions/9951274
keyPressHandled = true;
var activeElement = document.querySelector('#articleList .hover') || document.querySelector('#articleList a');
if (!activeElement) return;
// If user presses Enter, read the dirEntry
if (/Enter/.test(e.key)) {
if (activeElement.classList.contains('hover')) {
var dirEntryId = activeElement.getAttribute('dirEntryId');
findDirEntryFromDirEntryIdAndLaunchArticleRead(decodeURIComponent(dirEntryId));
return;
}
}
// If user presses ArrowDown...
// (NB selection is limited to five possibilities by regex above)
if (/Down/.test(e.key)) {
if (activeElement.classList.contains('hover')) {
activeElement.classList.remove('hover');
activeElement = activeElement.nextElementSibling || activeElement;
var nextElement = activeElement.nextElementSibling || activeElement;
if (!uiUtil.isElementInView(window, nextElement, true)) nextElement.scrollIntoView(false);
}
}
// If user presses ArrowUp...
if (/Up/.test(e.key)) {
activeElement.classList.remove('hover');
activeElement = activeElement.previousElementSibling || activeElement;
var previousElement = activeElement.previousElementSibling || activeElement;
if (!uiUtil.isElementInView(window, previousElement, true)) previousElement.scrollIntoView();
if (previousElement === activeElement) {
document.getElementById('articleListWithHeader').scrollIntoView();
document.getElementById('top').scrollIntoView();
}
}
activeElement.classList.add('hover');
}
});
// Search for titles as user types characters
prefix.addEventListener('keyup', function (e) {
if (appstate.selectedArchive !== null && appstate.selectedArchive.isReady()) {
// Prevent processing by keyup event if we already handled the keypress in keydown event
if (keyPressHandled) {
keyPressHandled = false;
} else {
onKeyUpPrefix(e);
}
}
});
// Restore the search results if user goes back into prefix field
prefix.addEventListener('focus', function () {
var val = prefix.value;
if (/^\s/.test(val)) {
// If user had previously had the archive index open, clear it
prefix.value = '';
} else if (val !== '') {
document.getElementById('articleListWithHeader').style.display = '';
}
scrollbox.style.position = 'absolute';
var headerHeight = document.getElementById('top').getBoundingClientRect().height;
var footerHeight = document.getElementById('footer').getBoundingClientRect().height;
scrollbox.style.height = window.innerHeight - headerHeight - footerHeight + 'px';
});
// Hide the search results if user moves out of prefix field
prefix.addEventListener('blur', function () {
if (!searchArticlesFocused) {
appstate.search.status = 'cancelled';
}
// We need to wait one tick for the activeElement to receive focus
setTimeout(function () {
if (!(/^articleList|searchSyntaxLink/.test(document.activeElement.id) ||
/^list-group/.test(document.activeElement.className))) {
scrollbox.style.height = 0;
document.getElementById('articleListWithHeader').style.display = 'none';
appstate.tempPrefix = '';
uiUtil.clearSpinner();
}
}, 1);
});
// Add keyboard shortcuts
window.addEventListener('keyup', function (e) {
// Alt-F for search in article, also patches Ctrl-F for apps that do not have access to browser search
if ((e.ctrlKey || e.altKey) && e.key === 'F') {
document.getElementById('findText').click();
}
});
window.addEventListener('keydown', function (e) {
// Ctrl-P to patch printing support, so iframe gets printed
if (e.ctrlKey && e.key === 'P') {
e.stopPropagation();
e.preventDefault();
printIntercept();
}
}, true);
// Set up listeners for print dialogues
function printArticle (doc) {
uiUtil.printCustomElements(doc);
uiUtil.systemAlert('<b>Document will now reload to restore the DOM after printing...</b>').then(function () {
printCleanup();
});
// innerDocument.execCommand("print", false, null);
// if (typeof window.nw !== 'undefined' || typeof window.fs === 'undefined') {
doc.defaultView.print();
// } else {
// // We are in an Electron app and need to use export to browser to print
// params.preloadingAllImages = false;
// // Add a window.print() script to the html
// document.getElementById('articleContent').contentDocument.head.innerHTML +=
// '\n<script type="text/javascript">window.onload=function() {\n' +
// ' alert("After you press OK, you will be asked to choose a printer.\\n" +\n' +
// ' "If you want to test the formatting, we suggest you print to\\n" +\n' +
// ' "PDF or XPS. You could then open the PDF and select specific pages.");\n' +
// ' window.print();\n' +
// '};<\/script>';
// //html = html.replace(/(<\/head>\s*)/i, '<script type="text/javascript">window.onload=window.print();<\/script>\n$1');
// uiUtil.extractHTML();
// }
};
document.getElementById('printDesktopCheck').addEventListener('click', function (e) {
// Reload article if user wants to print a different style
params.cssSource = e.target.checked ? 'desktop' : 'mobile';
params.printIntercept = true;
params.printInterception = false;
var btnContinue = document.getElementById('printapproveConfirm');
var btnCancel = document.getElementById('printdeclineConfirm');
btnCancel.disabled = true;
btnContinue.disabled = true;
btnContinue.innerHTML = 'Please wait';
goToArticle(params.lastPageVisit.replace(/@kiwixKey@.+/, ''));
});
document.getElementById('printImageCheck').addEventListener('click', function (e) {
// Reload article if user wants to print images
if (e.target.checked && !params.allowHTMLExtraction) {
params.printIntercept = true;
params.printInterception = false;
params.allowHTMLExtraction = true;
var btnContinue = document.getElementById('printapproveConfirm');
var btnCancel = document.getElementById('printdeclineConfirm');
btnCancel.disabled = true;
btnContinue.disabled = true;
btnContinue.innerHTML = 'Please wait';
goToArticle(params.lastPageVisit.replace(/@kiwixKey@.+/, ''));
}
});
function printCleanup () {
if (!params.printInterception) {
// We don't need a radical cleanup because there was no printIntercept
removePageMaxWidth();
setTab();
setArticleZoom(params.relativeFontSize);
params.cssTheme = settingsStore.getItem('cssTheme') || 'light';
if (document.getElementById('cssWikiDarkThemeDarkReaderCheck').checked) {
// It seems darkReader has been auto-turned on, so we need to respect that
params.cssTheme = 'darkReader';
}
switchCSSTheme();
return;
}
params.printIntercept = false;
params.printInterception = false;
// Immediately restore temporarily changed values
params.allowHTMLExtraction = settingsStore.getItem('allowHTMLExtraction') === 'true';
goToArticle(params.lastPageVisit.replace(/@kiwixKey@.+/, ''));
setTimeout(function () { // Restore temporarily changed value after page has reloaded
params.rememberLastPage = settingsStore.getItem('rememberLastPage') === 'true';
if (!params.rememberLastPage) {
settingsStore.setItem('lastPageVisit', '', Infinity);
params.lastPageHTML = '';
// DEV: replace this with cache.clear when you have repaired that method
cache.setArticle(params.lastPageVisit.replace(/.+@kiwixKey@/, ''), params.lastPageVisit.replace(/@kiwixKey@.+/, ''), '', function () {});
}
}, 5000);
}
// End of listeners for print dialogues
function printIntercept () {
params.printInterception = params.printIntercept;
params.printIntercept = false;
document.getElementById('btnAbout').classList.add('active');
var btnContinue = document.getElementById('printapproveConfirm');
var btnCancel = document.getElementById('printdeclineConfirm');
btnCancel.disabled = false;
btnContinue.disabled = false;
btnContinue.innerHTML = 'Continue';
var printModalContent = document.getElementById('print-modal-content');
openAllSections(true);
printModalContent.classList.remove('dark');
var determinedTheme = params.cssUITheme;
determinedTheme = determinedTheme === 'auto' ? cssUIThemeGetOrSet('auto', true) : determinedTheme;
if (determinedTheme !== 'light') {
printModalContent.classList.add('dark');
}
// If document is in wrong style, or images are one-time BLOBs, reload it
// var innerDoc = window.frames[0].frameElement.contentDocument;
var innerDoc = document.getElementById('articleContent').contentDocument;
if (appstate.isReplayWorkerAvailable) {
innerDoc = innerDoc ? innerDoc.getElementById('replay_iframe').contentDocument : null;
}
if (!innerDoc) {
return uiUtil.systemAlert('Sorry, we could not find a document to print! Please load one first.', 'Warning');
}
if (params.contentInjectionMode === 'serviceworker') {
// Re-establish lastPageVisit because it is not always set, for example with dynamic loads, in SW mode
params.lastPageVisit = articleDocument.location.href.replace(/^.+\/([^/]+\.[zZ][iI][mM]\w?\w?)\/([CA]\/.*$)/, function (m0, zimName, zimURL) {
return decodeURI(zimURL) + '@kiwixKey@' + decodeURI(zimName);
});
}
var printDesktopCheck = document.getElementById('printDesktopCheck').checked;
var printImageCheck = document.getElementById('printImageCheck').checked;
var styleIsDesktop = !/href\s*=\s*["'][^"']*?(?:minerva|mobile)/i.test(innerDoc.head.innerHTML);
// if (styleIsDesktop != printDesktopCheck || printImageCheck && !params.allowHTMLExtraction || params.contentInjectionMode == 'serviceworker') {
if (appstate.wikimediaZimLoaded && (styleIsDesktop !== printDesktopCheck || (printImageCheck && !params.allowHTMLExtraction))) {
// We need to reload the document because it doesn't match the requested style or images are one-time BLOBs
params.cssSource = printDesktopCheck ? 'desktop' : 'mobile';
params.rememberLastPage = true; // Re-enable caching to speed up reloading of page
// params.contentInjectionMode = 'jquery'; //Much easier to count images in Restricted mode
params.allowHTMLExtraction = true;
params.printIntercept = true;
params.printInterception = false;
btnCancel.disabled = true;
btnContinue.disabled = true;
btnContinue.innerHTML = 'Please wait';
// Show the modal so the user knows that printing is being prepared
document.getElementById('printModal').style.display = 'block';
goToArticle(params.lastPageVisit.replace(/@kiwixKey@.+/, ''));
return;
}
// Pre-load all images in case user wants to print them
if (params.imageDisplay) {
document.getElementById('printImageCheck').disabled = false;
if (printImageCheck) {
btnCancel.disabled = true;
btnContinue.disabled = true;
btnContinue.innerHTML = 'Loading images...';
// Callback for when all images are loaded
params.printImagesLoaded = function () {
// Images have finished loading, so enable buttons
btnCancel.disabled = false;
btnContinue.disabled = false;
btnContinue.innerHTML = 'Continue';
};
if (params.contentInjectionMode === 'jquery') {
images.prepareImagesJQuery(articleWindow, true);
} else {
images.prepareImagesServiceWorker(articleWindow, true);
}
}
} else {
document.getElementById('printImageCheck').checked = false;
document.getElementById('printImageCheck').disabled = true;
}
// Remove max page-width restriction
if (params.removePageMaxWidth !== true) {
var tempPageMaxWidth = params.removePageMaxWidth;
params.removePageMaxWidth = true;
removePageMaxWidth();
params.removePageMaxWidth = tempPageMaxWidth;
}
// Reset zoom level to 100%
setArticleZoom(100);
// Put doc into light mode
params.cssTheme = 'light';
switchCSSTheme();
uiUtil.systemAlert(' ', '', true, null, 'Continue', null, 'printModal').then(function (result) {
// Restore temporarily changed values
params.cssSource = settingsStore.getItem('cssSource') || 'auto';
params.cssTheme = settingsStore.getItem('cssTheme') || 'light';
if (result) printArticle(innerDoc);
else printCleanup();
});
}
// Establish some variables with global scope
var localSearch = {};
function clearFindInArticle () {
if (document.getElementById('row2').style.display === 'none') return;
if (typeof localSearch !== 'undefined' && localSearch.remove) {
localSearch.remove();
}
document.getElementById('findInArticle').value = '';
document.getElementById('matches').innerHTML = 'Full: 0';
document.getElementById('partial').innerHTML = 'Partial: 0';
document.getElementById('row2').style.display = 'none';
document.getElementById('findText').classList.remove('active');
}
document.getElementById('findText').addEventListener('click', function () {
var searchDiv = document.getElementById('row2');
if (searchDiv.style.display !== 'none') {
setTab();
// Return sections to original state
openAllSections();
// Return params.hideToolbars to its original state
checkToolbar();
return;
}
var findInArticle = null;
var innerDocument = document.getElementById('articleContent').contentDocument;
if (appstate.isReplayWorkerAvailable) {
innerDocument = innerDocument ? innerDocument.getElementById('replay_iframe').contentDocument : null;
}
innerDocument = innerDocument ? innerDocument.body : null;
if (!innerDocument || innerDocument.innerHTML.length < 10) return;
setTab('findText');
findInArticle = document.getElementById('findInArticle');
searchDiv.style.display = 'block';
// Show the toolbar
params.hideToolbars = false;
checkToolbar();
findInArticle.focus();
// We need to open all sections to search
openAllSections(true);
localSearch = new util.Hilitor(innerDocument);
// TODO: MatchType should be language specific
findInArticle.addEventListener('keyup', function (e) {
// If user pressed Alt-F or Ctrl-F, exit
if ((e.altKey || e.ctrlKey) && e.key === 'F') return;
var val = this.value;
// If user pressed enter / return key
if (val && (e.key === 'Enter' || e.keyCode === 13)) {
localSearch.scrollFrom = localSearch.scrollToFullMatch(val, localSearch.scrollFrom);
return;
}
// If value hasn't changed, exit
if (val === localSearch.lastScrollValue) return;
findInArticleKeyup(val);
});
var findInArticleKeyup = function (val) {
// Use a timeout, so that very quick typing does not cause a lot of overhead
if (window.timeoutFIAKeyup) {
window.clearTimeout(window.timeoutFIAKeyup);
}
window.timeoutFIAKeyup = window.setTimeout(function () {
findInArticleInitiate(val);
}, 500);
};
var findInArticleInitiate = function (val) {
// Ensure nothing happens if only one or two ASCII values have been entered (search is not specific enough)
// if no value has been entered (clears highlighting if user deletes all values in search field)
if (!/^\s*[A-Za-z\s]{1,2}$/.test(val)) {
localSearch.scrollFrom = 0;
localSearch.lastScrollValue = val;
localSearch.setMatchType('open');
// Change matchType to 'left' if we are dealing with an ASCII language and a space has been typed
if (/\s/.test(val) && /(?:^|[\s\b])[A-Za-z]+(?:[\b\s]|$)/.test(val)) localSearch.setMatchType('left');
localSearch.apply(val);
if (val.length) {
var fullTotal = localSearch.countFullMatches(val);
var partialTotal = localSearch.countPartialMatches();
fullTotal = fullTotal > partialTotal ? partialTotal : fullTotal;
document.getElementById('matches').innerHTML = '<a id="scrollLink" href="#">Full: ' + fullTotal + '</a>';
document.getElementById('partial').innerHTML = 'Partial: ' + partialTotal;
document.getElementById('scrollLink').addEventListener('click', function () {
localSearch.scrollFrom = localSearch.scrollToFullMatch(val, localSearch.scrollFrom);
});
// Auto-scroll: TODO - consider making this an option
localSearch.scrollFrom = localSearch.scrollToFullMatch(val, localSearch.scrollFrom);
} else {
document.getElementById('matches').innerHTML = 'Full: 0';
document.getElementById('partial').innerHTML = 'Partial: 0';
}
}
};
});
document.getElementById('btnRandomArticle').addEventListener('click', function () {
// In Restricted mode, only load random content in iframe (not tab or window)
appstate.target = 'iframe';
setTab('btnRandomArticle');
// Re-enable top-level scrolling
goToRandomArticle();
});
document.getElementById('btnToggleTheme').addEventListener('click', function () {
var determinedTheme = cssUIThemeGetOrSet(params.cssUITheme, true);
var desiredTheme = determinedTheme === 'light' ? 'dark' : 'light';
var themeToggle = document.getElementById('cssUIDarkThemeCheck');
// This is a tri-state switch, so we may need to click up to three times
themeToggle.click();
determinedTheme = cssUIThemeGetOrSet(params.cssUITheme, true);
if (determinedTheme !== desiredTheme) {
themeToggle.click();
}
determinedTheme = cssUIThemeGetOrSet(params.cssUITheme, true);
if (determinedTheme !== desiredTheme) {
themeToggle.click();
}
});
document.getElementById('btnRescanDeviceStorage').addEventListener('click', function () {
var returnDivs = document.getElementsByClassName('returntoArticle');
for (var i = 0; i < returnDivs.length; i++) {
returnDivs[i].innerHTML = '';
}
params.rescan = true;
// Deprecated: Reload any ZIM files in local storage (which the usar can't otherwise select with the filepicker)
// loadPackagedArchive();
if (storages.length) {
searchForArchivesInStorage();
} else {
displayFileSelect();
}
// Check if we are in an Android app, and if so, auto-select use of OPFS if there is no set value in settingsStore for useOPFS
if ((/Android/.test(params.appType) || /Firefox/.test(navigator.userAgent)) && !params.useOPFS && !settingsStore.getItem('useOPFS')) {
// This will only run first time app is run on Android
setTimeout(function () {
uiUtil.systemAlert('<p>We are switching to the Private File System (OPFS).</p>' +
'<p><b><i>If asked, please accept a one-time Storage permission prompt.</i></b></p>' +
'<i>More info</i>: the OPFS provides significant benefits such as: <b>faster file system access</b>; ' +
'<b>no permission prompts</b>; <b>automatic reload of archive on app start</b>.</p>',
'Switching to OPFS', true, 'Use classic file picker')
.then(function (response) {
if (response) {
document.getElementById('useOPFSCheck').click();
} else {
settingsStore.setItem('useOPFS', false, Infinity);
}
});
}, 2000);
} else if (!settingsStore.getItem('useOPFS')) {
// This esnures that there is an explicit setting for useOPFS, which in turn allows us to tell if the
// app is running for the first time (so we don't keep prompting the user to use the OPFS)
settingsStore.setItem('useOPFS', false, Infinity);
}
});
// Bottom bar :
// @TODO Since bottom bar now hidden in Settings and About the returntoArticle code cannot be accessed;
// consider adding it to top home button instead
document.getElementById('btnBack').addEventListener('click', function () {
if (document.getElementById('articleContent').style.display === 'none') {
document.getElementById('returntoArticle').click();
return;
}
clearFindInArticle();
history.back();
});
document.getElementById('btnForward').addEventListener('click', function () {
clearFindInArticle();
history.forward();
});
document.getElementById('btnZoomin').addEventListener('click', function () {
params.relativeFontSize = Math.min(200, params.relativeFontSize + 5);
setArticleZoom(params.relativeFontSize, true);
});
document.getElementById('btnZoomout').addEventListener('click', function () {
params.relativeFontSize = Math.max(50, params.relativeFontSize - 5);
setArticleZoom(params.relativeFontSize, true);
});
let zoomLabelTimeout;
function setArticleZoom (zoomLevel, set) {
const root = articleDocument.documentElement || articleDocument;
const percentageFontSize = zoomLevel + '%';
// Set CSS fontSize and zoom if supported
// Note that the zoom property is supported in Firefox since May 2024, but it doesn't
// scale the font size at least in Wikipedia pages, so we need to set fontSize as well
root.style.fontSize = percentageFontSize;
if ('zoom' in root.style) {
root.style.zoom = percentageFontSize;
}
// If we are setting a value from the UI, update the display and settings
if (set) {
// Update zoom label
const lblZoom = document.getElementById('lblZoom');
lblZoom.innerHTML = percentageFontSize;
lblZoom.style.cssText = 'position:absolute;right:' + window.innerWidth / 4 + 'px;bottom:50px;z-index:50;';
// Clear and set timeout to hide zoom label
if (zoomLabelTimeout) clearTimeout(zoomLabelTimeout);
zoomLabelTimeout = setTimeout(function () {
lblZoom.innerHTML = '';
}, 2500);
settingsStore.setItem('relativeFontSize', zoomLevel, Infinity);
document.getElementById('articleContent').contentWindow.focus();
}
}
setRelativeUIFontSize(params.relativeUIFontSize);
document.getElementById('relativeUIFontSizeSlider').addEventListener('change', function () {
setRelativeUIFontSize(this.value);
});
function setRelativeUIFontSize (value) {
value = ~~value;
document.getElementById('spinnerVal').innerHTML = value + '%';
document.getElementById('search-article').style.fontSize = value + '%';
document.getElementById('relativeUIFontSizeSlider').value = value;
var forms = document.querySelectorAll('.form-control');
var i;
for (i = 0; i < forms.length; i++) {
forms[i].style.fontSize = ~~(value * 14 / 100) + 'px';
}
var buttons = document.getElementsByClassName('btn');
for (i = 0; i < buttons.length; i++) {
// Some specific buttons need to be smaller
buttons[i].style.fontSize = /Archive|RefreshApp|Reset2/.test(buttons[i].id) ? ~~(value * 10 / 100) + 'px' : ~~(value * 14 / 100) + 'px';
}
var heads = document.querySelectorAll('h1, h2, h3, h4');
for (i = 0; i < heads.length; i++) {
var multiplier = 1;
var head = heads[i].tagName;
multiplier = head === 'H4' ? 1.4 : head === 'H3' ? 1.9 : head === 'H2' ? 2.3 : head === 'H1' ? 2.8 : multiplier;
heads[i].style.fontSize = ~~(value * 0.14 * multiplier) + 'px';
}
document.getElementById('displaySettingsDiv').scrollIntoView();
// prefix.style.height = ~~(value * 14 / 100) * 1.4285 + 14 + "px";
if (value !== params.relativeUIFontSize) {
params.relativeUIFontSize = value;
settingsStore.setItem('relativeUIFontSize', value, Infinity);
}
}
document.getElementById('btnHomeBottom').addEventListener('click', function () {
document.getElementById('btnHome').click();
});
// Deal with the Windows Mobile / Tablet back button
if (typeof Windows !== 'undefined' &&
typeof Windows.UI !== 'undefined' &&
typeof Windows.ApplicationModel !== 'undefined') {
var onBackRequested = function (eventArgs) {
window.history.back();
eventArgs.handled = true;
}
Windows.UI.Core.SystemNavigationManager.getForCurrentView()
.appViewBackButtonVisibility =
Windows.UI.Core.AppViewBackButtonVisibility.visible;
Windows.UI.Core.SystemNavigationManager.getForCurrentView()
.addEventListener('backrequested', onBackRequested);
}
document.getElementById('btnTop').addEventListener('click', function () {
var header = document.getElementById('top');
var iframe = document.getElementById('articleContent');
// If the toolbar is hidden, show it instead of jumping to top
if (!/\(0p?x?\)/.test(header.style.transform)) {
header.style.transform = 'translateY(0)';
} else {
if (!params.hideToolbars) iframe.style.transform = 'translateY(-1px)';
iframe.contentWindow.scrollTo({
top: '0',
behavior: 'smooth'
});
document.getElementById('search-article').scrollTop = 0;
}
iframe.contentWindow.focus();
});
// Top menu :
document.getElementById('btnHome').addEventListener('click', function () {
// In Restricted mode, only load landing page in iframe (not tab or window)
appstate.target = 'iframe';
setTab('btnHome');
document.getElementById('search-article').scrollTop = 0;
const articleContent = document.getElementById('articleContent');
const articleContentDoc = articleContent ? articleContent.contentDocument : null;
while (articleContentDoc.firstChild) articleContentDoc.removeChild(articleContentDoc.firstChild);
uiUtil.clearSpinner();
document.getElementById('welcomeText').style.display = '';
if (appstate.selectedArchive !== null && appstate.selectedArchive.isReady()) {
document.getElementById('welcomeText').style.display = 'none';
goToMainArticle();
}
});
var currentArchive = document.getElementById('currentArchive');
var currentArchiveLink = document.getElementById('currentArchiveLink');
var openCurrentArchive = document.getElementById('openCurrentArchive');
var archiveFilesLegacy = document.getElementById('archiveFilesLegacy');
var archiveDirLegacy = document.getElementById('archiveDirLegacy');
if (!params.webkitdirectory) {
archiveDirLegacy.style.display = 'none';
}
function setTab (activeBtn) {
// Highlight the selected section in the navbar
setActiveBtn(activeBtn);
clearFindInArticle();
// Re-enable bottom toolbar display
document.getElementById('footer').style.display = 'block';
// Re-enable top-level scrolling
document.getElementById('top').style.position = 'relative';
// Use the "light" navbar if the content is "light" (otherwise it looks shite....)
var determinedTheme = cssUIThemeGetOrSet(params.cssUITheme);
var determinedWikiTheme = params.cssTheme === 'auto' ? determinedTheme : params.cssTheme === 'inverted' ? 'dark' : params.cssTheme;
if (determinedWikiTheme !== determinedTheme) {
if ((determinedWikiTheme === 'light' && (!activeBtn || activeBtn === 'btnHome' || activeBtn === 'findText')) ||
(determinedWikiTheme === 'dark' && activeBtn && activeBtn !== 'btnHome' && activeBtn !== 'findText')) {
cssUIThemeGetOrSet('light');
} else {
cssUIThemeGetOrSet('dark');
}
} else {
cssUIThemeGetOrSet(determinedTheme);
}
if (typeof Windows === 'undefined' && typeof window.showDirectoryPicker !== 'function' && !window.dialog && !params.webkitdirectory) {
// If not UWP, File System Access API, webkitdirectory API or Electron methods, hide the folder picker
document.getElementById('archiveFiles').style.display = 'none';
document.getElementById('archiveFilesLabel').style.display = 'none';
}
// Display OPFS checkbox if the browser supports the full API
if (navigator && navigator.storage && ('getDirectory' in navigator.storage) && ('estimate' in navigator.storage)) {
document.getElementById('displayOPFS').style.display = '';
}
document.getElementById('archiveFilesLegacyDiv').style.display = 'none';
document.getElementById('chooseArchiveFromLocalStorage').style.display = 'block';
document.getElementById('libraryArea').style.borderColor = '';
document.getElementById('libraryArea').style.borderStyle = '';
if (params.packagedFile && params.storedFile && params.storedFile !== params.packagedFile) {
currentArchiveLink.innerHTML = params.storedFile.replace(/\.zim(\w\w)?$/i, '');
currentArchiveLink.dataset.archive = params.storedFile;
currentArchive.style.display = 'block';
openCurrentArchive.style.display = (params.pickedFile || params.pickedFolder) ? 'none' : '';
document.getElementById('downloadLinksText').style.display = 'none';
document.getElementById('usage').style.display = 'none';
}
if (params.storedFile && params.storedFile === params.packagedFile) {
if (/wikipedia.en.(100|ray.charles)/i.test(params.packagedFile)) document.getElementById('usage').style.display = 'inline';
document.getElementById('downloadLinksText').style.display = 'block';
currentArchive.style.display = 'none';
}
var update = document.getElementById('update');
if (update) document.getElementById('logUpdate').innerHTML = update.innerHTML.match(/<ul[^>]*>[\s\S]+/i);
var features = document.getElementById('features');
if (features) document.getElementById('logFeatures').innerHTML = features.innerHTML;
// Show the selected content in the page
document.getElementById('about').style.display = 'none';
document.getElementById('configuration').style.display = 'none';
document.getElementById('formArticleSearch').style.display = '';
if (!activeBtn || activeBtn === 'btnHome') {
scrollbox.style.height = 0;
document.getElementById('search-article').style.overflowY = 'hidden';
setTimeout(function () {
if (appstate.target === 'iframe' && appstate.selectedArchive) {
// Note that it is too early to display the zimit iframe due to possible loading of darkReader and other css issues
if (articleContainer && articleContainer.style && articleDocument) {
articleContainer.style.display = '';
}
if (articleWindow) articleWindow.focus();
}
}, 400);
}
setDynamicIcons(activeBtn);
const articleList = document.getElementById('articleList');
const articleListHeaderMessage = document.getElementById('articleListHeaderMessage');
while (articleList.firstChild) articleList.removeChild(articleList.firstChild);
while (articleListHeaderMessage.firstChild) articleListHeaderMessage.removeChild(articleListHeaderMessage.firstChild);
document.getElementById('articleListWithHeader').style.display = 'none';
prefix.value = '';
document.getElementById('welcomeText').style.display = 'none';
if (params.themeChanged) {
params.themeChanged = null;
goToMainArticle();
}
if (params.beforeinstallpromptFired) {
var divInstall1 = document.getElementById('divInstall1');
if (activeBtn !== 'btnConfigure' && !params.installLater && (params.pagesLoaded === 3 || params.pagesLoaded === 9)) {
divInstall1.style.display = 'block';
setTimeout(function () {
// If installLater is now true, then the user clicked the Later button and the timeout in init.js will hide the display
if (!params.installLater) {
divInstall1.style.display = 'none';
resizeIFrame();
}
}, 9000);
} else {
divInstall1.style.display = 'none';
}
}
// Check for upgrade of PWA
if (activeBtn === 'btnConfigure') checkPWAUpdate();
// Resize iframe
setTimeout(resizeIFrame, 100);
}
// Set the dynamic icons in the navbar
function setDynamicIcons (btn) {
var btnAbout = document.getElementById('btnAbout');
if (params.lockDisplayOrientation) {
if (uiUtil.appIsFullScreen()) {
btnAbout.innerHTML = '<span class="glyphicon glyphicon-resize-small"></span>';
btnAbout.title = 'Exit fullscreen';
} else {
btnAbout.innerHTML = '<span class="glyphicon glyphicon-fullscreen"></span>';
btnAbout.title = 'Return to fullscreen';
}
} else {
// When the scrollbox height is 0, we are not in Configuration or About
if ((!btn && scrollbox.offsetHeight === 0) || btn === 'btnHome' || btn === 'findText') {
btnAbout.innerHTML = '<span class="glyphicon glyphicon-print"></span>';
btnAbout.title = 'Ctrl-P: Print';
} else {
btnAbout.innerHTML = '<span class="glyphicon glyphicon-info-sign"></span>';
btnAbout.title = 'About';
}
}
}
// Check if a PWA update is available
function checkPWAUpdate () {
if (!params.upgradeNeeded && /PWA/.test(params.appType)) {
caches.keys().then(function (keyList) {
var cachePrefix = cache.APPCACHE.replace(/^([^\d]+).+/, '$1');
document.getElementById('alertBoxPersistent').innerHTML = '';
keyList.forEach(function (key) {
if (key === cache.APPCACHE || key === cache.CACHEAPI) return;
// Ignore any keys that do not begin with the APPCACHE prefix (they could be from other apps using the same domain)
if (key.indexOf(cachePrefix)) return;
// If we get here, then there is a kiwix cache key that does not match our version, i.e. a PWA-in-waiting
var version = key.replace(cachePrefix, '');
var loadOrInstall = params.PWAInstalled ? 'install' : 'load';
params.upgradeNeeded = true;
uiUtil.showUpgradeReady(version, loadOrInstall);
});
});
} else if (params.upgradeNeeded) {
var upgradeAlert = document.getElementById('upgradeAlert');
if (upgradeAlert) upgradeAlert.style.display = 'block';
}
}
// Electron callback listener if an update is found by main.js
if (window.electronAPI) {
electronAPI.on('update-available', function (data) {
console.log('Upgrade is available or in progress:' + data);
params.upgradeNeeded = true;
if (data.percent) {
var percent = data.percent.toFixed(1);
uiUtil.showUpgradeReady(percent, 'progress');
} else {