about summary refs log tree commit diff stats
path: root/src/reader.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/reader.ts')
-rw-r--r--src/reader.ts1858
1 files changed, 1858 insertions, 0 deletions
diff --git a/src/reader.ts b/src/reader.ts
new file mode 100644
index 0000000..567c920
--- /dev/null
+++ b/src/reader.ts
@@ -0,0 +1,1858 @@
+// @ts-check
+
+'use strict';
+
+/** Pattern definition as produced by the hyphen library's build process. */
+
+
+declare interface HTMLElement { checked: boolean }
+declare interface Event { deltaY: number, deltaX: number }
+declare interface Node { data: string }
+
+interface NetworkError extends Error {
+  responseText?: string; // optional
+}
+
+declare type SwipeState = {
+   active: boolean,
+   startX: number,
+    startY: number,
+    startTime: number,
+    direction: 'left'|'right';
+}
+
+declare type SwipeConfig = {
+   minDistance: number,
+   velocityThreshold: number,
+   verticalDistanceThreshold: number
+}
+
+const DEFAULT_FONT_SIZE = 16;
+const DEFAULT_FONT_FAMILY = "Arial";
+const DEFAULT_LINE_HEIGHT = 140;
+const MIN_LENGTH_TO_JUSTIFY = 32; /* characters */
+
+const LOCATION_DIVISOR = 10;
+const PAGE_RESET_PROGRESS = -1;
+
+/* eslint-disable-next-line no-unused-vars */
+class ReaderClass extends AppCommon {
+    _flattened_toc: any;
+    loader: any;
+    csrf_token = "";
+
+    last_stored_cfi = "";
+
+    startup_finished = false;
+
+    open_last_read_when_displayed = true;
+
+    hyphenate = {} as HyphenateMap;
+
+    _prevent_lastread_timeout: any;
+
+    _prevent_lastread: any;
+
+    cacheVersion = BUILD_CACHE_VERSION;
+
+    cosmeticVersion = BUILD_VERSION;
+
+    book: ePub.Book;
+
+    /** @type {SwipeState} */
+    _swipeState = {
+        active: false,
+        startX: 0,
+        startY: 0,
+        startTime: 0,
+        direction: '',
+    };
+
+    _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();
+
+        this.book = new ePub.Book();
+        this.loader = new ReaderLoader();
+    }
+
+    onTouchStart(evt: any) {
+        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',
+        };
+    }
+
+    onTouchEnd(evt: any) {
+        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 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 directionMatches = isLeft ? deltaX < 0 : deltaX > 0;
+
+        if (isSwipe && directionMatches) {
+            evt.preventDefault();
+            evt.stopPropagation();
+
+            if (isLeft) {
+                this.nextPage();
+            } else {
+                this.prevPage();
+            }
+        }
+    }
+
+    onTouchMove(evt: any) {
+        if (!this._swipeState.active) return;
+
+        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;
+        }
+    }
+
+    async init() {
+        console.log('cache version, current:', this.cacheVersion, 'worker:', await this.getActiveCacheVersion());
+
+        this.csrf_token = Cookie.get('epube_csrf_token');
+
+        Http.setCsrfToken(this.csrf_token);
+
+        $(document).on("keyup", (e: any) => {
+            this.hotkeyHandler(e);
+        });
+
+        $(".close_book").on("click", () => {
+            this.close();
+        });
+
+        $("#left").on("mouseup", () => {
+            this.prevPage();
+        });
+
+        $(".search_input").on("change", () => {
+            this.search();
+        });
+
+        $(".prev_location_btn").on("click", (evt: any) => {
+            this.openPrevious(evt.target);
+        });
+
+        $("#right").on("mouseup", () => {
+            this.nextPage();
+        });
+
+        $("#left, #right").on("touchstart", (evt: any) => {
+            this.onTouchStart(evt);
+        });
+
+        $("#left, #right").on("touchmove", (evt: any) => {
+            this.onTouchMove(evt);
+        });
+
+        $("#left, #right").on("touchend", (evt: any) => {
+            this.onTouchEnd(evt);
+        });
+
+        const load_failed = await this.loader.init(this);
+
+        console.log('[init] load failed', load_failed);
+
+        if (!load_failed) {
+            this.initSecondStage();
+        } else {
+            this.applyTheme();
+
+            $(".loading-message").text('Resource loader failed to initialize.');
+        }
+    }
+
+    // another method, maybe use this: window.matchMedia("(pointer: coarse)").matches
+    // https://stackoverflow.com/questions/4817029/whats-an-optimal-or-efficient-way-to-detect-a-touch-screen-device-using-javas
+    isTouchDevice() {
+        return ('ontouchstart' in window) || (navigator.maxTouchPoints > 0);
+    }
+
+    /**
+     * @param offline Whether the app is in offline mode.
+     */
+    async onOfflineModeChanged(offline: boolean) {
+        console.log('onOfflineModeChanged', offline);
+
+        if (!offline && this.book) {
+            console.log("we're online, storing lastread");
+
+            const currentCfi = this.book.rendition.currentLocation().start.cfi;
+            const currentPage = Math.round(this.book.locations.percentageFromCfi(currentCfi) * 100); // TODO wtf
+
+            try {
+                await Http.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: String(currentPage),
+                    cfi: currentCfi, timestamp: String(new Date().getTime()) });
+            } catch (e) {
+                const err = /** @type {HttpError} */(e);
+                if ((err as any).status == 401) {
+                    window.location.href = "index.html";
+                }
+            }
+        }
+    }
+
+    async initSecondStage() {
+
+        if (typeof EpubeApp != "undefined") {
+            EpubeApp.setPage("PAGE_READER");
+        } else {
+            $(window).on('online', () => {
+                this.onOfflineModeChanged(false);
+            });
+
+            $(window).on('offline', () => {
+                this.onOfflineModeChanged(true);
+            });
+        }
+
+        this.applyTheme();
+
+        const bookinfo = await localforage.getItem(this.cacheId());
+
+        if (!bookinfo) {
+            const bookId = this.urlParam("b");
+
+            console.log('requesting bookinfo for book', bookId)
+
+            try {
+                /** @type{HttpResponse} */
+                const resp = await Http.post("backend.php", {op: "list", ids: bookId });
+
+                /** @type{BookInfo} */
+                const info = resp.data['books'][0];
+
+                if (info.has_cover) {
+                    /** @type {HttpBlobResponse} */
+                    const cover = await Http.blob("backend.php", {op: "cover", id: bookId});
+
+                    await localforage.setItem(this.cacheId('cover'), cover.blob);
+                }
+
+                await localforage.setItem(this.cacheId(), info);
+
+                console.log('bookinfo saved');
+
+            } catch (e) {
+                // @type {NetworkError}
+                const err = /** @type {HttpError} */(e);
+
+                console.error(err);
+
+                $(".loading-message").html(`Unable to load book info.<br/><small>${this.escapeHtml((String)((err as any).responseText))}</small>`);
+                return;
+            }
+        }
+
+        console.log('trying to load book...');
+
+        let book_data = await localforage.getItem(this.cacheId("book")) as Blob;
+
+        if (!book_data) {
+            console.log("local data not found, loading from network...");
+
+            $(".loading-message").html("Downloading book…");
+
+            /** @type {HttpBlobResponse} */
+            const book_resp = await Http.blob("backend.php", {op: "download", id: this.urlParam("id")});
+
+            if (book_resp.blob) {
+                book_data = book_resp.blob;
+
+                await localforage.setItem(this.cacheId('book'), book_data);
+                console.log('saved local data for book');
+
+            } else {
+                $(".loading-message").html(`Unable to download book: ${book_resp.status}`);
+                return;
+            }
+        }
+
+        const fileReader = new FileReader();
+        const _reader = this;
+
+        fileReader.onload = function() {
+            try {
+                _reader.openBookData(this.result);
+            } catch (e) {
+                console.error(e);
+                $(".loading-message").html("Unable to load book blob: " + e);
+            }
+        };
+
+        fileReader.onerror = (e) => {
+            console.log('filereader error', e);
+            $(".loading-message").html("Unable to open book.<br/><small>" + this.escapeHtml(String(e)) + "</small>");
+        };
+
+        fileReader.readAsArrayBuffer(book_data);
+    }
+
+    async openBookData(book_data: any) {
+        //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>${this.escapeHtml(e instanceof Error ? e.message : String(e))}</small>`);
+            return;
+        }
+
+        await this.book.ready;
+
+        console.log('book is ready');
+
+        await this.showBookInfo(this.book);
+        await this.loadLocations(this.book);
+
+        const rendition = this.book.renderTo("reader", {
+            width: '100%',
+            height: '100%',
+            allowScriptedContent: false,
+            minSpreadWidth: 961
+        });
+
+        $(".location").on('click', async () => {
+            const current = Math.floor(rendition.currentLocation().start.location / LOCATION_DIVISOR);
+            const total = Math.floor(this.book.locations.length() / LOCATION_DIVISOR);
+
+            const page = prompt("Jump to location [1-" + total + "]", String(current));
+
+            if (page)
+                await rendition.display(this.book.locations._locations[parseInt(page) * LOCATION_DIVISOR]);
+        });
+
+        const enable_hyphens = await localforage.getItem("epube.enable-hyphens");
+
+        if (enable_hyphens) {
+            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 book The ePub book whose info should be displayed.
+     */
+    async showBookInfo(book: ePub.Book) {
+        const bookinfo = await localforage.getItem(this.cacheId()) as BookInfo;
+
+        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 book The ePub book whose locations should be loaded.
+     */
+    async loadLocations(book: ePub.Book) {
+        let locations = await localforage.getItem(this.cacheId("locations")) as string[];
+
+        // 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…");
+
+            try {
+                /** @type {HttpTextResponse} */
+                const resp = await Http.text("backend.php", {op: "getpagination", id: this.urlParam("id")});
+                console.log("got locations from server");
+
+                // if this doesn't load, we'll generate locations and save them
+                try {
+                    locations = JSON.parse(resp.text);
+                } catch (e) {
+                    console.warn(e);
+                }
+
+                if (locations && typeof locations[0] == "string") {
+                    console.log('saving locations locally...');
+
+                    await localforage.setItem(this.cacheId("locations"), locations);
+
+                    try {
+                        book.locations.load(locations);
+
+                        return;
+                    } catch (e) {
+                        console.warn(e);
+                    }
+                }
+            } catch (e) {
+                console.warn('failed to fetch locations', e);
+            }
+        }
+
+        $(".loading-message").html("Preparing locations…");
+
+        let generate_queue_max = 0;
+
+        locations = await book.locations.generate(100, (queue: any) => {
+            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}%)…`);
+            }
+        });
+
+        try {
+            await Http.post("backend.php", { op: "storepagination", id: this.urlParam("id"),
+                payload: JSON.stringify(locations), total: "100"});
+        } catch (e) {
+            console.warn('failed to store pagination', e);
+        }
+
+        await localforage.setItem(this.cacheId("locations"), locations);
+    }
+
+    /**
+     * @param book The ePub book instance.
+     * @param rendition The epub.js rendition to hook into.
+     */
+    initRenditionHooks(book: ePub.Book, rendition: ePub.Rendition) {
+        console.log('initRenditionHooks');
+
+        book.spine.hooks.content.register((doc: any/*, section */) => {
+            this.cleanupEmbeddedStyles(doc);
+        });
+
+        rendition.hooks.content.register(async (contents: any) => {
+
+            contents.on("linkClicked", (href: any) => {
+                console.log('linkClicked', href);
+
+                this.blockLastReadUpdate();
+
+                if (href.indexOf("://") == -1) {
+                    $(".prev_location_btn")
+                        .attr("data-location-cfi", rendition.currentLocation().start.cfi)
+                        .show();
+
+                    window.requestAnimationFrame(() => {
+                        this.showUI(true);
+                    });
+                }
+            });
+
+            contents.on("selected", async (cfiRange: any) => {
+                if (this.isOnline()) {
+                    const range = await book.getRange(cfiRange);
+
+                    const selection = range.endContainer.data.substring(range.startOffset, range.endOffset);
+
+                    console.log('selected', cfiRange, selection);
+
+                    if (selection.match(/^[\w­]+$/)) {
+                        this.lookupWord(selection, () => {
+                            if (typeof EpubeApp != "undefined")
+                                EpubeApp.showActionBar(false);
+
+                                contents.window.requestAnimationFrame(() => {
+                                    contents.window.getSelection().removeAllRanges();
+                                });
+                        });
+                    }
+                }
+            });
+
+            // get our stuff from resource loader and inject into iframe content
+
+            const 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.loader._res_data[base_url + 'dist/reader_iframe.min.css']));
+
+            const theme = (await localforage.getItem("epube.theme")) || 'default';
+
+            $(contents.document).find("body")
+                .attr("class", typeof EpubeApp != "undefined" ? "is-epube-app" : "")
+                .addClass("theme-" + theme);
+
+            console.log('contents', contents);
+
+            $(contents.window).on("click tap", (evt: any) => {
+                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: any) => {
+                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: any) => {
+            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: any, r: any) {
+                if (book.spine.get(r.href).canonical == cur_href) {
+                    toc_entry = r;
+                    return;
+                }
+            });
+            if (toc_entry && (toc_entry as any).label)
+                $(".chapter_title").text(this.escapeHtml((toc_entry as any).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: any) => this.onRelocated(book, location));
+    }
+
+    initModals() {
+        $('#settings-modal').on('shown.bs.modal', async () => {
+
+            const last_read = await localforage.getItem(this.cacheId("lastread")) as 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) {
+                try {
+                    /** @type {HttpResponse} */
+                    const lrResp = await Http.get("backend.php", { op: "getlastread", id: this.urlParam("id") });
+                    $(".lastread_input")
+                        .val(lrResp.data.page + '%')
+                        .attr('title', `[remote] ${lrResp.data.cfi}`);
+                } catch (e) {
+                    console.warn('failed to get remote lastread', e);
+                }
+            }
+
+            $(".font_family")
+                .off("change")
+                .on("change", (evt: any) => {
+                    this.onFontChanged(evt.target);
+                });
+
+            $(".font_size")
+                .off("change")
+                .on("change", (evt: any) => {
+                    this.onTextSizeChanged(evt.target);
+                });
+
+            $(".line_height")
+                .off("change")
+                .on("change", (evt: any) => {
+                    this.onLineHeightChanged(evt.target);
+                });
+
+            $(".theme_name")
+                .off("change")
+                .on("change", (evt: any) => {
+                    this.onThemeChanged(evt.target);
+                });
+
+            $(".enable_hyphens_checkbox")
+                .attr("checked", await localforage.getItem("epube.enable-hyphens"))
+                .off("click")
+                .on("click", (evt: any) => {
+                    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: any) => {
+                    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: any) => {
+                    localforage.setItem("epube.keep-ui-visible", evt.target.checked);
+                });
+            }
+
+            $(".last-mod-timestamp").html(`${this.cosmeticVersion} &mdash; ${this.cacheVersion}
+                (${this.isOnline() ? `<span class='text-success'>Online</span>` : `<span class='text-danger'>Offline</span>`})
+                `);
+
+            $(".font_family").val((await localforage.getItem("epube.fontFamily")) || DEFAULT_FONT_FAMILY);
+            $(".theme_name").val((await localforage.getItem("epube.theme")) || 'default');
+
+            const zoom = $(".font_size").html("");
+
+            for (let i = 10; i <= 32; i++) {
+                const opt = $("<option>").val(i).html(i + " px");
+                zoom.append(opt);
+            }
+
+            zoom.val((await localforage.getItem("epube.fontSize")) || DEFAULT_FONT_SIZE);
+
+            const line_height = $(".line_height").html("");
+
+            for (let i = 100; i <= 220; i += 10) {
+                const opt = $("<option>").val(i).html(i + "%");
+                line_height.append(opt);
+            }
+
+            line_height.val((await localforage.getItem("epube.lineHeight")) || DEFAULT_LINE_HEIGHT);
+
+        });
+
+        $('#dict-modal').on('shown.bs.modal', () => {
+            $(".dict_query")
+                .off("keyup")
+                .on("keyup", (evt: any) => {
+                    if (evt.which === 13) {
+                        evt.preventDefault();
+                        this.lookupWord('', null, '.dict_query');
+                    }
+                });
+
+            $(".dict_result").scrollTop(0);
+        });
+
+        // TODO: make configurable
+        $(".dict_search_btn").on("click", function() {
+            $("#dict-modal").modal('hide');
+            window.open("https://duckduckgo.com/?q=" + $(".dict_query").val());
+        });
+
+    }
+
+    /**
+     * @param book The ePub book whose TOC should be initialized.
+     */
+    initToc(book: ePub.Book) {
+        const _reader = this;
+
+        function toc_loc_msg(href: any) {
+            try {
+                const cfiBase = book.spine.get(href).cfiBase;
+
+                const loc = book.locations._locations.find(function(k: any) {
+                    return k.indexOf(cfiBase) != -1
+                });
+
+                if (loc)
+                    return Math.round(_reader.book.locations.locationFromCfi(loc) / LOCATION_DIVISOR);
+
+            } catch (e) {
+                console.warn(e);
+            }
+
+            return "";
+        }
+
+        /**
+         * @param row The TOC navigation item to process.
+         * @param list The jQuery element containing the TOC sublist.
+         * @param nest Current nesting depth (max 3).
+         */
+        function process_toc_sublist(row: ePub.NavItem, list: JQuery<HTMLElement>, nest: number) {
+
+            if (nest == 3) return false;
+
+            if (row.subitems) {
+
+                const sublist = $("<ul class='toc_sublist list-unstyled'>");
+
+                $.each(row.subitems, function(i: any, row: any) {
+
+                    const a = $("<a>")
+                        .attr('href', '#')
+                        .html("<b class='pull-right'>" + toc_loc_msg(row.href) + "</b>" + _reader.escapeHtml(row.label))
+                        .attr('data-href', row.href)
+                        .click(function() {
+                            book.rendition.display(a.attr('data-href'));
+                        });
+
+                    sublist.append($("<li>").append(a));
+
+                    process_toc_sublist(row, sublist, nest + 1);
+
+                });
+
+                list.append(sublist);
+            }
+        }
+
+        $('#toc-modal').on('shown.bs.modal', function() {
+
+            const toc = book.navigation.toc;
+
+            const list = $(".toc_list");
+            list.html("");
+
+            $.each(toc, function(i: any, row: any) {
+
+                // 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>" + _reader.escapeHtml(row.label))
+                        .attr('data-href', row.href)
+                        .click(function() {
+                            book.rendition.display(a.attr('data-href'));
+                        });
+
+                    list.append($("<li>").append(a));
+
+                    process_toc_sublist(row, list, 0);
+
+                } catch (e) {
+                    console.warn(e);
+                }
+            });
+
+            // well the toc didn't work out, might as well generate one
+            if (list.children().length <= 1) {
+
+                list.html("");
+
+                $.each(book.spine.items, function (i: any, row: any) {
+
+                    const a = $("<a>")
+                        .attr('href', '#')
+                        .attr('title', row.url)
+                        .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 */
+    /**
+     * @param doc The Document to clean up embedded styles from.
+     */
+    cleanupEmbeddedStyles(doc: Document) {
+        $(doc).find("p")
+                .filter((i, e: any) => (($(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 (this.hyphenate?.en) {
+            $(doc).find('p, div').each((i, elem) => {
+                const p = $(elem);
+
+                p.html(this.hyphenate.en(p.html()) as string);
+                p.html(this.hyphenate.ru(p.html()) as string);
+            });
+        }
+    }
+
+    /**
+     * @param base_url The base URL for resolving font paths.
+     */
+    generateFontsCss(base_url: string) {
+        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;
+            }
+            `;
+    }
+
+    /**
+     * @param entry The TOC entry whose sub-items should be flattened.
+     * @param nest Current nesting depth (max 3).
+     */
+    flattenTocSubItems(entry: ePub.NavItem, nest: number) {
+        let rv: any = [];
+
+        if (nest == 3) return false;
+
+        if (entry.subitems) {
+            $.each(entry.subitems, (i: any, r: any) => {
+                r._nest = nest;
+
+                rv.push(r);
+                rv = rv.concat(this.flattenTocSubItems(r, nest+1));
+            });
+        }
+
+        return rv;
+    }
+
+    /**
+     * Flattens the book's TOC into a single array of navigation items.
+     * @param book The ePub book whose TOC should be flattened.
+     * @returns An array of all TOC entries including nested sub-items.
+     */
+    flattenToc(book: ePub.Book): ePub.NavItem[] {
+        if (this._flattened_toc) {
+            return this._flattened_toc;
+        } else {
+            let rv: any = [];
+
+            $.each(book.navigation.toc, (i: any, r: any) => {
+                r._nest = 0;
+
+                rv.push(r);
+                rv = rv.concat(this.flattenTocSubItems(r, 1));
+            });
+
+            this._flattened_toc = rv;
+
+            return rv;
+        }
+    }
+
+    /**
+     * @param book The ePub book whose TOC bar should be generated.
+     * @param toc Array of TOC entries to render in the bar.
+     */
+    generateTocBar(book: ePub.Book, toc: any[]) {
+        $(".spacer")
+            .html("");
+
+        $.each(toc, function(i: any, te: any) {
+            try {
+                const cfiBase = book.spine.get(te.href).cfiBase;
+                const loc = book.locations._locations.find(function(k: any) {
+                    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())
+    }
+
+    /**
+     * @param book The ePub book instance.
+     * @param location The current reading location to position the TOC bar at.
+     */
+    updateTocBarPosition(book: ePub.Book, location: ePub.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: any) => {
+                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);
+            });
+    }
+
+    /**
+     * @param e The keyboard up event to handle.
+     */
+    hotkeyHandler(e: JQuery.KeyUpEvent<Document, undefined, Document, Document>) {
+        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: any) => {
+                const body = rendition.document.querySelector('body');
+
+                if (body)
+                    width += parseInt(rendition.window.getComputedStyle(body).getPropertyValue('padding-left'));
+            });
+
+        console.log(`resizing side columns to ${width} px`);
+
+        $("#left, #right").width(width);
+    }
+
+    async markAsRead() {
+        if (confirm("Mark book as read?")) {
+            $("#settings-modal").modal('hide');
+
+            const total = 100;
+            const lastCfi = this.book.locations.cfiFromPercentage(1);
+            const lastread_timestamp = new Date().getTime();
+
+            if (this.isOnline()) {
+                /** @type {HttpResponse} */
+                const data = await Http.post("backend.php", { op: "storelastread", page: String(total), cfi: lastCfi, id: this.urlParam("id"), timestamp: String(lastread_timestamp) });
+                $(".lastread_input").val(data.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()) {
+            try {
+                await Http.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: String(currentPage),
+                    cfi: currentCfi, timestamp: String(lastread_timestamp) });
+            } catch (e) {
+                console.warn('storelastread failed', e);
+            }
+            window.location.href = this.urlParam("rt") ? "index.html?mode=" + this.urlParam("rt") : "index.html";
+        } else {
+            window.location.href = "index.html";
+        }
+    }
+
+    /**
+     * Get the cache key for this book, optionally with a suffix.
+     * @param suffix Optional suffix to append to the cache key.
+     */
+    cacheId(suffix?: string): string {
+        return "epube-book." + this.urlParam("b") + (suffix ? "." + suffix : "");
+    }
+
+    /**
+     * @param show Whether to show (true) or hide (false) the UI.
+     */
+    showUI(show: boolean) {
+        if (show)
+            $(".header,.footer").fadeIn();
+        else
+            $(".header,.footer").fadeOut();
+    }
+
+    toggleUI() {
+        if ($(".header").is(":visible"))
+            $(".header,.footer").fadeOut();
+        else
+            $(".header,.footer").fadeIn();
+    }
+
+    /** @param [elem=null] jquery selector for the input element to use */
+    async lookupWord(word: string, callback: any, elem: string|null = null) {
+        if (elem)
+            word = $(elem).val() as string;
+
+        word = word.replace(/­/g, "");
+
+        console.log('lookupWord', word);
+
+        $(".dict_result").html('Loading, please wait...');
+
+        $("#dict-modal").modal('show');
+
+        try {
+            /** @type {HttpResponse} */
+            const data = await Http.post("backend.php", {op: 'define', word: word});
+
+            if (data.data) {
+
+                $(".dict_result").html(data.data.result.map((r: any) => this.escapeHtml(String(r))).join("<br/>"));
+                $(".dict_query").val(word);
+
+                if (callback) callback();
+            }
+        } catch (e) {
+            const err = e as NetworkError;
+
+            console.error(err);
+
+            $(".dict_result").html(`Network error while looking up word: ${this.escapeHtml((String)((err as any).responseText))}.`);
+        }
+    }
+
+    async search(): Promise<void> {
+        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: any) => {
+                    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: any) => {
+                console.log('sr', row);
+
+                const a = $("<a>")
+                    .attr('href', '#')
+                    .html(`<b class='pull-right'>${this.book.locations.locationFromCfi(row.cfi)}</b>${this.escapeHtml(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: any) => {
+                    if (!keep) this.showUI(false);
+                });
+    }
+
+    prevPage() {
+        this.book.rendition.prev();
+
+        if (typeof EpubeApp != "undefined")
+            EpubeApp.showActionBar(false);
+        else
+            localforage.getItem("epube.keep-ui-visible").then((keep: any) => {
+                if (!keep) this.showUI(false);
+            });
+    }
+
+    /**
+     * Navigate to the previously stored CFI location.
+     * @param elem The HTMLElement containing the data-location-cfi attribute.
+     */
+    async openPrevious(elem: HTMLElement) {
+        const cfi = $(elem).attr("data-location-cfi");
+
+        if (cfi)
+            await this.book.rendition.display(cfi);
+
+        $(elem).fadeOut();
+    }
+
+    blockLastReadUpdate() {
+        console.log('blocking last read updates...');
+
+        if (this._prevent_lastread_timeout)
+            window.clearTimeout(this._prevent_lastread_timeout);
+
+        this._prevent_lastread_timeout = window.setTimeout(() => {
+            this._prevent_lastread = false;
+            this._prevent_lastread_timeout = false;
+            console.log('unblocked last read updates');
+        }, 1000);
+
+        this._prevent_lastread = true;
+    }
+
+    /**
+     * Called when the reader's location is relocated (page turn, etc.).
+     * @param book The ePub book instance.
+     * @param location The new reading location.
+     */
+    async onRelocated(book: ePub.Book, location: ePub.Location) {
+        // locations not generated yet
+        if (book.locations.length() == 0)
+            return;
+
+        const currentCfi = location.start.cfi;
+        const currentPct = Math.round(book.locations.percentageFromCfi(currentCfi) * 100);
+
+        $("#cur_page").text(Math.floor(location.start.location / LOCATION_DIVISOR));
+        $("#total_pages").text(Math.floor(book.locations.length() / LOCATION_DIVISOR));
+        $("#page_pct").text(Math.round(book.locations.percentageFromCfi(currentCfi)*100) + '%');
+
+        this.updateTocBarPosition(book, location);
+
+        const displayed = location.start.displayed;
+
+        if (displayed) {
+            $("#chapter_cur_page").text(displayed.page);
+            $("#chapter_total_pages").text(displayed.total);
+
+            if (displayed.total > 0)
+                $("#chapter_pct").text(Math.round(displayed.page / displayed.total * 100) + '%')
+        }
+
+        if (this.startup_finished && this.last_stored_cfi != currentCfi && !this._prevent_lastread) {
+            const lastread_timestamp = new Date().getTime();
+
+            console.log("storing lastread", currentPct, currentCfi, lastread_timestamp);
+
+            await localforage.setItem(this.cacheId("lastread"),
+                {cfi: currentCfi, page: currentPct, total: 100, timestamp: lastread_timestamp});
+
+            if (this.isOnline()) {
+                console.log("updating remote lastread", currentCfi);
+                this.last_stored_cfi = currentCfi;
+
+                Http.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: String(currentPct),
+                    cfi: currentCfi, timestamp: String(lastread_timestamp) }).catch((e) => {
+                    console.warn('storelastread failed', e);
+                });
+            }
+        }
+    }
+
+    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 Http.post("backend.php", { op: "storelastread", page: String(PAGE_RESET_PROGRESS), cfi: "", id: this.urlParam("id"), timestamp: String(lastread_timestamp) });
+
+            await localforage.setItem(this.cacheId("lastread"),
+                {cfi: "", page: 0, total: total, timestamp: lastread_timestamp});
+
+            await this.book.rendition.display(this.book.locations.cfiFromPercentage(0));
+
+            $(".lastread_input").val('0%');
+        }
+    }
+
+    async resetLocations() {
+        if (confirm("Reset stored pagination data? This will also reset reading progress.")) {
+            $("#settings-modal").modal('hide');
+
+            await localforage.removeItem(this.cacheId("lastread"));
+            await localforage.removeItem(this.cacheId("locations"));
+
+            await Http.post("backend.php", { op: "storelastread", page: String(PAGE_RESET_PROGRESS), cfi: "", id: this.urlParam("id"), timestamp: String(new Date().getTime()) })
+
+            // this might return 404 and its okay
+            await Http.post("backend.php",
+                { op: "deletepagination", id: this.urlParam("id") }).catch((e) => console.log(e))
+
+            window.location.reload();
+        }
+    }
+
+    async openLastRead() {
+        $(".loading").show();
+        $(".loading-message").html("Opening last read page…");
+
+        $("#settings-modal").modal('hide');
+
+        const rendition = this.book.rendition;
+
+        if (!rendition) {
+            console.error('no rendition to work on');
+            return;
+        }
+
+        let location_found = false;
+
+        const lr_local = ((await localforage.getItem(this.cacheId("lastread"))) || {}) as LastRead;
+        console.log('got local lastread', lr_local);
+
+        if (this.isOnline()) {
+            try {
+                /** @type {HttpResponse} */
+                const lr_remote = await Http.get("backend.php", { op: "getlastread", id: this.urlParam("id") });
+
+                console.log('got remote lastread', lr_remote.data);
+
+                if (lr_remote.data) {
+                    if (lr_remote.data.cfi && lr_local.cfi != lr_remote.data.cfi && (lr_remote.data.page >= (lr_local.page || 0))) {
+                        console.log(`using remote lastread cfi ${lr_remote.data.cfi}: cfi is different and remote pct ${lr_remote.data.page}% is further than local pct ${lr_local.page}%`);
+
+                        await localforage.setItem(this.cacheId("lastread"),
+                            {cfi: lr_remote.data.cfi, page: lr_remote.data.page, total: lr_remote.data.total, timestamp: lr_remote.data.timestamp});
+
+                        location_found = await this.moveToCfiVerify(rendition, lr_remote.data.cfi);
+                    }
+                }
+            } catch (e) {
+                console.log('unable to get remote lastread, continuing...');
+                console.warn(e);
+            }
+        }
+
+        // for some reason this might not actually open *exact* CFI but it should generally be close enough after a few attempts,
+        // that's why we no longer reset to page 1 after trying local CFI
+        if (!location_found) {
+            if (lr_local && lr_local.cfi) {
+                console.log(`using local lastread cfi: ${lr_local.cfi}`);
+                try {
+                    await this.moveToCfiVerify(rendition, lr_local.cfi);
+                } catch (e) {
+                    console.warn(e);
+                }
+            }
+        }
+
+        $(".loading").fadeOut();
+    }
+
+    /**
+     * Calculate the delta (distance) between two CFI strings.
+     * Returns -1 if they cannot be compared or have different step counts/ids.
+     * @param a First CFI string (may be null).
+     * @param b Second CFI string (may be null).
+     */
+    calculateCfiDelta(a: string | null, b: string | null) {
+        if (!a || !b)
+            return -1;
+
+        const acfi = new ePub.CFI(a);
+        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;
+    }
+
+    /**
+     * Attempt to navigate to a CFI and verify the move was successful.
+     * @param rendition The ePub.js rendition to display on.
+     * @param cfi The target CFI string to navigate to.
+     */
+    async moveToCfiVerify(rendition: ePub.Rendition, cfi: string, 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;
+    }
+
+    /**
+     * Apply the selected theme after a change.
+     * @param elem The HTMLElement containing the selected theme value.
+     */
+    async onThemeChanged(elem: HTMLElement) {
+        const theme = $(elem).val() as string;
+
+        await localforage.setItem("epube.theme", theme);
+        this.applyTheme();
+    }
+
+    /**
+     * Apply the selected line height after a change.
+     * @param elem The HTMLElement containing the selected line height value.
+     */
+    async onLineHeightChanged(elem: HTMLElement) {
+        const height = $(elem).val() as string;
+
+        await localforage.setItem("epube.lineHeight", height);
+        this.applyTheme();
+    }
+
+    /**
+     * Apply the selected font size after a change.
+     * @param elem The HTMLElement containing the selected font size value.
+     */
+    async onTextSizeChanged(elem: HTMLElement) {
+        const size = $(elem).val() as string;
+
+        await localforage.setItem("epube.fontSize", size);
+        this.applyTheme();
+    }
+
+    /**
+     * Apply the selected font family after a change.
+     * @param elem The HTMLElement containing the selected font value.
+     */
+    async onFontChanged(elem: HTMLElement) {
+        const font = $(elem).val() as string;
+
+        await localforage.setItem("epube.fontFamily", font);
+        this.applyTheme();
+    }
+}
+
+class ReaderLoader {
+    _res_data = {};
+
+    /**
+     * Initialize the resource loader by reading cached assets.
+     * @param app The ReaderClass instance to use for cache operations.
+     */
+    async init(app: ReaderClass) {
+        const cacheName = await app.getActiveCacheName();
+
+        if (!cacheName) {
+            console.error('failed to determine active cache name');
+
+            $(".loading-message").html("Failed to determine active cache name");
+            return;
+        }
+
+        console.log('loader init for cache:', cacheName);
+
+        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.
+
+        const cache = await caches.open(cacheName);
+        const cacheKeys = await cache.keys();
+
+        const promises: Promise<void>[] = [];
+        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;
+
+            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();
+
+            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;
+            }));
+        }
+
+        await Promise.allSettled(promises);
+
+        if (Object.keys(this._res_data).length === 0) loadFailed = true;
+
+        console.log('[loader] loaded', Object.keys(this._res_data).length, 'resources, failed:', loadFailed);
+
+        return loadFailed;
+    }
+}