BlueGit

projects-timfalken-com allianties

Files

allianties / src / main.js

main.js

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