about summary refs log tree commit diff stats
path: root/src
diff options
context:
space:
mode:
authorAndrew Dolgov <fox@fakecake.org>2026-05-31 09:11:20 +0300
committerAndrew Dolgov <fox@fakecake.org>2026-05-31 09:11:20 +0300
commitb58f0a8f2431040edf94edb21f9c884f20ba6049 (patch)
treeb70055bf14983a59242ae27cdba75f6d39d391a3 /src
parentb76af33e9bfb57b46fb8d8292b614bf9ee2e3c2d (diff)
downloadthe-epube-b58f0a8f2431040edf94edb21f9c884f20ba6049.tar.gz
the-epube-b58f0a8f2431040edf94edb21f9c884f20ba6049.tar.xz
tabs to spaces
Diffstat (limited to 'src')
-rw-r--r--src/app.js1358
-rw-r--r--src/csrf.js26
-rw-r--r--src/reader.js3130
-rw-r--r--src/worker.js266
4 files changed, 2390 insertions, 2390 deletions
diff --git a/src/app.js b/src/app.js
index dca9d76..fd02999 100644
--- a/src/app.js
+++ b/src/app.js
@@ -5,752 +5,752 @@
 /* global localforage, EpubeApp, $, setupCsrfPrefilter */
 
 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;
-	}
+    static set(name, value, lifetime) {
+        const d = new Date();
+        d.setTime(d.getTime() + lifetime * 1000);
+        const expires = "expires=" + d.toUTCString();
+        document.cookie = name + "=" + encodeURIComponent(value) + "; " + expires;
+    }
+
+    static get(name) {
+        name = name + "=";
+        const ca = document.cookie.split(';');
+        for (let i=0; i < ca.length; i++) {
+            let c = ca[i];
+            while (c.charAt(0) == ' ') c = c.substring(1);
+            if (c.indexOf(name) == 0) return decodeURIComponent(c.substring(name.length, c.length));
+        }
+        return "";
+    }
+
+    static delete(name) {
+        const expires = "expires=Thu, 01-Jan-1970 00:00:01 GMT";
+        document.cookie = name + "=; " + expires;
+    }
 }
 
 class AppCommon {
-	urlParam(name){
-		try {
-			const results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
-			if (!results) return 0;
-			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;
-	}
-
-	async getActiveCacheName() {
-		const registration = await navigator.serviceWorker.ready;
-		const worker = registration.active;
-
-		if (!worker) return null;
-
-		return new Promise((resolve) => {
-			const channel = new MessageChannel();
-
-			// Listen for the service worker's response
-			channel.port1.onmessage = (event) => {
-				resolve(event.data.cacheName);
-			};
-
-			// Dispatch message to the service worker along with the response port
-			worker.postMessage({ type: 'GET_CACHE_NAME' }, [channel.port2]);
-		});
-	}
-
-	async getActiveCacheVersion() {
-		const registration = await navigator.serviceWorker.ready;
-		const worker = registration.active;
-
-		if (!worker) return null;
-
-		return new Promise((resolve) => {
-			const channel = new MessageChannel();
-
-			// Listen for the service worker's response
-			channel.port1.onmessage = (event) => {
-				resolve(event.data.cacheName);
-			};
-
-			// Dispatch message to the service worker along with the response port
-			worker.postMessage({ type: 'GET_CACHE_VERSION' }, [channel.port2]);
-		});
-	}
-
-	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"));
-	}
+    urlParam(name){
+        try {
+            const results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
+            if (!results) return 0;
+            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;
+    }
+
+    async getActiveCacheName() {
+        const registration = await navigator.serviceWorker.ready;
+        const worker = registration.active;
+
+        if (!worker) return null;
+
+        return new Promise((resolve) => {
+            const channel = new MessageChannel();
+
+            // Listen for the service worker's response
+            channel.port1.onmessage = (event) => {
+                resolve(event.data.cacheName);
+            };
+
+            // Dispatch message to the service worker along with the response port
+            worker.postMessage({ type: 'GET_CACHE_NAME' }, [channel.port2]);
+        });
+    }
+
+    async getActiveCacheVersion() {
+        const registration = await navigator.serviceWorker.ready;
+        const worker = registration.active;
+
+        if (!worker) return null;
+
+        return new Promise((resolve) => {
+            const channel = new MessageChannel();
+
+            // Listen for the service worker's response
+            channel.port1.onmessage = (event) => {
+                resolve(event.data.cacheName);
+            };
+
+            // Dispatch message to the service worker along with the response port
+            worker.postMessage({ type: 'GET_CACHE_VERSION' }, [channel.port2]);
+        });
+    }
+
+    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"));
+    }
 }
 
 /* eslint-disable-next-line no-unused-vars */
 class AppClass extends AppCommon {
-	_dl_progress_timeout;
+    _dl_progress_timeout;
 
-	index_mode = "";
+    index_mode = "";
 
-	index_query = "";
+    index_query = "";
 
-	index_offset = 0;
+    index_offset = 0;
 
-	cached_urls = [];
+    cached_urls = [];
 
-	version = BUILD_CACHE_VERSION;
+    version = BUILD_CACHE_VERSION;
 
-	// cacheManifest = [];
+    // cacheManifest = [];
 
-	csrf_token = "";
+    csrf_token = "";
 
-	async init() {
-		console.log('version', this.version, 'current, worker', await this.getActiveCacheVersion());
+    async init() {
+        console.log('version', this.version, 'current, worker', await this.getActiveCacheVersion());
 
-		this.csrf_token = Cookie.get('epube_csrf_token');
+        this.csrf_token = Cookie.get('epube_csrf_token');
 
-		setupCsrfPrefilter(this.csrf_token);
+        setupCsrfPrefilter(this.csrf_token);
 
-		if (typeof EpubeApp != "undefined") {
-			$(".navbar").hide();
-			$(".epube-app-filler").show();
-			$(".separate-search").show();
-			$("body").addClass("is-epube-app");
+        if (typeof EpubeApp != "undefined") {
+            $(".navbar").hide();
+            $(".epube-app-filler").show();
+            $(".separate-search").show();
+            $("body").addClass("is-epube-app");
 
-			if (this.urlParam("mode") == "favorites")
-				EpubeApp.setPage("PAGE_FAVORITES");
-			else
-				EpubeApp.setPage("PAGE_LIBRARY");
-		}
+            if (this.urlParam("mode") == "favorites")
+                EpubeApp.setPage("PAGE_FAVORITES");
+            else
+                EpubeApp.setPage("PAGE_LIBRARY");
+        }
 
-		this.initNightMode();
-		this.initCommonEventHandlers();
+        this.initNightMode();
+        this.initCommonEventHandlers();
 
-		this.populateList();
+        this.populateList();
 
-		if ('serviceWorker' in navigator) {
-			navigator.serviceWorker.addEventListener('message', () => {
-				// Future: handle SW messages (e.g., update available notifications)
-			});
+        if ('serviceWorker' in navigator) {
+            navigator.serviceWorker.addEventListener('message', () => {
+                // Future: handle SW messages (e.g., update available notifications)
+            });
 
-			this.showCovers();
-			this.updateOfflinePrompts();
-			//this.refreshCache();
+            this.showCovers();
+            this.updateOfflinePrompts();
+            //this.refreshCache();
 
-		} else {
-			$(".container-main")
-				.addClass("alert alert-danger")
-				.html("Service worker support missing in browser (are you using plain HTTP?).");
-		}
-	}
+        } else {
+            $(".container-main")
+                .addClass("alert alert-danger")
+                .html("Service worker support missing in browser (are you using plain HTTP?).");
+        }
+    }
 
-	initCommonEventHandlers() {
-		/* $(".refresh_cache_link").on('click', () => {
-			this.refreshCache(true);
-		}); */
+    initCommonEventHandlers() {
+        /* $(".refresh_cache_link").on('click', () => {
+            this.refreshCache(true);
+        }); */
 
-		$(".remove_all_downloads").on('click', () => {
-			this.removeAll();
-		});
+        $(".remove_all_downloads").on('click', () => {
+            this.removeAll();
+        });
 
-		$(".logout_link").on('click', () => {
-			this.logout();
-		});
+        $(".logout_link").on('click', () => {
+            this.logout();
+        });
 
-		$(".download_all_link").on('click', (e) => {
-			e.preventDefault();
-			this.getAll();
-		});
+        $(".download_all_link").on('click', (e) => {
+            e.preventDefault();
+            this.getAll();
+        });
 
-	}
+    }
 
-	logout() {
-		$.post("backend.php", {op: "logout"}).then(() => {
-			window.location.reload();
-		});
-	}
+    logout() {
+        $.post("backend.php", {op: "logout"}).then(() => {
+            window.location.reload();
+        });
+    }
 
-	async showSummary(elem) {
-		const bookId = elem.getAttribute("data-book-id");
+    async showSummary(elem) {
+        const bookId = elem.getAttribute("data-book-id");
 
-		if (this.isOnline()) {
+        if (this.isOnline()) {
 
-			const data = await $.post("backend.php", {op: 'getinfo', id: bookId});
-			const comment = data.comment ? data.comment : 'No description available';
+            const data = await $.post("backend.php", {op: 'getinfo', id: bookId});
+            const comment = data.comment ? data.comment : 'No description available';
 
-			$("#summary-modal .modal-title").text(data.title);
-			$("#summary-modal .book-summary").html(comment);
+            $("#summary-modal .modal-title").text(data.title);
+            $("#summary-modal .book-summary").html(comment);
 
-			$("#summary-modal").modal();
+            $("#summary-modal").modal();
 
-		} else {
-			const data = await localforage.getItem("epube-book." + bookId);
-			const comment = data.comment ? data.comment : 'No description available';
+        } else {
+            const data = await localforage.getItem("epube-book." + bookId);
+            const comment = data.comment ? data.comment : 'No description available';
 
-			$("#summary-modal .modal-title").text(data.title);
-			$("#summary-modal .book-summary").html(comment);
+            $("#summary-modal .modal-title").text(data.title);
+            $("#summary-modal .book-summary").html(comment);
 
-			$("#summary-modal").modal();
-		}
+            $("#summary-modal").modal();
+        }
 
-		return false;
-	}
+        return false;
+    }
 
-	showCovers() {
-		$("img[data-book-id]").each((i, elem) => {
-			const e = $(elem);
+    showCovers() {
+        $("img[data-book-id]").each((i, elem) => {
+            const e = $(elem);
 
-			if (e.attr('data-cover-link')) {
-				const img = $("<img>")
-					.on("load", () => {
-						e.css("background-image", "url(" + e.attr('data-cover-link') + ")")
-							.fadeIn();
+            if (e.attr('data-cover-link')) {
+                const img = $("<img>")
+                    .on("load", () => {
+                        e.css("background-image", "url(" + e.attr('data-cover-link') + ")")
+                            .fadeIn();
 
-						img.attr("src", null);
-					})
-					.attr("src", e.attr('data-cover-link') ?? "");
-			}
-		});
-	}
-
-	toggleFavorite(elem) {
-		const bookId = elem.getAttribute("data-book-id");
-
-		if (elem.getAttribute("data-is-fav") == "0" || confirm("Remove favorite?")) {
-
-			$.post("backend.php", {op: "togglefav", id: bookId}, (data) => {
-				if (data) {
-					let msg = "[Error]";
+                        img.attr("src", null);
+                    })
+                    .attr("src", e.attr('data-cover-link') ?? "");
+            }
+        });
+    }
+
+    toggleFavorite(elem) {
+        const bookId = elem.getAttribute("data-book-id");
+
+        if (elem.getAttribute("data-is-fav") == "0" || confirm("Remove favorite?")) {
+
+            $.post("backend.php", {op: "togglefav", id: bookId}, (data) => {
+                if (data) {
+                    let msg = "[Error]";
 
-					if (data.status == 0) {
-						msg = "Add to favorites";
-					} else if (data.status == 1) {
-						msg = "Remove from favorites";
-					}
+                    if (data.status == 0) {
+                        msg = "Add to favorites";
+                    } else if (data.status == 1) {
+                        msg = "Remove from favorites";
+                    }
 
-					$(elem).html(msg).attr('data-is-fav', data.status);
+                    $(elem).html(msg).attr('data-is-fav', data.status);
 
-					if (this.index_mode == "favorites" && data.status == 0) {
-						$("#cell-" + bookId).remove();
-					}
-				}
-			});
-		}
+                    if (this.index_mode == "favorites" && data.status == 0) {
+                        $("#cell-" + bookId).remove();
+                    }
+                }
+            });
+        }
 
-		return false;
-	}
+        return false;
+    }
 
-	/* async refreshCache(force) {
-		if ('serviceWorker' in navigator) {
-			const cachedVersion = await localforage.getItem("epube.cache-version");
+    /* async refreshCache(force) {
+        if ('serviceWorker' in navigator) {
+            const cachedVersion = await localforage.getItem("epube.cache-version");
 
-			console.log('cached version', cachedVersion, 'current version', this.version);
+            console.log('cached version', cachedVersion, 'current version', this.version);
 
-			if (force || cachedVersion != this.version) {
-				console.log('cache needs update, reloading...');
+            if (force || cachedVersion != this.version) {
+                console.log('cache needs update, reloading...');
 
-				// Show progress if SW is already controlling the page
-				if (navigator.serviceWorker.controller) {
-					$(".dl-progress")
-						.show()
-						.addClass("alert-info")
-						.html("Updating cache...");
-				}
+                // Show progress if SW is already controlling the page
+                if (navigator.serviceWorker.controller) {
+                    $(".dl-progress")
+                        .show()
+                        .addClass("alert-info")
+                        .html("Updating cache...");
+                }
 
-				await localforage.setItem("epube.cache-version", this.version);
+                await localforage.setItem("epube.cache-version", this.version);
 
-				// Reload — the SW will precache new assets on install
-				// and serve from cache on the next load
-				window.location.reload();
-			} else {
-				// Version matches — save it so we don't keep reloading
-				await localforage.setItem("epube.cache-version", this.version);
-			}
-		}
-	} */
+                // Reload — the SW will precache new assets on install
+                // and serve from cache on the next load
+                window.location.reload();
+            } else {
+                // Version matches — save it so we don't keep reloading
+                await localforage.setItem("epube.cache-version", this.version);
+            }
+        }
+    } */
 
-	updateOfflinePrompts() {
-		const elems = $(".offline_dropitem");
+    updateOfflinePrompts() {
+        const elems = $(".offline_dropitem");
 
-		$.each(elems, (i, elem) => {
-			this.updateOfflinePrompt(elem);
-		});
-	}
+        $.each(elems, (i, elem) => {
+            this.updateOfflinePrompt(elem);
+        });
+    }
 
-	async updateOfflinePrompt(elem) {
-		const bookId = elem.getAttribute("data-book-id");
-		const cacheId = "epube-book." + bookId;
+    async updateOfflinePrompt(elem) {
+        const bookId = elem.getAttribute("data-book-id");
+        const cacheId = "epube-book." + bookId;
 
-		const book = await localforage.getItem(cacheId);
+        const book = await localforage.getItem(cacheId);
 
-		if (book) {
-			elem.onclick = () => {
-				this.remove(bookId, () => {
-					this.updateOfflinePrompt(elem);
-				});
+        if (book) {
+            elem.onclick = () => {
+                this.remove(bookId, () => {
+                    this.updateOfflinePrompt(elem);
+                });
 
-				return false;
-			};
+                return false;
+            };
 
-			elem.innerHTML = "Remove offline data";
+            elem.innerHTML = "Remove offline data";
 
-		} else {
-			elem.onclick = () => {
-				this.get(bookId, () => {
-					this.updateOfflinePrompt(elem);
-				});
-				return false;
-			};
+        } else {
+            elem.onclick = () => {
+                this.get(bookId, () => {
+                    this.updateOfflinePrompt(elem);
+                });
+                return false;
+            };
 
-			elem.innerHTML = "Make available offline";
-		}
-	}
+            elem.innerHTML = "Make available offline";
+        }
+    }
 
