diff --git a/package-lock.json b/package-lock.json index a57afd0e..f58bbbf1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@d-i-t-a/reader", - "version": "2.1.0-beta.5", + "version": "2.1.0-beta.6", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@d-i-t-a/reader", - "version": "2.1.0-beta.5", + "version": "2.1.0-beta.6", "license": "Apache-2.0", "dependencies": { "@types/sass": "^1.43.1", @@ -17,6 +17,7 @@ "eventemitter3": "^4.0.7", "jscrypto": "^1.0.3", "lodash.clonedeep": "^4.5.0", + "loglevel": "^1.8.0", "mark.js": "^8.11.1", "promise-polyfill": "^8.2.0", "r2-shared-js": "^1.0.51", @@ -7464,6 +7465,18 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/loglevel": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/loglevel/-/loglevel-1.8.0.tgz", + "integrity": "sha512-G6A/nJLRgWOuuwdNuA6koovfEV1YpqqAG4pRUlFaz3jj2QNZ8M4vBqnVA+HBTmU/AMNUtlOsMmSpF6NyOjztbA==", + "engines": { + "node": ">= 0.6.0" + }, + "funding": { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/loglevel" + } + }, "node_modules/loose-envify": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", @@ -16861,6 +16874,11 @@ "is-unicode-supported": "^0.1.0" } }, + "loglevel": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/loglevel/-/loglevel-1.8.0.tgz", + "integrity": "sha512-G6A/nJLRgWOuuwdNuA6koovfEV1YpqqAG4pRUlFaz3jj2QNZ8M4vBqnVA+HBTmU/AMNUtlOsMmSpF6NyOjztbA==" + }, "loose-envify": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", diff --git a/package.json b/package.json index 5e9500c1..b302547f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@d-i-t-a/reader", - "version": "2.1.0-beta.5", + "version": "2.1.0-beta.6", "description": "A viewer application for EPUB files.", "repository": "https://github.com/d-i-t-a/R2D2BC", "license": "Apache-2.0", @@ -32,6 +32,7 @@ "eventemitter3": "^4.0.7", "jscrypto": "^1.0.3", "lodash.clonedeep": "^4.5.0", + "loglevel": "^1.8.0", "mark.js": "^8.11.1", "promise-polyfill": "^8.2.0", "r2-shared-js": "^1.0.51", diff --git a/src/model/user-settings/UserSettings.ts b/src/model/user-settings/UserSettings.ts index d79da3fd..0d9a9566 100644 --- a/src/model/user-settings/UserSettings.ts +++ b/src/model/user-settings/UserSettings.ts @@ -28,12 +28,12 @@ import { } from "./UserProperties"; import { ReadiumCSS } from "./ReadiumCSS"; import * as HTMLUtilities from "../../utils/HTMLUtilities"; -import { IS_DEV } from "../../utils"; import { addEventListenerOptional } from "../../utils/EventHandler"; import { Injectable, NavigatorAPI } from "../../navigator/IFrameNavigator"; import ReflowableBookView from "../../views/ReflowableBookView"; import FixedBookView from "../../views/FixedBookView"; import BookView from "../../views/BookView"; +import log from "loglevel"; export interface UserSettingsConfig { /** Store to save the user's selections in. */ @@ -113,7 +113,7 @@ export class UserSettings implements IUserSettings { ReadiumCSS.SCROLL_KEY ); - return scroll === false; + return !scroll; } async isScrollMode() { return !(await this.isPaginated()); @@ -185,7 +185,7 @@ export class UserSettings implements IUserSettings { prop.value = settings.verticalScroll; await settings.saveProperty(prop); } - if (IS_DEV) console.log(settings.verticalScroll); + log.log(settings.verticalScroll); } if (initialUserSettings.appearance) { settings.appearance = UserSettings.appearanceValues.findIndex( @@ -196,7 +196,7 @@ export class UserSettings implements IUserSettings { prop.value = settings.appearance; await settings.saveProperty(prop); } - if (IS_DEV) console.log(settings.appearance); + log.log(settings.appearance); } if (initialUserSettings.fontSize) { settings.fontSize = initialUserSettings.fontSize; @@ -205,7 +205,7 @@ export class UserSettings implements IUserSettings { prop.value = settings.fontSize; await settings.saveProperty(prop); } - if (IS_DEV) console.log(settings.fontSize); + log.log(settings.fontSize); } if (initialUserSettings.fontFamily) { settings.fontFamily = UserSettings.fontFamilyValues.findIndex( @@ -216,7 +216,7 @@ export class UserSettings implements IUserSettings { prop.value = settings.fontFamily; await settings.saveProperty(prop); } - if (IS_DEV) console.log(settings.fontFamily); + log.log(settings.fontFamily); if (settings.fontFamily !== 0) { settings.fontOverride = true; } @@ -233,7 +233,7 @@ export class UserSettings implements IUserSettings { await settings.saveProperty(prop); } // settings.publisherDefaults = false; - if (IS_DEV) console.log(settings.textAlignment); + log.log(settings.textAlignment); } if (initialUserSettings.columnCount) { settings.columnCount = UserSettings.columnCountValues.findIndex( @@ -246,7 +246,7 @@ export class UserSettings implements IUserSettings { prop.value = settings.columnCount; await settings.saveProperty(prop); } - if (IS_DEV) console.log(settings.columnCount); + log.log(settings.columnCount); } if (initialUserSettings.wordSpacing) { settings.wordSpacing = initialUserSettings.wordSpacing; @@ -257,7 +257,7 @@ export class UserSettings implements IUserSettings { prop.value = settings.wordSpacing; await settings.saveProperty(prop); } - if (IS_DEV) console.log(settings.wordSpacing); + log.log(settings.wordSpacing); } if (initialUserSettings.letterSpacing) { settings.letterSpacing = initialUserSettings.letterSpacing; @@ -268,7 +268,7 @@ export class UserSettings implements IUserSettings { prop.value = settings.letterSpacing; await settings.saveProperty(prop); } - if (IS_DEV) console.log(settings.letterSpacing); + log.log(settings.letterSpacing); } if (initialUserSettings.pageMargins) { settings.pageMargins = initialUserSettings.pageMargins; @@ -279,7 +279,7 @@ export class UserSettings implements IUserSettings { prop.value = settings.pageMargins; await settings.saveProperty(prop); } - if (IS_DEV) console.log(settings.pageMargins); + log.log(settings.pageMargins); } if (initialUserSettings.lineHeight) { settings.lineHeight = initialUserSettings.lineHeight; @@ -288,7 +288,7 @@ export class UserSettings implements IUserSettings { prop.value = settings.lineHeight; await settings.saveProperty(prop); } - if (IS_DEV) console.log(settings.lineHeight); + log.log(settings.lineHeight); } settings.userProperties = settings.getUserSettings(); await settings.initialise(); @@ -328,9 +328,7 @@ export class UserSettings implements IUserSettings { } stop() { - if (IS_DEV) { - console.log("book settings stop"); - } + log.log("book settings stop"); } private async initialise() { @@ -717,10 +715,10 @@ export class UserSettings implements IUserSettings { if (this.view) { this.view.iframe = iframe; } - if (this.settingsView) this.renderControls(this.settingsView); + if (this.settingsView) UserSettings.renderControls(this.settingsView); } - private renderControls(element: HTMLElement): void { + private static renderControls(element: HTMLElement): void { // Clicking the settings view outside the ul hides it, but clicking inside the ul keeps it up. addEventListenerOptional( HTMLUtilities.findElement(element, "ul"), @@ -801,9 +799,7 @@ export class UserSettings implements IUserSettings { }; if (this.api?.updateSettings) { this.api?.updateSettings(userSettings).then((_) => { - if (IS_DEV) { - console.log("api updated user settings", userSettings); - } + log.log("api updated user settings", JSON.stringify(userSettings)); }); } } diff --git a/src/modules/AnnotationModule.ts b/src/modules/AnnotationModule.ts index 6cb3dd13..8ca9d9b3 100644 --- a/src/modules/AnnotationModule.ts +++ b/src/modules/AnnotationModule.ts @@ -31,7 +31,6 @@ import { Bookmark, Locator, } from "../model/Locator"; -import { IS_DEV } from "../utils"; import { icons as IconLib } from "../utils/IconLib"; import { v4 as uuid } from "uuid"; import { Link } from "../model/Link"; @@ -42,6 +41,7 @@ import { ISelectionInfo, } from "./highlight/common/selection"; import * as lodash from "lodash"; +import log from "loglevel"; export type Highlight = (highlight: Annotation) => Promise; @@ -120,9 +120,7 @@ export class AnnotationModule implements ReaderModule { } async stop() { - if (IS_DEV) { - console.log("Annotation module stop"); - } + log.log("Annotation module stop"); } protected async start(): Promise { @@ -254,8 +252,8 @@ export class AnnotationModule implements ReaderModule { return ""; } } catch (err) { - console.log("uniqueCssSelector:"); - console.log(err); + log.log("uniqueCssSelector:"); + log.error(err); return ""; } } @@ -279,9 +277,7 @@ export class AnnotationModule implements ReaderModule { ); if (book) { this.saveAnnotation(book[0]).then((anno) => { - if (IS_DEV) { - console.log("saved bookmark " + anno.id); - } + log.log("saved bookmark " + anno.id); }); } } @@ -292,9 +288,7 @@ export class AnnotationModule implements ReaderModule { } async scrollToHighlight(id: any): Promise { - if (IS_DEV) { - console.log("still need to scroll to " + id); - } + log.log("still need to scroll to " + id); var position = await this.annotator?.getAnnotationPosition( id, this.delegate.iframes[0].contentWindow as any @@ -307,10 +301,8 @@ export class AnnotationModule implements ReaderModule { let deleted = await this.annotator.deleteAnnotation(annotation.id); let added = await this.addAnnotation(annotation); - if (IS_DEV) { - console.log("Highlight deleted " + JSON.stringify(deleted)); - console.log("Highlight added " + JSON.stringify(added)); - } + log.log("Highlight deleted " + JSON.stringify(deleted)); + log.log("Highlight added " + JSON.stringify(added)); await this.showHighlights(); await this.drawHighlights(); return added; @@ -323,9 +315,7 @@ export class AnnotationModule implements ReaderModule { if (this.annotator) { var deleted = await this.annotator.deleteAnnotation(id); - if (IS_DEV) { - console.log("Highlight deleted " + JSON.stringify(deleted)); - } + log.log("Highlight deleted " + JSON.stringify(deleted)); await this.showHighlights(); await this.drawHighlights(); return deleted; @@ -877,9 +867,7 @@ export class AnnotationModule implements ReaderModule { this.delegate.stopReadAloud(); this.delegate.navigate(locator); } else { - if (IS_DEV) { - console.log("annotation data missing: ", event); - } + log.log("annotation data missing: ", event); } } @@ -888,17 +876,13 @@ export class AnnotationModule implements ReaderModule { event: MouseEvent, locator: any ): void { - if (IS_DEV) { - console.log("annotation data locator: ", locator); - } + log.log("annotation data locator: ", locator); if (locator) { if (type === AnnotationType.Annotation) { this.deleteHighlight(locator); } } else { - if (IS_DEV) { - console.log("annotation data missing: ", event); - } + log.log("annotation data missing: ", event); } } diff --git a/src/modules/BookmarkModule.ts b/src/modules/BookmarkModule.ts index f66beba6..be95e938 100644 --- a/src/modules/BookmarkModule.ts +++ b/src/modules/BookmarkModule.ts @@ -41,7 +41,7 @@ import { } from "./highlight/common/highlight"; import { getClientRectsNoOverlap } from "./highlight/common/rect-utils"; import { _highlights } from "./highlight/TextHighlighter"; -import { IS_DEV } from "../utils"; +import log from "loglevel"; export interface BookmarkModuleAPI { addBookmark: (bookmark: Bookmark) => Promise; @@ -112,9 +112,7 @@ export class BookmarkModule implements ReaderModule { } stop() { - if (IS_DEV) { - console.log("Bookmark module stop"); - } + log.log("Bookmark module stop"); } protected async start(): Promise { @@ -188,18 +186,14 @@ export class BookmarkModule implements ReaderModule { await this.api?.deleteBookmark(bookmark); let deleted = await this.annotator.deleteBookmark(bookmark); - if (IS_DEV) { - console.log("Bookmark deleted " + JSON.stringify(deleted)); - } + log.log("Bookmark deleted " + JSON.stringify(deleted)); await this.showBookmarks(); await this.drawBookmarks(); return deleted; } else { let deleted = await this.annotator.deleteBookmark(bookmark); - if (IS_DEV) { - console.log("Bookmark deleted " + JSON.stringify(deleted)); - } + log.log("Bookmark deleted " + JSON.stringify(deleted)); await this.showBookmarks(); await this.drawBookmarks(); return deleted; @@ -276,21 +270,17 @@ export class BookmarkModule implements ReaderModule { if (result) { bookmark = result; } - if (IS_DEV) console.log(bookmark); + log.log(bookmark); let saved = this.annotator.saveBookmark(bookmark); - if (IS_DEV) { - console.log("Bookmark added " + JSON.stringify(saved)); - } + log.log("Bookmark added " + JSON.stringify(saved)); this.showBookmarks(); await this.drawBookmarks(); return saved; } else { let saved = this.annotator.saveBookmark(bookmark); - if (IS_DEV) { - console.log("Bookmark added " + JSON.stringify(saved)); - } + log.log("Bookmark added " + JSON.stringify(saved)); this.showBookmarks(); await this.drawBookmarks(); return saved; @@ -418,9 +408,7 @@ export class BookmarkModule implements ReaderModule { ?.removeAllRanges(); if (book) { return this.saveAnnotation(book[0]).then((anno) => { - if (IS_DEV) { - console.log("saved bookmark " + anno?.id); - } + log.log("saved bookmark " + anno?.id); }); } } @@ -679,9 +667,7 @@ export class BookmarkModule implements ReaderModule { if (this.annotator) { var deleted = await this.annotator.deleteAnnotation(id); - if (IS_DEV) { - console.log("Highlight deleted " + JSON.stringify(deleted)); - } + log.log("Highlight deleted " + JSON.stringify(deleted)); await this.showBookmarks(); await this.drawBookmarks(); return deleted; @@ -843,9 +829,7 @@ export class BookmarkModule implements ReaderModule { this.delegate.stopReadAloud(); this.delegate.navigate(locator); } else { - if (IS_DEV) { - console.log("bookmark data missing: ", event); - } + log.log("bookmark data missing: ", event); } } @@ -854,17 +838,13 @@ export class BookmarkModule implements ReaderModule { event: MouseEvent, locator: any ): void { - if (IS_DEV) { - console.log("bookmark data locator: ", locator); - } + log.log("bookmark data locator: ", locator); if (locator) { if (type === AnnotationType.Bookmark) { this.deleteBookmark(locator); } } else { - if (IS_DEV) { - console.log("bookmark data missing: ", event); - } + log.log("bookmark data missing: ", event); } } diff --git a/src/modules/TTS/TTSModule2.ts b/src/modules/TTS/TTSModule2.ts index a2138551..9c394da5 100644 --- a/src/modules/TTS/TTSModule2.ts +++ b/src/modules/TTS/TTSModule2.ts @@ -17,7 +17,6 @@ * Licensed to: CAST under one or more contributor license agreements. */ -import { IS_DEV } from "../../utils"; import { ReaderModule } from "../ReaderModule"; import { AnnotationMarker } from "../../model/Locator"; import { @@ -42,6 +41,7 @@ import { _getCssSelectorOptions, ISelectionInfo, } from "../highlight/common/selection"; +import log from "loglevel"; export class TTSModule2 implements ReaderModule { private tts: TTSSettings; @@ -190,14 +190,14 @@ export class TTSModule2 implements ReaderModule { let s = setSpeech(); s.then(async (voices: SpeechSynthesisVoice[]) => { - if (IS_DEV) console.log(voices); + log.log(voices); this.voices = []; voices.forEach((voice) => { if (voice.localService === true) { this.voices.push(voice); } }); - if (IS_DEV) console.log(this.voices); + log.log(this.voices); if (first) { // preferred-languages if (this.headerMenu) { @@ -349,7 +349,7 @@ export class TTSModule2 implements ReaderModule { utterance.pitch = this.tts.pitch; utterance.volume = this.tts.volume; - if (IS_DEV) console.log("this.tts.voice.lang", this.tts.voice.lang); + log.log("this.tts.voice.lang", this.tts.voice.lang); var initialVoiceHasHyphen = true; if (this.tts.voice && this.tts.voice.lang) { @@ -359,8 +359,8 @@ export class TTSModule2 implements ReaderModule { initialVoiceHasHyphen = true; } } - if (IS_DEV) console.log("initialVoiceHasHyphen", initialVoiceHasHyphen); - if (IS_DEV) console.log("voices", this.voices); + log.log("initialVoiceHasHyphen", initialVoiceHasHyphen); + log.log("voices", this.voices); var initialVoice; if (initialVoiceHasHyphen === true) { initialVoice = @@ -396,12 +396,11 @@ export class TTSModule2 implements ReaderModule { : undefined; } } - if (IS_DEV) console.log("initialVoice", initialVoice); + log.log("initialVoice", initialVoice); var publicationVoiceHasHyphen = self.delegate.publication.Metadata.Language[0].indexOf("-") !== -1; - if (IS_DEV) - console.log("publicationVoiceHasHyphen", publicationVoiceHasHyphen); + log.log("publicationVoiceHasHyphen", publicationVoiceHasHyphen); var publicationVoice; if (publicationVoiceHasHyphen === true) { publicationVoice = @@ -433,10 +432,10 @@ export class TTSModule2 implements ReaderModule { })[0] : undefined; } - if (IS_DEV) console.log("publicationVoice", publicationVoice); + log.log("publicationVoice", publicationVoice); var defaultVoiceHasHyphen = navigator.language.indexOf("-") !== -1; - if (IS_DEV) console.log("defaultVoiceHasHyphen", defaultVoiceHasHyphen); + log.log("defaultVoiceHasHyphen", defaultVoiceHasHyphen); var defaultVoice; if (defaultVoiceHasHyphen === true) { defaultVoice = this.voices.filter((voice: SpeechSynthesisVoice) => { @@ -455,24 +454,24 @@ export class TTSModule2 implements ReaderModule { return lang.includes(navigator.language) && voice.localService === true; })[0]; } - if (IS_DEV) console.log("defaultVoice", defaultVoice); + log.log("defaultVoice", defaultVoice); if (initialVoice) { - if (IS_DEV) console.log("initialVoice"); + log.log("initialVoice"); utterance.voice = initialVoice; } else if (publicationVoice) { - if (IS_DEV) console.log("publicationVoice"); + log.log("publicationVoice"); utterance.voice = publicationVoice; } else if (defaultVoice) { - if (IS_DEV) console.log("defaultVoice"); + log.log("defaultVoice"); utterance.voice = defaultVoice; } if (utterance.voice !== undefined && utterance.voice !== null) { utterance.lang = utterance.voice.lang; - if (IS_DEV) console.log("utterance.voice.lang", utterance.voice.lang); - if (IS_DEV) console.log("utterance.lang", utterance.lang); + log.log("utterance.voice.lang", utterance.voice.lang); + log.log("utterance.lang", utterance.lang); } - if (IS_DEV) console.log("navigator.language", navigator.language); + log.log("navigator.language", navigator.language); setTimeout(() => { window.speechSynthesis.speak(utterance); @@ -520,14 +519,14 @@ export class TTSModule2 implements ReaderModule { onend(); } if (idx > idxEnd) { - if (IS_DEV) console.log("utterance ended"); + log.log("utterance ended"); self.highlighter.doneSpeaking(); self.api?.finished(); self.delegate.emit("readaloud.finished", "finished"); } } } else { - if (IS_DEV) console.log("utterance ended"); + log.log("utterance ended"); self.highlighter.doneSpeaking(); self.api?.finished(); self.delegate.emit("readaloud.finished", "finished"); @@ -708,9 +707,7 @@ export class TTSModule2 implements ReaderModule { } stop() { - if (IS_DEV) { - console.log("TTS module stop"); - } + log.log("TTS module stop"); removeEventListenerOptional(document, "wheel", this.wheel.bind(this)); removeEventListenerOptional(this.body, "wheel", this.wheel.bind(this)); removeEventListenerOptional(document, "keydown", this.wheel.bind(this)); @@ -941,7 +938,7 @@ export class TTSModule2 implements ReaderModule { utterance.pitch = this.tts.pitch; utterance.volume = this.tts.volume; - if (IS_DEV) console.log("this.tts.voice.lang", this.tts.voice.lang); + log.log("this.tts.voice.lang", this.tts.voice.lang); var initialVoiceHasHyphen = true; if (this.tts.voice && this.tts.voice.lang) { @@ -951,8 +948,8 @@ export class TTSModule2 implements ReaderModule { initialVoiceHasHyphen = true; } } - if (IS_DEV) console.log("initialVoiceHasHyphen", initialVoiceHasHyphen); - if (IS_DEV) console.log("voices", this.voices); + log.log("initialVoiceHasHyphen", initialVoiceHasHyphen); + log.log("voices", this.voices); var initialVoice; if (initialVoiceHasHyphen === true) { initialVoice = @@ -988,13 +985,12 @@ export class TTSModule2 implements ReaderModule { : undefined; } } - if (IS_DEV) console.log("initialVoice", initialVoice); + log.log("initialVoice", initialVoice); var self = this; var publicationVoiceHasHyphen = self.delegate.publication.Metadata.Language[0].indexOf("-") !== -1; - if (IS_DEV) - console.log("publicationVoiceHasHyphen", publicationVoiceHasHyphen); + log.log("publicationVoiceHasHyphen", publicationVoiceHasHyphen); var publicationVoice; if (publicationVoiceHasHyphen === true) { publicationVoice = @@ -1026,10 +1022,10 @@ export class TTSModule2 implements ReaderModule { })[0] : undefined; } - if (IS_DEV) console.log("publicationVoice", publicationVoice); + log.log("publicationVoice", publicationVoice); var defaultVoiceHasHyphen = navigator.language.indexOf("-") !== -1; - if (IS_DEV) console.log("defaultVoiceHasHyphen", defaultVoiceHasHyphen); + log.log("defaultVoiceHasHyphen", defaultVoiceHasHyphen); var defaultVoice; if (defaultVoiceHasHyphen === true) { defaultVoice = this.voices.filter((voice: SpeechSynthesisVoice) => { @@ -1048,27 +1044,27 @@ export class TTSModule2 implements ReaderModule { return lang.includes(navigator.language) && voice.localService === true; })[0]; } - if (IS_DEV) console.log("defaultVoice", defaultVoice); + log.log("defaultVoice", defaultVoice); if (initialVoice) { - if (IS_DEV) console.log("initialVoice"); + log.log("initialVoice"); utterance.voice = initialVoice; } else if (publicationVoice) { - if (IS_DEV) console.log("publicationVoice"); + log.log("publicationVoice"); utterance.voice = publicationVoice; } else if (defaultVoice) { - if (IS_DEV) console.log("defaultVoice"); + log.log("defaultVoice"); utterance.voice = defaultVoice; } if (utterance.voice !== undefined && utterance.voice !== null) { utterance.lang = utterance.voice.lang; - if (IS_DEV) console.log("utterance.voice.lang", utterance.voice.lang); - if (IS_DEV) console.log("utterance.lang", utterance.lang); + log.log("utterance.voice.lang", utterance.voice.lang); + log.log("utterance.lang", utterance.lang); } - if (IS_DEV) console.log("navigator.language", navigator.language); + log.log("navigator.language", navigator.language); utterance.onboundary = (ev: SpeechSynthesisEvent) => { - console.log(ev.name); + log.log(ev.name); this.updateTTSInfo( ttsQueueItem, ev.charIndex, @@ -1169,24 +1165,22 @@ export class TTSModule2 implements ReaderModule { let txtToCheck = ttsQueueItemRef.item.combinedText; let charIndexAdjusted = charIndex; - if (IS_DEV) { - if (utteranceText !== txtToCheck) { - console.log( - "TTS utteranceText DIFF?? ", - `[[${utteranceText}]]`, - `[[${txtToCheck}]]` - ); - } - const ttsWord = utteranceText.substr(charIndex, charLength); - if (ttsWord !== word) { - console.log( - "TTS word DIFF?? ", - `[[${ttsWord}]]`, - `[[${word}]]`, - `${charIndex}--${charLength}`, - `${start}--${end - start}` - ); - } + if (utteranceText !== txtToCheck) { + log.log( + "TTS utteranceText DIFF?? ", + `[[${utteranceText}]]`, + `[[${txtToCheck}]]` + ); + } + const ttsWord = utteranceText.substr(charIndex, charLength); + if (ttsWord !== word) { + log.log( + "TTS word DIFF?? ", + `[[${ttsWord}]]`, + `[[${word}]]`, + `${charIndex}--${charLength}`, + `${start}--${end - start}` + ); } let acc = 0; @@ -1231,8 +1225,8 @@ export class TTSModule2 implements ReaderModule { return ""; } } catch (err) { - console.log("uniqueCssSelector:"); - console.log(err); + log.log("uniqueCssSelector:"); + log.error(err); return ""; } } diff --git a/src/modules/TTS/TTSSettings.ts b/src/modules/TTS/TTSSettings.ts index ea4e1b8f..3df893da 100644 --- a/src/modules/TTS/TTSSettings.ts +++ b/src/modules/TTS/TTSSettings.ts @@ -27,10 +27,10 @@ import { JSONable, } from "../../model/user-settings/UserProperties"; import * as HTMLUtilities from "../../utils/HTMLUtilities"; -import { IS_DEV } from "../../utils"; import { IFrameNavigator, ReaderRights } from "../../navigator/IFrameNavigator"; import { TextHighlighter } from "../highlight/TextHighlighter"; import { addEventListenerOptional } from "../../utils/EventHandler"; +import log from "loglevel"; export interface TTSModuleAPI { started: any; @@ -136,27 +136,27 @@ export class TTSSettings implements ITTSUserSettings { if (initialTTSSettings?.rate) { settings.rate = initialTTSSettings.rate; - if (IS_DEV) console.log(settings.rate); + log.log(settings.rate); } if (initialTTSSettings?.pitch) { settings.pitch = initialTTSSettings.pitch; - if (IS_DEV) console.log(settings.pitch); + log.log(settings.pitch); } if (initialTTSSettings?.volume) { settings.volume = initialTTSSettings.volume; - if (IS_DEV) console.log(settings.volume); + log.log(settings.volume); } if (initialTTSSettings?.color) { settings.color = initialTTSSettings.color; - if (IS_DEV) console.log(settings.color); + log.log(settings.color); } if (initialTTSSettings?.autoScroll) { settings.autoScroll = initialTTSSettings.autoScroll; - if (IS_DEV) console.log(settings.autoScroll); + log.log(settings.autoScroll); } if (initialTTSSettings?.voice) { settings.voice = initialTTSSettings.voice; - if (IS_DEV) console.log(settings.voice); + log.log(settings.voice); } } @@ -178,9 +178,7 @@ export class TTSSettings implements ITTSUserSettings { enableSplitter?: boolean; stop() { - if (IS_DEV) { - console.log("tts settings stop"); - } + log.log("tts settings stop"); } private initialise() { @@ -303,9 +301,7 @@ export class TTSSettings implements ITTSUserSettings { this.applyTTSSettings(ttsSettings); if (this.api?.updateSettings) { this.api?.updateSettings(ttsSettings).then(async (settings) => { - if (IS_DEV) { - console.log("api updated tts settings", settings); - } + log.log("api updated tts settings", settings); }); } } @@ -398,7 +394,7 @@ export class TTSSettings implements ITTSUserSettings { applyTTSSettings(ttsSettings: Partial) { if (ttsSettings.rate) { - if (IS_DEV) console.log("rate " + this.rate); + log.log("rate " + this.rate); this.rate = ttsSettings.rate; let prop = this.userProperties.getByRef(TTSREFS.RATE_REF); if (prop) { @@ -409,7 +405,7 @@ export class TTSSettings implements ITTSUserSettings { this.restartCallback(); } if (ttsSettings.pitch) { - if (IS_DEV) console.log("pitch " + this.pitch); + log.log("pitch " + this.pitch); this.pitch = ttsSettings.pitch; let prop = this.userProperties.getByRef(TTSREFS.PITCH_REF); if (prop) { @@ -420,7 +416,7 @@ export class TTSSettings implements ITTSUserSettings { this.restartCallback(); } if (ttsSettings.volume) { - if (IS_DEV) console.log("volume " + this.volume); + log.log("volume " + this.volume); this.volume = ttsSettings.volume; let prop = this.userProperties.getByRef(TTSREFS.VOLUME_REF); if (prop) { @@ -441,7 +437,7 @@ export class TTSSettings implements ITTSUserSettings { this.settingsChangeCallback(); } if (ttsSettings.autoScroll !== undefined) { - if (IS_DEV) console.log("autoScroll " + this.autoScroll); + log.log("autoScroll " + this.autoScroll); this.autoScroll = ttsSettings.autoScroll; let prop = this.userProperties.getByRef(TTSREFS.AUTO_SCROLL_REF); if (prop) { @@ -451,7 +447,7 @@ export class TTSSettings implements ITTSUserSettings { this.settingsChangeCallback(); } if (ttsSettings.voice) { - if (IS_DEV) console.log("voice " + this.voice); + log.log("voice " + this.voice); this.voice = ttsSettings.voice; let prop = this.userProperties.getByRef(TTSREFS.VOICE_REF); if (prop) { diff --git a/src/modules/citation/CitationModule.ts b/src/modules/citation/CitationModule.ts index 52d79360..8adfdb35 100644 --- a/src/modules/citation/CitationModule.ts +++ b/src/modules/citation/CitationModule.ts @@ -20,8 +20,8 @@ import { Publication } from "../../model/Publication"; import { IFrameNavigator } from "../../navigator/IFrameNavigator"; import { ReaderModule } from "../ReaderModule"; -import { IS_DEV } from "../../utils"; import { TextHighlighter } from "../highlight/TextHighlighter"; +import log from "loglevel"; export enum CitationStyle { Chicago = 0, @@ -80,9 +80,7 @@ export default class CitationModule implements ReaderModule { } async stop() { - if (IS_DEV) { - console.log("Timeline module stop"); - } + log.log("Timeline module stop"); } copyToClipboard(textToClipboard) { diff --git a/src/modules/highlight/LayerSettings.ts b/src/modules/highlight/LayerSettings.ts index 7d054a46..a6cf76c0 100644 --- a/src/modules/highlight/LayerSettings.ts +++ b/src/modules/highlight/LayerSettings.ts @@ -22,7 +22,7 @@ import { UserProperty, UserProperties, } from "../../model/user-settings/UserProperties"; -import { IS_DEV } from "../../utils"; +import log from "loglevel"; export interface LayerConfig { store: Store; @@ -47,9 +47,7 @@ export class LayerSettings implements ILayerSettings { } async stop() { - if (IS_DEV) { - console.log("MediaOverlay settings stop"); - } + log.log("MediaOverlay settings stop"); } private async initialize() { diff --git a/src/modules/highlight/TextHighlighter.ts b/src/modules/highlight/TextHighlighter.ts index 33a5cf65..db7fa47f 100644 --- a/src/modules/highlight/TextHighlighter.ts +++ b/src/modules/highlight/TextHighlighter.ts @@ -39,7 +39,6 @@ import { } from "./renderer/iframe/selection"; import { uniqueCssSelector } from "./renderer/common/cssselector2"; import { Annotation, AnnotationMarker } from "../../model/Locator"; -import { IS_DEV } from "../../utils"; import { icons, iconTemplateColored } from "../../utils/IconLib"; import { IFrameNavigator } from "../../navigator/IFrameNavigator"; import { TTSModule2 } from "../TTS/TTSModule2"; @@ -48,6 +47,7 @@ import * as lodash from "lodash"; import { LayerSettings } from "./LayerSettings"; import { Switchable } from "../../model/user-settings/UserProperties"; import { Popup } from "../search/Popup"; +import log from "loglevel"; export enum HighlightContainer { R2_ID_HIGHLIGHTS_CONTAINER = "R2_ID_HIGHLIGHTS_CONTAINER", @@ -1261,11 +1261,7 @@ export class TextHighlighter { self.delegate.annotationModule ?.updateAnnotation(anno) .then(async () => { - if (IS_DEV) { - console.log( - "update highlight " + anno.id - ); - } + log.log("update highlight " + anno.id); }); } }); @@ -1514,11 +1510,9 @@ export class TextHighlighter { return rect; } catch (error) { - if (IS_DEV) { - console.log("measureTextNode " + error); - console.log("measureTextNode " + node); - console.log(node.textContent); - } + log.log("measureTextNode " + error); + log.log("measureTextNode " + node); + log.log(`${node.textContent}`); } } @@ -2299,9 +2293,7 @@ export class TextHighlighter { const payload: IEventPayload_R2_EVENT_HIGHLIGHT_CLICK = { highlight: foundHighlight, }; - if (IS_DEV) { - console.log(payload); - } + log.log(JSON.stringify(payload)); let self = this; let anno; if (self.delegate.rights.enableAnnotations) { @@ -2321,9 +2313,7 @@ export class TextHighlighter { } if (anno?.id) { - if (IS_DEV) { - console.log("selected highlight " + anno.id); - } + log.log("selected highlight " + anno.id); self.lastSelectedHighlight = anno.id; let toolbox = document.getElementById("highlight-toolbox"); @@ -2352,9 +2342,7 @@ export class TextHighlighter { self.delegate.annotationModule ?.updateAnnotation(anno) .then(async () => { - if (IS_DEV) { - console.log("update highlight " + anno.id); - } + log.log("update highlight " + anno.id); if (toolbox) { toolbox.style.display = "none"; } @@ -2394,9 +2382,7 @@ export class TextHighlighter { self.delegate.annotationModule ?.deleteSelectedHighlight(anno) .then(async () => { - if (IS_DEV) { - console.log("delete highlight " + anno.id); - } + log.log("delete highlight " + anno.id); if (toolbox) { toolbox.style.display = "none"; } @@ -2406,9 +2392,7 @@ export class TextHighlighter { self.delegate.bookmarkModule ?.deleteSelectedHighlight(anno) .then(async () => { - if (IS_DEV) { - console.log("delete highlight " + anno.id); - } + log.log("delete highlight " + anno.id); if (toolbox) { toolbox.style.display = "none"; } @@ -2451,7 +2435,7 @@ export class TextHighlighter { let result = this.delegate.definitionsModule?.properties?.definitions?.filter( (el: any) => el.order === Number(foundElement?.dataset.order) )[0]; - console.log(result); + log.log(result); if (this.delegate.definitionsModule?.api?.click) { this.delegate.definitionsModule.api?.click( lodash.omit(result, "callbacks"), @@ -3092,9 +3076,7 @@ export class TextHighlighter { )) as Annotation; } - if (IS_DEV) { - console.log("selected highlight " + anno.id); - } + log.log("selected highlight " + anno.id); self.lastSelectedHighlight = anno.id; let toolbox = document.getElementById("highlight-toolbox"); @@ -3122,9 +3104,7 @@ export class TextHighlighter { self.delegate.annotationModule ?.updateAnnotation(anno) .then(async () => { - if (IS_DEV) { - console.log("update highlight " + anno.id); - } + log.log("update highlight " + anno.id); toolbox!!.style.display = "none"; self.selectionMenuClosed(); }); @@ -3158,9 +3138,7 @@ export class TextHighlighter { self.delegate.annotationModule ?.deleteSelectedHighlight(anno) .then(async () => { - if (IS_DEV) { - console.log("delete highlight " + anno.id); - } + log.log("delete highlight " + anno.id); toolbox!!.style.display = "none"; self.selectionMenuClosed(); }); @@ -3168,9 +3146,7 @@ export class TextHighlighter { self.delegate.bookmarkModule ?.deleteSelectedHighlight(anno) .then(async () => { - if (IS_DEV) { - console.log("delete highlight " + anno.id); - } + log.log("delete highlight " + anno.id); toolbox!!.style.display = "none"; self.selectionMenuClosed(); }); diff --git a/src/modules/highlight/common/rect-utils.ts b/src/modules/highlight/common/rect-utils.ts index 0ca5d948..e13a23a3 100644 --- a/src/modules/highlight/common/rect-utils.ts +++ b/src/modules/highlight/common/rect-utils.ts @@ -17,8 +17,7 @@ * Licensed to: Bokbasen AS and CAST under one or more contributor license agreements. */ -const IS_DEV = - process.env.NODE_ENV === "development" || process.env.NODE_ENV === "dev"; +import log from "loglevel"; export interface IRectSimple { height: number; @@ -75,28 +74,20 @@ export function getClientRectsNoOverlap_( const bigEnough = rect.width * rect.height > minArea; if (!bigEnough) { if (newRects.length > 1) { - if (IS_DEV) { - console.log("CLIENT RECT: remove small"); - } + log.log("CLIENT RECT: remove small"); newRects.splice(j, 1); } else { - if (IS_DEV) { - console.log("CLIENT RECT: remove small, but keep otherwise empty!"); - } + log.log("CLIENT RECT: remove small, but keep otherwise empty!"); break; } } } - if (IS_DEV) { - checkOverlaps(newRects); - } + checkOverlaps(newRects); - if (IS_DEV) { - console.log( - `CLIENT RECT: reduced ${originalRects.length} --> ${newRects.length}` - ); - } + log.log( + `CLIENT RECT: reduced ${originalRects.length} --> ${newRects.length}` + ); return newRects; } @@ -266,9 +257,7 @@ export function mergeTouchingRects( const rect1 = rects[i]; const rect2 = rects[j]; if (rect1 === rect2) { - if (IS_DEV) { - console.log("mergeTouchingRects rect1 === rect2 ??!"); - } + log.log("mergeTouchingRects rect1 === rect2 ??!"); continue; } @@ -289,12 +278,9 @@ export function mergeTouchingRects( const canMerge = aligned && rectsTouchOrOverlap(rect1, rect2, tolerance); if (canMerge) { - if (IS_DEV) { - // tslint:disable-next-line:max-line-length - console.log( - `CLIENT RECT: merging two into one, VERTICAL: ${rectsLineUpVertically} HORIZONTAL: ${rectsLineUpHorizontally} (${doNotMergeHorizontallyAlignedRects})` - ); - } + log.log( + `CLIENT RECT: merging two into one, VERTICAL: ${rectsLineUpVertically} HORIZONTAL: ${rectsLineUpHorizontally} (${doNotMergeHorizontallyAlignedRects})` + ); const newRects = rects.filter((rect) => { return rect !== rect1 && rect !== rect2; }); @@ -319,9 +305,7 @@ export function replaceOverlappingRects(rects: IRect[]): IRect[] { const rect1 = rects[i]; const rect2 = rects[j]; if (rect1 === rect2) { - if (IS_DEV) { - console.log("replaceOverlappingRects rect1 === rect2 ??!"); - } + log.log("replaceOverlappingRects rect1 === rect2 ??!"); continue; } @@ -352,18 +336,12 @@ export function replaceOverlappingRects(rects: IRect[]): IRect[] { } } - if (IS_DEV) { - const toCheck: IRect[] = []; - toCheck.push(toPreserve); - Array.prototype.push.apply(toCheck, toAdd); - checkOverlaps(toCheck); - } + const toCheck: IRect[] = []; + toCheck.push(toPreserve); + Array.prototype.push.apply(toCheck, toAdd); + checkOverlaps(toCheck); - if (IS_DEV) { - console.log( - `CLIENT RECT: overlap, cut one rect into ${toAdd.length}` - ); - } + log.log(`CLIENT RECT: overlap, cut one rect into ${toAdd.length}`); const newRects = rects.filter((rect) => { return rect !== toRemove; }); @@ -400,9 +378,7 @@ export function removeContainedRects( for (const rect of rects) { const bigEnough = rect.width > 1 && rect.height > 1; if (!bigEnough) { - if (IS_DEV) { - console.log("CLIENT RECT: remove tiny"); - } + log.log("CLIENT RECT: remove tiny"); rectsToKeep.delete(rect); continue; } @@ -414,9 +390,7 @@ export function removeContainedRects( continue; } if (rectContains(possiblyContainingRect, rect, tolerance)) { - if (IS_DEV) { - console.log("CLIENT RECT: remove contained"); - } + log.log("CLIENT RECT: remove contained"); rectsToKeep.delete(rect); break; } @@ -446,30 +420,26 @@ export function checkOverlaps(rects: IRect[]) { if (!has2) { stillOverlappingRects.push(rect2); } - if (IS_DEV) { - console.log("CLIENT RECT: overlap ---"); - // tslint:disable-next-line:max-line-length - console.log( - `#1 TOP:${rect1.top} BOTTOM:${rect1.bottom} LEFT:${rect1.left} RIGHT:${rect1.right} WIDTH:${rect1.width} HEIGHT:${rect1.height}` - ); - // tslint:disable-next-line:max-line-length - console.log( - `#2 TOP:${rect2.top} BOTTOM:${rect2.bottom} LEFT:${rect2.left} RIGHT:${rect2.right} WIDTH:${rect2.width} HEIGHT:${rect2.height}` - ); - - const xOverlap = getRectOverlapX(rect1, rect2); - console.log(`xOverlap: ${xOverlap}`); - - const yOverlap = getRectOverlapY(rect1, rect2); - console.log(`yOverlap: ${yOverlap}`); - } + log.log("CLIENT RECT: overlap ---"); + // tslint:disable-next-line:max-line-length + log.log( + `#1 TOP:${rect1.top} BOTTOM:${rect1.bottom} LEFT:${rect1.left} RIGHT:${rect1.right} WIDTH:${rect1.width} HEIGHT:${rect1.height}` + ); + // tslint:disable-next-line:max-line-length + log.log( + `#2 TOP:${rect2.top} BOTTOM:${rect2.bottom} LEFT:${rect2.left} RIGHT:${rect2.right} WIDTH:${rect2.width} HEIGHT:${rect2.height}` + ); + + const xOverlap = getRectOverlapX(rect1, rect2); + log.log(`xOverlap: ${xOverlap}`); + + const yOverlap = getRectOverlapY(rect1, rect2); + log.log(`yOverlap: ${yOverlap}`); } } } } if (stillOverlappingRects.length) { - if (IS_DEV) { - console.log(`CLIENT RECT: overlaps ${stillOverlappingRects.length}`); - } + log.log(`CLIENT RECT: overlaps ${stillOverlappingRects.length}`); } } diff --git a/src/modules/highlight/common/selection.ts b/src/modules/highlight/common/selection.ts index 63c39d17..070ceb71 100644 --- a/src/modules/highlight/common/selection.ts +++ b/src/modules/highlight/common/selection.ts @@ -17,13 +17,13 @@ * Licensed to: Bokbasen AS and CAST under one or more contributor license agreements. */ -import { IS_DEV } from "../../../utils"; - // https://developer.mozilla.org/en-US/docs/Web/API/Selection // https://developer.mozilla.org/en-US/docs/Web/API/Range // A serializable mapping with DOM Range // (simply encodes a CSS Selector for element, and if text node, then encodes its parent element) +import log from "loglevel"; + export interface IRangeInfo { // always references an element, // either Range.startContainer if its nodeType == Node.ELEMENT_NODE @@ -99,15 +99,11 @@ export function sameSelections( return false; } if (sel1.cleanText !== sel2.cleanText) { - if (IS_DEV) { - console.log("SAME RANGES BUT DIFFERENT CLEAN TEXT??"); - } + log.log("SAME RANGES BUT DIFFERENT CLEAN TEXT??"); return false; } if (sel1.rawText !== sel2.rawText) { - if (IS_DEV) { - console.log("SAME RANGES BUT DIFFERENT RAW TEXT??"); - } + log.log("SAME RANGES BUT DIFFERENT RAW TEXT??"); return false; } return true; diff --git a/src/modules/highlight/renderer/iframe/selection.ts b/src/modules/highlight/renderer/iframe/selection.ts index 2af173ee..a21680c0 100644 --- a/src/modules/highlight/renderer/iframe/selection.ts +++ b/src/modules/highlight/renderer/iframe/selection.ts @@ -18,9 +18,7 @@ */ import { IRangeInfo, ISelectionInfo } from "../../common/selection"; - -const IS_DEV = - process.env.NODE_ENV === "development" || process.env.NODE_ENV === "dev"; +import log from "loglevel"; // https://developer.mozilla.org/en-US/docs/Web/API/Selection @@ -41,18 +39,14 @@ export function getCurrentSelectionInfo( return undefined; } if (selection.isCollapsed) { - if (IS_DEV) { - console.log("^^^ SELECTION COLLAPSED."); - } + log.log("^^^ SELECTION COLLAPSED."); return undefined; } const rawText = selection.toString(); const cleanText = rawText.trim().replace(/\n/g, " ").replace(/\s\s+/g, " "); if (cleanText.length === 0) { - if (IS_DEV) { - console.log("^^^ SELECTION TEXT EMPTY."); - } + log.log("^^^ SELECTION TEXT EMPTY."); return undefined; } @@ -69,57 +63,41 @@ export function getCurrentSelectionInfo( selection.focusOffset ); if (!r || r.collapsed) { - if (IS_DEV) { - console.log( - "$$$$$$$$$$$$$$$$$ CANNOT GET NON-COLLAPSED SELECTION RANGE?!" - ); - } + log.log("$$$$$$$$$$$$$$$$$ CANNOT GET NON-COLLAPSED SELECTION RANGE?!"); return undefined; } const range = normalizeRange(r); - if (IS_DEV) { - if (range.startContainer !== r.startContainer) { - if (IS_DEV) { - console.log( - ">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: startContainer" - ); - console.log(range.startContainer); - console.log(r.startContainer); - } - } - if (range.startOffset !== r.startOffset) { - if (IS_DEV) { - console.log( - ">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: startOffset" - ); - console.log(`${range.startOffset} !== ${r.startOffset}`); - } - } - if (range.endContainer !== r.endContainer) { - if (IS_DEV) { - console.log( - ">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: endContainer" - ); - console.log(range.endContainer); - console.log(r.endContainer); - } - } - if (range.endOffset !== r.endOffset) { - if (IS_DEV) { - console.log( - ">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: endOffset" - ); - console.log(`${range.endOffset} !== ${r.endOffset}`); - } - } + if (range.startContainer !== r.startContainer) { + log.log( + ">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: startContainer" + ); + log.log(range.startContainer); + log.log(r.startContainer); + } + if (range.startOffset !== r.startOffset) { + log.log( + ">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: startOffset" + ); + log.log(`${range.startOffset} !== ${r.startOffset}`); + } + if (range.endContainer !== r.endContainer) { + log.log( + ">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: endContainer" + ); + log.log(range.endContainer); + log.log(r.endContainer); + } + if (range.endOffset !== r.endOffset) { + log.log( + ">>>>>>>>>>>>>>>>>>>>>>> SELECTION RANGE NORMALIZE diff: endOffset" + ); + log.log(`${range.endOffset} !== ${r.endOffset}`); } const rangeInfo = convertRange(range, getCssSelector); if (!rangeInfo) { - if (IS_DEV) { - console.log("^^^ SELECTION RANGE INFO FAIL?!"); - } + log.log("^^^ SELECTION RANGE INFO FAIL?!"); return undefined; } @@ -140,28 +118,20 @@ export function createOrderedRange( range.setStart(startNode, startOffset); range.setEnd(endNode, endOffset); if (!range.collapsed) { - if (IS_DEV) { - console.log(">>> createOrderedRange RANGE OK"); - } + log.log(">>> createOrderedRange RANGE OK"); return range; } - if (IS_DEV) { - console.log(">>> createOrderedRange COLLAPSED ... RANGE REVERSE?"); - } + log.log(">>> createOrderedRange COLLAPSED ... RANGE REVERSE?"); const rangeReverse = new Range(); // document.createRange() rangeReverse.setStart(endNode, endOffset); rangeReverse.setEnd(startNode, startOffset); if (!rangeReverse.collapsed) { - if (IS_DEV) { - console.log(">>> createOrderedRange RANGE REVERSE OK."); - } + log.log(">>> createOrderedRange RANGE REVERSE OK."); return range; } - if (IS_DEV) { - console.log(">>> createOrderedRange RANGE REVERSE ALSO COLLAPSED?!"); - } + log.log(">>> createOrderedRange RANGE REVERSE ALSO COLLAPSED?!"); return undefined; } catch (err) { console.warn(err.message); @@ -221,9 +191,7 @@ export function convertRange( range.endContainer ); if (!commonElementAncestor) { - if (IS_DEV) { - console.log("^^^ NO RANGE COMMON ANCESTOR?!"); - } + log.log("^^^ NO RANGE COMMON ANCESTOR?!"); return undefined; } if (range.commonAncestorContainer) { @@ -236,11 +204,9 @@ export function convertRange( rangeCommonAncestorElement.nodeType === Node.ELEMENT_NODE ) { if (commonElementAncestor !== rangeCommonAncestorElement) { - if (IS_DEV) { - console.log(">>>>>> COMMON ANCESTOR CONTAINER DIFF??!"); - console.log(getCssSelector(commonElementAncestor)); - console.log(getCssSelector(rangeCommonAncestorElement as Element)); - } + log.log(">>>>>> COMMON ANCESTOR CONTAINER DIFF??!"); + log.log(getCssSelector(commonElementAncestor)); + log.log(getCssSelector(rangeCommonAncestorElement as Element)); } } } @@ -268,9 +234,7 @@ export function convertRangeInfo( rangeInfo.startContainerElementCssSelector ); if (!startElement) { - if (IS_DEV) { - console.log("^^^ convertRangeInfo NO START ELEMENT CSS SELECTOR?!"); - } + log.log("^^^ convertRangeInfo NO START ELEMENT CSS SELECTOR?!"); return undefined; } let startContainer: Node = startElement; @@ -279,21 +243,17 @@ export function convertRangeInfo( rangeInfo.startContainerChildTextNodeIndex >= startElement.childNodes.length ) { - if (IS_DEV) { - console.log( - "^^^ convertRangeInfo rangeInfo.startContainerChildTextNodeIndex >= startElement.childNodes.length?!" - ); - } + log.log( + "^^^ convertRangeInfo rangeInfo.startContainerChildTextNodeIndex >= startElement.childNodes.length?!" + ); return undefined; } startContainer = startElement.childNodes[rangeInfo.startContainerChildTextNodeIndex]; if (startContainer.nodeType !== Node.TEXT_NODE) { - if (IS_DEV) { - console.log( - "^^^ convertRangeInfo startContainer.nodeType !== Node.TEXT_NODE?!" - ); - } + log.log( + "^^^ convertRangeInfo startContainer.nodeType !== Node.TEXT_NODE?!" + ); return undefined; } } @@ -301,9 +261,7 @@ export function convertRangeInfo( rangeInfo.endContainerElementCssSelector ); if (!endElement) { - if (IS_DEV) { - console.log("^^^ convertRangeInfo NO END ELEMENT CSS SELECTOR?!"); - } + log.log("^^^ convertRangeInfo NO END ELEMENT CSS SELECTOR?!"); return undefined; } let endContainer: Node = endElement; @@ -311,21 +269,17 @@ export function convertRangeInfo( if ( rangeInfo.endContainerChildTextNodeIndex >= endElement.childNodes.length ) { - if (IS_DEV) { - console.log( - "^^^ convertRangeInfo rangeInfo.endContainerChildTextNodeIndex >= endElement.childNodes.length?!" - ); - } + log.log( + "^^^ convertRangeInfo rangeInfo.endContainerChildTextNodeIndex >= endElement.childNodes.length?!" + ); return undefined; } endContainer = endElement.childNodes[rangeInfo.endContainerChildTextNodeIndex]; if (endContainer.nodeType !== Node.TEXT_NODE) { - if (IS_DEV) { - console.log( - "^^^ convertRangeInfo endContainer.nodeType !== Node.TEXT_NODE?!" - ); - } + log.log( + "^^^ convertRangeInfo endContainer.nodeType !== Node.TEXT_NODE?!" + ); return undefined; } } diff --git a/src/modules/history/HistoryModule.ts b/src/modules/history/HistoryModule.ts index a98d0460..887cadd2 100644 --- a/src/modules/history/HistoryModule.ts +++ b/src/modules/history/HistoryModule.ts @@ -17,7 +17,6 @@ * Licensed to: Allvit under one or more contributor license agreements. */ -import { IS_DEV } from "../../utils"; import { IFrameNavigator } from "../../navigator/IFrameNavigator"; import { ReaderModule } from "../ReaderModule"; import * as HTMLUtilities from "../../utils/HTMLUtilities"; @@ -28,6 +27,7 @@ import { import { Locator, ReadingPosition } from "../../model/Locator"; import { Publication } from "../../model/Publication"; import Annotator from "../../store/Annotator"; +import log from "loglevel"; export interface HistoryModuleProperties { hideLayer?: boolean; @@ -79,9 +79,7 @@ export class HistoryModule implements ReaderModule { } async stop() { - if (IS_DEV) { - console.log("Page Break module stop"); - } + log.log("Page Break module stop"); removeEventListenerOptional( this.historyForwardAnchorElement, "click", @@ -150,8 +148,8 @@ export class HistoryModule implements ReaderModule { const linkHref = this.publication.getAbsoluteHref( lastReadingPosition.href ); - if (IS_DEV) console.log(lastReadingPosition.href); - if (IS_DEV) console.log(linkHref); + log.log(lastReadingPosition.href); + log.log(linkHref); lastReadingPosition.href = linkHref; this.history.push(lastReadingPosition); diff --git a/src/modules/linefocus/LineFocusModule.ts b/src/modules/linefocus/LineFocusModule.ts index 5ffb6307..30c75468 100644 --- a/src/modules/linefocus/LineFocusModule.ts +++ b/src/modules/linefocus/LineFocusModule.ts @@ -20,7 +20,6 @@ import { Publication } from "../../model/Publication"; import { IFrameNavigator } from "../../navigator/IFrameNavigator"; import { ReaderModule } from "../ReaderModule"; -import { IS_DEV } from "../../utils"; import { TextHighlighter, CLASS_HIGHLIGHT_AREA, @@ -39,6 +38,7 @@ import { addEventListenerOptional, removeEventListenerOptional, } from "../../utils/EventHandler"; +import log from "loglevel"; const DEFAULT_BACKGROUND_COLOR_OPACITY = 0.5; @@ -99,9 +99,7 @@ export default class LineFocusModule implements ReaderModule { } async stop() { - if (IS_DEV) { - console.log("Definitions module stop"); - } + log.log("Definitions module stop"); this.hasEventListener = false; removeEventListenerOptional(document, "keydown", this.keydown.bind(this)); removeEventListenerOptional(document, "keyup", this.keyup.bind(this)); @@ -691,11 +689,9 @@ export default class LineFocusModule implements ReaderModule { range.detach(); // frees up memory in older browsers return rect; } catch (error) { - if (IS_DEV) { - console.log("measureTextNode " + error); - console.log("measureTextNode " + node); - console.log(node.textContent); - } + log.log("measureTextNode " + error); + log.log("measureTextNode " + node); + log.log(`${node.textContent}`); } } measureImageNodes(node: Element): any { @@ -707,11 +703,9 @@ export default class LineFocusModule implements ReaderModule { range.detach(); // frees up memory in older browsers return rect; } catch (error) { - if (IS_DEV) { - console.log("measureTextNode " + error); - console.log("measureTextNode " + node); - console.log(node.textContent); - } + log.log("measureTextNode " + error); + log.log("measureTextNode " + node); + log.log(`${node.textContent}`); } } } diff --git a/src/modules/mediaoverlays/MediaOverlayModule.ts b/src/modules/mediaoverlays/MediaOverlayModule.ts index 0c4bd43c..ee580ddb 100644 --- a/src/modules/mediaoverlays/MediaOverlayModule.ts +++ b/src/modules/mediaoverlays/MediaOverlayModule.ts @@ -17,7 +17,6 @@ * Licensed to: Bibliotheca LLC under one or more contributor license agreements. */ -import { IS_DEV } from "../../utils"; import { Publication } from "../../model/Publication"; import { IFrameNavigator } from "../../navigator/IFrameNavigator"; import { ReaderModule } from "../ReaderModule"; @@ -25,10 +24,11 @@ import { Link } from "../../model/Link"; import { MediaOverlayNode } from "r2-shared-js/dist/es6-es2015/src/models/media-overlay"; import { TaJsonDeserialize } from "../../utils/JsonUtil"; import { - R2_MO_CLASS_ACTIVE, MediaOverlaySettings, + R2_MO_CLASS_ACTIVE, } from "./MediaOverlaySettings"; import * as HTMLUtilities from "../../utils/HTMLUtilities"; +import log from "loglevel"; // Media Overlays // Synchronized Narration @@ -111,12 +111,12 @@ export class MediaOverlayModule implements ReaderModule { } stop() { - if (IS_DEV) console.log("MediaOverlay module stop"); + log.log("MediaOverlay module stop"); } protected start() { this.delegate.mediaOverlayModule = this; - if (IS_DEV) console.log("MediaOverlay module start"); + log.log("MediaOverlay module start"); } async initialize() { @@ -155,7 +155,7 @@ export class MediaOverlayModule implements ReaderModule { return; } if (!response.ok) { - if (IS_DEV) console.log("BAD RESPONSE?!"); + log.log("BAD RESPONSE?!"); } let moJson: any | undefined; @@ -165,7 +165,7 @@ export class MediaOverlayModule implements ReaderModule { console.error(e); } if (!moJson) { - if (IS_DEV) console.log("## moJson" + moJson); + log.log("## moJson" + moJson); return; } @@ -260,7 +260,7 @@ export class MediaOverlayModule implements ReaderModule { mo: MediaOverlayNode, textFragmentIDChain: Array | undefined ): MediaOverlayNode | undefined | null { - if (IS_DEV) console.log("findDepthFirstTextAudioPair()"); + log.log("findDepthFirstTextAudioPair()"); let isTextUrlMatch: boolean | undefined; let isFragmentIDMatch: boolean | undefined; @@ -284,23 +284,18 @@ export class MediaOverlayModule implements ReaderModule { } } - if (IS_DEV) { - console.log("isFragmentIDMatch: " + isFragmentIDMatch); - console.log("isTextUrlMatch: " + isTextUrlMatch); - } + log.log("isFragmentIDMatch: " + isFragmentIDMatch); + log.log("isTextUrlMatch: " + isTextUrlMatch); if (!mo.Children || !mo.Children.length) { - if (IS_DEV) - console.log("findDepthFirstTextAudioPair() - leaf text/audio pair"); + log.log("findDepthFirstTextAudioPair() - leaf text/audio pair"); if (!isTextUrlMatch) { - if (IS_DEV) - console.log("findDepthFirstTextAudioPair() - leaf - !isTextUrlMatch"); + log.log("findDepthFirstTextAudioPair() - leaf - !isTextUrlMatch"); return undefined; } if (isFragmentIDMatch || (isTextUrlMatch && !textFragmentIDChain)) { - if (IS_DEV) - console.log( - "findDepthFirstTextAudioPair() - leaf - isFragmentIDMatch || (isTextUrlMatch && !textFragmentIDChain" - ); + log.log( + "findDepthFirstTextAudioPair() - leaf - isFragmentIDMatch || (isTextUrlMatch && !textFragmentIDChain" + ); return mo; } return undefined; @@ -308,38 +303,27 @@ export class MediaOverlayModule implements ReaderModule { const textFragmentIDChainOriginal = textFragmentIDChain; let frags = textFragmentIDChain; for (const child of mo.Children) { - if (IS_DEV) { - console.log("findDepthFirstTextAudioPair() - child"); - console.log(JSON.stringify(child)); - } + log.log("findDepthFirstTextAudioPair() - child"); + log.log(JSON.stringify(child)); const match = this.findDepthFirstTextAudioPair(textHref, child, frags); if (match === null) { - if (IS_DEV) { - console.log( - "findDepthFirstTextAudioPair() - child - match null (skip)" - ); - } + log.log("findDepthFirstTextAudioPair() - child - match null (skip)"); frags = undefined; } if (match) { - if (IS_DEV) { - console.log("findDepthFirstTextAudioPair() - child - match"); - console.log(JSON.stringify(match)); - } + log.log("findDepthFirstTextAudioPair() - child - match"); + log.log(JSON.stringify(match)); return match; } } if (isFragmentIDMatch) { - if (IS_DEV) - console.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch"); + log.log("findDepthFirstTextAudioPair() - post isFragmentIDMatch"); const match = this.findDepthFirstTextAudioPair(textHref, mo, undefined); if (match) { - if (IS_DEV) { - console.log( - "findDepthFirstTextAudioPair() - post isFragmentIDMatch - match" - ); - console.log(JSON.stringify(match)); - } + log.log( + "findDepthFirstTextAudioPair() - post isFragmentIDMatch - match" + ); + log.log(JSON.stringify(match)); return match; } else { return match; @@ -360,7 +344,7 @@ export class MediaOverlayModule implements ReaderModule { this.currentAudioEnd && this.audioElement.currentTime >= this.currentAudioEnd - 0.05 ) { - if (IS_DEV) console.log("ontimeupdate - mediaOverlaysNext()"); + log.log("ontimeupdate - mediaOverlaysNext()"); this.mediaOverlaysNext(); } const match_i = this.mediaOverlayTextAudioPair.Text.lastIndexOf("#"); @@ -376,7 +360,7 @@ export class MediaOverlayModule implements ReaderModule { } mediaOverlaysNext(escape?: boolean) { - if (IS_DEV) console.log("mediaOverlaysNext()"); + log.log("mediaOverlaysNext()"); if (this.mediaOverlayRoot && this.mediaOverlayTextAudioPair) { const nextTextAudioPair = this.findNextTextAudioPair( @@ -386,7 +370,7 @@ export class MediaOverlayModule implements ReaderModule { escape ? true : false ); if (!nextTextAudioPair) { - if (IS_DEV) console.log("mediaOverlaysNext() - navLeftOrRight()"); + log.log("mediaOverlaysNext() - navLeftOrRight()"); this.mediaOverlaysStop(); if (this.currentLinks.length > 1 && this.currentLinkIndex === 0) { @@ -411,22 +395,19 @@ export class MediaOverlayModule implements ReaderModule { "https://dita.digital/" + nextTextAudioPair.Text ); if (hrefUrlObj1.pathname !== hrefUrlObj2.pathname) { - if (IS_DEV) { - console.log( - "mediaOverlaysNext() SWITCH! " + - hrefUrlObj1.pathname + - " != " + - hrefUrlObj2.pathname - ); - } + log.log( + "mediaOverlaysNext() SWITCH! " + + hrefUrlObj1.pathname + + " != " + + hrefUrlObj2.pathname + ); switchDoc = true; } } if (switchDoc) { this.mediaOverlaysStop(); } else { - if (IS_DEV) - console.log("mediaOverlaysNext() - playMediaOverlaysAudio()"); + log.log("mediaOverlaysNext() - playMediaOverlaysAudio()"); setTimeout(async () => { await this.playMediaOverlaysAudio( nextTextAudioPair, @@ -437,7 +418,7 @@ export class MediaOverlayModule implements ReaderModule { } } } else { - if (IS_DEV) console.log("mediaOverlaysNext() - navLeftOrRight() 2"); + log.log("mediaOverlaysNext() - navLeftOrRight() 2"); this.mediaOverlaysStop(); if (this.currentLinks.length > 1 && this.currentLinkIndex === 0) { @@ -455,7 +436,7 @@ export class MediaOverlayModule implements ReaderModule { } } mediaOverlaysStop() { - if (IS_DEV) console.log("mediaOverlaysStop()"); + log.log("mediaOverlaysStop()"); this.mediaOverlaysPause(); @@ -463,7 +444,7 @@ export class MediaOverlayModule implements ReaderModule { this.mediaOverlayTextAudioPair = undefined; } mediaOverlaysPause() { - if (IS_DEV) console.log("mediaOverlaysPause()"); + log.log("mediaOverlaysPause()"); this.mediaOverlayHighlight(undefined); @@ -479,22 +460,17 @@ export class MediaOverlayModule implements ReaderModule { ): MediaOverlayNode | undefined | null { if (!mo.Children || !mo.Children.length) { if (previousMo?.prev === moToMatch) { - if (IS_DEV) - console.log("findNextTextAudioPair() - prevMo === moToMatch"); + log.log("findNextTextAudioPair() - prevMo === moToMatch"); return mo; } - if (IS_DEV) { - console.log("findNextTextAudioPair() - set previous"); - console.log(JSON.stringify(mo)); - } + log.log("findNextTextAudioPair() - set previous"); + log.log(JSON.stringify(mo)); previousMo.prev = mo; return undefined; } for (const child of mo.Children) { - if (IS_DEV) { - console.log("findNextTextAudioPair() - child"); - console.log(JSON.stringify(child)); - } + log.log("findNextTextAudioPair() - child"); + log.log(JSON.stringify(child)); const match = this.findNextTextAudioPair( child, moToMatch, @@ -502,10 +478,8 @@ export class MediaOverlayModule implements ReaderModule { escape ); if (match) { - if (IS_DEV) { - console.log("findNextTextAudioPair() - match"); - console.log(JSON.stringify(match)); - } + log.log("findNextTextAudioPair() - match"); + log.log(JSON.stringify(match)); return match; } } @@ -516,7 +490,7 @@ export class MediaOverlayModule implements ReaderModule { begin: number | undefined, end: number | undefined ) { - if (IS_DEV) console.log("playMediaOverlaysAudio()"); + log.log("playMediaOverlaysAudio()"); this.mediaOverlayTextAudioPair = moTextAudioPair; @@ -550,14 +524,14 @@ export class MediaOverlayModule implements ReaderModule { try { this.currentAudioBegin = parseFloat(b); } catch (err) { - console.log(err); + log.error(err); } if (matches.length >= 3) { const e = matches[3]; try { this.currentAudioEnd = parseFloat(e); } catch (err) { - console.log(err); + log.error(err); } } } @@ -566,11 +540,9 @@ export class MediaOverlayModule implements ReaderModule { this.currentAudioBegin = begin; this.currentAudioEnd = end; } - if (IS_DEV) { - console.log( - `${urlFull} => [${this.currentAudioBegin}-${this.currentAudioEnd}]` - ); - } + log.log( + `${urlFull} => [${this.currentAudioBegin}-${this.currentAudioEnd}]` + ); const playClip = async (initial: boolean) => { if (!this.audioElement) { @@ -583,11 +555,9 @@ export class MediaOverlayModule implements ReaderModule { (initial && !timeToSeekTo) || this.audioElement.currentTime === timeToSeekTo ) { - if (IS_DEV) { - console.log( - "playMediaOverlaysAudio() - playClip() - _currentAudioElement.play()" - ); - } + log.log( + "playMediaOverlaysAudio() - playClip() - _currentAudioElement.play()" + ); this.ensureOnTimeUpdate(false, false); this.audioElement.playbackRate = this.settings.rate; this.audioElement.volume = this.settings.volume; @@ -607,22 +577,16 @@ export class MediaOverlayModule implements ReaderModule { checkReady(); } } else { - if (IS_DEV) { - console.log( - "playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked" - ); - } + log.log("playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked"); const ontimeupdateSeeked = async (_ev: Event) => { this.audioElement.removeEventListener( "timeupdate", ontimeupdateSeeked ); - if (IS_DEV) { - console.log( - "playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked - .play()" - ); - } + log.log( + "playMediaOverlaysAudio() - playClip() - ontimeupdateSeeked - .play()" + ); this.ensureOnTimeUpdate(false, false); if (this.audioElement) { this.audioElement.playbackRate = this.settings.rate; @@ -656,17 +620,11 @@ export class MediaOverlayModule implements ReaderModule { this.audioElement.currentTime >= timeToSeekTo - 0.1; this.ensureOnTimeUpdate(false, false); if (contiguous) { - if (IS_DEV) { - console.log( - "playMediaOverlaysAudio() - playClip() - ensureOnTimeUpdate" - ); - } + log.log("playMediaOverlaysAudio() - playClip() - ensureOnTimeUpdate"); } else { - if (IS_DEV) { - console.log( - "playMediaOverlaysAudio() - playClip() - currentTime = timeToSeekTo" - ); - } + log.log( + "playMediaOverlaysAudio() - playClip() - currentTime = timeToSeekTo" + ); this.audioElement.currentTime = timeToSeekTo; } } @@ -675,14 +633,12 @@ export class MediaOverlayModule implements ReaderModule { this.previousAudioUrl = this.currentAudioUrl; if (!this.currentAudioUrl || urlNoQuery !== this.currentAudioUrl) { this.currentAudioUrl = urlNoQuery; - if (IS_DEV) { - console.log( - "playMediaOverlaysAudio() - RESET: " + - this.previousAudioUrl + - " => " + - this.currentAudioUrl - ); - } + log.log( + "playMediaOverlaysAudio() - RESET: " + + this.previousAudioUrl + + " => " + + this.currentAudioUrl + ); this.audioElement = document.getElementById( "AUDIO_MO_ID" @@ -705,7 +661,7 @@ export class MediaOverlayModule implements ReaderModule { document.body.appendChild(this.audioElement); this.audioElement.addEventListener("error", (ev) => { - console.log( + log.log( "-1) error: " + (this.currentAudioUrl !== (ev.currentTarget as HTMLAudioElement).src ? this.currentAudioUrl + " -- " @@ -720,8 +676,8 @@ export class MediaOverlayModule implements ReaderModule { // 2 === MEDIA_ERR_NETWORK // 3 === MEDIA_ERR_DECODE // 4 === MEDIA_ERR_SRC_NOT_SUPPORTED - console.log(this.audioElement.error.code); - console.log(this.audioElement.error.message); + log.log(this.audioElement.error.code); + log.log(this.audioElement.error.message); } }); @@ -731,13 +687,13 @@ export class MediaOverlayModule implements ReaderModule { "canplaythrough", oncanplaythrough ); - if (IS_DEV) console.log("oncanplaythrough"); + log.log("oncanplaythrough"); await playClip(true); }; this.audioElement.addEventListener("canplaythrough", oncanplaythrough); const onended = async (_ev: Event) => { - if (IS_DEV) console.log("onended"); + log.log("onended"); if (this.currentLinks.length > 1 && this.currentLinkIndex === 0) { this.currentLinkIndex++; await this.playLink(); @@ -755,7 +711,7 @@ export class MediaOverlayModule implements ReaderModule { this.audioElement.playbackRate = this.settings.rate; this.audioElement.setAttribute("src", this.currentAudioUrl); } else { - if (IS_DEV) console.log("playMediaOverlaysAudio() - playClip()"); + log.log("playMediaOverlaysAudio() - playClip()"); await playClip(false); } } @@ -764,7 +720,7 @@ export class MediaOverlayModule implements ReaderModule { rootMo: MediaOverlayNode, textFragmentIDChain: Array | undefined ) { - if (IS_DEV) console.log("playMediaOverlays()"); + log.log("playMediaOverlays()"); let textFragmentIDChain_ = textFragmentIDChain ? textFragmentIDChain.filter((id) => id) @@ -779,13 +735,11 @@ export class MediaOverlayModule implements ReaderModule { textFragmentIDChain_ ); if (!moTextAudioPair && textFragmentIDChain_) { - if (IS_DEV) { - console.log( - "playMediaOverlays() - findDepthFirstTextAudioPair() SECOND CHANCE " - ); - console.log(JSON.stringify(textFragmentIDChain_, null, 4)); - console.log(JSON.stringify(rootMo, null, 4)); - } + log.log( + "playMediaOverlays() - findDepthFirstTextAudioPair() SECOND CHANCE " + ); + log.log(JSON.stringify(textFragmentIDChain_, null, 4)); + log.log(JSON.stringify(rootMo, null, 4)); moTextAudioPair = this.findDepthFirstTextAudioPair( textHref, rootMo, @@ -794,8 +748,7 @@ export class MediaOverlayModule implements ReaderModule { } if (moTextAudioPair) { if (moTextAudioPair.Audio) { - if (IS_DEV) - console.log("playMediaOverlays() - playMediaOverlaysAudio()"); + log.log("playMediaOverlays() - playMediaOverlaysAudio()"); this.mediaOverlayRoot = rootMo; await this.playMediaOverlaysAudio( moTextAudioPair, @@ -804,12 +757,11 @@ export class MediaOverlayModule implements ReaderModule { ); } } else { - if (IS_DEV) - console.log("playMediaOverlays() - !moTextAudioPair " + textHref); + log.log("playMediaOverlays() - !moTextAudioPair " + textHref); } } ontimeupdate = async (_v: Event) => { - if (IS_DEV) console.log("ontimeupdate"); + log.log("ontimeupdate"); this.trackCurrentTime(); }; ensureOnTimeUpdate = (remove: boolean, replace: boolean) => { @@ -839,7 +791,7 @@ export class MediaOverlayModule implements ReaderModule { }; mediaOverlayHighlight(id: string | undefined) { - if (IS_DEV) console.log("moHighlight: ## " + id); + log.log("moHighlight: ## " + id); let classActive = this.publication.Metadata?.MediaOverlay?.ActiveClass; if (!classActive) { classActive = this.settings.color; diff --git a/src/modules/mediaoverlays/MediaOverlaySettings.ts b/src/modules/mediaoverlays/MediaOverlaySettings.ts index 4aa9131b..96d93fc3 100644 --- a/src/modules/mediaoverlays/MediaOverlaySettings.ts +++ b/src/modules/mediaoverlays/MediaOverlaySettings.ts @@ -26,12 +26,13 @@ import { Incremental, } from "../../model/user-settings/UserProperties"; import * as HTMLUtilities from "../../utils/HTMLUtilities"; -import { IS_DEV } from "../../utils"; + import { addEventListenerOptional } from "../../utils/EventHandler"; import { MediaOverlayModuleAPI, MediaOverlayModuleProperties, } from "./MediaOverlayModule"; +import log from "loglevel"; export const R2_MO_CLASS_ACTIVE = "r2-mo-active"; @@ -104,27 +105,27 @@ export class MediaOverlaySettings implements IMediaOverlayUserSettings { let initialSettings = config.initialMediaOverlaySettings; if (initialSettings?.color) { settings.color = initialSettings.color; - if (IS_DEV) console.log(settings.color); + log.log(settings.color); } if (initialSettings?.autoScroll) { settings.autoScroll = initialSettings.autoScroll; - if (IS_DEV) console.log(settings.autoScroll); + log.log(settings.autoScroll); } if (initialSettings?.autoTurn) { settings.autoTurn = initialSettings.autoTurn; - if (IS_DEV) console.log(settings.autoTurn); + log.log(settings.autoScroll); } if (initialSettings?.volume) { settings.volume = initialSettings.volume; - if (IS_DEV) console.log(settings.volume); + log.log(settings.volume); } if (initialSettings?.rate) { settings.rate = initialSettings.rate; - if (IS_DEV) console.log(settings.rate); + log.log(settings.rate); } if (initialSettings?.wait) { settings.wait = initialSettings.wait; - if (IS_DEV) console.log(settings.wait); + log.log(settings.wait); } } @@ -141,13 +142,11 @@ export class MediaOverlaySettings implements IMediaOverlayUserSettings { this.api = api; this.headerMenu = headerMenu; this.initialise(); - console.log(this.api); + log.log(this.api); } stop() { - if (IS_DEV) { - console.log("MediaOverlay settings stop"); - } + log.log("MediaOverlay settings stop"); } private initialise() { @@ -265,9 +264,7 @@ export class MediaOverlaySettings implements IMediaOverlayUserSettings { this.applyMediaOverlaySettings(syncSettings); if (this.api?.updateSettings) { this.api?.updateSettings(syncSettings).then(async (settings) => { - if (IS_DEV) { - console.log("api updated sync settings", settings); - } + log.log("api updated sync settings", settings); }); } } @@ -361,7 +358,7 @@ export class MediaOverlaySettings implements IMediaOverlayUserSettings { this.settingsChangeCallback(); } if (mediaOverlaySettings.autoScroll !== undefined) { - if (IS_DEV) console.log("autoScroll " + this.autoScroll); + log.log("autoScroll " + this.autoScroll); this.autoScroll = mediaOverlaySettings.autoScroll; let prop = this.userProperties.getByRef(MEDIAOVERLAYREFS.AUTO_SCROLL_REF); if (prop) { @@ -371,7 +368,7 @@ export class MediaOverlaySettings implements IMediaOverlayUserSettings { this.settingsChangeCallback(); } if (mediaOverlaySettings.autoTurn !== undefined) { - if (IS_DEV) console.log("autoTurn " + this.autoTurn); + log.log("autoTurn " + this.autoTurn); this.autoTurn = mediaOverlaySettings.autoTurn; let prop = this.userProperties.getByRef(MEDIAOVERLAYREFS.AUTO_TURN_REF); if (prop) { @@ -381,7 +378,7 @@ export class MediaOverlaySettings implements IMediaOverlayUserSettings { this.settingsChangeCallback(); } if (mediaOverlaySettings.volume) { - if (IS_DEV) console.log("volume " + this.volume); + log.log("volume " + this.volume); this.volume = mediaOverlaySettings.volume; let prop = this.userProperties.getByRef(MEDIAOVERLAYREFS.VOLUME_REF); if (prop) { @@ -391,7 +388,7 @@ export class MediaOverlaySettings implements IMediaOverlayUserSettings { this.settingsChangeCallback(); } if (mediaOverlaySettings.rate) { - if (IS_DEV) console.log("rate " + this.rate); + log.log("rate " + this.rate); this.rate = mediaOverlaySettings.rate; let prop = this.userProperties.getByRef(MEDIAOVERLAYREFS.RATE_REF); if (prop) { diff --git a/src/modules/pagebreak/PageBreakModule.ts b/src/modules/pagebreak/PageBreakModule.ts index 55b06b63..bca6ad25 100644 --- a/src/modules/pagebreak/PageBreakModule.ts +++ b/src/modules/pagebreak/PageBreakModule.ts @@ -17,7 +17,6 @@ * Licensed to: CAST under one or more contributor license agreements. */ -import { IS_DEV } from "../../utils"; import { IFrameNavigator } from "../../navigator/IFrameNavigator"; import { ReaderModule } from "../ReaderModule"; import { uniqueCssSelector } from "../highlight/renderer/common/cssselector2"; @@ -34,6 +33,7 @@ import { AnnotationMarker, Locations, Locator } from "../../model/Locator"; import { SHA256 } from "jscrypto/es6/SHA256"; import { _highlights } from "../highlight/TextHighlighter"; import { Publication } from "../../model/Publication"; +import log from "loglevel"; export interface PageBreakModuleProperties { hideLayer?: boolean; @@ -79,9 +79,7 @@ export class PageBreakModule implements ReaderModule { } async stop() { - if (IS_DEV) { - console.log("Page Break module stop"); - } + log.log("Page Break module stop"); } protected async start(): Promise { @@ -184,15 +182,15 @@ export class PageBreakModule implements ReaderModule { return ""; } } catch (err) { - console.log("uniqueCssSelector:"); - console.log(err); + log.log("uniqueCssSelector:"); + log.error(err); return ""; } } if (pageBreaks) { for (let i = 0; i < pageBreaks.length; i++) { let img = pageBreaks[i] as HTMLElement; - if (IS_DEV) console.log(img); + log.log(img); let title = img.innerHTML; let hide = false; diff --git a/src/modules/positions/TimelineModule.ts b/src/modules/positions/TimelineModule.ts index 7a9c8fe1..3f1280d6 100644 --- a/src/modules/positions/TimelineModule.ts +++ b/src/modules/positions/TimelineModule.ts @@ -17,7 +17,6 @@ * Licensed to: Bibliotheca LLC, Bokbasen AS and CAST under one or more contributor license agreements. */ -import { IS_DEV } from "../../utils"; import { Publication } from "../../model/Publication"; import { IFrameNavigator } from "../../navigator/IFrameNavigator"; import { ReaderModule } from "../ReaderModule"; @@ -25,6 +24,7 @@ import * as HTMLUtilities from "../../utils/HTMLUtilities"; import { addEventListenerOptional } from "../../utils/EventHandler"; import { Locator } from "../../model/Locator"; import { Link } from "../../model/Link"; +import log from "loglevel"; export interface TimelineModuleConfig { publication: Publication; @@ -49,9 +49,7 @@ export class TimelineModule implements ReaderModule { } async stop() { - if (IS_DEV) { - console.log("Timeline module stop"); - } + log.log("Timeline module stop"); } protected async start(): Promise { @@ -157,7 +155,7 @@ export class TimelineModule implements ReaderModule { title: link.Title, }; } - if (IS_DEV) console.log(position); + log.log(position); this.delegate.navigate(position); }); diff --git a/src/modules/protection/ContentProtectionModule.ts b/src/modules/protection/ContentProtectionModule.ts index e7d601be..500caf37 100644 --- a/src/modules/protection/ContentProtectionModule.ts +++ b/src/modules/protection/ContentProtectionModule.ts @@ -25,9 +25,10 @@ import { removeEventListenerOptional, } from "../../utils/EventHandler"; import { debounce } from "debounce"; -import { delay, IS_DEV } from "../../utils"; +import { delay } from "../../utils"; import { getUserAgentRegExp } from "browserslist-useragent-regexp"; import { addListener, launch } from "devtools-detector"; +import log from "loglevel"; export interface ContentProtectionModuleProperties { enforceSupportedBrowsers: boolean; @@ -164,9 +165,7 @@ export class ContentProtectionModule implements ReaderModule { // create an observer instance this.mutationObserver = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { - if (IS_DEV) { - console.log(mutation.type); - } + log.log(mutation.type); self.isHacked = true; }); }); @@ -174,9 +173,7 @@ export class ContentProtectionModule implements ReaderModule { } async stop() { - if (IS_DEV) { - console.log("Protection module stop"); - } + log.log("Protection module stop"); this.mutationObserver.disconnect(); if (this.properties?.disableKeys) { @@ -738,9 +735,7 @@ export class ContentProtectionModule implements ReaderModule { preventDefault: () => void; stopPropagation: () => void; }) { - if (IS_DEV) { - console.log("copy action initiated"); - } + log.log("copy action initiated"); event.clipboardData.setData("text/plain", "copy not allowed"); event.stopPropagation(); event.preventDefault(); @@ -751,9 +746,7 @@ export class ContentProtectionModule implements ReaderModule { preventDefault: () => void; stopPropagation: () => void; }) { - if (IS_DEV) { - console.log("before print"); - } + log.log("before print"); if (this.delegate && this.delegate.headerMenu) { this.delegate.headerMenu.style.display = "none"; @@ -768,9 +761,7 @@ export class ContentProtectionModule implements ReaderModule { preventDefault: () => void; stopPropagation: () => void; }) { - if (IS_DEV) { - console.log("after print"); - } + log.log("after print"); if (this.delegate && this.delegate.headerMenu) { this.delegate.headerMenu.style.removeProperty("display"); @@ -882,14 +873,12 @@ export class ContentProtectionModule implements ReaderModule { rect.width = width; rect.left = left; } catch (error) { - if (IS_DEV) { - console.log("error " + error); - console.log(rect); - console.log(rect.node); - console.log("scrambledTextContent " + rect.scrambledTextContent); - console.log("textContent " + rect.textContent); - console.log("isObfuscated " + rect.isObfuscated); - } + log.log("error " + error); + log.log(rect); + log.log(rect.node); + log.log("scrambledTextContent " + rect.scrambledTextContent); + log.log("textContent " + rect.textContent); + log.log("isObfuscated " + rect.isObfuscated); } }); } @@ -968,11 +957,9 @@ export class ContentProtectionModule implements ReaderModule { return rect; } catch (error) { - if (IS_DEV) { - console.log("measureTextNode " + error); - console.log("measureTextNode " + node); - console.log(node.textContent); - } + log.log("measureTextNode " + error); + log.log("measureTextNode " + node); + log.log(node.textContent); } } @@ -983,7 +970,7 @@ export class ContentProtectionModule implements ReaderModule { element.style.position || element.hasAttribute("style") ) { - if (IS_DEV) console.log("content being hacked"); + log.log("content being hacked"); return true; } return false; diff --git a/src/modules/search/DefinitionsModule.ts b/src/modules/search/DefinitionsModule.ts index 115d631e..160b441c 100644 --- a/src/modules/search/DefinitionsModule.ts +++ b/src/modules/search/DefinitionsModule.ts @@ -17,7 +17,6 @@ * Licensed to: CAST under one or more contributor license agreements. */ -import { IS_DEV } from "../../utils"; import { IFrameNavigator } from "../../navigator/IFrameNavigator"; import { ReaderModule } from "../ReaderModule"; import { @@ -34,6 +33,7 @@ import { ISelectionInfo } from "../highlight/common/selection"; import { SHA256 } from "jscrypto/es6/SHA256"; import { AnnotationMarker } from "../../model/Locator"; import { Publication } from "../../model/Publication"; +import log from "loglevel"; export interface DefinitionsModuleAPI { success: any; @@ -100,9 +100,7 @@ export class DefinitionsModule implements ReaderModule { } async stop() { - if (IS_DEV) { - console.log("Definitions module stop"); - } + log.log("Definitions module stop"); } protected async start(): Promise { diff --git a/src/modules/search/SearchModule.ts b/src/modules/search/SearchModule.ts index 1e16c655..fda08d82 100644 --- a/src/modules/search/SearchModule.ts +++ b/src/modules/search/SearchModule.ts @@ -29,13 +29,13 @@ import { removeEventListenerOptional, } from "../../utils/EventHandler"; import { AnnotationMarker, Locations, Locator } from "../../model/Locator"; -import { IS_DEV } from "../../utils"; import { DEFAULT_BACKGROUND_COLOR } from "../highlight/TextHighlighter"; import { HighlightType, IHighlight } from "../highlight/common/highlight"; import { ISelectionInfo } from "../highlight/common/selection"; import { SHA256 } from "jscrypto"; import { searchDocDomSeek, reset } from "./searchWithDomSeek"; import { TextHighlighter } from "../highlight/TextHighlighter"; +import log from "loglevel"; export interface SearchModuleAPI {} @@ -103,9 +103,7 @@ export class SearchModule implements ReaderModule { } async stop() { - if (IS_DEV) { - console.log("Search module stop"); - } + log.log("Search module stop"); removeEventListenerOptional( this.searchInput, "keypress", diff --git a/src/navigator/IFrameNavigator.ts b/src/navigator/IFrameNavigator.ts index ad956df0..be24edfe 100644 --- a/src/navigator/IFrameNavigator.ts +++ b/src/navigator/IFrameNavigator.ts @@ -45,7 +45,6 @@ import { AnnotationModule, AnnotationModuleConfig, } from "../modules/AnnotationModule"; -import { IS_DEV } from "../utils"; import { SearchModule, SearchModuleConfig, @@ -75,10 +74,12 @@ import { ReaderModule } from "../modules/ReaderModule"; import { TTSModuleConfig } from "../modules/TTS/TTSSettings"; import { HighlightType } from "../modules/highlight/common/highlight"; -import { PageBreakModuleConfig } from "../modules/pagebreak/PageBreakModule"; +import { + PageBreakModule, + PageBreakModuleConfig, +} from "../modules/pagebreak/PageBreakModule"; import { Switchable } from "../model/user-settings/UserProperties"; import { TTSModule2 } from "../modules/TTS/TTSModule2"; -import { PageBreakModule } from "../modules/pagebreak/PageBreakModule"; import { DefinitionsModule, DefinitionsModuleConfig, @@ -91,6 +92,7 @@ import { HistoryModule } from "../modules/history/HistoryModule"; import CitationModule, { CitationModuleConfig, } from "../modules/citation/CitationModule"; +import log from "loglevel"; export type GetContent = (href: string) => Promise; export type GetContentBytesLength = ( @@ -384,9 +386,7 @@ export class IFrameNavigator extends EventEmitter implements Navigator { } stop() { - if (IS_DEV) { - console.log("Iframe navigator stop"); - } + log.log("Iframe navigator stop"); removeEventListenerOptional( this.previousChapterAnchorElement, @@ -780,7 +780,7 @@ export class IFrameNavigator extends EventEmitter implements Navigator { } catch (err: unknown) { // There's a mismatch between the template and the selectors above, // or we weren't able to insert the template in the element. - console.error(err); + log.error(err); this.abortOnError(err); return Promise.reject(err); } @@ -804,8 +804,8 @@ export class IFrameNavigator extends EventEmitter implements Navigator { const linkHref = this.publication.getAbsoluteHref( lastReadingPosition.href ); - if (IS_DEV) console.log(lastReadingPosition.href); - if (IS_DEV) console.log(linkHref); + log.log(lastReadingPosition.href); + log.log(linkHref); lastReadingPosition.href = linkHref; await this.navigate(lastReadingPosition); } @@ -1242,8 +1242,8 @@ export class IFrameNavigator extends EventEmitter implements Navigator { const linkHref = this.publication.getAbsoluteHref( lastReadingPosition.href ); - if (IS_DEV) console.log(lastReadingPosition.href); - if (IS_DEV) console.log(linkHref); + log.log(lastReadingPosition.href); + log.log(linkHref); lastReadingPosition.href = linkHref; await this.navigate(lastReadingPosition); } else if (startUrl) { @@ -1261,7 +1261,7 @@ export class IFrameNavigator extends EventEmitter implements Navigator { return new Promise((resolve) => resolve()); } catch (err: unknown) { - console.error(err); + log.error(err); this.abortOnError(err); return new Promise((_, reject) => reject(err)).catch(() => {}); } @@ -1493,7 +1493,7 @@ export class IFrameNavigator extends EventEmitter implements Navigator { return new Promise((resolve) => resolve()); } catch (err: unknown) { - console.error(err); + log.error(err); this.abortOnError(err); return Promise.reject(err); } @@ -2216,8 +2216,8 @@ export class IFrameNavigator extends EventEmitter implements Navigator { position.locations = locations; const linkHref = this.publication.getAbsoluteHref(locator.href); - if (IS_DEV) console.log(locator.href); - if (IS_DEV) console.log(linkHref); + log.log(locator.href); + log.log(linkHref); position.href = linkHref; this.stopReadAloud(); this.navigate(position); @@ -2280,7 +2280,7 @@ export class IFrameNavigator extends EventEmitter implements Navigator { snapToSelector(selector) { const doc = this.iframes[0].contentDocument; if (doc) { - console.log(selector); + log.log(selector); let result = doc.querySelectorAll(selector); if (result.length > 0) this.view?.snap(result[0]); } @@ -3156,15 +3156,11 @@ export class IFrameNavigator extends EventEmitter implements Navigator { if (this.api?.updateCurrentLocation) { this.api?.updateCurrentLocation(position).then(async (_) => { - if (IS_DEV) { - console.log("api updated current location", position); - } + log.log("api updated current location", position); return this.annotator?.saveLastReadingPosition(position); }); } else { - if (IS_DEV) { - console.log("save last reading position", position); - } + log.log("save last reading position", position); this.annotator.saveLastReadingPosition(position); } } diff --git a/src/utils/EventHandler.ts b/src/utils/EventHandler.ts index 20f0f788..9b6ffde7 100644 --- a/src/utils/EventHandler.ts +++ b/src/utils/EventHandler.ts @@ -17,10 +17,10 @@ * Licensed to: Bokbasen AS and CAST under one or more contributor license agreements. */ -import { IS_DEV } from "../utils"; import { Link } from "r2-shared-js/dist/es6-es2015/src/models/publication-link"; import { IFrameNavigator } from "../navigator/IFrameNavigator"; import { Popup } from "../modules/search/Popup"; +import log from "loglevel"; export function addEventListenerOptional( element: any, @@ -110,7 +110,7 @@ export default class EventHandler { private isReadingOrderInternal = ( clickedLink: HTMLAnchorElement ): boolean => { - if (IS_DEV) console.log("clickedLink: ", clickedLink); + log.log("clickedLink: ", clickedLink); const isEpubInternal = this.linkInPublication( this.navigator.publication.readingOrder, clickedLink.href @@ -119,7 +119,7 @@ export default class EventHandler { }; private isResourceInternal = (clickedLink: HTMLAnchorElement): boolean => { - if (IS_DEV) console.log("clickedLink: ", clickedLink); + log.log("clickedLink: ", clickedLink); const isEpubInternal = this.linkInPublication( this.navigator.publication.resources, clickedLink.href @@ -130,7 +130,7 @@ export default class EventHandler { private handleLinks = async ( event: MouseEvent | TouchEvent ): Promise => { - if (IS_DEV) console.log("R2 Click Handler"); + log.log("R2 Click Handler"); const link = this.checkForLink(event); if (link) { diff --git a/src/utils/index.ts b/src/utils/index.ts index 0ef0a000..582c2df6 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -2,11 +2,14 @@ * * Timer function that you can 'await' on */ +import log from "loglevel"; + export function delay(t: number, v?: any): Promise { return new Promise(function (resolve) { setTimeout(resolve.bind(null, v), t); }); } -export const IS_DEV = +const IS_DEV = process.env.NODE_ENV === "development" || process.env.NODE_ENV === "dev"; +log.setLevel(IS_DEV ? "trace" : "warn", true);