about summary refs log tree commit diff stats
path: root/dist/reader.js
diff options
context:
space:
mode:
Diffstat (limited to 'dist/reader.js')
-rw-r--r--dist/reader.js1346
1 files changed, 1346 insertions, 0 deletions
diff --git a/dist/reader.js b/dist/reader.js
new file mode 100644
index 0000000..053f495
--- /dev/null
+++ b/dist/reader.js
@@ -0,0 +1,1346 @@
+'use strict';
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.ReaderClass = void 0;
+const DEFAULT_FONT_SIZE = 16;
+const DEFAULT_FONT_FAMILY = "Arial";
+const DEFAULT_LINE_HEIGHT = 140;
+const MIN_LENGTH_TO_JUSTIFY = 32; /* characters */
+const LOCATION_DIVISOR = 10;
+const PAGE_RESET_PROGRESS = -1;
+const appcommon_1 = require("./appcommon");
+const cookie_1 = require("./cookie");
+class ReaderClass extends appcommon_1.AppCommon {
+    constructor() {
+        super(...arguments);
+        this.csrf_token = "";
+        this.last_stored_cfi = "";
+        this.startup_finished = false;
+        this.open_last_read_when_displayed = true;
+        this.hyphenate = { en: null, ru: null };
+    }
+    async init() {
+        this.csrf_token = cookie_1.Cookie.get('epube_csrf_token');
+        console.log('setting prefilter for token', this.csrf_token);
+        $.ajaxPrefilter((options, originalOptions /*, jqXHR*/) => {
+            if (originalOptions.type !== 'post' || options.type !== 'post') {
+                return;
+            }
+            const datatype = typeof originalOptions.data;
+            if (datatype == 'object')
+                options.data = $.param($.extend(originalOptions.data, { "csrf_token": this.csrf_token }));
+            else if (datatype == 'string')
+                options.data = originalOptions.data + "&csrf_token=" + encodeURIComponent(this.csrf_token);
+            console.log('>>>', options);
+        });
+        $(document).on("keyup", (e) => {
+            this.hotkeyHandler(e);
+        });
+        $(".close_book").on("click", () => {
+            this.close();
+        });
+        $("#left").on("mouseup", () => {
+            this.prevPage();
+        });
+        $(".search_input").on("change", () => {
+            this.search();
+        });
+        $(".prev_location_btn").on("click", (evt) => {
+            this.openPrevious(evt.target);
+        });
+        $("#right").on("mouseup", () => {
+            this.nextPage();
+        });
+        this.loader = new ReaderLoader();
+        const load_failed = await this.loader.init();
+        console.log('[init] load failed', load_failed);
+        if (!load_failed) {
+            this.initSecondStage();
+        }
+        else {
+            this.applyTheme();
+            $(".loading-message").text('Resource loader failed to initialize.');
+        }
+    }
+    // another method, maybe use this: window.matchMedia("(pointer: coarse)").matches
+    // https://stackoverflow.com/questions/4817029/whats-an-optimal-or-efficient-way-to-detect-a-touch-screen-device-using-javas
+    isTouchDevice() {
+        return ('ontouchstart' in window) || (navigator.maxTouchPoints > 0);
+    }
+    /**
+     * @param {boolean} offline
+     */
+    onOfflineModeChanged(offline) {
+        console.log('onOfflineModeChanged', offline);
+        if (!offline && this.book) {
+            console.log("we're online, storing lastread");
+            const currentCfi = this.book.rendition.currentLocation().start.cfi;
+            const currentPage = Math.round(this.book.locations.percentageFromCfi(currentCfi) * 100); // TODO wtf
+            $.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: currentPage,
+                cfi: currentCfi, timestamp: new Date().getTime() }, function () {
+                //
+            })
+                .fail(function (e) {
+                if (e && e.status == 401) {
+                    window.location.href = "index.php";
+                }
+            });
+        }
+    }
+    async initSecondStage() {
+        if (typeof EpubeApp != "undefined") {
+            EpubeApp.setPage("PAGE_READER");
+        }
+        else {
+            $(window).on('online', () => {
+                this.onOfflineModeChanged(false);
+            });
+            $(window).on('offline', () => {
+                this.onOfflineModeChanged(true);
+            });
+        }
+        this.applyTheme();
+        const bookinfo = await localforage.getItem(this.cacheId());
+        if (!bookinfo) {
+            const bookId = this.urlParam("b");
+            console.log('requesting bookinfo for book', bookId);
+            try {
+                const resp = await $.post("backend.php", { op: "getinfo", id: bookId });
+                if (resp.has_cover) {
+                    const cover = await fetch("backend.php?op=cover&id=" + bookId);
+                    if (cover.ok)
+                        await localforage.setItem(this.cacheId('cover'), cover.blob());
+                }
+                await localforage.setItem(this.cacheId(), resp);
+                console.log('bookinfo saved');
+            }
+            catch (e) {
+                $(".loading-message").html(`Unable to load book info.<br/><small>${e.responseText}</small>`);
+                return;
+            }
+        }
+        console.log('trying to load book...');
+        let book_data = await localforage.getItem(this.cacheId("book"));
+        if (!book_data) {
+            console.log("local data not found, loading from network...");
+            $(".loading-message").html("Downloading book…");
+            const book_resp = await fetch("backend.php?op=download&id=" + this.urlParam("id"));
+            if (book_resp.ok) {
+                book_data = await book_resp.blob();
+                if (book_data) {
+                    await localforage.setItem(this.cacheId('book'), book_data);
+                    console.log('saved local data for book');
+                }
+                else {
+                    $(".loading-message").html("Unable to get book blob data.");
+                    return;
+                }
+            }
+            else {
+                $(".loading-message").html(`Unable to download book: ${book_resp.status}`);
+                return;
+            }
+        }
+        const fileReader = new FileReader();
+        const _reader = this;
+        fileReader.onload = function () {
+            try {
+                _reader.openBookData(this.result);
+            }
+            catch (e) {
+                console.error(e);
+                $(".loading-message").html("Unable to load book blob: " + e);
+            }
+        };
+        fileReader.onerror = (e) => {
+            console.log('filereader error', e);
+            $(".loading-message").html("Unable to open book.<br/><small>" + e + "</small>");
+        };
+        fileReader.readAsArrayBuffer(book_data);
+    }
+    async openBookData(book_data) {
+        // @ts-ignore
+        this.book = new ePub.Book();
+        try {
+            await this.book.open(book_data);
+        }
+        catch (e) {
+            console.error(e);
+            $(".loading-message").html("Unable to open book.<br/><small>" + e.message + "</small>");
+            return;
+        }
+        await this.book.ready;
+        console.log('book is ready');
+        await this.showBookInfo(this.book);
+        await this.loadLocations(this.book);
+        const rendition = this.book.renderTo("reader", {
+            width: '100%',
+            height: '100%',
+            allowScriptedContent: false,
+            minSpreadWidth: 961
+        });
+        $(".location").on('click', async () => {
+            const current = Math.floor(rendition.currentLocation().start.location / LOCATION_DIVISOR);
+            const total = Math.floor(this.book.locations.length() / LOCATION_DIVISOR);
+            const page = prompt("Jump to location [1-" + total + "]", String(current));
+            if (page)
+                await rendition.display(this.book.locations._locations[parseInt(page) * LOCATION_DIVISOR]);
+        });
+        const enable_hyphens = await localforage.getItem("epube.enable-hyphens");
+        if (enable_hyphens) {
+            /* global hyphenationPatternsEnUs, hyphenationPatternsRu, createHyphenator */
+            this.hyphenate.en = createHyphenator(hyphenationPatternsEnUs, { html: true });
+            this.hyphenate.ru = createHyphenator(hyphenationPatternsRu, { html: true });
+        }
+        this.initRenditionHooks(this.book, rendition);
+        this.initModals();
+        this.initToc(this.book);
+        // open first page at startup, lastread will open when it is rendered
+        this.blockLastReadUpdate();
+        await rendition.display();
+        console.log('startup finished');
+        this.startup_finished = true;
+    }
+    /**
+     * @param {ePub.Book} book
+     */
+    async showBookInfo(book) {
+        const bookinfo = await localforage.getItem(this.cacheId());
+        let title;
+        let author;
+        if (bookinfo) {
+            title = bookinfo.title;
+            author = bookinfo.author_sort;
+        }
+        else {
+            const metadata = book.packaging.metadata;
+            title = metadata.title;
+            author = metadata.creator;
+        }
+        document.title = title + " – " + author + " – The Epube";
+        $(".title")
+            .text(title)
+            .attr("title", title + " – " + author);
+        if (typeof EpubeApp != "undefined") {
+            EpubeApp.setTitle(title);
+            EpubeApp.showActionBar(false);
+        }
+    }
+    /**
+     * @param {ePub.Book} book
+     */
+    async loadLocations(book) {
+        let locations = await localforage.getItem(this.cacheId("locations"));
+        // legacy format is array of objects {cfi: ..., page: ...}
+        if (locations && typeof locations[0] == "string") {
+            console.log('loading local locations...');
+            try {
+                await book.locations.load(locations);
+                return;
+            }
+            catch (e) {
+                console.warn(e);
+            }
+        }
+        if (this.isOnline()) {
+            console.log("downloading locations...");
+            $(".loading-message").html("Downloading locations…");
+            const resp = await fetch("backend.php?op=getpagination&id=" + this.urlParam("id"));
+            if (resp.ok) {
+                console.log("got locations from server");
+                // if this doesn't load, we'll generate locations and save them
+                try {
+                    locations = await resp.json();
+                }
+                catch (e) {
+                    console.warn(e);
+                }
+                if (locations && typeof locations[0] == "string") {
+                    console.log('saving locations locally...');
+                    await localforage.setItem(this.cacheId("locations"), locations);
+                    try {
+                        book.locations.load(locations);
+                        return;
+                    }
+                    catch (e) {
+                        console.warn(e);
+                    }
+                }
+            }
+        }
+        $(".loading-message").html("Preparing locations…");
+        let generate_queue_max = 0;
+        locations = await book.locations.generate(100, (queue) => {
+            if (!generate_queue_max)
+                generate_queue_max = queue.length();
+            // what if there's only one section or something and queue is already zero
+            if (generate_queue_max > 0) {
+                const queue_pct = Math.round((1 - queue.length() / generate_queue_max) * 100); // TODO un-wtf
+                $(".loading-message").html(`Preparing locations (${queue_pct}%)…`);
+            }
+        });
+        $.post("backend.php", { op: "storepagination", id: this.urlParam("id"),
+            payload: JSON.stringify(locations), total: 100 });
+        await localforage.setItem(this.cacheId("locations"), locations);
+    }
+    /**
+     * @param {ePub.Book} book
+     * @param {ePub.Rendition} rendition
+     */
+    initRenditionHooks(book, rendition) {
+        console.log('initRenditionHooks');
+        book.spine.hooks.content.register((doc /*, section */) => {
+            this.cleanupEmbeddedStyles(doc);
+        });
+        rendition.hooks.content.register(async (contents) => {
+            contents.on("linkClicked", (href) => {
+                console.log('linkClicked', href);
+                this.blockLastReadUpdate();
+                if (href.indexOf("://") == -1) {
+                    $(".prev_location_btn")
+                        .attr("data-location-cfi", rendition.currentLocation().start.cfi)
+                        .show();
+                    window.requestAnimationFrame(() => {
+                        this.showUI(true);
+                    });
+                }
+            });
+            contents.on("selected", async (cfiRange) => {
+                if (this.isOnline()) {
+                    const range = await book.getRange(cfiRange);
+                    const selection = range.endContainer.data.substring(range.startOffset, range.endOffset);
+                    console.log('selected', cfiRange, selection);
+                    if (selection.match(/^[\w­]+$/)) {
+                        this.lookupWord(selection, () => {
+                            if (typeof EpubeApp != "undefined")
+                                EpubeApp.showActionBar(false);
+                            contents.window.requestAnimationFrame(() => {
+                                contents.window.getSelection().removeAllRanges();
+                            });
+                        });
+                    }
+                }
+            });
+            // get our stuff from resource loader and inject into iframe content
+            const base_url = window.location.href.match(/^.*\//)[0];
+            $(contents.document.head)
+                .append($("<style type='text/css'>")
+                .text(this.generateFontsCss(base_url)));
+            $(contents.document.head)
+                .append($("<style type='text/css'>")
+                .text(this.loader._res_data[base_url + 'dist/reader_iframe.min.css']));
+            const theme = await localforage.getItem("epube.theme") || 'default';
+            $(contents.document).find("body")
+                .attr("class", typeof EpubeApp != "undefined" ? "is-epube-app" : "")
+                .addClass("theme-" + theme);
+            console.log('contents', contents);
+            $(contents.window).on("click tap", (evt) => {
+                if (evt.button == 0) {
+                    if ($(".modal").is(":visible"))
+                        return;
+                    if (typeof EpubeApp != "undefined")
+                        EpubeApp.toggleActionBar();
+                    else
+                        this.showUI(true);
+                }
+            });
+            $(contents.window).on("wheel", async (evt) => {
+                if (await localforage.getItem("epube.enable-wheel")) {
+                    if (evt.originalEvent.deltaY > 0) {
+                        this.nextPage();
+                    }
+                    else if (evt.originalEvent.deltaY < 0) {
+                        this.prevPage();
+                    }
+                }
+            });
+            // need to figure out how to do swipes safely (invisible overlay which passes text selection?)
+            /* if (typeof EpubeApp != "undefined" || Reader.isTouchDevice()) {
+                    $(window).on("swipeleft", function() {
+                        console.log('swipe left');
+
+                        this.nextPage();
+                    });
+
+                    $(window).on("swiperight", function() {
+                        console.log('swipe right');
+
+                        this.prevPage();
+                    });
+            } */
+        });
+        rendition.on("keyup", (e) => {
+            this.hotkeyHandler(e);
+        });
+        rendition.on('resized', ( /*chapter*/) => {
+            console.log('rendition resized');
+            this.blockLastReadUpdate();
+            this.open_last_read_when_displayed = true;
+        });
+        rendition.on('rendered', async ( /* section */) => {
+            console.log('rendition rendered');
+            this.applyTheme();
+            this.resizeSideColumns();
+            try {
+                const location = rendition.currentLocation();
+                if (location.start) {
+                    const cur_href = book.canonical(location.start.href);
+                    let toc_entry = { label: "" };
+                    $.each(this.flattenToc(book), function (i, r) {
+                        if (book.spine.get(r.href).canonical == cur_href) {
+                            toc_entry = r;
+                            return;
+                        }
+                    });
+                    if (toc_entry && toc_entry.label)
+                        $(".chapter_title").html(toc_entry.label.trim() + " | ");
+                    this.generateTocBar(book, this.flattenToc(book));
+                }
+            }
+            catch (e) {
+                console.warn(e);
+            }
+            if (this.open_last_read_when_displayed) {
+                this.open_last_read_when_displayed = false;
+                await this.openLastRead();
+            }
+        });
+        // this seems to be called a lot more than rendered
+        rendition.on('displayed', function ( /*chapter*/) {
+            console.log('rendition displayed');
+        });
+        rendition.on('relocated', (/** @type {ePub.Location} */ location) => this.onRelocated(book, location));
+    }
+    initModals() {
+        $('#settings-modal').on('shown.bs.modal', async () => {
+            const last_read = await localforage.getItem(this.cacheId("lastread"));
+            if (last_read && last_read.cfi) {
+                $(".lastread_input")
+                    .val(last_read.page + '%')
+                    .attr('title', `[local] ${last_read.cfi}`);
+            }
+            $(".clear_last_read")
+                .off("click")
+                .on("click", () => {
+                this.clearLastRead();
+            });
+            $(".open_last_read")
+                .off("click")
+                .on("click", () => {
+                this.openLastRead();
+            });
+            $(".mark_as_read")
+                .off("click")
+                .on("click", () => {
+                this.markAsRead();
+            });
+            $(".reset_locations")
+                .off("click")
+                .on("click", () => {
+                this.resetLocations();
+            });
+            if (navigator.onLine)
+                $.post("backend.php", { op: "getlastread", id: this.urlParam("id") }, (data) => {
+                    $(".lastread_input")
+                        .val(data.page + '%')
+                        .attr('title', `[remote] ${data.cfi}`);
+                });
+            $(".font_family")
+                .off("change")
+                .on("change", (evt) => {
+                this.onFontChanged(evt.target);
+            });
+            $(".font_size")
+                .off("change")
+                .on("change", (evt) => {
+                this.onTextSizeChanged(evt.target);
+            });
+            $(".line_height")
+                .off("change")
+                .on("change", (evt) => {
+                this.onLineHeightChanged(evt.target);
+            });
+            $(".theme_name")
+                .off("change")
+                .on("change", (evt) => {
+                this.onThemeChanged(evt.target);
+            });
+            $(".enable_hyphens_checkbox")
+                .attr("checked", await localforage.getItem("epube.enable-hyphens"))
+                .off("click")
+                .on("click", (evt) => {
+                localforage.setItem("epube.enable-hyphens", evt.target.checked);
+                if (confirm("Toggling hyphens requires page reload. Reload now?")) {
+                    window.location.reload();
+                }
+            });
+            $(".enable_wheel_checkbox")
+                .attr("checked", await localforage.getItem("epube.enable-wheel"))
+                .off("click")
+                .on("click", (evt) => {
+                localforage.setItem("epube.enable-wheel", evt.target.checked);
+            });
+            if (typeof EpubeApp != "undefined") {
+                $(".keep_ui_checkbox").parent().parent().hide();
+            }
+            else {
+                $(".keep_ui_checkbox")
+                    .attr("checked", await localforage.getItem("epube.keep-ui-visible"))
+                    .off("click")
+                    .on("click", (evt) => {
+                    localforage.setItem("epube.keep-ui-visible", evt.target.checked);
+                });
+            }
+            const stamp = String(await localforage.getItem("epube.cache-timestamp"));
+            const version = await localforage.getItem("epube.cache-version");
+            $(".last-mod-timestamp").html(`${version}
+				&mdash; ${parseInt(stamp) ? new Date(parseInt(stamp) * 1000).toLocaleString("en-GB") : "Unknown"}
+				(${this.isOnline() ? `<span class='text-success'>Online</span>` : `<span class='text-danger'>Offline</span>`})
+				`);
+            $(".font_family").val(await localforage.getItem("epube.fontFamily") || DEFAULT_FONT_FAMILY);
+            $(".theme_name").val(await localforage.getItem("epube.theme") || 'default');
+            const zoom = $(".font_size").html("");
+            for (let i = 10; i <= 32; i++) {
+                const opt = $("<option>").val(i).html(i + " px");
+                zoom.append(opt);
+            }
+            zoom.val(await localforage.getItem("epube.fontSize") || DEFAULT_FONT_SIZE);
+            const line_height = $(".line_height").html("");
+            for (let i = 100; i <= 220; i += 10) {
+                const opt = $("<option>").val(i).html(i + "%");
+                line_height.append(opt);
+            }
+            line_height.val(await localforage.getItem("epube.lineHeight") || DEFAULT_LINE_HEIGHT);
+        });
+        $('#dict-modal').on('shown.bs.modal', () => {
+            $(".dict_query")
+                .off("change")
+                .on("change", () => {
+                this.lookupWord(null, null, '.dict_query');
+            });
+            $(".dict_result").scrollTop(0);
+        });
+        // TODO: make configurable
+        $(".dict_search_btn").on("click", function () {
+            $("#dict-modal").modal('hide');
+            window.open("https://duckduckgo.com/?q=" + $(".dict_query").val());
+        });
+    }
+    initToc(book) {
+        const _reader = this;
+        function toc_loc_msg(href) {
+            try {
+                const cfiBase = book.spine.get(href).cfiBase;
+                const loc = book.locations._locations.find(function (k) {
+                    return k.indexOf(cfiBase) != -1;
+                });
+                return Math.round(_reader.book.locations.locationFromCfi(loc) / LOCATION_DIVISOR);
+            }
+            catch (e) {
+                console.warn(e);
+            }
+            return "";
+        }
+        function process_toc_sublist(row, list, nest) {
+            if (nest == 3)
+                return false;
+            if (row.subitems) {
+                const sublist = $("<ul class='toc_sublist list-unstyled'>");
+                $.each(row.subitems, function (i, row) {
+                    const a = $("<a>")
+                        .attr('href', '#')
+                        .html("<b class='pull-right'>" + toc_loc_msg(row.href) + "</b>" + row.label)
+                        .attr('data-href', row.href)
+                        .click(function () {
+                        book.rendition.display(a.attr('data-href'));
+                    });
+                    sublist.append($("<li>").append(a));
+                    process_toc_sublist(row, sublist, nest + 1);
+                });
+                list.append(sublist);
+            }
+        }
+        $('#toc-modal').on('shown.bs.modal', function () {
+            const toc = book.navigation.toc;
+            const list = $(".toc_list");
+            list.html("");
+            $.each(toc, function (i, row) {
+                // if anything fails here the toc entry is likely useless anyway (i.e. no cfi)
+                try {
+                    const a = $("<a>")
+                        .attr('href', '#')
+                        .html("<b class='pull-right'>" + toc_loc_msg(row.href) + "</b>" + row.label)
+                        .attr('data-href', row.href)
+                        .click(function () {
+                        book.rendition.display(a.attr('data-href'));
+                    });
+                    list.append($("<li>").append(a));
+                    process_toc_sublist(row, list, 0);
+                }
+                catch (e) {
+                    console.warn(e);
+                }
+            });
+            // well the toc didn't work out, might as well generate one
+            if (list.children().length <= 1) {
+                list.html("");
+                $.each(book.spine.items, function (i, row) {
+                    const a = $("<a>")
+                        .attr('href', '#')
+                        .attr('title', row.url)
+                        // @ts-ignore
+                        .html(`Section ${i + 1}`)
+                        .attr('data-href', row.href)
+                        .on('click', () => {
+                        book.rendition.display(a.attr('data-href'));
+                    });
+                    list.append($("<li>").append(a));
+                });
+            }
+        });
+    }
+    /* embedded styles may conflict with our font sizes, etc */
+    cleanupEmbeddedStyles(doc) {
+        $(doc).find("p")
+            // @ts-ignore
+            .filter((i, e) => (($(e).text().length >= MIN_LENGTH_TO_JUSTIFY) ? e : null))
+            .css("text-align", "justify");
+        $(doc).find("html")
+            .attr("class", "");
+        $(doc).find("pre")
+            .css("white-space", "pre-wrap");
+        $(doc).find("a, p, span, em, i, strong, b, body, header, section, div, big, small, table, tr, td, th, ul, ol, li")
+            .attr("class", "")
+            .css("font-family", "inherit")
+            .css("font-size", "inherit")
+            .css("line-height", "inherit")
+            .css("color", "")
+            .css("border", "none ! important")
+            .css("background", "")
+            .css("background-color", "")
+            .attr("width", "")
+            .attr("height", "");
+        // same as above except for allowed font-size
+        $(doc).find("h1, h2, h3, h4, h5")
+            .attr("class", "")
+            .css("font-family", "inherit")
+            .css("color", "")
+            .css("border", "none ! important")
+            .css("background", "")
+            .css("background-color", "");
+        if (typeof this.hyphenate.en != "undefined") {
+            $(doc).find('p, div').each((i, elem) => {
+                const p = $(elem);
+                p.html(this.hyphenate.en(p.html()));
+                p.html(this.hyphenate.ru(p.html()));
+            });
+        }
+    }
+    generateFontsCss(base_url) {
+        return `
+			/** Calibri */
+
+			@font-face {
+				font-family: 'Calibri';
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/calibriz.ttf']});
+				font-style: italic;
+				font-weight : 700;
+			}
+
+			@font-face {
+				font-family: 'Calibri';
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/calibrib.ttf']});
+				font-style: normal;
+				font-weight : 700;
+			}
+
+			@font-face {
+				font-family: 'Calibri';
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/calibrii.ttf']});
+				font-style: italic;
+				font-weight : 400;
+			}
+
+			@font-face {
+				font-family: 'Calibri';
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/calibri.ttf']});
+				font-style: normal;
+				font-weight : 400;
+			}
+
+			/** Cambria */
+
+			@font-face {
+				font-family: 'Cambria';
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/cambriab.ttf']});
+				font-style: normal;
+				font-weight : 700;
+			}
+
+			@font-face {
+				font-family: 'Cambria';
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/cambriaz.ttf']});
+				font-style: italic;
+				font-weight : 700;
+			}
+
+			@font-face {
+				font-family: 'Cambria';
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/cambriai.ttf']});
+				font-style: italic;
+				font-weight : 400;
+			}
+
+			@font-face {
+				font-family: 'Cambria';
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/cambria.ttf']});
+				font-style: normal;
+				font-weight : 400;
+			}
+
+			/** Caecilia */
+
+			@font-face {
+				font-family: Caecilia;
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/caecilia.ttf']});
+				font-weight : normal;
+			}
+
+			@font-face {
+				font-family: Caecilia;
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/caeciliab.ttf']});
+				font-weight : bold;
+			}
+
+			@font-face {
+				font-family: Caecilia;
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/caeciliai.ttf']});
+				font-style : italic;
+			}
+
+			/** Palatino */
+
+			@font-face {
+				font-family: 'Palatino';
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/palab.ttf']});
+				font-style: normal;
+				font-weight : 700;
+			}
+
+			@font-face {
+				font-family: 'Palatino';
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/palabi.ttf']});
+				font-style: italic;
+				font-weight : 700;
+			}
+
+			@font-face {
+				font-family: 'Palatino';
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/palai.ttf']});
+				font-style: italic;
+				font-weight : 400;
+			}
+
+			@font-face {
+				font-family: 'Palatino';
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/pala.ttf']});
+				font-style: normal;
+				font-weight : 400;
+			}
+
+			/** Consolas */
+
+			@font-face {
+				font-family: 'Consolas';
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/consolab.ttf']});
+				font-style: normal;
+				font-weight : 700;
+			}
+
+			@font-face {
+				font-family: 'Consolas';
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/consolaz.ttf']});
+				font-style: italic;
+				font-weight : 700;
+			}
+
+			@font-face {
+				font-family: 'Consolas';
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/consolai.ttf']});
+				font-style: italic;
+				font-weight : 400;
+			}
+
+			@font-face {
+				font-family: 'Consolas';
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/consola.ttf']});
+				font-style: normal;
+				font-weight : 400;
+			}
+
+			/** IBM Plex Mono */
+
+			@font-face {
+				font-family: 'IBM Plex Mono';
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/IBMPlexMono-Bold.otf']});
+				font-style: normal;
+				font-weight : 700;
+			}
+
+			@font-face {
+				font-family: 'IBM Plex Mono';
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/IBMPlexMono-BoldItalic.otf']});
+				font-style: italic;
+				font-weight : 700;
+			}
+
+			@font-face {
+				font-family: 'IBM Plex Mono';
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/IBMPlexMono-TextItalic.otf']});
+				font-style: italic;
+				font-weight : 400;
+			}
+
+			@font-face {
+				font-family: 'IBM Plex Mono';
+				src: url(${this.loader._res_data[base_url + 'lib/fonts/IBMPlexMono-Text.otf']});
+				font-style: normal;
+				font-weight : 400;
+			}
+			`;
+    }
+    flattenTocSubItems(entry, nest) {
+        let rv = [];
+        if (nest == 3)
+            return false;
+        if (entry.subitems) {
+            $.each(entry.subitems, (i, r) => {
+                r._nest = nest;
+                rv.push(r);
+                rv = rv.concat(this.flattenTocSubItems(r, nest + 1));
+            });
+        }
+        return rv;
+    }
+    /**
+     * @param { ePub.Book } book
+     *
+     * @returns { ePub.NavItem[] }
+     */
+    flattenToc(book) {
+        if (this._flattened_toc) {
+            return this._flattened_toc;
+        }
+        else {
+            let rv = [];
+            $.each(book.navigation.toc, (i, r) => {
+                // @ts-ignore
+                r._nest = 0;
+                rv.push(r);
+                rv = rv.concat(this.flattenTocSubItems(r, 1));
+            });
+            this._flattened_toc = rv;
+            return rv;
+        }
+    }
+    /**
+     * @param { ePub.Book } book
+     * @param { any[] } toc
+     */
+    generateTocBar(book, toc) {
+        $(".spacer")
+            .html("");
+        $.each(toc, function (i, te) {
+            try {
+                const cfiBase = book.spine.get(te.href).cfiBase;
+                const loc = book.locations._locations.find(function (k) {
+                    return k.indexOf(cfiBase) != -1;
+                });
+                if (loc) {
+                    const pct = Math.round(book.locations.percentageFromCfi(loc) * 100);
+                    $(".spacer").append($("<div class='toc-bar-entry'>")
+                        .attr('data-nest-level', te._nest)
+                        .css('left', pct + '%')
+                        .css('_width', (3 - te._nest) + "px")
+                        .attr("title", te.label));
+                }
+            }
+            catch (e) {
+                console.warn(e);
+            }
+        });
+        $(".spacer").append($("<div class='toc-bar-entry current-position'>"));
+        this.updateTocBarPosition(book, book.rendition.currentLocation());
+    }
+    updateTocBarPosition(book, location) {
+        const cur_pct = Math.round(location.start.location / book.locations.length() * 100);
+        $(".toc-bar-entry.current-position")
+            .css('left', cur_pct + '%');
+    }
+    async applyTheme() {
+        let fontSize = await localforage.getItem("epube.fontSize");
+        let fontFamily = await localforage.getItem("epube.fontFamily");
+        let lineHeight = await localforage.getItem("epube.lineHeight");
+        fontSize = fontSize ? fontSize + "px" : DEFAULT_FONT_SIZE + "px";
+        fontFamily = fontFamily ? fontFamily : DEFAULT_FONT_FAMILY;
+        lineHeight = lineHeight ? lineHeight + "%" : DEFAULT_LINE_HEIGHT + "%";
+        console.log('style', fontFamily, fontSize, lineHeight);
+        console.log('applying default theme styles...');
+        if (this.book && this.book.rendition)
+            this.book.rendition.themes.default({
+                html: {
+                    'font-size': fontSize,
+                    'font-family': "'" + fontFamily + "'",
+                    'line-height': lineHeight,
+                    'text-align': 'justify',
+                    'text-indent': '1em'
+                }
+            });
+        let theme = await localforage.getItem("epube.theme") || "default";
+        console.log('called for theme', theme);
+        if (theme == "default" && typeof EpubeApp != "undefined")
+            if (EpubeApp.isNightMode())
+                theme = "night";
+        console.log('setting main UI theme', theme);
+        $("body")
+            .attr("class", typeof EpubeApp != "undefined" ? "is-epube-app" : "")
+            .addClass("epube-reader theme-" + theme)
+            .attr("data-is-loading", "false");
+        if (typeof EpubeApp != "undefined") {
+            window.setTimeout(function () {
+                const bg_color = window.getComputedStyle(document.querySelector("body"), null)
+                    .getPropertyValue("background-color");
+                let match = bg_color.match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/);
+                if (match) {
+                    console.log("sending bgcolor", match);
+                    EpubeApp.setStatusBarColor(parseInt(match[1]), parseInt(match[2]), parseInt(match[3]));
+                }
+                const accent_color = window.getComputedStyle(document.querySelector(".header .title"), null)
+                    .getPropertyValue("color");
+                match = accent_color.match(/rgb\((\d{1,}), (\d{1,}), (\d{1,})\)/);
+                if (match) {
+                    console.log("sending accent_color", match);
+                    EpubeApp.setAccentColor(parseInt(match[1]), parseInt(match[2]), parseInt(match[3]));
+                }
+            }, 250);
+        }
+        if (this.book && this.book.rendition)
+            this.book.rendition.getContents().forEach((rendition) => {
+                console.log(`applying styles and theme ${theme} to `, rendition);
+                rendition.css("font-size", fontSize);
+                rendition.css("font-family", "'" + fontFamily + "'");
+                rendition.css("line-height", lineHeight);
+                rendition.css("text-align", 'justify');
+                $(rendition.document).find("body")
+                    .attr("class", typeof EpubeApp != "undefined" ? "is-epube-app" : "")
+                    .addClass("theme-" + theme);
+            });
+    }
+    hotkeyHandler(e) {
+        try {
+            //console.log('K3:' + e.which, e);
+            if ($(".modal").is(":visible"))
+                return;
+            // right or space or pagedown
+            if (e.which == 39 || e.which == 32 || e.which == 34) {
+                e.preventDefault();
+                this.nextPage();
+            }
+            // left or pageup
+            if (e.which == 37 || e.which == 33) {
+                e.preventDefault();
+                this.prevPage();
+            }
+            // esc
+            if (e.which == 27) {
+                e.preventDefault();
+                this.showUI(true);
+            }
+        }
+        catch (e) {
+            console.warn(e);
+        }
+    }
+    resizeSideColumns() {
+        let width = $("#reader").position().left;
+        if (this.book && this.book.rendition)
+            this.book.rendition.getContents().forEach((rendition) => {
+                width += parseInt(rendition.window.getComputedStyle(rendition.document.querySelector('body')).getPropertyValue('padding-left'));
+            });
+        console.log(`resizing side columns to ${width} px`);
+        $("#left, #right").width(width);
+    }
+    async markAsRead() {
+        if (confirm("Mark book as read?")) {
+            $("#settings-modal").modal('hide');
+            const total = 100;
+            const lastCfi = this.book.locations.cfiFromPercentage(1);
+            const lastread_timestamp = new Date().getTime();
+            if (this.isOnline()) {
+                const data = await $.post("backend.php", { op: "storelastread", page: total, cfi: lastCfi, id: this.urlParam("id"), timestamp: lastread_timestamp });
+                $(".lastread_input").val(data.page + '%');
+            }
+            await localforage.setItem(this.cacheId("lastread"), { cfi: lastCfi, page: total, total: total, timestamp: lastread_timestamp });
+            await this.openLastRead();
+        }
+    }
+    async close() {
+        const location = this.book.rendition.currentLocation();
+        const currentCfi = location.start.cfi;
+        const currentPage = Math.round(this.book.locations.percentageFromCfi(currentCfi) * 100);
+        const totalPages = 100;
+        const lastread_timestamp = new Date().getTime();
+        await localforage.setItem(this.cacheId("lastread"), { cfi: currentCfi, page: currentPage, total: totalPages, timestamp: lastread_timestamp });
+        if (this.isOnline()) {
+            $.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: currentPage,
+                cfi: currentCfi, timestamp: lastread_timestamp }, () => {
+                window.location.href = this.urlParam("rt") ? "index.php?mode=" + this.urlParam("rt") : "index.php";
+            })
+                .fail(() => {
+                window.location.href = "index.php";
+            });
+        }
+        else {
+            window.location.href = "index.php";
+        }
+    }
+    cacheId(suffix = "") {
+        return "epube-book." + this.urlParam("b") + (suffix ? "." + suffix : "");
+    }
+    showUI(show) {
+        if (show)
+            $(".header,.footer").fadeIn();
+        else
+            $(".header,.footer").fadeOut();
+    }
+    toggleUI() {
+        if ($(".header").is(":visible"))
+            $(".header,.footer").fadeOut();
+        else
+            $(".header,.footer").fadeIn();
+    }
+    async lookupWord(word, callback, elem = null) {
+        if (elem)
+            word = $(elem).val();
+        word = word.replace(/­/g, "");
+        console.log('lookupWord', word);
+        $(".dict_result").html('Loading, please wait...');
+        $("#dict-modal").modal('show');
+        try {
+            const data = await $.post("backend.php", { op: 'define', word: word });
+            if (data) {
+                $(".dict_result").html(data.result.join("<br/>"));
+                $(".dict_query").val(word);
+                if (callback)
+                    callback();
+            }
+        }
+        catch (e) {
+            console.error(e);
+            $(".dict_result").html(`Network error while looking up word: ${e.responseText}.`);
+        }
+    }
+    search() {
+        const query = $(".search_input").val();
+        const list = $(".search_results");
+        list.html("");
+        if (query) {
+            list.html("<li>Loading, please wait...</li>");
+            /* eslint-disable prefer-spread */
+            Promise.all(this.book.spine.spineItems.map((item) => item.load(this.book.load.bind(this.book))
+                // @ts-ignore TODO something wrong with the types (?)
+                .then(item.find.bind(item, query))
+                .finally(item.unload.bind(item))))
+                .then((results) => Promise.resolve([].concat.apply([], results)))
+                .then((results) => {
+                list.html("");
+                $.each(results, (i, row) => {
+                    const a = $("<a>")
+                        .attr('href', '#')
+                        .html("<b class='pull-right'>" + this.book.locations.locationFromCfi(row.cfi) + "</b>" + row.excerpt)
+                        .attr('data-cfi', row.cfi)
+                        .attr('data-id', row.id)
+                        .on('click', () => {
+                        this.book.rendition.display(a.attr('data-cfi'));
+                    });
+                    list.append($("<li>").append(a));
+                });
+            });
+        }
+    }
+    nextPage() {
+        this.book.rendition.next();
+        if (typeof EpubeApp != "undefined")
+            EpubeApp.showActionBar(false);
+        else
+            localforage.getItem("epube.keep-ui-visible").then((keep) => {
+                if (!keep)
+                    this.showUI(false);
+            });
+    }
+    prevPage() {
+        this.book.rendition.prev();
+        if (typeof EpubeApp != "undefined")
+            EpubeApp.showActionBar(false);
+        else
+            localforage.getItem("epube.keep-ui-visible").then((keep) => {
+                if (!keep)
+                    this.showUI(false);
+            });
+    }
+    /**
+     * @param {HTMLElement} elem
+     */
+    async openPrevious(elem) {
+        const cfi = $(elem).attr("data-location-cfi");
+        if (cfi)
+            await this.book.rendition.display(cfi);
+        $(elem).fadeOut();
+    }
+    blockLastReadUpdate() {
+        console.log('blocking last read updates...');
+        if (this._prevent_lastread_timeout)
+            window.clearTimeout(this._prevent_lastread_timeout);
+        this._prevent_lastread_timeout = window.setTimeout(() => {
+            this._prevent_lastread = false;
+            this._prevent_lastread_timeout = false;
+            console.log('unblocked last read updates');
+        }, 1000);
+        this._prevent_lastread = true;
+    }
+    /**
+     * @param { ePub.Book } book
+     * @param { ePub.Location } location
+     */
+    async onRelocated(book, location) {
+        // locations not generated yet
+        if (book.locations.length() == 0)
+            return;
+        const currentCfi = location.start.cfi;
+        const currentPct = Math.round(book.locations.percentageFromCfi(currentCfi) * 100);
+        $("#cur_page").text(Math.floor(location.start.location / LOCATION_DIVISOR));
+        $("#total_pages").text(Math.floor(book.locations.length() / LOCATION_DIVISOR));
+        $("#page_pct").text(Math.round(book.locations.percentageFromCfi(currentCfi) * 100) + '%');
+        this.updateTocBarPosition(book, location);
+        const displayed = location.start.displayed;
+        if (displayed) {
+            $("#chapter_cur_page").text(displayed.page);
+            $("#chapter_total_pages").text(displayed.total);
+            if (displayed.total > 0)
+                $("#chapter_pct").text(Math.round(displayed.page / displayed.total * 100) + '%');
+        }
+        if (this.startup_finished && this.last_stored_cfi != currentCfi && !this._prevent_lastread) {
+            const lastread_timestamp = new Date().getTime();
+            console.log("storing lastread", currentPct, currentCfi, lastread_timestamp);
+            await localforage.setItem(this.cacheId("lastread"), { cfi: currentCfi, page: currentPct, total: 100, timestamp: lastread_timestamp });
+            if (this.isOnline()) {
+                console.log("updating remote lastread", currentCfi);
+                this.last_stored_cfi = currentCfi;
+                $.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: currentPct,
+                    cfi: currentCfi, timestamp: lastread_timestamp });
+            }
+        }
+    }
+    async clearLastRead() {
+        if (confirm("Reset reading progress for this book?")) {
+            $("#settings-modal").modal('hide');
+            const total = this.book.locations.length();
+            const lastread_timestamp = new Date().getTime();
+            if (this.isOnline())
+                await $.post("backend.php", { op: "storelastread", page: PAGE_RESET_PROGRESS, cfi: "", id: this.urlParam("id"), timestamp: lastread_timestamp });
+            await localforage.setItem(this.cacheId("lastread"), { cfi: "", page: 0, total: total, timestamp: lastread_timestamp });
+            await this.book.rendition.display(this.book.locations.cfiFromPercentage(0));
+            $(".lastread_input").val('0%');
+        }
+    }
+    async resetLocations() {
+        if (confirm("Reset stored pagination data? This will also reset reading progress.")) {
+            $("#settings-modal").modal('hide');
+            await localforage.removeItem(this.cacheId("lastread"));
+            await localforage.removeItem(this.cacheId("locations"));
+            await $.post("backend.php", { op: "storelastread", page: PAGE_RESET_PROGRESS, cfi: "", id: this.urlParam("id"), timestamp: new Date().getTime() });
+            // this might return 404 and its okay
+            await $.post("backend.php", { op: "deletepagination", id: this.urlParam("id") }).catch((e) => console.log(e));
+            window.location.reload();
+        }
+    }
+    async openLastRead() {
+        $(".loading").show();
+        $(".loading-message").html("Opening last read page…");
+        $("#settings-modal").modal('hide');
+        const rendition = this.book.rendition;
+        if (!rendition) {
+            console.error('no rendition to work on');
+            return;
+        }
+        let location_found = false;
+        const lr_local = await localforage.getItem(this.cacheId("lastread")) || {};
+        console.log('got local lastread', lr_local);
+        if (this.isOnline()) {
+            try {
+                const lr_remote = await $.post("backend.php", { op: "getlastread", id: this.urlParam("id") });
+                console.log('got remote lastread', lr_remote);
+                if (lr_remote) {
+                    if (lr_remote.cfi && lr_local.cfi != lr_remote.cfi && (lr_remote.page >= (lr_local.page || 0))) {
+                        console.log(`using remote lastread cfi ${lr_remote.cfi}: cfi is different and remote pct ${lr_remote.page}% is further than local pct ${lr_local.page}%`);
+                        await localforage.setItem(this.cacheId("lastread"), { cfi: lr_remote.cfi, page: lr_remote.page, total: lr_remote.total, timestamp: lr_remote.timestamp });
+                        location_found = await this.moveToCfiVerify(rendition, lr_remote.cfi);
+                    }
+                }
+            }
+            catch (e) {
+                console.log('unable to get remote lastread, continuing...');
+                console.warn(e);
+            }
+        }
+        // for some reason this might not actually open *exact* CFI but it should generally be close enough after a few attempts,
+        // that's why we no longer reset to page 1 after trying local CFI
+        if (!location_found) {
+            if (lr_local && lr_local.cfi) {
+                console.log(`using local lastread cfi: ${lr_local.cfi}`);
+                try {
+                    await this.moveToCfiVerify(rendition, lr_local.cfi);
+                }
+                catch (e) {
+                    console.warn(e);
+                }
+            }
+        }
+        $(".loading").fadeOut();
+    }
+    /**
+     * @param {string} a
+     * @param {string} b
+     */
+    calculateCfiDelta(a, b) {
+        // @ts-ignore
+        const acfi = new ePub.CFI(a);
+        // @ts-ignore
+        const bcfi = new ePub.CFI(b);
+        console.log('calculateCfiDelta', acfi, bcfi);
+        if (acfi.path.steps.length != bcfi.path.steps.length)
+            return -1;
+        let delta = 0;
+        // this is about as ad-hoc as it gets...
+        for (let i = 0; i < acfi.path.steps.length; i++) {
+            // is this possible? who knows!
+            if (acfi.path.steps[i].type != bcfi.path.steps[i].type)
+                return -1;
+            // different "filepos" or w/e
+            if (acfi.path.steps[i].id != bcfi.path.steps[i].id)
+                return -1;
+            if (acfi.path.steps[i].id === null && acfi.path.steps[i].type === 'element')
+                delta += Math.abs(acfi.path.steps[i].index - bcfi.path.steps[i].index);
+        }
+        return delta;
+    }
+    /**
+     * @param {ePub.Rendition} rendition
+     * @param {string} cfi
+     */
+    async moveToCfiVerify(rendition, cfi, attempts = 5, maxDelta = 5) {
+        for (let att = 1; att < attempts; att++) {
+            this.blockLastReadUpdate();
+            console.log(`trying to open ${cfi}: attempt ${att} of ${attempts}...`);
+            /* eslint-disable no-await-in-loop */
+            await rendition.display(cfi); // we need to be synchronous here
+            let moved_to;
+            try {
+                moved_to = rendition.currentLocation().start.cfi;
+            }
+            catch (e) {
+                console.warn('location not yet available, will retry:', e);
+            }
+            try {
+                const delta = this.calculateCfiDelta(cfi, moved_to);
+                console.log(`opened cfi ${moved_to} expected ${cfi}; delta: ${delta}`);
+                if (moved_to == cfi || (delta != -1 && delta <= maxDelta)) {
+                    console.log("cfi move verified!");
+                    return true;
+                }
+            }
+            catch (e) {
+                console.warn('exception while parsing cfi, will retry: ', e);
+            }
+        }
+        return false;
+    }
+    /**
+     * @param {HTMLElement} elem
+     */
+    async onThemeChanged(elem) {
+        const theme = $(elem).val();
+        await localforage.setItem("epube.theme", theme);
+        this.applyTheme();
+    }
+    /**
+     * @param {HTMLElement} elem
+     */
+    async onLineHeightChanged(elem) {
+        const height = $(elem).val();
+        await localforage.setItem("epube.lineHeight", height);
+        this.applyTheme();
+    }
+    /**
+     * @param {HTMLElement} elem
+     */
+    async onTextSizeChanged(elem) {
+        const size = $(elem).val();
+        await localforage.setItem("epube.fontSize", size);
+        this.applyTheme();
+    }
+    /**
+     * @param {HTMLElement} elem
+     */
+    async onFontChanged(elem) {
+        const font = $(elem).val();
+        await localforage.setItem("epube.fontFamily", font);
+        this.applyTheme();
+    }
+}
+exports.ReaderClass = ReaderClass;
+class ReaderLoader {
+    constructor() {
+        this._res_data = [];
+        this.CACHE_NAME = 'epube-v3';
+    }
+    async init() {
+        if (typeof EpubeApp != "undefined") {
+            $("body").addClass("epube-app");
+        }
+        // we need to manually provide resources for reader iframe because service worker fetch() handler doesn't work inside iframes (chrome bug?)
+        const promises = [];
+        let load_failed = false;
+        const cache = await caches.open(this.CACHE_NAME);
+        const cache_keys = await cache.keys();
+        cache_keys.forEach((req) => {
+            if (!req.url.match('backend\.php')) {
+                console.log('[loader] loading resource', req.url);
+                const promise = fetch(req.url).then(async (resp) => {
+                    if (resp.ok) {
+                        const url = new URL(resp.url);
+                        url.searchParams.delete("ts");
+                        if (resp.url.match('\\.ttf|\\.otf')) {
+                            const blob = await resp.blob();
+                            console.log('[loader] storing blob', url.href);
+                            this._res_data[url.toString()] = URL.createObjectURL(blob);
+                        }
+                        else {
+                            const text = await resp.text();
+                            console.log('[loader] storing text', url.href);
+                            this._res_data[url.toString()] = text;
+                        }
+                    }
+                    else {
+                        console.warn('[loader] failed for resource', req.url, resp);
+                        $(".loading-message").html(`Unable to load resource.<br/><small>${req.url}</small>`);
+                        load_failed = true;
+                    }
+                });
+                promises.push(promise);
+            }
+        });
+        await Promise.allSettled(promises);
+        console.log('[loader] resource load complete, failed: ', load_failed);
+        return load_failed;
+    }
+}