-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.ts
49 lines (40 loc) · 1.55 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
import type { Ref } from 'vue-demi'
import { ref } from 'vue-demi'
import type { WindowEventName } from '../useEventListener'
import { useEventListener } from '../useEventListener'
import type { ConfigurableDocument } from '../_configurable'
import { defaultDocument } from '../_configurable'
export type KeyModifier = 'Alt' | 'AltGraph' | 'CapsLock' | 'Control' | 'Fn' | 'FnLock' | 'Meta' | 'NumLock' | 'ScrollLock' | 'Shift' | 'Symbol' | 'SymbolLock'
const defaultEvents: WindowEventName[] = ['mousedown', 'mouseup', 'keydown', 'keyup']
export interface UseModifierOptions<Initial> extends ConfigurableDocument {
/**
* Event names that will prompt update to modifier states
*
* @default ['mousedown', 'mouseup', 'keydown', 'keyup']
*/
events?: WindowEventName[]
/**
* Initial value of the returned ref
*
* @default null
*/
initial?: Initial
}
export type UseKeyModifierReturn<Initial> = Ref<Initial extends boolean ? boolean : boolean | null>
export function useKeyModifier<Initial extends boolean | null>(modifier: KeyModifier, options: UseModifierOptions<Initial> = {}): UseKeyModifierReturn<Initial> {
const {
events = defaultEvents,
document = defaultDocument,
initial = null,
} = options
const state = ref(initial) as Ref<boolean>
if (document) {
events.forEach((listenerEvent) => {
useEventListener(document, listenerEvent, (evt: KeyboardEvent | MouseEvent) => {
if (typeof evt.getModifierState === 'function')
state.value = evt.getModifierState(modifier)
})
})
}
return state
}