88 lines
2.4 KiB
JavaScript
88 lines
2.4 KiB
JavaScript
(() => {
|
|
const timeline = document.getElementById("thought-timeline");
|
|
const more = document.querySelector(".thought-timeline-more");
|
|
const button = document.querySelector(".thought-load-more");
|
|
if (!timeline || !button) return;
|
|
|
|
const defaultLabel = button.textContent.trim();
|
|
|
|
async function loadPage(url) {
|
|
const response = await fetch(url, { credentials: "same-origin" });
|
|
if (!response.ok) {
|
|
throw new Error(`Could not load ${url}: ${response.status}`);
|
|
}
|
|
|
|
const html = await response.text();
|
|
const doc = new DOMParser().parseFromString(html, "text/html");
|
|
const nextTimeline = doc.getElementById("thought-timeline");
|
|
const nextButton = doc.querySelector(".thought-load-more");
|
|
|
|
if (nextTimeline) {
|
|
timeline.append(...Array.from(nextTimeline.children));
|
|
}
|
|
|
|
if (nextButton && nextButton.dataset.next) {
|
|
button.dataset.next = nextButton.dataset.next;
|
|
return true;
|
|
}
|
|
|
|
button.remove();
|
|
if (more) more.remove();
|
|
return false;
|
|
}
|
|
|
|
async function loadOlder() {
|
|
if (button.disabled || !button.dataset.next) return;
|
|
|
|
const next = button.dataset.next;
|
|
button.disabled = true;
|
|
button.textContent = "Loading…";
|
|
|
|
try {
|
|
await loadPage(next);
|
|
} catch (error) {
|
|
console.error(error);
|
|
window.location.href = next;
|
|
return;
|
|
}
|
|
|
|
if (document.body.contains(button)) {
|
|
button.disabled = false;
|
|
button.textContent = defaultLabel;
|
|
}
|
|
}
|
|
|
|
button.addEventListener("click", loadOlder);
|
|
|
|
// A link to an older thought (for example from the RSS feed) may point to an
|
|
// entry that has not been loaded yet. Keep loading pages until it exists.
|
|
const hash = decodeURIComponent(window.location.hash.slice(1));
|
|
if (hash && !document.getElementById(hash) && button.dataset.next) {
|
|
(async () => {
|
|
let next = button.dataset.next;
|
|
|
|
while (next && !document.getElementById(hash)) {
|
|
button.disabled = true;
|
|
button.textContent = "Loading…";
|
|
|
|
try {
|
|
if (!(await loadPage(next))) break;
|
|
} catch (error) {
|
|
console.error(error);
|
|
break;
|
|
}
|
|
|
|
next = button.dataset.next;
|
|
}
|
|
|
|
if (document.body.contains(button)) {
|
|
button.disabled = false;
|
|
button.textContent = defaultLabel;
|
|
}
|
|
|
|
const target = document.getElementById(hash);
|
|
if (target) target.scrollIntoView({ block: "start" });
|
|
})();
|
|
}
|
|
})();
|