This commit is contained in:
Max Nuding 2023-04-05 17:10:18 +02:00
parent 4d689a86ab
commit 2409fa2b8d
Signed by: phlaym
GPG Key ID: A06651BAB6777237

View File

@ -8,34 +8,48 @@ import LoadMoreComponent from '$lib/components/LoadMoreComponent.svelte';
export let data: PageData;
const refreshInterval = parseInt(PUBLIC_REFRESH_INTERVAL);
let interval: NodeJS.Timer | null = null;
let moreOlderPostsAvailable = true;
let loadingOlderPosts = false;
onMount(async () => {
interval = setInterval(async () => {
const params = new URLSearchParams();
if (data.posts.length > 0) {
params.set('since', data.posts[0].created_at);
function refresh() {
const params = new URLSearchParams();
if (data.posts.length > 0) {
params.set('since', data.posts[0].created_at);
}
fetch(`/api/posts?${params}`)
.then(r => r.json())
.then((resp: Post[]) => {
if (resp.length > 0) {
// Prepend new posts, filter dupes
// There shouldn't be any duplicates, but better be safe than sorry
const combined = resp.concat(data.posts);
const filteredPosts = combined.filter((obj, index, arr) => {
return arr.map(mapObj => mapObj.url).indexOf(obj.url) === index;
});
data.posts = filteredPosts;
}
await fetch(`/api/posts?${params}`)
.then(r => r.json())
.then((resp: Post[]) => {
if (resp.length > 0) {
// Prepend new posts, filter dupes
// There shouldn't be any duplicates, but better be safe than sorry
const combined = resp.concat(data.posts);
const filteredPosts = combined.filter((obj, index, arr) => {
return arr.map(mapObj => mapObj.url).indexOf(obj.url) === index;
});
data.posts = filteredPosts;
}
})
.catch(e => {
// TODO: Show error in UI
console.error('Error loading newest posts', e);
});
}, parseInt(PUBLIC_REFRESH_INTERVAL));
})
.catch(e => {
// TODO: Show error in UI
console.error('Error loading newest posts', e);
});
}
onMount(async () => {
interval = setInterval(refresh, refreshInterval);
// - If the page is hidden, slow down refresh rate
// - If the page is shown, bump up refresh rate
document.addEventListener('visibilitychange', () => {
const delay = document.hidden ? refreshInterval * 10 : refreshInterval;
if (interval) {
clearInterval(interval);
}
interval = setInterval(refresh, delay);
});
return () => {
if (interval !== null) {
clearInterval(interval)