-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.ts
96 lines (83 loc) · 2.66 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import { tryOnScopeDispose } from '@vueuse/shared'
import { computed, watch } from 'vue-demi'
import type { MaybeComputedElementRef } from '../unrefElement'
import { unrefElement } from '../unrefElement'
import { useSupported } from '../useSupported'
import type { ConfigurableWindow } from '../_configurable'
import { defaultWindow } from '../_configurable'
export interface ResizeObserverSize {
readonly inlineSize: number
readonly blockSize: number
}
export interface ResizeObserverEntry {
readonly target: Element
readonly contentRect: DOMRectReadOnly
readonly borderBoxSize?: ReadonlyArray<ResizeObserverSize>
readonly contentBoxSize?: ReadonlyArray<ResizeObserverSize>
readonly devicePixelContentBoxSize?: ReadonlyArray<ResizeObserverSize>
}
export type ResizeObserverCallback = (entries: ReadonlyArray<ResizeObserverEntry>, observer: ResizeObserver) => void
export interface UseResizeObserverOptions extends ConfigurableWindow {
/**
* Sets which box model the observer will observe changes to. Possible values
* are `content-box` (the default), `border-box` and `device-pixel-content-box`.
*
* @default 'content-box'
*/
box?: ResizeObserverBoxOptions
}
declare class ResizeObserver {
constructor(callback: ResizeObserverCallback)
disconnect(): void
observe(target: Element, options?: UseResizeObserverOptions): void
unobserve(target: Element): void
}
/**
* Reports changes to the dimensions of an Element's content or the border-box
*
* @see https://vueuse.org/useResizeObserver
* @param target
* @param callback
* @param options
*/
export function useResizeObserver(
target: MaybeComputedElementRef | MaybeComputedElementRef[],
callback: ResizeObserverCallback,
options: UseResizeObserverOptions = {},
) {
const { window = defaultWindow, ...observerOptions } = options
let observer: ResizeObserver | undefined
const isSupported = useSupported(() => window && 'ResizeObserver' in window)
const cleanup = () => {
if (observer) {
observer.disconnect()
observer = undefined
}
}
const targets = computed(() =>
Array.isArray(target)
? target.map(el => unrefElement(el))
: [unrefElement(target)])
const stopWatch = watch(
targets,
(els) => {
cleanup()
if (isSupported.value && window) {
observer = new ResizeObserver(callback)
for (const _el of els)
_el && observer!.observe(_el, observerOptions)
}
},
{ immediate: true, flush: 'post' },
)
const stop = () => {
cleanup()
stopWatch()
}
tryOnScopeDispose(stop)
return {
isSupported,
stop,
}
}
export type UseResizeObserverReturn = ReturnType<typeof useResizeObserver>