'use client'; import { useRef, useCallback, useEffect, useState } from 'react'; import Link from 'next/link'; import { useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { formatDistanceToNow } from 'date-fns'; import api from '@/services/api'; import { draftService } from '@/services/draftService'; // ── Types ───────────────────────────────────────────────────────────────────── export interface GitHubActivityFeedProps { username: string; githubUsername?: string; } type GitgramEventType = 'POST'; type GitHubEventType = 'PushEvent' | 'PullRequestEvent' | 'IssuesEvent' | 'WatchEvent' | 'ForkEvent'; interface GitgramPost { 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 GitHubRepo { owner: string; name: string; fullName: string; } interface GitHubPushPayload { commitCount: number; ref: string; commits?: Array<{ sha: string; message: string }>; } interface GitHubPRPayload { action: string; number: number; title: string; url: string; merged: boolean; } interface GitHubIssuePayload { action: string; number: number; title: string; url: string; } interface GitHubStarPayload { action: string; } interface GitHubForkPayload { forkee: string; } type GitHubPayload = | GitHubPushPayload | GitHubPRPayload | GitHubIssuePayload | GitHubStarPayload | GitHubForkPayload; interface GitHubEvent { id: string; type: GitHubEventType; createdAt: string; repo?: GitHubRepo; payload: GitHubPayload; actor: { login: string; avatarUrl?: string; }; } interface FeedItem { kind: 'gitgram'; sortKey: string; data: GitgramPost; } interface GitHubFeedItem { kind: 'github'; sortKey: string; data: GitHubEvent; } type ActivityItem = FeedItem | GitHubFeedItem; interface GitgramFeedPage { posts: GitgramPost[]; nextCursor: string | null; } interface GitHubActivityPage { events: GitHubEvent[]; nextCursor: string | null; } // ── Fetchers ────────────────────────────────────────────────────────────────── async function fetchGitgramActivity(cursor?: string): Promise { const params: Record = {}; if (cursor) params.cursor = cursor; const res = await api.get('/v1/social/activity-feed', { params }); const raw = res.data as { posts?: GitgramPost[]; nextCursor?: string | null }; return { posts: raw.posts ?? [], nextCursor: raw.nextCursor ?? null, }; } async function fetchGitHubActivity(username: string, cursor?: string): Promise { const params: Record = {}; if (cursor) params.cursor = cursor; const res = await api.get(`/v1/users/${username}/github-activity`, { params }); const raw = res.data as { events?: GitHubEvent[]; nextCursor?: string | null }; return { events: raw.events ?? [], nextCursor: raw.nextCursor ?? null, }; } // ── Helpers ─────────────────────────────────────────────────────────────────── function mergeAndSort( gitgramPages: GitgramFeedPage[], githubPages: GitHubActivityPage[] ): ActivityItem[] { const gitgramItems: FeedItem[] = gitgramPages .flatMap((p) => p.posts) .map((post) => ({ kind: 'gitgram' as const, sortKey: post.createdAt, data: post, })); const githubItems: GitHubFeedItem[] = githubPages .flatMap((p) => p.events) .map((event) => ({ kind: 'github' as const, sortKey: event.createdAt, data: event, })); return [...gitgramItems, ...githubItems].sort( (a, b) => new Date(b.sortKey).getTime() - new Date(a.sortKey).getTime() ); } function buildShareContent(event: GitHubEvent): string { const repoLabel = event.repo ? event.repo.fullName : 'a repository'; switch (event.type) { case 'PushEvent': { const payload = event.payload as GitHubPushPayload; const branch = payload.ref?.replace('refs/heads/', '') ?? 'main'; return `Just pushed ${payload.commitCount} commit${payload.commitCount !== 1 ? 's' : ''} to ${branch} on ${repoLabel} 🚀`; } case 'PullRequestEvent': { const payload = event.payload as GitHubPRPayload; return `Opened PR #${payload.number} on ${repoLabel}: "${payload.title}"`; } case 'IssuesEvent': { const payload = event.payload as GitHubIssuePayload; return `Opened issue #${payload.number} on ${repoLabel}: "${payload.title}"`; } case 'WatchEvent': return `Starred ${repoLabel} ⭐`; case 'ForkEvent': return `Forked ${repoLabel} 🍴`; default: return `Activity on ${repoLabel}`; } } // ── Sub-components ──────────────────────────────────────────────────────────── function RepoBadge({ repo }: { repo: GitHubRepo }) { return ( {repo.fullName} ); } // Icon components for event types function PushIcon() { return ( ); } function PullRequestIcon() { return ( ); } function IssueIcon() { return ( ); } function StarIcon() { return ( ); } function ForkIcon() { return ( ); } interface EventIconConfig { icon: React.ReactNode; bgClass: string; textClass: string; label: string; } function getEventConfig(type: GitHubEventType): EventIconConfig { switch (type) { case 'PushEvent': return { icon: , bgClass: 'bg-blue-100 dark:bg-blue-900/40', textClass: 'text-blue-600 dark:text-blue-400', label: 'Push', }; case 'PullRequestEvent': return { icon: , bgClass: 'bg-purple-100 dark:bg-purple-900/40', textClass: 'text-purple-600 dark:text-purple-400', label: 'Pull Request', }; case 'IssuesEvent': return { icon: , bgClass: 'bg-yellow-100 dark:bg-yellow-900/40', textClass: 'text-yellow-600 dark:text-yellow-400', label: 'Issue', }; case 'WatchEvent': return { icon: , bgClass: 'bg-amber-100 dark:bg-amber-900/40', textClass: 'text-amber-500 dark:text-amber-400', label: 'Star', }; case 'ForkEvent': return { icon: , bgClass: 'bg-green-100 dark:bg-green-900/40', textClass: 'text-green-600 dark:text-green-400', label: 'Fork', }; } } function buildEventDescription(event: GitHubEvent): string { const repoLabel = event.repo ? event.repo.fullName : 'a repository'; switch (event.type) { case 'PushEvent': { const payload = event.payload as GitHubPushPayload; const branch = payload.ref?.replace('refs/heads/', '') ?? 'main'; return `pushed ${payload.commitCount} commit${payload.commitCount !== 1 ? 's' : ''} to ${branch}`; } case 'PullRequestEvent': { const payload = event.payload as GitHubPRPayload; return `opened PR #${payload.number}: ${payload.title}`; } case 'IssuesEvent': { const payload = event.payload as GitHubIssuePayload; return `opened issue: ${payload.title}`; } case 'WatchEvent': return `starred ${repoLabel}`; case 'ForkEvent': return `forked ${repoLabel}`; } } interface ShareButtonProps { event: GitHubEvent; onShared: (draftId: string) => void; } function ShareToGitgramButton({ event, onShared }: ShareButtonProps) { const mutation = useMutation({ mutationFn: () => draftService.createDraft(buildShareContent(event)), onSuccess: (draft) => { onShared(draft.id); }, }); return ( ); } interface GitHubEventCardProps { event: GitHubEvent; } function GitHubEventCard({ event }: GitHubEventCardProps) { const [sharedDraftId, setSharedDraftId] = useState(null); const config = getEventConfig(event.type); const description = buildEventDescription(event); const avatarSrc = event.actor.avatarUrl ?? `https://avatars.githubusercontent.com/${event.actor.login}`; return (
{/* Event type icon */}
{/* Actor avatar + name */} {event.actor.login} {event.actor.login} {description}
{/* Repo chip */} {event.repo && (
)} {/* Footer row */}
{sharedDraftId && ( Edit draft )}
); } interface GitgramPostCardProps { post: GitgramPost; onLike: (id: string, liked: boolean) => void; } function GitgramPostCard({ post, onLike }: GitgramPostCardProps) { return (
{post.account.username[0].toUpperCase()}
@{post.account.username}

{post.content}

{post.commentsCount} {post.sharesCount}
); } function FeedSkeleton() { return (
{[1, 2, 3].map((i) => (
))}
); } // ── Main Component ──────────────────────────────────────────────────────────── export default function GitHubActivityFeed({ username, githubUsername }: GitHubActivityFeedProps) { const queryClient = useQueryClient(); const sentinelRef = useRef(null); // Gitgram activity feed — cursor-based infinite query const gitgramQuery = useInfiniteQuery({ queryKey: ['activity-feed', username], queryFn: ({ pageParam }) => fetchGitgramActivity(pageParam as string | undefined), initialPageParam: undefined as string | undefined, getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined, }); // GitHub raw activity feed (optional) const githubQuery = useInfiniteQuery({ queryKey: ['github-activity', githubUsername], queryFn: ({ pageParam }) => fetchGitHubActivity(githubUsername!, pageParam as string | undefined), initialPageParam: undefined as string | undefined, getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined, enabled: Boolean(githubUsername), }); // Determine if any next page is available across both queries const hasNextPage = gitgramQuery.hasNextPage || (githubUsername ? githubQuery.hasNextPage : false); const isFetchingNextPage = gitgramQuery.isFetchingNextPage || githubQuery.isFetchingNextPage; const fetchNextPageBoth = useCallback(() => { if (gitgramQuery.hasNextPage && !gitgramQuery.isFetchingNextPage) { gitgramQuery.fetchNextPage(); } if (githubUsername && githubQuery.hasNextPage && !githubQuery.isFetchingNextPage) { githubQuery.fetchNextPage(); } }, [gitgramQuery, githubQuery, githubUsername]); // Intersection Observer for infinite scroll const onIntersect = useCallback( (entries: IntersectionObserverEntry[]) => { if (entries[0].isIntersecting && hasNextPage && !isFetchingNextPage) { fetchNextPageBoth(); } }, [fetchNextPageBoth, hasNextPage, isFetchingNextPage] ); useEffect(() => { const el = sentinelRef.current; if (!el) return; const observer = new IntersectionObserver(onIntersect, { rootMargin: '300px' }); observer.observe(el); return () => observer.disconnect(); }, [onIntersect]); // 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 }) => { const queryKey = ['activity-feed', username]; await queryClient.cancelQueries({ queryKey }); const prev = queryClient.getQueryData(queryKey); queryClient.setQueryData(queryKey, (old: typeof gitgramQuery.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(['activity-feed', username], ctx.prev); } }, onSettled: () => { queryClient.invalidateQueries({ queryKey: ['activity-feed', username] }); }, }); // Build interleaved feed const gitgramPages = gitgramQuery.data?.pages ?? []; const githubPages = githubQuery.data?.pages ?? []; const feedItems = mergeAndSort(gitgramPages, githubPages); // Loading state — show skeleton on initial fetch const isInitialLoading = gitgramQuery.status === 'pending' || (githubUsername && githubQuery.status === 'pending' && !githubQuery.isFetchingNextPage); if (isInitialLoading) { return ; } // Error state if (gitgramQuery.status === 'error') { return (

Failed to load activity feed.

); } // Empty state if (feedItems.length === 0) { return (

No activity yet.

{githubUsername && (

GitHub events will appear here once activity is detected.

)}
); } return (
{feedItems.map((item) => { if (item.kind === 'gitgram') { return ( likeMutation.mutate({ id, liked })} /> ); } return ( ); })} {/* Infinite scroll sentinel */}