Web Dev Solutions

Catalin Mititiuc

aboutsummaryrefslogtreecommitdiff
blob: bd7b7659283dbe7c6359880e46d277cb9ca854fb (plain)
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
import * as firingArc from './game/firing_arc.js';
import * as sightLine from './game/sight_line.js';
import * as soldier from './game/soldier.js';
import { Observable } from './observable';
import { programmaticPan } from 'pan-zoom';

const frontmostStore = new Map();

let svg,
  placing = [];

function getCellContents(cell) {
  return cell.querySelectorAll('*:not(use[href="#hex"])');
}

function getGridIndex({ parentElement: { dataset: { q, r, s, t }}}) {
  return { q: +q, r: +r, s: +s, t: +t };
}

function getHex(cell) {
  return cell.querySelector('use[href="#hex"]');
}

function getCellOccupant(cell) {
  return cell.querySelector('.counter') || svg.querySelector('.grid-top .counter');
}

function getCells(svg) {
  return svg.querySelectorAll('[data-q][data-r][data-s][data-t]');
}

function getLockedSightLine(svg) {
  return svg.querySelector('line.sight-line:not(.active)');
}

function getActiveSightLine(svg) {
  return svg.querySelector('line.sight-line.active');
}

function isCounter(el) {
  const regex = new RegExp('^#counter-')
  return el && regex.test(el.getAttribute('href'));
}

function isMechTemplate(el) {
  return el && el.getAttribute('class') === 'mech-template';
}

function getCellPosition(cell) {
  const [x, y] = cell.getAttributeNS(null, 'transform').match(/-?\d+\.?\d*/g);

  return { x, y };
}

function getCell(q, r, s, t) {
  return svg.querySelector(`g[data-q="${q}"][data-r="${r}"][data-s="${s}"][data-t="${t}"]`);
}

function getCounterAtGridIndex(...coords) {
  return getCell(...coords).querySelector('.counter');
}

function getSelected() {
  return svg.querySelector(`.counter.selected[data-allegiance][data-number]`);
}

function deselect() {
  const selected = getSelected();
  placing = [];

  if (selected) {
    selected.classList.remove(soldier.getSelectedClass());
    clearSightLine();
    firingArc.clipAll(svg);
  }
}

function clearSightLine() {
  sightLine.setHexes([]);
  sightLine.clear();
  Observable.notify('distance');
}

function calcSightLineIndexes(source, target) {
  const { q: sq, r: sr, s: ss } = source.dataset;
  const { q: tq, r: tr, s: ts } = target.dataset;
  const sourceIndex = { q: +sq, r: +sr, s: +ss };
  const targetIndex = { q: +tq, r: +tr, s: +ts };

  return sightLine.calcIndexes(sourceIndex, targetIndex);
}

function getSightLineHexes(indexes) {
  const selector = indexes
    .map(({ q, r, s }) => `g[data-q="${q}"][data-r="${r}"][data-s="${s}"] use[href="#hex"]`)
    .join(', ');

  return svg.querySelectorAll(selector);
}

function calcSightLine(source, target) {
  const indexes = calcSightLineIndexes(source, target);
  const hexes = getSightLineHexes(indexes);
  sightLine.setHexes(hexes);
  Observable.notify('distance', indexes.length - 1);
}

function updateSightLine(cell) {
  calcSightLine(cell, sightLine.getLockTarget());
  sightLine.update(getCellPosition(cell));
}

function drawSightLine(sourceCell, targetCell) {
  calcSightLine(sourceCell, targetCell);
  const line = sightLine.create(getCellPosition(sourceCell), getCellPosition(targetCell));
  svg.querySelector('.gameboard').appendChild(line);
}

function selectOffBoard() {
  Observable.notify('select', this, { revealRecord: true });
}

function viewElevation(elevationLevel) {
  const gb = svg.querySelector('.gameboard');
  gb.dataset.viewElevation = elevationLevel;
}

function panMapToCounter(counter) {
  const gb = svg.querySelector('.gameboard');

  if (gb.contains(counter)) {
    Observable.notify('viewElevation', counter.parentElement.dataset.t);
    const counterRect = counter.getBoundingClientRect();
    const mapRect = svg.parentNode.defaultView.frameElement.getBoundingClientRect();

    const counterCoords = {
      clientX: counterRect.x + counterRect.width / 2,
      clientY: counterRect.y + counterRect.height / 2
    };

    const mapViewportCenterCoords = {
      clientX: mapRect.width / 2,
      clientY: mapRect.height / 2
    };

    programmaticPan(gb, counterCoords, mapViewportCenterCoords);
  }
}

function select(data, opts) {
  const counter = data && (soldier.getCounter(svg, data) || soldier.createCounter(data));
  const isSelected = data && data.classList && data.classList.contains('selected');

  deselect();

  if (isSelected || !data) return;

  if (opts?.revealCounter && document.querySelector('#auto-center-map').checked)
    panMapToCounter(counter);

  counter.classList.add(soldier.getSelectedClass());
  firingArc.get(svg, counter).forEach(el => el.removeAttribute('clip-path'));
  placing.push(counter);
}

