|
1 | | -export function init(id) { |
2 | | - console.log(id); |
| 1 | +import EventHandler from '../../modules/event-handler.js' |
| 2 | + |
| 3 | +export function init(id) { |
| 4 | + const el = document.getElementById(id); |
| 5 | + EventHandler.on(el, 'keydown', 'input', e => { |
| 6 | + const isNumber = e.target.getAttribute('type') === 'number'; |
| 7 | + if (e.key === 'Tab') { |
| 8 | + |
| 9 | + } |
| 10 | + else if (e.key === 'Backspace' || e.key === 'ArrowLeft') { |
| 11 | + setPrevFocus(el, e.target); |
| 12 | + } |
| 13 | + else if (e.key === 'ArrowRight') { |
| 14 | + setNextFocus(el, e.target); |
| 15 | + } |
| 16 | + else if (isNumber) { |
| 17 | + if (e.key >= '0' && e.key <= '9') { |
| 18 | + setNextFocus(el, e.target); |
| 19 | + } |
| 20 | + else { |
| 21 | + e.preventDefault(); |
| 22 | + } |
| 23 | + } |
| 24 | + else if ((e.key >= 'a' && e.key <= 'z') || (e.key >= 'A' && e.key <= 'Z')) { |
| 25 | + setNextFocus(el, e.target); |
| 26 | + } |
| 27 | + else { |
| 28 | + e.preventDefault(); |
| 29 | + } |
| 30 | + }); |
| 31 | + EventHandler.on(el, 'focus', 'input', e => { |
| 32 | + if (e.target.select) { |
| 33 | + e.target.select(); |
| 34 | + } |
| 35 | + }); |
| 36 | +} |
| 37 | + |
| 38 | +const setPrevFocus = (el, target) => { |
| 39 | + const inputs = [...el.querySelectorAll('input')]; |
| 40 | + let index = inputs.indexOf(target); |
| 41 | + if (index > 0) { |
| 42 | + setFocus(inputs[index - 1]); |
| 43 | + } |
| 44 | + else { |
| 45 | + setBlur(target); |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +const setNextFocus = (el, target) => { |
| 50 | + const inputs = [...el.querySelectorAll('input')]; |
| 51 | + let index = inputs.indexOf(target); |
| 52 | + if (index < inputs.length - 1) { |
| 53 | + setFocus(inputs[index + 1]); |
| 54 | + } |
| 55 | + else { |
| 56 | + setBlur(target); |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +const setBlur = target => { |
| 61 | + const handler = setTimeout(function () { |
| 62 | + clearTimeout(handler); |
| 63 | + if (target.blur) { |
| 64 | + target.blur(); |
| 65 | + } |
| 66 | + }, 0); |
| 67 | +} |
| 68 | + |
| 69 | +const setFocus = target => { |
| 70 | + const handler = setTimeout(function () { |
| 71 | + clearTimeout(handler); |
| 72 | + if (target.focus) { |
| 73 | + target.focus(); |
| 74 | + } |
| 75 | + }, 10); |
3 | 76 | } |
4 | 77 |
|
5 | 78 | export function dispose(id) { |
6 | | - console.log(id); |
| 79 | + const el = document.getElementById(id); |
| 80 | + EventHandler.off(el, 'keydown'); |
7 | 81 | } |
0 commit comments