forked from vueuse/vueuse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
45 lines (37 loc) · 1.03 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
import { ref } from 'vue-demi'
import { type Fn, tryOnScopeDispose } from '@vueuse/shared'
import { type ConfigurableWindow, defaultWindow } from '../_configurable'
/**
* Reactively track `window.devicePixelRatio`.
*
* @see https://vueuse.org/useDevicePixelRatio
* @param options
*/
export function useDevicePixelRatio({
window = defaultWindow,
}: ConfigurableWindow = {}) {
if (!window) {
return {
pixelRatio: ref(1),
}
}
const pixelRatio = ref(1)
const cleanups: Fn[] = []
const cleanup = () => {
cleanups.map(i => i())
cleanups.length = 0
}
const observe = () => {
pixelRatio.value = window.devicePixelRatio
cleanup()
const media = window.matchMedia(`(resolution: ${pixelRatio.value}dppx)`)
media.addEventListener('change', observe, { once: true })
cleanups.push(() => {
media.removeEventListener('change', observe)
})
}
observe()
tryOnScopeDispose(cleanup)
return { pixelRatio }
}
export type UseDevicePixelRatioReturn = ReturnType<typeof useDevicePixelRatio>