Skip to content

Commit

Permalink
intersection observer
Browse files Browse the repository at this point in the history
  • Loading branch information
eyeseast committed Mar 29, 2024
1 parent 828871d commit d94710a
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
35 changes: 34 additions & 1 deletion src/lib/components/documents/ResultsList.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
<script lang="ts">
import type { Document, DocumentResults } from "$lib/api/types";
import { onMount } from "svelte";
import { _ } from "svelte-i18n";
import DocumentListItem from "./DocumentListItem.svelte";
Expand All @@ -18,8 +19,11 @@
export let results: Document[] = [];
export let count: number = undefined;
export let next: string | null = null;
export let auto = false;
let loading = false;
let end: HTMLElement;
let observer: IntersectionObserver;
// load the next set of results
async function load(url: URL) {
Expand All @@ -38,7 +42,36 @@
count = r.count;
next = r.next;
loading = false;
watch();
}
function watch() {
const io = new IntersectionObserver((entries, observer) => {
entries.forEach(async (entry) => {
if (entry.isIntersecting && next) {
await load(new URL(next));
observer.unobserve(end);
}
});
});
io.observe(end);
return io;
}
function unwatch(io: IntersectionObserver) {
io.unobserve(end);
}
onMount(() => {
if (auto) {
observer = watch();
}
return () => {
unwatch(observer);
};
});
</script>

<div class="container">
Expand All @@ -56,7 +89,7 @@
<p>{$_("noDocuments.queryNoResults")}</p>
</Empty>
{/each}
<div class="end">
<div class="end" bind:this={end}>
{#if next}
<Button on:click={(e) => load(new URL(next))}>Load more</Button>
{/if}
Expand Down
1 change: 1 addition & 0 deletions src/routes/app/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
results={results.results}
count={results.count}
next={results.next}
auto
/>
{/await}

Expand Down

0 comments on commit d94710a

Please sign in to comment.