function endMove() {
  const selected = getSelected();

  if (selected) {
    deselect();
  }
}

export function start(el) {
  svg = el;
  const grid = svg.querySelector('.grid');
  const frontmost = grid.querySelector('.frontmost');

  // For when the pointer leaves the window
  document.querySelector('object').addEventListener('pointerout', e => {
    if (clearHexDialog.open) return;
    svg.querySelectorAll('.hover').forEach(el => el.classList.remove('hover'));

    [...frontmost.children].forEach(child => {
      const parent = frontmostStore.get(child);
      parent.append(child);
      if (child.classList.contains('counter')) {
        firingArc.toggleCounterVisibility(svg, child, false);
      }
      frontmostStore.delete(child);
    });

    getActiveSightLine(svg) && clearSightLine();
  });

  svg.addEventListener('pointerover', e => {
    const targetCell = e.target.closest('[data-q][data-r][data-s][data-t], .frontmost');

    // Pointer moves outside the edge of the grid
    if (!targetCell) {
      svg.querySelectorAll('.hover').forEach(el => el.classList.remove('hover'));

      [...frontmost.children].forEach(child => {
        const parent = frontmostStore.get(child);
        parent.append(child);
        if (child.classList.contains('counter')) {
          firingArc.toggleCounterVisibility(svg, child, false);
        }
        frontmostStore.delete(child);
      });
    }

    // Pointer moves over a cell
    if (targetCell) {
      if ([
        // that is not already highlighted
        !targetCell.classList.contains('hover'),
        // 's contents that is in frontmost, whose parent cell is not already highlighted
        !(targetCell.classList.contains('frontmost') && frontmostStore.get(e.target.closest('.frontmost > *')).classList.contains('hover'))
      ].every(e => e)) {
        svg.querySelectorAll('.hover').forEach(el => el.classList.remove('hover'));

        if (placing[0]?.getAttributeNS(null, 'class') === 'mech-template') {
          targetCell.prepend(placing[0]);
        }

        [...frontmost.children].forEach(child => {
          const parent = frontmostStore.get(child);
          parent.append(child);
          if (child.classList.contains('counter')) {
            firingArc.toggleCounterVisibility(svg, child, false);
          }
          frontmostStore.delete(child);
        });

        frontmost.setAttributeNS(null, 'transform', targetCell.getAttributeNS(null, 'transform'));

        const children = [...targetCell.children].filter(c => c.getAttributeNS(null, 'href') !== '#hex');
        if (children.length > 0) {
          children.forEach(child => {
            if (child.classList.contains('counter')) {
              firingArc.toggleCounterVisibility(svg, child, true);
            }
            frontmostStore.set(child, targetCell);
            frontmost.append(child);
          });
        }

        targetCell.classList.contains('frontmost') ? frontmostStore.get(e.target.closest('.frontmost > *')).classList.add('hover') : targetCell.classList.add('hover');
      }
    }

    const selected = getSelected();

    if (selected && targetCell && svg.querySelector('.grid').contains(selected) && !getLockedSightLine(svg) && selected.parentElement !== frontmost) {
      clearSightLine();
      drawSightLine(selected.parentElement, grid.querySelector('.hover'));
    } else {
      getActiveSightLine(svg) && clearSightLine();
    }
  });

  grid.addEventListener('click', clickHandler);

  const clearHexDialog = document.querySelector('#clear-hex');

  clearHexDialog.addEventListener('close', e => {
    if (clearHexDialog.returnValue === 'confirm') {
      [...frontmost.children].forEach(child => {
        if (child.classList.contains('counter'))
          firingArc.get(svg, child).forEach(el => el.remove());

        frontmostStore.delete(child);
        child.remove();
      });
    }
  });

  grid.addEventListener('contextmenu', e => {
    e.preventDefault();

    const selected = getSelected();

    if (selected) {
      if (sightLine.getSightLine()) sightLine.toggleLock(grid.querySelector('.hover'));
      if (getActiveSightLine(svg)) {
        clearSightLine();
        if (selected.parentElement !== frontmost)
          drawSightLine(selected.parentElement, grid.querySelector('.hover'));
      }
    } else {
      clearHexDialog.showModal();
    }
  });

  const startingLocations = svg.querySelector('.start-locations');
  startingLocations && getUnits(startingLocations).forEach(unit => unit.addEventListener('click', selectOffBoard));

  function clickHandler(e) {
    const targetCell = grid.querySelector('.hover');
    const occupant = frontmost.querySelector('.counter');
    let toPlace = placing.pop();

    if (isCounter(toPlace) || isMechTemplate(toPlace)) {
      frontmostStore.set(toPlace, targetCell);
      isMechTemplate(toPlace) ? frontmost.prepend(toPlace) : frontmost.append(toPlace);
      if (isCounter(toPlace)) arrangeCounters(frontmost);
      removeEventListener("keydown", handleMechTemplateRotation);
    } else if (toPlace && !occupant) {
      frontmostStore.set(toPlace, targetCell);
      const mechTemplate = frontmost.querySelector('.mech-template');
      mechTemplate ? mechTemplate.after(toPlace) : frontmost.prepend(toPlace);
      placing.push(toPlace);
      getLockedSightLine(svg) ? updateSightLine(targetCell) : clearSightLine();
    } else if (toPlace && occupant) {
      if (toPlace === occupant) {
        Observable.notify('select');
      } else {
        Observable.notify('select', occupant, { revealRecord: true });
      }
    } else if (!toPlace && occupant) {
      Observable.notify('select', occupant, { revealRecord: true });
    }

    const selected = getSelected();
  }

  Observable.subscribe('select', select);
  Observable.subscribe('endmove', endMove);
  Observable.subscribe('viewElevation', viewElevation);

  console.log('gameboard.js loaded');
}

