Web Dev Solutions

Catalin Mititiuc

From d393934679290ab4e16aa0b4a73408273eb26596 Mon Sep 17 00:00:00 2001 From: Catalin Mititiuc Date: Tue, 30 Apr 2024 16:58:12 -0700 Subject: Refactor index.js --- src/modules/record_sheet.js | 60 +++++++++++++++++++++++++++++++++------------ 1 file changed, 45 insertions(+), 15 deletions(-) (limited to 'src/modules/record_sheet.js') diff --git a/src/modules/record_sheet.js b/src/modules/record_sheet.js index 88c8e15..736ffb2 100644 --- a/src/modules/record_sheet.js +++ b/src/modules/record_sheet.js @@ -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; - }, {}); - - for (const al in grouped) { - grouped[al] = grouped[al].map(createRecord); +export function start(startLoc, units, gbUnSelect, gbSelect) { + clear(); + const forces = createRecords(units); + + 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); } -- cgit v1.2.3