Use cache.js for storing last page's HTML

Former-commit-id: 0ac93628384b579884666772f06380a93427a6d9 [formerly b495a7423b90bbb3118ccc983a95995d0a1dd8ed [formerly f4b48b2fb4e3ecb29dc1c1e4ccec32978d916cee]]
Former-commit-id: c80eab62268f69455e173dcdc6c4d58cc13395e9
Former-commit-id: b9fbb66bed344b71a9727e5243494159962a33ae
This commit is contained in:
Jaifroid 2021-01-12 11:14:02 +00:00
parent 81c8b9b97d
commit 8ea32e613f
5 changed files with 55 additions and 74 deletions

View File

@ -186,8 +186,7 @@ div:not(.panel-success, .alert-message) {
.message { .message {
position: absolute; position: absolute;
bottom: 0; margin: 70px auto 0;
margin: auto 10px 50px auto;
left: 0; left: 0;
right: 0; right: 0;
font-size: smaller; font-size: smaller;
@ -195,8 +194,7 @@ div:not(.panel-success, .alert-message) {
color: dimgrey; color: dimgrey;
border: 1px solid gainsboro; border: 1px solid gainsboro;
padding: 1px 4px; padding: 1px 4px;
max-width: 300px; width: 200px;
width: 60%;
} }
.dark .message { .dark .message {

View File

@ -215,7 +215,7 @@
<!-- Status indicators --> <!-- Status indicators -->
<div id="searchingArticles" style="display: none;" class="status"> <div id="searchingArticles" style="display: none;" class="status">
<div class="loader"></div> <div class="loader"></div>
<div id="progressMessage" style="display: none;" class="message"></div> <div id="cachingAssets" style="display: none;" class="message"></div>
</div> </div>
<section id="search-article" role="region"> <section id="search-article" role="region">
<header id="top" style="width:100%; transition: top 0.3s;"> <header id="top" style="width:100%; transition: top 0.3s;">
@ -264,7 +264,7 @@
<h3 style="margin-top:0;"> <h3 style="margin-top:0;">
Offline Wikipedia Viewer <small>(Version <span class="version"></span>)</small> Offline Wikipedia Viewer <small>(Version <span class="version"></span>)</small>
</h3> </h3>
<p>Packaged ZIM archive: <b><span class="fileVersion"></span></b></p> <p class="packagedInfo" style="display: none">Packaged ZIM archive: <b><span class="fileVersion"></span></b></p>
<ul style="padding-left:1em;"> <ul style="padding-left:1em;">
<li><a href="#addingArchives">Adding archives and languages</a></li> <li><a href="#addingArchives">Adding archives and languages</a></li>
<li><a href="#changelog">Changelog and Features</a></li> <li><a href="#changelog">Changelog and Features</a></li>
@ -466,7 +466,7 @@
<div id="divInstall2" style="display:none; float:right;"> <div id="divInstall2" style="display:none; float:right;">
<button id="btnInstall2" class="btn btn-xs btn-primary">Install PWA</button> <button id="btnInstall2" class="btn btn-xs btn-primary">Install PWA</button>
</div> </div>
<p> <p class="packagedInfo" style="display: none;">
Packaged ZIM archive: <b><span class="fileVersion"></span></b> Packaged ZIM archive: <b><span class="fileVersion"></span></b>
<button style="display:none;" id="reloadPackagedArchive" type="button" class="btn btn-primary btn-xs">Reload</button> <button style="display:none;" id="reloadPackagedArchive" type="button" class="btn btn-primary btn-xs">Reload</button>
</p> </p>

View File

@ -56,7 +56,11 @@ define(['jquery', 'zimArchiveLoader', 'uiUtil', 'util', 'cache', 'images', 'sett
// because params.storeType is also set in a preliminary way in init.js) // because params.storeType is also set in a preliminary way in init.js)
params['storeType'] = null; params['storeType'] = null;
params['storeType'] = settingsStore.getBestAvailableStorageAPI(); params['storeType'] = settingsStore.getBestAvailableStorageAPI();
// Test caching capibility
cache.test(function(){});
params['lastPageVisit'] = params.storedFile ? settingsStore.getItem(params.storedFile) : '';
params.lastPageVisit = params.lastPageVisit ? params.lastPageVisit + '@kiwixKey@' + params.storedFile : '';
// Unique identifier of the article expected to be displayed // Unique identifier of the article expected to be displayed
var expectedArticleURLToBeDisplayed = ""; var expectedArticleURLToBeDisplayed = "";
@ -343,17 +347,12 @@ define(['jquery', 'zimArchiveLoader', 'uiUtil', 'util', 'cache', 'images', 'sett
goToArticle(thisURL); goToArticle(thisURL);
} }
setTimeout(function () { //Restore temporarily changed value after page has reloaded setTimeout(function () { //Restore temporarily changed value after page has reloaded
params.rememberLastPage = settingsStore.getItem('rememberLastPage') == "true"; params.rememberLastPage = settingsStore.getItem('rememberLastPage') === 'true';
if (!params.rememberLastPage) { if (!params.rememberLastPage) {
settingsStore.setItem('lastPageVisit', "", Infinity); settingsStore.setItem('lastPageVisit', '', Infinity);
params.lastPageHTML = ""; params.lastPageHTML = '';
if (typeof Storage !== "undefined") { // DEV: replace this with cache.clear when you have repaired that method
try { cache.setArticle(params.lastPageVisit.replace(/.+@kiwixKey@/, ''), params.lastPageVisit.replace(/@kiwixKey@.+/, ''), '', function(){});
localStorage.setItem(params.keyPrefix + 'lastPageHTML', "");
} catch (err) {
console.log("localStorage not supported: " + err);
}
}
} }
}, 5000); }, 5000);
} }
@ -713,9 +712,13 @@ define(['jquery', 'zimArchiveLoader', 'uiUtil', 'util', 'cache', 'images', 'sett
for (var i = 0; i < versionSpans.length; i++) { for (var i = 0; i < versionSpans.length; i++) {
versionSpans[i].innerHTML = i ? params.version : params.version.replace(/\s+.*$/, ""); versionSpans[i].innerHTML = i ? params.version : params.version.replace(/\s+.*$/, "");
} }
var fileVersionDivs = document.getElementsByClassName('fileVersion'); if (params.fileVersion && /UWP|Electron/.test(params.appType)) {
for (i = 0; i < fileVersionDivs.length; i++) { var packagedInfoParas = document.getElementsByClassName('packagedInfo');
fileVersionDivs[i].innerHTML = i ? params.fileVersion.replace(/\s+.+$/, "") : params.fileVersion; var fileVersionDivs = document.getElementsByClassName('fileVersion');
for (i = 0; i < fileVersionDivs.length; i++) {
packagedInfoParas[i].style.display = 'block';
fileVersionDivs[i].innerHTML = i ? params.fileVersion.replace(/\s+.+$/, '') : params.fileVersion;
}
} }
var update = document.getElementById('update'); var update = document.getElementById('update');
if (update) document.getElementById('logUpdate').innerHTML = update.innerHTML.match(/<ul[^>]*>[\s\S]+/i); if (update) document.getElementById('logUpdate').innerHTML = update.innerHTML.match(/<ul[^>]*>[\s\S]+/i);
@ -1243,15 +1246,8 @@ define(['jquery', 'zimArchiveLoader', 'uiUtil', 'util', 'cache', 'images', 'sett
settingsStore.setItem('rememberLastPage', params.rememberLastPage, Infinity); settingsStore.setItem('rememberLastPage', params.rememberLastPage, Infinity);
if (!params.rememberLastPage) { if (!params.rememberLastPage) {
settingsStore.setItem('lastPageVisit', "", Infinity); settingsStore.setItem('lastPageVisit', "", Infinity);
//Clear localStorage // DEV: replace this with cache.clear when you have repaired that method
if (typeof Storage !== "undefined") { cache.setArticle(params.lastPageVisit.replace(/.+@kiwixKey@/, ''), params.lastPageVisit.replace(/@kiwixKey@.+/, ''), '', function(){});
try {
localStorage.setItem(params.keyPrefix + 'lastPageHTML', "");
localStorage.clear();
} catch (err) {
console.log("localStorage not supported: " + err);
}
}
params.lastPageHTML = ""; params.lastPageHTML = "";
} }
}); });
@ -2756,13 +2752,14 @@ define(['jquery', 'zimArchiveLoader', 'uiUtil', 'util', 'cache', 'images', 'sett
if (params.rememberLastPage && params.lastPageVisit) lastPage = params.lastPageVisit.replace(/@kiwixKey@.+/, ""); if (params.rememberLastPage && params.lastPageVisit) lastPage = params.lastPageVisit.replace(/@kiwixKey@.+/, "");
if (params.rememberLastPage && (typeof Storage !== "undefined") && dirEntry.namespace + '/' + dirEntry.url == lastPage) { if (params.rememberLastPage && (typeof Storage !== "undefined") && dirEntry.namespace + '/' + dirEntry.url == lastPage) {
if (!params.lastPageHTML) { if (!params.lastPageHTML) {
try { cache.getArticle(params.lastPageVisit.replace(/.*@kiwixKey@/, ''), lastPage, function (html) {
params.lastPageHTML = localStorage.getItem(params.keyPrefix + 'lastPageHTML'); params.lastPageHTML = html;
} catch (err) { htmlContent = params.lastPageHTML || htmlContent;
console.log("localStorage not supported: " + err); });
} } else {
htmlContent = params.lastPageHTML;
} }
htmlContent = params.lastPageHTML || htmlContent;
} }
if (/<html[^>]*>/.test(htmlContent)) { if (/<html[^>]*>/.test(htmlContent)) {
console.log("Fast article retrieval from localStorage: " + lastPage); console.log("Fast article retrieval from localStorage: " + lastPage);
@ -3015,34 +3012,13 @@ define(['jquery', 'zimArchiveLoader', 'uiUtil', 'util', 'cache', 'images', 'sett
!~window.history.state.title.indexOf("/" + dirEntry.url)) { !~window.history.state.title.indexOf("/" + dirEntry.url)) {
pushBrowserHistoryState(dirEntry.namespace + "/" + dirEntry.url); pushBrowserHistoryState(dirEntry.namespace + "/" + dirEntry.url);
} }
// Store for fast retrieval
if (!~params.lastPageVisit.indexOf(dirEntry.url)) { if (!~params.lastPageVisit.indexOf(dirEntry.url)) {
params.lastPageVisit = dirEntry.namespace + "/" + dirEntry.url + params.lastPageVisit = dirEntry.namespace + "/" + dirEntry.url +
"@kiwixKey@" + appstate.selectedArchive._file._files[0].name; "@kiwixKey@" + appstate.selectedArchive._file._files[0].name;
if (params.rememberLastPage) { cache.setArticle(appstate.selectedArchive._file._files[0].name, dirEntry.namespace + '/' + dirEntry.url, htmlArticle, function(){});
settingsStore.setItem('lastPageVisit', params.lastPageVisit, Infinity);
//Store current document's raw HTML in localStorage for fast restart
try {
// Ensure we don't go over quota
localStorage.removeItem(params.keyPrefix + 'lastPageHTML');
localStorage.setItem(params.keyPrefix + 'lastPageHTML', htmlArticle);
} catch (err) {
if (/quota\s*exceeded/i.test(err.message)) {
// Note that Edge gives a quotaExceeded message when running from localhost even if the quota isn't exceeded
// Basically, it means localStorage is not supported in Edge running from localhost...
if (params.storeType === 'local_storage') {
uiUtil.systemAlert('Your localStorage has exceeded its quota, so we are forced to clear it.\n' +
'Because your browser is using localStorage for remembering your settings, these may\n' +
'have been reset. Next time the app launches, please go to Config and set them again.');
}
console.log('Clearing localStorage because quota was exceeded...');
localStorage.clear();
} else {
console.error("Something went wrong with localStorage: ", err);
}
}
params.lastPageHTML = htmlArticle;
}
} }
params.htmlArticle = htmlArticle;
// Replaces ZIM-style URLs of img, script, link and media tags with a data-kiwixurl to prevent 404 errors [kiwix-js #272 #376] // Replaces ZIM-style URLs of img, script, link and media tags with a data-kiwixurl to prevent 404 errors [kiwix-js #272 #376]
// This replacement also processes the URL to remove the path so that the URL is ready for subsequent jQuery functions // This replacement also processes the URL to remove the path so that the URL is ready for subsequent jQuery functions

View File

@ -51,9 +51,9 @@ var appstate = {};
/******** UPDATE VERSION IN pwabuilder-sw.js TO MATCH VERSION *******/ /******** UPDATE VERSION IN pwabuilder-sw.js TO MATCH VERSION *******/
params['version'] = "1.1.4-RP2"; //DEV: Manually update this version when there is a new release: it is compared to the Settings Store "version" in order to show first-time info, and the cookie is updated in app.js params['version'] = "1.1.4-RP2"; //DEV: Manually update this version when there is a new release: it is compared to the Settings Store "version" in order to show first-time info, and the cookie is updated in app.js
/******* UPDATE THIS ^^^^^^ IN serveice worker!! ********************/ /******* UPDATE THIS ^^^^^^ IN serveice worker!! ********************/
params['packagedFile'] = "wikipedia_en_100_maxi.zim"; //For packaged Kiwix JS (e.g. with Wikivoyage file), set this to the filename (for split files, give the first chunk *.zimaa) and place file(s) in default storage params['packagedFile'] = null; //For packaged Kiwix JS (e.g. with Wikivoyage file), set this to the filename (for split files, give the first chunk *.zimaa) and place file(s) in default storage
params['archivePath'] = "archives"; //The directory containing the packaged archive(s) (relative to app's root directory) params['archivePath'] = "archives"; //The directory containing the packaged archive(s) (relative to app's root directory)
params['fileVersion'] = "wikipedia_en_100_maxi_2020-12.zim (23-Dec-2020)"; //Use generic name for actual file, and give version here params['fileVersion'] = ""; //Use generic name for actual file, and give version here
params['cachedStartPage'] = false; //If you have cached the start page for quick start, give its URI here params['cachedStartPage'] = false; //If you have cached the start page for quick start, give its URI here
params['kiwixDownloadLink'] = "https://download.kiwix.org/zim/"; //Include final slash params['kiwixDownloadLink'] = "https://download.kiwix.org/zim/"; //Include final slash
@ -88,19 +88,19 @@ params['storedFilePath'] = getSetting('lastSelectedArchivePath');
params.storedFilePath = params.storedFilePath ? decodeURIComponent(params.storedFilePath) : params.archivePath + '/' + params.packagedFile; params.storedFilePath = params.storedFilePath ? decodeURIComponent(params.storedFilePath) : params.archivePath + '/' + params.packagedFile;
params.storedFilePath = launchArguments ? launchArguments.files[0].path || '' : params.storedFilePath; params.storedFilePath = launchArguments ? launchArguments.files[0].path || '' : params.storedFilePath;
params.originalPackagedFile = params.packagedFile; params.originalPackagedFile = params.packagedFile;
params['falFileToken'] = params['falFileToken'] || "zimfile"; //UWP support params['falFileToken'] = params['falFileToken'] || "zimfile"; // UWP support
params['falFolderToken'] = params['falFolderToken'] || "zimfilestore"; //UWP support params['falFolderToken'] = params['falFolderToken'] || "zimfilestore"; // UWP support
params['localStorage'] = params['localStorage'] || ""; params['localStorage'] = params['localStorage'] || "";
params['pickedFile'] = launchArguments ? launchArguments.files[0] : ""; params['pickedFile'] = launchArguments ? launchArguments.files[0] : "";
params['pickedFolder'] = params['pickedFolder'] || ""; params['pickedFolder'] = params['pickedFolder'] || "";
params['lastPageVisit'] = getSetting('lastPageVisit') || "";
params.lastPageVisit = params.lastPageVisit ? decodeURIComponent(params.lastPageVisit): "";
params['themeChanged'] = params['themeChanged'] || false; params['themeChanged'] = params['themeChanged'] || false;
params['allowInternetAccess'] = params['allowInternetAccess'] || false; //Do not get value from cookie, should be explicitly set by user on a per-session basis params['allowInternetAccess'] = params['allowInternetAccess'] || false; // Do not get value from cookie, should be explicitly set by user on a per-session basis
params['printIntercept'] = false; params['printIntercept'] = false;
params['printInterception'] = false; params['printInterception'] = false;
params['appIsLaunching'] = true; //Allows some routines to tell if the app has just been launched params['appIsLaunching'] = true; // Allows some routines to tell if the app has just been launched
params['useCache'] = true; // This needs to be made optional in UI
params['PWAInstalled'] = decodeURIComponent(getSetting('PWAInstalled')); params['PWAInstalled'] = decodeURIComponent(getSetting('PWAInstalled'));
params['appType'] = getAppType();
params.pagesLoaded = 0; // Page counter used to show PWA Install Prompt only after user has played with the app for a while params.pagesLoaded = 0; // Page counter used to show PWA Install Prompt only after user has played with the app for a while
//Prevent app boot loop with problematic pages that cause an app crash //Prevent app boot loop with problematic pages that cause an app crash
@ -146,7 +146,15 @@ document.getElementById('hideToolbarsCheck').indeterminate = params.hideToolbars
document.getElementById('hideToolbarsCheck').readOnly = params.hideToolbars === "top"; document.getElementById('hideToolbarsCheck').readOnly = params.hideToolbars === "top";
document.getElementById('hideToolbarsState').innerHTML = (params.hideToolbars === "top" ? "top" : params.hideToolbars ? "both" : "never"); document.getElementById('hideToolbarsState').innerHTML = (params.hideToolbars === "top" ? "top" : params.hideToolbars ? "both" : "never");
//Set up storage types // Get app type
function getAppType() {
if (typeof Windows !== 'undefined' && typeof Windows.Storage !== 'undefined') return 'UWP';
if (window.fs || window.nw) return 'Electron';
if (navigator.serviceWorker) return 'PWA';
return 'HTML5';
}
// Set up storage types
if (params.storedFile && typeof Windows !== 'undefined' && typeof Windows.Storage !== 'undefined') { //UWP if (params.storedFile && typeof Windows !== 'undefined' && typeof Windows.Storage !== 'undefined') { //UWP
Windows.ApplicationModel.Package.current.installedLocation.getFolderAsync(params.archivePath).done(function (folder) { Windows.ApplicationModel.Package.current.installedLocation.getFolderAsync(params.archivePath).done(function (folder) {
params.localStorage = folder; params.localStorage = folder;
@ -197,7 +205,6 @@ window.addEventListener('beforeinstallprompt', function(e) {
// Don't display prompt if the PWA for this version is already installed // Don't display prompt if the PWA for this version is already installed
if (!params.beforeinstallpromptFired && params.PWAInstalled !== params.version) { if (!params.beforeinstallpromptFired && params.PWAInstalled !== params.version) {
params.beforeinstallpromptFired = true; params.beforeinstallpromptFired = true;
var config = document.getElementById('configuration');
btnInstall1.addEventListener('click', installApp); btnInstall1.addEventListener('click', installApp);
btnLater.addEventListener('click', function (e) { btnLater.addEventListener('click', function (e) {
e.preventDefault(); e.preventDefault();

View File

@ -176,13 +176,13 @@ define(rqDef, function() {
function poll(msg) { function poll(msg) {
document.getElementById('searchingArticles').style.display = 'block'; document.getElementById('searchingArticles').style.display = 'block';
document.getElementById('progressMessage').innerHTML = msg; document.getElementById('cachingAssets').innerHTML = msg;
document.getElementById('progressMessage').style.display = 'block'; document.getElementById('cachingAssets').style.display = 'block';
} }
function clear() { function clear() {
document.getElementById('progressMessage').innerHTML = ''; document.getElementById('cachingAssets').innerHTML = '';
document.getElementById('progressMessage').style.display = 'none'; document.getElementById('cachingAssets').style.display = 'none';
} }
function printCustomElements() { function printCustomElements() {