-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.ts
66 lines (53 loc) · 2.22 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
import { ref } from 'vue-demi'
import { useEventListener } from '../useEventListener'
import { useSupported } from '../useSupported'
import type { ConfigurableWindow } from '../_configurable'
import { defaultWindow } from '../_configurable'
// TypeScript dropped the inline types for these types in 5.2
// We vendor them here to avoid the dependency
export type OrientationType = 'portrait-primary' | 'portrait-secondary' | 'landscape-primary' | 'landscape-secondary'
export type OrientationLockType = 'any' | 'natural' | 'landscape' | 'portrait' | 'portrait-primary' | 'portrait-secondary' | 'landscape-primary' | 'landscape-secondary'
export interface ScreenOrientation extends EventTarget {
lock: (orientation: OrientationLockType) => Promise<void>
unlock: () => void
readonly type: OrientationType
readonly angle: number
addEventListener: (type: 'change', listener: (this: this, ev: Event) => any, useCapture?: boolean) => void
}
/**
* Reactive screen orientation
*
* @see https://vueuse.org/useScreenOrientation
*/
export function useScreenOrientation(options: ConfigurableWindow = {}) {
const {
window = defaultWindow,
} = options
const isSupported = useSupported(() => window && 'screen' in window && 'orientation' in window.screen)
const screenOrientation = (isSupported.value ? window!.screen.orientation : {}) as ScreenOrientation
const orientation = ref<OrientationType | undefined>(screenOrientation.type)
const angle = ref(screenOrientation.angle || 0)
if (isSupported.value) {
useEventListener(window, 'orientationchange', () => {
orientation.value = screenOrientation.type
angle.value = screenOrientation.angle
})
}
const lockOrientation = (type: OrientationLockType) => {
if (isSupported.value && typeof screenOrientation.lock === 'function')
return screenOrientation.lock(type)
return Promise.reject(new Error('Not supported'))
}
const unlockOrientation = () => {
if (isSupported.value && typeof screenOrientation.unlock === 'function')
screenOrientation.unlock()
}
return {
isSupported,
orientation,
angle,
lockOrientation,
unlockOrientation,
}
}
export type UseScreenOrientationReturn = ReturnType<typeof useScreenOrientation>