-	async offlineInit() {
-		console.log('version', this.version, 'current, worker', await this.getActiveCacheVersion());
+    async offlineInit() {
+        console.log('version', this.version, 'current, worker', await this.getActiveCacheVersion());
 
-		if (typeof EpubeApp != "undefined") {
-			$(".navbar").hide();
-			$(".epube-app-filler").show();
-			$("body").addClass("is-epube-app");
+        if (typeof EpubeApp != "undefined") {
+            $(".navbar").hide();
+            $(".epube-app-filler").show();
+            $("body").addClass("is-epube-app");
 
-			EpubeApp.setPage("PAGE_OFFLINE");
-		}
-
-		this.initNightMode();
-		this.initCommonEventHandlers();
-
-		const query = this.urlParam("query");
-
-		if (query)
-			$(".search_query").val(query);
-
-		this.populateOfflineList();
-	}
-
-	get(bookId, callback) {
-		console.log("offline cache: " + bookId);
-
-		$.post("backend.php", {op: "getinfo", id: bookId}, (data) => {
-
-			if (data) {
-				const cacheId = 'epube-book.' + bookId;
+            EpubeApp.setPage("PAGE_OFFLINE");
+        }
+
+        this.initNightMode();
+        this.initCommonEventHandlers();
+
+        const query = this.urlParam("query");
+
+        if (query)
+            $(".search_query").val(query);
+
+        this.populateOfflineList();
+    }
+
+    get(bookId, callback) {
+        console.log("offline cache: " + bookId);
+
+        $.post("backend.php", {op: "getinfo", id: bookId}, (data) => {
+
+            if (data) {
+                const cacheId = 'epube-book.' + bookId;
 
-				localforage.setItem(cacheId, data).then((data) => {
+                localforage.setItem(cacheId, data).then((data) => {
 
-					console.log(cacheId + ' got data');
+                    console.log(cacheId + ' got data');
 
-					const promises = [];
-
-					promises.push(fetch('backend.php?op=download&id=' + data.epub_id, {credentials: 'same-origin'}).then(function(resp) {
-						if (resp.status == 200) {
-							console.log(cacheId + ' got book');
+                    const promises = [];
+
+                    promises.push(fetch('backend.php?op=download&id=' + data.epub_id, {credentials: 'same-origin'}).then(function(resp) {
+                        if (resp.status == 200) {
+                            console.log(cacheId + ' got book');
 
-							localforage.setItem(cacheId + '.book', resp.blob());
-						}
-					}));
-
-					promises.push(fetch("backend.php?op=getpagination&id=" + data.epub_id, {credentials: 'same-origin'}).then(function(resp) {
-						if (resp.status == 200) {
-							console.log(cacheId + ' got pagination');
-
-							resp.text().then(function(text) {
-								localforage.setItem(cacheId + '.locations', JSON.parse(text));
-							});
-						}
-					}));
-
-					promises.push(fetch("backend.php?op=getlastread&id=" + data.epub_id, {credentials: 'same-origin'}).then(function(resp) {
-						if (resp.status == 200) {
-							console.log(cacheId + ' got lastread');
-							resp.text().then(function(text) {
-								localforage.setItem(cacheId + '.lastread', JSON.parse(text));
-							});
-						}
-					}));
-
-					if (data.has_cover) {
-						promises.push(fetch("backend.php?op=cover&id=" + bookId, {credentials: 'same-origin'}).then(function(resp) {
-							if (resp.status == 200) {
-								console.log(cacheId + ' got cover');
-								localforage.setItem(cacheId + '.cover', resp.blob());
-							}
-						}));
-					}
-
-					Promise.all(promises).then(() => {
-						console.log('download done, running callback', callback);
-
-						callback();
-
-						$(".dl-progress")
-							.show()
-							.html("Finished downloading <b>" + data.title + "</b>");
-
-						window.clearTimeout(this._dl_progress_timeout);
-
-						this._dl_progress_timeout = window.setTimeout(function() {
-							$(".dl-progress").fadeOut();
-						}, 5*1000);
-					})
-
-				});
-			}
-		});
-	}
-
-	getAll() {
-		if (confirm("Download all books on this page?")) {
-
-			$(".row > div").each((i, row) => {
-				const bookId = ($(row).attr("id") ?? "").replace("cell-", "");
-				const dropitem = $(row).find(".offline_dropitem")[0] ?? null;
-
-				if (bookId) {
-					const cacheId = 'epube-book.' + bookId;
-
-					localforage.getItem(cacheId).then((book) => {
-						if (!book) {
-							this.get(bookId, () => {
-								this.updateOfflinePrompt(dropitem);
-							});
-						}
-					});
-				}
-			});
-		}
-	}
-
-	removeFromList(elem) {
-		const bookId = elem.getAttribute("data-book-id");
-
-		this.remove(bookId, () => {
-			$("#cell-" + bookId).remove();
-		});
-	}
-
-	remove(id, callback) {
-		if (confirm("Remove download?")) {
-
-			const cacheId = "epube-book." + id;
-			const promises = [];
-
-			console.log("offline remove: " + id);
-
-			localforage.iterate(function(value, key /*, i */) {
-				if (key.match(cacheId)) {
-					promises.push(localforage.removeItem(key));
-				}
-			});
-
-			Promise.all(promises).then(() => {
-				console.log('remove done, running callback', callback);
-
-				// just promise.all is not enough, need to wait a bit for localforage to actually delete item (?)
-				window.setTimeout(() => {
-					callback();
-				}, 250);
-			});
-		}
-	}
-
-	populateList() {
-		const params = new URLSearchParams({
-			op: "list",
-			mode: this.index_mode,
-			query: this.index_query,
-			offset: String(this.index_offset),
-			limit: String(60),
-		});
-
-		$.get("backend.php?" + params.toString()).done((data) => {
-			const books = $("#books_container");
-			books.html("");
-
-			if (data.books && data.books.length > 0) {
-				data.books.forEach((book) => {
-					const thumb_class = book.is_read ? "read" : "";
-					const title_class = book.in_progress ? "in_progress" : "";
-					const fav_attr = book.is_fav ? "1" : "0";
-					const fav_prompt = book.is_fav ? "Remove from favorites" : "Add to favorites";
-
-					const series_html = book.series_name ?
-						`<div><a title="${this.escapeHtml(book.series_full)}" href="${this.escapeHtml(book.series_link)}">${this.escapeHtml(book.series_full)}</a></div>` :
-						"";
-
-					const author_link = book.author_sort ?
-						`?${new URLSearchParams({query: book.author_sort}).toString()}` :
-						"";
-
-					const download_html = book.download_formats
-						.map((fmt) => {
-							const label_class = fmt.format === "EPUB" ? "label-success" : "label-primary";
-							return `<li><a target="_blank" href="backend.php?op=download&id=${fmt.id}">Download: <span class="label ${label_class}">${fmt.format}</span></a></li>`;
-						})
-						.join("");
-
-					const cell = $(`<div class="col-xxs-6 col-xs-3 col-sm-3 col-md-2" id="cell-${book.id}">
-						${book.read_link ?
-							`<a class="thumbnail ${thumb_class}" href="${book.read_link}">` :
-							`<span class="thumbnail ${thumb_class}">`}
-							<img style="display : none" data-book-id="${book.id}" data-cover-link="${book.cover_link}">
-						${book.read_link ? "</a>" : "</span>"}
-						<div class="caption">
-							<div title="${this.escapeHtml(book.title)}" class="${title_class}">
-								${book.read_link ?
-									`<a href="${book.read_link}">${this.escapeHtml(book.title)}</a>` :
-									this.escapeHtml(book.title)}
-							</div>
-							${series_html}
-							<div><a title="${this.escapeHtml(book.author_sort)}" href="${this.escapeHtml(author_link)}">${this.escapeHtml(book.author_sort)}</a></div>
-						</div>
-						<div class="dropdown" style="white-space : nowrap">
-							<a href="#" data-toggle="dropdown" role="button">More...<span class="caret"></span></a>
-							<ul class="dropdown-menu" aria-labelledby="dLabel">
-								<li><a href="#" class="summary_link" data-book-id="${book.id}">Summary</a></li>
-								<li><a href="#" class="fav_item" data-is-fav="${fav_attr}" data-book-id="${book.id}">${fav_prompt}</a></li>
-								${book.epub_id ? `<li><a href="#" data-book-id="${book.id}" class="offline_dropitem"></a></li><li class="divider"></li>` : ""}
-								${download_html}
-							</ul>
-						</div>
-					</div>`);
-
-					books.append(cell);
-				});
-
-				this.showCovers();
-				this.updateOfflinePrompts();
-
-				$(".summary_link").on('click', (e) => {
-					e.preventDefault();
-					this.showSummary(e.currentTarget);
-				});
-
-				$(".fav_item").on('click', (e) => {
-					e.preventDefault();
-					this.toggleFavorite(e.currentTarget);
-				});
-
-				$(".offline_dropitem").on('click', async (e) => {
-					e.preventDefault();
-					const bookId = e.currentTarget.getAttribute("data-book-id");
-					const cacheId = "epube-book." + bookId;
-					const book = await localforage.getItem(cacheId);
-
-					if (book) {
-						this.remove(bookId, () => {
-							this.updateOfflinePrompt(e.currentTarget);
-						});
-					} else {
-						this.get(bookId, () => {
-							this.updateOfflinePrompt(e.currentTarget);
-						});
-					}
-				});
-			}
-
-			this.updateIndexPagination(data);
-		});
-	}
-
-	updateIndexPagination(data) {
-		const prevLi = $(".pager .previous");
-		const nextLi = $(".pager .next");
-		const pagerInfo = $(".pager .pager-info");
-
-		const prevParams = new URLSearchParams({
-			mode: this.index_mode,
-			query: this.index_query,
-			offset: String(this.index_offset - 60),
-		});
-		const nextParams = new URLSearchParams({
-			mode: this.index_mode,
-			query: this.index_query,
-			offset: String(this.index_offset + 60),
-		});
-
-		if (this.index_offset > 0) {
-			prevLi.removeClass("disabled");
-			prevLi.find("a").attr("href", "?" + prevParams.toString());
-		} else {
-			prevLi.addClass("disabled");
-			prevLi.find("a").attr("href", "#");
-		}
-
-		if (data.books && data.books.length >= 60) {
-			nextLi.removeClass("disabled");
-			nextLi.find("a").attr("href", "?" + nextParams.toString());
-		} else {
-			nextLi.addClass("disabled");
-			nextLi.find("a").attr("href", "#");
-		}
-
-		const limit = data.limit || 60;
-		const total = data.total || 0;
-		const currentPage = Math.floor(this.index_offset / limit) + 1;
-		const totalPages = limit > 0 ? Math.ceil(total / limit) : 1;
-
-		pagerInfo.find("span").text(`Page ${currentPage} of ${totalPages}`);
-	}
-
-	escapeHtml(str) {
-		if (!str) return "";
-		const div = document.createElement("div");
-		div.appendChild(document.createTextNode(str));
-		return div.innerHTML;
-	}
-
-	async search() {
-		const query = $(".search_query").val();
-
-		await localforage.setItem("epube.search-query", query);
-
-		this.populateOfflineList();
-
-		return false;
-	}
-
-	async removeAll() {
-		if (confirm("Remove all downloaded books?")) {
-
-			const promises = [];
-
-			localforage.iterate(function(value, key/*, i*/) {
-				if (key.match("epube-book")) {
-					promises.push(localforage.removeItem(key));
-				}
-			});
-
-			await Promise.all(promises);
-
-			this.populateOfflineList();
-		}
-	}
-
-	populateOfflineList() {
-		let query = this.urlParam("query");
-
-		if (query) query = String(query).toLowerCase();
-
-		const books = $("#books_container");
-		books.html("");
-
-		localforage.iterate((value, key/*, i*/) => {
-			if (key.match(/epube-book\.\d{1,}$/)) {
-
-				Promise.all([
-					localforage.getItem(key),
-					localforage.getItem(key + ".cover"),
-					localforage.getItem(key + ".lastread"),
-					localforage.getItem(key + ".book")
-				]).then((results) => {
-
-					if (results[0] && results[3]) {
-						const info = results[0];
-
-						if (query) {
-							const match =
-								(info.series_name && info.series_name.toLowerCase().match(query)) ||
-								(info.title && info.title.toLowerCase().match(query)) ||
-								(info.author_sort && info.author_sort.toLowerCase().match(query));
-
-							if (!match) return;
-						}
-
-						let cover = "";
-
-						if (results && results[1]) {
-							cover = URL.createObjectURL(results[1]);
-						}
-
-						let in_progress = false;
-						let is_read = false;
-
-						const lastread = results[2];
-						if (lastread) {
-							in_progress = lastread.page > 0;
-							is_read = lastread.total > 0 && lastread.total - lastread.page < 5;
-						}
-
-						const thumb_class = is_read ? "read" : "";
-						const title_class = in_progress ? "in_progress" : "";
-
-						const series_link = info.series_name ? `<div><a class="series_link" href="#">${info.series_name + " [" + info.series_index + "]"}</a></div>` : "";
-
-						const cell = $(`<div class="col-xxs-6 col-xs-4 col-sm-3 col-md-2" id="cell-${info.id}">
-							<a class="thumbnail ${thumb_class}" href="read.html?id=${info.epub_id}&b=${info.id}">
-								<img style="display : none">
-							</a>
-							<div class="caption">
-								<div><a class="${title_class}" href="read.html?id=${info.epub_id}&b=${info.id}">${info.title}</a></div>
-								<div><a class="author_link" href="#">${info.author_sort}</a></div>
-								${series_link}
-							</div>
-							<div class="dropdown" style="white-space : nowrap">
-								<a href="#" data-toggle="dropdown" role="button">More...<span class="caret"></span></a>
-								<ul class="dropdown-menu">
-									<li><a href="#" class="offline_summary" data-book-id="${info.id}">Summary</a></li>
-									<li><a href="#" class="remove_offline_data" data-book-id="${info.id}">Remove offline data</a></li>
-								</ul>
-							</div>
-						</div>`);
-
-						$(cell).find(".offline_summary").on('click', (e) => {
-							e.preventDefault();
-							this.showSummary(e.currentTarget);
-						});
-
-						$(cell).find(".remove_offline_data").on('click', (e) => {
-							e.preventDefault();
-							this.removeFromList(e.currentTarget);
-						});
-
-						if (cover) {
-							cell.find("img")
-								.css("background-image", "url(" + cover + ")")
-								.fadeIn();
-						} else {
-							cell
-								.fadeIn();
-						}
-
-						cell.find(".series_link")
-							.attr("title", info.series_name + " [" + info.series_index  + "]")
-							.attr("href", "offline.html?query=" + encodeURIComponent(info.series_name));
-
-						cell.find(".author_link")
-							.attr("title", info.author_sort)
-							.attr("href", "offline.html?query=" + encodeURIComponent(info.author_sort));
-
-						books.append(cell);
-					}
-				});
-			}
-		});
-	}
+                            localforage.setItem(cacheId + '.book', resp.blob());
+                        }
+                    }));
+
+                    promises.push(fetch("backend.php?op=getpagination&id=" + data.epub_id, {credentials: 'same-origin'}).then(function(resp) {
+                        if (resp.status == 200) {
+                            console.log(cacheId + ' got pagination');
+
+                            resp.text().then(function(text) {
+                                localforage.setItem(cacheId + '.locations', JSON.parse(text));
+                            });
+                        }
+                    }));
+
+                    promises.push(fetch("backend.php?op=getlastread&id=" + data.epub_id, {credentials: 'same-origin'}).then(function(resp) {
+                        if (resp.status == 200) {
+                            console.log(cacheId + ' got lastread');
+                            resp.text().then(function(text) {
+                                localforage.setItem(cacheId + '.lastread', JSON.parse(text));
+                            });
+                        }
+                    }));
+
+                    if (data.has_cover) {
+                        promises.push(fetch("backend.php?op=cover&id=" + bookId, {credentials: 'same-origin'}).then(function(resp) {
+                            if (resp.status == 200) {
+                                console.log(cacheId + ' got cover');
+                                localforage.setItem(cacheId + '.cover', resp.blob());
+                            }
+                        }));
+                    }
+
+                    Promise.all(promises).then(() => {
+                        console.log('download done, running callback', callback);
+
+                        callback();
+
+                        $(".dl-progress")
+                            .show()
+                            .html("Finished downloading <b>" + data.title + "</b>");
+
+                        window.clearTimeout(this._dl_progress_timeout);
+
+                        this._dl_progress_timeout = window.setTimeout(function() {
+                            $(".dl-progress").fadeOut();
+                        }, 5*1000);
+                    })
+
+                });
+            }
+        });
+    }
+
+    getAll() {
+        if (confirm("Download all books on this page?")) {
+
+            $(".row > div").each((i, row) => {
+                const bookId = ($(row).attr("id") ?? "").replace("cell-", "");
+                const dropitem = $(row).find(".offline_dropitem")[0] ?? null;
+
+                if (bookId) {
+                    const cacheId = 'epube-book.' + bookId;
+
+                    localforage.getItem(cacheId).then((book) => {
+                        if (!book) {
+                            this.get(bookId, () => {
+                                this.updateOfflinePrompt(dropitem);
+                            });
+                        }
+                    });
+                }
+            });
+        }
+    }
+
+    removeFromList(elem) {
+        const bookId = elem.getAttribute("data-book-id");
+
+        this.remove(bookId, () => {
+            $("#cell-" + bookId).remove();
+        });
+    }
+
+    remove(id, callback) {
+        if (confirm("Remove download?")) {
+
+            const cacheId = "epube-book." + id;
+            const promises = [];
+
+            console.log("offline remove: " + id);
+
+            localforage.iterate(function(value, key /*, i */) {
+                if (key.match(cacheId)) {
+                    promises.push(localforage.removeItem(key));
+                }
+            });
+
+            Promise.all(promises).then(() => {
+                console.log('remove done, running callback', callback);
+
+                // just promise.all is not enough, need to wait a bit for localforage to actually delete item (?)
+                window.setTimeout(() => {
+                    callback();
+                }, 250);
+            });
+        }
+    }
+
+    populateList() {
+        const params = new URLSearchParams({
+            op: "list",
+            mode: this.index_mode,
+            query: this.index_query,
+            offset: String(this.index_offset),
+            limit: String(60),
+        });
+
+        $.get("backend.php?" + params.toString()).done((data) => {
+            const books = $("#books_container");
+            books.html("");
+
+            if (data.books && data.books.length > 0) {
+                data.books.forEach((book) => {
+                    const thumb_class = book.is_read ? "read" : "";
+                    const title_class = book.in_progress ? "in_progress" : "";
+                    const fav_attr = book.is_fav ? "1" : "0";
+                    const fav_prompt = book.is_fav ? "Remove from favorites" : "Add to favorites";
+
+                    const series_html = book.series_name ?
+                        `<div><a title="${this.escapeHtml(book.series_full)}" href="${this.escapeHtml(book.series_link)}">${this.escapeHtml(book.series_full)}</a></div>` :
+                        "";
+
+                    const author_link = book.author_sort ?
+                        `?${new URLSearchParams({query: book.author_sort}).toString()}` :
+                        "";
+
+                    const download_html = book.download_formats
+                        .map((fmt) => {
+                            const label_class = fmt.format === "EPUB" ? "label-success" : "label-primary";
+                            return `<li><a target="_blank" href="backend.php?op=download&id=${fmt.id}">Download: <span class="label ${label_class}">${fmt.format}</span></a></li>`;
+                        })
+                        .join("");
+
+                    const cell = $(`<div class="col-xxs-6 col-xs-3 col-sm-3 col-md-2" id="cell-${book.id}">
+                        ${book.read_link ?
+                            `<a class="thumbnail ${thumb_class}" href="${book.read_link}">` :
+                            `<span class="thumbnail ${thumb_class}">`}
+                            <img style="display : none" data-book-id="${book.id}" data-cover-link="${book.cover_link}">
+                        ${book.read_link ? "</a>" : "</span>"}
+                        <div class="caption">
+                            <div title="${this.escapeHtml(book.title)}" class="${title_class}">
+                                ${book.read_link ?
+                                    `<a href="${book.read_link}">${this.escapeHtml(book.title)}</a>` :
+                                    this.escapeHtml(book.title)}
+                            </div>
+                            ${series_html}
+                            <div><a title="${this.escapeHtml(book.author_sort)}" href="${this.escapeHtml(author_link)}">${this.escapeHtml(book.author_sort)}</a></div>
+                        </div>
+                        <div class="dropdown" style="white-space : nowrap">
+                            <a href="#" data-toggle="dropdown" role="button">More...<span class="caret"></span></a>
+                            <ul class="dropdown-menu" aria-labelledby="dLabel">
+                                <li><a href="#" class="summary_link" data-book-id="${book.id}">Summary</a></li>
+                                <li><a href="#" class="fav_item" data-is-fav="${fav_attr}" data-book-id="${book.id}">${fav_prompt}</a></li>
+                                ${book.epub_id ? `<li><a href="#" data-book-id="${book.id}" class="offline_dropitem"></a></li><li class="divider"></li>` : ""}
+                                ${download_html}
+                            </ul>
+                        </div>
+                    </div>`);
+
+                    books.append(cell);
+                });
+
+                this.showCovers();
+                this.updateOfflinePrompts();
+
+                $(".summary_link").on('click', (e) => {
+                    e.preventDefault();
+                    this.showSummary(e.currentTarget);
+                });
+
+                $(".fav_item").on('click', (e) => {
+                    e.preventDefault();
+                    this.toggleFavorite(e.currentTarget);
+                });
+
+                $(".offline_dropitem").on('click', async (e) => {
+                    e.preventDefault();
+                    const bookId = e.currentTarget.getAttribute("data-book-id");
+                    const cacheId = "epube-book." + bookId;
+                    const book = await localforage.getItem(cacheId);
+
+                    if (book) {
+                        this.remove(bookId, () => {
+                            this.updateOfflinePrompt(e.currentTarget);
+                        });
+                    } else {
+                        this.get(bookId, () => {
+                            this.updateOfflinePrompt(e.currentTarget);
+                        });
+                    }
+                });
+            }
+
+            this.updateIndexPagination(data);
+        });
+    }
+
+    updateIndexPagination(data) {
+        const prevLi = $(".pager .previous");
+        const nextLi = $(".pager .next");
+        const pagerInfo = $(".pager .pager-info");
+
+        const prevParams = new URLSearchParams({
+            mode: this.index_mode,
+            query: this.index_query,
+            offset: String(this.index_offset - 60),
+        });
+        const nextParams = new URLSearchParams({
+            mode: this.index_mode,
+            query: this.index_query,
+            offset: String(this.index_offset + 60),
+        });
+
+        if (this.index_offset > 0) {
+            prevLi.removeClass("disabled");
+            prevLi.find("a").attr("href", "?" + prevParams.toString());
+        } else {
+            prevLi.addClass("disabled");
+            prevLi.find("a").attr("href", "#");
+        }
+
+        if (data.books && data.books.length >= 60) {
+            nextLi.removeClass("disabled");
+            nextLi.find("a").attr("href", "?" + nextParams.toString());
+        } else {
+            nextLi.addClass("disabled");
+            nextLi.find("a").attr("href", "#");
+        }
+
+        const limit = data.limit || 60;
+        const total = data.total || 0;
+        const currentPage = Math.floor(this.index_offset / limit) + 1;
+        const totalPages = limit > 0 ? Math.ceil(total / limit) : 1;
+
+        pagerInfo.find("span").text(`Page ${currentPage} of ${totalPages}`);
+    }
+
+    escapeHtml(str) {
+        if (!str) return "";
+        const div = document.createElement("div");
+        div.appendChild(document.createTextNode(str));
+        return div.innerHTML;
+    }
+
+    async search() {
+        const query = $(".search_query").val();
+
+        await localforage.setItem("epube.search-query", query);
+
+        this.populateOfflineList();
+
+        return false;
+    }
+
+    async removeAll() {
+        if (confirm("Remove all downloaded books?")) {
+
+            const promises = [];
+
+            localforage.iterate(function(value, key/*, i*/) {
+                if (key.match("epube-book")) {
+                    promises.push(localforage.removeItem(key));
+                }
+            });
+
+            await Promise.all(promises);
+
+            this.populateOfflineList();
+        }
+    }
+
+    populateOfflineList() {
+        let query = this.urlParam("query");
+
+        if (query) query = String(query).toLowerCase();
+
+        const books = $("#books_container");
+        books.html("");
+
+        localforage.iterate((value, key/*, i*/) => {
+            if (key.match(/epube-book\.\d{1,}$/)) {
+
+                Promise.all([
+                    localforage.getItem(key),
+                    localforage.getItem(key + ".cover"),
+                    localforage.getItem(key + ".lastread"),
+                    localforage.getItem(key + ".book")
+                ]).then((results) => {
+
+                    if (results[0] && results[3]) {
+                        const info = results[0];
+
+                        if (query) {
+                            const match =
+                                (info.series_name && info.series_name.toLowerCase().match(query)) ||
+                                (info.title && info.title.toLowerCase().match(query)) ||
+                                (info.author_sort && info.author_sort.toLowerCase().match(query));
+
+                            if (!match) return;
+                        }
+
+                        let cover = "";
+
+                        if (results && results[1]) {
+                            cover = URL.createObjectURL(results[1]);
+                        }
+
+                        let in_progress = false;
+                        let is_read = false;
+
+                        const lastread = results[2];
+                        if (lastread) {
+                            in_progress = lastread.page > 0;
+                            is_read = lastread.total > 0 && lastread.total - lastread.page < 5;
+                        }
+
+                        const thumb_class = is_read ? "read" : "";
+                        const title_class = in_progress ? "in_progress" : "";
+
+                        const series_link = info.series_name ? `<div><a class="series_link" href="#">${info.series_name + " [" + info.series_index + "]"}</a></div>` : "";
+
+                        const cell = $(`<div class="col-xxs-6 col-xs-4 col-sm-3 col-md-2" id="cell-${info.id}">
+                            <a class="thumbnail ${thumb_class}" href="read.html?id=${info.epub_id}&b=${info.id}">
+                                <img style="display : none">
+                            </a>
+                            <div class="caption">
+                                <div><a class="${title_class}" href="read.html?id=${info.epub_id}&b=${info.id}">${info.title}</a></div>
+                                <div><a class="author_link" href="#">${info.author_sort}</a></div>
+                                ${series_link}
+                            </div>
+                            <div class="dropdown" style="white-space : nowrap">
+                                <a href="#" data-toggle="dropdown" role="button">More...<span class="caret"></span></a>
+                                <ul class="dropdown-menu">
+                                    <li><a href="#" class="offline_summary" data-book-id="${info.id}">Summary</a></li>
+                                    <li><a href="#" class="remove_offline_data" data-book-id="${info.id}">Remove offline data</a></li>
+                                </ul>
+                            </div>
+                        </div>`);
+
+                        $(cell).find(".offline_summary").on('click', (e) => {
+                            e.preventDefault();
+                            this.showSummary(e.currentTarget);
+                        });
+
+                        $(cell).find(".remove_offline_data").on('click', (e) => {
+                            e.preventDefault();
+                            this.removeFromList(e.currentTarget);
+                        });
+
+                        if (cover) {
+                            cell.find("img")
+                                .css("background-image", "url(" + cover + ")")
+                                .fadeIn();
+                        } else {
+                            cell
+                                .fadeIn();
+                        }
+
+                        cell.find(".series_link")
+                            .attr("title", info.series_name + " [" + info.series_index  + "]")
+                            .attr("href", "offline.html?query=" + encodeURIComponent(info.series_name));
+
+                        cell.find(".author_link")
+                            .attr("title", info.author_sort)
+                            .attr("href", "offline.html?query=" + encodeURIComponent(info.author_sort));
+
+                        books.append(cell);
+                    }
+                });
+            }
+        });
+    }
 
 }
