1
import { VNodeDirective } from 'vue/types/vnode'
2

3
type ObserveHandler = (
4
  entries: IntersectionObserverEntry[],
5
  observer: IntersectionObserver,
6
  isIntersecting: boolean,
7
) => void
8

9
interface ObserveVNodeDirective extends Omit<VNodeDirective, 'modifiers'> {
10
  value?: ObserveHandler | { handler: ObserveHandler, options?: IntersectionObserverInit }
11
  modifiers?: {
12
    once?: boolean
13
    quiet?: boolean
14
  }
15
}
16

17 1
function inserted (el: HTMLElement, binding: ObserveVNodeDirective) {
18 1
  const modifiers = binding.modifiers || {}
19 1
  const value = binding.value
20 1
  const { handler, options } = typeof value === 'object'
21 1
    ? value
22 1
    : { handler: value, options: {} }
23 1
  const observer = new IntersectionObserver((
24 1
    entries: IntersectionObserverEntry[] = [],
25
    observer: IntersectionObserver
26 1
  ) => {
27
    /* istanbul ignore if */
28 1
    if (!el._observe) return // Just in case, should never fire
29

30
    // If is not quiet or has already been
31
    // initted, invoke the user callback
32 1
    if (
33 1
      handler && (
34 1
        !modifiers.quiet ||
35 1
        el._observe.init
36
      )
37
    ) {
38 1
      const isIntersecting = Boolean(entries.find(entry => entry.isIntersecting))
39

40 1
      handler(entries, observer, isIntersecting)
41
    }
42

43
    // If has already been initted and
44
    // has the once modifier, unbind
45 1
    if (el._observe.init && modifiers.once) unbind(el)
46
    // Otherwise, mark the observer as initted
47 1
    else (el._observe.init = true)
48
  }, options)
49

50 1
  el._observe = { init: false, observer }
51

52 1
  observer.observe(el)
53
}
54

55 1
function unbind (el: HTMLElement) {
56
  /* istanbul ignore if */
57 1
  if (!el._observe) return
58

59 1
  el._observe.observer.unobserve(el)
60 1
  delete el._observe
61
}
62

63 1
export const Intersect = {
64
  inserted,
65
  unbind,
66
}
67

68
export default Intersect

Read our documentation on viewing source code .

Loading