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