diff --git a/src/csrf.js b/src/csrf.js
index 98aa1de..fd35d29 100644
--- a/src/csrf.js
+++ b/src/csrf.js
@@ -9,21 +9,21 @@
  */
 /* eslint-disable-next-line no-unused-vars */
 function setupCsrfPrefilter(token) {
-	console.log('setting prefilter for token', token);
+    console.log('setting prefilter for token', token);
 
-	/* eslint-disable no-unused-vars */
-	$.ajaxPrefilter((options, originalOptions, jqXHR) => {
-		if (originalOptions.type !== 'post' || options.type !== 'post') {
-			return;
-		}
+    /* eslint-disable no-unused-vars */
+    $.ajaxPrefilter((options, originalOptions, jqXHR) => {
+        if (originalOptions.type !== 'post' || options.type !== 'post') {
+            return;
+        }
 
-		const datatype = typeof originalOptions.data;
+        const datatype = typeof originalOptions.data;
 
-		if (datatype == 'object')
-			options.data = $.param($.extend(originalOptions.data, {"csrf_token": token}));
-		else if (datatype == 'string')
-			options.data = originalOptions.data + "&csrf_token=" + encodeURIComponent(token);
+        if (datatype == 'object')
+            options.data = $.param($.extend(originalOptions.data, {"csrf_token": token}));
+        else if (datatype == 'string')
+            options.data = originalOptions.data + "&csrf_token=" + encodeURIComponent(token);
 
-		console.log('>>>', options);
-	});
+        console.log('>>>', options);
+    });
 }
diff --git a/src/reader.js b/src/reader.js
index 1ffb06e..259e66d 100644
--- a/src/reader.js
+++ b/src/reader.js
@@ -14,1772 +14,1772 @@ const PAGE_RESET_PROGRESS = -1;
 
 /* eslint-disable-next-line no-unused-vars */
 class ReaderClass extends AppCommon {
-	csrf_token = "";
+    csrf_token = "";
 
-	last_stored_cfi = "";
+    last_stored_cfi = "";
 
-	startup_finished = false;
+    startup_finished = false;
 
-	open_last_read_when_displayed = true;
+    open_last_read_when_displayed = true;
 
-	hyphenate = {};
+    hyphenate = {};
 
-	_prevent_lastread_timeout;
+    _prevent_lastread_timeout;
 
-	_prevent_lastread;
+    _prevent_lastread;
 
-	version = BUILD_CACHE_VERSION;
+    version = BUILD_CACHE_VERSION;
 
-	/**
-	 * @type {ePub.Book}
-	 */
-	book;
+    /**
+     * @type {ePub.Book}
+     */
+    book;
 
-	/** @type {SwipeState} */
-	_swipeState = {
-		active: false,
-		startX: 0,
-		startY: 0,
-		startTime: 0,
-		direction: null,
-	};
+    /** @type {SwipeState} */
+    _swipeState = {
+        active: false,
+        startX: 0,
+        startY: 0,
+        startTime: 0,
+        direction: null,
+    };
 
-	/** @type {SwipeConfig} */
-	_swipeConfig = {
-		minDistance: 50,		   // px — minimum horizontal travel to count as swipe
-		velocityThreshold: 0.3,	// px/ms — minimum swipe speed
-		verticalDistanceThreshold: 80, // px — vertical movement before cancelling
-	};
+    /** @type {SwipeConfig} */
+    _swipeConfig = {
+        minDistance: 50,           // px — minimum horizontal travel to count as swipe
+        velocityThreshold: 0.3,    // px/ms — minimum swipe speed
+        verticalDistanceThreshold: 80, // px — vertical movement before cancelling
+    };
 
-	constructor() {
-		super();
+    constructor() {
+        super();
 
-		this.book = new ePub.Book();
-		this.loader = new ReaderLoader();
-	}
+        this.book = new ePub.Book();
+        this.loader = new ReaderLoader();
+    }
 
-	onTouchStart(evt) {
-		const touch = evt.touches[0] || evt.changedTouches[0];
+    onTouchStart(evt) {
+        const touch = evt.touches[0] || evt.changedTouches[0];
 
-		this._swipeState = {
-			active: true,
-			startX: touch.clientX,
-			startY: touch.clientY,
-			startTime: Date.now(),
-			direction: evt.target.id == "right" ? 'left' : 'right',
-		};
-	}
+        this._swipeState = {
+            active: true,
+            startX: touch.clientX,
+            startY: touch.clientY,
+            startTime: Date.now(),
+            direction: evt.target.id == "right" ? 'left' : 'right',
+        };
+    }
 
-	onTouchEnd(evt) {
-		if (!this._swipeState.active) return;
+    onTouchEnd(evt) {
+        if (!this._swipeState.active) return;
 
-		const touch = evt.changedTouches[0] || evt.changedTouches[evt.changedTouches.length - 1];
-		const deltaX = touch.clientX - this._swipeState.startX;
-		const deltaTime = Date.now() - this._swipeState.startTime;
+        const touch = evt.changedTouches[0] || evt.changedTouches[evt.changedTouches.length - 1];
+        const deltaX = touch.clientX - this._swipeState.startX;
+        const deltaTime = Date.now() - this._swipeState.startTime;
 
-		const velocity = deltaTime > 0 ? Math.abs(deltaX) / deltaTime : 0;
+        const velocity = deltaTime > 0 ? Math.abs(deltaX) / deltaTime : 0;
 
-		const isSwipe = Math.abs(deltaX) >= this._swipeConfig.minDistance && velocity >= this._swipeConfig.velocityThreshold;
-		const isLeft = this._swipeState.direction == "left";
+        const isSwipe = Math.abs(deltaX) >= this._swipeConfig.minDistance && velocity >= this._swipeConfig.velocityThreshold;
+        const isLeft = this._swipeState.direction == "left";
 
-		const directionMatches = isLeft ? deltaX < 0 : deltaX > 0;
+        const directionMatches = isLeft ? deltaX < 0 : deltaX > 0;
 
-		if (isSwipe && directionMatches) {
-			evt.preventDefault();
-			evt.stopPropagation();
+        if (isSwipe && directionMatches) {
+            evt.preventDefault();
+            evt.stopPropagation();
 
-			if (isLeft) {
-				this.nextPage();
-			} else {
-				this.prevPage();
-			}
-		}
-	}
+            if (isLeft) {
+                this.nextPage();
+            } else {
+                this.prevPage();
+            }
+        }
+    }
 
-	onTouchMove(evt) {
-		if (!this._swipeState.active) return;
+    onTouchMove(evt) {
+        if (!this._swipeState.active) return;
 
-		const touch = evt.touches[0] || evt.changedTouches[0];
-		const deltaY = Math.abs(touch.clientY - this._swipeState.startY);
+        const touch = evt.touches[0] || evt.changedTouches[0];
+        const deltaY = Math.abs(touch.clientY - this._swipeState.startY);
 
-		// Cancel if too much vertical movement
-		if (deltaY > this._swipeConfig.verticalDistanceThreshold) {
-			this._swipeState.active = false;
-			return;
-		}
-	}
+        // Cancel if too much vertical movement
+        if (deltaY > this._swipeConfig.verticalDistanceThreshold) {
+            this._swipeState.active = false;
+            return;
+        }
+    }
 
-	async init() {
-		console.log('version', this.version, 'current, worker', await this.getActiveCacheVersion());
+    async init() {
+        console.log('version', this.version, 'current, worker', await this.getActiveCacheVersion());
 
-		this.csrf_token = Cookie.get('epube_csrf_token');
+        this.csrf_token = Cookie.get('epube_csrf_token');
 
-		/** global setupCsrfPrefilter */
-		setupCsrfPrefilter(this.csrf_token);
+        /** global setupCsrfPrefilter */
+        setupCsrfPrefilter(this.csrf_token);
 
-		$(document).on("keyup", (e) => {
-			this.hotkeyHandler(e);
-		});
+        $(document).on("keyup", (e) => {
+            this.hotkeyHandler(e);
+        });
 
-		$(".close_book").on("click", () => {
-			this.close();
-		});
+        $(".close_book").on("click", () => {
+            this.close();
+        });
 
-		$("#left").on("mouseup", () => {
-			this.prevPage();
-		});
-
-		$(".search_input").on("change", () => {
-			this.search();
-		});
+        $("#left").on("mouseup", () => {
+            this.prevPage();
+        });
+
+        $(".search_input").on("change", () => {
+            this.search();
+        });
 
-		$(".prev_location_btn").on("click", (evt) => {
-			this.openPrevious(evt.target);
-		});
+        $(".prev_location_btn").on("click", (evt) => {
+            this.openPrevious(evt.target);
+        });
 
-		$("#right").on("mouseup", () => {
-			this.nextPage();
-		});
+        $("#right").on("mouseup", () => {
+            this.nextPage();
+        });
 
-		$("#left, #right").on("touchstart", (evt) => {
-			this.onTouchStart(evt);
-		});
+        $("#left, #right").on("touchstart", (evt) => {
+            this.onTouchStart(evt);
+        });
 
-		$("#left, #right").on("touchmove", (evt) => {
-			this.onTouchMove(evt);
-		});
+        $("#left, #right").on("touchmove", (evt) => {
+            this.onTouchMove(evt);
+        });
 
-		$("#left, #right").on("touchend", (evt) => {
-			this.onTouchEnd(evt);
-		});
+        $("#left, #right").on("touchend", (evt) => {
+            this.onTouchEnd(evt);
+        });
 
-		const load_failed = await this.loader.init(this);
+        const load_failed = await this.loader.init(this);
 
-		console.log('[init] load failed', load_failed);
+        console.log('[init] load failed', load_failed);
 
-		if (!load_failed) {
-			this.initSecondStage();
-		} else {
-			this.applyTheme();
+        if (!load_failed) {
+            this.initSecondStage();
+        } else {
+            this.applyTheme();
 
-			$(".loading-message").text('Resource loader failed to initialize.');
-		}
-	}
+            $(".loading-message").text('Resource loader failed to initialize.');
+        }
+    }
 
-	// another method, maybe use this: window.matchMedia("(pointer: coarse)").matches
-	// https://stackoverflow.com/questions/4817029/whats-an-optimal-or-efficient-way-to-detect-a-touch-screen-device-using-javas
-	isTouchDevice() {
-		return ('ontouchstart' in window) || (navigator.maxTouchPoints > 0);
-	}
+    // another method, maybe use this: window.matchMedia("(pointer: coarse)").matches
+    // https://stackoverflow.com/questions/4817029/whats-an-optimal-or-efficient-way-to-detect-a-touch-screen-device-using-javas
+    isTouchDevice() {
+        return ('ontouchstart' in window) || (navigator.maxTouchPoints > 0);
+    }
 
-	/**
-	 * @param {boolean} offline
-	 */
-	onOfflineModeChanged(offline) {
-		console.log('onOfflineModeChanged', offline);
+    /**
+     * @param {boolean} offline
+     */
+    onOfflineModeChanged(offline) {
+        console.log('onOfflineModeChanged', offline);
 
-		if (!offline && this.book) {
-			console.log("we're online, storing lastread");
+        if (!offline && this.book) {
+            console.log("we're online, storing lastread");
 
-			const currentCfi = this.book.rendition.currentLocation().start.cfi;
-			const currentPage = Math.round(this.book.locations.percentageFromCfi(currentCfi) * 100); // TODO wtf
+            const currentCfi = this.book.rendition.currentLocation().start.cfi;
+            const currentPage = Math.round(this.book.locations.percentageFromCfi(currentCfi) * 100); // TODO wtf
 
-			$.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: currentPage,
-				cfi: currentCfi, timestamp: new Date().getTime() }, function() {
-					//
-				})
-				.fail(function(e) {
-					if (e && e.status == 401) {
-						window.location.href = "index.php";
-					}
-				});
-		}
-	}
+            $.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: currentPage,
+                cfi: currentCfi, timestamp: new Date().getTime() }, function() {
+                    //
+                })
+                .fail(function(e) {
+                    if (e && e.status == 401) {
+                        window.location.href = "index.php";
+                    }
+                });
+        }
+    }
 
