docs/.vitepress/theme/components/extrepo/iconObserver.ts

ba4f23d3bab9e2bb3b8efdb22317c8cc8f353ec5
wotaku/docs/.vitepress/theme/components/extrepo/iconObserver.ts history · blame · raw

41 lines · 1133 bytes

4 symbols in this file
 1import { ICON_ROOT_MARGIN } from './constants'
 2
 3const callbacks = new Map<Element, () => void>()
 4let observer: IntersectionObserver | undefined
 5
 6function ensureObserver(): IntersectionObserver | undefined {
 7  if (
 8    observer || typeof window === 'undefined' ||
 9    !('IntersectionObserver' in window)
10  ) return observer
11  observer = new IntersectionObserver((entries) => {
12    for (const entry of entries) {
13      if (!entry.isIntersecting) continue
14      const cb = callbacks.get(entry.target)
15      if (cb) {
16        callbacks.delete(entry.target)
17        observer?.unobserve(entry.target)
18        cb()
19      }
20    }
21  }, { rootMargin: ICON_ROOT_MARGIN })
22  return observer
23}
24
25// Shared observer for all lazy icons; calls cb once when visible.
26export function observeIcon(el: Element, cb: () => void): () => void {
27  const io = ensureObserver()
28  if (!io) {
29    cb()
30    return () => {}
31  }
32  callbacks.set(el, cb)
33  io.observe(el)
34  return () => {
35    callbacks.delete(el)
36    io.unobserve(el)
37  }
38}
39
40// Remembers load results per src so repeated icons skip the queue.
41export const iconResultCache = new Map<string, boolean>()