forked from vueuse/vueuse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
47 lines (42 loc) · 1.36 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import type { MaybeRefOrGetter } from '@vueuse/shared'
import { ref } from 'vue-demi'
import type { MaybeComputedElementRef } from '../unrefElement'
import { useIntersectionObserver } from '../useIntersectionObserver'
import type { ConfigurableWindow } from '../_configurable'
import { defaultWindow } from '../_configurable'
export interface UseElementVisibilityOptions extends ConfigurableWindow {
scrollTarget?: MaybeRefOrGetter<HTMLElement | undefined | null>
}
/**
* Tracks the visibility of an element within the viewport.
*
* @see https://vueuse.org/useElementVisibility
*/
export function useElementVisibility(
element: MaybeComputedElementRef,
options: UseElementVisibilityOptions = {},
) {
const { window = defaultWindow, scrollTarget } = options
const elementIsVisible = ref(false)
useIntersectionObserver(
element,
(intersectionObserverEntries) => {
let isIntersecting = elementIsVisible.value
// Get the latest value of isIntersecting based on the entry time
let latestTime = 0
for (const entry of intersectionObserverEntries) {
if (entry.time >= latestTime) {
latestTime = entry.time
isIntersecting = entry.isIntersecting
}
}
elementIsVisible.value = isIntersecting
},
{
root: scrollTarget,
window,
threshold: 0,
},
)
return elementIsVisible
}