// @ts-check
'use strict';
/** Pattern definition as produced by the hyphen library's build process. */
declare interface HTMLElement { checked: boolean }
declare interface Event { deltaY: number, deltaX: number }
declare interface Node { data: string }
interface NetworkError extends Error {
responseText?: string; // optional
}
declare type SwipeState = {
active: boolean,
startX: number,
startY: number,
startTime: number,
direction: 'left'|'right';
}
declare type SwipeConfig = {
minDistance: number,
velocityThreshold: number,
verticalDistanceThreshold: number
}
const DEFAULT_FONT_SIZE = 16;
const DEFAULT_FONT_FAMILY = "Arial";
const DEFAULT_LINE_HEIGHT = 140;
const MIN_LENGTH_TO_JUSTIFY = 32; /* characters */
const LOCATION_DIVISOR = 10;
const PAGE_RESET_PROGRESS = -1;
/* eslint-disable-next-line no-unused-vars */
class ReaderClass extends AppCommon {
_flattened_toc: any;
loader: any;
csrf_token = "";
last_stored_cfi = "";
startup_finished = false;
open_last_read_when_displayed = true;
hyphenate = {} as HyphenateMap;
_prevent_lastread_timeout: any;
_prevent_lastread: any;
cacheVersion = BUILD_CACHE_VERSION;
cosmeticVersion = BUILD_VERSION;
book: ePub.Book;
/** @type {SwipeState} */
_swipeState = {
active: false,
startX: 0,
startY: 0,
startTime: 0,
direction: '',
};
_swipeConfig: SwipeConfig = {
minDistance: 50, // px — minimum horizontal travel to count as swipe
velocityThreshold: 0.3, // px/ms — minimum swipe speed
verticalDistanceThreshold: 80, // px — vertical movement before cancelling
};
constructor() {
super();
this.book = new ePub.Book();
this.loader = new ReaderLoader();
}
onTouchStart(evt: any) {
const touch = evt.touches[0] || evt.changedTouches[0];
this._swipeState = {
active: true,
startX: touch.clientX,
startY: touch.clientY,
startTime: Date.now(),
direction: evt.target.id == "right" ? 'left' : 'right',
};
}
onTouchEnd(evt: any) {
if (!this._swipeState.active) return;
const touch = evt.changedTouches[0] || evt.changedTouches[evt.changedTouches.length - 1];
const deltaX = touch.clientX - this._swipeState.startX;
const deltaTime = Date.now() - this._swipeState.startTime;
const velocity = deltaTime > 0 ? Math.abs(deltaX) / deltaTime : 0;
const isSwipe = Math.abs(deltaX) >= this._swipeConfig.minDistance && velocity >= this._swipeConfig.velocityThreshold;
const isLeft = this._swipeState.direction == "left";
const directionMatches = isLeft ? deltaX < 0 : deltaX > 0;
if (isSwipe && directionMatches) {
evt.preventDefault();
evt.stopPropagation();
if (isLeft) {
this.nextPage();
} else {
this.prevPage();
}
}
}
onTouchMove(evt: any) {
if (!this._swipeState.active) return;
const touch = evt.touches[0] || evt.changedTouches[0];
const deltaY = Math.abs(touch.clientY - this._swipeState.startY);
// Cancel if too much vertical movement
if (deltaY > this._swipeConfig.verticalDistanceThreshold) {
this._swipeState.active = false;
return;
}
}
async init() {
console.log('cache version, current:', this.cacheVersion, 'worker:', await this.getActiveCacheVersion());
this.csrf_token = Cookie.get('epube_csrf_token');
Http.setCsrfToken(this.csrf_token);
$(document).on("keyup", (e: any) => {
this.hotkeyHandler(e);
});
$(".close_book").on("click", () => {
this.close();
});
$("#left").on("mouseup", () => {
this.prevPage();
});
$(".search_input").on("change", () => {
this.search();
});
$(".prev_location_btn").on("click", (evt: any) => {
this.openPrevious(evt.target);
});
$("#right").on("mouseup", () => {
this.nextPage();
});
$("#left, #right").on("touchstart", (evt: any) => {
this.onTouchStart(evt);
});
$("#left, #right").on("touchmove", (evt: any) => {
this.onTouchMove(evt);
});
$("#left, #right").on("touchend", (evt: any) => {
this.onTouchEnd(evt);
});
const load_failed = await this.loader.init(this);
console.log('[init] load failed', load_failed);
if (!load_failed) {
this.initSecondStage();
} else {
this.applyTheme();
$(".loading-message").text('Resource loader failed to initialize.');
}
}
// another method, maybe use this: window.matchMedia("(pointer: coarse)").matches
// https://stackoverflow.com/questions/4817029/whats-an-optimal-or-efficient-way-to-detect-a-touch-screen-device-using-javas
isTouchDevice() {
return ('ontouchstart' in window) || (navigator.maxTouchPoints > 0);
}
/**
* @param offline Whether the app is in offline mode.
*/
async onOfflineModeChanged(offline: boolean) {
console.log('onOfflineModeChanged', offline);
if (!offline && this.book) {
console.log("we're online, storing lastread");
const currentCfi = this.book.rendition.currentLocation().start.cfi;
const currentPage = Math.round(this.book.locations.percentageFromCfi(currentCfi) * 100); // TODO wtf
try {
await Http.post("backend.php", { op: "storelastread", id: this.urlParam("id"), page: String(currentPage),
cfi: currentCfi, timestamp: String(new Date().getTime()) });
} catch (e) {
const err = /** @type {HttpError} */(e);
if ((err as any).status == 401) {
window.location.href = "index.html";
}
}
}
}
async initSecondStage() {
if (typeof EpubeApp != "undefined") {
EpubeApp.setPage("PAGE_READER");
} else {
$(window).on('online', () => {
this.onOfflineModeChanged(false);
});
$(window).on('offline', () => {
this.onOfflineModeChanged(true);
});
}
this.applyTheme();
const bookinfo = await localforage.getItem(this.cacheId());
if (!bookinfo) {
const bookId = this.urlParam("b");
console.log('requesting bookinfo for book', bookId)
try {
/** @type{HttpResponse} */
const resp = await Http.post("backend.php", {op: "list", ids: bookId });
/** @type{BookInfo} */
const info = resp.data['books'][0];
if (info.has_cover) {
/** @type {HttpBlobResponse} */
const cover = await Http.blob("backend.php", {op: "cover", id: bookId});
await localforage.setItem(this.cacheId('cover'), cover.blob);
}
await localforage.setItem(this.cacheId(), info);
console.log('bookinfo saved');
} catch (e) {
// @type {NetworkError}
const err = /** @type {HttpError} */(e);
console.error(err);
$(".loading-message").html(`Unable to load book info.
${this.escapeHtml((String)((err as any).responseText))}`);
return;
}
}
console.log('trying to load book...');
let book_data = await localforage.getItem(this.cacheId("book")) as Blob;
if (!book_data) {
console.log("local data not found, loading from network...");
$(".loading-message").html("Downloading book…");
/** @type {HttpBlobResponse} */
const book_resp = await Http.blob("backend.php", {op: "download", id: this.urlParam("id")});
if (book_resp.blob) {
book_data = book_resp.blob;
await localforage.setItem(this.cacheId('book'), book_data);
console.log('saved local data for book');
} else {
$(".loading-message").html(`Unable to download book: ${book_resp.status}`);
return;
}
}
const fileReader = new FileReader();
const _reader = this;
fileReader.onload = function() {
try {
_reader.openBookData(this.result);
} catch (e) {
console.error(e);
$(".loading-message").html("Unable to load book blob: " + e);
}
};
fileReader.onerror = (e) => {
console.log('filereader error', e);
$(".loading-message").html("Unable to open book.
" + this.escapeHtml(String(e)) + "");
};
fileReader.readAsArrayBuffer(book_data);
}
async openBookData(book_data: any) {
//this.book = new ePub.Book();
try {
await this.book.open(book_data);
} catch (e) {
console.error(e);
$(".loading-message").html(`Unable to open book.
${this.escapeHtml(e instanceof Error ? e.message : String(e))}`);
return;
}
await this.book.ready;
console.log('book is ready');
await this.showBookInfo(this.book);
await this.loadLocations(this.book);
const rendition = this.book.renderTo("reader", {
width: '100%',
height: '100%',
allowScriptedContent: false,
minSpreadWidth: 961
});
$(".location").on('click', async () => {
const current = Math.floor(rendition.currentLocation().start.location / LOCATION_DIVISOR);
const total = Math.floor(this.book.locations.length() / LOCATION_DIVISOR);
const page = prompt("Jump to location [1-" + total + "]", String(current));
if (page)
await rendition.display(this.book.locations._locations[parseInt(page) * LOCATION_DIVISOR]);
});
const enable_hyphens = await localforage.getItem("epube.enable-hyphens");
if (enable_hyphens) {
this.hyphenate.en = createHyphenator(hyphenationPatternsEnUs, { html: true });
this.hyphenate.ru = createHyphenator(hyphenationPatternsRu, { html: true });
}
this.initRenditionHooks(this.book, rendition);
this.initModals();
this.initToc(this.book);
// open first page at startup, lastread will open when it is rendered
this.blockLastReadUpdate();
await rendition.display();
console.log('startup finished');
this.startup_finished = true;
}
/**
* @param book The ePub book whose info should be displayed.
*/
async showBookInfo(book: ePub.Book) {
const bookinfo = await localforage.getItem(this.cacheId()) as BookInfo;
let title;
let author;
if (bookinfo) {
title = bookinfo.title;
author = bookinfo.author_sort;
} else {
const metadata = book.packaging.metadata;
title = metadata.title;
author = metadata.creator;
}
document.title = title + " – " + author + " – The Epube";
$(".title")
.text(title)
.attr("title", title + " – " + author);
if (typeof EpubeApp != "undefined") {
EpubeApp.setTitle(title);
EpubeApp.showActionBar(false);
}
}
/**
* @param book The ePub book whose locations should be loaded.
*/
async loadLocations(book: ePub.Book) {
let locations = await localforage.getItem(this.cacheId("locations")) as string[];
// legacy format is array of objects {cfi: ..., page: ...}
if (locations && typeof locations[0] == "string") {
console.log('loading local locations...');
try {
await book.locations.load(locations);
return;
} catch (e) {
console.warn(e);
}
}
if (this.isOnline()) {
console.log("downloading locations...");
$(".loading-message").html("Downloading locations…");
try {
/** @type {HttpTextResponse} */
const resp = await Http.text("backend.php", {op: "getpagination", id: this.urlParam("id")});
console.log("got locations from server");
// if this doesn't load, we'll generate locations and save them
try {
locations = JSON.parse(resp.text);
} catch (e) {
console.warn(e);
}
if (locations && typeof locations[0] == "string") {
console.log('saving locations locally...');
await localforage.setItem(this.cacheId("locations"), locations);
try {
book.locations.load(locations);
return;
} catch (e) {
console.warn(e);
}
}
} catch (e) {
console.warn('failed to fetch locations', e);
}
}
$(".loading-message").html("Preparing locations…");
let generate_queue_max = 0;
locations = await book.locations.generate(100, (queue: any) => {
if (!generate_queue_max)
generate_queue_max = queue.length();
// what if there's only one section or something and queue is already zero
if (generate_queue_max > 0) {
const queue_pct = Math.round((1 - queue.length() / generate_queue_max) * 100); // TODO un-wtf
$(".loading-message").html(`Preparing locations (${queue_pct}%)…`);
}
});
try {
await Http.post("backend.php", { op: "storepagination", id: this.urlParam("id"),
payload: JSON.stringify(locations), total: "100"});
} catch (e) {
console.warn('failed to store pagination', e);
}
await localforage.setItem(this.cacheId("locations"), locations);
}
/**
* @param book The ePub book instance.
* @param rendition The epub.js rendition to hook into.
*/
initRenditionHooks(book: ePub.Book, rendition: ePub.Rendition) {
console.log('initRenditionHooks');
book.spine.hooks.content.register((doc: any/*, section */) => {
this.cleanupEmbeddedStyles(doc);
});
rendition.hooks.content.register(async (contents: any) => {
contents.on("linkClicked", (href: any) => {
console.log('linkClicked', href);
this.blockLastReadUpdate();
if (href.indexOf("://") == -1) {
$(".prev_location_btn")
.attr("data-location-cfi", rendition.currentLocation().start.cfi)
.show();
window.requestAnimationFrame(() => {
this.showUI(true);
});
}
});
contents.on("selected", async (cfiRange: any) => {
if (this.isOnline()) {
const range = await book.getRange(cfiRange);
const selection = range.endContainer.data.substring(range.startOffset, range.endOffset);
console.log('selected', cfiRange, selection);
if (selection.match(/^[\w]+$/)) {
this.lookupWord(selection, () => {
if (typeof EpubeApp != "undefined")
EpubeApp.showActionBar(false);
contents.window.requestAnimationFrame(() => {
contents.window.getSelection().removeAllRanges();
});
});
}
}
});
// get our stuff from resource loader and inject into iframe content
const match = window.location.href.match(/^.*\//);
const base_url = match ? match[0] : window.location.href;
$(contents.document.head)
.append($("