-
Notifications
You must be signed in to change notification settings - Fork 54
/
TodoList.js
68 lines (55 loc) · 1.63 KB
/
TodoList.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
68
import { AppSortable } from './AppSortable.js';
import { TodoItem } from './TodoItem.js';
import { TodoItemInput } from './TodoItemInput.js';
/**
* @param {HTMLElement} el
*/
export function TodoList(el) {
let items = [];
el.innerHTML = /* html */ `
<div class="items"></div>
<div class="todo-item-input"></div>
`;
AppSortable(el.querySelector('.items'), {});
TodoItemInput(el.querySelector('.todo-item-input'));
el.addEventListener('sortableDrop', (e) =>
el.dispatchEvent(
new CustomEvent('moveTodoItem', {
detail: {
...e.detail.data.item,
index: e.detail.index,
},
bubbles: true,
}),
),
);
el.addEventListener('todoItems', (e) => {
items = e.detail;
update();
});
function update() {
const container = el.querySelector('.items');
const obsolete = new Set(container.children);
const childrenByKey = new Map();
obsolete.forEach((child) => childrenByKey.set(child.dataset.key, child));
const children = items.map((item) => {
let child = childrenByKey.get(item.id);
if (child) {
obsolete.delete(child);
} else {
child = document.createElement('div');
child.classList.add('todo-item');
child.dataset.key = item.id;
TodoItem(child);
}
child.dispatchEvent(new CustomEvent('todoItem', { detail: item }));
return child;
});
obsolete.forEach((child) => container.removeChild(child));
children.forEach((child, index) => {
if (child !== container.children[index]) {
container.insertBefore(child, container.children[index]);
}
});
}
}