'use client'
import { useEffect, useRef, useCallback } from 'react'
export interface GridPost {
id: string
content: string
author: {
username: string
avatarUrl?: string
}
likes: number
comments: number
createdAt: string
thumbnailUrl?: string
/** Author-supplied alt text for the thumbnail (accessibility). */
thumbnailAlt?: string
}
export interface PostGridProps {
posts: GridPost[]
onLoadMore: () => void
hasMore: boolean
isLoading: boolean
}
const CONTENT_PREVIEW_MAX = 80
function truncate(text: string, max: number): string {
if (text.length <= max) return text
return text.slice(0, max).trimEnd() + '…'
}
function HeartIcon() {
return (
)
}
function CommentIcon() {
return (
)
}
function SkeletonCell() {
return (
)
}
function PostCell({ post }: { post: GridPost }) {
const preview = truncate(post.content, CONTENT_PREVIEW_MAX)
return (
{/* Background: thumbnail image or gradient fallback */}
{post.thumbnailUrl ? (
) : (
)}
{/* Content preview bar (always visible at bottom) */}
{/* Hover overlay with like/comment counts */}
{post.likes.toLocaleString()}
{post.comments.toLocaleString()}
@{post.author.username}
)
}
export default function PostGrid({
posts,
onLoadMore,
hasMore,
isLoading,
}: PostGridProps) {
const sentinelRef = useRef(null)
// Stable ref so the IntersectionObserver callback never captures stale props
const onLoadMoreRef = useRef(onLoadMore)
useEffect(() => {
onLoadMoreRef.current = onLoadMore
}, [onLoadMore])
const handleIntersect = useCallback(
(entries: IntersectionObserverEntry[]) => {
const [entry] = entries
if (entry.isIntersecting && hasMore && !isLoading) {
onLoadMoreRef.current()
}
},
[hasMore, isLoading],
)
useEffect(() => {
const el = sentinelRef.current
if (!el) return
const observer = new IntersectionObserver(handleIntersect, {
rootMargin: '120px',
threshold: 0,
})
observer.observe(el)
return () => observer.disconnect()
}, [handleIntersect])
return (
<>
{posts.map((post) => (
))}
{isLoading &&
Array.from({ length: 6 }).map((_, i) => (
))}
{/* Sentinel element watched by IntersectionObserver */}
{!hasMore && !isLoading && posts.length > 0 && (
You’ve reached the end
)}
>
)
}