'use client'; import Link from 'next/link'; import { useMutation, useQueryClient } from '@tanstack/react-query'; import api from '@/services/api'; import { buildRepoPath } from '@/utils/repositoryRouting'; const LANGUAGE_COLORS: Record = { JavaScript: '#f1e05a', TypeScript: '#3178c6', Python: '#3572A5', Go: '#00ADD8', Rust: '#dea584', }; const MAX_VISIBLE_TOPICS = 3; interface RepositorySocialCardProps { id: string; owner: string; name: string; fullName: string; description?: string; stars: number; forks: number; language?: string; topics?: string[]; isFollowed?: boolean; followersCount?: number; } interface FollowState { isFollowed: boolean; followersCount: number; } function formatCount(n: number): string { if (n >= 1000) { return `${(n / 1000).toFixed(1).replace(/\.0$/, '')}k`; } return String(n); } export default function RepositorySocialCard({ id, owner, name, fullName, description, stars, forks, language, topics = [], isFollowed = false, followersCount = 0, }: RepositorySocialCardProps) { const queryClient = useQueryClient(); const queryKey = ['repo-follow', id]; const currentState: FollowState = queryClient.getQueryData(queryKey) ?? { isFollowed, followersCount, }; const { mutate, isPending } = useMutation({ mutationFn: async () => { if (currentState.isFollowed) { await api.delete(`/v1/repositories/${id}/follow`); } else { await api.post(`/v1/repositories/${id}/follow`); } }, onMutate: async () => { await queryClient.cancelQueries({ queryKey }); const prev = queryClient.getQueryData(queryKey) ?? { isFollowed, followersCount }; const next: FollowState = { isFollowed: !prev.isFollowed, followersCount: prev.isFollowed ? prev.followersCount - 1 : prev.followersCount + 1, }; queryClient.setQueryData(queryKey, next); return { prev }; }, onError: (_err, _vars, ctx) => { if (ctx?.prev) { queryClient.setQueryData(queryKey, ctx.prev); } }, onSettled: () => { queryClient.invalidateQueries({ queryKey }); }, }); const state = queryClient.getQueryData(queryKey) ?? { isFollowed, followersCount }; const languageColor = language ? (LANGUAGE_COLORS[language] ?? '#6b7280') : null; const visibleTopics = topics.slice(0, MAX_VISIBLE_TOPICS); const extraTopics = topics.length - MAX_VISIBLE_TOPICS; return (
{fullName} {description && (

{description}

)}
{languageColor && language && ( )} {formatCount(stars)} {formatCount(forks)} {state.followersCount > 0 && ( {formatCount(state.followersCount)} )}
{visibleTopics.length > 0 && (
{visibleTopics.map((topic) => ( {topic} ))} {extraTopics > 0 && ( +{extraTopics} more )}
)}
); }