2023-10-10 23:06:12 +00:00
|
|
|
const THEMES = ["light", "tan", "blue", "gray", "black"];
|
2023-11-29 11:15:44 +00:00
|
|
|
const THEME_FILE = "/assets/reader/themes.css";
|
2023-10-10 23:06:12 +00:00
|
|
|
|
2023-10-30 22:25:43 +00:00
|
|
|
/**
|
|
|
|
* Initial load handler. Gets called on DOMContentLoaded. Responsible for
|
|
|
|
* normalizing the documentData depending on type (REMOTE or LOCAL), and
|
|
|
|
* populating the metadata of the book into the DOM.
|
|
|
|
**/
|
2023-10-29 00:07:24 +00:00
|
|
|
async function initReader() {
|
|
|
|
let documentData;
|
|
|
|
let filePath;
|
|
|
|
|
2023-10-30 22:25:43 +00:00
|
|
|
// Get Document ID & Type
|
2023-10-29 00:07:24 +00:00
|
|
|
const urlParams = new URLSearchParams(window.location.hash.slice(1));
|
|
|
|
const documentID = urlParams.get("id");
|
2023-10-30 22:25:43 +00:00
|
|
|
const documentType = urlParams.get("type");
|
2023-10-29 00:07:24 +00:00
|
|
|
|
2023-10-30 22:25:43 +00:00
|
|
|
if (documentType == "REMOTE") {
|
2023-10-29 00:07:24 +00:00
|
|
|
// Get Server / Cached Document
|
2023-11-27 02:41:17 +00:00
|
|
|
let progressResp = await fetch("/reader/progress/" + documentID);
|
2023-10-29 00:07:24 +00:00
|
|
|
documentData = await progressResp.json();
|
|
|
|
|
2023-10-30 22:25:43 +00:00
|
|
|
// Update With Local Cache
|
2023-10-29 00:07:24 +00:00
|
|
|
let localCache = await IDB.get("PROGRESS-" + documentID);
|
|
|
|
if (localCache) {
|
|
|
|
documentData.progress = localCache.progress;
|
|
|
|
documentData.percentage = Math.round(localCache.percentage * 10000) / 100;
|
|
|
|
}
|
|
|
|
|
|
|
|
filePath = "/documents/" + documentID + "/file";
|
2023-10-30 22:25:43 +00:00
|
|
|
} else if (documentType == "LOCAL") {
|
|
|
|
documentData = await IDB.get("FILE-METADATA-" + documentID);
|
|
|
|
let fileBlob = await IDB.get("FILE-" + documentID);
|
|
|
|
filePath = URL.createObjectURL(fileBlob);
|
2023-10-29 00:07:24 +00:00
|
|
|
} else {
|
2023-10-30 22:25:43 +00:00
|
|
|
throw new Error("Invalid Type");
|
2023-10-29 00:07:24 +00:00
|
|
|
}
|
|
|
|
|
2023-10-30 22:25:43 +00:00
|
|
|
// Update Type
|
|
|
|
documentData.type = documentType;
|
|
|
|
|
|
|
|
// Populate Metadata & Create Reader
|
2023-10-29 00:07:24 +00:00
|
|
|
window.currentReader = new EBookReader(filePath, documentData);
|
2023-10-30 22:25:43 +00:00
|
|
|
populateMetadata(documentData);
|
2023-10-29 00:07:24 +00:00
|
|
|
}
|
|
|
|
|
2023-10-30 22:25:43 +00:00
|
|
|
/**
|
|
|
|
* Populates metadata into the DOM. Specifically for the top "drop" down.
|
|
|
|
**/
|
2023-10-29 00:07:24 +00:00
|
|
|
function populateMetadata(data) {
|
2023-10-30 22:25:43 +00:00
|
|
|
let documentLocation =
|
2023-10-30 23:23:38 +00:00
|
|
|
data.type == "LOCAL" ? "/local" : "/documents/" + data.id;
|
2023-10-29 00:07:24 +00:00
|
|
|
|
2023-10-30 22:25:43 +00:00
|
|
|
let documentCoverLocation =
|
|
|
|
data.type == "LOCAL"
|
|
|
|
? "/assets/images/no-cover.jpg"
|
|
|
|
: "/documents/" + data.id + "/cover";
|
2023-10-29 00:07:24 +00:00
|
|
|
|
|
|
|
let [backEl, coverEl] = document.querySelectorAll("a");
|
|
|
|
backEl.setAttribute("href", documentLocation);
|
|
|
|
coverEl.setAttribute("href", documentLocation);
|
|
|
|
coverEl.firstElementChild.setAttribute("src", documentCoverLocation);
|
|
|
|
|
|
|
|
let [titleEl, authorEl] = document.querySelectorAll("#top-bar p + p");
|
|
|
|
titleEl.innerText = data.title;
|
|
|
|
authorEl.innerText = data.author;
|
|
|
|
}
|
|
|
|
|
2023-10-30 22:25:43 +00:00
|
|
|
/**
|
|
|
|
* This is the main reader class. All functionality is wrapped in this class.
|
|
|
|
* Responsible for handling gesture / clicks, flushing progress & activity,
|
|
|
|
* storing and processing themes, etc.
|
|
|
|
**/
|
2023-10-10 23:06:12 +00:00
|
|
|
class EBookReader {
|
|
|
|
bookState = {
|
|
|
|
pages: 0,
|
|
|
|
percentage: 0,
|
|
|
|
progress: "",
|
2023-10-16 03:23:58 +00:00
|
|
|
progressElement: null,
|
2023-10-12 23:14:29 +00:00
|
|
|
readActivity: [],
|
2023-10-10 23:06:12 +00:00
|
|
|
words: 0,
|
|
|
|
};
|
|
|
|
|
|
|
|
constructor(file, bookState) {
|
|
|
|
// Set Variables
|
|
|
|
Object.assign(this.bookState, bookState);
|
|
|
|
|
2023-10-16 03:23:58 +00:00
|
|
|
// Load Settings
|
|
|
|
this.loadSettings();
|
|
|
|
|
2023-10-10 23:06:12 +00:00
|
|
|
// Load EPUB
|
|
|
|
this.book = ePub(file, { openAs: "epub" });
|
|
|
|
|
|
|
|
// Render
|
|
|
|
this.rendition = this.book.renderTo("viewer", {
|
|
|
|
manager: "default",
|
|
|
|
flow: "paginated",
|
|
|
|
width: "100%",
|
|
|
|
height: "100%",
|
|
|
|
});
|
|
|
|
|
|
|
|
// Setup Reader
|
|
|
|
this.book.ready.then(this.setupReader.bind(this));
|
|
|
|
|
|
|
|
// Initialize
|
2023-10-12 23:14:29 +00:00
|
|
|
this.initDevice();
|
2023-10-14 01:06:49 +00:00
|
|
|
this.initWakeLock();
|
2023-10-10 23:06:12 +00:00
|
|
|
this.initThemes();
|
|
|
|
this.initRenditionListeners();
|
|
|
|
this.initDocumentListeners();
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2023-10-12 23:14:29 +00:00
|
|
|
* Load progress and generate locations
|
2023-10-10 23:06:12 +00:00
|
|
|
**/
|
|
|
|
async setupReader() {
|
2023-11-04 03:43:08 +00:00
|
|
|
// Get Word Count
|
|
|
|
this.bookState.words = await this.countWords();
|
2023-10-27 00:20:58 +00:00
|
|
|
|
2023-10-12 23:14:29 +00:00
|
|
|
// Load Progress
|
2023-10-16 03:23:58 +00:00
|
|
|
let { cfi } = await this.getCFIFromXPath(this.bookState.progress);
|
2023-10-10 23:06:12 +00:00
|
|
|
|
2023-10-25 23:52:01 +00:00
|
|
|
// Update Position
|
|
|
|
await this.setPosition(cfi);
|
2023-10-16 03:23:58 +00:00
|
|
|
|
|
|
|
// Highlight Element - DOM Has Element
|
|
|
|
let { element } = await this.getCFIFromXPath(this.bookState.progress);
|
2023-10-24 22:30:01 +00:00
|
|
|
|
2023-11-04 04:04:31 +00:00
|
|
|
// Set Progress Element & Highlight
|
2023-10-16 03:23:58 +00:00
|
|
|
this.bookState.progressElement = element;
|
|
|
|
this.highlightPositionMarker();
|
2023-11-04 04:04:31 +00:00
|
|
|
|
|
|
|
// Update Stats & Page Start
|
|
|
|
let stats = await this.getBookStats();
|
|
|
|
this.updateBookStatElements(stats);
|
|
|
|
this.bookState.pageStart = Date.now();
|
2023-10-10 23:06:12 +00:00
|
|
|
}
|
|
|
|
|
2023-10-12 23:14:29 +00:00
|
|
|
initDevice() {
|
|
|
|
function randomID() {
|
|
|
|
return "00000000000000000000000000000000".replace(/[018]/g, (c) =>
|
|
|
|
(c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4))))
|
|
|
|
.toString(16)
|
|
|
|
.toUpperCase()
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2023-11-27 02:41:17 +00:00
|
|
|
// Device Already Set
|
|
|
|
if (this.readerSettings.deviceID) return;
|
2023-10-12 23:14:29 +00:00
|
|
|
|
2023-11-27 02:41:17 +00:00
|
|
|
// Get Elements
|
|
|
|
let devicePopup = document.querySelector("#device-selector");
|
|
|
|
let devSelector = devicePopup.querySelector("select");
|
|
|
|
let devInput = devicePopup.querySelector("input");
|
|
|
|
let [assumeButton, createButton] = devicePopup.querySelectorAll("button");
|
2023-10-12 23:14:29 +00:00
|
|
|
|
2023-11-27 02:41:17 +00:00
|
|
|
// Set Visible
|
|
|
|
devicePopup.classList.remove("hidden");
|
|
|
|
|
|
|
|
// Add Devices
|
|
|
|
fetch("/reader/devices").then(async (r) => {
|
|
|
|
let data = await r.json();
|
|
|
|
|
|
|
|
data.forEach((item) => {
|
|
|
|
let optionEl = document.createElement("option");
|
|
|
|
optionEl.value = item.id;
|
|
|
|
optionEl.textContent = item.device_name;
|
|
|
|
devSelector.appendChild(optionEl);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
assumeButton.addEventListener("click", () => {
|
|
|
|
let deviceID = devSelector.value;
|
|
|
|
|
|
|
|
if (deviceID == "") {
|
|
|
|
// TODO - Error Message
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
let selectedOption = devSelector.children[devSelector.selectedIndex];
|
|
|
|
let deviceName = selectedOption.textContent;
|
|
|
|
|
|
|
|
this.readerSettings.deviceID = deviceID;
|
|
|
|
this.readerSettings.deviceName = deviceName;
|
|
|
|
this.saveSettings();
|
|
|
|
devicePopup.classList.add("hidden");
|
|
|
|
});
|
|
|
|
|
|
|
|
createButton.addEventListener("click", () => {
|
|
|
|
let deviceName = devInput.value.trim();
|
|
|
|
|
|
|
|
if (deviceName == "") {
|
|
|
|
// TODO - Error Message
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.readerSettings.deviceID = randomID();
|
|
|
|
this.readerSettings.deviceName = deviceName;
|
|
|
|
this.saveSettings();
|
|
|
|
devicePopup.classList.add("hidden");
|
|
|
|
});
|
2023-10-12 23:14:29 +00:00
|
|
|
}
|
|
|
|
|
2023-10-14 01:06:49 +00:00
|
|
|
/**
|
2023-10-19 23:03:15 +00:00
|
|
|
* This is a hack and maintains a wake lock. It will automatically disable
|
|
|
|
* if there's been no input for 10 minutes.
|
2023-10-14 01:06:49 +00:00
|
|
|
*
|
2023-10-19 23:03:15 +00:00
|
|
|
* Ideally we use "navigator.wakeLock", but there's a bug in Safari (as of
|
|
|
|
* iOS 17.03) when intalled as a PWA that doesn't allow it to work [0]
|
2023-10-14 01:06:49 +00:00
|
|
|
*
|
2023-10-19 23:03:15 +00:00
|
|
|
* Unfortunate downside is iOS indicates that "No Sleep" is playing in both
|
|
|
|
* the Control Center and Lock Screen. iOS also stops any background sound.
|
2023-10-14 01:06:49 +00:00
|
|
|
*
|
|
|
|
* [0] https://progressier.com/pwa-capabilities/screen-wake-lock
|
|
|
|
**/
|
|
|
|
initWakeLock() {
|
|
|
|
// Setup Wake Lock (Adding to DOM Necessary - iOS 17.03)
|
|
|
|
let timeoutID = null;
|
|
|
|
let wakeLock = new NoSleep();
|
|
|
|
|
|
|
|
// Override Standalone (Modified No-Sleep)
|
|
|
|
if (window.navigator.standalone) {
|
|
|
|
Object.assign(wakeLock.noSleepVideo.style, {
|
|
|
|
position: "absolute",
|
|
|
|
top: "-100%",
|
|
|
|
});
|
|
|
|
document.body.append(wakeLock.noSleepVideo);
|
|
|
|
}
|
|
|
|
|
|
|
|
// User Action Required (Manual bubble up from iFrame)
|
|
|
|
document.addEventListener("wakelock", function () {
|
|
|
|
// 10 Minute Timeout
|
|
|
|
if (timeoutID) clearTimeout(timeoutID);
|
|
|
|
timeoutID = setTimeout(wakeLock.disable, 1000 * 60 * 10);
|
|
|
|
|
|
|
|
// Enable
|
|
|
|
wakeLock.enable();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-10-10 23:06:12 +00:00
|
|
|
/**
|
|
|
|
* Register all themes with reader
|
|
|
|
**/
|
|
|
|
initThemes() {
|
|
|
|
// Register Themes
|
|
|
|
THEMES.forEach((theme) =>
|
|
|
|
this.rendition.themes.register(theme, THEME_FILE)
|
|
|
|
);
|
2023-10-14 01:06:49 +00:00
|
|
|
|
|
|
|
let themeLinkEl = document.createElement("link");
|
|
|
|
themeLinkEl.setAttribute("id", "themes");
|
|
|
|
themeLinkEl.setAttribute("rel", "stylesheet");
|
|
|
|
themeLinkEl.setAttribute("href", THEME_FILE);
|
|
|
|
document.head.append(themeLinkEl);
|
2023-10-25 23:52:01 +00:00
|
|
|
|
|
|
|
// Set Theme Style
|
|
|
|
this.rendition.themes.default({
|
|
|
|
"*": {
|
|
|
|
"font-size": "var(--editor-font-size) !important",
|
|
|
|
"font-family": "var(--editor-font-family) !important",
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
// Restore Theme Hook
|
|
|
|
this.rendition.hooks.content.register(
|
|
|
|
function () {
|
|
|
|
// Restore Theme
|
|
|
|
this.setTheme();
|
|
|
|
|
2023-11-29 11:15:44 +00:00
|
|
|
// Set Fonts
|
2023-10-25 23:52:01 +00:00
|
|
|
this.rendition.getContents().forEach((c) => {
|
2023-11-29 11:15:44 +00:00
|
|
|
let el = c.document.head.appendChild(
|
|
|
|
c.document.createElement("link")
|
|
|
|
);
|
|
|
|
el.setAttribute("rel", "stylesheet");
|
|
|
|
el.setAttribute("href", "/assets/reader/fonts.css");
|
2023-10-25 23:52:01 +00:00
|
|
|
});
|
|
|
|
}.bind(this)
|
|
|
|
);
|
2023-10-12 23:14:29 +00:00
|
|
|
}
|
2023-10-10 23:06:12 +00:00
|
|
|
|
2023-10-12 23:14:29 +00:00
|
|
|
/**
|
|
|
|
* Set theme & meta theme color
|
|
|
|
**/
|
2023-10-16 03:23:58 +00:00
|
|
|
setTheme(newTheme) {
|
2023-10-25 23:52:01 +00:00
|
|
|
// Assert Theme Object
|
|
|
|
this.readerSettings.theme =
|
|
|
|
typeof this.readerSettings.theme == "object"
|
|
|
|
? this.readerSettings.theme
|
|
|
|
: {};
|
|
|
|
|
|
|
|
// Assign Values
|
|
|
|
Object.assign(this.readerSettings.theme, newTheme);
|
|
|
|
|
|
|
|
// Get Desired Theme (Defaults)
|
|
|
|
let colorScheme = this.readerSettings.theme.colorScheme || "tan";
|
|
|
|
let fontFamily = this.readerSettings.theme.fontFamily || "serif";
|
|
|
|
let fontSize = this.readerSettings.theme.fontSize || 1;
|
2023-10-14 01:06:49 +00:00
|
|
|
|
|
|
|
// Set Reader Theme
|
2023-10-25 23:52:01 +00:00
|
|
|
this.rendition.themes.select(colorScheme);
|
2023-10-14 01:06:49 +00:00
|
|
|
|
|
|
|
// Get Reader Theme
|
2023-10-12 23:14:29 +00:00
|
|
|
let themeColorEl = document.querySelector("[name='theme-color']");
|
2023-10-14 01:06:49 +00:00
|
|
|
let themeStyleSheet = document.querySelector("#themes").sheet;
|
|
|
|
let themeStyleRule = Array.from(themeStyleSheet.cssRules).find(
|
2023-10-25 23:52:01 +00:00
|
|
|
(item) => item.selectorText == "." + colorScheme
|
2023-10-14 01:06:49 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
// Match Reader Theme
|
|
|
|
if (!themeStyleRule) return;
|
|
|
|
let backgroundColor = themeStyleRule.style.backgroundColor;
|
2023-10-12 23:14:29 +00:00
|
|
|
themeColorEl.setAttribute("content", backgroundColor);
|
|
|
|
document.body.style.backgroundColor = backgroundColor;
|
2023-10-16 03:23:58 +00:00
|
|
|
|
2023-10-25 23:52:01 +00:00
|
|
|
// Set Font Family & Highlight Style
|
2023-10-16 03:23:58 +00:00
|
|
|
this.rendition.getContents().forEach((item) => {
|
2023-10-25 23:52:01 +00:00
|
|
|
// Set Font Family
|
|
|
|
item.document.documentElement.style.setProperty(
|
|
|
|
"--editor-font-family",
|
|
|
|
fontFamily
|
|
|
|
);
|
|
|
|
|
|
|
|
// Set Font Size
|
|
|
|
item.document.documentElement.style.setProperty(
|
|
|
|
"--editor-font-size",
|
|
|
|
fontSize + "em"
|
|
|
|
);
|
|
|
|
|
|
|
|
// Set Highlight Style
|
2023-10-16 03:23:58 +00:00
|
|
|
item.document.querySelectorAll(".highlight").forEach((el) => {
|
|
|
|
Object.assign(el.style, {
|
|
|
|
background: backgroundColor,
|
|
|
|
});
|
|
|
|
});
|
|
|
|
});
|
2023-10-25 23:52:01 +00:00
|
|
|
|
|
|
|
// Save Settings (Theme)
|
|
|
|
this.saveSettings();
|
2023-10-16 03:23:58 +00:00
|
|
|
}
|
|
|
|
|
2023-10-25 23:52:01 +00:00
|
|
|
/**
|
|
|
|
* Takes existing progressElement and applies the highlight style to it.
|
|
|
|
* This is nice when font size or font family changes as it can cause
|
|
|
|
* the position to move.
|
|
|
|
**/
|
2023-10-16 03:23:58 +00:00
|
|
|
highlightPositionMarker() {
|
|
|
|
if (!this.bookState.progressElement) return;
|
|
|
|
|
|
|
|
// Remove Existing
|
|
|
|
this.rendition.getContents().forEach((item) => {
|
|
|
|
item.document.querySelectorAll(".highlight").forEach((el) => {
|
|
|
|
el.removeAttribute("style");
|
|
|
|
el.classList.remove("highlight");
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
// Compute Style
|
|
|
|
let backgroundColor = getComputedStyle(
|
|
|
|
this.bookState.progressElement.ownerDocument.body
|
|
|
|
).backgroundColor;
|
|
|
|
|
|
|
|
// Set Style
|
|
|
|
Object.assign(this.bookState.progressElement.style, {
|
|
|
|
background: backgroundColor,
|
|
|
|
filter: "invert(0.2)",
|
|
|
|
});
|
|
|
|
|
|
|
|
// Update Class
|
|
|
|
this.bookState.progressElement.classList.add("highlight");
|
2023-10-10 23:06:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Rendition hooks
|
|
|
|
**/
|
|
|
|
initRenditionListeners() {
|
|
|
|
/**
|
|
|
|
* Initiate the debounce when the given function returns true.
|
|
|
|
* Don't run it again until the timeout lapses.
|
|
|
|
**/
|
|
|
|
function debounceFunc(fn, d) {
|
|
|
|
let timer;
|
|
|
|
let bouncing = false;
|
|
|
|
return function () {
|
|
|
|
let context = this;
|
|
|
|
let args = arguments;
|
|
|
|
|
|
|
|
if (bouncing) return;
|
|
|
|
if (!fn.apply(context, args)) return;
|
|
|
|
|
|
|
|
bouncing = true;
|
|
|
|
clearTimeout(timer);
|
|
|
|
timer = setTimeout(() => {
|
|
|
|
bouncing = false;
|
|
|
|
}, d);
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
// Elements
|
|
|
|
let topBar = document.querySelector("#top-bar");
|
|
|
|
let bottomBar = document.querySelector("#bottom-bar");
|
|
|
|
|
2023-10-16 03:23:58 +00:00
|
|
|
// Local Functions
|
|
|
|
let getCFIFromXPath = this.getCFIFromXPath.bind(this);
|
2023-10-25 23:52:01 +00:00
|
|
|
let setPosition = this.setPosition.bind(this);
|
2023-10-10 23:06:12 +00:00
|
|
|
let nextPage = this.nextPage.bind(this);
|
|
|
|
let prevPage = this.prevPage.bind(this);
|
|
|
|
let saveSettings = this.saveSettings.bind(this);
|
|
|
|
|
2023-10-16 03:23:58 +00:00
|
|
|
// Local Vars
|
2023-10-10 23:06:12 +00:00
|
|
|
let readerSettings = this.readerSettings;
|
2023-10-16 03:23:58 +00:00
|
|
|
let bookState = this.bookState;
|
|
|
|
|
2023-10-10 23:06:12 +00:00
|
|
|
this.rendition.hooks.render.register(function (doc, data) {
|
|
|
|
let renderDoc = doc.document;
|
|
|
|
|
2023-10-14 01:06:49 +00:00
|
|
|
// ------------------------------------------------ //
|
|
|
|
// ---------------- Wake Lock Hack ---------------- //
|
|
|
|
// ------------------------------------------------ //
|
|
|
|
let wakeLockListener = function () {
|
|
|
|
doc.window.parent.document.dispatchEvent(new CustomEvent("wakelock"));
|
|
|
|
};
|
|
|
|
renderDoc.addEventListener("click", wakeLockListener);
|
|
|
|
renderDoc.addEventListener("gesturechange", wakeLockListener);
|
|
|
|
renderDoc.addEventListener("touchstart", wakeLockListener);
|
|
|
|
|
2023-10-10 23:06:12 +00:00
|
|
|
// ------------------------------------------------ //
|
|
|
|
// --------------- Swipe Pagination --------------- //
|
|
|
|
// ------------------------------------------------ //
|
|
|
|
let touchStartX,
|
|
|
|
touchStartY,
|
|
|
|
touchEndX,
|
|
|
|
touchEndY = undefined;
|
|
|
|
|
|
|
|
renderDoc.addEventListener(
|
|
|
|
"touchstart",
|
|
|
|
function (event) {
|
|
|
|
touchStartX = event.changedTouches[0].screenX;
|
|
|
|
touchStartY = event.changedTouches[0].screenY;
|
|
|
|
},
|
|
|
|
false
|
|
|
|
);
|
|
|
|
|
|
|
|
renderDoc.addEventListener(
|
|
|
|
"touchend",
|
|
|
|
function (event) {
|
|
|
|
touchEndX = event.changedTouches[0].screenX;
|
|
|
|
touchEndY = event.changedTouches[0].screenY;
|
2023-10-25 23:52:01 +00:00
|
|
|
handleGesture(event);
|
2023-10-10 23:06:12 +00:00
|
|
|
},
|
|
|
|
false
|
|
|
|
);
|
|
|
|
|
|
|
|
function handleGesture(event) {
|
|
|
|
let drasticity = 75;
|
|
|
|
|
|
|
|
// Swipe Down
|
|
|
|
if (touchEndY - drasticity > touchStartY) {
|
|
|
|
return handleSwipeDown();
|
|
|
|
}
|
|
|
|
|
|
|
|
// Swipe Up
|
|
|
|
if (touchEndY + drasticity < touchStartY) {
|
|
|
|
// Prioritize Down & Up Swipes
|
|
|
|
return handleSwipeUp();
|
|
|
|
}
|
|
|
|
|
|
|
|
// Swipe Left
|
|
|
|
if (touchEndX + drasticity < touchStartX) {
|
|
|
|
nextPage();
|
|
|
|
}
|
|
|
|
|
|
|
|
// Swipe Right
|
|
|
|
if (touchEndX - drasticity > touchStartX) {
|
|
|
|
prevPage();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// ------------------------------------------------ //
|
|
|
|
// --------------- Bottom & Top Bar --------------- //
|
|
|
|
// ------------------------------------------------ //
|
2023-10-29 00:07:24 +00:00
|
|
|
renderDoc.addEventListener(
|
|
|
|
"click",
|
|
|
|
function (event) {
|
|
|
|
// Get Window Dimensions
|
|
|
|
let windowWidth = window.innerWidth;
|
|
|
|
let windowHeight = window.innerHeight;
|
|
|
|
|
|
|
|
// Calculate X & Y Hot Zones
|
|
|
|
let barPixels = windowHeight * 0.2;
|
|
|
|
let pagePixels = windowWidth * 0.2;
|
|
|
|
|
|
|
|
// Calculate Top & Bottom Thresholds
|
|
|
|
let top = barPixels;
|
|
|
|
let bottom = window.innerHeight - top;
|
|
|
|
|
|
|
|
// Calculate Left & Right Thresholds
|
|
|
|
let left = pagePixels;
|
|
|
|
let right = windowWidth - left;
|
|
|
|
|
|
|
|
// Calculate Relative Coords
|
|
|
|
let leftOffset = this.views().container.scrollLeft;
|
|
|
|
let yCoord = event.clientY;
|
|
|
|
let xCoord = event.clientX - leftOffset;
|
|
|
|
|
|
|
|
// Handle Event
|
|
|
|
if (yCoord < top) handleSwipeDown();
|
|
|
|
else if (yCoord > bottom) handleSwipeUp();
|
|
|
|
else if (xCoord < left) prevPage();
|
|
|
|
else if (xCoord > right) nextPage();
|
|
|
|
else {
|
|
|
|
bottomBar.classList.remove("bottom-0");
|
|
|
|
topBar.classList.remove("top-0");
|
|
|
|
}
|
|
|
|
}.bind(this)
|
|
|
|
);
|
2023-10-10 23:06:12 +00:00
|
|
|
|
|
|
|
renderDoc.addEventListener(
|
|
|
|
"wheel",
|
|
|
|
debounceFunc((event) => {
|
|
|
|
if (event.deltaY > 25) {
|
|
|
|
handleSwipeUp();
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
if (event.deltaY < -25) {
|
|
|
|
handleSwipeDown();
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}, 400)
|
|
|
|
);
|
|
|
|
|
|
|
|
function handleSwipeDown() {
|
|
|
|
if (bottomBar.classList.contains("bottom-0"))
|
|
|
|
bottomBar.classList.remove("bottom-0");
|
|
|
|
else topBar.classList.add("top-0");
|
|
|
|
}
|
|
|
|
|
|
|
|
function handleSwipeUp() {
|
|
|
|
if (topBar.classList.contains("top-0"))
|
|
|
|
topBar.classList.remove("top-0");
|
|
|
|
else bottomBar.classList.add("bottom-0");
|
|
|
|
}
|
|
|
|
|
|
|
|
// ------------------------------------------------ //
|
|
|
|
// -------------- Keyboard Shortcuts -------------- //
|
|
|
|
// ------------------------------------------------ //
|
|
|
|
renderDoc.addEventListener(
|
|
|
|
"keyup",
|
|
|
|
function (e) {
|
|
|
|
// Left Key (Previous Page)
|
|
|
|
if ((e.keyCode || e.which) == 37) {
|
|
|
|
prevPage();
|
|
|
|
}
|
|
|
|
|
|
|
|
// Right Key (Next Page)
|
|
|
|
if ((e.keyCode || e.which) == 39) {
|
|
|
|
nextPage();
|
|
|
|
}
|
|
|
|
|
|
|
|
// "t" Key (Theme Cycle)
|
|
|
|
if ((e.keyCode || e.which) == 84) {
|
2023-10-25 23:52:01 +00:00
|
|
|
let currentThemeIdx = THEMES.indexOf(
|
|
|
|
readerSettings.theme.colorScheme
|
|
|
|
);
|
|
|
|
let colorScheme =
|
|
|
|
THEMES.length == currentThemeIdx + 1
|
|
|
|
? THEMES[0]
|
|
|
|
: THEMES[currentThemeIdx + 1];
|
|
|
|
setTheme({ colorScheme });
|
2023-10-10 23:06:12 +00:00
|
|
|
}
|
|
|
|
},
|
|
|
|
false
|
|
|
|
);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Document listeners
|
|
|
|
**/
|
|
|
|
initDocumentListeners() {
|
|
|
|
// Elements
|
|
|
|
let topBar = document.querySelector("#top-bar");
|
|
|
|
|
|
|
|
let nextPage = this.nextPage.bind(this);
|
|
|
|
let prevPage = this.prevPage.bind(this);
|
|
|
|
|
2023-10-25 23:52:01 +00:00
|
|
|
// Keyboard Shortcuts
|
2023-10-10 23:06:12 +00:00
|
|
|
document.addEventListener(
|
|
|
|
"keyup",
|
|
|
|
function (e) {
|
|
|
|
// Left Key (Previous Page)
|
|
|
|
if ((e.keyCode || e.which) == 37) {
|
|
|
|
prevPage();
|
|
|
|
}
|
|
|
|
|
|
|
|
// Right Key (Next Page)
|
|
|
|
if ((e.keyCode || e.which) == 39) {
|
|
|
|
nextPage();
|
|
|
|
}
|
|
|
|
|
|
|
|
// "t" Key (Theme Cycle)
|
|
|
|
if ((e.keyCode || e.which) == 84) {
|
2023-10-25 23:52:01 +00:00
|
|
|
let currentThemeIdx = THEMES.indexOf(
|
|
|
|
this.readerSettings.theme.colorScheme
|
|
|
|
);
|
|
|
|
let colorScheme =
|
2023-10-14 01:06:49 +00:00
|
|
|
THEMES.length == currentThemeIdx + 1
|
|
|
|
? THEMES[0]
|
|
|
|
: THEMES[currentThemeIdx + 1];
|
2023-10-25 23:52:01 +00:00
|
|
|
this.setTheme({ colorScheme });
|
2023-10-10 23:06:12 +00:00
|
|
|
}
|
2023-10-12 23:14:29 +00:00
|
|
|
}.bind(this),
|
2023-10-10 23:06:12 +00:00
|
|
|
false
|
|
|
|
);
|
|
|
|
|
2023-10-25 23:52:01 +00:00
|
|
|
// Color Scheme Switcher
|
|
|
|
document.querySelectorAll(".color-scheme").forEach(
|
2023-10-10 23:06:12 +00:00
|
|
|
function (item) {
|
|
|
|
item.addEventListener(
|
|
|
|
"click",
|
|
|
|
function (event) {
|
2023-10-25 23:52:01 +00:00
|
|
|
let colorScheme = event.target.innerText;
|
|
|
|
this.setTheme({ colorScheme });
|
|
|
|
}.bind(this)
|
|
|
|
);
|
|
|
|
}.bind(this)
|
|
|
|
);
|
|
|
|
|
|
|
|
// Font Switcher
|
|
|
|
document.querySelectorAll(".font-family").forEach(
|
|
|
|
function (item) {
|
|
|
|
item.addEventListener(
|
|
|
|
"click",
|
|
|
|
async function (event) {
|
|
|
|
let { cfi } = await this.getCFIFromXPath(this.bookState.progress);
|
|
|
|
|
|
|
|
let fontFamily = event.target.innerText;
|
|
|
|
this.setTheme({ fontFamily });
|
|
|
|
|
|
|
|
this.setPosition(cfi);
|
2023-10-10 23:06:12 +00:00
|
|
|
}.bind(this)
|
|
|
|
);
|
|
|
|
}.bind(this)
|
|
|
|
);
|
|
|
|
|
2023-10-25 23:52:01 +00:00
|
|
|
// Font Size
|
|
|
|
document.querySelectorAll(".font-size").forEach(
|
|
|
|
function (item) {
|
|
|
|
item.addEventListener(
|
|
|
|
"click",
|
|
|
|
async function (event) {
|
|
|
|
// Get Initial CFI
|
|
|
|
let { cfi } = await this.getCFIFromXPath(this.bookState.progress);
|
|
|
|
|
|
|
|
// Modify Size
|
|
|
|
let currentSize = this.readerSettings.theme.fontSize || 1;
|
|
|
|
let direction = event.target.innerText;
|
|
|
|
if (direction == "-") {
|
|
|
|
this.setTheme({ fontSize: currentSize * 0.99 });
|
|
|
|
} else if (direction == "+") {
|
|
|
|
this.setTheme({ fontSize: currentSize * 1.01 });
|
|
|
|
}
|
|
|
|
|
|
|
|
// Restore CFI
|
|
|
|
this.setPosition(cfi);
|
|
|
|
}.bind(this)
|
|
|
|
);
|
|
|
|
}.bind(this)
|
|
|
|
);
|
|
|
|
|
|
|
|
// Close Top Bar
|
2023-10-10 23:06:12 +00:00
|
|
|
document.querySelector(".close-top-bar").addEventListener("click", () => {
|
|
|
|
topBar.classList.remove("top-0");
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Progresses to the next page & monitors reading activity
|
|
|
|
**/
|
|
|
|
async nextPage() {
|
2023-10-29 00:07:24 +00:00
|
|
|
// Create Activity
|
|
|
|
await this.createActivity();
|
2023-10-10 23:06:12 +00:00
|
|
|
|
|
|
|
// Render Next Page
|
|
|
|
await this.rendition.next();
|
|
|
|
|
|
|
|
// Reset Read Timer
|
|
|
|
this.bookState.pageStart = Date.now();
|
|
|
|
|
|
|
|
// Update Stats
|
2023-11-04 03:43:08 +00:00
|
|
|
let stats = await this.getBookStats();
|
2023-10-29 00:07:24 +00:00
|
|
|
this.updateBookStatElements(stats);
|
2023-10-10 23:06:12 +00:00
|
|
|
|
2023-10-29 00:07:24 +00:00
|
|
|
// Create Progress
|
|
|
|
this.createProgress();
|
2023-10-10 23:06:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Progresses to the previous page & monitors reading activity
|
|
|
|
**/
|
|
|
|
async prevPage() {
|
|
|
|
// Render Previous Page
|
|
|
|
await this.rendition.prev();
|
|
|
|
|
|
|
|
// Reset Read Timer
|
|
|
|
this.bookState.pageStart = Date.now();
|
|
|
|
|
|
|
|
// Update Stats
|
2023-11-04 03:43:08 +00:00
|
|
|
let stats = await this.getBookStats();
|
2023-10-29 00:07:24 +00:00
|
|
|
this.updateBookStatElements(stats);
|
2023-10-10 23:06:12 +00:00
|
|
|
|
2023-10-29 00:07:24 +00:00
|
|
|
// Create Progress
|
|
|
|
this.createProgress();
|
2023-10-12 23:14:29 +00:00
|
|
|
}
|
|
|
|
|
2023-10-25 23:52:01 +00:00
|
|
|
/**
|
|
|
|
* Display @ CFI x 3 (Hack)
|
|
|
|
*
|
|
|
|
* This is absurd. Only way to get it to consistently show the correct
|
|
|
|
* page is to execute this three times. I tried the font hook,
|
|
|
|
* rendition hook, relocated hook, etc. No reliable way outside of
|
|
|
|
* running this three times.
|
|
|
|
*
|
|
|
|
* Likely Bug: https://github.com/futurepress/epub.js/issues/1194
|
|
|
|
**/
|
|
|
|
async setPosition(cfi) {
|
|
|
|
await this.rendition.display(cfi);
|
|
|
|
await this.rendition.display(cfi);
|
|
|
|
await this.rendition.display(cfi);
|
|
|
|
|
|
|
|
this.highlightPositionMarker();
|
|
|
|
}
|
|
|
|
|
2023-10-29 00:07:24 +00:00
|
|
|
async createActivity() {
|
|
|
|
// WPM MAX & MIN
|
2023-10-12 23:14:29 +00:00
|
|
|
const WPM_MAX = 2000;
|
|
|
|
const WPM_MIN = 100;
|
|
|
|
|
2023-10-29 00:07:24 +00:00
|
|
|
// Get Elapsed Time
|
|
|
|
let pageStart = this.bookState.pageStart;
|
|
|
|
let elapsedTime = Date.now() - pageStart;
|
2023-10-12 23:14:29 +00:00
|
|
|
|
2023-10-29 00:07:24 +00:00
|
|
|
// Update Current Word
|
|
|
|
let pageWords = await this.getVisibleWordCount();
|
2023-11-04 03:43:08 +00:00
|
|
|
let currentWord = await this.getBookWordPosition();
|
2023-10-29 00:07:24 +00:00
|
|
|
let percentRead = pageWords / this.bookState.words;
|
2023-10-12 23:14:29 +00:00
|
|
|
|
2023-10-29 00:07:24 +00:00
|
|
|
let pageWPM = pageWords / (elapsedTime / 60000);
|
2023-10-31 21:30:42 +00:00
|
|
|
console.log("[createActivity] Page WPM:", pageWPM);
|
2023-10-12 23:14:29 +00:00
|
|
|
|
2023-10-29 00:07:24 +00:00
|
|
|
// Exclude Ridiculous WPM
|
2023-10-31 21:30:42 +00:00
|
|
|
if (pageWPM >= WPM_MAX)
|
|
|
|
return console.log(
|
|
|
|
"[createActivity] Page WPM Exceeds Max (2000):",
|
|
|
|
pageWPM
|
|
|
|
);
|
2023-10-12 23:14:29 +00:00
|
|
|
|
2023-10-29 00:07:24 +00:00
|
|
|
// Ensure WPM Minimum
|
|
|
|
if (pageWPM < WPM_MIN) elapsedTime = (pageWords / WPM_MIN) * 60000;
|
2023-10-12 23:14:29 +00:00
|
|
|
|
2023-10-29 00:07:24 +00:00
|
|
|
let totalPages = Math.round(1 / percentRead);
|
2023-10-12 23:14:29 +00:00
|
|
|
|
2023-10-31 21:30:42 +00:00
|
|
|
// Exclude 0 Pages
|
|
|
|
if (totalPages == 0)
|
2023-11-04 03:43:08 +00:00
|
|
|
return console.warn("[createActivity] Invalid Total Pages (0)");
|
2023-10-31 21:30:42 +00:00
|
|
|
|
2023-10-29 00:07:24 +00:00
|
|
|
let currentPage = Math.round(
|
2023-11-04 03:43:08 +00:00
|
|
|
(currentWord * totalPages) / this.bookState.words
|
2023-10-29 00:07:24 +00:00
|
|
|
);
|
2023-10-12 23:14:29 +00:00
|
|
|
|
|
|
|
// Create Activity Event
|
|
|
|
let activityEvent = {
|
|
|
|
device_id: this.readerSettings.deviceID,
|
|
|
|
device: this.readerSettings.deviceName,
|
2023-10-29 00:07:24 +00:00
|
|
|
activity: [
|
|
|
|
{
|
|
|
|
document: this.bookState.id,
|
|
|
|
duration: Math.round(elapsedTime / 1000),
|
|
|
|
start_time: Math.round(pageStart / 1000),
|
|
|
|
page: currentPage,
|
|
|
|
pages: totalPages,
|
|
|
|
},
|
|
|
|
],
|
2023-10-12 23:14:29 +00:00
|
|
|
};
|
|
|
|
|
2023-10-30 22:25:43 +00:00
|
|
|
// Local Files
|
|
|
|
if (this.bookState.type == "LOCAL") return;
|
|
|
|
|
|
|
|
// Remote Flush -> Offline Cache IDB
|
2023-10-29 00:07:24 +00:00
|
|
|
this.flushActivity(activityEvent).catch(async (e) => {
|
|
|
|
console.error("[createActivity] Activity Flush Failed:", {
|
|
|
|
error: e,
|
|
|
|
data: activityEvent,
|
|
|
|
});
|
|
|
|
|
|
|
|
// Get & Update Activity
|
|
|
|
let existingActivity = await IDB.get("ACTIVITY", { activity: [] });
|
|
|
|
existingActivity.device_id = activityEvent.device_id;
|
|
|
|
existingActivity.device = activityEvent.device;
|
|
|
|
existingActivity.activity.push(...activityEvent.activity);
|
|
|
|
|
|
|
|
// Update IDB
|
|
|
|
await IDB.set("ACTIVITY", existingActivity);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Normalize and flush activity
|
|
|
|
**/
|
|
|
|
flushActivity(activityEvent) {
|
|
|
|
console.log("[flushActivity] Flushing Activity...");
|
|
|
|
|
2023-10-12 23:14:29 +00:00
|
|
|
// Flush Activity
|
2023-10-29 00:07:24 +00:00
|
|
|
return fetch("/api/ko/activity", {
|
2023-10-12 23:14:29 +00:00
|
|
|
method: "POST",
|
|
|
|
body: JSON.stringify(activityEvent),
|
2023-10-29 00:07:24 +00:00
|
|
|
}).then(async (r) =>
|
|
|
|
console.log("[flushActivity] Flushed Activity:", {
|
|
|
|
response: r,
|
|
|
|
json: await r.json(),
|
|
|
|
data: activityEvent,
|
|
|
|
})
|
|
|
|
);
|
2023-10-12 23:14:29 +00:00
|
|
|
}
|
|
|
|
|
2023-10-29 00:07:24 +00:00
|
|
|
async createProgress() {
|
|
|
|
// Update Pointers
|
|
|
|
let currentCFI = await this.rendition.currentLocation();
|
|
|
|
let { element, xpath } = await this.getXPathFromCFI(currentCFI.start.cfi);
|
2023-11-04 03:43:08 +00:00
|
|
|
let currentWord = await this.getBookWordPosition();
|
|
|
|
console.log("[createProgress] Current Word:", currentWord);
|
2023-10-29 00:07:24 +00:00
|
|
|
this.bookState.progress = xpath;
|
|
|
|
this.bookState.progressElement = element;
|
2023-10-12 23:14:29 +00:00
|
|
|
|
2023-10-29 00:07:24 +00:00
|
|
|
// Create Event
|
2023-10-12 23:14:29 +00:00
|
|
|
let progressEvent = {
|
|
|
|
document: this.bookState.id,
|
|
|
|
device_id: this.readerSettings.deviceID,
|
|
|
|
device: this.readerSettings.deviceName,
|
|
|
|
percentage:
|
2023-11-04 03:43:08 +00:00
|
|
|
Math.round((currentWord / this.bookState.words) * 100000) / 100000,
|
2023-10-12 23:14:29 +00:00
|
|
|
progress: this.bookState.progress,
|
|
|
|
};
|
|
|
|
|
2023-10-30 22:25:43 +00:00
|
|
|
// Update Local Metadata
|
|
|
|
if (this.bookState.type == "LOCAL") {
|
|
|
|
let currentMetadata = await IDB.get("FILE-METADATA-" + this.bookState.id);
|
|
|
|
return IDB.set("FILE-METADATA-" + this.bookState.id, {
|
|
|
|
...currentMetadata,
|
|
|
|
progress: progressEvent.progress,
|
|
|
|
percentage: Math.round(progressEvent.percentage * 10000) / 100,
|
|
|
|
words: this.bookState.words,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
// Remote Flush -> Offline Cache IDB
|
2023-10-29 00:07:24 +00:00
|
|
|
this.flushProgress(progressEvent).catch(async (e) => {
|
|
|
|
console.error("[createProgress] Progress Flush Failed:", {
|
|
|
|
error: e,
|
|
|
|
data: progressEvent,
|
|
|
|
});
|
|
|
|
|
|
|
|
// Update IDB
|
|
|
|
await IDB.set("PROGRESS-" + progressEvent.document, progressEvent);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Flush progress to the API. Called when the page changes.
|
|
|
|
**/
|
|
|
|
flushProgress(progressEvent) {
|
|
|
|
console.log("[flushProgress] Flushing Progress...");
|
|
|
|
|
2023-10-12 23:14:29 +00:00
|
|
|
// Flush Progress
|
2023-10-29 00:07:24 +00:00
|
|
|
return fetch("/api/ko/syncs/progress", {
|
2023-10-12 23:14:29 +00:00
|
|
|
method: "PUT",
|
|
|
|
body: JSON.stringify(progressEvent),
|
2023-10-29 00:07:24 +00:00
|
|
|
}).then(async (r) =>
|
|
|
|
console.log("[flushProgress] Flushed Progress:", {
|
|
|
|
response: r,
|
|
|
|
json: await r.json(),
|
|
|
|
data: progressEvent,
|
|
|
|
})
|
|
|
|
);
|
2023-10-10 23:06:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Derive chapter current page and total pages
|
|
|
|
**/
|
|
|
|
sectionProgress() {
|
|
|
|
let visibleItems = this.rendition.manager.visible();
|
2023-10-29 00:07:24 +00:00
|
|
|
if (visibleItems.length == 0)
|
|
|
|
return console.log("[sectionProgress] No Items");
|
2023-10-10 23:06:12 +00:00
|
|
|
let visibleSection = visibleItems[0];
|
|
|
|
let visibleIndex = visibleSection.index;
|
|
|
|
let pagesPerBlock = visibleSection.layout.divisor;
|
|
|
|
let totalBlocks = visibleSection.width() / visibleSection.layout.width;
|
|
|
|
let sectionPages = totalBlocks;
|
|
|
|
|
|
|
|
let leftOffset = this.rendition.views().container.scrollLeft;
|
|
|
|
let sectionCurrentPage =
|
|
|
|
Math.round(leftOffset / visibleSection.layout.width) + 1;
|
|
|
|
|
|
|
|
return { sectionPages, sectionCurrentPage };
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get chapter pages, name and progress percentage
|
|
|
|
**/
|
2023-11-04 03:43:08 +00:00
|
|
|
async getBookStats() {
|
2023-10-10 23:06:12 +00:00
|
|
|
let currentProgress = this.sectionProgress();
|
|
|
|
if (!currentProgress) return;
|
|
|
|
let { sectionPages, sectionCurrentPage } = currentProgress;
|
|
|
|
|
|
|
|
let currentLocation = this.rendition.currentLocation();
|
2023-11-04 03:43:08 +00:00
|
|
|
let currentWord = await this.getBookWordPosition();
|
2023-10-10 23:06:12 +00:00
|
|
|
|
|
|
|
let currentTOC = this.book.navigation.toc.find(
|
|
|
|
(item) => item.href == currentLocation.start.href
|
|
|
|
);
|
|
|
|
|
|
|
|
return {
|
|
|
|
sectionPage: sectionCurrentPage,
|
|
|
|
sectionTotalPages: sectionPages,
|
|
|
|
chapterName: currentTOC ? currentTOC.label.trim() : "N/A",
|
|
|
|
percentage:
|
2023-11-04 03:43:08 +00:00
|
|
|
Math.round((currentWord / this.bookState.words) * 10000) / 100,
|
2023-10-10 23:06:12 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Update elements with stats
|
|
|
|
**/
|
2023-10-29 00:07:24 +00:00
|
|
|
updateBookStatElements(data) {
|
2023-10-10 23:06:12 +00:00
|
|
|
if (!data) return;
|
|
|
|
|
|
|
|
let chapterStatus = document.querySelector("#chapter-status");
|
|
|
|
let progressStatus = document.querySelector("#progress-status");
|
|
|
|
let chapterName = document.querySelector("#chapter-name-status");
|
|
|
|
let progressBar = document.querySelector("#progress-bar-status");
|
|
|
|
|
|
|
|
chapterStatus.innerText = `${data.sectionPage} / ${data.sectionTotalPages}`;
|
|
|
|
progressStatus.innerText = `${data.percentage}%`;
|
|
|
|
progressBar.style.width = data.percentage + "%";
|
|
|
|
chapterName.innerText = `${data.chapterName}`;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get XPath from current location
|
|
|
|
**/
|
2023-10-16 03:23:58 +00:00
|
|
|
async getXPathFromCFI(cfi) {
|
2023-11-07 00:41:35 +00:00
|
|
|
// Get DocFragment (Spine Index)
|
2023-10-16 03:23:58 +00:00
|
|
|
let startCFI = cfi.replace("epubcfi(", "");
|
|
|
|
let docFragmentIndex =
|
|
|
|
this.book.spine.spineItems.find((item) =>
|
|
|
|
startCFI.startsWith(item.cfiBase)
|
|
|
|
).index + 1;
|
2023-10-10 23:06:12 +00:00
|
|
|
|
2023-10-12 23:14:29 +00:00
|
|
|
// Base Progress
|
2023-11-07 00:41:35 +00:00
|
|
|
let basePos = "/body/DocFragment[" + docFragmentIndex + "]/body";
|
2023-10-10 23:06:12 +00:00
|
|
|
|
2023-11-07 00:41:35 +00:00
|
|
|
// Get First Node & Element Reference
|
2023-10-10 23:06:12 +00:00
|
|
|
let contents = this.rendition.getContents()[0];
|
2023-11-07 00:41:35 +00:00
|
|
|
let currentNode = contents.range(cfi).startContainer;
|
|
|
|
let element =
|
|
|
|
currentNode.nodeType == Node.ELEMENT_NODE
|
|
|
|
? currentNode
|
|
|
|
: currentNode.parentElement;
|
|
|
|
|
|
|
|
// XPath Reference
|
|
|
|
let allPos = "";
|
|
|
|
|
|
|
|
// Walk Upwards
|
|
|
|
while (currentNode.nodeName != "BODY") {
|
|
|
|
// Get Parent
|
|
|
|
let parentElement = currentNode.parentElement;
|
|
|
|
|
|
|
|
// Unknown Node -> Update Reference
|
|
|
|
if (currentNode.nodeType != Node.ELEMENT_NODE) {
|
|
|
|
console.log("[getXPathFromCFI] Unknown Node Type:", currentNode);
|
|
|
|
currentNode = parentElement;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Exclude A tags. This could potentially be all inline elements:
|
|
|
|
* https://github.com/koreader/crengine/blob/master/cr3gui/data/epub.css#L149
|
|
|
|
**/
|
|
|
|
while (parentElement.nodeName == "A") {
|
|
|
|
parentElement = parentElement.parentElement;
|
2023-10-14 01:06:49 +00:00
|
|
|
}
|
|
|
|
|
2023-11-07 00:41:35 +00:00
|
|
|
/**
|
|
|
|
* Note: This is depth / document order first, which means that this
|
|
|
|
* _could_ return incorrect results when dealing with nested "A" tags
|
|
|
|
* (dependent on how KOReader deals with nested "A" tags)
|
|
|
|
**/
|
|
|
|
let allDescendents = parentElement.querySelectorAll(currentNode.nodeName);
|
|
|
|
let relativeIndex = Array.from(allDescendents).indexOf(currentNode) + 1;
|
|
|
|
|
|
|
|
// Get Node Position
|
|
|
|
let nodePos =
|
|
|
|
currentNode.nodeName.toLowerCase() + "[" + relativeIndex + "]";
|
|
|
|
|
|
|
|
// Update Reference
|
|
|
|
currentNode = parentElement;
|
|
|
|
|
|
|
|
// Update Position
|
|
|
|
allPos = "/" + nodePos + allPos;
|
2023-10-10 23:06:12 +00:00
|
|
|
}
|
|
|
|
|
2023-11-07 00:41:35 +00:00
|
|
|
// Combine XPath
|
|
|
|
let xpath = basePos + allPos;
|
2023-10-16 03:23:58 +00:00
|
|
|
|
2023-11-07 00:41:35 +00:00
|
|
|
// Return Derived Progress
|
2023-10-16 03:23:58 +00:00
|
|
|
return { xpath, element };
|
2023-10-10 23:06:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2023-10-16 03:23:58 +00:00
|
|
|
* Get CFI from current location
|
2023-10-10 23:06:12 +00:00
|
|
|
**/
|
2023-10-16 03:23:58 +00:00
|
|
|
async getCFIFromXPath(xpath) {
|
|
|
|
// No XPath
|
2023-10-25 23:52:01 +00:00
|
|
|
if (!xpath || xpath == "") return {};
|
2023-10-10 23:06:12 +00:00
|
|
|
|
|
|
|
// Match Document Fragment Index
|
2023-10-16 03:23:58 +00:00
|
|
|
let fragMatch = xpath.match(/^\/body\/DocFragment\[(\d+)\]/);
|
2023-10-10 23:06:12 +00:00
|
|
|
if (!fragMatch) {
|
2023-11-07 00:41:35 +00:00
|
|
|
console.warn("[getCFIFromXPath] No XPath Match");
|
2023-10-25 23:52:01 +00:00
|
|
|
return {};
|
2023-10-10 23:06:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Match Item Index
|
2023-10-16 03:23:58 +00:00
|
|
|
let indexMatch = xpath.match(/\.(\d+)$/);
|
2023-10-10 23:06:12 +00:00
|
|
|
let itemIndex = indexMatch ? parseInt(indexMatch[1]) : 0;
|
|
|
|
|
|
|
|
// Get Spine Item
|
|
|
|
let spinePosition = parseInt(fragMatch[1]) - 1;
|
2023-10-16 03:23:58 +00:00
|
|
|
let sectionItem = this.book.spine.get(spinePosition);
|
|
|
|
await sectionItem.load(this.book.load.bind(this.book));
|
2023-10-10 23:06:12 +00:00
|
|
|
|
2023-10-19 23:03:15 +00:00
|
|
|
/**
|
|
|
|
* Prefer Document Rendered over Document Not Rendered
|
|
|
|
*
|
|
|
|
* If the rendition is not displayed, the document does not exist in the
|
|
|
|
* DOM. Since we return the matching element for potential theming, we
|
|
|
|
* want to first at least try to get the document that exists in the DOM.
|
|
|
|
*
|
|
|
|
* This is only relevant on initial load and on font resize when we theme
|
|
|
|
* the element to indicate to the user the last position, and is why we run
|
|
|
|
* this function twice in the setupReader function; once before render to
|
|
|
|
* get CFI, and once after render to get the actual element in the DOM to
|
|
|
|
* theme.
|
|
|
|
**/
|
2023-10-16 03:23:58 +00:00
|
|
|
let docItem =
|
|
|
|
this.rendition
|
|
|
|
.getContents()
|
|
|
|
.find((item) => item.sectionIndex == spinePosition)?.document ||
|
|
|
|
sectionItem.document;
|
2023-10-10 23:06:12 +00:00
|
|
|
|
2023-11-06 12:12:24 +00:00
|
|
|
// Derive Namespace & XPath
|
2023-10-16 03:23:58 +00:00
|
|
|
let namespaceURI = docItem.documentElement.namespaceURI;
|
|
|
|
let remainingXPath = xpath
|
2023-10-10 23:06:12 +00:00
|
|
|
// Replace with new base
|
|
|
|
.replace(fragMatch[0], "/html")
|
|
|
|
// Replace `.0` Ending Indexes
|
|
|
|
.replace(/\.(\d+)$/, "")
|
|
|
|
// Remove potential trailing `text()`
|
2023-10-26 02:44:16 +00:00
|
|
|
.replace(/\/text\(\)(\[\d+\])?$/, "");
|
2023-10-10 23:06:12 +00:00
|
|
|
|
2023-11-07 00:41:35 +00:00
|
|
|
// XPath to Element
|
|
|
|
let derivedSelectorElement = remainingXPath
|
2023-11-06 12:12:24 +00:00
|
|
|
.replace(/^\/html\/body/, "body")
|
2023-11-07 00:41:35 +00:00
|
|
|
.split("/")
|
|
|
|
.reduce((el, item) => {
|
|
|
|
// No Match
|
|
|
|
if (!el) return null;
|
|
|
|
|
|
|
|
// Non Index
|
|
|
|
let indexMatch = item.match(/(\w+)\[(\d+)\]$/);
|
|
|
|
if (!indexMatch) return el.querySelector(item);
|
|
|
|
|
|
|
|
// Get @ Index
|
|
|
|
let tag = indexMatch[1];
|
|
|
|
let index = parseInt(indexMatch[2]) - 1;
|
|
|
|
return el.querySelectorAll(tag)[index];
|
|
|
|
}, docItem);
|
|
|
|
|
|
|
|
console.log("[getCFIFromXPath] Selector Element:", derivedSelectorElement);
|
2023-11-06 12:12:24 +00:00
|
|
|
|
2023-10-10 23:06:12 +00:00
|
|
|
// Validate Namespace
|
|
|
|
if (namespaceURI) remainingXPath = remainingXPath.replaceAll("/", "/ns:");
|
|
|
|
|
|
|
|
// Perform XPath
|
2023-10-16 03:23:58 +00:00
|
|
|
let docSearch = docItem.evaluate(
|
2023-10-10 23:06:12 +00:00
|
|
|
remainingXPath,
|
2023-10-16 03:23:58 +00:00
|
|
|
docItem,
|
2023-10-10 23:06:12 +00:00
|
|
|
function (prefix) {
|
|
|
|
if (prefix === "ns") {
|
|
|
|
return namespaceURI;
|
|
|
|
} else {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
);
|
|
|
|
|
2023-11-06 12:12:24 +00:00
|
|
|
/**
|
|
|
|
* There are two ways to do this. One via XPath, and the other via derived
|
|
|
|
* CSS selectors. Unfortunately it seems like KOReaders XPath implementation
|
|
|
|
* is a little wonky, requiring the need for CSS Selectors.
|
|
|
|
*
|
|
|
|
* For example the following XPath was generated by KOReader:
|
|
|
|
* "/body/DocFragment[19]/body/h1/img.0"
|
|
|
|
*
|
|
|
|
* In reality, the XPath should have been (note the 'a'):
|
|
|
|
* "/body/DocFragment[19]/body/h1/a/img.0"
|
|
|
|
*
|
|
|
|
* Unfortunately due to the above, `docItem.evaluate` will not find the
|
|
|
|
* element. So as an alternative I thought it would be possible to derive
|
|
|
|
* a CSS selector. I think this should be fully comprehensive; AFAICT
|
|
|
|
* KOReader only creates XPaths referencing HTML tag names and indexes.
|
|
|
|
**/
|
|
|
|
|
|
|
|
// Get Element & CFI (XPath -> CSS Selector Fallback)
|
2023-11-07 00:41:35 +00:00
|
|
|
let element = docSearch.iterateNext() || derivedSelectorElement;
|
2023-10-16 03:23:58 +00:00
|
|
|
let cfi = sectionItem.cfiFromElement(element);
|
|
|
|
|
|
|
|
return { cfi, element };
|
2023-10-10 23:06:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get visible word count - used for reading stats
|
|
|
|
**/
|
|
|
|
async getVisibleWordCount() {
|
2023-11-04 03:43:08 +00:00
|
|
|
let visibleText = await this.getVisibleText();
|
|
|
|
return visibleText.trim().split(/\s+/).length;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Gets the word number of the whole book for the first visible word.
|
|
|
|
**/
|
|
|
|
async getBookWordPosition() {
|
|
|
|
// Get Contents & Spine
|
|
|
|
let contents = this.rendition.getContents()[0];
|
|
|
|
let spineItem = this.book.spine.get(contents.sectionIndex);
|
|
|
|
|
|
|
|
// Get CFI Range
|
|
|
|
let firstCFI = spineItem.cfiFromElement(
|
|
|
|
spineItem.document.body.children[0]
|
|
|
|
);
|
|
|
|
let currentLocation = await this.rendition.currentLocation();
|
|
|
|
let cfiRange = this.getCFIRange(firstCFI, currentLocation.start.cfi);
|
|
|
|
|
|
|
|
// Get Chapter Text (Before Current Position)
|
|
|
|
let textRange = await this.book.getRange(cfiRange);
|
|
|
|
let chapterText = textRange.toString();
|
|
|
|
|
|
|
|
// Get Chapter & Book Positions
|
|
|
|
let chapterWordPosition = chapterText.trim().split(/\s+/).length;
|
|
|
|
let preChapterWordPosition = this.book.spine.spineItems
|
|
|
|
.slice(0, contents.sectionIndex)
|
|
|
|
.reduce((totalCount, item) => totalCount + item.wordCount, 0);
|
|
|
|
|
|
|
|
// Return Current Word Pointer
|
|
|
|
return chapterWordPosition + preChapterWordPosition;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get visible text - used for word counts
|
|
|
|
**/
|
|
|
|
async getVisibleText() {
|
2023-10-10 23:06:12 +00:00
|
|
|
// Force Expand & Resize (Race Condition Issue)
|
|
|
|
this.rendition.manager.visible().forEach((item) => item.expand());
|
|
|
|
|
|
|
|
// Get Start & End CFI
|
|
|
|
let currentLocation = await this.rendition.currentLocation();
|
|
|
|
const [startCFI, endCFI] = [
|
|
|
|
currentLocation.start.cfi,
|
|
|
|
currentLocation.end.cfi,
|
|
|
|
];
|
|
|
|
|
|
|
|
// Derive Range & Get Text
|
|
|
|
let cfiRange = this.getCFIRange(startCFI, endCFI);
|
|
|
|
let textRange = await this.book.getRange(cfiRange);
|
|
|
|
let visibleText = textRange.toString();
|
|
|
|
|
|
|
|
// Split on Whitespace
|
2023-11-04 03:43:08 +00:00
|
|
|
return visibleText;
|
2023-10-10 23:06:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Given two CFI's, return range
|
|
|
|
**/
|
|
|
|
getCFIRange(a, b) {
|
|
|
|
const CFI = new ePub.CFI();
|
|
|
|
const start = CFI.parse(a),
|
|
|
|
end = CFI.parse(b);
|
|
|
|
const cfi = {
|
|
|
|
range: true,
|
|
|
|
base: start.base,
|
|
|
|
path: {
|
|
|
|
steps: [],
|
|
|
|
terminal: null,
|
|
|
|
},
|
|
|
|
start: start.path,
|
|
|
|
end: end.path,
|
|
|
|
};
|
|
|
|
const len = cfi.start.steps.length;
|
|
|
|
for (let i = 0; i < len; i++) {
|
|
|
|
if (CFI.equalStep(cfi.start.steps[i], cfi.end.steps[i])) {
|
|
|
|
if (i == len - 1) {
|
|
|
|
// Last step is equal, check terminals
|
|
|
|
if (cfi.start.terminal === cfi.end.terminal) {
|
|
|
|
// CFI's are equal
|
|
|
|
cfi.path.steps.push(cfi.start.steps[i]);
|
|
|
|
// Not a range
|
|
|
|
cfi.range = false;
|
|
|
|
}
|
|
|
|
} else cfi.path.steps.push(cfi.start.steps[i]);
|
|
|
|
} else break;
|
|
|
|
}
|
|
|
|
cfi.start.steps = cfi.start.steps.slice(cfi.path.steps.length);
|
|
|
|
cfi.end.steps = cfi.end.steps.slice(cfi.path.steps.length);
|
|
|
|
|
|
|
|
return (
|
|
|
|
"epubcfi(" +
|
|
|
|
CFI.segmentString(cfi.base) +
|
|
|
|
"!" +
|
|
|
|
CFI.segmentString(cfi.path) +
|
|
|
|
"," +
|
|
|
|
CFI.segmentString(cfi.start) +
|
|
|
|
"," +
|
|
|
|
CFI.segmentString(cfi.end) +
|
|
|
|
")"
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2023-10-27 00:20:58 +00:00
|
|
|
/**
|
|
|
|
* Count the words of the book. Useful for keeping a more accurate track
|
|
|
|
* of progress percentage. Implementation returns the same number as the
|
|
|
|
* server side implementation.
|
|
|
|
**/
|
2023-11-04 03:43:08 +00:00
|
|
|
async countWords() {
|
|
|
|
let spineWC = await Promise.all(
|
|
|
|
this.book.spine.spineItems.map(async (item) => {
|
|
|
|
let newDoc = await item.load(this.book.load.bind(this.book));
|
|
|
|
let spineWords = newDoc.innerText.trim().split(/\s+/).length;
|
|
|
|
item.wordCount = spineWords;
|
|
|
|
return spineWords;
|
|
|
|
})
|
|
|
|
);
|
|
|
|
|
|
|
|
return spineWC.reduce((totalCount, itemCount) => totalCount + itemCount, 0);
|
2023-10-27 00:20:58 +00:00
|
|
|
}
|
|
|
|
|
2023-10-10 23:06:12 +00:00
|
|
|
/**
|
|
|
|
* Save settings to localStorage
|
|
|
|
**/
|
2023-10-25 23:52:01 +00:00
|
|
|
saveSettings() {
|
2023-10-10 23:06:12 +00:00
|
|
|
if (!this.readerSettings) this.loadSettings();
|
2023-10-25 23:52:01 +00:00
|
|
|
localStorage.setItem("readerSettings", JSON.stringify(this.readerSettings));
|
2023-10-10 23:06:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Load reader settings from localStorage
|
|
|
|
**/
|
|
|
|
loadSettings() {
|
|
|
|
this.readerSettings = JSON.parse(
|
|
|
|
localStorage.getItem("readerSettings") || "{}"
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
2023-10-29 00:07:24 +00:00
|
|
|
|
|
|
|
document.addEventListener("DOMContentLoaded", initReader);
|
2024-01-01 04:12:46 +00:00
|
|
|
|
|
|
|
// WIP
|
|
|
|
async function getTOC() {
|
|
|
|
let toc = currentReader.book.navigation.toc;
|
|
|
|
|
|
|
|
// Alternatively:
|
|
|
|
// let nav = await currentReader.book.loaded.navigation;
|
|
|
|
// let toc = nav.toc;
|
|
|
|
|
|
|
|
currentReader.rendition.display(nav.toc[10].href);
|
|
|
|
}
|