1
0
mirror of https://github.com/morris/vanilla-todo.git synced 2025-08-20 04:41:26 +02:00
Files
vanilla-todo/public/scripts/TodoList.js
2023-12-05 00:27:22 +01:00

69 lines
1.6 KiB
JavaScript

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]);
}
});
}
}