From edb511eda1a1e04a73d4e5cbbd32d4c15c87e5dd Mon Sep 17 00:00:00 2001 From: tdro Date: Tue, 5 Dec 2023 14:05:22 -0500 Subject: static/js/infinitescroll: Abort to fallback on failure Set key, use congruent offset, and set count --- static/js/infinitescroll.ts | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) (limited to 'static') diff --git a/static/js/infinitescroll.ts b/static/js/infinitescroll.ts index c366619..1d9fcf8 100644 --- a/static/js/infinitescroll.ts +++ b/static/js/infinitescroll.ts @@ -1,24 +1,33 @@ (function () { type percent = number; - function fetch(url, method, callback) { + function fetch(url, method, callback, fallback) { const http = new XMLHttpRequest(); http.onreadystatechange = function () { if (callback && http.readyState === 4 && http.status === 200) { callback(http); } }; + http.addEventListener("error", fallback); http.open(method, url); http.send(); return http; } + let abort = false; + + const key = "config.scroll.infinite"; + + if (!localStorage[key]) localStorage[key] = ""; + ["scroll", "DOMContentLoaded"].forEach(function (event) { self.addEventListener(event, function () { + if (abort) return; + const remaining = Math.abs( document.documentElement.scrollHeight - document.documentElement.clientHeight - - document.documentElement.scrollTop + - self.pageYOffset ); const traversed = self.pageYOffset; @@ -30,31 +39,32 @@ if (!pagination) return; const main = document.querySelector("main"); + const count = main.childNodes.length; const next = pagination.querySelector('[rel="next"]'); const end = pagination.querySelector('[rel="last"]').title === "hidden"; const asynchronous = document.querySelectorAll("[data-type='pagination']").length !== 1; if (end || asynchronous) return pagination.remove(); - if (threshold) { - - pagination.remove(); - + if (threshold && (pagination.remove() === undefined)) { fetch(next.href, "GET", function (http) { const page = (new DOMParser()).parseFromString(http.responseText, "text/html"); const items = page.querySelector("main").childNodes; - const paginate = page.querySelector('[data-type="pagination"]'); + const paginate = page.querySelector('[data-type="pagination"]'); - for (let i = 0; i < items.length; i++) { - main.appendChild(items[i]); - } + for (let i = 0; i < items.length; i++) main.appendChild(items[i]); main.after(paginate); + console.log("Fetch:", next.href, items); + + }, function (event) { + console.log("WARNING: Switching to native pagination", event); + main.insertAdjacentElement("afterend", pagination); + abort = true; }); } - - console.log("r:", remaining, "t:", traversed, "j:", journey, "%:", ratio); + console.log("r:", remaining, "t:", traversed, "j:", journey, "%:", ratio, "c:", count); }); }); })(); -- cgit v1.2.3