'use client'; import { useRef, useCallback, useEffect, useState } from 'react'; import Link from 'next/link'; import { useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import RepoCard from './RepoCard'; import RichContent from './RichContent'; import AitmChangeStoryCard from './AitmChangeStoryCard'; import BookmarkButton from './BookmarkButton'; import LoadLatestButton from './LoadLatestButton'; import { parseAitmChangeStoryBlock } from '@/utils/aitmChangeStory'; import ContentHider from './moderation/ContentHider'; import { useModeration } from '@/hooks/useModeration'; import { isPostMuted, parseSelfLabel } from '@/utils/moderation'; import { realtimeService } from '@/services/realtimeService'; import { useFeedFeedback } from '@/hooks/useFeedFeedback'; import PostFeedbackMenu from './PostFeedbackMenu'; import SeenTracker from './SeenTracker'; import api from '@/services/api'; interface Post { id: string; content: string; createdAt: string; likesCount: number; commentsCount: number; sharesCount: number; likedByMe?: boolean; account: { username: string; type: 'USER' | 'REPOSITORY' | 'ORGANIZATION'; avatar?: string; displayName?: string; }; } interface Repo { id: string; owner: string; name: string; fullName: string; description?: string; stars: number; forks: number; language?: string; } interface FeedPage { posts: Post[]; nextCursor: string | null; isDiscover?: boolean; } async function fetchFeedPage(cursor?: string): Promise { const params: Record = {}; if (cursor) params.cursor = cursor; const res = await api.get('/v1/posts/feed', { params }); const data = res.data as FeedPage; // Following feed empty → fall back to discover (Bluesky HomeFeedAPI pattern) if (!data.posts?.length && !cursor) { const discoverRes = await api.get('/v1/posts/explore', { params: { limit: '20' } }); const discoverData = discoverRes.data as FeedPage; return { posts: discoverData.posts || [], nextCursor: discoverData.nextCursor ?? null, isDiscover: true }; } return { posts: data.posts || [], nextCursor: data.nextCursor ?? null }; } /** * Lightweight poll for the very latest post ids at the top of the feed. Used to * detect content published after the feed rendered without disturbing the * existing infinite-query cache. Returns ids newest-first. */ async function fetchLatestPostIds(): Promise { const res = await api.get('/v1/posts/feed', { params: { limit: '20' } }); const data = res.data as FeedPage; return (data.posts ?? []).map((p) => p.id); } const NEW_POSTS_POLL_INTERVAL_MS = 60_000; const ACCOUNT_BADGES = { USER: { color: 'bg-blue-500', icon: '👤' }, REPOSITORY: { color: 'bg-purple-500', icon: '📦' }, ORGANIZATION: { color: 'bg-green-500', icon: '🏢' }, } as const; export default function Feed() { const queryClient = useQueryClient(); const sentinelRef = useRef(null); const moderation = useModeration(); const feedback = useFeedFeedback(); // ── Infinite feed query ──────────────────────────────────────────────────── const { data, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage, status, } = useInfiniteQuery({ queryKey: ['feed'], queryFn: ({ pageParam }) => fetchFeedPage(pageParam as string | undefined), initialPageParam: undefined as string | undefined, getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined, }); const allPosts = data?.pages.flatMap((p) => p.posts) ?? []; const isDiscover = data?.pages[0]?.isDiscover; // Apply client-side moderation (muted words / accounts / threads) and hide // posts the viewer marked "not interested". const posts = allPosts.filter( (post) => !feedback.isHidden(post.id) && !isPostMuted( { id: post.id, content: post.content ?? '', username: post.account.username }, moderation, ), ); const mutedCount = allPosts.length - posts.length; // ── "New posts" pill: surface content published after the feed rendered ──── const [newPostCount, setNewPostCount] = useState(0); const loadedIds = useRef>(new Set()); loadedIds.current = new Set(allPosts.map((p) => p.id)); const checkForNewPosts = useCallback(async () => { // Don't bother on the discover fallback — it isn't a chronological feed. if (isDiscover) return; try { const latestIds = await fetchLatestPostIds(); const known = loadedIds.current; const fresh = latestIds.filter((id) => !known.has(id)).length; if (fresh > 0) setNewPostCount(fresh); } catch { // Polling failures are non-fatal — keep the existing feed intact. } }, [isDiscover]); // Poll on an interval while the tab is visible. useEffect(() => { if (status !== 'success') return; const tick = () => { if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return; void checkForNewPosts(); }; const interval = setInterval(tick, NEW_POSTS_POLL_INTERVAL_MS); return () => clearInterval(interval); }, [status, checkForNewPosts]); // React immediately to realtime like activity as a cheap "something changed" // signal, then confirm with a targeted poll. useEffect(() => { const unsubscribe = realtimeService.onNotification((n) => { if (n.type === 'post' || n.type === 'mention' || n.type === 'new_post') { void checkForNewPosts(); } }); return unsubscribe; }, [checkForNewPosts]); const handleLoadLatest = useCallback(async () => { setNewPostCount(0); if (typeof window !== 'undefined') { window.scrollTo({ top: 0, behavior: 'smooth' }); } // Refetch the first page so freshly-published posts are prepended. await queryClient.invalidateQueries({ queryKey: ['feed'] }); }, [queryClient]); // ── Intersection Observer for infinite scroll ────────────────────────────── const onIntersect = useCallback( (entries: IntersectionObserverEntry[]) => { if (entries[0].isIntersecting && hasNextPage && !isFetching) { fetchNextPage(); } }, [fetchNextPage, hasNextPage, isFetching] ); useEffect(() => { const el = sentinelRef.current; if (!el) return; const observer = new IntersectionObserver(onIntersect, { rootMargin: '200px' }); observer.observe(el); return () => observer.disconnect(); }, [onIntersect]); // ── Trending repos (one-shot, no pagination needed) ──────────────────────── const { data: trendingData } = useInfiniteQuery({ queryKey: ['trending-repos'], queryFn: async () => { const res = await api.get('/v1/repositories/trending'); const repos: Repo[] = ((res.data as { repositories?: Repo[] }).repositories || []).slice(0, 3); return repos; }, initialPageParam: undefined, getNextPageParam: () => undefined, }); const trendingRepos = trendingData?.pages[0] ?? []; // ── Optimistic like mutation ─────────────────────────────────────────────── const likeMutation = useMutation({ mutationFn: async ({ id, liked }: { id: string; liked: boolean }) => { if (liked) { await api.delete(`/v1/posts/${id}/like`); } else { await api.post(`/v1/posts/${id}/like`); } }, onMutate: async ({ id, liked }) => { await queryClient.cancelQueries({ queryKey: ['feed'] }); const prev = queryClient.getQueryData(['feed']); queryClient.setQueryData(['feed'], (old: typeof data) => { if (!old) return old; return { ...old, pages: old.pages.map((page) => ({ ...page, posts: page.posts.map((p) => p.id === id ? { ...p, likedByMe: !liked, likesCount: liked ? p.likesCount - 1 : p.likesCount + 1, } : p ), })), }; }); return { prev }; }, onError: (_err, _vars, ctx) => { if (ctx?.prev) queryClient.setQueryData(['feed'], ctx.prev); }, onSettled: () => { queryClient.invalidateQueries({ queryKey: ['feed'] }); }, }); // ── Render ───────────────────────────────────────────────────────────────── if (status === 'pending') { return (
{[1, 2, 3].map((i) => (
))}
); } if (status === 'error') { return (

Failed to load feed. Please try again.

); } if (!posts.length) { // Distinguish a genuinely empty feed from one fully hidden by moderation. if (mutedCount > 0) { return (

All {mutedCount} post{mutedCount === 1 ? '' : 's'} here are hidden by your muted words or accounts.

Manage moderation filters
); } return (

No posts yet

Follow some accounts or{' '} claim a repository

); } return (
{isDiscover && (

Showing popular posts — follow more people to personalize your feed

)} {mutedCount > 0 && (

{mutedCount} post{mutedCount === 1 ? '' : 's'} hidden by your{' '} moderation filters

)} {trendingRepos.length > 0 && (

Trending Repos

{trendingRepos.map((repo) => ( ))}
)} {posts.map((post) => { const badge = ACCOUNT_BADGES[post.account.type] ?? ACCOUNT_BADGES.USER; const { label: selfLabel, cleanContent: labelledContent } = parseSelfLabel(post.content || ''); const { story, cleanContent } = parseAitmChangeStoryBlock(labelledContent); return ( feedback.markSeen(post.id)}>
{post.account.username[0].toUpperCase()}
@{post.account.username} {badge.icon}
{new Date(post.createdAt).toLocaleString()}
feedback.requestLess(post.id)} onShowMore={() => feedback.requestMore(post.id)} />
{story && }
); })} {/* Infinite scroll sentinel */}
{isFetchingNextPage && (
)} {!hasNextPage && posts.length > 0 && (

You're all caught up

)}
); }