-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.ts
56 lines (46 loc) · 1.69 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
/* this implementation is original ported from https://github.com/logaretm/vue-use-web by Abdelrahman Awad */
import { ref, watchEffect } from 'vue-demi'
import type { MaybeComputedRef } from '@vueuse/shared'
import { resolveRef, tryOnScopeDispose } from '@vueuse/shared'
import type { ConfigurableWindow } from '../_configurable'
import { defaultWindow } from '../_configurable'
import { useSupported } from '../useSupported'
/**
* Reactive Media Query.
*
* @see https://vueuse.org/useMediaQuery
* @param query
* @param options
*/
export function useMediaQuery(query: MaybeComputedRef<string>, options: ConfigurableWindow = {}) {
const { window = defaultWindow } = options
const isSupported = useSupported(() => window && 'matchMedia' in window && typeof window.matchMedia === 'function')
let mediaQuery: MediaQueryList | undefined
const matches = ref(false)
const cleanup = () => {
if (!mediaQuery)
return
if ('removeEventListener' in mediaQuery)
// eslint-disable-next-line @typescript-eslint/no-use-before-define
mediaQuery.removeEventListener('change', update)
else
// @ts-expect-error deprecated API
// eslint-disable-next-line @typescript-eslint/no-use-before-define
mediaQuery.removeListener(update)
}
const update = () => {
if (!isSupported.value)
return
cleanup()
mediaQuery = window!.matchMedia(resolveRef(query).value)
matches.value = mediaQuery.matches
if ('addEventListener' in mediaQuery)
mediaQuery.addEventListener('change', update)
else
// @ts-expect-error deprecated API
mediaQuery.addListener(update)
}
watchEffect(update)
tryOnScopeDispose(() => cleanup())
return matches
}