-	async initSecondStage() {
+    async initSecondStage() {
 
-		if (typeof EpubeApp != "undefined") {
-			EpubeApp.setPage("PAGE_READER");
-		} else {
-			$(window).on('online', () => {
-				this.onOfflineModeChanged(false);
-			});
+        if (typeof EpubeApp != "undefined") {
+            EpubeApp.setPage("PAGE_READER");
+        } else {
+            $(window).on('online', () => {
+                this.onOfflineModeChanged(false);
+            });
 
-			$(window).on('offline', () => {
-				this.onOfflineModeChanged(true);
-			});
-		}
+            $(window).on('offline', () => {
+                this.onOfflineModeChanged(true);
+            });
+        }
 
-		this.applyTheme();
+        this.applyTheme();
 
-		const bookinfo = await localforage.getItem(this.cacheId());
+        const bookinfo = await localforage.getItem(this.cacheId());
 
-		if (!bookinfo) {
-			const bookId = this.urlParam("b");
+        if (!bookinfo) {
+            const bookId = this.urlParam("b");
 
-			console.log('requesting bookinfo for book', bookId)
+            console.log('requesting bookinfo for book', bookId)
 
-			try {
-				const resp = await $.post("backend.php", {op: "getinfo", id: bookId });
+            try {
+                const resp = await $.post("backend.php", {op: "getinfo", id: bookId });
 
-				if (resp.has_cover) {
-					const cover = await fetch("backend.php?op=cover&id=" + bookId);
+                if (resp.has_cover) {
+                    const cover = await fetch("backend.php?op=cover&id=" + bookId);
 
-					if (cover.ok)
-						await localforage.setItem(this.cacheId('cover'), cover.blob());
-				}
+                    if (cover.ok)
+                        await localforage.setItem(this.cacheId('cover'), cover.blob());
+                }
 
-				await localforage.setItem(this.cacheId(), resp);
+                await localforage.setItem(this.cacheId(), resp);
 
-				console.log('bookinfo saved');
+                console.log('bookinfo saved');
 
-			} catch (e) {
-				// @type {NetworkError}
-				const err = /** @type {*} */(e);
+            } catch (e) {
+                // @type {NetworkError}
+                const err = /** @type {*} */(e);
 
-				console.error(err);
+                console.error(err);
 
-				$(".loading-message").html(`Unable to load book info.<br/><small>${err.responseText}</small>`);
-				return;
-			}
-		}
+                $(".loading-message").html(`Unable to load book info.<br/><small>${err.responseText}</small>`);
+                return;
+            }
+        }
 
-		console.log('trying to load book...');
+        console.log('trying to load book...');
 
-		let book_data = await localforage.getItem(this.cacheId("book"));
+        let book_data = await localforage.getItem(this.cacheId("book"));
 
-		if (!book_data) {
-			console.log("local data not found, loading from network...");
+        if (!book_data) {
+            console.log("local data not found, loading from network...");
 
-			$(".loading-message").html("Downloading book…");
+            $(".loading-message").html("Downloading book…");
 
-			const book_resp = await fetch("backend.php?op=download&id=" + this.urlParam("id"));
+            const book_resp = await fetch("backend.php?op=download&id=" + this.urlParam("id"));
 
-			if (book_resp.ok) {
-				book_data = await book_resp.blob();
+            if (book_resp.ok) {
+                book_data = await book_resp.blob();
 
-				if (book_data) {
-					await localforage.setItem(this.cacheId('book'), book_data);
-					console.log('saved local data for book');
-				} else {
-					$(".loading-message").html("Unable to get book blob data.");
-					return;
-				}
+                if (book_data) {
+                    await localforage.setItem(this.cacheId('book'), book_data);
+                    console.log('saved local data for book');
+                } else {
+                    $(".loading-message").html("Unable to get book blob data.");
+                    return;
+                }
 
-			} else {
-				$(".loading-message").html(`Unable to download book: ${book_resp.status}`);
-				return;
-			}
-		}
+            } else {
+                $(".loading-message").html(`Unable to download book: ${book_resp.status}`);
+                return;
+            }
+        }
 
-		const fileReader = new FileReader();
-		const _reader = this;
+        const fileReader = new FileReader();
+        const _reader = this;
 
-		fileReader.onload = function() {
-			try {
-				_reader.openBookData(this.result);
-			} catch (e) {
-				console.error(e);
-				$(".loading-message").html("Unable to load book blob: " + e);
-			}
-		};
+        fileReader.onload = function() {
+            try {
+                _reader.openBookData(this.result);
+            } catch (e) {
+                console.error(e);
+                $(".loading-message").html("Unable to load book blob: " + e);
+            }
+        };
 
-		fileReader.onerror = (e) => {
-			console.log('filereader error', e);
-			$(".loading-message").html("Unable to open book.<br/><small>" + e + "</small>");
-		};
+        fileReader.onerror = (e) => {
+            console.log('filereader error', e);
+            $(".loading-message").html("Unable to open book.<br/><small>" + e + "</small>");
+        };
 
-		fileReader.readAsArrayBuffer(book_data);
-	}
+        fileReader.readAsArrayBuffer(book_data);
+    }
 
