docs/.vitepress/theme/composables/useFavicons.ts

ba4f23d3bab9e2bb3b8efdb22317c8cc8f353ec5
wotaku/docs/.vitepress/theme/composables/useFavicons.ts history · blame · raw

105 lines · 3367 bytes

9 symbols in this file
  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
 27export async function resolveFaviconUrl(domain: string): Promise<string | null> {
 28  const icons = await getFaviconManifest()
 29  const path = icons[domain.toLowerCase()]
 30  return path ? `${FAVICON_BASE_URL}${path}` : null
 31}
 32
 33function showGlobeFallback(el: HTMLElement) {
 34  const span = document.createElement('span')
 35  span.className = 'wk-favicon wk-favicon-fallback i-lucide:globe'
 36  span.setAttribute('aria-hidden', 'true')
 37  el.replaceWith(span)
 38}
 39
 40async function loadFavicon(img: HTMLImageElement, domain: string) {
 41  const icons = await getFaviconManifest()
 42  const path = icons[domain]
 43  if (!path) {
 44    showGlobeFallback(img)
 45    return
 46  }
 47  img.onerror = () => showGlobeFallback(img)
 48  img.src = `${FAVICON_BASE_URL}${path}`
 49}
 50
 51function ensureFaviconObserver() {
 52  if (faviconObserver) return faviconObserver
 53  faviconObserver = new IntersectionObserver((entries, observer) => {
 54    for (const entry of entries) {
 55      if (!entry.isIntersecting) continue
 56      const img = entry.target as HTMLImageElement
 57      const domain = img.dataset.domain
 58      if (domain) loadFavicon(img, domain)
 59      observer.unobserve(img)
 60    }
 61  }, { rootMargin: '200px' })
 62  return faviconObserver
 63}
 64
 65// Only plain `[text](url)` prose links
 66export function applyFavicons(root: ParentNode) {
 67  const origin = window.location.origin
 68  const observer = ensureFaviconObserver()
 69
 70  root
 71    .querySelectorAll<HTMLAnchorElement>('.vp-doc a[href]:not([data-favicon-applied])')
 72    .forEach((link) => {
 73      const href = link.getAttribute('href') ?? ''
 74      if (!/^https?:\/\//i.test(href) || href.startsWith(origin)) return
 75      if (link.querySelector('.highlight-pill, .icon-tip, img, svg')) return
 76      if (!link.textContent?.trim()) return
 77
 78      let hostname: string
 79      try {
 80        hostname = new URL(href).hostname
 81      } catch {
 82        return
 83      }
 84
 85      link.dataset.faviconApplied = '1'
 86      const img = document.createElement('img')
 87      img.className = 'wk-favicon'
 88      img.alt = ''
 89      img.width = 14
 90      img.height = 14
 91      img.decoding = 'async'
 92      img.dataset.domain = hostname
 93      link.prepend(img)
 94      observer.observe(img)
 95    })
 96}
 97
 98export function removeFavicons() {
 99  faviconObserver?.disconnect()
100  faviconObserver = null
101  document.querySelectorAll('.wk-favicon').forEach((el) => el.remove())
102  document
103    .querySelectorAll<HTMLElement>('.vp-doc a[data-favicon-applied]')
104    .forEach((link) => { delete link.dataset.faviconApplied })
105}