BlueGit

projects-timfalken-com allianties

Files

allianties / src / main.js

main.js

main.js 58.1 KiB Download Raw
1'use strict';
2
3var App = {
4 screen: 'menu',
5 games: [],
6 game: null,
7 selected: null, // player id or 'self-move'
8 pollTimer: null,
9 tickTimer: null,
10 replay: null, // { events, index, timer, snapshot }
11 rulesDirty: false,
12 savingRules: false
13};
14
15function $(id)
16{
17 return document.getElementById(id);
18}
19
20function showScreen(name)
21{
22 ['menu', 'lobby', 'game'].forEach(function (s)
23 {
24 var el = $(s);
25 if (el) { el.hidden = s !== name; }
26 });
27 App.screen = name;
28 $('top-bar').hidden = name !== 'game';
29 if (name !== 'game')
30 { App.stopReplay(); }
31}
32
33function showError(id, err)
34{
35 var el = $(id);
36 if (!el) { return; }
37 if (!err)
38 {
39 el.hidden = true;
40 el.textContent = '';
41 return;
42 }
43 var msg = err && (err.code || err.message) ? I18n.error(err.code || err.message) : String(err);
44 if (err && err.status)
45 { msg = I18n.t('error.serverStatus', { status: err.status }); }
46 el.textContent = msg;
47 el.hidden = false;
48}
49
50function initials(name)
51{
52 if (!name) { return '?'; }
53 var parts = String(name).trim().split(/\s+/);
54 var s = parts[0].charAt(0);
55 if (parts.length > 1)
56 { s += parts[parts.length - 1].charAt(0); }
57 return s.toUpperCase();
58}
59
60function avatarNode(player, size, fixed)
61{
62 size = size || 40;
63 var wrap = document.createElement('span');
64 wrap.className = 'avatar-wrap';
65 wrap.style.setProperty('--c', player.color || '#fff');
66 wrap.style.setProperty('--sz', size + 'px');
67 if (fixed)
68 {
69 wrap.classList.add('avatar-wrap-fixed');
70 wrap.style.width = size + 'px';
71 wrap.style.height = size + 'px';
72 }
73 function stylePiece(el)
74 {
75 el.className = (el.className ? el.className + ' ' : '') + 'piece' + (player.alive === false ? ' dead' : '');
76 if (fixed)
77 {
78 el.classList.add('piece-fixed');
79 el.style.width = size + 'px';
80 el.style.height = size + 'px';
81 el.style.borderColor = player.color || '#fff';
82 }
83 else
84 {
85 el.style.borderColor = player.color || '#fff';
86 }
87 }
88 if (player.avatar)
89 {
90 var img = document.createElement('img');
91 img.alt = player.name || '';
92 img.width = size;
93 img.height = size;
94 stylePiece(img);
95 img.src = player.avatar;
96 img.addEventListener('error', function ()
97 {
98 img.remove();
99 var fb = document.createElement('span');
100 fb.className = 'piece-initials';
101 stylePiece(fb);
102 fb.textContent = initials(player.name);
103 wrap.appendChild(fb);
104 });
105 wrap.appendChild(img);
106 }
107 else
108 {
109 var fb = document.createElement('span');
110 fb.className = 'piece-initials';
111 stylePiece(fb);
112 fb.textContent = initials(player.name);
113 wrap.appendChild(fb);
114 }
115 return wrap;
116}
117
118function findPlayer(id)
119{
120 if (!App.game || !App.game.players) { return null; }
121 for (var i = 0; i < App.game.players.length; i++)
122 {
123 if (App.game.players[i].id === id)
124 { return App.game.players[i]; }
125 }
126 return null;
127}
128
129function you()
130{
131 return App.game ? findPlayer(App.game.you) : null;
132}
133
134/* ---------- init ---------- */
135
136App.init = function ()
137{
138 I18n.init();
139 I18n.bindPicker();
140 I18n.onChange(function ()
141 {
142 App.render();
143 });
144 this.bind();
145 this.localLinks();
146 var params = new URLSearchParams(location.search);
147 var join = params.get('join');
148 Api.loadMe().then(function (data)
149 {
150 if (data.locale)
151 { I18n.applyFromProfile(data.locale); }
152 App.games = data.games || [];
153 App.renderMenu(data);
154 if (join)
155 {
156 if (!Api.me)
157 {
158 location.href = 'auth.php?next=' + encodeURIComponent('index.html?join=' + join);
159 return;
160 }
161 App.doJoin(join);
162 }
163 }).catch(function (err)
164 {
165 showError('menu-error', err);
166 App.renderMenu({});
167 });
168 this.tickTimer = setInterval(function () { App.tickClocks(); }, 250);
169 document.addEventListener('visibilitychange', function ()
170 {
171 if (document.hidden)
172 {
173 App.stopPoll();
174 }
175 else if (App.game && App.screen !== 'menu')
176 {
177 App.refreshFull();
178 App.startPoll();
179 }
180 });
181};
182
183App.localLinks = function ()
184{
185 var span = $('local-links');
186 if (!span) { return; }
187 span.innerHTML = '';
188 for (var i = 1; i <= 8; i++)
189 {
190 if (i > 1) { span.appendChild(document.createTextNode(' · ')); }
191 var a = document.createElement('a');
192 a.href = 'auth.php?test=' + i;
193 a.textContent = 'test_user_' + i;
194 span.appendChild(a);
195 }
196};
197
198App.bind = function ()
199{
200 $('btn-create').addEventListener('click', function () { App.createLobby(); });
201 $('join-form').addEventListener('submit', function (e)
202 {
203 e.preventDefault();
204 App.doJoin($('join-code').value);
205 });
206 $('lobby-back').addEventListener('click', function () { App.toMenu(); });
207 $('btn-copy').addEventListener('click', function () { App.copyInvite(); });
208 $('btn-start').addEventListener('click', function () { App.startGame(); });
209 $('btn-leave').addEventListener('click', function () { App.leaveLobby(); });
210 $('btn-upgrade').addEventListener('click', function () { App.act({ type: 'upgrade' }); });
211 $('btn-settings').addEventListener('click', function () { $('settings-panel').hidden = false; });
212 $('settings-close').addEventListener('click', function () { $('settings-panel').hidden = true; });
213 $('btn-to-menu').addEventListener('click', function ()
214 {
215 $('settings-panel').hidden = true;
216 App.toMenu();
217 });
218 $('btn-surrender').addEventListener('click', function () { App.confirmSurrender(); });
219 $('modal-close').addEventListener('click', function () { App.closeModal(); });
220 $('modal').addEventListener('click', function (e)
221 {
222 if (e.target === $('modal')) { App.closeModal(); }
223 });
224 $('sheet-close').addEventListener('click', function () { App.closeSheet(); });
225 $('sheet').addEventListener('click', function (e)
226 {
227 if (e.target === $('sheet')) { App.closeSheet(); }
228 });
229 $('tl-play').addEventListener('click', function () { App.toggleReplay(); });
230 $('tl-live').addEventListener('click', function () { App.jumpToPresent(); });
231 if ($('tl-back')) { $('tl-back').addEventListener('click', function () { App.stepReplay(-1); }); }
232 if ($('tl-fwd')) { $('tl-fwd').addEventListener('click', function () { App.stepReplay(1); }); }
233 this.bindTimelineScrub();
234 this.bindRuleEditors();
235 document.addEventListener('keydown', function (e)
236 {
237 if (e.key === 'Escape')
238 {
239 App.closeModal();
240 App.closeSheet();
241 $('settings-panel').hidden = true;
242 return;
243 }
244 App.onGameKey(e);
245 });
246};
247
248App.onGameKey = function (e)
249{
250 if (App.screen !== 'game' || !App.game) { return; }
251 var t = e.target;
252 var tag = (t && t.tagName) ? t.tagName.toUpperCase() : '';
253 if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || (t && t.isContentEditable))
254 { return; }
255 if (e.altKey || e.ctrlKey || e.metaKey) { return; }
256 if (e.key === 'ArrowLeft')
257 {
258 e.preventDefault();
259 App.stepReplay(-1);
260 }
261 else if (e.key === 'ArrowRight')
262 {
263 e.preventDefault();
264 App.stepReplay(1);
265 }
266 else if (e.key === ' ' || e.key === 'Spacebar' || e.code === 'Space')
267 {
268 e.preventDefault();
269 App.toggleReplay();
270 }
271 else if (e.key === 'End')
272 {
273 e.preventDefault();
274 App.jumpToPresent();
275 }
276};
277
278App.jumpToPresent = function ()
279{
280 App.stopReplay();
281 if (App.game) { App.renderGame(); }
282};
283
284App.stepReplay = function (dir)
285{
286 if (!App.game || App.game.status === 'lobby') { return; }
287 var n = this.spendEvents(App.game).length;
288 if (!n && dir) { return; }
289 var idx = App.replay ? App.replay.index : n;
290 var next = Math.max(0, Math.min(n, idx + dir));
291 if (App.replay && App.replay.timer)
292 {
293 clearInterval(App.replay.timer);
294 App.replay.timer = null;
295 }
296 if (next >= n)
297 {
298 this.jumpToPresent();
299 return;
300 }
301 this.jumpReplay(next, { animate: dir > 0 });
302};
303
304
305App.bindRuleEditors = function ()
306{
307 ['rule-jury', 'rule-shrink', 'rule-ceasefire', 'rule-shrink-days', 'rule-ap-loot', 'rule-ap-time'].forEach(function (id)
308 {
309 if ($(id)) { $(id).addEventListener('change', function () { App.onRulesChange(); }); }
310 });
311 $('cf-add').addEventListener('click', function ()
312 {
313 var ranges = App.currentCfRanges();
314 ranges.push({ start: '22:00', end: '06:00' });
315 App.setCfRanges(ranges);
316 App.onRulesChange();
317 });
318 var vis = $('lobby-visibility');
319 if (vis)
320 {
321 vis.addEventListener('change', function () { App.onRulesChange(); });
322 }
323};
324
325App.visKeys = ['vis_shots', 'vis_gifts', 'vis_ap', 'vis_range', 'vis_lives'];
326
327App.syncVisRadios = function (r, isHost)
328{
329 App.visKeys.forEach(function (k)
330 {
331 var val = (r && r[k]) || 'public';
332 document.querySelectorAll('input[name="' + k + '"]').forEach(function (inp)
333 {
334 inp.checked = inp.value === val;
335 inp.disabled = !isHost;
336 });
337 });
338};
339
340App.readVisRules = function ()
341{
342 var o = {};
343 App.visKeys.forEach(function (k)
344 {
345 var inp = document.querySelector('input[name="' + k + '"]:checked');
346 o[k] = inp ? inp.value : 'public';
347 });
348 return o;
349};
350
351App.render = function ()
352{
353 I18n.apply();
354 I18n.renderPicker();
355 if (App.screen === 'menu') { App.renderMenu({ games: App.games, me: Api.me, configured: Api.configured, local: Api.local }); }
356 else if (App.screen === 'lobby') { App.renderLobby(); }
357 else if (App.screen === 'game') { App.renderGame(); }
358};
359
360/* ---------- menu ---------- */
361
362App.renderMenu = function (data)
363{
364 showScreen('menu');
365 App.stopPoll();
366 data = data || {};
367 var me = data.me !== undefined ? data.me : Api.me;
368 $('menu-guest').hidden = !!me;
369 $('menu-user').hidden = !me;
370 $('menu-guest-hint').hidden = !!me;
371 $('menu-actions').hidden = !me;
372 $('my-games').hidden = !me;
373 $('menu-unconfigured').hidden = !!Api.configured || !!Api.local;
374 $('menu-local-login').hidden = !Api.local;
375 if (me)
376 {
377 $('menu-name').textContent = me.name;
378 var av = $('menu-avatar');
379 if (me.avatar) { av.src = me.avatar; av.hidden = false; }
380 else { av.hidden = true; }
381 }
382 App.games = data.games || App.games || [];
383 var list = $('games-list');
384 list.innerHTML = '';
385 $('no-games').hidden = App.games.length > 0;
386 App.games.forEach(function (g)
387 {
388 var li = document.createElement('li');
389 var info = document.createElement('div');
390 info.style.flex = '1';
391 var st = g.status === 'lobby' ? I18n.t('menu.statusLobby')
392 : g.status === 'finished' ? I18n.t('menu.statusFinished')
393 : I18n.t('menu.statusRunning');
394 var sub = I18n.plural('lobby.playerCount', g.players);
395 if (g.status === 'finished')
396 {
397 if (g.draw) { sub = I18n.t('menu.draw'); }
398 else if (g.you_won) { sub = I18n.t('menu.youWon'); }
399 else
400 {
401 var w = (g.names || []).filter(function (p) { return p.id === g.winner_id; })[0];
402 sub = I18n.t('menu.winnerIs', { name: w ? w.name : '?' });
403 }
404 }
405 info.innerHTML = '<strong>' + st + '</strong> · <span class="mono">' + escapeHtml(g.code) + '</span><br><span class="hint">' + escapeHtml(sub) + '</span>';
406 var btn = document.createElement('button');
407 btn.type = 'button';
408 btn.textContent = I18n.t(g.status === 'finished' ? 'menu.open' : 'menu.continue');
409 btn.addEventListener('click', function () { App.openGame(g.id, g.status); });
410 li.appendChild(info);
411 li.appendChild(btn);
412 list.appendChild(li);
413 });
414 I18n.apply($('menu'));
415};
416
417App.toMenu = function ()
418{
419 App.game = null;
420 App.selected = null;
421 App.stopPoll();
422 Api.games().then(function (data)
423 {
424 App.games = data.games || [];
425 App.renderMenu(data);
426 }).catch(function () { App.renderMenu({}); });
427 // clean join from URL
428 if (location.search)
429 { history.replaceState({}, '', 'index.html'); }
430};
431
432App.createLobby = function ()
433{
434 showError('menu-error');
435 Api.createLobby(Rules.defaultRules()).then(function (data)
436 {
437 App.enter(data.game);
438 }).catch(function (err) { showError('menu-error', err); });
439};
440
441App.doJoin = function (code)
442{
443 showError('menu-error');
444 code = String(code || '').trim();
445 if (!code) { return; }
446 Api.join(code).then(function (data)
447 {
448 App.enter(data.game);
449 }).catch(function (err)
450 {
451 // Already a member of a game that has started: open it from the list.
452 if (err && err.code === 'game_started')
453 {
454 var want = String(code).toUpperCase();
455 var existing = (App.games || []).filter(function (g)
456 {
457 return String(g.code || '').toUpperCase() === want;
458 })[0];
459 if (existing)
460 {
461 App.openGame(existing.id, existing.status);
462 return;
463 }
464 }
465 showError('menu-error', err);
466 });
467};
468
469App.openGame = function (id, status)
470{
471 Api.game(id).then(function (data)
472 {
473 App.enter(data.game);
474 }).catch(function (err) { showError('menu-error', err); });
475};
476
477App.enter = function (game)
478{
479 App.game = game;
480 if (game.status === 'lobby')
481 {
482 showScreen('lobby');
483 App.renderLobby();
484 }
485 else
486 {
487 showScreen('game');
488 App.renderGame();
489 }
490 App.startPoll();
491 if (game && game.code)
492 {
493 history.replaceState({}, '', 'index.html?join=' + encodeURIComponent(game.code));
494 }
495};
496
497/* ---------- lobby ---------- */
498
499App.renderLobby = function ()
500{
501 var g = App.game;
502 if (!g) { return; }
503 $('lobby-code').textContent = g.code;
504 var url = location.origin + location.pathname.replace(/index\.html$/, '') + 'index.html?join=' + encodeURIComponent(g.code);
505 $('invite-link').value = url;
506 var isHost = g.host_id === g.you;
507 var list = $('lobby-players');
508 list.innerHTML = '';
509 (g.players || []).forEach(function (p)
510 {
511 var li = document.createElement('li');
512 li.appendChild(avatarNode(p, 40, true));
513 var name = document.createElement('span');
514 name.style.flex = '1';
515 name.textContent = p.name + (p.is_you ? ' (' + I18n.t('lobby.you') + ')' : '') + (p.is_host ? ' · ' + I18n.t('lobby.host') : '');
516 li.appendChild(name);
517 var dot = document.createElement('span');
518 dot.className = 'player-dot';
519 dot.style.background = p.color;
520 li.appendChild(dot);
521 list.appendChild(li);
522 });
523 var n = (g.players || []).length;
524 $('lobby-need').hidden = n >= 2;
525 $('btn-start').hidden = !isHost;
526 $('btn-start').disabled = n < 2;
527 $('lobby-waiting').hidden = isHost;
528 // Rules
529 var r = g.rules || Rules.defaultRules();
530 $('rule-jury').checked = !!r.jury;
531 if ($('rule-ap-loot')) { $('rule-ap-loot').checked = !!r.ap_loot; }
532 if ($('rule-ap-time')) { $('rule-ap-time').value = r.ap_time || '00:00'; }
533 $('rule-shrink').checked = !!r.shrinking_arena;
534 $('rule-shrink-days').value = r.shrink_interval_days || 7;
535 $('rule-ceasefire').checked = !!r.ceasefire;
536 $('shrink-days-wrap').hidden = !r.shrinking_arena;
537 $('ceasefire-editor').hidden = !r.ceasefire;
538 ['rule-jury', 'rule-shrink', 'rule-ceasefire', 'rule-shrink-days', 'cf-add', 'rule-ap-loot', 'rule-ap-time'].forEach(function (id)
539 {
540 if ($(id)) { $(id).disabled = !isHost; }
541 });
542 App.renderCfEditor(r.ceasefire_ranges || [], isHost);
543 App.syncVisRadios(r, isHost);
544 I18n.apply($('lobby'));
545};
546
547App.currentCfRanges = function ()
548{
549 return (App.game && App.game.rules && App.game.rules.ceasefire_ranges) || [];
550};
551
552App.setCfRanges = function (ranges)
553{
554 if (!App.game.rules) { App.game.rules = Rules.defaultRules(); }
555 App.game.rules.ceasefire_ranges = Rules.normalizeRanges(ranges);
556 App.renderCfEditor(App.game.rules.ceasefire_ranges, App.game.host_id === App.game.you);
557};
558
559App.renderCfEditor = function (ranges, editable)
560{
561 CeasefireClock.render($('cf-clock'), ranges, {
562 editable: editable,
563 onChange: function (next)
564 {
565 App.setCfRanges(next);
566 App.onRulesChange();
567 }
568 });
569 var ul = $('cf-ranges');
570 ul.innerHTML = '';
571 if (!ranges.length)
572 {
573 var empty = document.createElement('li');
574 empty.className = 'hint';
575 empty.setAttribute('data-i18n', 'lobby.ceasefireEmpty');
576 empty.textContent = I18n.t('lobby.ceasefireEmpty');
577 ul.appendChild(empty);
578 return;
579 }
580 ranges.forEach(function (r, i)
581 {
582 var li = document.createElement('li');
583 var a = document.createElement('input');
584 a.type = 'time';
585 a.value = r.start;
586 a.setAttribute('aria-label', I18n.t('lobby.ceasefireStart'));
587 a.disabled = !editable;
588 var b = document.createElement('input');
589 b.type = 'time';
590 b.value = r.end;
591 b.setAttribute('aria-label', I18n.t('lobby.ceasefireEnd'));
592 b.disabled = !editable;
593 function commit()
594 {
595 var next = App.currentCfRanges().slice();
596 next[i] = { start: a.value, end: b.value };
597 App.setCfRanges(next);
598 App.onRulesChange();
599 }
600 a.addEventListener('change', commit);
601 b.addEventListener('change', commit);
602 var rm = document.createElement('button');
603 rm.type = 'button';
604 rm.className = 'btn-secondary';
605 rm.textContent = I18n.t('lobby.ceasefireRemove');
606 rm.disabled = !editable;
607 rm.addEventListener('click', function ()
608 {
609 var next = App.currentCfRanges().slice();
610 next.splice(i, 1);
611 App.setCfRanges(next);
612 App.onRulesChange();
613 });
614 li.appendChild(a);
615 li.appendChild(document.createTextNode('–'));
616 li.appendChild(b);
617 li.appendChild(rm);
618 ul.appendChild(li);
619 });
620};
621
622App.onRulesChange = function ()
623{
624 if (!App.game || App.game.status !== 'lobby') { return; }
625 if (App.game.host_id !== App.game.you) { return; }
626 $('shrink-days-wrap').hidden = !$('rule-shrink').checked;
627 $('ceasefire-editor').hidden = !$('rule-ceasefire').checked;
628 var rules = {
629 jury: $('rule-jury').checked,
630 shrinking_arena: $('rule-shrink').checked,
631 shrink_interval_days: parseInt($('rule-shrink-days').value, 10) || 7,
632 ceasefire: $('rule-ceasefire').checked,
633 ceasefire_ranges: App.currentCfRanges(),
634 ap_loot: $('rule-ap-loot') ? $('rule-ap-loot').checked : false,
635 ap_time: ($('rule-ap-time') && $('rule-ap-time').value) ? $('rule-ap-time').value : '00:00'
636 };
637 Object.assign(rules, App.readVisRules());
638 App.game.rules = Object.assign({}, App.game.rules, rules);
639 App.rulesDirty = true;
640 if (App._rulesTimer) { clearTimeout(App._rulesTimer); }
641 App._rulesTimer = setTimeout(function ()
642 {
643 if (!App.rulesDirty) { return; }
644 App.rulesDirty = false;
645 Api.setRules(App.game.id, App.game.rules).then(function (data)
646 {
647 App.game = data.game;
648 App.renderLobby();
649 }).catch(function (err) { showError('lobby-error', err); });
650 }, 350);
651};
652
653App.copyInvite = function ()
654{
655 var v = $('invite-link').value;
656 function ok()
657 {
658 $('copy-status').hidden = false;
659 setTimeout(function () { $('copy-status').hidden = true; }, 1500);
660 }
661 if (navigator.clipboard && navigator.clipboard.writeText)
662 {
663 navigator.clipboard.writeText(v).then(ok).catch(function ()
664 {
665 $('invite-link').select();
666 try { document.execCommand('copy'); ok(); } catch (e) {}
667 });
668 }
669 else
670 {
671 $('invite-link').select();
672 try { document.execCommand('copy'); ok(); } catch (e) {}
673 }
674};
675
676App.startGame = function ()
677{
678 showError('lobby-error');
679 Api.start(App.game.id).then(function (data)
680 {
681 App.enter(data.game);
682 }).catch(function (err) { showError('lobby-error', err); });
683};
684
685App.leaveLobby = function ()
686{
687 Api.leave(App.game.id).then(function () { App.toMenu(); })
688 .catch(function (err) { showError('lobby-error', err); });
689};
690
691/* ---------- game ---------- */
692
693App.renderGame = function ()
694{
695 var g = App.replay ? App.replay.view : App.game;
696 if (!g) { return; }
697 this.renderHud(g);
698 this.renderBoard(g);
699 this.renderJury(g);
700 this.renderTimeline(App.game); // ticks from the (already filtered) event list
701 this.tickClocks();
702 I18n.apply($('game'));
703 I18n.apply($('top-bar'));
704 if (!App.replay) { this.clearBoardFx(); }
705};
706
707App.renderHud = function (g)
708{
709 var me = findIn(g.players, g.you) || you();
710 var stats = $('you-stats');
711 if (me)
712 {
713 stats.innerHTML = '<strong>' + escapeHtml(me.name) + '</strong> · '
714 + I18n.t('game.lives') + ' <strong>' + me.lives + '</strong> · '
715 + I18n.t('game.ap') + ' <strong>' + me.ap + '</strong> · '
716 + I18n.t('game.range') + ' <strong>' + me.range + '</strong>';
717 }
718 var legal = g.legal || {};
719 $('btn-upgrade').hidden = !legal.upgrade;
720 $('btn-upgrade').disabled = !legal.upgrade;
721 $('day-label').textContent = I18n.t('game.day', { n: g.day || 0 });
722 var sb = $('shrink-banner');
723 if (g.rules && g.rules.shrinking_arena && g.shrink_in_days != null)
724 {
725 sb.hidden = false;
726 if (g.shrink_in_days === 0) { sb.textContent = I18n.t('game.shrinkToday'); }
727 else if (g.shrink_in_days === 1) { sb.textContent = I18n.t('game.shrinkTomorrow'); }
728 else { sb.textContent = I18n.plural('game.shrinkInDays', g.shrink_in_days); }
729 }
730 else { sb.hidden = true; }
731 var banner = $('game-banner');
732 if (g.status === 'finished')
733 {
734 banner.hidden = false;
735 if (g.draw) { banner.textContent = I18n.t('game.draw'); }
736 else if (g.winner_id === g.you) { banner.textContent = I18n.t('game.youWin'); }
737 else
738 {
739 var w = findIn(g.players, g.winner_id);
740 banner.textContent = I18n.t('game.winner', { name: w ? w.name : '?' });
741 }
742 }
743 else if (me && !me.alive)
744 {
745 banner.hidden = false;
746 banner.textContent = I18n.t('game.spectating');
747 }
748 else { banner.hidden = true; }
749};
750
751function findIn(list, id)
752{
753 if (!list) { return null; }
754 for (var i = 0; i < list.length; i++)
755 {
756 if (list[i].id === id) { return list[i]; }
757 }
758 return null;
759}
760
761App.renderBoard = function (g)
762{
763 var board = $('board');
764 var size = g.grid || 6;
765 var inset = g.arena_inset || 0;
766 var nextInset = (g.rules && g.rules.shrinking_arena && g.shrink_in_days != null && g.max_inset > inset)
767 ? inset + 1 : null;
768 board.style.setProperty('--n', String(size));
769 board.style.gridTemplateColumns = 'repeat(' + size + ', 1fr)';
770 board.style.gridTemplateRows = 'repeat(' + size + ', 1fr)';
771 board.innerHTML = '';
772 var legal = (!App.replay && g.legal) ? g.legal : { move: [], shoot: [] };
773 var moveSet = {};
774 (legal.move || []).forEach(function (t) { moveSet[t.x + ',' + t.y] = true; });
775 var me = findIn(g.players, g.you);
776 var showMoves = App.selected && me && App.selected === me.id;
777 for (var y = 0; y < size; y++)
778 {
779 for (var x = 0; x < size; x++)
780 {
781 var cell = document.createElement('button');
782 cell.type = 'button';
783 cell.className = 'cell';
784 cell.setAttribute('role', 'gridcell');
785 cell.dataset.x = String(x);
786 cell.dataset.y = String(y);
787 var passable = Rules.isPassable(size, inset, x, y);
788 if (!passable)
789 {
790 cell.classList.add('impassable');
791 cell.disabled = true;
792 cell.title = I18n.t('game.impassable');
793 }
794 else if (nextInset != null && !Rules.isPassable(size, nextInset, x, y))
795 {
796 cell.classList.add('threat');
797 cell.title = I18n.t('game.willShrink');
798 }
799 if (showMoves && moveSet[x + ',' + y])
800 { cell.classList.add('move-target'); }
801 var occupant = null;
802 (g.players || []).forEach(function (p)
803 {
804 if (p.x === x && p.y === y) { occupant = p; }
805 });
806 // Prefer living occupant if two (dead + living shouldn't share, but dead stay visually)
807 (g.players || []).forEach(function (p)
808 {
809 if (p.x === x && p.y === y && p.alive) { occupant = p; }
810 });
811 if (occupant)
812 {
813 var node = avatarNode(occupant, 48);
814 var pic = node.firstChild;
815 if (pic) { cell.appendChild(pic); }
816 if (App.selected === occupant.id) { cell.classList.add('selected'); }
817 if (!App.replay && legal.shoot && legal.shoot.indexOf(occupant.id) >= 0)
818 { cell.classList.add('in-range'); }
819 }
820 (function (cx, cy, occ)
821 {
822 cell.addEventListener('click', function () { App.onCell(cx, cy, occ); });
823 })(x, y, occupant);
824 board.appendChild(cell);
825 }
826 }
827};
828
829App.onCell = function (x, y, occupant)
830{
831 if (App.replay) { this.stopReplay(); }
832 var g = App.game;
833 if (!g || g.status !== 'running')
834 {
835 if (occupant) { this.openInfo(occupant); }
836 return;
837 }
838 var me = you();
839 var legal = g.legal || {};
840 // Move onto highlighted tile
841 if (me && App.selected === me.id && !occupant)
842 {
843 var ok = (legal.move || []).some(function (t) { return t.x === x && t.y === y; });
844 if (ok)
845 {
846 this.act({ type: 'move', x: x, y: y });
847 App.selected = null;
848 return;
849 }
850 }
851 if (occupant)
852 {
853 if (occupant.is_you || occupant.id === g.you)
854 {
855 App.selected = occupant.id;
856 this.renderGame();
857 return;
858 }
859 this.openPlayerOptions(occupant);
860 return;
861 }
862 App.selected = null;
863 this.renderGame();
864};
865
866App.openPlayerOptions = function (p)
867{
868 App.selected = p.id;
869 this.renderGame();
870 var g = App.game;
871 var legal = g.legal || {};
872 var body = document.createElement('div');
873 body.className = 'opt-list';
874 function add(label, fn, disabled, reason)
875 {
876 var b = document.createElement('button');
877 b.type = 'button';
878 b.textContent = label;
879 if (disabled)
880 {
881 b.disabled = true;
882 if (reason) { b.title = reason; }
883 }
884 else
885 {
886 b.addEventListener('click', function () { App.closeSheet(); fn(); });
887 }
888 body.appendChild(b);
889 }
890 add(I18n.t('opt.info'), function () { App.openInfo(p); });
891 var canAttack = legal.shoot && legal.shoot.indexOf(p.id) >= 0;
892 var cfBlock = legal.ceasefire || (g.ceasefire && g.ceasefire.active);
893 add(I18n.t('opt.attack'), function () { App.act({ type: 'shoot', target: p.id }); },
894 !canAttack,
895 cfBlock ? I18n.t('game.attackDisabledReason') : (I18n.t('error.out_of_range')));
896 var canGive = legal.give && legal.give.indexOf(p.id) >= 0;
897 add(I18n.t('opt.give'), function () { App.openGive(p); }, !canGive);
898 add(I18n.t('opt.message'), function () { App.openChat(p); });
899 $('sheet-body').innerHTML = '';
900 var head = document.createElement('h2');
901 head.textContent = p.name;
902 $('sheet-body').appendChild(head);
903 $('sheet-body').appendChild(body);
904 $('sheet').hidden = false;
905};
906
907App.openInfo = function (p)
908{
909 var body = document.createElement('div');
910 function stat(label, val)
911 {
912 var shown = (val == null) ? I18n.t('info.hidden') : String(val);
913 return '<p>' + label + ': <strong>' + shown + '</strong></p>';
914 }
915 body.innerHTML = stat(I18n.t('info.lives'), p.lives)
916 + stat(I18n.t('info.ap'), p.ap)
917 + stat(I18n.t('info.range'), p.range);
918 if (!p.alive)
919 {
920 body.innerHTML += '<p>' + I18n.t(p.surrendered ? 'game.surrendered' : 'game.dead') + '</p>';
921 }
922 var lab = document.createElement('label');
923 lab.textContent = I18n.t('info.notes');
924 var ta = document.createElement('textarea');
925 ta.rows = 5;
926 ta.value = p.note || '';
927 ta.setAttribute('maxlength', '2000');
928 var hint = document.createElement('p');
929 hint.className = 'hint';
930 hint.textContent = I18n.t('info.notesHint');
931 var save = document.createElement('button');
932 save.type = 'button';
933 save.textContent = I18n.t('info.saveNotes');
934 var st = document.createElement('span');
935 st.className = 'hint';
936 save.addEventListener('click', function ()
937 {
938 Api.note(App.game.id, p.id, ta.value).then(function (data)
939 {
940 App.game = data.game;
941 st.textContent = I18n.t('info.saved');
942 }).catch(function (err) { st.textContent = I18n.error(err.code || err.message); });
943 });
944 body.appendChild(lab);
945 body.appendChild(ta);
946 body.appendChild(hint);
947 body.appendChild(save);
948 body.appendChild(st);
949 App.openModal(I18n.t('info.title') + ' — ' + p.name, body);
950};
951
952App.openGive = function (p)
953{
954 var me = you();
955 var max = me ? me.ap : 1;
956 var body = document.createElement('div');
957 var lab = document.createElement('label');
958 lab.textContent = I18n.t('give.howMany');
959 var inp = document.createElement('input');
960 inp.type = 'number';
961 inp.min = '1';
962 inp.max = String(max);
963 inp.value = '1';
964 inp.inputMode = 'numeric';
965 var have = document.createElement('p');
966 have.className = 'hint';
967 have.textContent = I18n.t('give.youHave', { n: max });
968 var btn = document.createElement('button');
969 btn.type = 'button';
970 btn.textContent = I18n.t('give.send');
971 btn.addEventListener('click', function ()
972 {
973 var n = parseInt(inp.value, 10);
974 App.closeModal();
975 App.act({ type: 'give', target: p.id, amount: n });
976 });
977 body.appendChild(lab);
978 body.appendChild(inp);
979 body.appendChild(have);
980 body.appendChild(btn);
981 App.openModal(I18n.t('give.title') + ' — ' + p.name, body);
982};
983
984App.openChat = function (p)
985{
986 var body = document.createElement('div');
987 var log = document.createElement('div');
988 log.className = 'chat-log';
989 function fill(game)
990 {
991 log.innerHTML = '';
992 var msgs = (game.messages || []).filter(function (m)
993 {
994 return (m.from === p.id && m.to === game.you) || (m.to === p.id && m.from === game.you);
995 });
996 if (!msgs.length)
997 {
998 var em = document.createElement('p');
999 em.className = 'hint';
1000 em.textContent = I18n.t('chat.empty');
1001 log.appendChild(em);
1002 }
1003 msgs.forEach(function (m)
1004 {
1005 var b = document.createElement('div');
1006 b.className = 'chat-bubble' + (m.from === game.you ? ' mine' : '');
1007 b.textContent = m.text;
1008 log.appendChild(b);
1009 });
1010 log.scrollTop = log.scrollHeight;
1011 }
1012 fill(App.game);
1013 var row = document.createElement('form');
1014 row.className = 'chat-compose';
1015 row.action = '#';
1016 var inp = document.createElement('input');
1017 inp.type = 'text';
1018 inp.maxLength = 1000;
1019 inp.placeholder = I18n.t('chat.placeholder');
1020 inp.setAttribute('data-i18n-placeholder', 'chat.placeholder');
1021 var send = document.createElement('button');
1022 send.type = 'submit';
1023 send.textContent = I18n.t('chat.send');
1024 row.appendChild(inp);
1025 row.appendChild(send);
1026 row.addEventListener('submit', function (e)
1027 {
1028 e.preventDefault();
1029 var t = inp.value.trim();
1030 if (!t) { return; }
1031 inp.value = '';
1032 Api.message(App.game.id, p.id, t).then(function (data)
1033 {
1034 App.game = data.game;
1035 fill(App.game);
1036 }).catch(function (err) { showError('game-error', err); });
1037 });
1038 body.appendChild(log);
1039 body.appendChild(row);
1040 App.openModal(I18n.t('chat.title', { name: p.name }), body);
1041 // Keep a hook so polls refresh an open chat
1042 App._openChat = { id: p.id, fill: fill };
1043 inp.focus();
1044};
1045
1046App.openModal = function (title, body)
1047{
1048 $('modal-title').textContent = title;
1049 $('modal-body').innerHTML = '';
1050 $('modal-body').appendChild(body);
1051 $('modal').hidden = false;
1052};
1053
1054App.closeModal = function ()
1055{
1056 $('modal').hidden = true;
1057 App._openChat = null;
1058};
1059
1060App.closeSheet = function ()
1061{
1062 $('sheet').hidden = true;
1063};
1064
1065App.renderJury = function (g)
1066{
1067 var panel = $('jury-panel');
1068 var legal = g.legal || {};
1069 if (App.replay || !legal.vote)
1070 {
1071 panel.hidden = true;
1072 return;
1073 }
1074 panel.hidden = false;
1075 var ul = $('jury-list');
1076 ul.innerHTML = '';
1077 legal.vote.forEach(function (id)
1078 {
1079 var p = findIn(g.players, id);
1080 if (!p) { return; }
1081 var li = document.createElement('li');
1082 li.appendChild(avatarNode(p, 32, true));
1083 var n = document.createElement('span');
1084 n.style.flex = '1';
1085 n.textContent = p.name;
1086 li.appendChild(n);
1087 var b = document.createElement('button');
1088 b.type = 'button';
1089 if (legal.my_vote === id)
1090 {
1091 b.textContent = I18n.t('jury.votedFor', { name: p.name });
1092 b.disabled = true;
1093 }
1094 else
1095 {
1096 b.textContent = legal.my_vote ? I18n.t('jury.change') : I18n.t('jury.vote');
1097 b.addEventListener('click', function () { App.act({ type: 'vote', target: id }); });
1098 }
1099 li.appendChild(b);
1100 ul.appendChild(li);
1101 });
1102};
1103
1104App.confirmSurrender = function ()
1105{
1106 $('settings-panel').hidden = true;
1107 var body = document.createElement('div');
1108 var p = document.createElement('p');
1109 p.textContent = I18n.t('game.surrenderConfirm');
1110 var yes = document.createElement('button');
1111 yes.type = 'button';
1112 yes.className = 'btn-danger';
1113 yes.textContent = I18n.t('game.surrenderConfirmBtn');
1114 yes.addEventListener('click', function ()
1115 {
1116 App.closeModal();
1117 App.act({ type: 'surrender' });
1118 });
1119 var no = document.createElement('button');
1120 no.type = 'button';
1121 no.className = 'btn-secondary';
1122 no.textContent = I18n.t('game.surrenderCancel');
1123 no.addEventListener('click', function () { App.closeModal(); });
1124 body.appendChild(p);
1125 body.appendChild(yes);
1126 body.appendChild(document.createTextNode(' '));
1127 body.appendChild(no);
1128 App.openModal(I18n.t('game.surrender'), body);
1129};
1130
1131App.act = function (action)
1132{
1133 showError('game-error');
1134 Api.act(App.game.id, action).then(function (data)
1135 {
1136 App.game = data.game;
1137 App.selected = action.type === 'move' ? null : App.selected;
1138 App.renderGame();
1139 }).catch(function (err) { showError('game-error', err); });
1140};
1141
1142/* ---------- clocks & polling ---------- */
1143
1144App.tickClocks = function ()
1145{
1146 if (App.screen !== 'game' || !App.game) { return; }
1147 var now = Api.now();
1148 var next = App.game.next_distribution_at;
1149 if (next && App.game.status === 'running')
1150 {
1151 $('ap-hms').textContent = Rules.formatHms(next - now);
1152 $('ap-countdown').hidden = false;
1153 }
1154 else
1155 {
1156 $('ap-countdown').hidden = App.game.status !== 'running';
1157 if (App.game.status !== 'running') { $('ap-hms').textContent = '00:00:00'; }
1158 }
1159 var cf = App.game.ceasefire;
1160 var box = $('cf-countdown');
1161 if (cf && cf.enabled && cf.until && App.game.status === 'running')
1162 {
1163 box.hidden = false;
1164 box.classList.toggle('active', !!cf.active);
1165 $('cf-label').textContent = I18n.t(cf.active ? 'game.ceasefireLeft' : 'game.ceasefireUntil');
1166 $('cf-hms').textContent = Rules.formatHms(cf.until - now);
1167 }
1168 else { box.hidden = true; }
1169};
1170
1171App.startPoll = function ()
1172{
1173 this.stopPoll();
1174 this.pollTimer = setInterval(function () { App.poll(); }, 3000);
1175};
1176
1177App.stopPoll = function ()
1178{
1179 if (this.pollTimer)
1180 {
1181 clearInterval(this.pollTimer);
1182 this.pollTimer = null;
1183 }
1184};
1185
1186App.poll = function ()
1187{
1188 if (document.hidden || !App.game) { return; }
1189 var id = App.game.id;
1190 var v = App.game.version || 0;
1191 Api.sync(id, v).then(function (data)
1192 {
1193 if (!App.game || App.game.id !== id) { return; }
1194 if (data.next_distribution_at != null)
1195 { App.game.next_distribution_at = data.next_distribution_at; }
1196 if (data.ceasefire !== undefined)
1197 { App.game.ceasefire = data.ceasefire; }
1198 if (data.server_now) { /* Api already stored */ }
1199 if (data.changed && data.game)
1200 {
1201 var stayOn = App._openChat && App._openChat.id;
1202 App.game = data.game;
1203 if (App.screen === 'lobby' && data.game.status === 'lobby')
1204 { App.renderLobby(); }
1205 else if (data.game.status !== 'lobby')
1206 {
1207 if (App.screen !== 'game') { showScreen('game'); }
1208 if (!App.replay) { App.renderGame(); }
1209 else { App.renderTimeline(App.game); }
1210 }
1211 if (stayOn && App._openChat)
1212 { App._openChat.fill(App.game); }
1213 }
1214 App.tickClocks();
1215 }).catch(function () { /* transient; next poll retries */ });
1216};
1217
1218App.refreshFull = function ()
1219{
1220 if (!App.game) { return; }
1221 var id = App.game.id;
1222 Api.game(id).then(function (data)
1223 {
1224 if (!App.game || App.game.id !== id) { return; }
1225 App.game = data.game;
1226 if (data.game.status === 'lobby') { App.renderLobby(); }
1227 else { App.renderGame(); }
1228 if (App._openChat) { App._openChat.fill(App.game); }
1229 }).catch(function () {});
1230};
1231
1232/* ---------- timeline ---------- */
1233
1234App.spendEvents = function (game)
1235{
1236 return (game.events || []).filter(function (e) { return e.spend; });
1237};
1238
1239App.renderTimeline = function (game)
1240{
1241 var spends = this.spendEvents(game);
1242 var track = $('tl-track');
1243 var ticks = $('tl-ticks');
1244 ticks.innerHTML = '';
1245 var n = spends.length;
1246 track.setAttribute('aria-valuemax', String(Math.max(n, 0)));
1247 spends.forEach(function (e, i)
1248 {
1249 var t = document.createElement('div');
1250 t.className = 'tl-tick';
1251 // Align with playhead: spend i is at index i+1, position (i+1)/n.
1252 t.style.left = ((n <= 0 ? 0 : (i + 1) / n) * 100) + '%';
1253 ticks.appendChild(t);
1254 });
1255 var idx = App.replay ? App.replay.index : n;
1256 this.setPlayhead(idx, n);
1257 $('tl-play').textContent = (App.replay && App.replay.timer) ? '❚❚' : '▶';
1258 $('tl-play').title = I18n.t((App.replay && App.replay.timer) ? 'timeline.pause' : 'timeline.play');
1259 this.setCaption();
1260 track.setAttribute('aria-valuetext', idx + ' / ' + n);
1261};
1262
1263App.setPlayhead = function (idx, n)
1264{
1265 var head = $('tl-head');
1266 if (n <= 0)
1267 { head.style.left = '0%'; }
1268 else if (n === 1)
1269 { head.style.left = (idx <= 0 ? '0%' : '100%'); }
1270 else
1271 { head.style.left = (Math.max(0, Math.min(n, idx)) / n) * 100 + '%'; }
1272 $('tl-track').setAttribute('aria-valuenow', String(idx));
1273};
1274
1275App.setCaption = function ()
1276{
1277 // No direct text log: events are shown only as playback visuals.
1278 var el = $('tl-caption');
1279 if (el)
1280 {
1281 el.hidden = true;
1282 el.textContent = '';
1283 }
1284};
1285
1286App.eventLabel = function (ev, game)
1287{
1288 function name(id)
1289 {
1290 var p = findIn(game.players, id);
1291 return p ? p.name : (id || '');
1292 }
1293 switch (ev.type)
1294 {
1295 case 'start': return I18n.t('timeline.event.start');
1296 case 'move': return I18n.t('timeline.event.move', { name: name(ev.player) });
1297 case 'shoot': return I18n.t('timeline.event.shoot', { name: name(ev.player), target: name(ev.target) });
1298 case 'give': return I18n.t('timeline.event.give', { name: name(ev.player), target: name(ev.target), n: ev.amount });
1299 case 'upgrade': return I18n.t('timeline.event.upgrade', { name: name(ev.player), n: ev.range });
1300 case 'surrender': return I18n.t('timeline.event.surrender', { name: name(ev.player) });
1301 case 'daily':
1302 var s = I18n.t('timeline.event.daily', { n: ev.day });
1303 if (ev.jury && ev.jury.winners && ev.jury.winners.length)
1304 {
1305 var names = ev.jury.winners.map(name);
1306 s += ' — ' + (names.length === 1
1307 ? I18n.t('timeline.event.jury', { name: names[0] })
1308 : I18n.t('timeline.event.juryTie', { names: names.join(', ') }));
1309 }
1310 return s;
1311 case 'shrink': return I18n.t('timeline.event.shrink');
1312 case 'win': return I18n.t('timeline.event.win', { name: name(ev.player) });
1313 case 'draw': return I18n.t('timeline.event.draw');
1314 case 'death':
1315 if (ev.cause === 'shot') { return I18n.t('timeline.event.deathShot', { name: name(ev.player), by: name(ev.by) }); }
1316 if (ev.cause === 'shrink') { return I18n.t('timeline.event.deathShrink', { name: name(ev.player) }); }
1317 if (ev.cause === 'crushed') { return I18n.t('timeline.event.deathCrushed', { name: name(ev.player) }); }
1318 return I18n.t('timeline.event.death', { name: name(ev.player) });
1319 default: return ev.type;
1320 }
1321};
1322
1323App.bindTimelineScrub = function ()
1324{
1325 var track = $('tl-track');
1326 var dragging = false;
1327 function clientX(ev)
1328 {
1329 if (ev.clientX != null && ev.clientX !== 0) { return ev.clientX; }
1330 if (ev.touches && ev.touches[0]) { return ev.touches[0].clientX; }
1331 if (ev.changedTouches && ev.changedTouches[0]) { return ev.changedTouches[0].clientX; }
1332 return ev.clientX;
1333 }
1334 function pos(ev)
1335 {
1336 var r = track.getBoundingClientRect();
1337 var x = clientX(ev) - r.left;
1338 var t = r.width <= 0 ? 0 : x / r.width;
1339 var n = App.spendEvents(App.game).length;
1340 return Rules.timelineIndex(t, n);
1341 }
1342 function go(ev, scrub)
1343 {
1344 if (!App.game) { return; }
1345 // Click/tap: jump to the nearest event. Drag: scrub through them.
1346 App.jumpReplay(pos(ev), { animate: false, scrub: !!scrub });
1347 }
1348 function down(e)
1349 {
1350 if (e.button != null && e.button !== 0) { return; }
1351 dragging = true;
1352 if (track.setPointerCapture && e.pointerId != null)
1353 {
1354 try { track.setPointerCapture(e.pointerId); } catch (err) {}
1355 }
1356 if (e.preventDefault) { e.preventDefault(); }
1357 go(e, false);
1358 }
1359 function move(e)
1360 {
1361 if (!dragging) { return; }
1362 if (e.preventDefault) { e.preventDefault(); }
1363 go(e, true);
1364 }
1365 function up() { dragging = false; }
1366 track.addEventListener('pointerdown', down);
1367 track.addEventListener('pointermove', move);
1368 track.addEventListener('pointerup', up);
1369 track.addEventListener('pointercancel', up);
1370 // Fallback for older browsers / mixed input: same handlers on touch.
1371 track.addEventListener('touchstart', down, { passive: false });
1372 track.addEventListener('touchmove', move, { passive: false });
1373 track.addEventListener('touchend', up);
1374 track.addEventListener('touchcancel', up);
1375};
1376
1377App.toggleReplay = function ()
1378{
1379 if (App.replay && App.replay.timer)
1380 {
1381 clearInterval(App.replay.timer);
1382 App.replay.timer = null;
1383 this.renderTimeline(App.game);
1384 return;
1385 }
1386 var n = this.spendEvents(App.game).length;
1387 if (!n) { return; }
1388 var startAt = (App.replay && App.replay.index < n) ? App.replay.index : 0;
1389 this.jumpReplay(startAt);
1390 App.replay.timer = setInterval(function ()
1391 {
1392 if (!App.replay) { return; }
1393 if (App.replay.index >= n)
1394 {
1395 App.stopReplay();
1396 return;
1397 }
1398 App.jumpReplay(App.replay.index + 1);
1399 }, 500);
1400 this.renderTimeline(App.game);
1401};
1402
1403App.jumpReplay = function (index, opts)
1404{
1405 opts = opts || {};
1406 var game = App.game;
1407 var spends = this.spendEvents(game);
1408 var n = spends.length;
1409 index = Math.max(0, Math.min(n, index));
1410 var prev = App.replay && App.replay.view;
1411 var prevIndex = App.replay ? App.replay.index : null;
1412 var view = this.viewAtSpend(game, index);
1413 if (!App.replay) { App.replay = { timer: null }; }
1414 var stepping = prevIndex != null && index === prevIndex + 1;
1415 var animate = opts.animate !== false && (opts.animate || (App.replay.timer && stepping));
1416 App.replay.index = index;
1417 App.replay.view = view;
1418 this.renderBoard(view);
1419 this.renderHud(view);
1420 this.renderJury(view);
1421 this.renderTimeline(game);
1422 this.setCaption();
1423 var ev = index > 0 ? spends[index - 1] : null;
1424 this.playBoardFx(view, ev, prev, !!animate);
1425};
1426
1427App.viewAtSpend = function (game, spendCount)
1428{
1429 // Walk a shallow clone of players from the start event / initial, applying
1430 // events until `spendCount` spend-ticks have been applied.
1431 var players = (game.players || []).map(function (p)
1432 {
1433 return Object.assign({}, p);
1434 });
1435 // Remember which numeric stats the server hid from this viewer, so replay
1436 // never invents values the live state would not show.
1437 var hidden = {};
1438 players.forEach(function (p)
1439 {
1440 hidden[p.id] = { lives: p.lives == null, ap: p.ap == null, range: p.range == null };
1441 });
1442 var events = game.events || [];
1443 var applied = 0;
1444 var start = events.filter(function (e) { return e.type === 'start'; })[0];
1445 if (start && start.players)
1446 {
1447 start.players.forEach(function (sp)
1448 {
1449 players.forEach(function (p)
1450 {
1451 if (p.id === sp.id)
1452 {
1453 p.x = sp.x; p.y = sp.y;
1454 if (!hidden[p.id] || !hidden[p.id].lives) { p.lives = 3; }
1455 if (!hidden[p.id] || !hidden[p.id].ap) { p.ap = 1; }
1456 if (!hidden[p.id] || !hidden[p.id].range) { p.range = 2; }
1457 p.alive = true; p.surrendered = false;
1458 }
1459 });
1460 });
1461 }
1462 var inset = 0;
1463 var day = 0;
1464 function apply(ev)
1465 {
1466 var p;
1467 if (ev.type === 'move')
1468 {
1469 p = findIn(players, ev.player);
1470 if (p && ev.to) { p.x = ev.to.x; p.y = ev.to.y; if (p.ap > 0) { p.ap--; } }
1471 }
1472 else if (ev.type === 'shoot')
1473 {
1474 p = findIn(players, ev.player);
1475 if (p && p.ap != null && p.ap > 0) { p.ap--; }
1476 var t = findIn(players, ev.target);
1477 if (t)
1478 {
1479 if (ev.lives_left != null && t.lives != null) { t.lives = ev.lives_left; }
1480 if (ev.killed)
1481 {
1482 t.alive = false;
1483 if (t.ap != null) { t.ap = 0; }
1484 if (t.lives != null) { t.lives = 0; }
1485 }
1486 }
1487 }
1488 else if (ev.type === 'give')
1489 {
1490 p = ev.player ? findIn(players, ev.player) : null;
1491 var t2 = findIn(players, ev.target);
1492 if (p && p.ap != null) { p.ap = Math.max(0, p.ap - (ev.amount || 1)); }
1493 if (t2 && t2.ap != null) { t2.ap += (ev.amount || 1); }
1494 }
1495 else if (ev.type === 'upgrade')
1496 {
1497 p = findIn(players, ev.player);
1498 if (p)
1499 {
1500 if (p.range != null && ev.range != null) { p.range = ev.range; }
1501 if (p.ap != null && p.ap > 0) { p.ap--; }
1502 }
1503 }
1504 else if (ev.type === 'surrender')
1505 {
1506 p = findIn(players, ev.player);
1507 if (p) { p.alive = false; p.surrendered = true; p.lives = 0; p.ap = 0; }
1508 }
1509 else if (ev.type === 'daily' && ev.grants)
1510 {
1511 day = ev.day || day;
1512 players.forEach(function (pl)
1513 {
1514 if (ev.grants[pl.id]) { pl.ap += ev.grants[pl.id]; }
1515 });
1516 }
1517 else if (ev.type === 'shrink')
1518 {
1519 inset = ev.inset || inset;
1520 (ev.moved || []).forEach(function (m)
1521 {
1522 var q = findIn(players, m.id);
1523 if (q && m.to) { q.x = m.to.x; q.y = m.to.y; if (q.lives > 0 && ev.hurt && ev.hurt.indexOf(m.id) >= 0) { /* already in lives? */ } }
1524 });
1525 (ev.hurt || []).forEach(function (id)
1526 {
1527 var q = findIn(players, id);
1528 if (q && ev.killed && ev.killed.indexOf(id) < 0 && q.lives > 0) { q.lives = Math.max(1, q.lives); }
1529 });
1530 (ev.killed || []).forEach(function (id)
1531 {
1532 var q = findIn(players, id);
1533 if (q) { q.alive = false; q.lives = 0; q.ap = 0; }
1534 });
1535 }
1536 }
1537 for (var i = 0; i < events.length; i++)
1538 {
1539 var ev = events[i];
1540 if (ev.spend)
1541 {
1542 if (applied >= spendCount) { break; }
1543 apply(ev);
1544 applied++;
1545 }
1546 else
1547 {
1548 // Apply non-spend events that occurred before this point (start,
1549 // daily, shrink, death) — only those before the next unapplied spend.
1550 // If we have already reached the target spend count, stop before later dailies.
1551 if (applied >= spendCount && ev.type !== 'start') { continue; }
1552 apply(ev);
1553 }
1554 }
1555 players.forEach(function (p)
1556 {
1557 var h = hidden[p.id];
1558 if (!h) { return; }
1559 if (h.lives) { p.lives = null; }
1560 if (h.ap) { p.ap = null; }
1561 if (h.range) { p.range = null; }
1562 });
1563 return {
1564 you: game.you,
1565 players: players,
1566 grid: game.grid,
1567 arena_inset: inset,
1568 max_inset: game.max_inset,
1569 shrink_in_days: null,
1570 rules: game.rules,
1571 legal: { move: [], shoot: [], give: [], upgrade: false, vote: null },
1572 day: day,
1573 status: game.status,
1574 winner_id: null,
1575 draw: false,
1576 next_distribution_at: null,
1577 ceasefire: null
1578 };
1579};
1580
1581App.stopReplay = function ()
1582{
1583 if (App.replay && App.replay.timer)
1584 { clearInterval(App.replay.timer); }
1585 App.replay = null;
1586 this.clearBoardFx();
1587 if (App.game && App.screen === 'game')
1588 {
1589 this.renderGame();
1590 }
1591};
1592
1593App.clearBoardFx = function ()
1594{
1595 var fx = $('board-fx');
1596 if (fx) { fx.innerHTML = ''; }
1597 var wrap = $('board-wrap');
1598 if (wrap)
1599 {
1600 wrap.querySelectorAll('.fx-float').forEach(function (n) { n.remove(); });
1601 }
1602 document.querySelectorAll('#board .piece.moving, #board .piece.range-pulse, #board .piece-initials.moving, #board .piece-initials.range-pulse').forEach(function (el)
1603 {
1604 el.classList.remove('moving', 'range-pulse');
1605 el.style.transform = '';
1606 el.style.transition = '';
1607 });
1608};
1609
1610App.cellCenter = function (x, y)
1611{
1612 var cell = document.querySelector('#board .cell[data-x="' + x + '"][data-y="' + y + '"]');
1613 var wrap = $('board-wrap');
1614 if (!cell || !wrap) { return null; }
1615 var wr = wrap.getBoundingClientRect();
1616 var r = cell.getBoundingClientRect();
1617 return {
1618 x: r.left + r.width / 2 - wr.left,
1619 y: r.top + r.height / 2 - wr.top,
1620 s: Math.min(r.width, r.height)
1621 };
1622};
1623
1624App.playerCell = function (view, id)
1625{
1626 var p = findIn(view && view.players, id);
1627 if (!p) { return null; }
1628 return App.cellCenter(p.x, p.y);
1629};
1630
1631App.pieceInCell = function (x, y)
1632{
1633 var cell = document.querySelector('#board .cell[data-x="' + x + '"][data-y="' + y + '"]');
1634 return cell ? cell.querySelector('.piece, .piece-initials') : null;
1635};
1636
1637App.playBoardFx = function (view, ev, prev, animate)
1638{
1639 this.clearBoardFx();
1640 if (!ev || !view) { return; }
1641 var wrap = $('board-wrap');
1642 var fx = $('board-fx');
1643 if (!wrap || !fx) { return; }
1644 fx.setAttribute('width', String(wrap.clientWidth));
1645 fx.setAttribute('height', String(wrap.clientHeight));
1646 fx.setAttribute('viewBox', '0 0 ' + wrap.clientWidth + ' ' + wrap.clientHeight);
1647
1648 if (ev.type === 'shoot' && ev.target)
1649 {
1650 var from = ev.player ? App.playerCell(prev || view, ev.player) : null;
1651 var to = App.playerCell(view, ev.target);
1652 // If the shooter is known (not filtered), draw a red arrow; the number
1653 // is damage, not remaining lives, so it does not leak hidden life totals.
1654 if (from && to && ev.player)
1655 {
1656 App.drawArrow(from, to, '#e85d5d', ev.damage != null ? ev.damage : 1);
1657 }
1658 else if (to)
1659 {
1660 App.floatNumber(to, ev.damage != null ? ev.damage : 1, '#e85d5d');
1661 }
1662 if (ev.loot && ev.player)
1663 {
1664 var lootAt = App.playerCell(view, ev.player);
1665 if (lootAt) { App.floatNumber(lootAt, '+' + ev.loot, '#4ecb8d'); }
1666 }
1667 }
1668 else if (ev.type === 'give')
1669 {
1670 var tTo = ev.target ? App.playerCell(view, ev.target) : null;
1671 var amount = ev.amount != null ? ev.amount : 1;
1672 if (ev.anonymous || !ev.player)
1673 {
1674 // Must not reveal the giver: show the AP gain on the recipient only,
1675 // with no source arrow (an arrow "from nowhere" would still suggest a direction).
1676 if (tTo) { App.floatNumber(tTo, '+' + amount, '#4ecb8d'); }
1677 }
1678 else
1679 {
1680 var gFrom = App.playerCell(prev || view, ev.player);
1681 if (gFrom && tTo)
1682 {
1683 App.drawArrow(gFrom, tTo, '#4ecb8d', amount);
1684 }
1685 else if (tTo)
1686 {
1687 App.floatNumber(tTo, '+' + amount, '#4ecb8d');
1688 }
1689 }
1690 }
1691 else if (ev.type === 'move' && ev.to && ev.from && ev.player && animate)
1692 {
1693 App.animateMove(ev.from, ev.to);
1694 }
1695 else if (ev.type === 'upgrade' && ev.player)
1696 {
1697 var p = findIn(view.players, ev.player);
1698 if (p)
1699 {
1700 var piece = App.pieceInCell(p.x, p.y);
1701 if (piece)
1702 {
1703 piece.classList.remove('range-pulse');
1704 void piece.offsetWidth;
1705 piece.classList.add('range-pulse');
1706 }
1707 }
1708 }
1709};
1710
1711App.drawArrow = function (from, to, color, number)
1712{
1713 var fx = $('board-fx');
1714 if (!fx || !from || !to) { return; }
1715 var ns = 'http://www.w3.org/2000/svg';
1716 var dx = to.x - from.x, dy = to.y - from.y;
1717 var len = Math.sqrt(dx * dx + dy * dy) || 1;
1718 var ux = dx / len, uy = dy / len;
1719 var inset = Math.min(from.s || 24, to.s || 24) * 0.38;
1720 if (inset * 2 >= len) { inset = len * 0.22; }
1721 var x1 = from.x + ux * inset, y1 = from.y + uy * inset;
1722 var x2 = to.x - ux * inset, y2 = to.y - uy * inset;
1723 var mid = 'm' + Math.round(x1) + '-' + Math.round(y1) + '-' + Math.round(x2) + '-' + Math.round(y2);
1724 var defs = document.createElementNS(ns, 'defs');
1725 var marker = document.createElementNS(ns, 'marker');
1726 marker.setAttribute('id', mid);
1727 marker.setAttribute('viewBox', '0 0 10 10');
1728 marker.setAttribute('refX', '8');
1729 marker.setAttribute('refY', '5');
1730 marker.setAttribute('markerWidth', '7');
1731 marker.setAttribute('markerHeight', '7');
1732 marker.setAttribute('orient', 'auto');
1733 var tip = document.createElementNS(ns, 'path');
1734 tip.setAttribute('d', 'M 0 0 L 10 5 L 0 10 z');
1735 tip.setAttribute('fill', color);
1736 marker.appendChild(tip);
1737 defs.appendChild(marker);
1738 fx.appendChild(defs);
1739 var line = document.createElementNS(ns, 'line');
1740 line.setAttribute('x1', String(x1));
1741 line.setAttribute('y1', String(y1));
1742 line.setAttribute('x2', String(x2));
1743 line.setAttribute('y2', String(y2));
1744 line.setAttribute('stroke', color);
1745 line.setAttribute('stroke-width', '4');
1746 line.setAttribute('stroke-linecap', 'round');
1747 line.setAttribute('marker-end', 'url(#' + mid + ')');
1748 fx.appendChild(line);
1749 if (number != null && number !== '')
1750 {
1751 var mx = x1 + (x2 - x1) * 0.55;
1752 var my = y1 + (y2 - y1) * 0.55;
1753 var circ = document.createElementNS(ns, 'circle');
1754 circ.setAttribute('cx', String(mx));
1755 circ.setAttribute('cy', String(my));
1756 circ.setAttribute('r', '13');
1757 circ.setAttribute('fill', color);
1758 circ.setAttribute('stroke', '#0c1020');
1759 circ.setAttribute('stroke-width', '2');
1760 fx.appendChild(circ);
1761 var tx = document.createElementNS(ns, 'text');
1762 tx.setAttribute('x', String(mx));
1763 tx.setAttribute('y', String(my + 1));
1764 tx.setAttribute('text-anchor', 'middle');
1765 tx.setAttribute('dominant-baseline', 'middle');
1766 tx.setAttribute('fill', '#fff');
1767 tx.setAttribute('font-size', '13');
1768 tx.setAttribute('font-weight', '700');
1769 tx.setAttribute('font-family', 'ui-sans-serif, system-ui, sans-serif');
1770 tx.textContent = String(number);
1771 fx.appendChild(tx);
1772 }
1773};
1774
1775App.floatNumber = function (at, text, color)
1776{
1777 var wrap = $('board-wrap');
1778 if (!wrap || !at) { return; }
1779 var el = document.createElement('div');
1780 el.className = 'fx-float';
1781 el.textContent = String(text);
1782 el.style.left = at.x + 'px';
1783 el.style.top = at.y + 'px';
1784 if (color) { el.style.color = color; }
1785 wrap.appendChild(el);
1786};
1787
1788App.animateMove = function (from, to)
1789{
1790 var piece = App.pieceInCell(to.x, to.y);
1791 var a = App.cellCenter(from.x, from.y);
1792 var b = App.cellCenter(to.x, to.y);
1793 if (!piece || !a || !b) { return; }
1794 var dx = a.x - b.x, dy = a.y - b.y;
1795 if (Math.abs(dx) < 1 && Math.abs(dy) < 1) { return; }
1796 piece.classList.add('moving');
1797 piece.style.transition = 'none';
1798 piece.style.transform = 'translate(' + dx + 'px, ' + dy + 'px)';
1799 requestAnimationFrame(function ()
1800 {
1801 requestAnimationFrame(function ()
1802 {
1803 piece.style.transition = 'transform 0.4s ease';
1804 piece.style.transform = 'translate(0, 0)';
1805 });
1806 });
1807};
1808
1809
1810function escapeHtml(s)
1811{
1812 return String(s).replace(/[&<>"']/g, function (c)
1813 {
1814 return ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c];
1815 });
1816}
1817
1818/* ---------- 24-hour cease-fire clock ---------- */
1819
1820var CeasefireClock = {
1821 size: 320,
1822 cx: 160,
1823 cy: 160,
1824 r: 128
1825};
1826
1827CeasefireClock.minsToAngle = function (mins)
1828{
1829 // 0 at top, clockwise, 1440 minutes = 360°.
1830 return (mins / 1440) * 2 * Math.PI - Math.PI / 2;
1831};
1832
1833CeasefireClock.angleToMins = function (ang)
1834{
1835 // atan2: 0 at 3 o'clock, CCW. Convert to clockwise from top.
1836 var a = ang + Math.PI / 2;
1837 if (a < 0) { a += 2 * Math.PI; }
1838 var mins = Math.round((a / (2 * Math.PI)) * 1440 / 5) * 5;
1839 if (mins >= 1440) { mins = 0; }
1840 if (mins < 0) { mins = 0; }
1841 return mins;
1842};
1843
1844CeasefireClock.arcPath = function (r, startMin, endMin)
1845{
1846 var cx = this.cx, cy = this.cy;
1847 var a1 = this.minsToAngle(startMin);
1848 var a2 = this.minsToAngle(endMin);
1849 var x1 = cx + r * Math.cos(a1), y1 = cy + r * Math.sin(a1);
1850 var x2 = cx + r * Math.cos(a2), y2 = cy + r * Math.sin(a2);
1851 var delta = endMin - startMin;
1852 if (delta <= 0) { delta += 1440; }
1853 var large = delta > 720 ? 1 : 0;
1854 return 'M ' + cx + ' ' + cy + ' L ' + x1 + ' ' + y1 + ' A ' + r + ' ' + r + ' 0 ' + large + ' 1 ' + x2 + ' ' + y2 + ' Z';
1855};
1856
1857CeasefireClock.handlePos = function (mins)
1858{
1859 var a = this.minsToAngle(mins);
1860 return { x: this.cx + this.r * Math.cos(a), y: this.cy + this.r * Math.sin(a) };
1861};
1862
1863CeasefireClock.render = function (container, ranges, opts)
1864{
1865 opts = opts || {};
1866 var self = this;
1867 ranges = Rules.normalizeRanges(ranges || []);
1868 var size = this.size;
1869 var svgNS = 'http://www.w3.org/2000/svg';
1870 container.innerHTML = '';
1871 var svg = document.createElementNS(svgNS, 'svg');
1872 svg.setAttribute('viewBox', '0 0 ' + size + ' ' + size);
1873 svg.setAttribute('width', String(size));
1874 svg.setAttribute('height', String(size));
1875 svg.setAttribute('role', 'img');
1876
1877 function el(name, attrs)
1878 {
1879 var n = document.createElementNS(svgNS, name);
1880 Object.keys(attrs).forEach(function (k) { n.setAttribute(k, attrs[k]); });
1881 return n;
1882 }
1883
1884 // Allowed (gold) background disc
1885 svg.appendChild(el('circle', {
1886 cx: this.cx, cy: this.cy, r: this.r,
1887 fill: '#3a3420', stroke: '#e8c547', 'stroke-width': '3'
1888 }));
1889
1890 // Cease-fire slices (red)
1891 ranges.forEach(function (r, i)
1892 {
1893 var s = Rules.hmToMinutes(r.start);
1894 var e = Rules.hmToMinutes(r.end);
1895 var slices = e > s ? [[s, e]] : [[s, 1440], [0, e]];
1896 slices.forEach(function (sl)
1897 {
1898 if (sl[1] === sl[0]) { return; }
1899 svg.appendChild(el('path', {
1900 d: self.arcPath(self.r - 1, sl[0], sl[1]),
1901 fill: '#8a2a2a',
1902 'fill-opacity': '0.92',
1903 'data-range': String(i)
1904 }));
1905 });
1906 });
1907
1908 // Ticks and labels (0 at top, then 3, 6, 12, 18…)
1909 for (var h = 0; h < 24; h++)
1910 {
1911 var mins = h * 60;
1912 var a = this.minsToAngle(mins);
1913 var inner = this.r - (h % 3 === 0 ? 14 : 7);
1914 var outer = this.r;
1915 svg.appendChild(el('line', {
1916 x1: this.cx + inner * Math.cos(a),
1917 y1: this.cy + inner * Math.sin(a),
1918 x2: this.cx + outer * Math.cos(a),
1919 y2: this.cy + outer * Math.sin(a),
1920 stroke: '#e8eaf2',
1921 'stroke-width': h % 6 === 0 ? '2.2' : '1',
1922 'stroke-opacity': '0.7'
1923 }));
1924 if (h % 3 === 0)
1925 {
1926 var tx = this.cx + (this.r + 22) * Math.cos(a);
1927 var ty = this.cy + (this.r + 22) * Math.sin(a);
1928 var lab = el('text', {
1929 x: tx, y: ty,
1930 fill: '#e8c547',
1931 'font-size': '13',
1932 'font-weight': '700',
1933 'text-anchor': 'middle',
1934 'dominant-baseline': 'middle',
1935 'pointer-events': 'none'
1936 });
1937 lab.textContent = String(h);
1938 svg.appendChild(lab);
1939 }
1940 }
1941
1942 // Inner hole so it looks like a ring-pie (keep a smaller gold disc for “now” later)
1943 svg.appendChild(el('circle', {
1944 cx: this.cx, cy: this.cy, r: 36,
1945 fill: '#0c1020', stroke: '#e8c54755', 'stroke-width': '1.5'
1946 }));
1947 var mid = el('text', {
1948 x: this.cx, y: this.cy + 1,
1949 fill: '#e8eaf2',
1950 'font-size': '11',
1951 'text-anchor': 'middle',
1952 'dominant-baseline': 'middle',
1953 'pointer-events': 'none'
1954 });
1955 mid.textContent = '24h';
1956 svg.appendChild(mid);
1957
1958 // Handles
1959 if (opts.editable)
1960 {
1961 ranges.forEach(function (r, i)
1962 {
1963 ['start', 'end'].forEach(function (which)
1964 {
1965 var pos = self.handlePos(Rules.hmToMinutes(r[which]));
1966 var c = el('circle', {
1967 cx: pos.x, cy: pos.y, r: 14,
1968 fill: '#e8c547',
1969 stroke: '#1a1404',
1970 'stroke-width': '2',
1971 'data-range': String(i),
1972 'data-which': which,
1973 style: 'cursor:grab; touch-action:none'
1974 });
1975 // invisible larger hit target
1976 var hit = el('circle', {
1977 cx: pos.x, cy: pos.y, r: 22,
1978 fill: 'transparent',
1979 'data-range': String(i),
1980 'data-which': which,
1981 style: 'cursor:grab; touch-action:none'
1982 });
1983 svg.appendChild(hit);
1984 svg.appendChild(c);
1985 });
1986 });
1987 }
1988
1989 container.appendChild(svg);
1990 if (!opts.editable) { return; }
1991
1992 var drag = null;
1993 var painting = null;
1994
1995 function localMins(ev)
1996 {
1997 var rect = svg.getBoundingClientRect();
1998 var cx = ev.clientX != null ? ev.clientX : ev.touches[0].clientX;
1999 var cy = ev.clientY != null ? ev.clientY : ev.touches[0].clientY;
2000 var x = (cx - rect.left) / rect.width * size;
2001 var y = (cy - rect.top) / rect.height * size;
2002 return self.angleToMins(Math.atan2(y - self.cy, x - self.cx));
2003 }
2004
2005 function commit(next)
2006 {
2007 if (opts.onChange) { opts.onChange(next); }
2008 }
2009
2010 svg.addEventListener('pointerdown', function (e)
2011 {
2012 e.preventDefault();
2013 svg.setPointerCapture(e.pointerId);
2014 var t = e.target;
2015 var ri = t.getAttribute && t.getAttribute('data-range');
2016 var which = t.getAttribute && t.getAttribute('data-which');
2017 if (ri != null && which)
2018 {
2019 drag = { i: parseInt(ri, 10), which: which };
2020 return;
2021 }
2022 // Start a new range from this angle, drag to set the end.
2023 var m = localMins(e);
2024 painting = { start: m, end: (m + 60) % 1440 };
2025 });
2026 svg.addEventListener('pointermove', function (e)
2027 {
2028 if (!drag && !painting) { return; }
2029 e.preventDefault();
2030 var m = localMins(e);
2031 if (drag)
2032 {
2033 var next = ranges.map(function (r) { return { start: r.start, end: r.end }; });
2034 if (!next[drag.i]) { return; }
2035 next[drag.i][drag.which] = Rules.minutesToHm(m);
2036 // Live preview
2037 self.render(container, next, opts);
2038 // re-bind happens via render → we need to keep dragging. Store on object.
2039 CeasefireClock._pending = { drag: drag, ranges: next, opts: opts, container: container };
2040 }
2041 else if (painting)
2042 {
2043 painting.end = m;
2044 var preview = ranges.concat([{
2045 start: Rules.minutesToHm(painting.start),
2046 end: Rules.minutesToHm(painting.end === painting.start ? (painting.start + 5) % 1440 : painting.end)
2047 }]);
2048 self.render(container, preview, opts);
2049 CeasefireClock._pending = { painting: painting, ranges: ranges, opts: opts, container: container };
2050 }
2051 });
2052 function endDrag(e)
2053 {
2054 var pending = CeasefireClock._pending;
2055 CeasefireClock._pending = null;
2056 if (drag && pending && pending.ranges)
2057 {
2058 var d = drag;
2059 drag = null;
2060 commit(pending.ranges);
2061 return;
2062 }
2063 if (painting)
2064 {
2065 var p = painting;
2066 painting = null;
2067 if (p.start === p.end) { self.render(container, ranges, opts); return; }
2068 commit(ranges.concat([{
2069 start: Rules.minutesToHm(p.start),
2070 end: Rules.minutesToHm(p.end)
2071 }]));
2072 }
2073 drag = null;
2074 }
2075 svg.addEventListener('pointerup', endDrag);
2076 svg.addEventListener('pointercancel', endDrag);
2077};
2078
2079// Re-attach pointer handlers after a live-preview re-render by using
2080// event delegation on the container (already on svg after each render).
2081// The _pending flag lets pointermove after re-render continue: we also
2082// bind at the document level during a drag.
2083(function ()
2084{
2085 var active = false;
2086 document.addEventListener('pointermove', function (e)
2087 {
2088 var p = CeasefireClock._pending;
2089 if (!p || !p.opts) { return; }
2090 if (!p.drag && !p.painting) { return; }
2091 // The new svg already has handlers; this is a safety net no-op if they fire.
2092 });
2093})();
2094
2095/* boot */
2096if (typeof document !== 'undefined')
2097{
2098 if (document.readyState === 'loading')
2099 { document.addEventListener('DOMContentLoaded', function () { App.init(); }); }
2100 else
2101 { App.init(); }
2102}
2103
2104if (typeof module !== 'undefined' && module.exports)
2105{ module.exports = { App: App, CeasefireClock: CeasefireClock, Rules: (typeof Rules !== 'undefined' ? Rules : null) }; }