/** * TODO: * - Offling / Online Checker * - Flush oustanding read activity & progress * - No files cached * - Upload Files **/ const BASE_ITEM = `
`; const GET_SW_CACHE = "GET_SW_CACHE"; const DEL_SW_CACHE = "DEL_SW_CACHE"; async function initOffline() { updateOnlineIndicator(); if (document.location.pathname !== "/offline") window.history.replaceState(null, null, "/offline"); // Ensure Installed await SW.install(); // Get Service Worker Cache & Local Cache - Override Local let swCache = await SW.send({ type: GET_SW_CACHE }); let allCache = await Promise.all( swCache.map(async (item) => { let localCache = await IDB.get("PROGRESS-" + item.id); if (localCache) { item.progress = localCache.progress; item.percentage = Math.round(localCache.percentage * 10000) / 100; } return item; }) ); populateDOM(allCache); } /** * Populate DOM with cached documents. **/ function populateDOM(data) { let allDocuments = document.querySelector("#items"); // Update Loader / No Results Indicator let loadingEl = document.querySelector("#loading"); if (data.length == 0) loadingEl.innerText = "No Results"; else loadingEl.remove(); data.forEach((item) => { // Create Main Element let baseEl = document.createElement("div"); baseEl.innerHTML = BASE_ITEM; baseEl = baseEl.firstElementChild; // Get Elements let coverEl = baseEl.querySelector("a img"); let [titleEl, authorEl, percentageEl] = baseEl.querySelectorAll("p + p"); let downloadEl = baseEl.querySelector("svg").parentElement; // Set Variables downloadEl.setAttribute("href", "/documents/" + item.id + "/file"); coverEl.setAttribute("src", "/documents/" + item.id + "/cover"); coverEl.parentElement.setAttribute("href", "/reader#id=" + item.id); titleEl.textContent = item.title; authorEl.textContent = item.author; percentageEl.textContent = item.percentage + "%"; allDocuments.append(baseEl); }); } /** * Allow adding file to offline reader. Add to IndexedDB, * and later upload? Add style indicating external file? **/ function handleFileAdd() {} function updateOnlineIndicator(isOnline) { let onlineEl = document.querySelector("#online"); isOnline = isOnline == undefined ? navigator.onLine : isOnline; onlineEl.hidden = !isOnline; } // Initialize window.addEventListener("DOMContentLoaded", initOffline); window.addEventListener("online", () => updateOnlineIndicator(true)); window.addEventListener("offline", () => updateOnlineIndicator(false));