docs/.vitepress/theme/composables/useFavicons.ts
99 lines · 3144 bytes
1import { useStorage } from '@vueuse/core'
2import { computed } from 'vue'
3
4import { FaviconsStorageKey } from '../constants'
5
6export function useFavicons() {
7 const favicons = useStorage(FaviconsStorageKey, 'off')
8 const faviconsEnabled = computed(() => favicons.value === 'on')
9
10 return { favicons, faviconsEnabled }
11}
12
13const FAVICON_BASE_URL = 'https://wfav.pages.dev/'
14let faviconManifestPromise: Promise<Record<string, string>> | null = null
15let faviconObserver: IntersectionObserver | null = null
16
17function getFaviconManifest() {
18 if (!faviconManifestPromise) {
19 faviconManifestPromise = fetch(`${FAVICON_BASE_URL}manifest.json`)
20 .then((res) => res.ok ? res.json() : Promise.reject(new Error(`HTTP ${res.status}`)))
21 .then((data) => (data.icons ?? {}) as Record<string, string>)
22 .catch(() => ({}) as Record<string, string>)
23 }
24 return faviconManifestPromise
25}
26
27function showGlobeFallback(el: HTMLElement) {
28 const span = document.createElement('span')
29 span.className = 'wk-favicon wk-favicon-fallback i-lucide:globe'
30 span.setAttribute('aria-hidden', 'true')
31 el.replaceWith(span)
32}
33
34async function loadFavicon(img: HTMLImageElement, domain: string) {
35 const icons = await getFaviconManifest()
36 const path = icons[domain]
37 if (!path) {
38 showGlobeFallback(img)
39 return
40 }
41 img.onerror = () => showGlobeFallback(img)
42 img.src = `${FAVICON_BASE_URL}${path}`
43}
44
45function ensureFaviconObserver() {
46 if (faviconObserver) return faviconObserver
47 faviconObserver = new IntersectionObserver((entries, observer) => {
48 for (const entry of entries) {
49 if (!entry.isIntersecting) continue
50 const img = entry.target as HTMLImageElement
51 const domain = img.dataset.domain
52 if (domain) loadFavicon(img, domain)
53 observer.unobserve(img)
54 }
55 }, { rootMargin: '200px' })
56 return faviconObserver
57}
58
59// Only plain `[text](url)` prose links
60export function applyFavicons(root: ParentNode) {
61 const origin = window.location.origin
62 const observer = ensureFaviconObserver()
63
64 root
65 .querySelectorAll<HTMLAnchorElement>('.vp-doc a[href]:not([data-favicon-applied])')
66 .forEach((link) => {
67 const href = link.getAttribute('href') ?? ''
68 if (!/^https?:\/\//i.test(href) || href.startsWith(origin)) return
69 if (link.querySelector('.highlight-pill, .icon-tip, img, svg')) return
70 if (!link.textContent?.trim()) return
71
72 let hostname: string
73 try {
74 hostname = new URL(href).hostname
75 } catch {
76 return
77 }
78
79 link.dataset.faviconApplied = '1'
80 const img = document.createElement('img')
81 img.className = 'wk-favicon'
82 img.alt = ''
83 img.width = 14
84 img.height = 14
85 img.decoding = 'async'
86 img.dataset.domain = hostname
87 link.prepend(img)
88 observer.observe(img)
89 })
90}
91
92export function removeFavicons() {
93 faviconObserver?.disconnect()
94 faviconObserver = null
95 document.querySelectorAll('.wk-favicon').forEach((el) => el.remove())
96 document
97 .querySelectorAll<HTMLElement>('.vp-doc a[data-favicon-applied]')
98 .forEach((link) => { delete link.dataset.faviconApplied })
99}