/
index.ts
70 lines (57 loc) · 1.65 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
/* this implementation is original ported from https://github.com/streamich/react-use by Vadim Dalecky */
import { useEventListener } from '../useEventListener'
import type { ConfigurableDocument } from '../_configurable'
import { defaultDocument } from '../_configurable'
function isFocusedElementEditable() {
const { activeElement, body } = document
if (!activeElement)
return false
// If not element has focus, we assume it is not editable, too.
if (activeElement === body)
return false
// Assume <input> and <textarea> elements are editable.
switch (activeElement.tagName) {
case 'INPUT':
case 'TEXTAREA':
return true
}
// Check if any other focused element id editable.
return activeElement.hasAttribute('contenteditable')
}
function isTypedCharValid({
keyCode,
metaKey,
ctrlKey,
altKey,
}: KeyboardEvent) {
if (metaKey || ctrlKey || altKey)
return false
// 0...9
if (keyCode >= 48 && keyCode <= 57)
return true
// A...Z
if (keyCode >= 65 && keyCode <= 90)
return true
// a...z
if (keyCode >= 97 && keyCode <= 122)
return true
// All other keys.
return false
}
/**
* Fires when users start typing on non-editable elements.
*
* @see https://vueuse.org/onStartTyping
* @param callback
* @param options
*/
export function onStartTyping(callback: (event: KeyboardEvent) => void, options: ConfigurableDocument = {}) {
const { document = defaultDocument } = options
const keydown = (event: KeyboardEvent) => {
!isFocusedElementEditable()
&& isTypedCharValid(event)
&& callback(event)
}
if (document)
useEventListener(document, 'keydown', keydown, { passive: true })
}