-	async openBookData(book_data) {
-		//this.book = new ePub.Book();
+    async openBookData(book_data) {
+        //this.book = new ePub.Book();
 
-		try {
-			await this.book.open(book_data);
-		} catch (e) {
-			console.error(e);
-			$(".loading-message").html(`Unable to open book.<br/><small>${e instanceof Error ? e.message: e}</small>`);
-			return;
-		}
+        try {
+            await this.book.open(book_data);
+        } catch (e) {
+            console.error(e);
+            $(".loading-message").html(`Unable to open book.<br/><small>${e instanceof Error ? e.message: e}</small>`);
+            return;
+        }
 
-		await this.book.ready;
+        await this.book.ready;
 
-		console.log('book is ready');
+        console.log('book is ready');
 
-		await this.showBookInfo(this.book);
-		await this.loadLocations(this.book);
+        await this.showBookInfo(this.book);
+        await this.loadLocations(this.book);
 
-		const rendition = this.book.renderTo("reader", {
-			width: '100%',
-			height: '100%',
-			allowScriptedContent: false,
-			minSpreadWidth: 961
-		});
+        const rendition = this.book.renderTo("reader", {
+            width: '100%',
+            height: '100%',
+            allowScriptedContent: false,
+            minSpreadWidth: 961
+        });
 
-		$(".location").on('click', async () => {
-			const current = Math.floor(rendition.currentLocation().start.location / LOCATION_DIVISOR);
-			const total = Math.floor(this.book.locations.length() / LOCATION_DIVISOR);
+        $(".location").on('click', async () => {
+            const current = Math.floor(rendition.currentLocation().start.location / LOCATION_DIVISOR);
+            const total = Math.floor(this.book.locations.length() / LOCATION_DIVISOR);
 
-			const page = prompt("Jump to location [1-" + total + "]", String(current));
+            const page = prompt("Jump to location [1-" + total + "]", String(current));
 
-			if (page)
-				await rendition.display(this.book.locations._locations[parseInt(page) * LOCATION_DIVISOR]);
-		});
-
-		const enable_hyphens = await localforage.getItem("epube.enable-hyphens");
+            if (page)
+                await rendition.display(this.book.locations._locations[parseInt(page) * LOCATION_DIVISOR]);
+        });
+
+        const enable_hyphens = await localforage.getItem("epube.enable-hyphens");
 
-		if (enable_hyphens) {
-			/* global hyphenationPatternsEnUs, hyphenationPatternsRu, createHyphenator */
-			this.hyphenate.en = createHyphenator(hyphenationPatternsEnUs, { html: true });
-			this.hyphenate.ru = createHyphenator(hyphenationPatternsRu, { html: true });
-		}
-
-		this.initRenditionHooks(this.book, rendition);
-		this.initModals();
-		this.initToc(this.book);
-
-		// open first page at startup, lastread will open when it is rendered
-		this.blockLastReadUpdate();
-		await rendition.display();
-
-		console.log('startup finished');
-		this.startup_finished = true;
-	}
-
-	/**
-	 * @param {ePub.Book} book
-	 */
-	async showBookInfo(book) {
-		const bookinfo = await localforage.getItem(this.cacheId());
-
-		let title;
-		let author;
-
-		if (bookinfo) {
-			title = bookinfo.title;
-			author = bookinfo.author_sort;
-		} else {
-			const metadata = book.packaging.metadata;
-
-			title = metadata.title;
-			author = metadata.creator;
-		}
-
-		document.title = title + " – " + author + " – The Epube";
-
-		$(".title")
-			.text(title)
-			.attr("title", title + " – " + author);
-
-		if (typeof EpubeApp != "undefined") {
-			EpubeApp.setTitle(title);
-			EpubeApp.showActionBar(false);
-		}
-	}
-
-	/**
-	 * @param {ePub.Book} book
-	 */
-	async loadLocations(book) {
-		let locations = await localforage.getItem(this.cacheId("locations"));
+        if (enable_hyphens) {
+            /* global hyphenationPatternsEnUs, hyphenationPatternsRu, createHyphenator */
+            this.hyphenate.en = createHyphenator(hyphenationPatternsEnUs, { html: true });
+            this.hyphenate.ru = createHyphenator(hyphenationPatternsRu, { html: true });
+        }
+
+        this.initRenditionHooks(this.book, rendition);
+        this.initModals();
+        this.initToc(this.book);
+
+        // open first page at startup, lastread will open when it is rendered
+        this.blockLastReadUpdate();
+        await rendition.display();
+
+        console.log('startup finished');
+        this.startup_finished = true;
+    }
+
+    /**
+     * @param {ePub.Book} book
+     */
+    async showBookInfo(book) {
+        const bookinfo = await localforage.getItem(this.cacheId());
+
+        let title;
+        let author;
+
+        if (bookinfo) {
+            title = bookinfo.title;
+            author = bookinfo.author_sort;
+        } else {
+            const metadata = book.packaging.metadata;
+
+            title = metadata.title;
+            author = metadata.creator;
+        }
+
+        document.title = title + " – " + author + " – The Epube";
+
+        $(".title")
+            .text(title)
+            .attr("title", title + " – " + author);
+
+        if (typeof EpubeApp != "undefined") {
+            EpubeApp.setTitle(title);
+            EpubeApp.showActionBar(false);
+        }
+    }
+
+    /**
+     * @param {ePub.Book} book
+     */
+    async loadLocations(book) {
+        let locations = await localforage.getItem(this.cacheId("locations"));
 
-		// legacy format is array of objects {cfi: ..., page: ...}
-		if (locations && typeof locations[0] == "string") {
-			console.log('loading local locations...');
-			try {
-				await book.locations.load(locations);
-				return;
-			} catch (e) {
-				console.warn(e);
-			}
-		}
+        // legacy format is array of objects {cfi: ..., page: ...}
+        if (locations && typeof locations[0] == "string") {
+            console.log('loading local locations...');
+            try {
+                await book.locations.load(locations);
+                return;
+            } catch (e) {
+                console.warn(e);
+            }
+        }
 
-		if (this.isOnline()) {
-			console.log("downloading locations...");
-
-			$(".loading-message").html("Downloading locations…");
+        if (this.isOnline()) {
+            console.log("downloading locations...");
+
+            $(".loading-message").html("Downloading locations…");
 
-			const resp = await fetch("backend.php?op=getpagination&id=" + this.urlParam("id"));
+            const resp = await fetch("backend.php?op=getpagination&id=" + this.urlParam("id"));
 
-			if (resp.ok) {
-				console.log("got locations from server");
+            if (resp.ok) {
+                console.log("got locations from server");
 
-				// if this doesn't load, we'll generate locations and save them
-				try {
-					locations = await resp.json();
-				} catch (e) {
-					console.warn(e);
-				}
-
-				if (locations && typeof locations[0] == "string") {
-					console.log('saving locations locally...');
+                // if this doesn't load, we'll generate locations and save them
+                try {
+                    locations = await resp.json();
+                } catch (e) {
+                    console.warn(e);
+                }
+
+                if (locations && typeof locations[0] == "string") {
+                    console.log('saving locations locally...');
 
-					await localforage.setItem(this.cacheId("locations"), locations);
+                    await localforage.setItem(this.cacheId("locations"), locations);
 
-					try {
-						book.locations.load(locations);
+                    try {
+                        book.locations.load(locations);
 
-						return;
-					} catch (e) {
-						console.warn(e);
-					}
-				}
-			}
-		}
+                        return;
+                    } catch (e) {
+                        console.warn(e);
+                    }
+                }
+            }
+        }
 
-		$(".loading-message").html("Preparing locations…");
-
-		let generate_queue_max = 0;
-
-		locations = await book.locations.generate(100, (queue) => {
-			if (!generate_queue_max)
-				generate_queue_max = queue.length();
-
-			// what if there's only one section or something and queue is already zero
-			if (generate_queue_max > 0) {
-				const queue_pct = Math.round((1 - queue.length() / generate_queue_max) * 100); // TODO un-wtf
-
-				$(".loading-message").html(`Preparing locations (${queue_pct}%)…`);
-			}
-		});
-
-		$.post("backend.php", { op: "storepagination", id: this.urlParam("id"),
-			payload: JSON.stringify(locations), total: 100});
-
-		await localforage.setItem(this.cacheId("locations"), locations);
-	}
-
-	/**
-	 * @param {ePub.Book} book
-	 * @param {ePub.Rendition} rendition
-	 */
-	initRenditionHooks(book, rendition) {
-		console.log('initRenditionHooks');
-
-		book.spine.hooks.content.register((doc/*, section */) => {
-			this.cleanupEmbeddedStyles(doc);
-		});
+        $(".loading-message").html("Preparing locations…");
+
+        let generate_queue_max = 0;
+
+        locations = await book.locations.generate(100, (queue) => {
+            if (!generate_queue_max)
+                generate_queue_max = queue.length();
+
+            // what if there's only one section or something and queue is already zero
+            if (generate_queue_max > 0) {
+                const queue_pct = Math.round((1 - queue.length() / generate_queue_max) * 100); // TODO un-wtf
+
+                $(".loading-message").html(`Preparing locations (${queue_pct}%)…`);
+            }
+        });
+
+        $.post("backend.php", { op: "storepagination", id: this.urlParam("id"),
+            payload: JSON.stringify(locations), total: 100});
+
+        await localforage.setItem(this.cacheId("locations"), locations);
+    }
+
+    /**
+     * @param {ePub.Book} book
+     * @param {ePub.Rendition} rendition
+     */
+    initRenditionHooks(book, rendition) {
+        console.log('initRenditionHooks');
+
+        book.spine.hooks.content.register((doc/*, section */) => {
+            this.cleanupEmbeddedStyles(doc);
+        });
 
-		rendition.hooks.content.register(async (contents) => {
-
-			contents.on("linkClicked", (href) => {
-				console.log('linkClicked', href);
+        rendition.hooks.content.register(async (contents) => {
+
+            contents.on("linkClicked", (href) => {
+                console.log('linkClicked', href);
 
-				this.blockLastReadUpdate();
+                this.blockLastReadUpdate();
 
-				if (href.indexOf("://") == -1) {
-					$(".prev_location_btn")
-						.attr("data-location-cfi", rendition.currentLocation().start.cfi)
-						.show();
-
-					window.requestAnimationFrame(() => {
-						this.showUI(true);
-					});
-				}
-			});
+                if (href.indexOf("://") == -1) {
+                    $(".prev_location_btn")
+                        .attr("data-location-cfi", rendition.currentLocation().start.cfi)
+                        .show();
+
+                    window.requestAnimationFrame(() => {
+                        this.showUI(true);
+                    });
+                }
+            });
 
-			contents.on("selected", async (cfiRange) => {
-				if (this.isOnline()) {
-					const range = await book.getRange(cfiRange);
+            contents.on("selected", async (cfiRange) => {
+                if (this.isOnline()) {
+                    const range = await book.getRange(cfiRange);
 
-					const selection = range.endContainer.data.substring(range.startOffset, range.endOffset);
+                    const selection = range.endContainer.data.substring(range.startOffset, range.endOffset);
 
-					console.log('selected', cfiRange, selection);
+                    console.log('selected', cfiRange, selection);
 
-					if (selection.match(/^[\w­]+$/)) {
-						this.lookupWord(selection, () => {
-							if (typeof EpubeApp != "undefined")
-								EpubeApp.showActionBar(false);
+                    if (selection.match(/^[\w­]+$/)) {
+                        this.lookupWord(selection, () => {
+                            if (typeof EpubeApp != "undefined")
+                                EpubeApp.showActionBar(false);
 
-								contents.window.requestAnimationFrame(() => {
-									contents.window.getSelection().removeAllRanges();
-								});
-						});
-					}
-				}
-			});
+                                contents.window.requestAnimationFrame(() => {
+                                    contents.window.getSelection().removeAllRanges();
+                                });
+                        });
+                    }
+                }
+            });
 
-			// get our stuff from resource loader and inject into iframe content
+            // get our stuff from resource loader and inject into iframe content
 
-			const match = window.location.href.match(/^.*\//);
-			const base_url = match ? match[0] : window.location.href;
+            const match = window.location.href.match(/^.*\//);
+            const base_url = match ? match[0] : window.location.href;
 
-			$(contents.document.head)
-				.append($("<style type='text/css'>")
-					.text(this.generateFontsCss(base_url)));
+            $(contents.document.head)
+                .append($("<style type='text/css'>")
+                    .text(this.generateFontsCss(base_url)));
 
-			$(contents.document.head)
-				.append($("<style type='text/css'>")
-					.text(this.loader._res_data[base_url + 'dist/reader_iframe.min.css']));
+            $(contents.document.head)
+                .append($("<style type='text/css'>")
+                    .text(this.loader._res_data[base_url + 'dist/reader_iframe.min.css']));
 
-			const theme = await localforage.getItem("epube.theme") || 'default';
+            const theme = await localforage.getItem("epube.theme") || 'default';
 
-			$(contents.document).find("body")
-				.attr("class", typeof EpubeApp != "undefined" ? "is-epube-app" : "")
-				.addClass("theme-" + theme);
+            $(contents.document).find("body")
+                .attr("class", typeof EpubeApp != "undefined" ? "is-epube-app" : "")
+                .addClass("theme-" + theme);
 
-			console.log('contents', contents);
+            console.log('contents', contents);
 
-			$(contents.window).on("click tap", (evt) => {
-				if (evt.button == 0) {
-					if ($(".modal").is(":visible"))
-						return;
+            $(contents.window).on("click tap", (evt) => {
+                if (evt.button == 0) {
+                    if ($(".modal").is(":visible"))
+                        return;
 
-					if (typeof EpubeApp != "undefined")
-						EpubeApp.toggleActionBar();
-					else
-						this.showUI(true);
-				}
-			});
-
-			$(contents.window).on("wheel", async (evt) => {
-				if (await localforage.getItem("epube.enable-wheel")) {
-					if ((evt.originalEvent?.deltaY ?? 0) > 0) {
-						this.nextPage();
-					} else if ((evt.originalEvent?.deltaY ?? 0) < 0) {
-						this.prevPage();
-					}
-				}
-			});
-		});
-
-		rendition.on("keyup", (e) => {
-			this.hotkeyHandler(e);
-		});
-
-		rendition.on('resized',  (/*chapter*/) => {
-			console.log('rendition resized');
-
-			this.blockLastReadUpdate();
-			this.open_last_read_when_displayed = true;
-		});
-
-		rendition.on('rendered', async (/* section */) => {
-			console.log('rendition rendered');
-
-			this.applyTheme();
-			this.resizeSideColumns();
-
-			try {
-				const location = rendition.currentLocation();
-
-				if (location.start) {
-					const cur_href = book.canonical(location.start.href);
-					let toc_entry = {};
-
-					$.each(this.flattenToc(book), function(i, r) {
-
-						if (book.spine.get(r.href).canonical == cur_href) {
-							toc_entry = r;
-							return;
-						}
-					});
-
-					if (toc_entry && toc_entry.label)
-						$(".chapter_title").html(toc_entry.label.trim() + " | ");
-
-					this.generateTocBar(book, this.flattenToc(book));
-				}
-
-			} catch (e) {
-				console.warn(e);
-			}
-
-			if (this.open_last_read_when_displayed) {
-				this.open_last_read_when_displayed = false;
-
-				await this.openLastRead();
-			}
-		});
-
-		// this seems to be called a lot more than rendered
-		rendition.on('displayed', function(/*chapter*/) {
-			console.log('rendition displayed');
-		});
-
-		rendition.on('relocated', (/** @type {ePub.Location} */ location) => this.onRelocated(book, location));
-	}
-
-	initModals() {
-		$('#settings-modal').on('shown.bs.modal', async () => {
-
-			const last_read = await localforage.getItem(this.cacheId("lastread"));
-
-			if (last_read && last_read.cfi) {
-				$(".lastread_input")
-					.val(last_read.page + '%')
-					.attr('title', `[local] ${last_read.cfi}`);
-			}
-
-			$(".clear_last_read")
-				.off("click")
-				.on("click", () => {
-					this.clearLastRead();
-				});
-
-			$(".open_last_read")
-				.off("click")
-				.on("click", () => {
-					this.openLastRead();
-				});
-
-			$(".mark_as_read")
-				.off("click")
-				.on("click", () => {
-					this.markAsRead();
-				});
-
-			$(".reset_locations")
-				.off("click")
-				.on("click", () => {
-					this.resetLocations();
-				});
-
-			if (navigator.onLine)
-				$.post("backend.php", { op: "getlastread", id: this.urlParam("id") }, (data) => {
-					$(".lastread_input")
-						.val(data.page + '%')
-						.attr('title', `[remote] ${data.cfi}`);
-				});
-
-			$(".font_family")
-				.off("change")
-				.on("change", (evt) => {
-					this.onFontChanged(evt.target);
-				});
-
-			$(".font_size")
-				.off("change")
-				.on("change", (evt) => {
-					this.onTextSizeChanged(evt.target);
-				});
-
-			$(".line_height")
-				.off("change")
-				.on("change", (evt) => {
-					this.onLineHeightChanged(evt.target);
-				});
-
-			$(".theme_name")
-				.off("change")
-				.on("change", (evt) => {
-					this.onThemeChanged(evt.target);
-				});
-
-			$(".enable_hyphens_checkbox")
-				.attr("checked", await localforage.getItem("epube.enable-hyphens"))
-				.off("click")
-				.on("click", (evt) => {
-					localforage.setItem("epube.enable-hyphens", evt.target.checked);
-
-					if (confirm("Toggling hyphens requires page reload. Reload now?")) {
-						window.location.reload();
-					}
-				});
-
-			$(".enable_wheel_checkbox")
-				.attr("checked", await localforage.getItem("epube.enable-wheel"))
-				.off("click")
-				.on("click", (evt) => {
-					localforage.setItem("epube.enable-wheel", evt.target.checked);
-				});
-
-			if (typeof EpubeApp != "undefined") {
-				$(".keep_ui_checkbox").parent().parent().hide();
-			} else {
-				$(".keep_ui_checkbox")
-				.attr("checked", await localforage.getItem("epube.keep-ui-visible"))
-				.off("click")
-				.on("click", (evt) => {
-					localforage.setItem("epube.keep-ui-visible", evt.target.checked);
-				});
-			}
+                    if (typeof EpubeApp != "undefined")
+                        EpubeApp.toggleActionBar();
+                    else
+                        this.showUI(true);
+                }
+            });
+
+            $(contents.window).on("wheel", async (evt) => {
+                if (await localforage.getItem("epube.enable-wheel")) {
+                    if ((evt.originalEvent?.deltaY ?? 0) > 0) {
+                        this.nextPage();
+                    } else if ((evt.originalEvent?.deltaY ?? 0) < 0) {
+                        this.prevPage();
+                    }
+                }
+            });
+        });
+
+        rendition.on("keyup", (e) => {
+            this.hotkeyHandler(e);
+        });
+
+        rendition.on('resized',  (/*chapter*/) => {
+            console.log('rendition resized');
+
+            this.blockLastReadUpdate();
+            this.open_last_read_when_displayed = true;
+        });
+
+        rendition.on('rendered', async (/* section */) => {
+            console.log('rendition rendered');
+
+            this.applyTheme();
+            this.resizeSideColumns();
+
+            try {
+                const location = rendition.currentLocation();
+
+                if (location.start) {
+                    const cur_href = book.canonical(location.start.href);
+                    let toc_entry = {};
+
+                    $.each(this.flattenToc(book), function(i, r) {
+
+                        if (book.spine.get(r.href).canonical == cur_href) {
+                            toc_entry = r;
+                            return;
+                        }
+                    });
+
+                    if (toc_entry && toc_entry.label)
+                        $(".chapter_title").html(toc_entry.label.trim() + " | ");
+
+                    this.generateTocBar(book, this.flattenToc(book));
+                }
+
+            } catch (e) {
+                console.warn(e);
+            }
+
+            if (this.open_last_read_when_displayed) {
+                this.open_last_read_when_displayed = false;
+
+                await this.openLastRead();
+            }
+        });
+
+        // this seems to be called a lot more than rendered
+        rendition.on('displayed', function(/*chapter*/) {
+            console.log('rendition displayed');
+        });
+
+        rendition.on('relocated', (/** @type {ePub.Location} */ location) => this.onRelocated(book, location));
+    }
+
+    initModals() {
+        $('#settings-modal').on('shown.bs.modal', async () => {
+
+            const last_read = await localforage.getItem(this.cacheId("lastread"));
+
+            if (last_read && last_read.cfi) {
+                $(".lastread_input")
+                    .val(last_read.page + '%')
+                    .attr('title', `[local] ${last_read.cfi}`);
+            }
+
+            $(".clear_last_read")
+                .off("click")
+                .on("click", () => {
+                    this.clearLastRead();
+                });
+
+            $(".open_last_read")
+                .off("click")
+                .on("click", () => {
+                    this.openLastRead();
+                });
+
+            $(".mark_as_read")
+                .off("click")
+                .on("click", () => {
+                    this.markAsRead();
+                });
+
+            $(".reset_locations")
+                .off("click")
+                .on("click", () => {
+                    this.resetLocations();
+                });
+
+            if (navigator.onLine)
+                $.post("backend.php", { op: "getlastread", id: this.urlParam("id") }, (data) => {
+                    $(".lastread_input")
+                        .val(data.page + '%')
+                        .attr('title', `[remote] ${data.cfi}`);
+                });
+
+            $(".font_family")
+                .off("change")
+                .on("change", (evt) => {
+                    this.onFontChanged(evt.target);
+                });
+
+            $(".font_size")
+                .off("change")
+                .on("change", (evt) => {
+                    this.onTextSizeChanged(evt.target);
+                });
+
+            $(".line_height")
+                .off("change")
+                .on("change", (evt) => {
+                    this.onLineHeightChanged(evt.target);
+                });
+
+            $(".theme_name")
+                .off("change")
+                .on("change", (evt) => {
+                    this.onThemeChanged(evt.target);
+                });
+
+            $(".enable_hyphens_checkbox")
+                .attr("checked", await localforage.getItem("epube.enable-hyphens"))
+                .off("click")
+                .on("click", (evt) => {
+                    localforage.setItem("epube.enable-hyphens", evt.target.checked);
+
+                    if (confirm("Toggling hyphens requires page reload. Reload now?")) {
+                        window.location.reload();
+                    }
+                });
+
+            $(".enable_wheel_checkbox")
+                .attr("checked", await localforage.getItem("epube.enable-wheel"))
+                .off("click")
+                .on("click", (evt) => {
+                    localforage.setItem("epube.enable-wheel", evt.target.checked);
+                });
+
+            if (typeof EpubeApp != "undefined") {
+                $(".keep_ui_checkbox").parent().parent().hide();
+            } else {
+                $(".keep_ui_checkbox")
+                .attr("checked", await localforage.getItem("epube.keep-ui-visible"))
+                .off("click")
+                .on("click", (evt) => {
+                    localforage.setItem("epube.keep-ui-visible", evt.target.checked);
+                });
+            }
 
-			$(".last-mod-timestamp").html(`${this.version}
-				(${this.isOnline() ? `<span class='text-success'>Online</span>` : `<span class='text-danger'>Offline</span>`})
-				`);
+            $(".last-mod-timestamp").html(`${this.version}
+                (${this.isOnline() ? `<span class='text-success'>Online</span>` : `<span class='text-danger'>Offline</span>`})
+                `);
 
-			$(".font_family").val(await localforage.getItem("epube.fontFamily") || DEFAULT_FONT_FAMILY);
-			$(".theme_name").val(await localforage.getItem("epube.theme") || 'default');
-
-			const zoom = $(".font_size").html("");
-
-			for (let i = 10; i <= 32; i++) {
-				const opt = $("<option>").val(i).html(i + " px");
-				zoom.append(opt);
-			}
-
-			zoom.val(await localforage.getItem("epube.fontSize") || DEFAULT_FONT_SIZE);
+            $(".font_family").val(await localforage.getItem("epube.fontFamily") || DEFAULT_FONT_FAMILY);
+            $(".theme_name").val(await localforage.getItem("epube.theme") || 'default');
+
+            const zoom = $(".font_size").html("");
+
+            for (let i = 10; i <= 32; i++) {
+                const opt = $("<option>").val(i).html(i + " px");
+                zoom.append(opt);
+            }
+
+            zoom.val(await localforage.getItem("epube.fontSize") || DEFAULT_FONT_SIZE);
 
-			const line_height = $(".line_height").html("");
-
-			for (let i = 100; i <= 220; i += 10) {
-				const opt = $("<option>").val(i).html(i + "%");
-				line_height.append(opt);
-			}
-
-			line_height.val(await localforage.getItem("epube.lineHeight") || DEFAULT_LINE_HEIGHT);
+            const line_height = $(".line_height").html("");
+
+            for (let i = 100; i <= 220; i += 10) {
+                const opt = $("<option>").val(i).html(i + "%");
+                line_height.append(opt);
+            }
+
+            line_height.val(await localforage.getItem("epube.lineHeight") || DEFAULT_LINE_HEIGHT);
 
-		});
+        });
 
-		$('#dict-modal').on('shown.bs.modal', () => {
-			$(".dict_query")
-				.off("change")
-				.on("change", () => {
-					this.lookupWord(null, null, '.dict_query');
-				});
+        $('#dict-modal').on('shown.bs.modal', () => {
+            $(".dict_query")
+                .off("change")
+                .on("change", () => {
+                    this.lookupWord(null, null, '.dict_query');
+                });
 
-			$(".dict_result").scrollTop(0);
-		});
+            $(".dict_result").scrollTop(0);
+        });
 
-		// TODO: make configurable
-		$(".dict_search_btn").on("click", function() {
-			$("#dict-modal").modal('hide');
-			window.open("https://duckduckgo.com/?q=" + $(".dict_query").val());
-		});
+        // TODO: make configurable
+        $(".dict_search_btn").on("click", function() {
+            $("#dict-modal").modal('hide');
+            window.open("https://duckduckgo.com/?q=" + $(".dict_query").val());
+        });
 
-	}
+    }
 
-	initToc(book) {
-		const _reader = this;
+    initToc(book) {
+        const _reader = this;
 
-		function toc_loc_msg(href) {
-			try {
-				const cfiBase = book.spine.get(href).cfiBase;
+        function toc_loc_msg(href) {
+            try {
+                const cfiBase = book.spine.get(href).cfiBase;
 
-				const loc = book.locations._locations.find(function(k) {
-					return k.indexOf(cfiBase) != -1
-				});
+                const loc = book.locations._locations.find(function(k) {
+                    return k.indexOf(cfiBase) != -1
+                });
 
-				return Math.round(_reader.book.locations.locationFromCfi(loc) / LOCATION_DIVISOR);
+                return Math.round(_reader.book.locations.locationFromCfi(loc) / LOCATION_DIVISOR);
 
-			} catch (e) {
-				console.warn(e);
-			}
+            } catch (e) {
+                console.warn(e);
+            }
 
-			return "";
-		}
+            return "";
+        }
 
-		function process_toc_sublist(row, list, nest) {
+        function process_toc_sublist(row, list, nest) {
 
-			if (nest == 3) return false;
+            if (nest == 3) return false;
 
-			if (row.subitems) {
+            if (row.subitems) {
 
-				const sublist = $("<ul class='toc_sublist list-unstyled'>");
+                const sublist = $("<ul class='toc_sublist list-unstyled'>");
 
-				$.each(row.subitems, function(i, row) {
+                $.each(row.subitems, function(i, row) {
 
-					const a = $("<a>")
-						.attr('href', '#')
-						.html("<b class='pull-right'>" + toc_loc_msg(row.href) + "</b>" + row.label)
-						.attr('data-href', row.href)
-						.click(function() {
-							book.rendition.display(a.attr('data-href'));
-						});
+                    const a = $("<a>")
+                        .attr('href', '#')
+                        .html("<b class='pull-right'>" + toc_loc_msg(row.href) + "</b>" + row.label)
+                        .attr('data-href', row.href)
+                        .click(function() {
+                            book.rendition.display(a.attr('data-href'));
+                        });
 
-					sublist.append($("<li>").append(a));
+                    sublist.append($("<li>").append(a));
 
-					process_toc_sublist(row, sublist, nest + 1);
+                    process_toc_sublist(row, sublist, nest + 1);
 
-				});
+                });
 
-				list.append(sublist);
-			}
-		}
+                list.append(sublist);
+            }
+        }
 
-		$('#toc-modal').on('shown.bs.modal', function() {
+        $('#toc-modal').on('shown.bs.modal', function() {
 
-			const toc = book.navigation.toc;
+            const toc = book.navigation.toc;
 
-			const list = $(".toc_list");
-			list.html("");
+            const list = $(".toc_list");
+            list.html("");
 
-			$.each(toc, function(i, row) {
+            $.each(toc, function(i, row) {
 
-				// if anything fails here the toc entry is likely useless anyway (i.e. no cfi)
-				try {
-					const a = $("<a>")
-						.attr('href', '#')
-						.html("<b class='pull-right'>" + toc_loc_msg(row.href) + "</b>" + row.label)
-						.attr('data-href', row.href)
-						.click(function() {
-							book.rendition.display(a.attr('data-href'));
-						});
+                // if anything fails here the toc entry is likely useless anyway (i.e. no cfi)
+                try {
+                    const a = $("<a>")
+                        .attr('href', '#')
+                        .html("<b class='pull-right'>" + toc_loc_msg(row.href) + "</b>" + row.label)
+                        .attr('data-href', row.href)
+                        .click(function() {
+                            book.rendition.display(a.attr('data-href'));
+                        });
 
-					list.append($("<li>").append(a));
+                    list.append($("<li>").append(a));
 
-					process_toc_sublist(row, list, 0);
+                    process_toc_sublist(row, list, 0);
 
-				} catch (e) {
-					console.warn(e);
-				}
-			});
-
-			// well the toc didn't work out, might as well generate one
-			if (list.children().length <= 1) {
+                } catch (e) {
+                    console.warn(e);
+                }
+            });
+
+            // well the toc didn't work out, might as well generate one
+            if (list.children().length <= 1) {
 
-				list.html("");
-
-				$.each(book.spine.items, function (i, row) {
-
-					const a = $("<a>")
-						.attr('href', '#')
-						.attr('title', row.url)
-						// @ts-ignore
-						.html(`Section ${i+1}`)
-						.attr('data-href', row.href)
-						.on('click', () => {
-							book.rendition.display(a.attr('data-href'));
-						});
-
-					list.append($("<li>").append(a));
-
-				});
-			}
-
-		});
-	}
-
-	/* embedded styles may conflict with our font sizes, etc */
-	cleanupEmbeddedStyles(doc) {
-		$(doc).find("p")
-				// @ts-ignore
-				.filter((i, e) => (($(e).text().length >= MIN_LENGTH_TO_JUSTIFY) ? e : null))
-					.css("text-align", "justify");
-
-		$(doc).find("html")
-				.attr("class", "");
-
-		$(doc).find("pre")
-				.css("white-space", "pre-wrap");
-
-		$(doc).find("a, p, span, em, i, strong, b, body, header, section, div, big, small, table, tr, td, th, ul, ol, li")
-				.attr("class", "")
-				.css("font-family", "inherit")
-				.css("font-size", "inherit")
-				.css("line-height", "inherit")
-				.css("color", "")
-				.css("border", "none ! important")
-				.css("background", "")
-				.css("background-color", "")
-				.attr("width", "")
-				.attr("height", "");
-
-		// same as above except for allowed font-size
-		$(doc).find("h1, h2, h3, h4, h5")
-			.attr("class", "")
-			.css("font-family", "inherit")
-			.css("color", "")
-			.css("border", "none ! important")
-			.css("background", "")
-			.css("background-color", "");
-
-		if (typeof this.hyphenate.en != "undefined") {
-			$(doc).find('p, div').each((i, elem) => {
-				const p = $(elem);
-
-				p.html(this.hyphenate.en(p.html()));
-				p.html(this.hyphenate.ru(p.html()));
-			});
-		}
-	}
-
-	generateFontsCss(base_url) {
-		return `
-			/** Calibri */
-
-			@font-face {
-				font-family: 'Calibri';
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/calibriz.ttf']});
-				font-style: italic;
-				font-weight : 700;
-			}
-
-			@font-face {
-				font-family: 'Calibri';
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/calibrib.ttf']});
-				font-style: normal;
-				font-weight : 700;
-			}
-
-			@font-face {
-				font-family: 'Calibri';
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/calibrii.ttf']});
-				font-style: italic;
-				font-weight : 400;
-			}
-
-			@font-face {
-				font-family: 'Calibri';
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/calibri.ttf']});
-				font-style: normal;
-				font-weight : 400;
-			}
-
-			/** Cambria */
-
-			@font-face {
-				font-family: 'Cambria';
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/cambriab.ttf']});
-				font-style: normal;
-				font-weight : 700;
-			}
-
-			@font-face {
-				font-family: 'Cambria';
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/cambriaz.ttf']});
-				font-style: italic;
-				font-weight : 700;
-			}
-
-			@font-face {
-				font-family: 'Cambria';
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/cambriai.ttf']});
-				font-style: italic;
-				font-weight : 400;
-			}
-
-			@font-face {
-				font-family: 'Cambria';
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/cambria.ttf']});
-				font-style: normal;
-				font-weight : 400;
-			}
-
-			/** Caecilia */
-
-			@font-face {
-				font-family: Caecilia;
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/caecilia.ttf']});
-				font-weight : normal;
-			}
-
-			@font-face {
-				font-family: Caecilia;
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/caeciliab.ttf']});
-				font-weight : bold;
-			}
-
-			@font-face {
-				font-family: Caecilia;
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/caeciliai.ttf']});
-				font-style : italic;
-			}
-
-			/** Palatino */
-
-			@font-face {
-				font-family: 'Palatino';
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/palab.ttf']});
-				font-style: normal;
-				font-weight : 700;
-			}
-
-			@font-face {
-				font-family: 'Palatino';
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/palabi.ttf']});
-				font-style: italic;
-				font-weight : 700;
-			}
-
-			@font-face {
-				font-family: 'Palatino';
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/palai.ttf']});
-				font-style: italic;
-				font-weight : 400;
-			}
-
-			@font-face {
-				font-family: 'Palatino';
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/pala.ttf']});
-				font-style: normal;
-				font-weight : 400;
-			}
-
-			/** Consolas */
-
-			@font-face {
-				font-family: 'Consolas';
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/consolab.ttf']});
-				font-style: normal;
-				font-weight : 700;
-			}
-
-			@font-face {
-				font-family: 'Consolas';
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/consolaz.ttf']});
-				font-style: italic;
-				font-weight : 700;
-			}
-
-			@font-face {
-				font-family: 'Consolas';
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/consolai.ttf']});
-				font-style: italic;
-				font-weight : 400;
-			}
-
-			@font-face {
-				font-family: 'Consolas';
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/consola.ttf']});
-				font-style: normal;
-				font-weight : 400;
-			}
-
-			/** IBM Plex Mono */
-
-			@font-face {
-				font-family: 'IBM Plex Mono';
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/IBMPlexMono-Bold.otf']});
-				font-style: normal;
-				font-weight : 700;
-			}
-
-			@font-face {
-				font-family: 'IBM Plex Mono';
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/IBMPlexMono-BoldItalic.otf']});
-				font-style: italic;
-				font-weight : 700;
-			}
-
-			@font-face {
-				font-family: 'IBM Plex Mono';
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/IBMPlexMono-TextItalic.otf']});
-				font-style: italic;
-				font-weight : 400;
-			}
-
-			@font-face {
-				font-family: 'IBM Plex Mono';
-				src: url(${this.loader._res_data[base_url + 'lib/fonts/IBMPlexMono-Text.otf']});
-				font-style: normal;
-				font-weight : 400;
-			}
-			`;
-	}
-
-	flattenTocSubItems(entry, nest) {
-		let rv = [];
-
-		if (nest == 3) return false;
-
-		if (entry.subitems) {
-			$.each(entry.subitems, (i, r) => {
-				r._nest = nest;
-
-				rv.push(r);
-				rv = rv.concat(this.flattenTocSubItems(r, nest+1));
-			});
-		}
-
-		return rv;
-	}
-
-	/**
-	 * @param { ePub.Book } book
-	 *
-	 * @returns { ePub.NavItem[] }
-	 */
-	flattenToc(book) {
-		if (this._flattened_toc) {
-			return this._flattened_toc;
-		} else {
-			let rv = [];
-
-			$.each(book.navigation.toc, (i, r) => {
-				// @ts-ignore
-				r._nest = 0;
-
-				rv.push(r);
-				rv = rv.concat(this.flattenTocSubItems(r, 1));
-			});
-
-			this._flattened_toc = rv;
-
-			return rv;
-		}
-	}
-
-	/**
-	 * @param { ePub.Book } book
-	 * @param { any[] } toc
-	 */
-	generateTocBar(book, toc) {
-		$(".spacer")
-			.html("");
-
-		$.each(toc, function(i, te) {
-			try {
-				const cfiBase = book.spine.get(te.href).cfiBase;
-				const loc = book.locations._locations.find(function(k) {
-					return k.indexOf(cfiBase) != -1
-				});
-
-				if (loc) {
-					const pct = Math.round(book.locations.percentageFromCfi(loc) * 100);
-
-					$(".spacer").append(
-						$("<div class='toc-bar-entry'>")
-							.attr('data-nest-level', te._nest)
-							.css('left', pct + '%')
-							.css('_width', (3 - te._nest) + "px")
-							.attr("title", te.label)
-						)
-
-				}
-
-			} catch (e) {
-				console.warn(e);
-			}
-		});
-
-		$(".spacer").append($("<div class='toc-bar-entry current-position'>"));
-
-		this.updateTocBarPosition(book, book.rendition.currentLocation())
-	}
-
-	updateTocBarPosition(book, location) {
-		const cur_pct = Math.round(location.start.location / book.locations.length() * 100);
-
-		$(".toc-bar-entry.current-position")
-				.css('left', cur_pct + '%');
-	}
-
-	async applyTheme() {
-		let fontSize = await localforage.getItem("epube.fontSize");
-		let fontFamily = await localforage.getItem("epube.fontFamily");
-		let lineHeight = await localforage.getItem("epube.lineHeight");
-
-		fontSize = fontSize ? fontSize + "px" : DEFAULT_FONT_SIZE + "px";
-		fontFamily = fontFamily ? fontFamily : DEFAULT_FONT_FAMILY;
-		lineHeight = lineHeight ? lineHeight + "%" : DEFAULT_LINE_HEIGHT + "%";
-
-		console.log('style', fontFamily, fontSize, lineHeight);
-		console.log('applying default theme styles...');
-
-		if (this.book && this.book.rendition)
-			this.book.rendition.themes.default({
-				html: {
-					'font-size': fontSize,
-					'font-family': "'" + fontFamily + "'",
-					'line-height': lineHeight,
-					'text-align': 'justify',
-					'text-indent': '1em'
-				}
-			});
-
-		let theme = await localforage.getItem("epube.theme") || "default";
-
-		console.log('called for theme', theme);
-
-		if (theme == "default" && typeof EpubeApp != "undefined")
-			if (EpubeApp.isNightMode())
-				theme = "night";
-
-		console.log('setting main UI theme', theme);
-
-		$("body")
-			.attr("class", typeof EpubeApp != "undefined" ? "is-epube-app" : "")
-			.addClass("epube-reader theme-" + theme)
-			.attr("data-is-loading", "false");
-
-		if (typeof EpubeApp != "undefined") {
-			window.setTimeout(function() {
-				const body = document.querySelector("body");
-				const bg_color = body ? window.getComputedStyle(body, null)
-					.getPropertyValue("background-color") : "";
-
-				let match = bg_color.match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/);
-
-				if (match) {
-					console.log("sending bgcolor", match);
-
-					EpubeApp.setStatusBarColor(parseInt(match[1]), parseInt(match[2]), parseInt(match[3]));
-				}
-
-				const title = document.querySelector(".header .title");
-				const accent_color = title ? window.getComputedStyle(title, null)
-					.getPropertyValue("color") : "";
-
-				match = accent_color.match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/);
-
-				if (match) {
-					console.log("sending accent_color", match);
-
-					EpubeApp.setAccentColor(parseInt(match[1]), parseInt(match[2]), parseInt(match[3]));
-				}
-
-			}, 250);
-		}
-
-		if (this.book && this.book.rendition)
-			this.book.rendition.getContents().forEach((rendition) => {
-				console.log(`applying styles and theme ${theme} to `, rendition);
-
-				rendition.css("font-size", fontSize);
-				rendition.css("font-family", "'" + fontFamily + "'");
-				rendition.css("line-height", lineHeight);
-				rendition.css("text-align", 'justify');
-
-				$(rendition.document).find("body")
-					.attr("class", typeof EpubeApp != "undefined" ? "is-epube-app" : "")
-					.addClass("theme-" + theme);
-			});
-	}
-
-	hotkeyHandler(e) {
-		try {
-			//console.log('K3:' + e.which, e);
-
-			if ($(".modal").is(":visible"))
-				return;
-
-			// right or space or pagedown
-			if (e.which == 39 || e.which == 32 || e.which == 34) {
-				e.preventDefault();
-				this.nextPage();
-			}
-
-			// left or pageup
-			if (e.which == 37 || e.which == 33) {
-				e.preventDefault();
-				this.prevPage();
-			}
-
-			// esc
-			if (e.which == 27) {
-				e.preventDefault();
-				this.showUI(true);
-			}
-		} catch (e) {
-			console.warn(e);
-		}
-	}
-
-	resizeSideColumns() {
-		let width = $("#reader").position().left;
-
-		if (this.book && this.book.rendition)
-			this.book.rendition.getContents().forEach((rendition) => {
-				const body = rendition.document.querySelector('body');
+                list.html("");
+
+                $.each(book.spine.items, function (i, row) {
+
+                    const a = $("<a>")
+                        .attr('href', '#')
+                        .attr('title', row.url)
+                        // @ts-ignore
+                        .html(`Section ${i+1}`)
+                        .attr('data-href', row.href)
+                        .on('click', () => {
+                            book.rendition.display(a.attr('data-href'));
+                        });
+
+                    list.append($("<li>").append(a));
+
+                });
+            }
+
+        });
+    }
+
+    /* embedded styles may conflict with our font sizes, etc */
+    cleanupEmbeddedStyles(doc) {
+        $(doc).find("p")
+                // @ts-ignore
+                .filter((i, e) => (($(e).text().length >= MIN_LENGTH_TO_JUSTIFY) ? e : null))
+                    .css("text-align", "justify");
+
+        $(doc).find("html")
+                .attr("class", "");
+
+        $(doc).find("pre")
+                .css("white-space", "pre-wrap");
+
+        $(doc).find("a, p, span, em, i, strong, b, body, header, section, div, big, small, table, tr, td, th, ul, ol, li")
+                .attr("class", "")
+                .css("font-family", "inherit")
+                .css("font-size", "inherit")
+                .css("line-height", "inherit")
+                .css("color", "")
+                .css("border", "none ! important")
+                .css("background", "")
+                .css("background-color", "")
+                .attr("width", "")
+                .attr("height", "");
+
+        // same as above except for allowed font-size
+        $(doc).find("h1, h2, h3, h4, h5")
+            .attr("class", "")
+            .css("font-family", "inherit")
+            .css("color", "")
+            .css("border", "none ! important")
+            .css("background", "")
+            .css("background-color", "");
+
+        if (typeof this.hyphenate.en != "undefined") {
+            $(doc).find('p, div').each((i, elem) => {
+                const p = $(elem);
+
+                p.html(this.hyphenate.en(p.html()));
+                p.html(this.hyphenate.ru(p.html()));
+            });
+        }
+    }
+
+    generateFontsCss(base_url) {
+        return `
+            /** Calibri */
+
+            @font-face {
+                font-family: 'Calibri';
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/calibriz.ttf']});
+                font-style: italic;
+                font-weight : 700;
+            }
+
+            @font-face {
+                font-family: 'Calibri';
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/calibrib.ttf']});
+                font-style: normal;
+                font-weight : 700;
+            }
+
+            @font-face {
+                font-family: 'Calibri';
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/calibrii.ttf']});
+                font-style: italic;
+                font-weight : 400;
+            }
+
+            @font-face {
+                font-family: 'Calibri';
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/calibri.ttf']});
+                font-style: normal;
+                font-weight : 400;
+            }
+
+            /** Cambria */
+
+            @font-face {
+                font-family: 'Cambria';
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/cambriab.ttf']});
+                font-style: normal;
+                font-weight : 700;
+            }
+
+            @font-face {
+                font-family: 'Cambria';
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/cambriaz.ttf']});
+                font-style: italic;
+                font-weight : 700;
+            }
+
+            @font-face {
+                font-family: 'Cambria';
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/cambriai.ttf']});
+                font-style: italic;
+                font-weight : 400;
+            }
+
+            @font-face {
+                font-family: 'Cambria';
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/cambria.ttf']});
+                font-style: normal;
+                font-weight : 400;
+            }
+
+            /** Caecilia */
+
+            @font-face {
+                font-family: Caecilia;
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/caecilia.ttf']});
+                font-weight : normal;
+            }
+
+            @font-face {
+                font-family: Caecilia;
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/caeciliab.ttf']});
+                font-weight : bold;
+            }
+
+            @font-face {
+                font-family: Caecilia;
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/caeciliai.ttf']});
+                font-style : italic;
+            }
+
+            /** Palatino */
+
+            @font-face {
+                font-family: 'Palatino';
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/palab.ttf']});
+                font-style: normal;
+                font-weight : 700;
+            }
+
+            @font-face {
+                font-family: 'Palatino';
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/palabi.ttf']});
+                font-style: italic;
+                font-weight : 700;
+            }
+
+            @font-face {
+                font-family: 'Palatino';
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/palai.ttf']});
+                font-style: italic;
+                font-weight : 400;
+            }
+
+            @font-face {
+                font-family: 'Palatino';
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/pala.ttf']});
+                font-style: normal;
+                font-weight : 400;
+            }
+
+            /** Consolas */
+
+            @font-face {
+                font-family: 'Consolas';
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/consolab.ttf']});
+                font-style: normal;
+                font-weight : 700;
+            }
+
+            @font-face {
+                font-family: 'Consolas';
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/consolaz.ttf']});
+                font-style: italic;
+                font-weight : 700;
+            }
+
+            @font-face {
+                font-family: 'Consolas';
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/consolai.ttf']});
+                font-style: italic;
+                font-weight : 400;
+            }
+
+            @font-face {
+                font-family: 'Consolas';
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/consola.ttf']});
+                font-style: normal;
+                font-weight : 400;
+            }
+
+            /** IBM Plex Mono */
+
+            @font-face {
+                font-family: 'IBM Plex Mono';
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/IBMPlexMono-Bold.otf']});
+                font-style: normal;
+                font-weight : 700;
+            }
+
+            @font-face {
+                font-family: 'IBM Plex Mono';
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/IBMPlexMono-BoldItalic.otf']});
+                font-style: italic;
+                font-weight : 700;
+            }
+
+            @font-face {
+                font-family: 'IBM Plex Mono';
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/IBMPlexMono-TextItalic.otf']});
+                font-style: italic;
+                font-weight : 400;
+            }
+
+            @font-face {
+                font-family: 'IBM Plex Mono';
+                src: url(${this.loader._res_data[base_url + 'lib/fonts/IBMPlexMono-Text.otf']});
+                font-style: normal;
+                font-weight : 400;
+            }
+            `;
+    }
+
+    flattenTocSubItems(entry, nest) {
+        let rv = [];
+
+        if (nest == 3) return false;
+
+        if (entry.subitems) {
+            $.each(entry.subitems, (i, r) => {
+                r._nest = nest;
+
+                rv.push(r);
+                rv = rv.concat(this.flattenTocSubItems(r, nest+1));
+            });
+        }
+
+        return rv;
+    }
+
+    /**
+     * @param { ePub.Book } book
+     *
+     * @returns { ePub.NavItem[] }
+     */
+    flattenToc(book) {
+        if (this._flattened_toc) {
+            return this._flattened_toc;
+        } else {
+            let rv = [];
+
+            $.each(book.navigation.toc, (i, r) => {
+                // @ts-ignore
+                r._nest = 0;
+
+                rv.push(r);
+                rv = rv.concat(this.flattenTocSubItems(r, 1));
+            });
+
+            this._flattened_toc = rv;
+
+            return rv;
+        }
+    }
+
+    /**
+     * @param { ePub.Book } book
+     * @param { any[] } toc
+     */
+    generateTocBar(book, toc) {
+        $(".spacer")
+            .html("");
+
+        $.each(toc, function(i, te) {
+            try {
+                const cfiBase = book.spine.get(te.href).cfiBase;
+                const loc = book.locations._locations.find(function(k) {
+                    return k.indexOf(cfiBase) != -1
+                });
+
+                if (loc) {
+                    const pct = Math.round(book.locations.percentageFromCfi(loc) * 100);
+
+                    $(".spacer").append(
+                        $("<div class='toc-bar-entry'>")
+                            .attr('data-nest-level', te._nest)
+                            .css('left', pct + '%')
+                            .css('_width', (3 - te._nest) + "px")
+                            .attr("title", te.label)
+                        )
+
+                }
+
+            } catch (e) {
+                console.warn(e);
+            }
+        });
+
+        $(".spacer").append($("<div class='toc-bar-entry current-position'>"));
+
+        this.updateTocBarPosition(book, book.rendition.currentLocation())
+    }
+
+    updateTocBarPosition(book, location) {
+        const cur_pct = Math.round(location.start.location / book.locations.length() * 100);
+
+        $(".toc-bar-entry.current-position")
+                .css('left', cur_pct + '%');
+    }
+
+    async applyTheme() {
+        let fontSize = await localforage.getItem("epube.fontSize");
+        let fontFamily = await localforage.getItem("epube.fontFamily");
+        let lineHeight = await localforage.getItem("epube.lineHeight");
+
+        fontSize = fontSize ? fontSize + "px" : DEFAULT_FONT_SIZE + "px";
+        fontFamily = fontFamily ? fontFamily : DEFAULT_FONT_FAMILY;
+        lineHeight = lineHeight ? lineHeight + "%" : DEFAULT_LINE_HEIGHT + "%";
+
+        console.log('style', fontFamily, fontSize, lineHeight);
+        console.log('applying default theme styles...');
+
+        if (this.book && this.book.rendition)
+            this.book.rendition.themes.default({
+                html: {
+                    'font-size': fontSize,
+                    'font-family': "'" + fontFamily + "'",
+                    'line-height': lineHeight,
+                    'text-align': 'justify',
+                    'text-indent': '1em'
+                }
+            });
+
+        let theme = await localforage.getItem("epube.theme") || "default";
+
+        console.log('called for theme', theme);
+
+        if (theme == "default" && typeof EpubeApp != "undefined")
+            if (EpubeApp.isNightMode())
+                theme = "night";
+
+        console.log('setting main UI theme', theme);
+
+        $("body")
+            .attr("class", typeof EpubeApp != "undefined" ? "is-epube-app" : "")
+            .addClass("epube-reader theme-" + theme)
+            .attr("data-is-loading", "false");
+
+        if (typeof EpubeApp != "undefined") {
+            window.setTimeout(function() {
+                const body = document.querySelector("body");
+                const bg_color = body ? window.getComputedStyle(body, null)
+                    .getPropertyValue("background-color") : "";
+
+                let match = bg_color.match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/);
+
+                if (match) {
+                    console.log("sending bgcolor", match);
+
+                    EpubeApp.setStatusBarColor(parseInt(match[1]), parseInt(match[2]), parseInt(match[3]));
+                }
+
+                const title = document.querySelector(".header .title");
+                const accent_color = title ? window.getComputedStyle(title, null)
+                    .getPropertyValue("color") : "";
+
+                match = accent_color.match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/);
+
+                if (match) {
+                    console.log("sending accent_color", match);
+
+                    EpubeApp.setAccentColor(parseInt(match[1]), parseInt(match[2]), parseInt(match[3]));
+                }
+
+            }, 250);
+        }
+
+        if (this.book && this.book.rendition)
+            this.book.rendition.getContents().forEach((rendition) => {
+                console.log(`applying styles and theme ${theme} to `, rendition);
+
+                rendition.css("font-size", fontSize);
+                rendition.css("font-family", "'" + fontFamily + "'");
+                rendition.css("line-height", lineHeight);
+                rendition.css("text-align", 'justify');
+
+                $(rendition.document).find("body")
+                    .attr("class", typeof EpubeApp != "undefined" ? "is-epube-app" : "")
+                    .addClass("theme-" + theme);
+            });
+    }
+
+    hotkeyHandler(e) {
+        try {
+            //console.log('K3:' + e.which, e);
+
+            if ($(".modal").is(":visible"))
+                return;
+
+            // right or space or pagedown
+            if (e.which == 39 || e.which == 32 || e.which == 34) {
+                e.preventDefault();
+                this.nextPage();
+            }
+
+            // left or pageup
+            if (e.which == 37 || e.which == 33) {
+                e.preventDefault();
+                this.prevPage();
+            }
+
+            // esc
+            if (e.which == 27) {
+                e.preventDefault();
+                this.showUI(true);
+            }
+        } catch (e) {
+            console.warn(e);
+        }
+    }
+
+    resizeSideColumns() {
+        let width = $("#reader").position().left;
+
+        if (this.book && this.book.rendition)
+            this.book.rendition.getContents().forEach((rendition) => {
+                const body = rendition.document.querySelector('body');
 
-				if (body)
-					width += parseInt(rendition.window.getComputedStyle(body).getPropertyValue('padding-left'));
-			});
+                if (body)
+                    width += parseInt(rendition.window.getComputedStyle(body).getPropertyValue('padding-left'));
+            });
 
