about summary refs log tree commit diff stats
diff options
context:
space:
mode:
-rw-r--r--src/app.ts222
1 files changed, 106 insertions, 116 deletions
diff --git a/src/app.ts b/src/app.ts
index 1d40637..481f669 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -1,15 +1,14 @@
-// @ts-check
-
 'use strict';
 
 class Cookie {
 
     /**
-     * @param {string} name
-     * @param {string | number | boolean} value
-     * @param {number} lifetime
+     * Set a cookie.
+     * @param name - The cookie name.
+     * @param value - The cookie value.
+     * @param lifetime - Lifetime in seconds.
      */
-    static set(name: any, value: any, lifetime: any) {
+    static set(name: string, value: string | number | boolean, lifetime: number): void {
         const d = new Date();
         d.setTime(d.getTime() + lifetime * 1000);
         const expires = "expires=" + d.toUTCString();
@@ -17,9 +16,10 @@ class Cookie {
     }
 
     /**
-     * @param {string} name
+     * Get a cookie value by name.
+     * @param name - The cookie name.
      */
-    static get(name: any) {
+    static get(name: string): string {
         name = name + "=";
         const ca = document.cookie.split(';');
         for (let i=0; i < ca.length; i++) {
@@ -31,9 +31,10 @@ class Cookie {
     }
 
     /**
-     * @param {string} name
+     * Delete a cookie by name.
+     * @param name - The cookie name.
      */
-    static delete(name: any) {
+    static delete(name: string): void {
         const expires = "expires=Thu, 01-Jan-1970 00:00:01 GMT";
         document.cookie = name + "=; " + expires;
     }
@@ -41,9 +42,10 @@ class Cookie {
 
 class AppCommon {
     /**
-     * @param {string} name
+     * Extract a URL query parameter.
+     * @param name - The parameter name.
      */
-    urlParam(name: any){
+    urlParam(name: string): string{
         try {
             const results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
             if (!results) return "";
@@ -67,9 +69,9 @@ class AppCommon {
         // Fast exit if no worker is active
         if (!worker) return null;
 
-        return new Promise((resolve, reject) => {
+        return new Promise<string | null>((resolve, reject) => {
             const channel = new MessageChannel();
-            let timeoutId: any = null;
+            let timeoutId = -1;
 
             channel.port1.onmessage = (event) => {
                 clearTimeout(timeoutId); // Clean up the timeout
@@ -77,7 +79,7 @@ class AppCommon {
             };
 
             // 1. Set a timeout so it never gets stuck forever
-            timeoutId = setTimeout(() => {
+            timeoutId = window.setTimeout(() => {
                 channel.port1.onmessage = null; // Clean up listener
                 console.warn('Service worker did not respond to GET_CACHE_NAME');
                 resolve(null);
@@ -95,9 +97,9 @@ class AppCommon {
         // Fast exit if no worker is active
         if (!worker) return null;
 
-        return new Promise((resolve, reject) => {
+        return new Promise<string | null>((resolve, reject) => {
             const channel = new MessageChannel();
-            let timeoutId: any = null;
+            let timeoutId = -1;
 
             channel.port1.onmessage = (event) => {
                 clearTimeout(timeoutId); // Clean up the timeout
@@ -105,7 +107,7 @@ class AppCommon {
             };
 
             // 1. Set a timeout so it never gets stuck forever
-            timeoutId = setTimeout(() => {
+            timeoutId = window.setTimeout(() => {
                 channel.port1.onmessage = null; // Clean up listener
                 console.warn('Service worker did not respond to GET_CACHE_VERSION');
                 resolve(null);
@@ -133,20 +135,16 @@ class AppCommon {
         }
     }
 
-    /** @param {boolean} is_night */
-    applyNightMode(is_night: any) {
+    /** Apply night/dark mode styling. */
+    applyNightMode(is_night: boolean): void {
         console.log("night mode changed to", is_night);
 
         $("#theme_css").attr("href",
             "lib/bootstrap/v3/css/" + (is_night ? "theme-dark.min.css" : "bootstrap-theme.min.css"));
     }
 
-    /** htmlspecialchars()-alike for headlines data-content attribute
-      * @param {string | number | boolean} p
-      *
-      * @return {string}
-      */
-    escapeHtml(p: any) {
+    /** htmlspecialchars()-alike for headlines data-content attribute. */
+    escapeHtml(p: string | number | boolean): string {
         if (p === null || p === undefined) {
             return '';
         }
@@ -169,31 +167,20 @@ class AppCommon {
     }
 }
 
-/* eslint-disable-next-line no-unused-vars */
 class AppClass extends AppCommon {
-    _dl_progress_timeout: any;
-
-    /** @type{string} */
-    index_mode = "";
-
-    /** @type{string} */
-    index_query = "";
-
-    /** @type{number} */
-    index_offset = 0;
-
-    cached_urls = [];
+    _dl_progress_timeout: number = -1;
 
-    /** @type{string} */
-    cacheVersion = BUILD_CACHE_VERSION;
+    index_mode: string = "";
+    index_query: string = "";
+    index_offset: number = 0;
 
-    /** @type{string} */
-    cosmeticVersion = BUILD_VERSION;
+    cached_urls: string[] = [];
 
-    /** @type{string} */
-    csrf_token = "";
+    cacheVersion = BUILD_CACHE_VERSION as string;
+    cosmeticVersion = BUILD_VERSION as string;
+    csrf_token: string = "";
 
-    async init() {
+    async init(): Promise<void> {
         console.log('cache version, current:', this.cacheVersion, 'worker:', await this.getActiveCacheVersion());
 
         // Read URL params for mode/query/offset
@@ -220,7 +207,7 @@ class AppClass extends AppCommon {
             await Http.get("backend.php?" + checkParams.toString());
             // If we get here without error, we're authenticated
         } catch (e) {
-            const err = /** @type {HttpError} */(e);
+            const err = e as HttpError;
             // 401 Unauthorized — redirect to login
             if ((err as any).status === 401) {
                 window.location.href = "login.php";
@@ -269,12 +256,12 @@ class AppClass extends AppCommon {
             this.logout();
         });
 
-        $(".download_all_link").on('click', (e: any) => {
+        $(".download_all_link").on('click', (e: JQuery.Event) => {
             e.preventDefault();
             this.getAll();
         });
 
-        $(".update_link").on('click', (e: any) => {
+        $(".update_link").on('click', (e: JQuery.Event) => {
             e.preventDefault();
             window.location.reload();
         });
@@ -283,7 +270,7 @@ class AppClass extends AppCommon {
 
     }
 
-    async logout() {
+    async logout(): Promise<void> {
         try {
             await Http.post("backend.php", {op: "logout"});
         } catch (e) {
@@ -293,21 +280,20 @@ class AppClass extends AppCommon {
     }
 
     /**
-     * @param {HTMLElement} elem
+     * Show the book summary modal.
+     * @param elem - The trigger element with data-book-id.
      */
-    async showSummary(elem: any) {
+    async showSummary(elem: HTMLElement): Promise<boolean> {
         const bookId = elem.getAttribute("data-book-id");
 
         if (!bookId)
-            return;
+            return false;
 
         if (this.isOnline()) {
 
-            /** @type{HttpResponse} */
-            const reply = await Http.post("backend.php", {op: 'list', ids: bookId});
+            const reply = await Http.post("backend.php", {op: 'list', ids: bookId}) as HttpResponse;
 
-            /** @type{BookInfo} */
-            const data = reply.data['books'][0];
+            const data = reply.data['books'][0] as BookInfo;
 
             const comment = data.comment ? data.comment : 'No description available';
 
@@ -330,7 +316,7 @@ class AppClass extends AppCommon {
     }
 
     showCovers() {
-        $("img[data-book-id]").each((i: any, elem: any) => {
+        $("img[data-book-id]").each((i: number, elem: HTMLElement) => {
             const e = $(elem);
 
             if (e.attr('data-cover-link')) {
@@ -347,28 +333,30 @@ class AppClass extends AppCommon {
     }
 
     /**
-     * @param {HTMLElement} elem
-     * @param {boolean} is_fav
+     * Update the favorite prompt text on an element.
+     * @param elem - The element to update.
+     * @param is_fav - Whether the book is a favorite.
      */
-    updateFavoritePrompt(elem: any, is_fav: any) {
+    updateFavoritePrompt(elem: HTMLElement, is_fav: boolean): void {
         $(elem)
             .text(is_fav ? "Remove from favorites" : "Add to favorites")
             .attr('data-is-fav', is_fav ? 1 : 0);
     }
 
     /**
-     * @param {HTMLElement} elem
+     * Toggle a book's favorite status.
+     * @param elem - The trigger element with data-book-id.
      */
-    async toggleFavorite(elem: any) {
+    async toggleFavorite(elem: HTMLElement): Promise<boolean> {
         const bookId = elem.getAttribute("data-book-id");
 
         if (!bookId)
-            return;
+            return false;
 
         if (elem.getAttribute("data-is-fav") == "0" || confirm("Remove favorite?")) {
 
             try {
-                const resp = await Http.post("backend.php", {op: "togglefav", id: bookId});
+                const resp = await Http.post("backend.php", {op: "togglefav", id: bookId}) as HttpResponse;
                 if (resp.data) {
                     this.updateFavoritePrompt(elem, resp.data.status == "1");
 
@@ -387,15 +375,16 @@ class AppClass extends AppCommon {
     updateOfflinePrompts() {
         const elems = $(".offline_dropitem");
 
-        $.each(elems, (i: any, elem: any) => {
+        $.each(elems, (i: number, elem: HTMLElement) => {
             this.updateOfflinePrompt(elem);
         });
     }
 
     /**
-     * @param {HTMLElement} elem
+     * Update the offline prompt for a single book element.
+     * @param elem - The element to update.
      */
-    async updateOfflinePrompt(elem: any) {
+    async updateOfflinePrompt(elem: HTMLElement): Promise<void> {
         const bookId = elem.getAttribute("data-book-id");
 
         if (!bookId)
@@ -428,7 +417,7 @@ class AppClass extends AppCommon {
         }
     }
 
-    async offlineInit() {
+    async offlineInit(): Promise<void> {
         console.log('cache version, current:', this.cacheVersion, 'worker:', await this.getActiveCacheVersion());
 
         if (typeof EpubeApp != "undefined") {
@@ -448,17 +437,16 @@ class AppClass extends AppCommon {
     }
 
      /**
-     * @param {string} bookId
-     * @param {Function} callback
+     * Download a single book for offline reading.
+     * @param bookId - The book ID to download.
+     * @param callback - Callback invoked after download completes.
      */
-    async get(bookId: any, callback: any) {
+    async get(bookId: string, callback: () => void): Promise<void> {
         console.log("offline cache: " + bookId);
 
-        /** @type {HttpResponse} */
-        const reply = await Http.post("backend.php", {op: "list", ids: bookId});
+        const reply = await Http.post("backend.php", {op: "list", ids: bookId}) as HttpResponse;
 
-        /** @type{BookInfo} */
-        const data = reply.data['books'][0];
+        const data = reply.data['books'][0] as BookInfo;
 
         if (data) {
             const cacheId = 'epube-book.' + bookId;
@@ -466,7 +454,7 @@ class AppClass extends AppCommon {
             await localforage.setItem(cacheId, data);
             console.log(cacheId + ' got data');
 
-            const promises: Promise<any>[] = [];
+            const promises: Promise<void|Blob>[] = [];
 
             promises.push(Http.blob('backend.php?op=download&id=' + data.epub_id).then((resp) => {
                 console.log(cacheId + ' got book');
@@ -507,20 +495,20 @@ class AppClass extends AppCommon {
         }
     }
 
-    getAll() {
+    getAll(): void {
         if (confirm("Download all books on this page?")) {
 
-            $(".row > div").each((i: any, row: any) => {
+            $(".row > div").each((i: number, row: HTMLElement) => {
                 const bookId = ($(row).attr("id") ?? "").replace("cell-", "");
                 const dropitem = $(row).find(".offline_dropitem")[0] ?? null;
 
                 if (bookId) {
                     const cacheId = 'epube-book.' + bookId;
 
-                    localforage.getItem(cacheId).then((book: any) => {
+                    localforage.getItem(cacheId).then((book) => {
                         if (!book) {
                             this.get(bookId, () => {
-                                this.updateOfflinePrompt(dropitem);
+                                this.updateOfflinePrompt(dropitem as HTMLElement);
                             });
                         }
                     });
@@ -530,25 +518,28 @@ class AppClass extends AppCommon {
     }
 
     /**
-     * @param {HTMLElement} elem
+     * Remove a book from the list UI.
+     * @param elem - The element with data-book-id.
      */
-    removeFromList(elem: any) {
+    removeFromList(elem: HTMLElement): void {
         const bookId = elem.getAttribute("data-book-id");
 
-        this.remove(bookId, () => {
-            $("#cell-" + bookId).remove();
-        });
+        if (bookId) {
+            this.remove(bookId, () => {
+                $("#cell-" + bookId).remove();
+            });
+        }
     }
 
-    remove(id: any, callback: any) {
+    remove(id: string, callback: () => void): void {
         if (confirm("Remove download?")) {
 
             const cacheId = "epube-book." + id;
-            const promises: any = [];
+            const promises: Promise<void>[] = [];
 
             console.log("offline remove: " + id);
 
-            localforage.iterate(function(value: any, key: any /*, i */) {
+            localforage.iterate(function(value: unknown, key: string /*, i */) {
                 if (key.match(cacheId)) {
                     promises.push(localforage.removeItem(key));
                 }
@@ -565,7 +556,7 @@ class AppClass extends AppCommon {
         }
     }
 
-    async populateList() {
+    async populateList(): Promise<void> {
         const params = new URLSearchParams({
             op: "list",
             mode: this.index_mode,
@@ -574,27 +565,25 @@ class AppClass extends AppCommon {
             limit: String(60),
         });
 
-        /** @type {HttpResponse} */
-        let resp;
+        let resp: HttpResponse;
         try {
             resp = await Http.get("backend.php?" + params.toString());
         } catch (e) {
-            const err = /** @type {HttpError} */(e);
+            const err = e as HttpError;
             if ((err as any).status === 401) {
                 window.location.href = "login.php";
             }
             return;
         }
 
-        /** @type{BookList} */
-        const data = resp.data;
+        const data = resp.data as BookList;
         const books = $("#books_container");
         books.html("");
 
         if (data) {
-            data.books.forEach((book: any) => {
+            data.books.forEach((book: BookInfo) => {
                 const download_html = book.download_formats
-                    .map((fmt: any) => {
+                    .map((fmt: { id: number, format: string }) => {
                         const label_class = fmt.format === "EPUB" ? "label-success" : "label-primary";
                         return `<li><a target="_blank" href="backend.php?op=download&id=${fmt.id}">Download: <span class="label ${label_class}">${fmt.format}</span></a></li>`;
                     })
@@ -628,9 +617,10 @@ class AppClass extends AppCommon {
     }
 
     /**
-     * @param {BookList} data
+     * Update the index pagination UI.
+     * @param data - The book list response containing pagination info.
      */
-    updateIndexPagination(data: any) {
+    updateIndexPagination(data: BookList): void {
         const prevLi = $(".pager .previous");
         const nextLi = $(".pager .next");
         const pagerInfo = $(".pager .pager-info");
@@ -672,14 +662,14 @@ class AppClass extends AppCommon {
 
     /**
      * Render a book cell DOM element.
-     * @param {BookInfo} book - Book data object.
-     * @param {Object} opts - Rendering options.
-     * @param {string[]} opts.menuItems - Array of <li> menu item HTML strings.
-     * @param {String} [opts.seriesUrl] - Search by series override
-     * @param {String} [opts.authorUrl] - Search by author override
+     * @param book - Book data object.
+     * @param opts - Rendering options.
+     * @param opts.menuItems - Array of <li> menu item HTML strings.
+     * @param opts.seriesUrl - Search by series override
+     * @param opts.authorUrl - Search by author override
      * @returns {JQuery<HTMLElement>} The created cell element.
      */
-    renderBookCell(book: any, opts: any) {
+    renderBookCell(book: BookInfo, opts: { menuItems: string[], seriesUrl?: string, authorUrl?: string }): JQuery<HTMLElement> {
         //console.log('renderBookCell', book, opts);
 
         const cellThumbClass = book.is_read ? "read" : "";
@@ -726,18 +716,18 @@ class AppClass extends AppCommon {
             </div>
         </div>`);
 
-        cell.find('.summary_link').on('click', (evt: any) => {
+        cell.find('.summary_link').on('click', (evt: JQuery.ClickEvent) => {
             evt.preventDefault();
             this.showSummary(evt.currentTarget);
         });
 
-        cell.find('.fav_item').on('click', (evt: any) => {
+        cell.find('.fav_item').on('click', (evt: JQuery.ClickEvent) => {
             evt.preventDefault();
             this.toggleFavorite(evt.currentTarget);
         });
 
         // specific to offline index
-        cell.find('.remove_offline_data').on('click', (evt: any) => {
+        cell.find('.remove_offline_data').on('click', (evt: JQuery.ClickEvent) => {
             evt.preventDefault();
             this.removeFromList(evt.currentTarget);
         });
@@ -745,8 +735,8 @@ class AppClass extends AppCommon {
         return cell;
     }
 
-    async search() {
-        const query = $(".search_query").val();
+    async search(): Promise<boolean> {
+        const query = $(".search_query").val() as string | undefined;
 
         await localforage.setItem("epube.search-query", query);
 
@@ -755,12 +745,12 @@ class AppClass extends AppCommon {
         return false;
     }
 
-    async removeAll() {
+    async removeAll(): Promise<void> {
         if (confirm("Remove all downloaded books?")) {
 
-            const promises: any = [];
+            const promises: Promise<void>[] = [];
 
-            localforage.iterate(function(value: any, key: any/*, i*/) {
+            localforage.iterate(function(value: unknown, key: string/*, i*/) {
                 if (key.match("epube-book")) {
                     promises.push(localforage.removeItem(key));
                 }
@@ -772,14 +762,14 @@ class AppClass extends AppCommon {
         }
     }
 
-   populateOfflineList() {
+   populateOfflineList(): void {
         let query = this.urlParam("query");
         if (query) query = String(query).toLowerCase();
 
         const books = $("#books_container");
         books.html("");
 
-        localforage.iterate((value: any, key: any) => {
+        localforage.iterate((value: unknown, key: string) => {
             if (key.match(/epube-book\.\d{1,}$/)) {
 
                 Promise.all([
@@ -807,7 +797,7 @@ class AppClass extends AppCommon {
                             cover = URL.createObjectURL(results[1] as Blob);
                         }
 
-                        const lastread = results[2] as LastRead;
+                        const lastread = results[2] as LastRead | null;
                         info.in_progress = lastread ? lastread.page > 0 : false;
                         info.is_read = lastread ? (lastread.total > 0 && lastread.total - lastread.page < 5) : false;