nitter/public/js/infiniteScroll.js

78 lines
2.7 KiB
JavaScript
Raw Normal View History

// @license http://www.gnu.org/licenses/agpl-3.0.html AGPL-3.0
2021-12-27 01:43:27 +00:00
// SPDX-License-Identifier: AGPL-3.0-only
2020-01-07 02:00:16 +00:00
function insertBeforeLast(node, elem) {
node.insertBefore(elem, node.childNodes[node.childNodes.length - 2]);
}
function getLoadMore(doc) {
2023-07-24 08:37:25 +00:00
return doc.querySelector(".show-more:not(.timeline-item)");
2020-01-07 02:00:16 +00:00
}
function isDuplicate(item, itemClass) {
const tweet = item.querySelector(".tweet-link");
if (tweet == null) return false;
const href = tweet.getAttribute("href");
return document.querySelector(itemClass + " .tweet-link[href='" + href + "']") != null;
}
2023-07-24 08:37:25 +00:00
window.onload = function () {
const url = window.location.pathname;
const isTweet = url.indexOf("/status/") !== -1;
2020-01-07 02:00:16 +00:00
const containerClass = isTweet ? ".replies" : ".timeline";
2023-07-24 08:37:25 +00:00
const itemClass = containerClass + " > div:not(.top-ref)";
2020-01-07 02:00:16 +00:00
var html = document.querySelector("html");
var container = document.querySelector(containerClass);
var loading = false;
2023-07-24 08:37:25 +00:00
function handleScroll(failed) {
2020-01-07 02:00:16 +00:00
if (loading) return;
2023-07-24 08:37:25 +00:00
2020-01-07 02:00:16 +00:00
if (html.scrollTop + html.clientHeight >= html.scrollHeight - 3000) {
loading = true;
var loadMore = getLoadMore(document);
if (loadMore == null) return;
loadMore.children[0].text = "Loading...";
var url = new URL(loadMore.children[0].href);
2023-07-24 08:37:25 +00:00
url.searchParams.append("scroll", "true");
2020-01-07 02:00:16 +00:00
fetch(url.toString()).then(function (response) {
2023-07-24 08:37:25 +00:00
if (response.status === 404) throw "error";
2020-01-13 05:15:45 +00:00
return response.text();
2020-01-07 02:00:16 +00:00
}).then(function (html) {
var parser = new DOMParser();
2023-07-24 08:37:25 +00:00
var doc = parser.parseFromString(html, "text/html");
2020-01-07 02:00:16 +00:00
loadMore.remove();
for (var item of doc.querySelectorAll(itemClass)) {
if (item.className == "timeline-item show-more") continue;
if (isDuplicate(item, itemClass)) continue;
2020-01-07 02:00:16 +00:00
if (isTweet) container.appendChild(item);
else insertBeforeLast(container, item);
}
loading = false;
const newLoadMore = getLoadMore(doc);
if (newLoadMore == null) return;
if (isTweet) container.appendChild(newLoadMore);
else insertBeforeLast(container, newLoadMore);
2020-01-07 02:00:16 +00:00
}).catch(function (err) {
2023-07-24 08:37:25 +00:00
console.warn("Something went wrong.", err);
if (failed > 3) {
loadMore.children[0].text = "Error";
return;
}
loading = false;
handleScroll((failed || 0) + 1);
2020-01-07 02:00:16 +00:00
});
}
2023-07-24 08:37:25 +00:00
}
window.addEventListener("scroll", () => handleScroll());
2020-01-07 02:00:16 +00:00
};
// @license-end