|
| 1 | +export function initGithubStars(theme) { |
| 2 | + if (typeof document === 'undefined') return |
| 3 | + |
| 4 | + const githubLink = theme.value?.socialLinks?.find( |
| 5 | + (l) => l.icon === 'github' || l.link.includes('github.com') |
| 6 | + )?.link |
| 7 | + |
| 8 | + if (!githubLink) return |
| 9 | + |
| 10 | + const match = githubLink.match(/github\.com\/([^/]+\/[^/]+)/) |
| 11 | + if (!match) return |
| 12 | + |
| 13 | + let repoName = match[1].replace(/\.git$/, '').replace(/\/$/, '') |
| 14 | + |
| 15 | + fetch(`https://api.github.com/repos/${repoName}`) |
| 16 | + .then((res) => res.json()) |
| 17 | + .then((data) => { |
| 18 | + if (data.stargazers_count !== undefined) { |
| 19 | + const stars = data.stargazers_count |
| 20 | + const formatStars = (num) => (num > 999 ? (num / 1000).toFixed(1) + 'k' : num) |
| 21 | + const starsText = formatStars(stars) |
| 22 | + |
| 23 | + const injectStars = () => { |
| 24 | + document.querySelectorAll('.VPSocialLink[href*="github.com"]').forEach((el) => { |
| 25 | + if (!el.querySelector('.ct-github-stars')) { |
| 26 | + const span = document.createElement('span') |
| 27 | + span.className = 'ct-github-stars' |
| 28 | + span.textContent = starsText |
| 29 | + |
| 30 | + el.appendChild(span) |
| 31 | + |
| 32 | + el.style.width = 'auto' |
| 33 | + el.style.padding = '0 8px' |
| 34 | + el.style.textDecoration = 'none' |
| 35 | + el.style.gap = '6px' |
| 36 | + |
| 37 | + span.style.fontSize = '13px' |
| 38 | + span.style.fontWeight = '500' |
| 39 | + span.style.fontFamily = 'var(--vp-font-family-base)' |
| 40 | + } |
| 41 | + }) |
| 42 | + } |
| 43 | + |
| 44 | + const observer = new MutationObserver(injectStars) |
| 45 | + observer.observe(document.body, { childList: true, subtree: true }) |
| 46 | + injectStars() |
| 47 | + } |
| 48 | + }) |
| 49 | + .catch(console.error) |
| 50 | +} |
0 commit comments