export function stop() {
  Observable.unsubscribe('select', select);
  Observable.unsubscribe('endmove', endMove);
  Observable.unsubscribe('viewElevation', viewElevation);
}

export function getUnits() {
  return soldier.getAllCounters(svg);
}

export function clearFiringArcs(allegiance) {
  firingArc.clear(svg, allegiance);
}

export function toggleFiringArcVisibility() {
  firingArc.toggleVisibility(svg, this.dataset.allegiance);
}

export function setFiringArc() {
  const counter = getSelected(),
    isOnBoard = counter => counter && counter.parentElement.hasAttribute('data-q');

  if (isOnBoard(counter)) {
    firingArc.set(svg, this.dataset.size, counter, getCellPosition(counter.parentElement));
  }
}

export function setCounter(name) {
  const selected = getSelected();
  const counter = document.createElementNS(svgns, 'use');

  counter.addEventListener('click', e => {
    e.stopPropagation()
    const container = counter.parentElement;
    counter.remove()
    arrangeCounters(container);
  });

  counter.setAttributeNS(null, 'href', `#counter-${name}`);
  counter.classList.add(`counter-${name}`);

  if (selected) {
    selected.append(counter);
    arrangeCounters(selected);
  }
  else
    placing.push(counter);
}

function arrangeCounters(container) {
  const counters = [...container.children].filter(isCounter);
  const length = 12;
  const gravity = 1;
  const lateralForce = gravity;
  const rads = Math.atan(lateralForce / gravity);
  const bestFitCount = 8;
  const deflection = counters.length > bestFitCount ? 2 * Math.PI / counters.length : Math.atan(lateralForce / gravity);

  counters.forEach((counter, index, arr) => {
    const mult = index - arr.length / 2 + 0.5;
    const theta = deflection * mult;
    const x = length * Math.sin(theta);
    const y = length * Math.cos(theta);
    counter.setAttributeNS(null, 'style', `--x: ${-x}px; --y: ${y}px`);
  });
}

function handleMechTemplateRotation(event) {
  const counter = placing[0];
  const upper = placing[0].querySelector('use[href="#mech-template-upper"]');

  if (event.key === 'a') {
    let direction = +counter.style.transform.match(/-?\d+/) || 0;
    direction -= 60;
    counter.style.transform = `rotate(${direction}deg)`;
  } else if (event.key === 'd') {
    let direction = +counter.style.transform.match(/-?\d+/) || 0;
    direction += 60;
    counter.style.transform = `rotate(${direction}deg)`;
  } else if (event.key === 'q') {
    let facing = +upper.style.transform.match(/-?\d+/) || 0;
    facing = facing <= -60 ? -60 : facing - 60;
    upper.style.transform = `rotate(${facing}deg)`;
  } else if (event.key === 'e') {
    let facing = +upper.style.transform.match(/-?\d+/) || 0;
    facing = facing >= 60 ? 60 : facing + 60;
    upper.style.transform = `rotate(${facing}deg)`;
  }
}

export function setMechTemplate() {
  const counter = document.createElementNS(svgns, 'g');
  counter.setAttributeNS(null, 'class', 'mech-template');
  counter.style.pointerEvents = 'none';
  counter.style.transition = 'transform 0.5s';

  const lower = document.createElementNS(svgns, 'use');
  lower.setAttributeNS(null, 'href', '#mech-template-lower');

  const upper = document.createElementNS(svgns, 'use');
  upper.setAttributeNS(null, 'href', '#mech-template-upper');
  upper.style.transition = 'transform 0.5s';

  counter.appendChild(lower);
  counter.appendChild(upper);

  addEventListener("keydown", handleMechTemplateRotation);
  placing.push(counter);
}