-		console.log(`resizing side columns to ${width} px`);
+        console.log(`resizing side columns to ${width} px`);
 
-		$("#left, #right").width(width);
-	}
-
-	async markAsRead() {
-		if (confirm("Mark book as read?")) {
-			$("#settings-modal").modal('hide');
+        $("#left, #right").width(width);
+    }
+
+    async markAsRead() {
+        if (confirm("Mark book as read?")) {
+            $("#settings-modal").modal('hide');
 
-			const total = 100;
-			const lastCfi = this.book.locations.cfiFromPercentage(1);
-			const lastread_timestamp = new Date().getTime();
+            const total = 100;
+            const lastCfi = this.book.locations.cfiFromPercentage(1);
+            const lastread_timestamp = new Date().getTime();
 
-			if (this.isOnline()) {
-				const data = await $.post("backend.php", { op: "storelastread", page: total, cfi: lastCfi, id: this.urlParam("id"), timestamp: lastread_timestamp });
-				$(".lastread_input").val(data.page + '%');
-			}
-
-			await localforage.setItem(this.cacheId("lastread"),
-				{cfi: lastCfi, page: total, total: total, timestamp: lastread_timestamp});
-
-			await this.openLastRead();
-		}
-	}
-
-	async close() {
-		const location = this.book.rendition.currentLocation();
-
-		const currentCfi = location.start.cfi;
-		const currentPage = Math.round(this.book.locations.percentageFromCfi(currentCfi) * 100);
-		const totalPages = 100;
-		const lastread_timestamp = new Date().getTime();
-
-		await localforage.setItem(this.cacheId("lastread"),
-			{cfi: currentCfi, page: currentPage, total: totalPages, timestamp: lastread_timestamp});
-
-		if (this.isOnline()) {
-			$.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: currentPage,
-				cfi: currentCfi, timestamp: lastread_timestamp }, () => {
-				window.location.href = this.urlParam("rt") ? "index.php?mode=" + this.urlParam("rt") : "index.php";
-			})
-				.fail(() => {
-					window.location.href = "index.php";
-				});
-		} else {
-			window.location.href = "index.php";
-		}
-	}
-
-	cacheId(suffix) {
-		return "epube-book." + this.urlParam("b") + (suffix ? "." + suffix : "");
-	}
-
-	showUI(show) {
-		if (show)
-			$(".header,.footer").fadeIn();
-		else
-			$(".header,.footer").fadeOut();
-	}
-
-	toggleUI() {
-		if ($(".header").is(":visible"))
-			$(".header,.footer").fadeOut();
-		else
-			$(".header,.footer").fadeIn();
-	}
-
-	async lookupWord(word, callback, elem) {
-		if (elem)
-			word = $(elem).val();
-
-		word = word.replace(/­/g, "");
-
-		console.log('lookupWord', word);
-
-		$(".dict_result").html('Loading, please wait...');
-
-		$("#dict-modal").modal('show');
-
-		try {
-			const data = await $.post("backend.php", {op: 'define', word: word});
-
-			if (data) {
-
-				$(".dict_result").html(data.result.join("<br/>"));
-				$(".dict_query").val(word);
-
-				if (callback) callback();
-			}
-		} catch (e) {
-			// @type {NetworkError}
-			const err = /** @type {*} */(e);
-
-			console.error(err);
-
-			$(".dict_result").html(`Network error while looking up word: ${err.responseText}.`);
-		}
-	}
-
-	/**
-	 * @returns {Promise<void>}
-	 */
-	async search() {
-		const query = $(".search_input").val();
-		const list = $(".search_results");
-
-		list.html("");
-
-		if (!query) return;
-
-		list.html("<li>Loading, please wait...</li>");
-
-		try {
-			const searchResults = await Promise.all(
-				this.book.spine.spineItems.map(async (item) => {
-					try {
-						await item.load(this.book.load.bind(this.book));
-						const results = await item.find(`${query}`);
-						return results;
-					} finally {
-						await item.unload();
-					}
-				})
-			);
-
-			list.html("");
-
-			searchResults.flat().forEach((row) => {
-				console.log('sr', row);
-
-				const a = $("<a>")
-					.attr('href', '#')
-					.html(`<b class='pull-right'>${this.book.locations.locationFromCfi(row.cfi)}</b>${row.excerpt}`)
-					.attr('data-cfi', row.cfi)
-					.on('click', () => {
-						this.book.rendition.display($(a).attr('data-cfi'));
-					});
-
-				list.append($("<li>").append(a));
-			});
-		} catch (e) {
-			console.error('Search failed:', e);
-		}
-	}
-
-	nextPage() {
-			this.book.rendition.next();
-
-			if (typeof EpubeApp != "undefined")
-				EpubeApp.showActionBar(false);
-			else
-				localforage.getItem("epube.keep-ui-visible").then((keep) => {
-					if (!keep) this.showUI(false);
-				});
-	}
+            if (this.isOnline()) {
+                const data = await $.post("backend.php", { op: "storelastread", page: total, cfi: lastCfi, id: this.urlParam("id"), timestamp: lastread_timestamp });
+                $(".lastread_input").val(data.page + '%');
+            }
+
+            await localforage.setItem(this.cacheId("lastread"),
+                {cfi: lastCfi, page: total, total: total, timestamp: lastread_timestamp});
+
+            await this.openLastRead();
+        }
+    }
+
+    async close() {
+        const location = this.book.rendition.currentLocation();
+
+        const currentCfi = location.start.cfi;
+        const currentPage = Math.round(this.book.locations.percentageFromCfi(currentCfi) * 100);
+        const totalPages = 100;
+        const lastread_timestamp = new Date().getTime();
+
+        await localforage.setItem(this.cacheId("lastread"),
+            {cfi: currentCfi, page: currentPage, total: totalPages, timestamp: lastread_timestamp});
+
+        if (this.isOnline()) {
+            $.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: currentPage,
+                cfi: currentCfi, timestamp: lastread_timestamp }, () => {
+                window.location.href = this.urlParam("rt") ? "index.php?mode=" + this.urlParam("rt") : "index.php";
+            })
+                .fail(() => {
+                    window.location.href = "index.php";
+                });
+        } else {
+            window.location.href = "index.php";
+        }
+    }
+
+    cacheId(suffix) {
+        return "epube-book." + this.urlParam("b") + (suffix ? "." + suffix : "");
+    }
+
+    showUI(show) {
+        if (show)
+            $(".header,.footer").fadeIn();
+        else
+            $(".header,.footer").fadeOut();
+    }
+
+    toggleUI() {
+        if ($(".header").is(":visible"))
+            $(".header,.footer").fadeOut();
+        else
+            $(".header,.footer").fadeIn();
+    }
+
+    async lookupWord(word, callback, elem) {
+        if (elem)
+            word = $(elem).val();
+
+        word = word.replace(/­/g, "");
+
+        console.log('lookupWord', word);
+
+        $(".dict_result").html('Loading, please wait...');
+
+        $("#dict-modal").modal('show');
+
+        try {
+            const data = await $.post("backend.php", {op: 'define', word: word});
+
+            if (data) {
+
+                $(".dict_result").html(data.result.join("<br/>"));
+                $(".dict_query").val(word);
+
+                if (callback) callback();
+            }
+        } catch (e) {
+            // @type {NetworkError}
+            const err = /** @type {*} */(e);
+
+            console.error(err);
+
+            $(".dict_result").html(`Network error while looking up word: ${err.responseText}.`);
+        }
+    }
+
+    /**
+     * @returns {Promise<void>}
+     */
+    async search() {
+        const query = $(".search_input").val();
+        const list = $(".search_results");
+
+        list.html("");
+
+        if (!query) return;
+
+        list.html("<li>Loading, please wait...</li>");
+
+        try {
+            const searchResults = await Promise.all(
+                this.book.spine.spineItems.map(async (item) => {
+                    try {
+                        await item.load(this.book.load.bind(this.book));
+                        const results = await item.find(`${query}`);
+                        return results;
+                    } finally {
+                        await item.unload();
+                    }
+                })
+            );
+
+            list.html("");
+
+            searchResults.flat().forEach((row) => {
+                console.log('sr', row);
+
+                const a = $("<a>")
+                    .attr('href', '#')
+                    .html(`<b class='pull-right'>${this.book.locations.locationFromCfi(row.cfi)}</b>${row.excerpt}`)
+                    .attr('data-cfi', row.cfi)
+                    .on('click', () => {
+                        this.book.rendition.display($(a).attr('data-cfi'));
+                    });
+
+                list.append($("<li>").append(a));
+            });
+        } catch (e) {
+            console.error('Search failed:', e);
+        }
+    }
+
+    nextPage() {
+            this.book.rendition.next();
+
+            if (typeof EpubeApp != "undefined")
+                EpubeApp.showActionBar(false);
+            else
+                localforage.getItem("epube.keep-ui-visible").then((keep) => {
+                    if (!keep) this.showUI(false);
+                });
+    }
 
