diff options
| author | Andrew Dolgov <fox@fakecake.org> | 2026-03-29 09:54:51 +0300 |
|---|---|---|
| committer | Andrew Dolgov <fox@fakecake.org> | 2026-03-29 09:54:51 +0300 |
| commit | 7d1f357a5e263567707b8f018da17f74c44c6d50 (patch) | |
| tree | faefd91113c180f3591002a8fdf291dbfdf6e692 | |
| parent | d2ea17abf815b6cd754511e27f4853045e0b3ca2 (diff) | |
| download | the-epube-ts.tar.gz the-epube-ts.tar.xz | |
horrors of ts ts
| -rw-r--r-- | dist/app.js | 417 | ||||
| -rw-r--r-- | dist/app.min.js | 1 | ||||
| -rw-r--r-- | dist/appcommon.js | 38 | ||||
| -rw-r--r-- | dist/cookie.js | 28 | ||||
| -rw-r--r-- | dist/reader.js | 1346 | ||||
| -rw-r--r-- | gulpfile.js | 14 | ||||
| -rw-r--r-- | js/app.d.ts | 2 | ||||
| -rw-r--r-- | js/localforage.d.ts | 123 | ||||
| -rw-r--r-- | js/reader.d.ts | 10 | ||||
| -rw-r--r-- | package-lock.json | 210 | ||||
| -rw-r--r-- | package.json | 7 | ||||
| -rw-r--r-- | src/app.ts (renamed from js/app.js) | 91 | ||||
| -rw-r--r-- | src/appcommon.ts | 43 | ||||
| -rw-r--r-- | src/cookie.ts | 24 | ||||
| -rw-r--r-- | src/reader.ts (renamed from js/reader.js) | 50 | ||||
| -rw-r--r-- | tsconfig.json | 9 |
16 files changed, 2169 insertions, 244 deletions
diff --git a/dist/app.js b/dist/app.js new file mode 100644 index 0000000..5950757 --- /dev/null +++ b/dist/app.js @@ -0,0 +1,417 @@ +'use strict'; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AppClass = void 0; +const appcommon_1 = require("./appcommon"); +const cookie_1 = require("./cookie"); +class AppClass extends appcommon_1.AppCommon { + constructor() { + super(...arguments); + this.index_mode = ""; + this.cached_urls = []; + this.version = "UNKNOWN"; + this.buildTimestamp = 0; + this.csrf_token = ""; + } + init() { + let refreshed_files = 0; + this.csrf_token = cookie_1.Cookie.get('epube_csrf_token'); + console.log('setting prefilter for token', this.csrf_token); + /* eslint-disable no-unused-vars */ + $.ajaxPrefilter((options, originalOptions, jqXHR) => { + if (originalOptions.type !== 'post' || options.type !== 'post') { + return; + } + const datatype = typeof originalOptions.data; + if (datatype == 'object') + options.data = $.param($.extend(originalOptions.data, { "csrf_token": this.csrf_token })); + else if (datatype == 'string') + options.data = originalOptions.data + "&csrf_token=" + encodeURIComponent(this.csrf_token); + console.log('>>>', options); + }); + if (typeof EpubeApp != "undefined") { + $(".navbar").hide(); + $(".epube-app-filler").show(); + $(".separate-search").show(); + $("body").addClass("is-epube-app"); + if (this.urlParam("mode") == "favorites") + EpubeApp.setPage("PAGE_FAVORITES"); + else + EpubeApp.setPage("PAGE_LIBRARY"); + } + this.initNightMode(); + this.initCommonEventHandlers(); + if ('serviceWorker' in navigator) { + navigator.serviceWorker.addEventListener('message', (event) => { + if (event.data == 'refresh-started') { + console.log('cache refresh started'); + refreshed_files = 0; + $(".dl-progress") + .fadeIn() + .text("Loading, please wait..."); + } + if (event.data && event.data.indexOf("refreshed:") == 0) { + ++refreshed_files; + $(".dl-progress") + .fadeIn() + .text("Updated " + refreshed_files + " files..."); + } + if (event.data == 'refresh-finished') { + localforage.setItem("epube.cache-version", this.version); + localforage.setItem("epube.cache-timestamp", this.buildTimestamp); + window.location.reload(); + } + }); + this.showCovers(); + this.updateOfflinePrompts(); + this.refreshCache(false); + } + else { + $(".container-main") + .addClass("alert alert-danger") + .html("Service worker support missing in browser (are you using plain HTTP?)."); + } + } + initCommonEventHandlers() { + $(".refresh_cache_link").on('click', () => { + this.refreshCache(true); + }); + $(".remove_all_downloads").on('click', () => { + this.removeAll(); + }); + $(".logout_link").on('click', () => { + this.logout(); + }); + } + logout() { + $.post("backend.php", { op: "logout" }).then(() => { + window.location.reload(); + }); + } + async showSummary(elem) { + const bookId = elem.getAttribute("data-book-id"); + if (this.isOnline()) { + const data = await $.post("backend.php", { op: 'getinfo', id: bookId }); + const comment = data.comment ? data.comment : 'No description available'; + $("#summary-modal .modal-title").html(data.title); + $("#summary-modal .book-summary").html(comment); + $("#summary-modal").modal(); + } + else { + const data = await localforage.getItem("epube-book." + bookId); + const comment = data.comment ? data.comment : 'No description available'; + $("#summary-modal .modal-title").html(data.title); + $("#summary-modal .book-summary").html(comment); + $("#summary-modal").modal(); + } + return false; + } + showCovers() { + $("img[data-book-id]").each((i, elem) => { + const e = $(elem); + if (e.attr('data-cover-link')) { + const img = $("<img>") + .on("load", () => { + e.css("background-image", "url(" + e.attr('data-cover-link') + ")") + .fadeIn(); + img.attr("src", null); + }) + .attr("src", e.attr('data-cover-link')); + } + }); + } + toggleFavorite(elem) { + const bookId = elem.getAttribute("data-book-id"); + if (elem.getAttribute("data-is-fav") == "0" || confirm("Remove favorite?")) { + $.post("backend.php", { op: "togglefav", id: bookId }, (data) => { + if (data) { + let msg = "[Error]"; + if (data.status == 0) { + msg = "Add to favorites"; + } + else if (data.status == 1) { + msg = "Remove from favorites"; + } + $(elem).html(msg).attr('data-is-fav', data.status); + if (this.index_mode == "favorites" && data.status == 0) { + $("#cell-" + bookId).remove(); + } + } + }); + } + return false; + } + async refreshCache(force) { + if ('serviceWorker' in navigator) { + const version = await localforage.getItem("epube.cache-version"); + console.log('local version', version, 'remote version', this.version); + if (force || version != this.version) { + console.log('asking worker to refresh cache'); + if (navigator.serviceWorker.controller) { + navigator.serviceWorker.controller.postMessage({ msg: "refresh-cache", urls: this.cached_urls }); + } + else { + const done = await localforage.getItem("epube.initial-load-done"); + console.log("initial load done?", done); + if (done) { + $(".dl-progress") + .show() + .addClass("alert-danger") + .html("Could not communicate with service worker. Try reloading the page."); + } + else { + await localforage.setItem("epube.initial-load-done", true); + $(".dl-progress") + .show() + .addClass("alert-info") + .html("Page will reload to activate service worker..."); + window.setTimeout(function () { + window.location.reload(); + }, 3 * 1000); + } + } + } + } + else { + $(".dl-progress") + .show() + .addClass("alert-danger") + .html("Could not communicate with service worker. Try reloading the page."); + } + } + appCheckOffline() { + EpubeApp.setOffline(!this.isOnline); + } + updateOfflinePrompts() { + const elems = $(".offline_dropitem"); + $.each(elems, (i, elem) => { + this.updateOfflinePrompt(elem); + }); + } + async updateOfflinePrompt(elem) { + const bookId = elem.getAttribute("data-book-id"); + const cacheId = "epube-book." + bookId; + const book = await localforage.getItem(cacheId); + if (book) { + elem.onclick = () => { + this.remove(bookId, () => { + this.updateOfflinePrompt(elem); + }); + return false; + }; + elem.innerHTML = "Remove offline data"; + } + else { + elem.onclick = () => { + this.get(bookId, () => { + this.updateOfflinePrompt(elem); + }); + return false; + }; + elem.innerHTML = "Make available offline"; + } + } + offlineInit() { + if (typeof EpubeApp != "undefined") { + $(".navbar").hide(); + $(".epube-app-filler").show(); + $("body").addClass("is-epube-app"); + EpubeApp.setPage("PAGE_OFFLINE"); + } + this.initNightMode(); + this.initCommonEventHandlers(); + const query = this.urlParam("query"); + if (query) + $(".search_query").val(query); + this.populateList(); + } + get(bookId, callback) { + console.log("offline cache: " + bookId); + $.post("backend.php", { op: "getinfo", id: bookId }, (data) => { + if (data) { + const cacheId = 'epube-book.' + bookId; + localforage.setItem(cacheId, data).then((data) => { + console.log(cacheId + ' got data'); + const promises = []; + promises.push(fetch('backend.php?op=download&id=' + data.epub_id, { credentials: 'same-origin' }).then(function (resp) { + if (resp.status == 200) { + console.log(cacheId + ' got book'); + localforage.setItem(cacheId + '.book', resp.blob()); + } + })); + promises.push(fetch("backend.php?op=getpagination&id=" + data.epub_id, { credentials: 'same-origin' }).then(function (resp) { + if (resp.status == 200) { + console.log(cacheId + ' got pagination'); + resp.text().then(function (text) { + localforage.setItem(cacheId + '.locations', JSON.parse(text)); + }); + } + })); + promises.push(fetch("backend.php?op=getlastread&id=" + data.epub_id, { credentials: 'same-origin' }).then(function (resp) { + if (resp.status == 200) { + console.log(cacheId + ' got lastread'); + resp.text().then(function (text) { + localforage.setItem(cacheId + '.lastread', JSON.parse(text)); + }); + } + })); + if (data.has_cover) { + promises.push(fetch("backend.php?op=cover&id=" + bookId, { credentials: 'same-origin' }).then(function (resp) { + if (resp.status == 200) { + console.log(cacheId + ' got cover'); + localforage.setItem(cacheId + '.cover', resp.blob()); + } + })); + } + Promise.all(promises).then(() => { + console.log('download done, running callback', callback); + callback(); + $(".dl-progress") + .show() + .html("Finished downloading <b>" + data.title + "</b>"); + window.clearTimeout(this._dl_progress_timeout); + this._dl_progress_timeout = window.setTimeout(function () { + $(".dl-progress").fadeOut(); + }, 5 * 1000); + }); + }); + } + }); + } + getAll() { + if (confirm("Download all books on this page?")) { + $(".row > div").each((i, row) => { + const bookId = $(row).attr("id").replace("cell-", ""); + const dropitem = $(row).find(".offline_dropitem")[0]; + if (bookId) { + const cacheId = 'epube-book.' + bookId; + localforage.getItem(cacheId).then((book) => { + if (!book) { + this.get(bookId, () => { + this.updateOfflinePrompt(dropitem); + }); + } + }); + } + }); + } + } + removeFromList(elem) { + const bookId = elem.getAttribute("data-book-id"); + this.remove(bookId, () => { + $("#cell-" + bookId).remove(); + }); + } + remove(id, callback) { + if (confirm("Remove download?")) { + const cacheId = "epube-book." + id; + const promises = []; + console.log("offline remove: " + id); + localforage.iterate(function (value, key /*, i */) { + if (key.match(cacheId)) { + promises.push(localforage.removeItem(key)); + } + }); + Promise.all(promises).then(() => { + console.log('remove done, running callback', callback); + // just promise.all is not enough, need to wait a bit for localforage to actually delete item (?) + window.setTimeout(() => { + callback(); + }, 250); + }); + } + } + async search() { + const query = $(".search_query").val(); + await localforage.setItem("epube.search-query", query); + this.populateList(); + return false; + } + async removeAll() { + if (confirm("Remove all downloaded books?")) { + const promises = []; + localforage.iterate(function (value, key /*, i*/) { + if (key.match("epube-book")) { + promises.push(localforage.removeItem(key)); + } + }); + await Promise.all(promises); + this.populateList(); + } + } + populateList() { + let query = this.urlParam("query"); + if (query) + query = String(query).toLowerCase(); + const books = $("#books_container"); + books.html(""); + localforage.iterate(function (value, key /*, i*/) { + if (key.match(/epube-book\.\d{1,}$/)) { + Promise.all([ + localforage.getItem(key), + localforage.getItem(key + ".cover"), + localforage.getItem(key + ".lastread"), + localforage.getItem(key + ".book") + ]).then(function (results) { + if (results[0] && results[3]) { + const info = results[0]; + if (query) { + const match = (info.series_name && info.series_name.toLowerCase().match(query)) || + (info.title && info.title.toLowerCase().match(query)) || + (info.author_sort && info.author_sort.toLowerCase().match(query)); + if (!match) + return; + } + let cover = ""; + if (results && results[1]) { + cover = URL.createObjectURL(results[1]); + } + let in_progress = false; + let is_read = false; + const lastread = results[2]; + if (lastread) { + in_progress = lastread.page > 0; + is_read = lastread.total > 0 && lastread.total - lastread.page < 5; + } + const thumb_class = is_read ? "read" : ""; + const title_class = in_progress ? "in_progress" : ""; + const series_link = info.series_name ? `<div><a class="series_link" href="#">${info.series_name + " [" + info.series_index + "]"}</a></div>` : ""; + const cell = $(`<div class="col-xxs-6 col-xs-4 col-sm-3 col-md-2" id="cell-${info.id}"> + <a class="thumbnail ${thumb_class}" href="read.html?id=${info.epub_id}&b=${info.id}"> + <img style="display : none"> + </a> + <div class="caption"> + <div><a class="${title_class}" href="read.html?id=${info.epub_id}&b=${info.id}">${info.title}</a></div> + <div><a class="author_link" href="#">${info.author_sort}</a></div> + ${series_link} + </div> + <div class="dropdown" style="white-space : nowrap"> + <a href="#" data-toggle="dropdown" role="button">More...<span class="caret"></span></a> + <ul class="dropdown-menu"> + <li><a href="#" data-book-id="${info.id}" onclick="return App.showSummary(this)">Summary</a></li> + <li><a href="#" data-book-id="${info.id}" onclick="App.removeFromList(this)">Remove offline data</a></li> + </ul> + </div> + </div>`); + if (cover) { + cell.find("img") + .css("background-image", "url(" + cover + ")") + .fadeIn(); + } + else { + cell + .fadeIn(); + } + cell.find(".series_link") + .attr("title", info.series_name + " [" + info.series_index + "]") + .attr("href", "offline.html?query=" + encodeURIComponent(info.series_name)); + cell.find(".author_link") + .attr("title", info.author_sort) + .attr("href", "offline.html?query=" + encodeURIComponent(info.author_sort)); + books.append(cell); + } + }); + } + }); + } +} +exports.AppClass = AppClass; diff --git a/dist/app.min.js b/dist/app.min.js deleted file mode 100644 index ba1c9f6..0000000 --- a/dist/app.min.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";class Cookie{static set(t,e,o){const a=new Date;a.setTime(a.getTime()+1e3*o);const n="expires="+a.toUTCString();document.cookie=t+"="+encodeURIComponent(e)+"; "+n}static get(t){t+="=";const e=document.cookie.split(";");for(let o=0;o<e.length;o++){let a=e[o];for(;" "==a.charAt(0);)a=a.substring(1);if(0==a.indexOf(t))return decodeURIComponent(a.substring(t.length,a.length))}return""}static delete(t){document.cookie=t+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT"}}class AppCommon{urlParam(t){try{const e=new RegExp("[?&]"+t+"=([^&#]*)").exec(window.location.href);return decodeURIComponent(e[1].replace(/\+/g," "))||0}catch(t){return 0}}isOnline(){return"undefined"!=typeof EpubeApp&&void 0!==EpubeApp.isOnline?EpubeApp.isOnline():navigator.onLine}initNightMode(){if("undefined"==typeof EpubeApp){if(window.matchMedia){const t=window.matchMedia("(prefers-color-scheme: dark)");t.addEventListener("change",()=>{this.applyNightMode(t.matches)}),this.applyNightMode(t.matches)}}else this.applyNightMode(EpubeApp.isNightMode())}applyNightMode(t){console.log("night mode changed to",t),$("#theme_css").attr("href","lib/bootstrap/v3/css/"+(t?"theme-dark.min.css":"bootstrap-theme.min.css"))}}class AppClass extends AppCommon{_dl_progress_timeout;index_mode="";cached_urls=[];version="UNKNOWN";buildTimestamp=0;csrf_token="";init(){let t=0;this.csrf_token=Cookie.get("epube_csrf_token"),console.log("setting prefilter for token",this.csrf_token),$.ajaxPrefilter((t,e,o)=>{if("post"!==e.type||"post"!==t.type)return;const a=typeof e.data;"object"==a?t.data=$.param($.extend(e.data,{csrf_token:this.csrf_token})):"string"==a&&(t.data=e.data+"&csrf_token="+encodeURIComponent(this.csrf_token)),console.log(">>>",t)}),"undefined"!=typeof EpubeApp&&($(".navbar").hide(),$(".epube-app-filler").show(),$(".separate-search").show(),$("body").addClass("is-epube-app"),"favorites"==this.urlParam("mode")?EpubeApp.setPage("PAGE_FAVORITES"):EpubeApp.setPage("PAGE_LIBRARY")),this.initNightMode(),this.initCommonEventHandlers(),"serviceWorker"in navigator?(navigator.serviceWorker.addEventListener("message",e=>{"refresh-started"==e.data&&(console.log("cache refresh started"),t=0,$(".dl-progress").fadeIn().text("Loading, please wait...")),e.data&&0==e.data.indexOf("refreshed:")&&(++t,$(".dl-progress").fadeIn().text("Updated "+t+" files...")),"refresh-finished"==e.data&&(localforage.setItem("epube.cache-version",this.version),localforage.setItem("epube.cache-timestamp",this.buildTimestamp),window.location.reload())}),this.showCovers(),this.updateOfflinePrompts(),this.refreshCache()):$(".container-main").addClass("alert alert-danger").html("Service worker support missing in browser (are you using plain HTTP?).")}initCommonEventHandlers(){$(".refresh_cache_link").on("click",()=>{this.refreshCache(!0)}),$(".remove_all_downloads").on("click",()=>{this.removeAll()}),$(".logout_link").on("click",()=>{this.logout()})}logout(){$.post("backend.php",{op:"logout"}).then(()=>{window.location.reload()})}async showSummary(t){const e=t.getAttribute("data-book-id");if(this.isOnline()){const t=await $.post("backend.php",{op:"getinfo",id:e}),o=t.comment?t.comment:"No description available";$("#summary-modal .modal-title").html(t.title),$("#summary-modal .book-summary").html(o),$("#summary-modal").modal()}else{const t=await localforage.getItem("epube-book."+e),o=t.comment?t.comment:"No description available";$("#summary-modal .modal-title").html(t.title),$("#summary-modal .book-summary").html(o),$("#summary-modal").modal()}return!1}showCovers(){$("img[data-book-id]").each((t,e)=>{const o=$(e);if(o.attr("data-cover-link")){const t=$("<img>").on("load",()=>{o.css("background-image","url("+o.attr("data-cover-link")+")").fadeIn(),t.attr("src",null)}).attr("src",o.attr("data-cover-link"))}})}toggleFavorite(t){const e=t.getAttribute("data-book-id");return("0"==t.getAttribute("data-is-fav")||confirm("Remove favorite?"))&&$.post("backend.php",{op:"togglefav",id:e},o=>{if(o){let a="[Error]";0==o.status?a="Add to favorites":1==o.status&&(a="Remove from favorites"),$(t).html(a).attr("data-is-fav",o.status),"favorites"==this.index_mode&&0==o.status&&$("#cell-"+e).remove()}}),!1}async refreshCache(t){if("serviceWorker"in navigator){const e=await localforage.getItem("epube.cache-version");if(console.log("local version",e,"remote version",this.version),t||e!=this.version)if(console.log("asking worker to refresh cache"),navigator.serviceWorker.controller)navigator.serviceWorker.controller.postMessage({msg:"refresh-cache",urls:this.cached_urls});else{const t=await localforage.getItem("epube.initial-load-done");console.log("initial load done?",t),t?$(".dl-progress").show().addClass("alert-danger").html("Could not communicate with service worker. Try reloading the page."):(await localforage.setItem("epube.initial-load-done",!0),$(".dl-progress").show().addClass("alert-info").html("Page will reload to activate service worker..."),window.setTimeout((function(){window.location.reload()}),3e3))}}else $(".dl-progress").show().addClass("alert-danger").html("Could not communicate with service worker. Try reloading the page.")}appCheckOffline(){EpubeApp.setOffline(!this.isOnline)}updateOfflinePrompts(){const t=$(".offline_dropitem");$.each(t,(t,e)=>{this.updateOfflinePrompt(e)})}async updateOfflinePrompt(t){const e=t.getAttribute("data-book-id"),o="epube-book."+e;await localforage.getItem(o)?(t.onclick=()=>(this.remove(e,()=>{this.updateOfflinePrompt(t)}),!1),t.innerHTML="Remove offline data"):(t.onclick=()=>(this.get(e,()=>{this.updateOfflinePrompt(t)}),!1),t.innerHTML="Make available offline")}offlineInit(){"undefined"!=typeof EpubeApp&&($(".navbar").hide(),$(".epube-app-filler").show(),$("body").addClass("is-epube-app"),EpubeApp.setPage("PAGE_OFFLINE")),this.initNightMode(),this.initCommonEventHandlers();const t=this.urlParam("query");t&&$(".search_query").val(t),this.populateList()}get(t,e){console.log("offline cache: "+t),$.post("backend.php",{op:"getinfo",id:t},o=>{if(o){const a="epube-book."+t;localforage.setItem(a,o).then(o=>{console.log(a+" got data");const n=[];n.push(fetch("backend.php?op=download&id="+o.epub_id,{credentials:"same-origin"}).then((function(t){200==t.status&&(console.log(a+" got book"),localforage.setItem(a+".book",t.blob()))}))),n.push(fetch("backend.php?op=getpagination&id="+o.epub_id,{credentials:"same-origin"}).then((function(t){200==t.status&&(console.log(a+" got pagination"),t.text().then((function(t){localforage.setItem(a+".locations",JSON.parse(t))})))}))),n.push(fetch("backend.php?op=getlastread&id="+o.epub_id,{credentials:"same-origin"}).then((function(t){200==t.status&&(console.log(a+" got lastread"),t.text().then((function(t){localforage.setItem(a+".lastread",JSON.parse(t))})))}))),o.has_cover&&n.push(fetch("backend.php?op=cover&id="+t,{credentials:"same-origin"}).then((function(t){200==t.status&&(console.log(a+" got cover"),localforage.setItem(a+".cover",t.blob()))}))),Promise.all(n).then(()=>{console.log("download done, running callback",e),e(),$(".dl-progress").show().html("Finished downloading <b>"+o.title+"</b>"),window.clearTimeout(this._dl_progress_timeout),this._dl_progress_timeout=window.setTimeout((function(){$(".dl-progress").fadeOut()}),5e3)})})}})}getAll(){confirm("Download all books on this page?")&&$(".row > div").each((t,e)=>{const o=$(e).attr("id").replace("cell-",""),a=$(e).find(".offline_dropitem")[0];if(o){const t="epube-book."+o;localforage.getItem(t).then(t=>{t||this.get(o,()=>{this.updateOfflinePrompt(a)})})}})}removeFromList(t){const e=t.getAttribute("data-book-id");this.remove(e,()=>{$("#cell-"+e).remove()})}remove(t,e){if(confirm("Remove download?")){const o="epube-book."+t,a=[];console.log("offline remove: "+t),localforage.iterate((function(t,e){e.match(o)&&a.push(localforage.removeItem(e))})),Promise.all(a).then(()=>{console.log("remove done, running callback",e),window.setTimeout(()=>{e()},250)})}}async search(){const t=$(".search_query").val();return await localforage.setItem("epube.search-query",t),this.populateList(),!1}async removeAll(){if(confirm("Remove all downloaded books?")){const t=[];localforage.iterate((function(e,o){o.match("epube-book")&&t.push(localforage.removeItem(o))})),await Promise.all(t),this.populateList()}}populateList(){let t=this.urlParam("query");t&&(t=String(t).toLowerCase());const e=$("#books_container");e.html(""),localforage.iterate((function(o,a){a.match(/epube-book\.\d{1,}$/)&&Promise.all([localforage.getItem(a),localforage.getItem(a+".cover"),localforage.getItem(a+".lastread"),localforage.getItem(a+".book")]).then((function(o){if(o[0]&&o[3]){const a=o[0];if(t){if(!(a.series_name&&a.series_name.toLowerCase().match(t)||a.title&&a.title.toLowerCase().match(t)||a.author_sort&&a.author_sort.toLowerCase().match(t)))return}let n="";o&&o[1]&&(n=URL.createObjectURL(o[1]));let i=!1,s=!1;const l=o[2];l&&(i=l.page>0,s=l.total>0&&l.total-l.page<5);const r=s?"read":"",c=i?"in_progress":"",d=a.series_name?`<div><a class="series_link" href="#">${a.series_name+" ["+a.series_index+"]"}</a></div>`:"",h=$(`<div class="col-xxs-6 col-xs-4 col-sm-3 col-md-2" id="cell-${a.id}">\n\t\t\t\t\t\t<a class="thumbnail ${r}" href="read.html?id=${a.epub_id}&b=${a.id}">\n\t\t\t\t\t\t\t<img style="display : none">\n\t\t\t\t\t\t</a>\n\t\t\t\t\t\t<div class="caption">\n\t\t\t\t\t\t\t<div><a class="${c}" href="read.html?id=${a.epub_id}&b=${a.id}">${a.title}</a></div>\n\t\t\t\t\t\t\t<div><a class="author_link" href="#">${a.author_sort}</a></div>\n\t\t\t\t\t\t\t${d}\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class="dropdown" style="white-space : nowrap">\n\t\t\t\t\t\t\t<a href="#" data-toggle="dropdown" role="button">More...<span class="caret"></span></a>\n\t\t\t\t\t\t\t<ul class="dropdown-menu">\n\t\t\t\t\t\t\t\t<li><a href="#" data-book-id="${a.id}" onclick="return App.showSummary(this)">Summary</a></li>\n\t\t\t\t\t\t\t\t<li><a href="#" data-book-id="${a.id}" onclick="App.removeFromList(this)">Remove offline data</a></li>\n\t\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>`);n?h.find("img").css("background-image","url("+n+")").fadeIn():h.fadeIn(),h.find(".series_link").attr("title",a.series_name+" ["+a.series_index+"]").attr("href","offline.html?query="+encodeURIComponent(a.series_name)),h.find(".author_link").attr("title",a.author_sort).attr("href","offline.html?query="+encodeURIComponent(a.author_sort)),e.append(h)}}))}))}}const DEFAULT_FONT_SIZE=16,DEFAULT_FONT_FAMILY="Arial",DEFAULT_LINE_HEIGHT=140,MIN_LENGTH_TO_JUSTIFY=32,LOCATION_DIVISOR=10,PAGE_RESET_PROGRESS=-1;class ReaderClass extends AppCommon{csrf_token="";last_stored_cfi="";startup_finished=!1;open_last_read_when_displayed=!0;hyphenate={};_prevent_lastread_timeout;_prevent_lastread;book;async init(){this.csrf_token=Cookie.get("epube_csrf_token"),console.log("setting prefilter for token",this.csrf_token),$.ajaxPrefilter((t,e)=>{if("post"!==e.type||"post"!==t.type)return;const o=typeof e.data;"object"==o?t.data=$.param($.extend(e.data,{csrf_token:this.csrf_token})):"string"==o&&(t.data=e.data+"&csrf_token="+encodeURIComponent(this.csrf_token)),console.log(">>>",t)}),$(document).on("keyup",t=>{this.hotkeyHandler(t)}),$(".close_book").on("click",()=>{this.close()}),$("#left").on("mouseup",()=>{this.prevPage()}),$(".search_input").on("change",()=>{this.search()}),$(".prev_location_btn").on("click",t=>{this.openPrevious(t.target)}),$("#right").on("mouseup",()=>{this.nextPage()}),this.loader=new ReaderLoader;const t=await this.loader.init();console.log("[init] load failed",t),t?(this.applyTheme(),$(".loading-message").text("Resource loader failed to initialize.")):this.initSecondStage()}isTouchDevice(){return"ontouchstart"in window||navigator.maxTouchPoints>0}onOfflineModeChanged(t){if(console.log("onOfflineModeChanged",t),!t&&this.book){console.log("we're online, storing lastread");const t=this.book.rendition.currentLocation().start.cfi,e=Math.round(100*this.book.locations.percentageFromCfi(t));$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:e,cfi:t,timestamp:(new Date).getTime()},(function(){})).fail((function(t){t&&401==t.status&&(window.location.href="index.php")}))}}async initSecondStage(){"undefined"!=typeof EpubeApp?EpubeApp.setPage("PAGE_READER"):($(window).on("online",()=>{this.onOfflineModeChanged(!1)}),$(window).on("offline",()=>{this.onOfflineModeChanged(!0)})),this.applyTheme();if(!await localforage.getItem(this.cacheId())){const t=this.urlParam("b");console.log("requesting bookinfo for book",t);try{const e=await $.post("backend.php",{op:"getinfo",id:t});if(e.has_cover){const e=await fetch("backend.php?op=cover&id="+t);e.ok&&await localforage.setItem(this.cacheId("cover"),e.blob())}await localforage.setItem(this.cacheId(),e),console.log("bookinfo saved")}catch(t){return void $(".loading-message").html(`Unable to load book info.<br/><small>${t.responseText}</small>`)}}console.log("trying to load book...");let t=await localforage.getItem(this.cacheId("book"));if(!t){console.log("local data not found, loading from network..."),$(".loading-message").html("Downloading book…");const e=await fetch("backend.php?op=download&id="+this.urlParam("id"));if(!e.ok)return void $(".loading-message").html("Unable to download book: "+e.status);if(t=await e.blob(),!t)return void $(".loading-message").html("Unable to get book blob data.");await localforage.setItem(this.cacheId("book"),t),console.log("saved local data for book")}const e=new FileReader,o=this;e.onload=function(){try{o.openBookData(this.result)}catch(t){console.error(t),$(".loading-message").html("Unable to load book blob: "+t)}},e.onerror=t=>{console.log("filereader error",t),$(".loading-message").html("Unable to open book.<br/><small>"+t+"</small>")},e.readAsArrayBuffer(t)}async openBookData(t){this.book=new ePub.Book;try{await this.book.open(t)}catch(t){return console.error(t),void $(".loading-message").html("Unable to open book.<br/><small>"+t.message+"</small>")}await this.book.ready,console.log("book is ready"),await this.showBookInfo(this.book),await this.loadLocations(this.book);const e=this.book.renderTo("reader",{width:"100%",height:"100%",allowScriptedContent:!1,minSpreadWidth:961});$(".location").on("click",async()=>{const t=Math.floor(e.currentLocation().start.location/10),o=Math.floor(this.book.locations.length()/10),a=prompt("Jump to location [1-"+o+"]",String(t));a&&await e.display(this.book.locations._locations[10*parseInt(a)])});await localforage.getItem("epube.enable-hyphens")&&(this.hyphenate.en=createHyphenator(hyphenationPatternsEnUs,{html:!0}),this.hyphenate.ru=createHyphenator(hyphenationPatternsRu,{html:!0})),this.initRenditionHooks(this.book,e),this.initModals(),this.initToc(this.book),this.blockLastReadUpdate(),await e.display(),console.log("startup finished"),this.startup_finished=!0}async showBookInfo(t){const e=await localforage.getItem(this.cacheId());let o,a;if(e)o=e.title,a=e.author_sort;else{const e=t.packaging.metadata;o=e.title,a=e.creator}document.title=o+" – "+a+" – The Epube",$(".title").text(o).attr("title",o+" – "+a),"undefined"!=typeof EpubeApp&&(EpubeApp.setTitle(o),EpubeApp.showActionBar(!1))}async loadLocations(t){let e=await localforage.getItem(this.cacheId("locations"));if(e&&"string"==typeof e[0]){console.log("loading local locations...");try{return void await t.locations.load(e)}catch(t){console.warn(t)}}if(this.isOnline()){console.log("downloading locations..."),$(".loading-message").html("Downloading locations…");const o=await fetch("backend.php?op=getpagination&id="+this.urlParam("id"));if(o.ok){console.log("got locations from server");try{e=await o.json()}catch(t){console.warn(t)}if(e&&"string"==typeof e[0]){console.log("saving locations locally..."),await localforage.setItem(this.cacheId("locations"),e);try{return void t.locations.load(e)}catch(t){console.warn(t)}}}}$(".loading-message").html("Preparing locations…");let o=0;e=await t.locations.generate(100,t=>{if(o||(o=t.length()),o>0){const e=Math.round(100*(1-t.length()/o));$(".loading-message").html(`Preparing locations (${e}%)…`)}}),$.post("backend.php",{op:"storepagination",id:this.urlParam("id"),payload:JSON.stringify(e),total:100}),await localforage.setItem(this.cacheId("locations"),e)}initRenditionHooks(t,e){console.log("initRenditionHooks"),t.spine.hooks.content.register(t=>{this.cleanupEmbeddedStyles(t)}),e.hooks.content.register(async o=>{o.on("linkClicked",t=>{console.log("linkClicked",t),this.blockLastReadUpdate(),-1==t.indexOf("://")&&($(".prev_location_btn").attr("data-location-cfi",e.currentLocation().start.cfi).show(),window.requestAnimationFrame(()=>{this.showUI(!0)}))}),o.on("selected",async e=>{if(this.isOnline()){const a=await t.getRange(e),n=a.endContainer.data.substring(a.startOffset,a.endOffset);console.log("selected",e,n),n.match(/^[\w]+$/)&&this.lookupWord(n,()=>{"undefined"!=typeof EpubeApp&&EpubeApp.showActionBar(!1),o.window.requestAnimationFrame(()=>{o.window.getSelection().removeAllRanges()})})}});const a=window.location.href.match(/^.*\//)[0];$(o.document.head).append($("<style type='text/css'>").text(this.generateFontsCss(a))),$(o.document.head).append($("<style type='text/css'>").text(this.loader._res_data[a+"dist/reader_iframe.min.css"]));const n=await localforage.getItem("epube.theme")||"default";$(o.document).find("body").attr("class","undefined"!=typeof EpubeApp?"is-epube-app":"").addClass("theme-"+n),console.log("contents",o),$(o.window).on("click tap",t=>{if(0==t.button){if($(".modal").is(":visible"))return;"undefined"!=typeof EpubeApp?EpubeApp.toggleActionBar():this.showUI(!0)}}),$(o.window).on("wheel",async t=>{await localforage.getItem("epube.enable-wheel")&&(t.originalEvent.deltaY>0?this.nextPage():t.originalEvent.deltaY<0&&this.prevPage())})}),e.on("keyup",t=>{this.hotkeyHandler(t)}),e.on("resized",()=>{console.log("rendition resized"),this.blockLastReadUpdate(),this.open_last_read_when_displayed=!0}),e.on("rendered",async()=>{console.log("rendition rendered"),this.applyTheme(),this.resizeSideColumns();try{const o=e.currentLocation();if(o.start){const e=t.canonical(o.start.href);let a={};$.each(this.flattenToc(t),(function(o,n){t.spine.get(n.href).canonical!=e||(a=n)})),a&&a.label&&$(".chapter_title").html(a.label.trim()+" | "),this.generateTocBar(t,this.flattenToc(t))}}catch(t){console.warn(t)}this.open_last_read_when_displayed&&(this.open_last_read_when_displayed=!1,await this.openLastRead())}),e.on("displayed",(function(){console.log("rendition displayed")})),e.on("relocated",e=>this.onRelocated(t,e))}initModals(){$("#settings-modal").on("shown.bs.modal",async()=>{const t=await localforage.getItem(this.cacheId("lastread"));t&&t.cfi&&$(".lastread_input").val(t.page+"%").attr("title","[local] "+t.cfi),$(".clear_last_read").off("click").on("click",()=>{this.clearLastRead()}),$(".open_last_read").off("click").on("click",()=>{this.openLastRead()}),$(".mark_as_read").off("click").on("click",()=>{this.markAsRead()}),$(".reset_locations").off("click").on("click",()=>{this.resetLocations()}),navigator.onLine&&$.post("backend.php",{op:"getlastread",id:this.urlParam("id")},t=>{$(".lastread_input").val(t.page+"%").attr("title","[remote] "+t.cfi)}),$(".font_family").off("change").on("change",t=>{this.onFontChanged(t.target)}),$(".font_size").off("change").on("change",t=>{this.onTextSizeChanged(t.target)}),$(".line_height").off("change").on("change",t=>{this.onLineHeightChanged(t.target)}),$(".theme_name").off("change").on("change",t=>{this.onThemeChanged(t.target)}),$(".enable_hyphens_checkbox").attr("checked",await localforage.getItem("epube.enable-hyphens")).off("click").on("click",t=>{localforage.setItem("epube.enable-hyphens",t.target.checked),confirm("Toggling hyphens requires page reload. Reload now?")&&window.location.reload()}),$(".enable_wheel_checkbox").attr("checked",await localforage.getItem("epube.enable-wheel")).off("click").on("click",t=>{localforage.setItem("epube.enable-wheel",t.target.checked)}),"undefined"!=typeof EpubeApp?$(".keep_ui_checkbox").parent().parent().hide():$(".keep_ui_checkbox").attr("checked",await localforage.getItem("epube.keep-ui-visible")).off("click").on("click",t=>{localforage.setItem("epube.keep-ui-visible",t.target.checked)});const e=await localforage.getItem("epube.cache-timestamp"),o=await localforage.getItem("epube.cache-version");$(".last-mod-timestamp").html(`${o}\n\t\t\t\t— ${parseInt(e)?new Date(1e3*e).toLocaleString("en-GB"):"Unknown"}\n\t\t\t\t(${this.isOnline()?"<span class='text-success'>Online</span>":"<span class='text-danger'>Offline</span>"})\n\t\t\t\t`),$(".font_family").val(await localforage.getItem("epube.fontFamily")||"Arial"),$(".theme_name").val(await localforage.getItem("epube.theme")||"default");const a=$(".font_size").html("");for(let t=10;t<=32;t++){const e=$("<option>").val(t).html(t+" px");a.append(e)}a.val(await localforage.getItem("epube.fontSize")||16);const n=$(".line_height").html("");for(let t=100;t<=220;t+=10){const e=$("<option>").val(t).html(t+"%");n.append(e)}n.val(await localforage.getItem("epube.lineHeight")||140)}),$("#dict-modal").on("shown.bs.modal",()=>{$(".dict_query").off("change").on("change",()=>{this.lookupWord(null,null,".dict_query")}),$(".dict_result").scrollTop(0)}),$(".dict_search_btn").on("click",(function(){$("#dict-modal").modal("hide"),window.open("https://duckduckgo.com/?q="+$(".dict_query").val())}))}initToc(t){const e=this;function o(o){try{const a=t.spine.get(o).cfiBase,n=t.locations._locations.find((function(t){return-1!=t.indexOf(a)}));return Math.round(e.book.locations.locationFromCfi(n)/10)}catch(t){console.warn(t)}return""}$("#toc-modal").on("shown.bs.modal",(function(){const e=t.navigation.toc,a=$(".toc_list");a.html(""),$.each(e,(function(e,n){try{const e=$("<a>").attr("href","#").html("<b class='pull-right'>"+o(n.href)+"</b>"+n.label).attr("data-href",n.href).click((function(){t.rendition.display(e.attr("data-href"))}));a.append($("<li>").append(e)),function e(a,n,i){if(3==i)return!1;if(a.subitems){const s=$("<ul class='toc_sublist list-unstyled'>");$.each(a.subitems,(function(a,n){const l=$("<a>").attr("href","#").html("<b class='pull-right'>"+o(n.href)+"</b>"+n.label).attr("data-href",n.href).click((function(){t.rendition.display(l.attr("data-href"))}));s.append($("<li>").append(l)),e(n,s,i+1)})),n.append(s)}}(n,a,0)}catch(t){console.warn(t)}})),a.children().length<=1&&(a.html(""),$.each(t.spine.items,(function(e,o){const n=$("<a>").attr("href","#").attr("title",o.url).html("Section "+(e+1)).attr("data-href",o.href).on("click",()=>{t.rendition.display(n.attr("data-href"))});a.append($("<li>").append(n))})))}))}cleanupEmbeddedStyles(t){$(t).find("p").filter((t,e)=>$(e).text().length>=32?e:null).css("text-align","justify"),$(t).find("html").attr("class",""),$(t).find("pre").css("white-space","pre-wrap"),$(t).find("a, p, span, em, i, strong, b, body, header, section, div, big, small, table, tr, td, th, ul, ol, li").attr("class","").css("font-family","inherit").css("font-size","inherit").css("line-height","inherit").css("color","").css("border","none ! important").css("background","").css("background-color","").attr("width","").attr("height",""),$(t).find("h1, h2, h3, h4, h5").attr("class","").css("font-family","inherit").css("color","").css("border","none ! important").css("background","").css("background-color",""),void 0!==this.hyphenate.en&&$(t).find("p, div").each((t,e)=>{const o=$(e);o.html(this.hyphenate.en(o.html())),o.html(this.hyphenate.ru(o.html()))})}generateFontsCss(t){return`\n\t\t\t/** Calibri */\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Calibri';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/calibriz.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Calibri';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/calibrib.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Calibri';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/calibrii.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Calibri';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/calibri.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t/** Cambria */\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Cambria';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/cambriab.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Cambria';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/cambriaz.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Cambria';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/cambriai.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Cambria';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/cambria.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t/** Caecilia */\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: Caecilia;\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/caecilia.ttf"]});\n\t\t\t\tfont-weight : normal;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: Caecilia;\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/caeciliab.ttf"]});\n\t\t\t\tfont-weight : bold;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: Caecilia;\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/caeciliai.ttf"]});\n\t\t\t\tfont-style : italic;\n\t\t\t}\n\n\t\t\t/** Palatino */\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Palatino';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/palab.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Palatino';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/palabi.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Palatino';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/palai.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Palatino';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/pala.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t/** Consolas */\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Consolas';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/consolab.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Consolas';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/consolaz.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Consolas';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/consolai.ttf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'Consolas';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/consola.ttf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t/** IBM Plex Mono */\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'IBM Plex Mono';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/IBMPlexMono-Bold.otf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'IBM Plex Mono';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/IBMPlexMono-BoldItalic.otf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 700;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'IBM Plex Mono';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/IBMPlexMono-TextItalic.otf"]});\n\t\t\t\tfont-style: italic;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\n\t\t\t@font-face {\n\t\t\t\tfont-family: 'IBM Plex Mono';\n\t\t\t\tsrc: url(${this.loader._res_data[t+"lib/fonts/IBMPlexMono-Text.otf"]});\n\t\t\t\tfont-style: normal;\n\t\t\t\tfont-weight : 400;\n\t\t\t}\n\t\t\t`}flattenTocSubItems(t,e){let o=[];return 3!=e&&(t.subitems&&$.each(t.subitems,(t,a)=>{a._nest=e,o.push(a),o=o.concat(this.flattenTocSubItems(a,e+1))}),o)}flattenToc(t){if(this._flattened_toc)return this._flattened_toc;{let e=[];return $.each(t.navigation.toc,(t,o)=>{o._nest=0,e.push(o),e=e.concat(this.flattenTocSubItems(o,1))}),this._flattened_toc=e,e}}generateTocBar(t,e){$(".spacer").html(""),$.each(e,(function(e,o){try{const e=t.spine.get(o.href).cfiBase,a=t.locations._locations.find((function(t){return-1!=t.indexOf(e)}));if(a){const e=Math.round(100*t.locations.percentageFromCfi(a));$(".spacer").append($("<div class='toc-bar-entry'>").attr("data-nest-level",o._nest).css("left",e+"%").css("_width",3-o._nest+"px").attr("title",o.label))}}catch(t){console.warn(t)}})),$(".spacer").append($("<div class='toc-bar-entry current-position'>")),this.updateTocBarPosition(t,t.rendition.currentLocation())}updateTocBarPosition(t,e){const o=Math.round(e.start.location/t.locations.length()*100);$(".toc-bar-entry.current-position").css("left",o+"%")}async applyTheme(){let t=await localforage.getItem("epube.fontSize"),e=await localforage.getItem("epube.fontFamily"),o=await localforage.getItem("epube.lineHeight");t=t?t+"px":"16px",e=e||"Arial",o=o?o+"%":"140%",console.log("style",e,t,o),console.log("applying default theme styles..."),this.book&&this.book.rendition&&this.book.rendition.themes.default({html:{"font-size":t,"font-family":"'"+e+"'","line-height":o,"text-align":"justify","text-indent":"1em"}});let a=await localforage.getItem("epube.theme")||"default";console.log("called for theme",a),"default"==a&&"undefined"!=typeof EpubeApp&&EpubeApp.isNightMode()&&(a="night"),console.log("setting main UI theme",a),$("body").attr("class","undefined"!=typeof EpubeApp?"is-epube-app":"").addClass("epube-reader theme-"+a).attr("data-is-loading","false"),"undefined"!=typeof EpubeApp&&window.setTimeout((function(){let t=window.getComputedStyle(document.querySelector("body"),null).getPropertyValue("background-color").match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/);t&&(console.log("sending bgcolor",t),EpubeApp.setStatusBarColor(parseInt(t[1]),parseInt(t[2]),parseInt(t[3])));t=window.getComputedStyle(document.querySelector(".header .title"),null).getPropertyValue("color").match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/),t&&(console.log("sending accent_color",t),EpubeApp.setAccentColor(parseInt(t[1]),parseInt(t[2]),parseInt(t[3])))}),250),this.book&&this.book.rendition&&this.book.rendition.getContents().forEach(n=>{console.log(`applying styles and theme ${a} to `,n),n.css("font-size",t),n.css("font-family","'"+e+"'"),n.css("line-height",o),n.css("text-align","justify"),$(n.document).find("body").attr("class","undefined"!=typeof EpubeApp?"is-epube-app":"").addClass("theme-"+a)})}hotkeyHandler(t){try{if($(".modal").is(":visible"))return;39!=t.which&&32!=t.which&&34!=t.which||(t.preventDefault(),this.nextPage()),37!=t.which&&33!=t.which||(t.preventDefault(),this.prevPage()),27==t.which&&(t.preventDefault(),this.showUI(!0))}catch(t){console.warn(t)}}resizeSideColumns(){let t=$("#reader").position().left;this.book&&this.book.rendition&&this.book.rendition.getContents().forEach(e=>{t+=parseInt(e.window.getComputedStyle(e.document.querySelector("body")).getPropertyValue("padding-left"))}),console.log(`resizing side columns to ${t} px`),$("#left, #right").width(t)}async markAsRead(){if(confirm("Mark book as read?")){$("#settings-modal").modal("hide");const t=100,e=this.book.locations.cfiFromPercentage(1),o=(new Date).getTime();if(this.isOnline()){const a=await $.post("backend.php",{op:"storelastread",page:t,cfi:e,id:this.urlParam("id"),timestamp:o});$(".lastread_input").val(a.page+"%")}await localforage.setItem(this.cacheId("lastread"),{cfi:e,page:t,total:t,timestamp:o}),await this.openLastRead()}}async close(){const t=this.book.rendition.currentLocation().start.cfi,e=Math.round(100*this.book.locations.percentageFromCfi(t)),o=(new Date).getTime();await localforage.setItem(this.cacheId("lastread"),{cfi:t,page:e,total:100,timestamp:o}),this.isOnline()?$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:e,cfi:t,timestamp:o},()=>{window.location.href=this.urlParam("rt")?"index.php?mode="+this.urlParam("rt"):"index.php"}).fail(()=>{window.location.href="index.php"}):window.location.href="index.php"}cacheId(t){return"epube-book."+this.urlParam("b")+(t?"."+t:"")}showUI(t){t?$(".header,.footer").fadeIn():$(".header,.footer").fadeOut()}toggleUI(){$(".header").is(":visible")?$(".header,.footer").fadeOut():$(".header,.footer").fadeIn()}async lookupWord(t,e,o){o&&(t=$(o).val()),t=t.replace(//g,""),console.log("lookupWord",t),$(".dict_result").html("Loading, please wait..."),$("#dict-modal").modal("show");try{const o=await $.post("backend.php",{op:"define",word:t});o&&($(".dict_result").html(o.result.join("<br/>")),$(".dict_query").val(t),e&&e())}catch(t){console.error(t),$(".dict_result").html(`Network error while looking up word: ${t.responseText}.`)}}search(){const t=$(".search_input").val(),e=$(".search_results");e.html(""),t&&(e.html("<li>Loading, please wait...</li>"),Promise.all(this.book.spine.spineItems.map(e=>e.load(this.book.load.bind(this.book)).then(e.find.bind(e,t)).finally(e.unload.bind(e)))).then(t=>Promise.resolve([].concat.apply([],t))).then(t=>{e.html(""),$.each(t,(t,o)=>{const a=$("<a>").attr("href","#").html("<b class='pull-right'>"+this.book.locations.locationFromCfi(o.cfi)+"</b>"+o.excerpt).attr("data-cfi",o.cfi).attr("data-id",o.id).on("click",()=>{this.book.rendition.display(a.attr("data-cfi"))});e.append($("<li>").append(a))})}))}nextPage(){this.book.rendition.next(),"undefined"!=typeof EpubeApp?EpubeApp.showActionBar(!1):localforage.getItem("epube.keep-ui-visible").then(t=>{t||this.showUI(!1)})}prevPage(){this.book.rendition.prev(),"undefined"!=typeof EpubeApp?EpubeApp.showActionBar(!1):localforage.getItem("epube.keep-ui-visible").then(t=>{t||this.showUI(!1)})}async openPrevious(t){const e=$(t).attr("data-location-cfi");e&&await this.book.rendition.display(e),$(t).fadeOut()}blockLastReadUpdate(){console.log("blocking last read updates..."),this._prevent_lastread_timeout&&window.clearTimeout(this._prevent_lastread_timeout),this._prevent_lastread_timeout=window.setTimeout(()=>{this._prevent_lastread=!1,this._prevent_lastread_timeout=!1,console.log("unblocked last read updates")},1e3),this._prevent_lastread=!0}async onRelocated(t,e){if(0==t.locations.length())return;const o=e.start.cfi,a=Math.round(100*t.locations.percentageFromCfi(o));$("#cur_page").text(Math.floor(e.start.location/10)),$("#total_pages").text(Math.floor(t.locations.length()/10)),$("#page_pct").text(Math.round(100*t.locations.percentageFromCfi(o))+"%"),this.updateTocBarPosition(t,e);const n=e.start.displayed;if(n&&($("#chapter_cur_page").text(n.page),$("#chapter_total_pages").text(n.total),n.total>0&&$("#chapter_pct").text(Math.round(n.page/n.total*100)+"%")),this.startup_finished&&this.last_stored_cfi!=o&&!this._prevent_lastread){const t=(new Date).getTime();console.log("storing lastread",a,o,t),await localforage.setItem(this.cacheId("lastread"),{cfi:o,page:a,total:100,timestamp:t}),this.isOnline()&&(console.log("updating remote lastread",o),this.last_stored_cfi=o,$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:a,cfi:o,timestamp:t}))}}async clearLastRead(){if(confirm("Reset reading progress for this book?")){$("#settings-modal").modal("hide");const t=this.book.locations.length(),e=(new Date).getTime();this.isOnline()&&await $.post("backend.php",{op:"storelastread",page:-1,cfi:"",id:this.urlParam("id"),timestamp:e}),await localforage.setItem(this.cacheId("lastread"),{cfi:"",page:0,total:t,timestamp:e}),await this.book.rendition.display(this.book.locations.cfiFromPercentage(0)),$(".lastread_input").val("0%")}}async resetLocations(){confirm("Reset stored pagination data? This will also reset reading progress.")&&($("#settings-modal").modal("hide"),await localforage.removeItem(this.cacheId("lastread")),await localforage.removeItem(this.cacheId("locations")),await $.post("backend.php",{op:"storelastread",page:-1,cfi:"",id:this.urlParam("id"),timestamp:(new Date).getTime()}),await $.post("backend.php",{op:"deletepagination",id:this.urlParam("id")}).catch(t=>console.log(t)),window.location.reload())}async openLastRead(){$(".loading").show(),$(".loading-message").html("Opening last read page…"),$("#settings-modal").modal("hide");const t=this.book.rendition;if(!t)return void console.error("no rendition to work on");let e=!1;const o=await localforage.getItem(this.cacheId("lastread"))||{};if(console.log("got local lastread",o),this.isOnline())try{const a=await $.post("backend.php",{op:"getlastread",id:this.urlParam("id")});console.log("got remote lastread",a),a&&a.cfi&&o.cfi!=a.cfi&&a.page>=(o.page||0)&&(console.log(`using remote lastread cfi ${a.cfi}: cfi is different and remote pct ${a.page}% is further than local pct ${o.page}%`),await localforage.setItem(this.cacheId("lastread"),{cfi:a.cfi,page:a.page,total:a.total,timestamp:a.timestamp}),e=await this.moveToCfiVerify(t,a.cfi))}catch(t){console.log("unable to get remote lastread, continuing..."),console.warn(t)}if(!e&&o&&o.cfi){console.log("using local lastread cfi: "+o.cfi);try{await this.moveToCfiVerify(t,o.cfi)}catch(t){console.warn(t)}}$(".loading").fadeOut()}calculateCfiDelta(t,e){const o=new ePub.CFI(t),a=new ePub.CFI(e);if(console.log("calculateCfiDelta",o,a),o.path.steps.length!=a.path.steps.length)return-1;let n=0;for(let t=0;t<o.path.steps.length;t++){if(o.path.steps[t].type!=a.path.steps[t].type)return-1;if(o.path.steps[t].id!=a.path.steps[t].id)return-1;null===o.path.steps[t].id&&"element"===o.path.steps[t].type&&(n+=Math.abs(o.path.steps[t].index-a.path.steps[t].index))}return n}async moveToCfiVerify(t,e,o=5,a=5){for(let n=1;n<o;n++){let i;this.blockLastReadUpdate(),console.log(`trying to open ${e}: attempt ${n} of ${o}...`),await t.display(e);try{i=t.currentLocation().start.cfi}catch(t){console.warn("location not yet available, will retry:",t)}try{const t=this.calculateCfiDelta(e,i);if(console.log(`opened cfi ${i} expected ${e}; delta: ${t}`),i==e||-1!=t&&t<=a)return console.log("cfi move verified!"),!0}catch(t){console.warn("exception while parsing cfi, will retry: ",t)}}return!1}async onThemeChanged(t){const e=$(t).val();await localforage.setItem("epube.theme",e),this.applyTheme()}async onLineHeightChanged(t){const e=$(t).val();await localforage.setItem("epube.lineHeight",e),this.applyTheme()}async onTextSizeChanged(t){const e=$(t).val();await localforage.setItem("epube.fontSize",e),this.applyTheme()}async onFontChanged(t){const e=$(t).val();await localforage.setItem("epube.fontFamily",e),this.applyTheme()}}class ReaderLoader{_res_data=[];CACHE_NAME="epube-v3";async init(){"undefined"!=typeof EpubeApp&&$("body").addClass("epube-app");const t=[];let e=!1;const o=await caches.open(this.CACHE_NAME);return(await o.keys()).forEach(o=>{if(!o.url.match("backend.php")){console.log("[loader] loading resource",o.url);const a=fetch(o.url).then(async t=>{if(t.ok){const e=new URL(t.url);if(e.searchParams.delete("ts"),t.url.match("\\.ttf|\\.otf")){const o=await t.blob();console.log("[loader] storing blob",e.href),this._res_data[e.toString()]=URL.createObjectURL(o)}else{const o=await t.text();console.log("[loader] storing text",e.href),this._res_data[e.toString()]=o}}else console.warn("[loader] failed for resource",o.url,t),$(".loading-message").html(`Unable to load resource.<br/><small>${o.url}</small>`),e=!0});t.push(a)}}),await Promise.allSettled(t),console.log("[loader] resource load complete, failed: ",e),e}} \ No newline at end of file diff --git a/dist/appcommon.js b/dist/appcommon.js new file mode 100644 index 0000000..c457e6b --- /dev/null +++ b/dist/appcommon.js @@ -0,0 +1,38 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AppCommon = void 0; +class AppCommon { + urlParam(name) { + try { + const results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href); + return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0; + } + catch (e) { + return 0; + } + } + isOnline() { + if (typeof EpubeApp != "undefined" && typeof EpubeApp.isOnline != "undefined") + return EpubeApp.isOnline(); + else + return navigator.onLine; + } + initNightMode() { + if (typeof EpubeApp != "undefined") { + this.applyNightMode(EpubeApp.isNightMode()); + return; + } + if (window.matchMedia) { + const mql = window.matchMedia('(prefers-color-scheme: dark)'); + mql.addEventListener("change", () => { + this.applyNightMode(mql.matches); + }); + this.applyNightMode(mql.matches); + } + } + applyNightMode(is_night) { + console.log("night mode changed to", is_night); + $("#theme_css").attr("href", "lib/bootstrap/v3/css/" + (is_night ? "theme-dark.min.css" : "bootstrap-theme.min.css")); + } +} +exports.AppCommon = AppCommon; diff --git a/dist/cookie.js b/dist/cookie.js new file mode 100644 index 0000000..fb01989 --- /dev/null +++ b/dist/cookie.js @@ -0,0 +1,28 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Cookie = void 0; +class Cookie { + static set(name, value, lifetime) { + const d = new Date(); + d.setTime(d.getTime() + lifetime * 1000); + const expires = "expires=" + d.toUTCString(); + document.cookie = name + "=" + encodeURIComponent(value) + "; " + expires; + } + static get(name) { + name = name + "="; + const ca = document.cookie.split(';'); + for (let i = 0; i < ca.length; i++) { + let c = ca[i]; + while (c.charAt(0) == ' ') + c = c.substring(1); + if (c.indexOf(name) == 0) + return decodeURIComponent(c.substring(name.length, c.length)); + } + return ""; + } + static delete(name) { + const expires = "expires=Thu, 01-Jan-1970 00:00:01 GMT"; + document.cookie = name + "=; " + expires; + } +} +exports.Cookie = Cookie; diff --git a/dist/reader.js b/dist/reader.js new file mode 100644 index 0000000..053f495 --- /dev/null +++ b/dist/reader.js @@ -0,0 +1,1346 @@ +'use strict'; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ReaderClass = void 0; +const DEFAULT_FONT_SIZE = 16; +const DEFAULT_FONT_FAMILY = "Arial"; +const DEFAULT_LINE_HEIGHT = 140; +const MIN_LENGTH_TO_JUSTIFY = 32; /* characters */ +const LOCATION_DIVISOR = 10; +const PAGE_RESET_PROGRESS = -1; +const appcommon_1 = require("./appcommon"); +const cookie_1 = require("./cookie"); +class ReaderClass extends appcommon_1.AppCommon { + constructor() { + super(...arguments); + this.csrf_token = ""; + this.last_stored_cfi = ""; + this.startup_finished = false; + this.open_last_read_when_displayed = true; + this.hyphenate = { en: null, ru: null }; + } + async init() { + this.csrf_token = cookie_1.Cookie.get('epube_csrf_token'); + console.log('setting prefilter for token', this.csrf_token); + $.ajaxPrefilter((options, originalOptions /*, jqXHR*/) => { + if (originalOptions.type !== 'post' || options.type !== 'post') { + return; + } + const datatype = typeof originalOptions.data; + if (datatype == 'object') + options.data = $.param($.extend(originalOptions.data, { "csrf_token": this.csrf_token })); + else if (datatype == 'string') + options.data = originalOptions.data + "&csrf_token=" + encodeURIComponent(this.csrf_token); + console.log('>>>', options); + }); + $(document).on("keyup", (e) => { + this.hotkeyHandler(e); + }); + $(".close_book").on("click", () => { + this.close(); + }); + $("#left").on("mouseup", () => { + this.prevPage(); + }); + $(".search_input").on("change", () => { + this.search(); + }); + $(".prev_location_btn").on("click", (evt) => { + this.openPrevious(evt.target); + }); + $("#right").on("mouseup", () => { + this.nextPage(); + }); + this.loader = new ReaderLoader(); + const load_failed = await this.loader.init(); + console.log('[init] load failed', load_failed); + if (!load_failed) { + this.initSecondStage(); + } + else { + this.applyTheme(); + $(".loading-message").text('Resource loader failed to initialize.'); + } + } + // another method, maybe use this: window.matchMedia("(pointer: coarse)").matches + // https://stackoverflow.com/questions/4817029/whats-an-optimal-or-efficient-way-to-detect-a-touch-screen-device-using-javas + isTouchDevice() { + return ('ontouchstart' in window) || (navigator.maxTouchPoints > 0); + } + /** + * @param {boolean} offline + */ + onOfflineModeChanged(offline) { + console.log('onOfflineModeChanged', offline); + if (!offline && this.book) { + console.log("we're online, storing lastread"); + const currentCfi = this.book.rendition.currentLocation().start.cfi; + const currentPage = Math.round(this.book.locations.percentageFromCfi(currentCfi) * 100); // TODO wtf + $.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: currentPage, + cfi: currentCfi, timestamp: new Date().getTime() }, function () { + // + }) + .fail(function (e) { + if (e && e.status == 401) { + window.location.href = "index.php"; + } + }); + } + } + async initSecondStage() { + if (typeof EpubeApp != "undefined") { + EpubeApp.setPage("PAGE_READER"); + } + else { + $(window).on('online', () => { + this.onOfflineModeChanged(false); + }); + $(window).on('offline', () => { + this.onOfflineModeChanged(true); + }); + } + this.applyTheme(); + const bookinfo = await localforage.getItem(this.cacheId()); + if (!bookinfo) { + const bookId = this.urlParam("b"); + console.log('requesting bookinfo for book', bookId); + try { + const resp = await $.post("backend.php", { op: "getinfo", id: bookId }); + if (resp.has_cover) { + const cover = await fetch("backend.php?op=cover&id=" + bookId); + if (cover.ok) + await localforage.setItem(this.cacheId('cover'), cover.blob()); + } + await localforage.setItem(this.cacheId(), resp); + console.log('bookinfo saved'); + } + catch (e) { + $(".loading-message").html(`Unable to load book info.<br/><small>${e.responseText}</small>`); + return; + } + } + console.log('trying to load book...'); + let book_data = await localforage.getItem(this.cacheId("book")); + if (!book_data) { + console.log("local data not found, loading from network..."); + $(".loading-message").html("Downloading book…"); + const book_resp = await fetch("backend.php?op=download&id=" + this.urlParam("id")); + if (book_resp.ok) { + book_data = await book_resp.blob(); + if (book_data) { + await localforage.setItem(this.cacheId('book'), book_data); + console.log('saved local data for book'); + } + else { + $(".loading-message").html("Unable to get book blob data."); + return; + } + } + else { + $(".loading-message").html(`Unable to download book: ${book_resp.status}`); + return; + } + } + const fileReader = new FileReader(); + const _reader = this; + fileReader.onload = function () { + try { + _reader.openBookData(this.result); + } + catch (e) { + console.error(e); + $(".loading-message").html("Unable to load book blob: " + e); + } + }; + fileReader.onerror = (e) => { + console.log('filereader error', e); + $(".loading-message").html("Unable to open book.<br/><small>" + e + "</small>"); + }; + fileReader.readAsArrayBuffer(book_data); + } + async openBookData(book_data) { + // @ts-ignore + this.book = new ePub.Book(); + try { + await this.book.open(book_data); + } + catch (e) { + console.error(e); + $(".loading-message").html("Unable to open book.<br/><small>" + e.message + "</small>"); + return; + } + await this.book.ready; + console.log('book is ready'); + await this.showBookInfo(this.book); + await this.loadLocations(this.book); + const rendition = this.book.renderTo("reader", { + width: '100%', + height: '100%', + allowScriptedContent: false, + minSpreadWidth: 961 + }); + $(".location").on('click', async () => { + const current = Math.floor(rendition.currentLocation().start.location / LOCATION_DIVISOR); + const total = Math.floor(this.book.locations.length() / LOCATION_DIVISOR); + const page = prompt("Jump to location [1-" + total + "]", String(current)); + if (page) + await rendition.display(this.book.locations._locations[parseInt(page) * LOCATION_DIVISOR]); + }); + const enable_hyphens = await localforage.getItem("epube.enable-hyphens"); + if (enable_hyphens) { + /* global hyphenationPatternsEnUs, hyphenationPatternsRu, createHyphenator */ + this.hyphenate.en = createHyphenator(hyphenationPatternsEnUs, { html: true }); + this.hyphenate.ru = createHyphenator(hyphenationPatternsRu, { html: true }); + } + this.initRenditionHooks(this.book, rendition); + this.initModals(); + this.initToc(this.book); + // open first page at startup, lastread will open when it is rendered + this.blockLastReadUpdate(); + await rendition.display(); + console.log('startup finished'); + this.startup_finished = true; + } + /** + * @param {ePub.Book} book + */ + async showBookInfo(book) { + const bookinfo = await localforage.getItem(this.cacheId()); + let title; + let author; + if (bookinfo) { + title = bookinfo.title; + author = bookinfo.author_sort; + } + else { + const metadata = book.packaging.metadata; + title = metadata.title; + author = metadata.creator; + } + document.title = title + " – " + author + " – The Epube"; + $(".title") + .text(title) + .attr("title", title + " – " + author); + if (typeof EpubeApp != "undefined") { + EpubeApp.setTitle(title); + EpubeApp.showActionBar(false); + } + } + /** + * @param {ePub.Book} book + */ + async loadLocations(book) { + let locations = await localforage.getItem(this.cacheId("locations")); + // legacy format is array of objects {cfi: ..., page: ...} + if (locations && typeof locations[0] == "string") { + console.log('loading local locations...'); + try { + await book.locations.load(locations); + return; + } + catch (e) { + console.warn(e); + } + } + if (this.isOnline()) { + console.log("downloading locations..."); + $(".loading-message").html("Downloading locations…"); + const resp = await fetch("backend.php?op=getpagination&id=" + this.urlParam("id")); + if (resp.ok) { + console.log("got locations from server"); + // if this doesn't load, we'll generate locations and save them + try { + locations = await resp.json(); + } + catch (e) { + console.warn(e); + } + if (locations && typeof locations[0] == "string") { + console.log('saving locations locally...'); + await localforage.setItem(this.cacheId("locations"), locations); + try { + book.locations.load(locations); + return; + } + catch (e) { + console.warn(e); + } + } + } + } + $(".loading-message").html("Preparing locations…"); + let generate_queue_max = 0; + locations = await book.locations.generate(100, (queue) => { + if (!generate_queue_max) + generate_queue_max = queue.length(); + // what if there's only one section or something and queue is already zero + if (generate_queue_max > 0) { + const queue_pct = Math.round((1 - queue.length() / generate_queue_max) * 100); // TODO un-wtf + $(".loading-message").html(`Preparing locations (${queue_pct}%)…`); + } + }); + $.post("backend.php", { op: "storepagination", id: this.urlParam("id"), + payload: JSON.stringify(locations), total: 100 }); + await localforage.setItem(this.cacheId("locations"), locations); + } + /** + * @param {ePub.Book} book + * @param {ePub.Rendition} rendition + */ + initRenditionHooks(book, rendition) { + console.log('initRenditionHooks'); + book.spine.hooks.content.register((doc /*, section */) => { + this.cleanupEmbeddedStyles(doc); + }); + rendition.hooks.content.register(async (contents) => { + contents.on("linkClicked", (href) => { + console.log('linkClicked', href); + this.blockLastReadUpdate(); + if (href.indexOf("://") == -1) { + $(".prev_location_btn") + .attr("data-location-cfi", rendition.currentLocation().start.cfi) + .show(); + window.requestAnimationFrame(() => { + this.showUI(true); + }); + } + }); + contents.on("selected", async (cfiRange) => { + if (this.isOnline()) { + const range = await book.getRange(cfiRange); + const selection = range.endContainer.data.substring(range.startOffset, range.endOffset); + console.log('selected', cfiRange, selection); + if (selection.match(/^[\w]+$/)) { + this.lookupWord(selection, () => { + if (typeof EpubeApp != "undefined") + EpubeApp.showActionBar(false); + contents.window.requestAnimationFrame(() => { + contents.window.getSelection().removeAllRanges(); + }); + }); + } + } + }); + // get our stuff from resource loader and inject into iframe content + const base_url = window.location.href.match(/^.*\//)[0]; + $(contents.document.head) + .append($("<style type='text/css'>") + .text(this.generateFontsCss(base_url))); + $(contents.document.head) + .append($("<style type='text/css'>") + .text(this.loader._res_data[base_url + 'dist/reader_iframe.min.css'])); + const theme = await localforage.getItem("epube.theme") || 'default'; + $(contents.document).find("body") + .attr("class", typeof EpubeApp != "undefined" ? "is-epube-app" : "") + .addClass("theme-" + theme); + console.log('contents', contents); + $(contents.window).on("click tap", (evt) => { + if (evt.button == 0) { + if ($(".modal").is(":visible")) + return; + if (typeof EpubeApp != "undefined") + EpubeApp.toggleActionBar(); + else + this.showUI(true); + } + }); + $(contents.window).on("wheel", async (evt) => { + if (await localforage.getItem("epube.enable-wheel")) { + if (evt.originalEvent.deltaY > 0) { + this.nextPage(); + } + else if (evt.originalEvent.deltaY < 0) { + this.prevPage(); + } + } + }); + // need to figure out how to do swipes safely (invisible overlay which passes text selection?) + /* if (typeof EpubeApp != "undefined" || Reader.isTouchDevice()) { + $(window).on("swipeleft", function() { + console.log('swipe left'); + + this.nextPage(); + }); + + $(window).on("swiperight", function() { + console.log('swipe right'); + + this.prevPage(); + }); + } */ + }); + rendition.on("keyup", (e) => { + this.hotkeyHandler(e); + }); + rendition.on('resized', ( /*chapter*/) => { + console.log('rendition resized'); + this.blockLastReadUpdate(); + this.open_last_read_when_displayed = true; + }); + rendition.on('rendered', async ( /* section */) => { + console.log('rendition rendered'); + this.applyTheme(); + this.resizeSideColumns(); + try { + const location = rendition.currentLocation(); + if (location.start) { + const cur_href = book.canonical(location.start.href); + let toc_entry = { label: "" }; + $.each(this.flattenToc(book), function (i, r) { + if (book.spine.get(r.href).canonical == cur_href) { + toc_entry = r; + return; + } + }); + if (toc_entry && toc_entry.label) + $(".chapter_title").html(toc_entry.label.trim() + " | "); + this.generateTocBar(book, this.flattenToc(book)); + } + } + catch (e) { + console.warn(e); + } + if (this.open_last_read_when_displayed) { + this.open_last_read_when_displayed = false; + await this.openLastRead(); + } + }); + // this seems to be called a lot more than rendered + rendition.on('displayed', function ( /*chapter*/) { + console.log('rendition displayed'); + }); + rendition.on('relocated', (/** @type {ePub.Location} */ location) => this.onRelocated(book, location)); + } + initModals() { + $('#settings-modal').on('shown.bs.modal', async () => { + const last_read = await localforage.getItem(this.cacheId("lastread")); + if (last_read && last_read.cfi) { + $(".lastread_input") + .val(last_read.page + '%') + .attr('title', `[local] ${last_read.cfi}`); + } + $(".clear_last_read") + .off("click") + .on("click", () => { + this.clearLastRead(); + }); + $(".open_last_read") + .off("click") + .on("click", () => { + this.openLastRead(); + }); + $(".mark_as_read") + .off("click") + .on("click", () => { + this.markAsRead(); + }); + $(".reset_locations") + .off("click") + .on("click", () => { + this.resetLocations(); + }); + if (navigator.onLine) + $.post("backend.php", { op: "getlastread", id: this.urlParam("id") }, (data) => { + $(".lastread_input") + .val(data.page + '%') + .attr('title', `[remote] ${data.cfi}`); + }); + $(".font_family") + .off("change") + .on("change", (evt) => { + this.onFontChanged(evt.target); + }); + $(".font_size") + .off("change") + .on("change", (evt) => { + this.onTextSizeChanged(evt.target); + }); + $(".line_height") + .off("change") + .on("change", (evt) => { + this.onLineHeightChanged(evt.target); + }); + $(".theme_name") + .off("change") + .on("change", (evt) => { + this.onThemeChanged(evt.target); + }); + $(".enable_hyphens_checkbox") + .attr("checked", await localforage.getItem("epube.enable-hyphens")) + .off("click") + .on("click", (evt) => { + localforage.setItem("epube.enable-hyphens", evt.target.checked); + if (confirm("Toggling hyphens requires page reload. Reload now?")) { + window.location.reload(); + } + }); + $(".enable_wheel_checkbox") + .attr("checked", await localforage.getItem("epube.enable-wheel")) + .off("click") + .on("click", (evt) => { + localforage.setItem("epube.enable-wheel", evt.target.checked); + }); + if (typeof EpubeApp != "undefined") { + $(".keep_ui_checkbox").parent().parent().hide(); + } + else { + $(".keep_ui_checkbox") + .attr("checked", await localforage.getItem("epube.keep-ui-visible")) + .off("click") + .on("click", (evt) => { + localforage.setItem("epube.keep-ui-visible", evt.target.checked); + }); + } + const stamp = String(await localforage.getItem("epube.cache-timestamp")); + const version = await localforage.getItem("epube.cache-version"); + $(".last-mod-timestamp").html(`${version} + — ${parseInt(stamp) ? new Date(parseInt(stamp) * 1000).toLocaleString("en-GB") : "Unknown"} + (${this.isOnline() ? `<span class='text-success'>Online</span>` : `<span class='text-danger'>Offline</span>`}) + `); + $(".font_family").val(await localforage.getItem("epube.fontFamily") || DEFAULT_FONT_FAMILY); + $(".theme_name").val(await localforage.getItem("epube.theme") || 'default'); + const zoom = $(".font_size").html(""); + for (let i = 10; i <= 32; i++) { + const opt = $("<option>").val(i).html(i + " px"); + zoom.append(opt); + } + zoom.val(await localforage.getItem("epube.fontSize") || DEFAULT_FONT_SIZE); + const line_height = $(".line_height").html(""); + for (let i = 100; i <= 220; i += 10) { + const opt = $("<option>").val(i).html(i + "%"); + line_height.append(opt); + } + line_height.val(await localforage.getItem("epube.lineHeight") || DEFAULT_LINE_HEIGHT); + }); + $('#dict-modal').on('shown.bs.modal', () => { + $(".dict_query") + .off("change") + .on("change", () => { + this.lookupWord(null, null, '.dict_query'); + }); + $(".dict_result").scrollTop(0); + }); + // TODO: make configurable + $(".dict_search_btn").on("click", function () { + $("#dict-modal").modal('hide'); + window.open("https://duckduckgo.com/?q=" + $(".dict_query").val()); + }); + } + initToc(book) { + const _reader = this; + function toc_loc_msg(href) { + try { + const cfiBase = book.spine.get(href).cfiBase; + const loc = book.locations._locations.find(function (k) { + return k.indexOf(cfiBase) != -1; + }); + return Math.round(_reader.book.locations.locationFromCfi(loc) / LOCATION_DIVISOR); + } + catch (e) { + console.warn(e); + } + return ""; + } + function process_toc_sublist(row, list, nest) { + if (nest == 3) + return false; + if (row.subitems) { + const sublist = $("<ul class='toc_sublist list-unstyled'>"); + $.each(row.subitems, function (i, row) { + const a = $("<a>") + .attr('href', '#') + .html("<b class='pull-right'>" + toc_loc_msg(row.href) + "</b>" + row.label) + .attr('data-href', row.href) + .click(function () { + book.rendition.display(a.attr('data-href')); + }); + sublist.append($("<li>").append(a)); + process_toc_sublist(row, sublist, nest + 1); + }); + list.append(sublist); + } + } + $('#toc-modal').on('shown.bs.modal', function () { + const toc = book.navigation.toc; + const list = $(".toc_list"); + list.html(""); + $.each(toc, function (i, row) { + // if anything fails here the toc entry is likely useless anyway (i.e. no cfi) + try { + const a = $("<a>") + .attr('href', '#') + .html("<b class='pull-right'>" + toc_loc_msg(row.href) + "</b>" + row.label) + .attr('data-href', row.href) + .click(function () { + book.rendition.display(a.attr('data-href')); + }); + list.append($("<li>").append(a)); + process_toc_sublist(row, list, 0); + } + catch (e) { + console.warn(e); + } + }); + // well the toc didn't work out, might as well generate one + if (list.children().length <= 1) { + list.html(""); + $.each(book.spine.items, function (i, row) { + const a = $("<a>") + .attr('href', '#') + .attr('title', row.url) + // @ts-ignore + .html(`Section ${i + 1}`) + .attr('data-href', row.href) + .on('click', () => { + book.rendition.display(a.attr('data-href')); + }); + list.append($("<li>").append(a)); + }); + } + }); + } + /* embedded styles may conflict with our font sizes, etc */ + cleanupEmbeddedStyles(doc) { + $(doc).find("p") + // @ts-ignore + .filter((i, e) => (($(e).text().length >= MIN_LENGTH_TO_JUSTIFY) ? e : null)) + .css("text-align", "justify"); + $(doc).find("html") + .attr("class", ""); + $(doc).find("pre") + .css("white-space", "pre-wrap"); + $(doc).find("a, p, span, em, i, strong, b, body, header, section, div, big, small, table, tr, td, th, ul, ol, li") + .attr("class", "") + .css("font-family", "inherit") + .css("font-size", "inherit") + .css("line-height", "inherit") + .css("color", "") + .css("border", "none ! important") + .css("background", "") + .css("background-color", "") + .attr("width", "") + .attr("height", ""); + // same as above except for allowed font-size + $(doc).find("h1, h2, h3, h4, h5") + .attr("class", "") + .css("font-family", "inherit") + .css("color", "") + .css("border", "none ! important") + .css("background", "") + .css("background-color", ""); + if (typeof this.hyphenate.en != "undefined") { + $(doc).find('p, div').each((i, elem) => { + const p = $(elem); + p.html(this.hyphenate.en(p.html())); + p.html(this.hyphenate.ru(p.html())); + }); + } + } + generateFontsCss(base_url) { + return ` + /** Calibri */ + + @font-face { + font-family: 'Calibri'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/calibriz.ttf']}); + font-style: italic; + font-weight : 700; + } + + @font-face { + font-family: 'Calibri'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/calibrib.ttf']}); + font-style: normal; + font-weight : 700; + } + + @font-face { + font-family: 'Calibri'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/calibrii.ttf']}); + font-style: italic; + font-weight : 400; + } + + @font-face { + font-family: 'Calibri'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/calibri.ttf']}); + font-style: normal; + font-weight : 400; + } + + /** Cambria */ + + @font-face { + font-family: 'Cambria'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/cambriab.ttf']}); + font-style: normal; + font-weight : 700; + } + + @font-face { + font-family: 'Cambria'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/cambriaz.ttf']}); + font-style: italic; + font-weight : 700; + } + + @font-face { + font-family: 'Cambria'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/cambriai.ttf']}); + font-style: italic; + font-weight : 400; + } + + @font-face { + font-family: 'Cambria'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/cambria.ttf']}); + font-style: normal; + font-weight : 400; + } + + /** Caecilia */ + + @font-face { + font-family: Caecilia; + src: url(${this.loader._res_data[base_url + 'lib/fonts/caecilia.ttf']}); + font-weight : normal; + } + + @font-face { + font-family: Caecilia; + src: url(${this.loader._res_data[base_url + 'lib/fonts/caeciliab.ttf']}); + font-weight : bold; + } + + @font-face { + font-family: Caecilia; + src: url(${this.loader._res_data[base_url + 'lib/fonts/caeciliai.ttf']}); + font-style : italic; + } + + /** Palatino */ + + @font-face { + font-family: 'Palatino'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/palab.ttf']}); + font-style: normal; + font-weight : 700; + } + + @font-face { + font-family: 'Palatino'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/palabi.ttf']}); + font-style: italic; + font-weight : 700; + } + + @font-face { + font-family: 'Palatino'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/palai.ttf']}); + font-style: italic; + font-weight : 400; + } + + @font-face { + font-family: 'Palatino'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/pala.ttf']}); + font-style: normal; + font-weight : 400; + } + + /** Consolas */ + + @font-face { + font-family: 'Consolas'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/consolab.ttf']}); + font-style: normal; + font-weight : 700; + } + + @font-face { + font-family: 'Consolas'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/consolaz.ttf']}); + font-style: italic; + font-weight : 700; + } + + @font-face { + font-family: 'Consolas'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/consolai.ttf']}); + font-style: italic; + font-weight : 400; + } + + @font-face { + font-family: 'Consolas'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/consola.ttf']}); + font-style: normal; + font-weight : 400; + } + + /** IBM Plex Mono */ + + @font-face { + font-family: 'IBM Plex Mono'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/IBMPlexMono-Bold.otf']}); + font-style: normal; + font-weight : 700; + } + + @font-face { + font-family: 'IBM Plex Mono'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/IBMPlexMono-BoldItalic.otf']}); + font-style: italic; + font-weight : 700; + } + + @font-face { + font-family: 'IBM Plex Mono'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/IBMPlexMono-TextItalic.otf']}); + font-style: italic; + font-weight : 400; + } + + @font-face { + font-family: 'IBM Plex Mono'; + src: url(${this.loader._res_data[base_url + 'lib/fonts/IBMPlexMono-Text.otf']}); + font-style: normal; + font-weight : 400; + } + `; + } + flattenTocSubItems(entry, nest) { + let rv = []; + if (nest == 3) + return false; + if (entry.subitems) { + $.each(entry.subitems, (i, r) => { + r._nest = nest; + rv.push(r); + rv = rv.concat(this.flattenTocSubItems(r, nest + 1)); + }); + } + return rv; + } + /** + * @param { ePub.Book } book + * + * @returns { ePub.NavItem[] } + */ + flattenToc(book) { + if (this._flattened_toc) { + return this._flattened_toc; + } + else { + let rv = []; + $.each(book.navigation.toc, (i, r) => { + // @ts-ignore + r._nest = 0; + rv.push(r); + rv = rv.concat(this.flattenTocSubItems(r, 1)); + }); + this._flattened_toc = rv; + return rv; + } + } + /** + * @param { ePub.Book } book + * @param { any[] } toc + */ + generateTocBar(book, toc) { + $(".spacer") + .html(""); + $.each(toc, function (i, te) { + try { + const cfiBase = book.spine.get(te.href).cfiBase; + const loc = book.locations._locations.find(function (k) { + return k.indexOf(cfiBase) != -1; + }); + if (loc) { + const pct = Math.round(book.locations.percentageFromCfi(loc) * 100); + $(".spacer").append($("<div class='toc-bar-entry'>") + .attr('data-nest-level', te._nest) + .css('left', pct + '%') + .css('_width', (3 - te._nest) + "px") + .attr("title", te.label)); + } + } + catch (e) { + console.warn(e); + } + }); + $(".spacer").append($("<div class='toc-bar-entry current-position'>")); + this.updateTocBarPosition(book, book.rendition.currentLocation()); + } + updateTocBarPosition(book, location) { + const cur_pct = Math.round(location.start.location / book.locations.length() * 100); + $(".toc-bar-entry.current-position") + .css('left', cur_pct + '%'); + } + async applyTheme() { + let fontSize = await localforage.getItem("epube.fontSize"); + let fontFamily = await localforage.getItem("epube.fontFamily"); + let lineHeight = await localforage.getItem("epube.lineHeight"); + fontSize = fontSize ? fontSize + "px" : DEFAULT_FONT_SIZE + "px"; + fontFamily = fontFamily ? fontFamily : DEFAULT_FONT_FAMILY; + lineHeight = lineHeight ? lineHeight + "%" : DEFAULT_LINE_HEIGHT + "%"; + console.log('style', fontFamily, fontSize, lineHeight); + console.log('applying default theme styles...'); + if (this.book && this.book.rendition) + this.book.rendition.themes.default({ + html: { + 'font-size': fontSize, + 'font-family': "'" + fontFamily + "'", + 'line-height': lineHeight, + 'text-align': 'justify', + 'text-indent': '1em' + } + }); + let theme = await localforage.getItem("epube.theme") || "default"; + console.log('called for theme', theme); + if (theme == "default" && typeof EpubeApp != "undefined") + if (EpubeApp.isNightMode()) + theme = "night"; + console.log('setting main UI theme', theme); + $("body") + .attr("class", typeof EpubeApp != "undefined" ? "is-epube-app" : "") + .addClass("epube-reader theme-" + theme) + .attr("data-is-loading", "false"); + if (typeof EpubeApp != "undefined") { + window.setTimeout(function () { + const bg_color = window.getComputedStyle(document.querySelector("body"), null) + .getPropertyValue("background-color"); + let match = bg_color.match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/); + if (match) { + console.log("sending bgcolor", match); + EpubeApp.setStatusBarColor(parseInt(match[1]), parseInt(match[2]), parseInt(match[3])); + } + const accent_color = window.getComputedStyle(document.querySelector(".header .title"), null) + .getPropertyValue("color"); + match = accent_color.match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/); + if (match) { + console.log("sending accent_color", match); + EpubeApp.setAccentColor(parseInt(match[1]), parseInt(match[2]), parseInt(match[3])); + } + }, 250); + } + if (this.book && this.book.rendition) + this.book.rendition.getContents().forEach((rendition) => { + console.log(`applying styles and theme ${theme} to `, rendition); + rendition.css("font-size", fontSize); + rendition.css("font-family", "'" + fontFamily + "'"); + rendition.css("line-height", lineHeight); + rendition.css("text-align", 'justify'); + $(rendition.document).find("body") + .attr("class", typeof EpubeApp != "undefined" ? "is-epube-app" : "") + .addClass("theme-" + theme); + }); + } + hotkeyHandler(e) { + try { + //console.log('K3:' + e.which, e); + if ($(".modal").is(":visible")) + return; + // right or space or pagedown + if (e.which == 39 || e.which == 32 || e.which == 34) { + e.preventDefault(); + this.nextPage(); + } + // left or pageup + if (e.which == 37 || e.which == 33) { + e.preventDefault(); + this.prevPage(); + } + // esc + if (e.which == 27) { + e.preventDefault(); + this.showUI(true); + } + } + catch (e) { + console.warn(e); + } + } + resizeSideColumns() { + let width = $("#reader").position().left; + if (this.book && this.book.rendition) + this.book.rendition.getContents().forEach((rendition) => { + width += parseInt(rendition.window.getComputedStyle(rendition.document.querySelector('body')).getPropertyValue('padding-left')); + }); + console.log(`resizing side columns to ${width} px`); + $("#left, #right").width(width); + } + async markAsRead() { + if (confirm("Mark book as read?")) { + $("#settings-modal").modal('hide'); + const total = 100; + const lastCfi = this.book.locations.cfiFromPercentage(1); + const lastread_timestamp = new Date().getTime(); + if (this.isOnline()) { + const data = await $.post("backend.php", { op: "storelastread", page: total, cfi: lastCfi, id: this.urlParam("id"), timestamp: lastread_timestamp }); + $(".lastread_input").val(data.page + '%'); + } + await localforage.setItem(this.cacheId("lastread"), { cfi: lastCfi, page: total, total: total, timestamp: lastread_timestamp }); + await this.openLastRead(); + } + } + async close() { + const location = this.book.rendition.currentLocation(); + const currentCfi = location.start.cfi; + const currentPage = Math.round(this.book.locations.percentageFromCfi(currentCfi) * 100); + const totalPages = 100; + const lastread_timestamp = new Date().getTime(); + await localforage.setItem(this.cacheId("lastread"), { cfi: currentCfi, page: currentPage, total: totalPages, timestamp: lastread_timestamp }); + if (this.isOnline()) { + $.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: currentPage, + cfi: currentCfi, timestamp: lastread_timestamp }, () => { + window.location.href = this.urlParam("rt") ? "index.php?mode=" + this.urlParam("rt") : "index.php"; + }) + .fail(() => { + window.location.href = "index.php"; + }); + } + else { + window.location.href = "index.php"; + } + } + cacheId(suffix = "") { + return "epube-book." + this.urlParam("b") + (suffix ? "." + suffix : ""); + } + showUI(show) { + if (show) + $(".header,.footer").fadeIn(); + else + $(".header,.footer").fadeOut(); + } + toggleUI() { + if ($(".header").is(":visible")) + $(".header,.footer").fadeOut(); + else + $(".header,.footer").fadeIn(); + } + async lookupWord(word, callback, elem = null) { + if (elem) + word = $(elem).val(); + word = word.replace(//g, ""); + console.log('lookupWord', word); + $(".dict_result").html('Loading, please wait...'); + $("#dict-modal").modal('show'); + try { + const data = await $.post("backend.php", { op: 'define', word: word }); + if (data) { + $(".dict_result").html(data.result.join("<br/>")); + $(".dict_query").val(word); + if (callback) + callback(); + } + } + catch (e) { + console.error(e); + $(".dict_result").html(`Network error while looking up word: ${e.responseText}.`); + } + } + search() { + const query = $(".search_input").val(); + const list = $(".search_results"); + list.html(""); + if (query) { + list.html("<li>Loading, please wait...</li>"); + /* eslint-disable prefer-spread */ + Promise.all(this.book.spine.spineItems.map((item) => item.load(this.book.load.bind(this.book)) + // @ts-ignore TODO something wrong with the types (?) + .then(item.find.bind(item, query)) + .finally(item.unload.bind(item)))) + .then((results) => Promise.resolve([].concat.apply([], results))) + .then((results) => { + list.html(""); + $.each(results, (i, row) => { + const a = $("<a>") + .attr('href', '#') + .html("<b class='pull-right'>" + this.book.locations.locationFromCfi(row.cfi) + "</b>" + row.excerpt) + .attr('data-cfi', row.cfi) + .attr('data-id', row.id) + .on('click', () => { + this.book.rendition.display(a.attr('data-cfi')); + }); + list.append($("<li>").append(a)); + }); + }); + } + } + nextPage() { + this.book.rendition.next(); + if (typeof EpubeApp != "undefined") + EpubeApp.showActionBar(false); + else + localforage.getItem("epube.keep-ui-visible").then((keep) => { + if (!keep) + this.showUI(false); + }); + } + prevPage() { + this.book.rendition.prev(); + if (typeof EpubeApp != "undefined") + EpubeApp.showActionBar(false); + else + localforage.getItem("epube.keep-ui-visible").then((keep) => { + if (!keep) + this.showUI(false); + }); + } + /** + * @param {HTMLElement} elem + */ + async openPrevious(elem) { + const cfi = $(elem).attr("data-location-cfi"); + if (cfi) + await this.book.rendition.display(cfi); + $(elem).fadeOut(); + } + blockLastReadUpdate() { + console.log('blocking last read updates...'); + if (this._prevent_lastread_timeout) + window.clearTimeout(this._prevent_lastread_timeout); + this._prevent_lastread_timeout = window.setTimeout(() => { + this._prevent_lastread = false; + this._prevent_lastread_timeout = false; + console.log('unblocked last read updates'); + }, 1000); + this._prevent_lastread = true; + } + /** + * @param { ePub.Book } book + * @param { ePub.Location } location + */ + async onRelocated(book, location) { + // locations not generated yet + if (book.locations.length() == 0) + return; + const currentCfi = location.start.cfi; + const currentPct = Math.round(book.locations.percentageFromCfi(currentCfi) * 100); + $("#cur_page").text(Math.floor(location.start.location / LOCATION_DIVISOR)); + $("#total_pages").text(Math.floor(book.locations.length() / LOCATION_DIVISOR)); + $("#page_pct").text(Math.round(book.locations.percentageFromCfi(currentCfi) * 100) + '%'); + this.updateTocBarPosition(book, location); + const displayed = location.start.displayed; + if (displayed) { + $("#chapter_cur_page").text(displayed.page); + $("#chapter_total_pages").text(displayed.total); + if (displayed.total > 0) + $("#chapter_pct").text(Math.round(displayed.page / displayed.total * 100) + '%'); + } + if (this.startup_finished && this.last_stored_cfi != currentCfi && !this._prevent_lastread) { + const lastread_timestamp = new Date().getTime(); + console.log("storing lastread", currentPct, currentCfi, lastread_timestamp); + await localforage.setItem(this.cacheId("lastread"), { cfi: currentCfi, page: currentPct, total: 100, timestamp: lastread_timestamp }); + if (this.isOnline()) { + console.log("updating remote lastread", currentCfi); + this.last_stored_cfi = currentCfi; + $.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: currentPct, + cfi: currentCfi, timestamp: lastread_timestamp }); + } + } + } + async clearLastRead() { + if (confirm("Reset reading progress for this book?")) { + $("#settings-modal").modal('hide'); + const total = this.book.locations.length(); + const lastread_timestamp = new Date().getTime(); + if (this.isOnline()) + await $.post("backend.php", { op: "storelastread", page: PAGE_RESET_PROGRESS, cfi: "", id: this.urlParam("id"), timestamp: lastread_timestamp }); + await localforage.setItem(this.cacheId("lastread"), { cfi: "", page: 0, total: total, timestamp: lastread_timestamp }); + await this.book.rendition.display(this.book.locations.cfiFromPercentage(0)); + $(".lastread_input").val('0%'); + } + } + async resetLocations() { + if (confirm("Reset stored pagination data? This will also reset reading progress.")) { + $("#settings-modal").modal('hide'); + await localforage.removeItem(this.cacheId("lastread")); + await localforage.removeItem(this.cacheId("locations")); + await $.post("backend.php", { op: "storelastread", page: PAGE_RESET_PROGRESS, cfi: "", id: this.urlParam("id"), timestamp: new Date().getTime() }); + // this might return 404 and its okay + await $.post("backend.php", { op: "deletepagination", id: this.urlParam("id") }).catch((e) => console.log(e)); + window.location.reload(); + } + } + async openLastRead() { + $(".loading").show(); + $(".loading-message").html("Opening last read page…"); + $("#settings-modal").modal('hide'); + const rendition = this.book.rendition; + if (!rendition) { + console.error('no rendition to work on'); + return; + } + let location_found = false; + const lr_local = await localforage.getItem(this.cacheId("lastread")) || {}; + console.log('got local lastread', lr_local); + if (this.isOnline()) { + try { + const lr_remote = await $.post("backend.php", { op: "getlastread", id: this.urlParam("id") }); + console.log('got remote lastread', lr_remote); + if (lr_remote) { + if (lr_remote.cfi && lr_local.cfi != lr_remote.cfi && (lr_remote.page >= (lr_local.page || 0))) { + console.log(`using remote lastread cfi ${lr_remote.cfi}: cfi is different and remote pct ${lr_remote.page}% is further than local pct ${lr_local.page}%`); + await localforage.setItem(this.cacheId("lastread"), { cfi: lr_remote.cfi, page: lr_remote.page, total: lr_remote.total, timestamp: lr_remote.timestamp }); + location_found = await this.moveToCfiVerify(rendition, lr_remote.cfi); + } + } + } + catch (e) { + console.log('unable to get remote lastread, continuing...'); + console.warn(e); + } + } + // for some reason this might not actually open *exact* CFI but it should generally be close enough after a few attempts, + // that's why we no longer reset to page 1 after trying local CFI + if (!location_found) { + if (lr_local && lr_local.cfi) { + console.log(`using local lastread cfi: ${lr_local.cfi}`); + try { + await this.moveToCfiVerify(rendition, lr_local.cfi); + } + catch (e) { + console.warn(e); + } + } + } + $(".loading").fadeOut(); + } + /** + * @param {string} a + * @param {string} b + */ + calculateCfiDelta(a, b) { + // @ts-ignore + const acfi = new ePub.CFI(a); + // @ts-ignore + const bcfi = new ePub.CFI(b); + console.log('calculateCfiDelta', acfi, bcfi); + if (acfi.path.steps.length != bcfi.path.steps.length) + return -1; + let delta = 0; + // this is about as ad-hoc as it gets... + for (let i = 0; i < acfi.path.steps.length; i++) { + // is this possible? who knows! + if (acfi.path.steps[i].type != bcfi.path.steps[i].type) + return -1; + // different "filepos" or w/e + if (acfi.path.steps[i].id != bcfi.path.steps[i].id) + return -1; + if (acfi.path.steps[i].id === null && acfi.path.steps[i].type === 'element') + delta += Math.abs(acfi.path.steps[i].index - bcfi.path.steps[i].index); + } + return delta; + } + /** + * @param {ePub.Rendition} rendition + * @param {string} cfi + */ + async moveToCfiVerify(rendition, cfi, attempts = 5, maxDelta = 5) { + for (let att = 1; att < attempts; att++) { + this.blockLastReadUpdate(); + console.log(`trying to open ${cfi}: attempt ${att} of ${attempts}...`); + /* eslint-disable no-await-in-loop */ + await rendition.display(cfi); // we need to be synchronous here + let moved_to; + try { + moved_to = rendition.currentLocation().start.cfi; + } + catch (e) { + console.warn('location not yet available, will retry:', e); + } + try { + const delta = this.calculateCfiDelta(cfi, moved_to); + console.log(`opened cfi ${moved_to} expected ${cfi}; delta: ${delta}`); + if (moved_to == cfi || (delta != -1 && delta <= maxDelta)) { + console.log("cfi move verified!"); + return true; + } + } + catch (e) { + console.warn('exception while parsing cfi, will retry: ', e); + } + } + return false; + } + /** + * @param {HTMLElement} elem + */ + async onThemeChanged(elem) { + const theme = $(elem).val(); + await localforage.setItem("epube.theme", theme); + this.applyTheme(); + } + /** + * @param {HTMLElement} elem + */ + async onLineHeightChanged(elem) { + const height = $(elem).val(); + await localforage.setItem("epube.lineHeight", height); + this.applyTheme(); + } + /** + * @param {HTMLElement} elem + */ + async onTextSizeChanged(elem) { + const size = $(elem).val(); + await localforage.setItem("epube.fontSize", size); + this.applyTheme(); + } + /** + * @param {HTMLElement} elem + */ + async onFontChanged(elem) { + const font = $(elem).val(); + await localforage.setItem("epube.fontFamily", font); + this.applyTheme(); + } +} +exports.ReaderClass = ReaderClass; +class ReaderLoader { + constructor() { + this._res_data = []; + this.CACHE_NAME = 'epube-v3'; + } + async init() { + if (typeof EpubeApp != "undefined") { + $("body").addClass("epube-app"); + } + // we need to manually provide resources for reader iframe because service worker fetch() handler doesn't work inside iframes (chrome bug?) + const promises = []; + let load_failed = false; + const cache = await caches.open(this.CACHE_NAME); + const cache_keys = await cache.keys(); + cache_keys.forEach((req) => { + if (!req.url.match('backend\.php')) { + console.log('[loader] loading resource', req.url); + const promise = fetch(req.url).then(async (resp) => { + if (resp.ok) { + const url = new URL(resp.url); + url.searchParams.delete("ts"); + if (resp.url.match('\\.ttf|\\.otf')) { + const blob = await resp.blob(); + console.log('[loader] storing blob', url.href); + this._res_data[url.toString()] = URL.createObjectURL(blob); + } + else { + const text = await resp.text(); + console.log('[loader] storing text', url.href); + this._res_data[url.toString()] = text; + } + } + else { + console.warn('[loader] failed for resource', req.url, resp); + $(".loading-message").html(`Unable to load resource.<br/><small>${req.url}</small>`); + load_failed = true; + } + }); + promises.push(promise); + } + }); + await Promise.allSettled(promises); + console.log('[loader] resource load complete, failed: ', load_failed); + return load_failed; + } +} diff --git a/gulpfile.js b/gulpfile.js index ba113ad..e98d011 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -7,6 +7,9 @@ const rename = require('gulp-rename'); const uglify = require('gulp-uglify-es').default; const touch = require('gulp-touch-fd'); +const ts = require("gulp-typescript"); +const tsProject = ts.createProject("tsconfig.json"); + function swallowError(error) { console.log(error.toString()) @@ -35,12 +38,15 @@ gulp.task('minifyLibsJS', function(cb) { }); gulp.task('minifyJS', function(cb) { - gulp - .src(['js/*.js']) + tsProject + .src() + .pipe(tsProject()) + .on('error', swallowError) + .js + .pipe(gulp.dest("dist")) .pipe(concat('app.min.js')) .pipe(uglify()) .on('error', swallowError) - .pipe(gulp.dest('dist/')); cb(); }); @@ -73,7 +79,7 @@ gulp.task( gulp.series(['minifyCSS', 'minifyJS', 'minifyLibsJS'])(); gulp.watch(['lib/**/*.js', 'lib/*.js', 'node_modules/**/.js'], gulp.series('minifyLibsJS')); - gulp.watch(['js/*.js'], gulp.series('minifyJS')); + gulp.watch(['src/*.ts'], gulp.series('minifyJS')); gulp.watch(['css/*.less'], gulp.series('minifyCSS')); cb(); diff --git a/js/app.d.ts b/js/app.d.ts deleted file mode 100644 index 58eddc3..0000000 --- a/js/app.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -declare var EpubeApp: class; -declare var localforage: LocalForage; diff --git a/js/localforage.d.ts b/js/localforage.d.ts deleted file mode 100644 index 7fb8f58..0000000 --- a/js/localforage.d.ts +++ /dev/null @@ -1,123 +0,0 @@ -interface LocalForageDbInstanceOptions { - name?: string; - - storeName?: string; -} - -interface LocalForageOptions extends LocalForageDbInstanceOptions { - driver?: string | string[]; - - size?: number; - - version?: number; - - description?: string; -} - -interface LocalForageDbMethodsCore { - getItem<T>(key: string, callback?: (err: any, value: T | null) => void): Promise<T | null>; - - setItem<T>(key: string, value: T, callback?: (err: any, value: T) => void): Promise<T>; - - removeItem(key: string, callback?: (err: any) => void): Promise<void>; - - clear(callback?: (err: any) => void): Promise<void>; - - length(callback?: (err: any, numberOfKeys: number) => void): Promise<number>; - - key(keyIndex: number, callback?: (err: any, key: string) => void): Promise<string>; - - keys(callback?: (err: any, keys: string[]) => void): Promise<string[]>; - - iterate<T, U>(iteratee: (value: T, key: string, iterationNumber: number) => U, - callback?: (err: any, result: U) => void): Promise<U>; -} - -interface LocalForageDropInstanceFn { - (dbInstanceOptions?: LocalForageDbInstanceOptions, callback?: (err: any) => void): Promise<void>; -} - -interface LocalForageDriverMethodsOptional { - dropInstance?: LocalForageDropInstanceFn; -} - -// duplicating LocalForageDriverMethodsOptional to preserve TS v2.0 support, -// since Partial<> isn't supported there -interface LocalForageDbMethodsOptional { - dropInstance: LocalForageDropInstanceFn; -} - -interface LocalForageDriverDbMethods extends LocalForageDbMethodsCore, LocalForageDriverMethodsOptional {} - -interface LocalForageDriverSupportFunc { - (): Promise<boolean>; -} - -interface LocalForageDriver extends LocalForageDriverDbMethods { - _driver: string; - - _initStorage(options: LocalForageOptions): void; - - _support?: boolean | LocalForageDriverSupportFunc; -} - -interface LocalForageSerializer { - serialize<T>(value: T | ArrayBuffer | Blob, callback: (value: string, error: any) => void): void; - - deserialize<T>(value: string): T | ArrayBuffer | Blob; - - stringToBuffer(serializedString: string): ArrayBuffer; - - bufferToString(buffer: ArrayBuffer): string; -} - -interface LocalForageDbMethods extends LocalForageDbMethodsCore, LocalForageDbMethodsOptional {} - -interface LocalForage extends LocalForageDbMethods { - LOCALSTORAGE: string; - WEBSQL: string; - INDEXEDDB: string; - - /** - * Set and persist localForage options. This must be called before any other calls to localForage are made, but can be called after localForage is loaded. - * If you set any config values with this method they will persist after driver changes, so you can call config() then setDriver() - * @param {LocalForageOptions} options? - */ - config(options: LocalForageOptions): boolean; - config(options: string): any; - config(): LocalForageOptions; - - /** - * Create a new instance of localForage to point to a different store. - * All the configuration options used by config are supported. - * @param {LocalForageOptions} options - */ - createInstance(options: LocalForageOptions): LocalForage; - - driver(): string; - - /** - * Force usage of a particular driver or drivers, if available. - * @param {string} driver - */ - setDriver(driver: string | string[], callback?: () => void, errorCallback?: (error: any) => void): Promise<void>; - - defineDriver(driver: LocalForageDriver, callback?: () => void, errorCallback?: (error: any) => void): Promise<void>; - - /** - * Return a particular driver - * @param {string} driver - */ - getDriver(driver: string): Promise<LocalForageDriver>; - - getSerializer(callback?: (serializer: LocalForageSerializer) => void): Promise<LocalForageSerializer>; - - supports(driverName: string): boolean; - - ready(callback?: (error: any) => void): Promise<void>; -} - -declare module "localforage" { - let localforage: LocalForage; - export = localforage; -} diff --git a/js/reader.d.ts b/js/reader.d.ts deleted file mode 100644 index 322db63..0000000 --- a/js/reader.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -declare var EpubeApp: class; -declare var localforage: LocalForage; -declare var createHyphenator: function; - -declare var hyphenationPatternsEnUs: any; -declare var hyphenationPatternsRu: any; - -declare interface HTMLElement { checked: boolean } -declare interface Event { deltaY: int, deltaX: int } -declare interface Node { data: string } diff --git a/package-lock.json b/package-lock.json index e87ae94..70d554e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,6 +14,9 @@ "localforage": "^1.9.0" }, "devDependencies": { + "@types/bootstrap": "^3.4.0", + "@types/jquery": "^4.0.0", + "@types/localforage": "^0.0.34", "eslint": "^8.0.1", "eslint-formatter-gitlab": "^5.1.0", "gulp": "^4.0.2", @@ -22,8 +25,10 @@ "gulp-minify-css": "^1.2.4", "gulp-rename": "^2.0.0", "gulp-touch-fd": "^2.0.0", + "gulp-typescript": "^5.0.1", "gulp-uglify-es": "^2.0.0", - "less": "^3.12.2" + "less": "^3.12.2", + "typescript": "^6.0.2" } }, "node_modules/@eslint-community/eslint-utils": { @@ -165,11 +170,29 @@ "node": ">= 8" } }, + "node_modules/@types/bootstrap": { + "version": "3.4.0", + "resolved": "https://nexus.fakecake.org/repository/npm/@types/bootstrap/-/bootstrap-3.4.0.tgz", + "integrity": "sha512-LS05hVAAsX86qbHg7W+ydwBlNHrVCoFw6wEP3/uW4eYmRXl08bWmPeN/+onM+8qZTFfDgUlG/OItJI8SW972oQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/jquery": "*" + } + }, + "node_modules/@types/jquery": { + "version": "4.0.0", + "resolved": "https://nexus.fakecake.org/repository/npm/@types/jquery/-/jquery-4.0.0.tgz", + "integrity": "sha512-Z+to+A2VkaHq1DfI2oSwsoCdhCHMpTSgjWzNcbNlRGYzksDBpPUgEcAL+RQjOBJRaLoEAOHXxqDGBVP+BblBwg==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/localforage": { "version": "0.0.34", - "resolved": "https://registry.npmjs.org/@types/localforage/-/localforage-0.0.34.tgz", - "integrity": "sha1-XjHDLdh5HsS5/z70fJy1Wy0NlDg=", + "resolved": "https://nexus.fakecake.org/repository/npm/@types/localforage/-/localforage-0.0.34.tgz", + "integrity": "sha512-tJxahnjm9dEI1X+hQSC5f2BSd/coZaqbIl1m3TCl0q9SVuC52XcXfV0XmoCU1+PmjyucuVITwoTnN8OlTbEXXA==", "deprecated": "This is a stub types definition for localforage (https://github.com/localForage/localForage). localforage provides its own type definitions, so you don't need @types/localforage installed!", + "license": "MIT", "dependencies": { "localforage": "*" } @@ -295,6 +318,16 @@ "node": ">=0.4.2" } }, + "node_modules/ansi-colors": { + "version": "3.2.4", + "resolved": "https://nexus.fakecake.org/repository/npm/ansi-colors/-/ansi-colors-3.2.4.tgz", + "integrity": "sha512-hHUXGagefjN2iRrID63xckIvotOXOojhQKWIPUZ4mNUZ9nLZW+7FMNoE1lOkEhNWYsx/7ysGIuJYCiMAA9FnrA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/ansi-cyan": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/ansi-cyan/-/ansi-cyan-0.1.1.tgz", @@ -2656,6 +2689,77 @@ "map-stream": "0.0.7" } }, + "node_modules/gulp-typescript": { + "version": "5.0.1", + "resolved": "https://nexus.fakecake.org/repository/npm/gulp-typescript/-/gulp-typescript-5.0.1.tgz", + "integrity": "sha512-YuMMlylyJtUSHG1/wuSVTrZp60k1dMEFKYOvDf7OvbAJWrDtxxD4oZon4ancdWwzjj30ztiidhe4VXJniF0pIQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-colors": "^3.0.5", + "plugin-error": "^1.0.1", + "source-map": "^0.7.3", + "through2": "^3.0.0", + "vinyl": "^2.1.0", + "vinyl-fs": "^3.0.3" + }, + "engines": { + "node": ">= 8" + }, + "peerDependencies": { + "typescript": "~2.7.1 || >=2.8.0-dev || >=2.9.0-dev || ~3.0.0 || >=3.0.0-dev || >=3.1.0-dev || >= 3.2.0-dev || >= 3.3.0-dev" + } + }, + "node_modules/gulp-typescript/node_modules/plugin-error": { + "version": "1.0.1", + "resolved": "https://nexus.fakecake.org/repository/npm/plugin-error/-/plugin-error-1.0.1.tgz", + "integrity": "sha512-L1zP0dk7vGweZME2i+EeakvUNqSrdiI3F91TwEoYiGrAfUXmVv6fJIq4g82PAXxNsWOp0J7ZqQy/3Szz0ajTxA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-colors": "^1.0.1", + "arr-diff": "^4.0.0", + "arr-union": "^3.1.0", + "extend-shallow": "^3.0.2" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/gulp-typescript/node_modules/plugin-error/node_modules/ansi-colors": { + "version": "1.1.0", + "resolved": "https://nexus.fakecake.org/repository/npm/ansi-colors/-/ansi-colors-1.1.0.tgz", + "integrity": "sha512-SFKX67auSNoVR38N3L+nvsPjOE0bybKTYbkf5tRvushrAPQ9V75huw0ZxBkKVeRU9kqH3d6HA4xTckbwZ4ixmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-wrap": "^0.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/gulp-typescript/node_modules/source-map": { + "version": "0.7.6", + "resolved": "https://nexus.fakecake.org/repository/npm/source-map/-/source-map-0.7.6.tgz", + "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">= 12" + } + }, + "node_modules/gulp-typescript/node_modules/through2": { + "version": "3.0.2", + "resolved": "https://nexus.fakecake.org/repository/npm/through2/-/through2-3.0.2.tgz", + "integrity": "sha512-enaDQ4MUyP2W6ZyT6EsMzqBPZaM/avg8iuo+l2d3QCs0J+6RaqkHV/2/lOwDTueBHeJ/2LG9lrLW3d5rWPucuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "inherits": "^2.0.4", + "readable-stream": "2 || 3" + } + }, "node_modules/gulp-uglify-es": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/gulp-uglify-es/-/gulp-uglify-es-2.0.0.tgz", @@ -5571,6 +5675,20 @@ "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=", "dev": true }, + "node_modules/typescript": { + "version": "6.0.2", + "resolved": "https://nexus.fakecake.org/repository/npm/typescript/-/typescript-6.0.2.tgz", + "integrity": "sha512-bGdAIrZ0wiGDo5l8c++HWtbaNCWTS4UTv7RaTH/ThVIgjkveJt83m74bBHMJkuCbslY8ixgLBVZJIOiQlQTjfQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, "node_modules/uglify-js": { "version": "2.8.29", "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-2.8.29.tgz", @@ -6241,10 +6359,25 @@ "fastq": "^1.6.0" } }, + "@types/bootstrap": { + "version": "3.4.0", + "resolved": "https://nexus.fakecake.org/repository/npm/@types/bootstrap/-/bootstrap-3.4.0.tgz", + "integrity": "sha512-LS05hVAAsX86qbHg7W+ydwBlNHrVCoFw6wEP3/uW4eYmRXl08bWmPeN/+onM+8qZTFfDgUlG/OItJI8SW972oQ==", + "dev": true, + "requires": { + "@types/jquery": "*" + } + }, + "@types/jquery": { + "version": "4.0.0", + "resolved": "https://nexus.fakecake.org/repository/npm/@types/jquery/-/jquery-4.0.0.tgz", + "integrity": "sha512-Z+to+A2VkaHq1DfI2oSwsoCdhCHMpTSgjWzNcbNlRGYzksDBpPUgEcAL+RQjOBJRaLoEAOHXxqDGBVP+BblBwg==", + "dev": true + }, "@types/localforage": { "version": "0.0.34", - "resolved": "https://registry.npmjs.org/@types/localforage/-/localforage-0.0.34.tgz", - "integrity": "sha1-XjHDLdh5HsS5/z70fJy1Wy0NlDg=", + "resolved": "https://nexus.fakecake.org/repository/npm/@types/localforage/-/localforage-0.0.34.tgz", + "integrity": "sha512-tJxahnjm9dEI1X+hQSC5f2BSd/coZaqbIl1m3TCl0q9SVuC52XcXfV0XmoCU1+PmjyucuVITwoTnN8OlTbEXXA==", "requires": { "localforage": "*" } @@ -6343,6 +6476,12 @@ "integrity": "sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU=", "dev": true }, + "ansi-colors": { + "version": "3.2.4", + "resolved": "https://nexus.fakecake.org/repository/npm/ansi-colors/-/ansi-colors-3.2.4.tgz", + "integrity": "sha512-hHUXGagefjN2iRrID63xckIvotOXOojhQKWIPUZ4mNUZ9nLZW+7FMNoE1lOkEhNWYsx/7ysGIuJYCiMAA9FnrA==", + "dev": true + }, "ansi-cyan": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/ansi-cyan/-/ansi-cyan-0.1.1.tgz", @@ -8239,6 +8378,61 @@ "map-stream": "0.0.7" } }, + "gulp-typescript": { + "version": "5.0.1", + "resolved": "https://nexus.fakecake.org/repository/npm/gulp-typescript/-/gulp-typescript-5.0.1.tgz", + "integrity": "sha512-YuMMlylyJtUSHG1/wuSVTrZp60k1dMEFKYOvDf7OvbAJWrDtxxD4oZon4ancdWwzjj30ztiidhe4VXJniF0pIQ==", + "dev": true, + "requires": { + "ansi-colors": "^3.0.5", + "plugin-error": "^1.0.1", + "source-map": "^0.7.3", + "through2": "^3.0.0", + "vinyl": "^2.1.0", + "vinyl-fs": "^3.0.3" + }, + "dependencies": { + "plugin-error": { + "version": "1.0.1", + "resolved": "https://nexus.fakecake.org/repository/npm/plugin-error/-/plugin-error-1.0.1.tgz", + "integrity": "sha512-L1zP0dk7vGweZME2i+EeakvUNqSrdiI3F91TwEoYiGrAfUXmVv6fJIq4g82PAXxNsWOp0J7ZqQy/3Szz0ajTxA==", + "dev": true, + "requires": { + "ansi-colors": "^1.0.1", + "arr-diff": "^4.0.0", + "arr-union": "^3.1.0", + "extend-shallow": "^3.0.2" + }, + "dependencies": { + "ansi-colors": { + "version": "1.1.0", + "resolved": "https://nexus.fakecake.org/repository/npm/ansi-colors/-/ansi-colors-1.1.0.tgz", + "integrity": "sha512-SFKX67auSNoVR38N3L+nvsPjOE0bybKTYbkf5tRvushrAPQ9V75huw0ZxBkKVeRU9kqH3d6HA4xTckbwZ4ixmA==", + "dev": true, + "requires": { + "ansi-wrap": "^0.1.0" + } + } + } + }, + "source-map": { + "version": "0.7.6", + "resolved": "https://nexus.fakecake.org/repository/npm/source-map/-/source-map-0.7.6.tgz", + "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==", + "dev": true + }, + "through2": { + "version": "3.0.2", + "resolved": "https://nexus.fakecake.org/repository/npm/through2/-/through2-3.0.2.tgz", + "integrity": "sha512-enaDQ4MUyP2W6ZyT6EsMzqBPZaM/avg8iuo+l2d3QCs0J+6RaqkHV/2/lOwDTueBHeJ/2LG9lrLW3d5rWPucuQ==", + "dev": true, + "requires": { + "inherits": "^2.0.4", + "readable-stream": "2 || 3" + } + } + } + }, "gulp-uglify-es": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/gulp-uglify-es/-/gulp-uglify-es-2.0.0.tgz", @@ -10559,6 +10753,12 @@ "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=", "dev": true }, + "typescript": { + "version": "6.0.2", + "resolved": "https://nexus.fakecake.org/repository/npm/typescript/-/typescript-6.0.2.tgz", + "integrity": "sha512-bGdAIrZ0wiGDo5l8c++HWtbaNCWTS4UTv7RaTH/ThVIgjkveJt83m74bBHMJkuCbslY8ixgLBVZJIOiQlQTjfQ==", + "dev": true + }, "uglify-js": { "version": "2.8.29", "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-2.8.29.tgz", diff --git a/package.json b/package.json index 5e6a496..85db37f 100644 --- a/package.json +++ b/package.json @@ -4,6 +4,9 @@ "license": "GPL-3.0", "description": "", "devDependencies": { + "@types/bootstrap": "^3.4.0", + "@types/jquery": "^4.0.0", + "@types/localforage": "^0.0.34", "eslint": "^8.0.1", "eslint-formatter-gitlab": "^5.1.0", "gulp": "^4.0.2", @@ -12,8 +15,10 @@ "gulp-minify-css": "^1.2.4", "gulp-rename": "^2.0.0", "gulp-touch-fd": "^2.0.0", + "gulp-typescript": "^5.0.1", "gulp-uglify-es": "^2.0.0", - "less": "^3.12.2" + "less": "^3.12.2", + "typescript": "^6.0.2" }, "dependencies": { "epubjs": "^0.3.88", diff --git a/js/app.js b/src/app.ts index c5f35b4..8c6df78 100644 --- a/js/app.js +++ b/src/app.ts @@ -1,78 +1,12 @@ -// @ts-check +'use strict' -'use strict'; +declare var EpubeApp: any; +declare var localforage: LocalForage; -/* global localforage, EpubeApp, $ */ +import { AppCommon } from "./appcommon"; +import { Cookie } from "./cookie"; -class Cookie { - static set(name, value, lifetime) { - const d = new Date(); - d.setTime(d.getTime() + lifetime * 1000); - const expires = "expires=" + d.toUTCString(); - document.cookie = name + "=" + encodeURIComponent(value) + "; " + expires; - } - - static get(name) { - name = name + "="; - const ca = document.cookie.split(';'); - for (let i=0; i < ca.length; i++) { - let c = ca[i]; - while (c.charAt(0) == ' ') c = c.substring(1); - if (c.indexOf(name) == 0) return decodeURIComponent(c.substring(name.length, c.length)); - } - return ""; - } - - static delete(name) { - const expires = "expires=Thu, 01-Jan-1970 00:00:01 GMT"; - document.cookie = name + "=; " + expires; - } -} - -class AppCommon { - urlParam(name){ - try { - const results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href); - return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0; - } catch (e) { - return 0; - } - } - - isOnline() { - if (typeof EpubeApp != "undefined" && typeof EpubeApp.isOnline != "undefined") - return EpubeApp.isOnline(); - else - return navigator.onLine; - } - - initNightMode() { - if (typeof EpubeApp != "undefined") { - this.applyNightMode(EpubeApp.isNightMode()); - return; - } - - if (window.matchMedia) { - const mql = window.matchMedia('(prefers-color-scheme: dark)'); - - mql.addEventListener("change", () => { - this.applyNightMode(mql.matches); - }); - - this.applyNightMode(mql.matches); - } - } - - applyNightMode(is_night) { - console.log("night mode changed to", is_night); - - $("#theme_css").attr("href", - "lib/bootstrap/v3/css/" + (is_night ? "theme-dark.min.css" : "bootstrap-theme.min.css")); - } -} - -/* exported AppClass */ -class AppClass extends AppCommon { +export class AppClass extends AppCommon { _dl_progress_timeout; index_mode = ""; @@ -153,7 +87,7 @@ class AppClass extends AppCommon { this.showCovers(); this.updateOfflinePrompts(); - this.refreshCache(); + this.refreshCache(false); } else { $(".container-main") @@ -196,7 +130,7 @@ class AppClass extends AppCommon { $("#summary-modal").modal(); } else { - const data = await localforage.getItem("epube-book." + bookId); + const data = <any> await localforage.getItem("epube-book." + bookId); const comment = data.comment ? data.comment : 'No description available'; $("#summary-modal .modal-title").html(data.title); @@ -528,7 +462,7 @@ class AppClass extends AppCommon { ]).then(function(results) { if (results[0] && results[3]) { - const info = results[0]; + const info = <any> results[0]; if (query) { const match = @@ -543,13 +477,14 @@ class AppClass extends AppCommon { let cover = ""; if (results && results[1]) { - cover = URL.createObjectURL(results[1]); - } + cover = URL.createObjectURL(results[1] as Blob); + } let in_progress = false; let is_read = false; - const lastread = results[2]; + const lastread = <any> results[2]; + if (lastread) { in_progress = lastread.page > 0; is_read = lastread.total > 0 && lastread.total - lastread.page < 5; diff --git a/src/appcommon.ts b/src/appcommon.ts new file mode 100644 index 0000000..393b781 --- /dev/null +++ b/src/appcommon.ts @@ -0,0 +1,43 @@ +declare var EpubeApp: any; + +export class AppCommon { + urlParam(name){ + try { + const results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href); + return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0; + } catch (e) { + return 0; + } + } + + isOnline() { + if (typeof EpubeApp != "undefined" && typeof EpubeApp.isOnline != "undefined") + return EpubeApp.isOnline(); + else + return navigator.onLine; + } + + initNightMode() { + if (typeof EpubeApp != "undefined") { + this.applyNightMode(EpubeApp.isNightMode()); + return; + } + + if (window.matchMedia) { + const mql = window.matchMedia('(prefers-color-scheme: dark)'); + + mql.addEventListener("change", () => { + this.applyNightMode(mql.matches); + }); + + this.applyNightMode(mql.matches); + } + } + + applyNightMode(is_night) { + console.log("night mode changed to", is_night); + + $("#theme_css").attr("href", + "lib/bootstrap/v3/css/" + (is_night ? "theme-dark.min.css" : "bootstrap-theme.min.css")); + } +} diff --git a/src/cookie.ts b/src/cookie.ts new file mode 100644 index 0000000..c38a1ac --- /dev/null +++ b/src/cookie.ts @@ -0,0 +1,24 @@ +export class Cookie { + static set(name, value, lifetime) { + const d = new Date(); + d.setTime(d.getTime() + lifetime * 1000); + const expires = "expires=" + d.toUTCString(); + document.cookie = name + "=" + encodeURIComponent(value) + "; " + expires; + } + + static get(name) { + name = name + "="; + const ca = document.cookie.split(';'); + for (let i=0; i < ca.length; i++) { + let c = ca[i]; + while (c.charAt(0) == ' ') c = c.substring(1); + if (c.indexOf(name) == 0) return decodeURIComponent(c.substring(name.length, c.length)); + } + return ""; + } + + static delete(name) { + const expires = "expires=Thu, 01-Jan-1970 00:00:01 GMT"; + document.cookie = name + "=; " + expires; + } +} diff --git a/js/reader.js b/src/reader.ts index 27f4337..1758a74 100644 --- a/js/reader.js +++ b/src/reader.ts @@ -1,8 +1,11 @@ -// @ts-check - 'use strict'; -/* global localforage, EpubeApp, ePub, Cookie, AppCommon, $ */ +declare var EpubeApp: any; +declare var localforage: LocalForage; + +declare var createHyphenator: any; +declare var hyphenationPatternsEnUs: any; +declare var hyphenationPatternsRu: any; const DEFAULT_FONT_SIZE = 16; const DEFAULT_FONT_FAMILY = "Arial"; @@ -12,8 +15,10 @@ const MIN_LENGTH_TO_JUSTIFY = 32; /* characters */ const LOCATION_DIVISOR = 10; const PAGE_RESET_PROGRESS = -1; -/* exported ReaderClass */ -class ReaderClass extends AppCommon { +import { AppCommon } from "./appcommon"; +import { Cookie } from "./cookie"; + +export class ReaderClass extends AppCommon { csrf_token = ""; last_stored_cfi = ""; @@ -22,12 +27,16 @@ class ReaderClass extends AppCommon { open_last_read_when_displayed = true; - hyphenate = {}; + hyphenate = {en: null, ru: null}; _prevent_lastread_timeout; _prevent_lastread; + _flattened_toc; + + loader; + /** * @type {ePub.Book} */ @@ -211,10 +220,11 @@ class ReaderClass extends AppCommon { $(".loading-message").html("Unable to open book.<br/><small>" + e + "</small>"); }; - fileReader.readAsArrayBuffer(book_data); + fileReader.readAsArrayBuffer(book_data as Blob); } async openBookData(book_data) { + // @ts-ignore this.book = new ePub.Book(); try { @@ -273,7 +283,7 @@ class ReaderClass extends AppCommon { * @param {ePub.Book} book */ async showBookInfo(book) { - const bookinfo = await localforage.getItem(this.cacheId()); + const bookinfo = <any> await localforage.getItem(this.cacheId()); let title; let author; @@ -456,9 +466,9 @@ class ReaderClass extends AppCommon { $(contents.window).on("wheel", async (evt) => { if (await localforage.getItem("epube.enable-wheel")) { - if (evt.originalEvent.deltaY > 0) { + if ((evt.originalEvent as WheelEvent).deltaY > 0) { this.nextPage(); - } else if (evt.originalEvent.deltaY < 0) { + } else if ((evt.originalEvent as WheelEvent).deltaY < 0) { this.prevPage(); } } @@ -504,7 +514,7 @@ class ReaderClass extends AppCommon { if (location.start) { const cur_href = book.canonical(location.start.href); - let toc_entry = {}; + let toc_entry = {label: ""}; $.each(this.flattenToc(book), function(i, r) { @@ -542,7 +552,7 @@ class ReaderClass extends AppCommon { initModals() { $('#settings-modal').on('shown.bs.modal', async () => { - const last_read = await localforage.getItem(this.cacheId("lastread")); + const last_read = <any> await localforage.getItem(this.cacheId("lastread")); if (last_read && last_read.cfi) { $(".lastread_input") @@ -609,7 +619,7 @@ class ReaderClass extends AppCommon { .attr("checked", await localforage.getItem("epube.enable-hyphens")) .off("click") .on("click", (evt) => { - localforage.setItem("epube.enable-hyphens", evt.target.checked); + localforage.setItem("epube.enable-hyphens", (evt.target as HTMLInputElement).checked); if (confirm("Toggling hyphens requires page reload. Reload now?")) { window.location.reload(); @@ -620,7 +630,7 @@ class ReaderClass extends AppCommon { .attr("checked", await localforage.getItem("epube.enable-wheel")) .off("click") .on("click", (evt) => { - localforage.setItem("epube.enable-wheel", evt.target.checked); + localforage.setItem("epube.enable-wheel", (evt.target as HTMLInputElement).checked); }); if (typeof EpubeApp != "undefined") { @@ -630,15 +640,15 @@ class ReaderClass extends AppCommon { .attr("checked", await localforage.getItem("epube.keep-ui-visible")) .off("click") .on("click", (evt) => { - localforage.setItem("epube.keep-ui-visible", evt.target.checked); + localforage.setItem("epube.keep-ui-visible", (evt.target as HTMLInputElement).checked); }); } - const stamp = await localforage.getItem("epube.cache-timestamp"); + const stamp = String(await localforage.getItem("epube.cache-timestamp")); const version = await localforage.getItem("epube.cache-version"); $(".last-mod-timestamp").html(`${version} - — ${parseInt(stamp) ? new Date(stamp*1000).toLocaleString("en-GB") : "Unknown"} + — ${parseInt(stamp) ? new Date(parseInt(stamp) * 1000).toLocaleString("en-GB") : "Unknown"} (${this.isOnline() ? `<span class='text-success'>Online</span>` : `<span class='text-danger'>Offline</span>`}) `); @@ -1255,7 +1265,7 @@ class ReaderClass extends AppCommon { } } - cacheId(suffix) { + cacheId(suffix = "") { return "epube-book." + this.urlParam("b") + (suffix ? "." + suffix : ""); } @@ -1273,7 +1283,7 @@ class ReaderClass extends AppCommon { $(".header,.footer").fadeIn(); } - async lookupWord(word, callback, elem) { + async lookupWord(word, callback, elem = null) { if (elem) word = $(elem).val(); @@ -1485,7 +1495,7 @@ class ReaderClass extends AppCommon { let location_found = false; - const lr_local = await localforage.getItem(this.cacheId("lastread")) || {}; + const lr_local = <any> await localforage.getItem(this.cacheId("lastread")) || {}; console.log('got local lastread', lr_local); if (this.isOnline()) { diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..dfe4808 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,9 @@ +{ + "files": ["src/*.ts"], + "compilerOptions": { + "noImplicitAny": false, + "target": "es2020", + "module": "CommonJS", + "types": ["node", "jquery", "localforage", "bootstrap"] + } +} |
