infinite scroll

This commit is contained in:
john 2025-05-03 23:51:17 +02:00
parent 9f8f6b55a5
commit 8cd565c647

View file

@ -3,88 +3,96 @@ import PostsFeed from '../components/PostsFeed.tsx'
import { useCallback, useEffect, useRef, useState } from 'react' import { useCallback, useEffect, useRef, useState } from 'react'
import './FeedView.css' import './FeedView.css'
// Stub for spinner component const PageSize = 10
const Spinner = () => (
<div className="animate-spin h-5 w-5 border-2 border-gray-500 rounded-full border-t-transparent"></div>
)
const PageSize = 2
interface FeedViewProps { interface FeedViewProps {
loadPosts: (cursor: string | null, amount: number) => Promise<Post[]> loadPosts: (cursor: string | null, amount: number) => Promise<Post[]>
} }
export default function FeedView({ loadPosts }: FeedViewProps) { export default function FeedView({ loadPosts }: FeedViewProps) {
const [pages, setPages] = useState<Post[][]>([]) const [pages, setPages] = useState<Post[][]>([])
const posts = pages.flat() const posts = pages.flat()
const [hasMore, setHasMore] = useState(true) const [hasMore, setHasMore] = useState(true)
const cursor = useRef<string | null>(null)
const [isLoading, setIsLoading] = useState(false) const [isLoading, setIsLoading] = useState(false)
const cursor = useRef<string | null>(null)
const loading = useRef(false) const loading = useRef(false)
const sentinelRef = useRef<HTMLDivElement | null>(null)
const loadNextPage = useCallback(async () => { const loadNextPage = useCallback(async () => {
if (loading.current) return if (loading.current || !hasMore) return
loading.current = true loading.current = true
setIsLoading(true)
try { try {
const page = await loadPosts(cursor.current, PageSize) const delay = new Promise((resolve) => setTimeout(resolve, 500)) // minimum delay
const pagePromise = loadPosts(cursor.current, PageSize)
if (page.length < PageSize) { const [page] = await Promise.all([pagePromise, delay]) // wait for both
setHasMore(false)
}
if (page.length < PageSize) setHasMore(false)
cursor.current = page.at(-1)?.postId ?? null cursor.current = page.at(-1)?.postId ?? null
setPages((prev) => [...prev, page]) setPages((prev) => [...prev, page])
} finally { } finally {
loading.current = false loading.current = false
setIsLoading(false) setIsLoading(false)
} }
}, [loadPosts]) }, [loadPosts, hasMore])
useEffect(() => { useEffect(() => {
const timeoutId = setTimeout(async () => { const observer = new IntersectionObserver(
await loadNextPage() (entries) => {
}) const entry = entries[0]
if (entry.isIntersecting) {
loadNextPage()
}
},
{
root: null,
rootMargin: '100px',
threshold: 0.1,
},
)
const sentinel = sentinelRef.current
if (sentinel) observer.observe(sentinel)
return () => { return () => {
clearTimeout(timeoutId) if (sentinel) observer.unobserve(sentinel)
} }
}, [loadNextPage]) }, [loadNextPage])
// Ensure content fills viewport after initial render
useEffect(() => {
const checkContentHeight = async () => {
while (
document.documentElement.scrollHeight <= window.innerHeight &&
hasMore &&
!loading.current
) {
await loadNextPage()
}
}
checkContentHeight()
}, [posts.length, loadNextPage, hasMore])
return ( return (
<main className={`w-full max-w-full px-12 py-6`}> <main className="w-full max-w-full px-12 py-6">
<div className={`col-start-1`}> <div className="col-start-1">
<PostsFeed posts={posts} /> <PostsFeed posts={posts} />
{hasMore && ( {isLoading && (
<LoadMoreButton state={isLoading ? 'loading' : 'ready'} onClick={loadNextPage} /> <div className="w-full flex justify-center py-4">
<Spinner />
</div>
)} )}
<div ref={sentinelRef} className="h-1" />
</div> </div>
</main> </main>
) )
} }
interface LoadMoreButtonProps { // Spinner component
state: 'ready' | 'loading' const Spinner = () => (
onClick: () => void <div className="animate-spin h-5 w-5 border-2 border-gray-500 rounded-full border-t-transparent"></div>
} )
function LoadMoreButton({ state, onClick }: LoadMoreButtonProps) {
const buttonClasses =
'w-full py-3 px-4 bg-gray-100 hover:bg-gray-200 text-gray-800 rounded-md flex items-center justify-center disabled:opacity-70'
switch (state) {
case 'loading':
return (
<button disabled={true} className={buttonClasses}>
<Spinner />
</button>
)
case 'ready':
return (
<button className={buttonClasses} onClick={onClick}>
Load more
</button>
)
}
}