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