1 | import useIsomorphicLayoutEffect from './useIsomorphicLayoutEffect';
|
---|
2 | import { off, on } from './misc/util';
|
---|
3 | var isFocusedElementEditable = function () {
|
---|
4 | var activeElement = document.activeElement, body = document.body;
|
---|
5 | if (!activeElement) {
|
---|
6 | return false;
|
---|
7 | }
|
---|
8 | // If not element has focus, we assume it is not editable, too.
|
---|
9 | if (activeElement === body) {
|
---|
10 | return false;
|
---|
11 | }
|
---|
12 | // Assume <input> and <textarea> elements are editable.
|
---|
13 | switch (activeElement.tagName) {
|
---|
14 | case 'INPUT':
|
---|
15 | case 'TEXTAREA':
|
---|
16 | return true;
|
---|
17 | }
|
---|
18 | // Check if any other focused element id editable.
|
---|
19 | return activeElement.hasAttribute('contenteditable');
|
---|
20 | };
|
---|
21 | var isTypedCharGood = function (_a) {
|
---|
22 | var keyCode = _a.keyCode, metaKey = _a.metaKey, ctrlKey = _a.ctrlKey, altKey = _a.altKey;
|
---|
23 | if (metaKey || ctrlKey || altKey) {
|
---|
24 | return false;
|
---|
25 | }
|
---|
26 | // 0...9
|
---|
27 | if (keyCode >= 48 && keyCode <= 57) {
|
---|
28 | return true;
|
---|
29 | }
|
---|
30 | // a...z
|
---|
31 | if (keyCode >= 65 && keyCode <= 90) {
|
---|
32 | return true;
|
---|
33 | }
|
---|
34 | // All other keys.
|
---|
35 | return false;
|
---|
36 | };
|
---|
37 | var useStartTyping = function (onStartTyping) {
|
---|
38 | useIsomorphicLayoutEffect(function () {
|
---|
39 | var keydown = function (event) {
|
---|
40 | !isFocusedElementEditable() && isTypedCharGood(event) && onStartTyping(event);
|
---|
41 | };
|
---|
42 | on(document, 'keydown', keydown);
|
---|
43 | return function () {
|
---|
44 | off(document, 'keydown', keydown);
|
---|
45 | };
|
---|
46 | }, []);
|
---|
47 | };
|
---|
48 | export default useStartTyping;
|
---|