-
Notifications
You must be signed in to change notification settings - Fork 54
/
TodoItemInput.js
67 lines (53 loc) · 1.3 KB
/
TodoItemInput.js
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
import { AppIcon } from './AppIcon.js';
/**
* @param {HTMLElement} el
*/
export function TodoItemInput(el) {
let saveOnBlur = true;
el.innerHTML = /* html */ `
<input type="text" class="input use-focus-other" aria-label="Label">
<button class="app-button save" title="Save">
<i class="app-icon" data-id="plus-24"></i>
</button>
`;
const inputEl = el.querySelector('.input');
const saveEl = el.querySelector('.save');
el.querySelectorAll('.app-icon').forEach(AppIcon);
inputEl.addEventListener('keyup', (e) => {
switch (e.keyCode) {
case 13: // Enter
save();
break;
case 27: // Escape
clear();
break;
}
});
inputEl.addEventListener('blur', () => {
if (saveOnBlur) save();
saveOnBlur = true;
});
inputEl.addEventListener('focusOther', save);
saveEl.addEventListener('mousedown', () => {
saveOnBlur = false;
});
saveEl.addEventListener('click', () => {
save();
inputEl.focus();
});
function save() {
const label = inputEl.value.trim();
if (label === '') return;
inputEl.value = '';
el.dispatchEvent(
new CustomEvent('addTodoItem', {
detail: { label },
bubbles: true,
}),
);
}
function clear() {
inputEl.value = '';
inputEl.blur();
}
}