-	prevPage() {
-		this.book.rendition.prev();
+    prevPage() {
+        this.book.rendition.prev();
 
-		if (typeof EpubeApp != "undefined")
-			EpubeApp.showActionBar(false);
-		else
-			localforage.getItem("epube.keep-ui-visible").then((keep) => {
-				if (!keep) this.showUI(false);
-			});
-	}
+        if (typeof EpubeApp != "undefined")
+            EpubeApp.showActionBar(false);
+        else
+            localforage.getItem("epube.keep-ui-visible").then((keep) => {
+                if (!keep) this.showUI(false);
+            });
+    }
 
-	/**
-	 * @param {HTMLElement} elem
-	 */
-	async openPrevious(elem) {
-		const cfi = $(elem).attr("data-location-cfi");
+    /**
+     * @param {HTMLElement} elem
+     */
+    async openPrevious(elem) {
+        const cfi = $(elem).attr("data-location-cfi");
 
-		if (cfi)
-			await this.book.rendition.display(cfi);
+        if (cfi)
+            await this.book.rendition.display(cfi);
 
-		$(elem).fadeOut();
-	}
+        $(elem).fadeOut();
+    }
 
-	blockLastReadUpdate() {
-		console.log('blocking last read updates...');
+    blockLastReadUpdate() {
+        console.log('blocking last read updates...');
 
-		if (this._prevent_lastread_timeout)
-			window.clearTimeout(this._prevent_lastread_timeout);
+        if (this._prevent_lastread_timeout)
+            window.clearTimeout(this._prevent_lastread_timeout);
 
-		this._prevent_lastread_timeout = window.setTimeout(() => {
-			this._prevent_lastread = false;
-			this._prevent_lastread_timeout = false;
-			console.log('unblocked last read updates');
-		}, 1000);
+        this._prevent_lastread_timeout = window.setTimeout(() => {
+            this._prevent_lastread = false;
+            this._prevent_lastread_timeout = false;
+            console.log('unblocked last read updates');
+        }, 1000);
 
-		this._prevent_lastread = true;
-	}
+        this._prevent_lastread = true;
+    }
 
-	/**
-	 * @param { ePub.Book } book
-	 * @param { ePub.Location } location
-	 */
-	async onRelocated(book, location) {
-		// locations not generated yet
-		if (book.locations.length() == 0)
-			return;
+    /**
+     * @param { ePub.Book } book
+     * @param { ePub.Location } location
+     */
+    async onRelocated(book, location) {
+        // locations not generated yet
+        if (book.locations.length() == 0)
+            return;
 
-		const currentCfi = location.start.cfi;
-		const currentPct = Math.round(book.locations.percentageFromCfi(currentCfi) * 100);
+        const currentCfi = location.start.cfi;
+        const currentPct = Math.round(book.locations.percentageFromCfi(currentCfi) * 100);
 
-		$("#cur_page").text(Math.floor(location.start.location / LOCATION_DIVISOR));
-		$("#total_pages").text(Math.floor(book.locations.length() / LOCATION_DIVISOR));
-		$("#page_pct").text(Math.round(book.locations.percentageFromCfi(currentCfi)*100) + '%');
+        $("#cur_page").text(Math.floor(location.start.location / LOCATION_DIVISOR));
+        $("#total_pages").text(Math.floor(book.locations.length() / LOCATION_DIVISOR));
+        $("#page_pct").text(Math.round(book.locations.percentageFromCfi(currentCfi)*100) + '%');
 
-		this.updateTocBarPosition(book, location);
+        this.updateTocBarPosition(book, location);
 
-		const displayed = location.start.displayed;
-
-		if (displayed) {
-			$("#chapter_cur_page").text(displayed.page);
-			$("#chapter_total_pages").text(displayed.total);
+        const displayed = location.start.displayed;
+
+        if (displayed) {
+            $("#chapter_cur_page").text(displayed.page);
+            $("#chapter_total_pages").text(displayed.total);
 
-			if (displayed.total > 0)
-				$("#chapter_pct").text(Math.round(displayed.page / displayed.total * 100) + '%')
-		}
+            if (displayed.total > 0)
+                $("#chapter_pct").text(Math.round(displayed.page / displayed.total * 100) + '%')
+        }
 
-		if (this.startup_finished && this.last_stored_cfi != currentCfi && !this._prevent_lastread) {
-			const lastread_timestamp = new Date().getTime();
+        if (this.startup_finished && this.last_stored_cfi != currentCfi && !this._prevent_lastread) {
+            const lastread_timestamp = new Date().getTime();
 
-			console.log("storing lastread", currentPct, currentCfi, lastread_timestamp);
-
-			await localforage.setItem(this.cacheId("lastread"),
-				{cfi: currentCfi, page: currentPct, total: 100, timestamp: lastread_timestamp});
-
-			if (this.isOnline()) {
-				console.log("updating remote lastread", currentCfi);
-				this.last_stored_cfi = currentCfi;
-
-				$.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: currentPct,
-					cfi: currentCfi, timestamp: lastread_timestamp });
-			}
-		}
-	}
-
-	async clearLastRead() {
-		if (confirm("Reset reading progress for this book?")) {
-			$("#settings-modal").modal('hide');
-
-			const total = this.book.locations.length();
-			const lastread_timestamp = new Date().getTime();
+            console.log("storing lastread", currentPct, currentCfi, lastread_timestamp);
+
+            await localforage.setItem(this.cacheId("lastread"),
+                {cfi: currentCfi, page: currentPct, total: 100, timestamp: lastread_timestamp});
+
+            if (this.isOnline()) {
+                console.log("updating remote lastread", currentCfi);
+                this.last_stored_cfi = currentCfi;
+
+                $.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: currentPct,
+                    cfi: currentCfi, timestamp: lastread_timestamp });
+            }
+        }
+    }
+
+    async clearLastRead() {
+        if (confirm("Reset reading progress for this book?")) {
+            $("#settings-modal").modal('hide');
+
+            const total = this.book.locations.length();
+            const lastread_timestamp = new Date().getTime();
 
-			if (this.isOnline())
-				await $.post("backend.php", { op: "storelastread", page: PAGE_RESET_PROGRESS, cfi: "", id: this.urlParam("id"), timestamp: lastread_timestamp });
+            if (this.isOnline())
+                await $.post("backend.php", { op: "storelastread", page: PAGE_RESET_PROGRESS, cfi: "", id: this.urlParam("id"), timestamp: lastread_timestamp });
 
-			await localforage.setItem(this.cacheId("lastread"),
-				{cfi: "", page: 0, total: total, timestamp: lastread_timestamp});
+            await localforage.setItem(this.cacheId("lastread"),
+                {cfi: "", page: 0, total: total, timestamp: lastread_timestamp});
 
-			await this.book.rendition.display(this.book.locations.cfiFromPercentage(0));
+            await this.book.rendition.display(this.book.locations.cfiFromPercentage(0));
 
-			$(".lastread_input").val('0%');
-		}
-	}
+            $(".lastread_input").val('0%');
+        }
+    }
 
-	async resetLocations() {
-		if (confirm("Reset stored pagination data? This will also reset reading progress.")) {
-			$("#settings-modal").modal('hide');
+    async resetLocations() {
+        if (confirm("Reset stored pagination data? This will also reset reading progress.")) {
+            $("#settings-modal").modal('hide');
 
-			await localforage.removeItem(this.cacheId("lastread"));
-			await localforage.removeItem(this.cacheId("locations"));
+            await localforage.removeItem(this.cacheId("lastread"));
+            await localforage.removeItem(this.cacheId("locations"));
 
-			await $.post("backend.php", { op: "storelastread", page: PAGE_RESET_PROGRESS, cfi: "", id: this.urlParam("id"), timestamp: new Date().getTime() })
+            await $.post("backend.php", { op: "storelastread", page: PAGE_RESET_PROGRESS, cfi: "", id: this.urlParam("id"), timestamp: new Date().getTime() })
 
-			// this might return 404 and its okay
-			await $.post("backend.php",
-				{ op: "deletepagination", id: this.urlParam("id") }).catch((e) => console.log(e))
+            // this might return 404 and its okay
+            await $.post("backend.php",
+                { op: "deletepagination", id: this.urlParam("id") }).catch((e) => console.log(e))
 
-			window.location.reload();
-		}
-	}
+            window.location.reload();
+        }
+    }
 
