about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorAndrew Dolgov <fox@fakecake.org>2026-03-22 11:37:34 +0300
committerAndrew Dolgov <fox@fakecake.org>2026-03-22 11:37:34 +0300
commit254bc97e737a568cb23fbbcb773f0dfb8894b9ff (patch)
tree850c6dceda07214248c3bfa2bf3bf0e15fa3e329
parent6c991424547b149b3cac70a94a4e14f3661908a6 (diff)
downloadthe-epube-typescript-native.tar.gz
the-epube-typescript-native.tar.xz
wip typescript stuff typescript-native
-rw-r--r--dist/app.min.js2
-rw-r--r--gulpfile.js18
-rw-r--r--js/app.d.ts2
-rw-r--r--js/localforage.d.ts123
-rw-r--r--js/reader.d.ts10
-rw-r--r--package-lock.json251
-rw-r--r--package.json3
-rw-r--r--src/app.ts (renamed from js/app.js)85
-rw-r--r--src/appcommon.ts43
-rw-r--r--src/cookie.ts28
-rw-r--r--src/reader.ts (renamed from js/reader.js)49
-rw-r--r--tsconfig.json10
12 files changed, 341 insertions, 283 deletions
diff --git a/dist/app.min.js b/dist/app.min.js
index 57ed9d2..5c1eb1f 100644
--- a/dist/app.min.js
+++ b/dist/app.min.js
@@ -1 +1 @@
-"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(),"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?).")}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();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;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)}),$("#left").on("mouseup",()=>{this.prevPage()}),$("#right").on("mouseup",()=>{this.nextPage()}),this.loader=new ReaderLoader,this.loader.init(t=>{t?this.applyTheme():this.initSecondStage()})}isTouchDevice(){return"ontouchstart"in window||navigator.maxTouchPoints>0}onOfflineModeChanged(t){if(console.log("onOfflineModeChanged",t),!t&&this.book){const t=this.book;console.log("we're online, storing lastread");const e=t.rendition.currentLocation().start.cfi,o=Math.round(100*t.locations.percentageFromCfi(e));$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:o,cfi:e,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){const e=ePub();this.book=e;try{await e.open(t)}catch(t){return console.error(t),void $(".loading-message").html("Unable to open book.<br/><small>"+t.message+"</small>")}await e.ready,console.log("book is ready"),await this.showBookInfo(e),await this.loadLocations(e);const o=e.renderTo("reader",{width:"100%",height:"100%",allowScriptedContent:!1,minSpreadWidth:961});$(".location").on("click",async()=>{const t=Math.floor(o.currentLocation().start.location/10),a=Math.floor(e.locations.length()/10),n=prompt("Jump to location [1-"+a+"]",String(t));n&&await o.display(e.locations._locations[10*parseInt(n)])});await localforage.getItem("epube.enable-hyphens")&&(this.hyphenate.en=createHyphenator(hyphenationPatternsEnUs,{html:!0}),this.hyphenate.ru=createHyphenator(hyphenationPatternsRu,{html:!0})),this.initRenditionHooks(e,o),this.initModals(),this.initToc(e),this.blockLastReadUpdate(),await o.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.package.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 o=>{console.log("rendition rendered section",o),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),navigator.onLine&&$.post("backend.php",{op:"getlastread",id:this.urlParam("id")},t=>{$(".lastread_input").val(t.page+"%").attr("title","[remote] "+t.cfi)}),$(".enable_hyphens_checkbox").attr("checked",await localforage.getItem("epube.enable-hyphens")).off("click").on("click",(function(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",(function(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",(function(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&mdash; ${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",(function(){$(".dict_result").scrollTop(0)})),$(".dict_search_btn").on("click",(function(){$("#dict-modal").modal("hide"),window.open("https://duckduckgo.com/?q="+$(".dict_query").val())})),$(".wiki_search_btn").on("click",(function(){$(".dict_result").html("Loading, please wait..."),$.post("backend.php",{op:"wikisearch",query:$(".dict_query").val()}).then(t=>{try{console.log("wikisearch resp",t);let e="";$.each(t.query.pages,(t,o)=>{e+=o.extract}),$(".dict_result").html(e&&"undefined"!=e?e:"No definition found for "+$(".dict_query").val()+".")}catch(t){console.error(t),$(".dict_result").text("Error while processing data: "+t)}}).fail(t=>{console.error(t),$(".dict_result").text("Error while retrieving data.")})}))}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, 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){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++){this.blockLastReadUpdate(),console.log(`trying to open ${e}: attempt ${n} of ${o}...`),await t.display(e);let i=!1;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(t){"undefined"!=typeof EpubeApp&&$("body").addClass("epube-app");const e=[];let o=!1;const a=await caches.open(this.CACHE_NAME);(await a.keys()).forEach(t=>{if(!t.url.match("backend.php")){console.log("[loader] loading resource",t.url);const a=fetch(t.url).then(async e=>{if(e.ok){const t=new URL(e.url);if(t.searchParams.delete("ts"),e.url.match("\\.ttf|\\.otf")){const o=await e.blob();console.log("[loader] storing blob",t.href),this._res_data[t.toString()]=URL.createObjectURL(o)}else{const o=await e.text();console.log("[loader] storing text",t.href),this._res_data[t.toString()]=o}}else console.warn("[loader] failed for resource",t.url,e),$(".loading-message").html(`Unable to load resource.<br/><small>${t.url}</small>`),o=!0});e.push(a)}}),await Promise.allSettled(e),console.log("[loader] resource load complete, failed: ",o),t(o)}}
\ No newline at end of file
+import localforage from"localforage";import{AppCommon}from"./appcommon";import{Cookie}from"./cookie";export class AppClass extends AppCommon{constructor(){super(...arguments),this.index_mode="",this.cached_urls=[],this.version="UNKNOWN",this.buildTimestamp=0,this.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(),"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?).")}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=!1){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();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)}}))}))}}export 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"))}}export 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"}}import localforage from"localforage";import{Cookie}from"./cookie";import{AppCommon}from"./appcommon";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;export class ReaderClass extends AppCommon{constructor(){super(...arguments),this.csrf_token="",this.last_stored_cfi="",this.startup_finished=!1,this.open_last_read_when_displayed=!0}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)}),$("#left").on("mouseup",()=>{this.prevPage()}),$("#right").on("mouseup",()=>{this.nextPage()}),this.loader=new ReaderLoader,this.loader.init(t=>{t?this.applyTheme():this.initSecondStage()})}isTouchDevice(){return"ontouchstart"in window||navigator.maxTouchPoints>0}onOfflineModeChanged(t){if(console.log("onOfflineModeChanged",t),!t&&this.book){const t=this.book;console.log("we're online, storing lastread");const e=t.rendition.currentLocation().start.cfi,o=Math.round(100*t.locations.percentageFromCfi(e));$.post("backend.php",{op:"storelastread",id:this.urlParam("id"),page:o,cfi:e,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){const e=ePub();this.book=e;try{await e.open(t)}catch(t){return console.error(t),void $(".loading-message").html("Unable to open book.<br/><small>"+t.message+"</small>")}await e.ready,console.log("book is ready"),await this.showBookInfo(e),await this.loadLocations(e);const o=e.renderTo("reader",{width:"100%",height:"100%",allowScriptedContent:!1,minSpreadWidth:961});$(".location").on("click",async()=>{const t=Math.floor(o.currentLocation().start.location/10),a=Math.floor(e.locations.length()/10),n=prompt("Jump to location [1-"+a+"]",String(t));n&&await o.display(e.locations._locations[10*parseInt(n)])});await localforage.getItem("epube.enable-hyphens")&&(this.hyphenate.en=createHyphenator(hyphenationPatternsEnUs,{html:!0}),this.hyphenate.ru=createHyphenator(hyphenationPatternsRu,{html:!0})),this.initRenditionHooks(e,o),this.initModals(),this.initToc(e),this.blockLastReadUpdate(),await o.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.package.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 o=>{console.log("rendition rendered section",o),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),navigator.onLine&&$.post("backend.php",{op:"getlastread",id:this.urlParam("id")},t=>{$(".lastread_input").val(t.page+"%").attr("title","[remote] "+t.cfi)}),$(".enable_hyphens_checkbox").attr("checked",await localforage.getItem("epube.enable-hyphens")).off("click").on("click",(function(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",(function(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",(function(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&mdash; ${parseInt(e)?new Date(1e3*parseInt(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",(function(){$(".dict_result").scrollTop(0)})),$(".dict_search_btn").on("click",(function(){$("#dict-modal").modal("hide"),window.open("https://duckduckgo.com/?q="+$(".dict_query").val())})),$(".wiki_search_btn").on("click",(function(){$(".dict_result").html("Loading, please wait..."),$.post("backend.php",{op:"wikisearch",query:$(".dict_query").val()}).then(t=>{try{console.log("wikisearch resp",t);let e="";$.each(t.query.pages,(t,o)=>{e+=o.extract}),$(".dict_result").html(e&&"undefined"!=e?e:"No definition found for "+$(".dict_query").val()+".")}catch(t){console.error(t),$(".dict_result").text("Error while processing data: "+t)}}).fail(t=>{console.error(t),$(".dict_result").text("Error while retrieving data.")})}))}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, 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){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++){this.blockLastReadUpdate(),console.log(`trying to open ${e}: attempt ${n} of ${o}...`),await t.display(e);let i=!1;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{constructor(){this._res_data=[],this.CACHE_NAME="epube-v3"}async init(t){"undefined"!=typeof EpubeApp&&$("body").addClass("epube-app");const e=[];let o=!1;const a=await caches.open(this.CACHE_NAME);(await a.keys()).forEach(t=>{if(!t.url.match("backend.php")){console.log("[loader] loading resource",t.url);const a=fetch(t.url).then(async e=>{if(e.ok){const t=new URL(e.url);if(t.searchParams.delete("ts"),e.url.match("\\.ttf|\\.otf")){const o=await e.blob();console.log("[loader] storing blob",t.href),this._res_data[t.toString()]=URL.createObjectURL(o)}else{const o=await e.text();console.log("[loader] storing text",t.href),this._res_data[t.toString()]=o}}else console.warn("[loader] failed for resource",t.url,e),$(".loading-message").html(`Unable to load resource.<br/><small>${t.url}</small>`),o=!0});e.push(a)}}),await Promise.allSettled(e),console.log("[loader] resource load complete, failed: ",o),t(o)}}
\ No newline at end of file
diff --git a/gulpfile.js b/gulpfile.js
index ba113ad..1374d82 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())
 
@@ -34,12 +37,13 @@ gulp.task('minifyLibsJS', function(cb) {
 		cb();
 });
 
-gulp.task('minifyJS', function(cb) {
-	gulp
-		.src(['js/*.js'])
+gulp.task('minifyTS', function(cb) {
+	tsProject
+		.src()
+		.pipe(tsProject()).js
 		.pipe(concat('app.min.js'))
-		.pipe(uglify())
-		.on('error', swallowError)
+		//.pipe(uglify())
+		//.on('error', swallowError)
 		.pipe(gulp.dest('dist/'));
 
 		cb();
@@ -70,10 +74,10 @@ gulp.task('minifyCSS', function(cb) {
 gulp.task(
   'default',
   function(cb) {
-		gulp.series(['minifyCSS', 'minifyJS', 'minifyLibsJS'])();
+		gulp.series(['minifyCSS', 'minifyTS', '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('minifyTS'));
 		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 189b3bb..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 Window { book: ePub }
-declare interface HTMLElement { checked: boolean }
-declare interface Event { deltaY: int, deltaX: int }
diff --git a/package-lock.json b/package-lock.json
index e87ae94..b7ab547 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -14,6 +14,8 @@
         "localforage": "^1.9.0"
       },
       "devDependencies": {
+        "@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,6 +24,7 @@
         "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"
       }
@@ -165,11 +168,19 @@
         "node": ">= 8"
       }
     },
+    "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 +306,19 @@
         "node": ">=0.4.2"
       }
     },
+    "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/ansi-cyan": {
       "version": "0.1.1",
       "resolved": "https://registry.npmjs.org/ansi-cyan/-/ansi-cyan-0.1.1.tgz",
@@ -2579,18 +2603,6 @@
         "node": ">= 0.10"
       }
     },
-    "node_modules/gulp-cli/node_modules/ansi-colors": {
-      "version": "1.1.0",
-      "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-1.1.0.tgz",
-      "integrity": "sha512-SFKX67auSNoVR38N3L+nvsPjOE0bybKTYbkf5tRvushrAPQ9V75huw0ZxBkKVeRU9kqH3d6HA4xTckbwZ4ixmA==",
-      "dev": true,
-      "dependencies": {
-        "ansi-wrap": "^0.1.0"
-      },
-      "engines": {
-        "node": ">=0.10.0"
-      }
-    },
     "node_modules/gulp-concat": {
       "version": "2.6.1",
       "resolved": "https://registry.npmjs.org/gulp-concat/-/gulp-concat-2.6.1.tgz",
@@ -2656,24 +2668,59 @@
         "map-stream": "0.0.7"
       }
     },
-    "node_modules/gulp-uglify-es": {
-      "version": "2.0.0",
-      "resolved": "https://registry.npmjs.org/gulp-uglify-es/-/gulp-uglify-es-2.0.0.tgz",
-      "integrity": "sha512-00KkawzjWdjPo1YfD1FXKijVxZkyr6YSwJ2cJQgD1fNKFZCFPNjGc5sTyzyW8tZns8FmZafgHMrg7LUDNvIQ5A==",
+    "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": {
-        "o-stream": "^0.2.2",
+        "ansi-colors": "^3.0.5",
         "plugin-error": "^1.0.1",
-        "terser": "^4.3.9",
-        "vinyl": "^2.2.0",
-        "vinyl-sourcemaps-apply": "^0.2.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/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/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-uglify-es/node_modules/ansi-colors": {
+    "node_modules/gulp-typescript/node_modules/plugin-error/node_modules/ansi-colors": {
       "version": "1.1.0",
-      "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-1.1.0.tgz",
+      "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"
       },
@@ -2681,6 +2728,40 @@
         "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",
+      "integrity": "sha512-00KkawzjWdjPo1YfD1FXKijVxZkyr6YSwJ2cJQgD1fNKFZCFPNjGc5sTyzyW8tZns8FmZafgHMrg7LUDNvIQ5A==",
+      "dev": true,
+      "dependencies": {
+        "o-stream": "^0.2.2",
+        "plugin-error": "^1.0.1",
+        "terser": "^4.3.9",
+        "vinyl": "^2.2.0",
+        "vinyl-sourcemaps-apply": "^0.2.1"
+      }
+    },
     "node_modules/gulp-uglify-es/node_modules/plugin-error": {
       "version": "1.0.1",
       "resolved": "https://registry.npmjs.org/plugin-error/-/plugin-error-1.0.1.tgz",
@@ -5571,6 +5652,21 @@
       "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=",
       "dev": true
     },
+    "node_modules/typescript": {
+      "version": "5.9.3",
+      "resolved": "https://nexus.fakecake.org/repository/npm/typescript/-/typescript-5.9.3.tgz",
+      "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "peer": true,
+      "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 +6337,16 @@
         "fastq": "^1.6.0"
       }
     },
+    "@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 +6445,15 @@
       "integrity": "sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU=",
       "dev": true
     },
+    "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"
+      }
+    },
     "ansi-cyan": {
       "version": "0.1.1",
       "resolved": "https://registry.npmjs.org/ansi-cyan/-/ansi-cyan-0.1.1.tgz",
@@ -8171,17 +8282,6 @@
         "semver-greatest-satisfied-range": "^1.1.0",
         "v8flags": "^3.2.0",
         "yargs": "^7.1.0"
-      },
-      "dependencies": {
-        "ansi-colors": {
-          "version": "1.1.0",
-          "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-1.1.0.tgz",
-          "integrity": "sha512-SFKX67auSNoVR38N3L+nvsPjOE0bybKTYbkf5tRvushrAPQ9V75huw0ZxBkKVeRU9kqH3d6HA4xTckbwZ4ixmA==",
-          "dev": true,
-          "requires": {
-            "ansi-wrap": "^0.1.0"
-          }
-        }
       }
     },
     "gulp-concat": {
@@ -8239,6 +8339,67 @@
         "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": {
+        "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
+        },
+        "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",
@@ -8252,15 +8413,6 @@
         "vinyl-sourcemaps-apply": "^0.2.1"
       },
       "dependencies": {
-        "ansi-colors": {
-          "version": "1.1.0",
-          "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-1.1.0.tgz",
-          "integrity": "sha512-SFKX67auSNoVR38N3L+nvsPjOE0bybKTYbkf5tRvushrAPQ9V75huw0ZxBkKVeRU9kqH3d6HA4xTckbwZ4ixmA==",
-          "dev": true,
-          "requires": {
-            "ansi-wrap": "^0.1.0"
-          }
-        },
         "plugin-error": {
           "version": "1.0.1",
           "resolved": "https://registry.npmjs.org/plugin-error/-/plugin-error-1.0.1.tgz",
@@ -10559,6 +10711,13 @@
       "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=",
       "dev": true
     },
+    "typescript": {
+      "version": "5.9.3",
+      "resolved": "https://nexus.fakecake.org/repository/npm/typescript/-/typescript-5.9.3.tgz",
+      "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+      "dev": true,
+      "peer": 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..8c80fd4 100644
--- a/package.json
+++ b/package.json
@@ -4,6 +4,8 @@
   "license": "GPL-3.0",
   "description": "",
   "devDependencies": {
+    "@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,6 +14,7 @@
     "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"
   },
diff --git a/js/app.js b/src/app.ts
index 0e7e4c0..f7fcfee 100644
--- a/js/app.js
+++ b/src/app.ts
@@ -1,78 +1,13 @@
-// @ts-check
-
-'use strict';
-
 /* global localforage, EpubeApp, $ */
 
-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;
-	}
+declare var EpubeApp: any;
 
-	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;
-	}
+import localforage from "localforage";
 
-	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"));
-	}
-}
+import { AppCommon } from "./appcommon.js";
+import { Cookie } from "./cookie.js";
 
-/* exported AppClass */
-class AppClass extends AppCommon {
+export class AppClass extends AppCommon {
 	_dl_progress_timeout;
 
 	index_mode = "";
@@ -181,7 +116,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);
@@ -237,7 +172,7 @@ class AppClass extends AppCommon {
 		return false;
 	}
 
-	async refreshCache(force) {
+	async refreshCache(force = false) {
 		if ('serviceWorker' in navigator) {
 			const version = await localforage.getItem("epube.cache-version");
 
@@ -512,7 +447,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 =
@@ -527,13 +462,13 @@ 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..e37146c
--- /dev/null
+++ b/src/cookie.ts
@@ -0,0 +1,28 @@
+// @ts-check
+
+'use strict';
+
+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 b4fd731..9fbc4d6 100644
--- a/js/reader.js
+++ b/src/reader.ts
@@ -1,6 +1,14 @@
-// @ts-check
+declare var EpubeApp: any;
 
-'use strict';
+declare var createHyphenator: any;
+
+declare var hyphenationPatternsEnUs: any;
+declare var hyphenationPatternsRu: any;
+
+import localforage from "localforage";
+
+import { Cookie } from "./cookie.js";
+import { AppCommon } from "./appcommon.js";
 
 /* global localforage, EpubeApp, ePub, Cookie, AppCommon, $ */
 
@@ -12,8 +20,7 @@ const MIN_LENGTH_TO_JUSTIFY = 32; /* characters */
 const LOCATION_DIVISOR = 10;
 const PAGE_RESET_PROGRESS = -1;
 
-/* exported ReaderClass */
-class ReaderClass extends AppCommon {
+export class ReaderClass extends AppCommon {
 	csrf_token = "";
 
 	last_stored_cfi = "";
@@ -22,14 +29,18 @@ class ReaderClass extends AppCommon {
 
 	open_last_read_when_displayed = true;
 
-	hyphenate = {};
+	hyphenate;
 
 	_prevent_lastread_timeout;
 
 	_prevent_lastread;
 
+	_flattened_toc;
+
 	book;
 
+	loader;
+
 	init() {
 		this.csrf_token = Cookie.get('epube_csrf_token');
 
@@ -190,7 +201,7 @@ 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) {
@@ -252,7 +263,7 @@ class ReaderClass extends AppCommon {
 	}
 
 	async showBookInfo(book) {
-		const bookinfo = await localforage.getItem(this.cacheId());
+		const bookinfo = <any> await localforage.getItem(this.cacheId());
 
 		let title;
 		let author;
@@ -427,9 +438,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();
 					}
 				}
@@ -475,7 +486,7 @@ class ReaderClass extends AppCommon {
 
 				if (location.start) {
 					const cur_href = book.canonical(location.start.href);
-					let toc_entry = {};
+					let toc_entry;
 
 					$.each(this.flattenToc(book), function(i, r) {
 
@@ -513,7 +524,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")
@@ -532,7 +543,7 @@ class ReaderClass extends AppCommon {
 				.attr("checked", await localforage.getItem("epube.enable-hyphens"))
 				.off("click")
 				.on("click", function(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();
@@ -543,7 +554,7 @@ class ReaderClass extends AppCommon {
 				.attr("checked", await localforage.getItem("epube.enable-wheel"))
 				.off("click")
 				.on("click", function(evt) {
-					localforage.setItem("epube.enable-wheel", evt.target.checked);
+					localforage.setItem("epube.enable-wheel", (evt.target as HTMLInputElement).checked);
 				});
 
 			if (typeof EpubeApp != "undefined") {
@@ -553,15 +564,15 @@ class ReaderClass extends AppCommon {
 				.attr("checked", await localforage.getItem("epube.keep-ui-visible"))
 				.off("click")
 				.on("click", function(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}
-				&mdash; ${parseInt(stamp) ? new Date(stamp*1000).toLocaleString("en-GB") : "Unknown"}
+				&mdash; ${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>`})
 				`);
 
@@ -1187,7 +1198,7 @@ class ReaderClass extends AppCommon {
 		}
 	}
 
-	cacheId(suffix) {
+	cacheId(suffix = "") {
 		return "epube-book." + this.urlParam("b") + (suffix ? "." + suffix : "");
 	}
 
@@ -1406,12 +1417,12 @@ 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()) {
 			try {
-				const lr_remote = await $.post("backend.php", { op: "getlastread", id: this.urlParam("id") });
+				const lr_remote = <any> await $.post("backend.php", { op: "getlastread", id: this.urlParam("id") });
 
 				console.log('got remote lastread', lr_remote);
 
diff --git a/tsconfig.json b/tsconfig.json
new file mode 100644
index 0000000..161d847
--- /dev/null
+++ b/tsconfig.json
@@ -0,0 +1,10 @@
+{
+  "include": ["src/*"],
+  "compilerOptions": {
+    "noImplicitAny": false,
+    "target": "es2020",
+    "module": "NodeNext",
+    "moduleResolution": "NodeNext",
+    "allowSyntheticDefaultImports": true
+  }
+}