|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import { useEffect, useState } from 'react'; |
| 4 | +import { PiArrowUpRightBold, PiGitPullRequest, PiStarFill } from 'react-icons/pi'; |
| 5 | + |
| 6 | +const cacheDuration = 30 * 60 * 1000; |
| 7 | + |
| 8 | +function formatStars(value: number) { |
| 9 | + if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(value >= 10_000_000 ? 0 : 1)}m`; |
| 10 | + if (value >= 1_000) return `${(value / 1_000).toFixed(value >= 100_000 ? 0 : 1)}k`; |
| 11 | + return value.toLocaleString('en-US'); |
| 12 | +} |
| 13 | + |
| 14 | +export default function GitHubProjectStats({ repositoryUrl, prUrl }: { repositoryUrl: string; prUrl: string }) { |
| 15 | + const [stars, setStars] = useState<number | null>(null); |
| 16 | + const repository = new URL(repositoryUrl).pathname.replace(/^\//, '').replace(/\/$/, ''); |
| 17 | + const prNumber = new URL(prUrl).pathname.split('/').filter(Boolean).at(-1); |
| 18 | + |
| 19 | + useEffect(() => { |
| 20 | + const controller = new AbortController(); |
| 21 | + const cacheKey = `github-stars:${repository}`; |
| 22 | + |
| 23 | + const load = async () => { |
| 24 | + try { |
| 25 | + const cached = window.localStorage.getItem(cacheKey); |
| 26 | + if (cached) { |
| 27 | + const parsed = JSON.parse(cached) as { value: number; updatedAt: number }; |
| 28 | + if (typeof parsed.value === 'number') { |
| 29 | + setStars(parsed.value); |
| 30 | + if (Date.now() - parsed.updatedAt < cacheDuration) return; |
| 31 | + } |
| 32 | + } |
| 33 | + const response = await fetch(`https://api.github.com/repos/${repository}`, { |
| 34 | + headers: { Accept: 'application/vnd.github+json' }, |
| 35 | + signal: controller.signal, |
| 36 | + }); |
| 37 | + if (!response.ok) return; |
| 38 | + const data = await response.json() as { stargazers_count?: number }; |
| 39 | + if (typeof data.stargazers_count !== 'number') return; |
| 40 | + window.localStorage.setItem(cacheKey, JSON.stringify({ value: data.stargazers_count, updatedAt: Date.now() })); |
| 41 | + setStars(data.stargazers_count); |
| 42 | + } catch { |
| 43 | + // Keep the cached value or the loading fallback when GitHub rate-limits the request. |
| 44 | + } |
| 45 | + }; |
| 46 | + |
| 47 | + void load(); |
| 48 | + return () => controller.abort(); |
| 49 | + }, [repository]); |
| 50 | + |
| 51 | + return <section className="github-detail-stats" aria-label="GitHub 项目信息"> |
| 52 | + <div><PiStarFill aria-hidden="true" /><span>GitHub Stars</span><strong title={stars ? `${stars.toLocaleString('en-US')} Stars` : undefined}>{stars === null ? '—' : formatStars(stars)}</strong><small>每 30 分钟更新</small></div> |
| 53 | + <a href={prUrl} target="_blank" rel="noopener noreferrer"><PiGitPullRequest aria-hidden="true" /><span>我的 Pull Request</span><strong>#{prNumber} · MERGED</strong><small>查看上游合并记录 <PiArrowUpRightBold aria-hidden="true" /></small></a> |
| 54 | + </section>; |
| 55 | +} |
0 commit comments