Refactor index.js

This commit is contained in:
2025-06-16 22:41:29 -07:00
parent e6b6217221
commit 8970c1f59e
4 changed files with 157 additions and 120 deletions

View File

@@ -46,6 +46,39 @@ function createRecord({ dataset: { allegiance, number }}) {
return div;
}
function createRecords(units) {
const grouped = Array.from(units).reduce((acc, unit) => {
acc[unit.dataset.allegiance]?.push(unit) || (acc[unit.dataset.allegiance] = [unit]);
return acc;
}, {});
for (const al in grouped) {
grouped[al] = grouped[al].map(createRecord);
}
return grouped;
}
function clear() {
document.querySelectorAll('#attacker-record > div, #defender-record > div').forEach(el => el.remove());
document.querySelector('#attacker-record .name').textContent = 'attacker';
document.querySelector('#defender-record .name').textContent = 'defender';
}
function addEventListeners(unSelectCounter, selectCounter) {
document.querySelectorAll('.soldier-record').forEach(el =>
el.addEventListener('click', () => {
if (el.classList.contains('selected')) {
el.classList.remove('selected');
unSelectCounter();
unSelect();
} else {
selectCounter(el);
}
})
);
}
export function unSelect() {
const selected = getSelected();
@@ -79,21 +112,18 @@ export function endMove() {
unSelect();
}
export function createRecords(units, { content }) {
const grouped = Array.from(units).reduce((acc, unit) => {
acc[unit.dataset.allegiance]?.push(unit) || (acc[unit.dataset.allegiance] = [unit]);
return acc;
}, {});
export function start(startLoc, units, gbUnSelect, gbSelect) {
clear();
const forces = createRecords(units);
for (const al in grouped) {
grouped[al] = grouped[al].map(createRecord);
for (const affiliation in forces) {
const container = document.querySelector(`#${affiliation}-record`);
const name = startLoc.dataset[`${affiliation}Name`];
if (name) {
container.querySelector('.name').textContent = name;
}
forces[affiliation].forEach(r => container.appendChild(r));
}
return grouped;
}
export function clear() {
document.querySelectorAll('#attacker-record > div, #defender-record > div').forEach(el => el.remove());
document.querySelector('#attacker-record .name').textContent = 'attacker';
document.querySelector('#defender-record .name').textContent = 'defender';
addEventListeners(gbUnSelect, gbSelect);
}