-	async openLastRead() {
-		$(".loading").show();
-		$(".loading-message").html("Opening last read page…");
+    async openLastRead() {
+        $(".loading").show();
+        $(".loading-message").html("Opening last read page…");
 
-		$("#settings-modal").modal('hide');
+        $("#settings-modal").modal('hide');
 
-		const rendition = this.book.rendition;
+        const rendition = this.book.rendition;
 
-		if (!rendition) {
-			console.error('no rendition to work on');
-			return;
-		}
+        if (!rendition) {
+            console.error('no rendition to work on');
+            return;
+        }
 
-		let location_found = false;
+        let location_found = false;
 
-		const lr_local = await localforage.getItem(this.cacheId("lastread")) || {};
-		console.log('got local lastread', lr_local);
+        const lr_local = await localforage.getItem(this.cacheId("lastread")) || {};
+        console.log('got local lastread', lr_local);
 
-		if (this.isOnline()) {
-			try {
-				const lr_remote = await $.post("backend.php", { op: "getlastread", id: this.urlParam("id") });
+        if (this.isOnline()) {
+            try {
+                const lr_remote = await $.post("backend.php", { op: "getlastread", id: this.urlParam("id") });
 
-				console.log('got remote lastread', lr_remote);
+                console.log('got remote lastread', lr_remote);
 
-				if (lr_remote) {
-					if (lr_remote.cfi && lr_local.cfi != lr_remote.cfi && (lr_remote.page >= (lr_local.page || 0))) {
-						console.log(`using remote lastread cfi ${lr_remote.cfi}: cfi is different and remote pct ${lr_remote.page}% is further than local pct ${lr_local.page}%`);
+                if (lr_remote) {
+                    if (lr_remote.cfi && lr_local.cfi != lr_remote.cfi && (lr_remote.page >= (lr_local.page || 0))) {
+                        console.log(`using remote lastread cfi ${lr_remote.cfi}: cfi is different and remote pct ${lr_remote.page}% is further than local pct ${lr_local.page}%`);
 
-						await localforage.setItem(this.cacheId("lastread"),
-							{cfi: lr_remote.cfi, page: lr_remote.page, total: lr_remote.total, timestamp: lr_remote.timestamp});
+                        await localforage.setItem(this.cacheId("lastread"),
+                            {cfi: lr_remote.cfi, page: lr_remote.page, total: lr_remote.total, timestamp: lr_remote.timestamp});
 
-						location_found = await this.moveToCfiVerify(rendition, lr_remote.cfi);
-					}
-				}
-			} catch (e) {
-				console.log('unable to get remote lastread, continuing...');
-				console.warn(e);
-			}
-		}
+                        location_found = await this.moveToCfiVerify(rendition, lr_remote.cfi);
+                    }
+                }
+            } catch (e) {
+                console.log('unable to get remote lastread, continuing...');
+                console.warn(e);
+            }
+        }
 
-		// for some reason this might not actually open *exact* CFI but it should generally be close enough after a few attempts,
-		// that's why we no longer reset to page 1 after trying local CFI
-		if (!location_found) {
-			if (lr_local && lr_local.cfi) {
-				console.log(`using local lastread cfi: ${lr_local.cfi}`);
-				try {
-					await this.moveToCfiVerify(rendition, lr_local.cfi);
-				} catch (e) {
-					console.warn(e);
-				}
-			}
-		}
+        // for some reason this might not actually open *exact* CFI but it should generally be close enough after a few attempts,
+        // that's why we no longer reset to page 1 after trying local CFI
+        if (!location_found) {
+            if (lr_local && lr_local.cfi) {
+                console.log(`using local lastread cfi: ${lr_local.cfi}`);
+                try {
+                    await this.moveToCfiVerify(rendition, lr_local.cfi);
+                } catch (e) {
+                    console.warn(e);
+                }
+            }
+        }
 
-		$(".loading").fadeOut();
-	}
-
-	/**
-	 * @param {?string} a
-	 * @param {?string} b
-	 */
-	calculateCfiDelta(a, b) {
-		if (!a || !b)
-			return -1;
+        $(".loading").fadeOut();
+    }
+
+    /**
+     * @param {?string} a
+     * @param {?string} b
+     */
+    calculateCfiDelta(a, b) {
+        if (!a || !b)
+            return -1;
 
-		// @ts-ignore
-		const acfi = new ePub.CFI(a);
-		// @ts-ignore
-		const bcfi = new ePub.CFI(b);
-
-		console.log('calculateCfiDelta', acfi, bcfi);
-
-		if (acfi.path.steps.length != bcfi.path.steps.length)
-			return -1;
-
-		let delta = 0;
-
-		// this is about as ad-hoc as it gets...
-		for (let i = 0; i < acfi.path.steps.length; i++) {
-
-			// is this possible? who knows!
-			if (acfi.path.steps[i].type != bcfi.path.steps[i].type)
-				return -1;
-
-			// different "filepos" or w/e
-			if (acfi.path.steps[i].id != bcfi.path.steps[i].id)
-				return -1;
-
-			if (acfi.path.steps[i].id === null && acfi.path.steps[i].type === 'element')
-				delta += Math.abs(acfi.path.steps[i].index - bcfi.path.steps[i].index);
-		}
-
-		return delta;
-	}
-
-	/**
-	 * @param {ePub.Rendition} rendition
-	 * @param {string} cfi
-	 */
-	async moveToCfiVerify(rendition, cfi, attempts = 5, maxDelta = 5) {
-		for (let att = 1; att < attempts; att++) {
-			this.blockLastReadUpdate();
-
-			console.log(`trying to open ${cfi}: attempt ${att} of ${attempts}...`);
-
-			/* eslint-disable no-await-in-loop */
-			await rendition.display(cfi); // we need to be synchronous here
-
-			let moved_to;
-
-			try {
-				moved_to = rendition.currentLocation().start.cfi;
-			} catch (e) {
-				console.warn('location not yet available, will retry:', e);
-			}
-
-			try {
-				const delta = this.calculateCfiDelta(cfi, moved_to ?? null);
-
-				console.log(`opened cfi ${moved_to} expected ${cfi}; delta: ${delta}`);
-
-				if (moved_to == cfi || (delta != -1 && delta <= maxDelta)) {
-					console.log("cfi move verified!");
-					return true;
-				}
-			} catch (e) {
-				console.warn('exception while parsing cfi, will retry: ', e);
-			}
-		}
-
-		return false;
-	}
-
-	/**
-	 * @param {HTMLElement} elem
-	 */
-	async onThemeChanged(elem) {
-		const theme = $(elem).val();
-
-		await localforage.setItem("epube.theme", theme);
-		this.applyTheme();
-	}
-
-	/**
-	 * @param {HTMLElement} elem
-	 */
-	async onLineHeightChanged(elem) {
-		const height = $(elem).val();
-
-		await localforage.setItem("epube.lineHeight", height);
-		this.applyTheme();
-	}
-
-	/**
-	 * @param {HTMLElement} elem
-	 */
-	async onTextSizeChanged(elem) {
-		const size = $(elem).val();
-
-		await localforage.setItem("epube.fontSize", size);
-		this.applyTheme();
-	}
-
-	/**
-	 * @param {HTMLElement} elem
-	 */
-	async onFontChanged(elem) {
-		const font = $(elem).val();
-
-		await localforage.setItem("epube.fontFamily", font);
-		this.applyTheme();
-	}
+        // @ts-ignore
+        const acfi = new ePub.CFI(a);
+        // @ts-ignore
+        const bcfi = new ePub.CFI(b);
+
+        console.log('calculateCfiDelta', acfi, bcfi);
+
+        if (acfi.path.steps.length != bcfi.path.steps.length)
+            return -1;
+
+        let delta = 0;
+
+        // this is about as ad-hoc as it gets...
+        for (let i = 0; i < acfi.path.steps.length; i++) {
+
+            // is this possible? who knows!
+            if (acfi.path.steps[i].type != bcfi.path.steps[i].type)
+                return -1;
+
+            // different "filepos" or w/e
+            if (acfi.path.steps[i].id != bcfi.path.steps[i].id)
+                return -1;
+
+            if (acfi.path.steps[i].id === null && acfi.path.steps[i].type === 'element')
+                delta += Math.abs(acfi.path.steps[i].index - bcfi.path.steps[i].index);
+        }
+
+        return delta;
+    }
+
+    /**
+     * @param {ePub.Rendition} rendition
+     * @param {string} cfi
+     */
+    async moveToCfiVerify(rendition, cfi, attempts = 5, maxDelta = 5) {
+        for (let att = 1; att < attempts; att++) {
+            this.blockLastReadUpdate();
+
+            console.log(`trying to open ${cfi}: attempt ${att} of ${attempts}...`);
+
+            /* eslint-disable no-await-in-loop */
+            await rendition.display(cfi); // we need to be synchronous here
+
+            let moved_to;
+
+            try {
+                moved_to = rendition.currentLocation().start.cfi;
+            } catch (e) {
+                console.warn('location not yet available, will retry:', e);
+            }
+
+            try {
+                const delta = this.calculateCfiDelta(cfi, moved_to ?? null);
+
+                console.log(`opened cfi ${moved_to} expected ${cfi}; delta: ${delta}`);
+
+                if (moved_to == cfi || (delta != -1 && delta <= maxDelta)) {
+                    console.log("cfi move verified!");
+                    return true;
+                }
+            } catch (e) {
+                console.warn('exception while parsing cfi, will retry: ', e);
+            }
+        }
+
+        return false;
+    }
+
+    /**
+     * @param {HTMLElement} elem
+     */
+    async onThemeChanged(elem) {
+        const theme = $(elem).val();
+
+        await localforage.setItem("epube.theme", theme);
+        this.applyTheme();
+    }
+
+    /**
+     * @param {HTMLElement} elem
+     */
+    async onLineHeightChanged(elem) {
+        const height = $(elem).val();
+
+        await localforage.setItem("epube.lineHeight", height);
+        this.applyTheme();
+    }
+
+    /**
+     * @param {HTMLElement} elem
+     */
+    async onTextSizeChanged(elem) {
+        const size = $(elem).val();
+
+        await localforage.setItem("epube.fontSize", size);
+        this.applyTheme();
+    }
+
+    /**
+     * @param {HTMLElement} elem
+     */
+    async onFontChanged(elem) {
+        const font = $(elem).val();
+
+        await localforage.setItem("epube.fontFamily", font);
+        this.applyTheme();
+    }
 }
 
 class ReaderLoader {
-	_res_data = {};
+    _res_data = {};
 
-	/**
-	 * @param {ReaderClass} app
-	 */
-	async init(app) {
-		const cacheName = await app.getActiveCacheName();
+    /**
+     * @param {ReaderClass} app
+     */
+    async init(app) {
+        const cacheName = await app.getActiveCacheName();
 
-		console.log('loader init for cache:', cacheName);
+        console.log('loader init for cache:', cacheName);
 
-		if (typeof EpubeApp != "undefined") {
-			$("body").addClass("epube-app");
-		}
+        if (typeof EpubeApp != "undefined") {
+            $("body").addClass("epube-app");
+        }
 
-		// Reader runs inside an iframe where the service worker can't intercept requests.
-		// We read resources directly from the cache (no network) and inject them into the iframe.
+        // Reader runs inside an iframe where the service worker can't intercept requests.
+        // We read resources directly from the cache (no network) and inject them into the iframe.
 
-		const cache = await caches.open(cacheName);
-		const cacheKeys = await cache.keys();
+        const cache = await caches.open(cacheName);
+        const cacheKeys = await cache.keys();
 
-		const promises = [];
-		let loadFailed = false;
+        const promises = [];
+        let loadFailed = false;
 
-		for (const req of cacheKeys) {
-			// Skip API responses — we only need static assets for the iframe
-			if (req.url.match(/backend\.php/)) continue;
+        for (const req of cacheKeys) {
+            // Skip API responses — we only need static assets for the iframe
+            if (req.url.match(/backend\.php/)) continue;
 
-			const response = await cache.match(req.url);
-			if (!response) {
-				console.warn('[loader] cache miss for', req.url);
-				loadFailed = true;
-				continue;
-			}
+            const response = await cache.match(req.url);
+            if (!response) {
+                console.warn('[loader] cache miss for', req.url);
+                loadFailed = true;
+                continue;
+            }
 
-			const url = new URL(req.url);
-			url.searchParams.delete("ts");
-			const key = url.toString();
+            const url = new URL(req.url);
+            url.searchParams.delete("ts");
+            const key = url.toString();
 
-			let promise;
-			if (req.url.match(/\.(ttf|otf)$/)) {
-				promise = response.blob().then((blob) => {
-					this._res_data[key] = URL.createObjectURL(blob);
-				});
-			} else {
-				promise = response.text().then((text) => {
-					this._res_data[key] = text;
-				});
-			}
+            let promise;
+            if (req.url.match(/\.(ttf|otf)$/)) {
+                promise = response.blob().then((blob) => {
+                    this._res_data[key] = URL.createObjectURL(blob);
+                });
+            } else {
+                promise = response.text().then((text) => {
+                    this._res_data[key] = text;
+                });
+            }
 
-			promises.push(promise.catch((err) => {
-				console.warn('[loader] failed to read', req.url, err);
-				loadFailed = true;
-			}));
-		}
+            promises.push(promise.catch((err) => {
+                console.warn('[loader] failed to read', req.url, err);
+                loadFailed = true;
+            }));
+        }
 
-		await Promise.allSettled(promises);
+        await Promise.allSettled(promises);
 
-		if (Object.keys(this._res_data).length === 0) loadFailed = true;
+        if (Object.keys(this._res_data).length === 0) loadFailed = true;
 
-		console.log('[loader] loaded', Object.keys(this._res_data).length, 'resources, failed:', loadFailed);
+        console.log('[loader] loaded', Object.keys(this._res_data).length, 'resources, failed:', loadFailed);
 
-		return loadFailed;
-	}
+        return loadFailed;
+    }
 }
diff --git a/src/worker.js b/src/worker.js
index 917aaf5..af38aa4 100644
--- a/src/worker.js
+++ b/src/worker.js
@@ -11,153 +11,153 @@ const MANIFEST_ASSETS = BUILD_MANIFEST_ASSETS;
 
 // Install: precache all assets from manifest
 sw.addEventListener('install', (event) => {
-	event.waitUntil(
-		(async () => {
-			console.log('[worker] install started', CACHE_NAME);
-
-			// await loadConfig();
-
-			const cache = await caches.open(CACHE_NAME);
-
-			// 1. Map assets to Request objects that bypass old service worker caches
-			const requests = MANIFEST_ASSETS.map((url) => new Request(url, { cache: 'reload' }));
-
-			try {
-				// 2. Atomic install: fills cache entirely, or fails completely if one file is missing
-				await cache.addAll(requests);
-				console.log('[worker] all assets cached successfully');
-
-				// Only skip waiting if the entire cache was successfully built
-				sw.skipWaiting();
-			} catch (err) {
-				console.error('[worker] Critical precache failed! Critical asset missing:', err);
-				// Do NOT call skipWaiting(). Let this installation fail so the old worker stays safe.
-			}
-		})()
-	);
+    event.waitUntil(
+        (async () => {
+            console.log('[worker] install started', CACHE_NAME);
+
+            // await loadConfig();
+
+            const cache = await caches.open(CACHE_NAME);
+
+            // 1. Map assets to Request objects that bypass old service worker caches
+            const requests = MANIFEST_ASSETS.map((url) => new Request(url, { cache: 'reload' }));
+
+            try {
+                // 2. Atomic install: fills cache entirely, or fails completely if one file is missing
+                await cache.addAll(requests);
+                console.log('[worker] all assets cached successfully');
+
+                // Only skip waiting if the entire cache was successfully built
+                sw.skipWaiting();
+            } catch (err) {
+                console.error('[worker] Critical precache failed! Critical asset missing:', err);
+                // Do NOT call skipWaiting(). Let this installation fail so the old worker stays safe.
+            }
+        })()
+    );
 });
 
 sw.addEventListener('message', (event) => {
-	if (event.data && event.data.type === 'GET_CACHE_NAME') {
-		// Respond directly to the specific frontend window/tab that asked
-		event.ports[0].postMessage({ cacheName: CACHE_NAME });
-	} else if (event.data && event.data.type === 'GET_CACHE_VERSION') {
-		// Respond directly to the specific frontend window/tab that asked
-		event.ports[0].postMessage({ cacheName: CACHE_VERSION });
-	}
+    if (event.data && event.data.type === 'GET_CACHE_NAME') {
+        // Respond directly to the specific frontend window/tab that asked
+        event.ports[0].postMessage({ cacheName: CACHE_NAME });
+    } else if (event.data && event.data.type === 'GET_CACHE_VERSION') {
+        // Respond directly to the specific frontend window/tab that asked
+        event.ports[0].postMessage({ cacheName: CACHE_VERSION });
+    }
 
 });
 
 // Activate: clean up old caches and take control of all pages
 sw.addEventListener('activate', (event) => {
-	console.log('[worker] activate');
+    console.log('[worker] activate');
 
-	// Create the async task block
-	const activationTask = async () => {
-		// await loadConfig();
+    // Create the async task block
+    const activationTask = async () => {
+        // await loadConfig();
 
-		const keyList = await caches.keys();
-		for (const key of keyList) {
-			if (key.includes(CACHE_PREFIX) && key !== CACHE_NAME) {
-				/* eslint-disable no-await-in-loop */
-				await caches.delete(key);
-			}
-		}
+        const keyList = await caches.keys();
+        for (const key of keyList) {
+            if (key.includes(CACHE_PREFIX) && key !== CACHE_NAME) {
+                /* eslint-disable no-await-in-loop */
+                await caches.delete(key);
+            }
+        }
 
-		await sw.clients.claim();
-	};
+        await sw.clients.claim();
+    };
 
-	// Hand the executed promise directly to the event
-	event.waitUntil(activationTask());
+    // Hand the executed promise directly to the event
+    event.waitUntil(activationTask());
 });
 
 // Fetch: cache-first for static assets, network-first for API
 sw.addEventListener('fetch', (event) => {
-	const url = new URL(event.request.url);
-
-	// console.log('[fetch]', url);
-
-	// /assets/ belong to android app
-	if (url.pathname.startsWith('/assets/')) return;
-
-	// request specific API endpoints from the network if possible and cache them locally
-	if (url.pathname.match('backend.php\\?op=(cover|getinfo)')) {
-		event.respondWith(
-			// @ts-ignore-next-line
-			(async () => {
-				try {
-					const networkResp = await fetch(event.request);
-
-					if (networkResp.ok) {
-						const cache = await caches.open(CACHE_NAME);
-						await cache.put(networkResp.url, networkResp.clone());
-					}
-
-					return networkResp;
-				} catch (err) {
-					// Network failed, try to get the cached API response
-					const cachedResp = await caches.match(event.request);
-					if (cachedResp) return cachedResp;
-				}
-			})()
-		);
-		return;
-	}
-
-	// index & read UI: online first; if offline, map index pages to offline.html & map all read.html?* to offline read.html
-	if (url.pathname == "/" || url.pathname.match("index.php|offline.html|read.html")) {
-		event.respondWith(
-			// @ts-ignore-next-line
-			(async () => {
-				try {
-					const networkResp = await fetch(event.request);
-
-					if (networkResp.ok) {
-						const cache = await caches.open(CACHE_NAME);
-						await cache.put(networkResp.url, networkResp.clone());
-					}
-
-					return networkResp;
-				} catch (err) {
-					// i.e. read.html?id=1234&b=1234
-					if (url.pathname.includes("read.html")) {
-						return caches.match("read.html");
-					} else {
-						return caches.match('/offline.html');
-					}
-				}
-			})()
-		);
-
-		return;
-	}
-
-	// everything else: cache-first with network fallback
-	event.respondWith(
-		(async () => {
-			const cache = await caches.open(CACHE_NAME);
-			const cached = await cache.match(event.request);
-
-			if (cached) {
-				// if cached, try to update: fire background network check without waiting for it (no await)
-				fetch(event.request)
-					.then((networkResp) => {
-						if (networkResp.ok) cache.put(event.request, networkResp.clone());
-					})
-					.catch((e) => console.warn('[worker] Background update failed:', e));
-
-				// Return cached asset immediately
-				return cached;
-			}
-
-			// Cache miss: fetch from network and cache it
-			const networkResp = await fetch(event.request);
-
-			/* if (networkResp.ok) { -- we don't cache all responses
-				await cache.put(event.request, networkResp.clone());
-			} */
-
-			return networkResp;
-		})()
-	);
+    const url = new URL(event.request.url);
+
+    // console.log('[fetch]', url);
+
+    // /assets/ belong to android app
+    if (url.pathname.startsWith('/assets/')) return;
+
+    // request specific API endpoints from the network if possible and cache them locally
+    if (url.pathname.match('backend.php\\?op=(cover|getinfo)')) {
+        event.respondWith(
+            // @ts-ignore-next-line
+            (async () => {
+                try {
+                    const networkResp = await fetch(event.request);
+
+                    if (networkResp.ok) {
+                        const cache = await caches.open(CACHE_NAME);
+                        await cache.put(networkResp.url, networkResp.clone());
+                    }
+
+                    return networkResp;
+                } catch (err) {
+                    // Network failed, try to get the cached API response
+                    const cachedResp = await caches.match(event.request);
+                    if (cachedResp) return cachedResp;
+                }
+            })()
+        );
+        return;
+    }
+
+    // index & read UI: online first; if offline, map index pages to offline.html & map all read.html?* to offline read.html
+    if (url.pathname == "/" || url.pathname.match("index.php|offline.html|read.html")) {
+        event.respondWith(
+            // @ts-ignore-next-line
+            (async () => {
+                try {
+                    const networkResp = await fetch(event.request);
+
+                    if (networkResp.ok) {
+                        const cache = await caches.open(CACHE_NAME);
+                        await cache.put(networkResp.url, networkResp.clone());
+                    }
+
+                    return networkResp;
+                } catch (err) {
+                    // i.e. read.html?id=1234&b=1234
+                    if (url.pathname.includes("read.html")) {
+                        return caches.match("read.html");
+                    } else {
+                        return caches.match('/offline.html');
+                    }
+                }
+            })()
+        );
+
+        return;
+    }
+
+    // everything else: cache-first with network fallback
+    event.respondWith(
+        (async () => {
+            const cache = await caches.open(CACHE_NAME);
+            const cached = await cache.match(event.request);
+
+            if (cached) {
+                // if cached, try to update: fire background network check without waiting for it (no await)
+                fetch(event.request)
+                    .then((networkResp) => {
+                        if (networkResp.ok) cache.put(event.request, networkResp.clone());
+                    })
+                    .catch((e) => console.warn('[worker] Background update failed:', e));
+
+                // Return cached asset immediately
+                return cached;
+            }
+
+            // Cache miss: fetch from network and cache it
+            const networkResp = await fetch(event.request);
+
+            /* if (networkResp.ok) { -- we don't cache all responses
+                await cache.put(event.request, networkResp.clone());
+            } */
+
+            return networkResp;
+        })()
+    );
 });