BlueGit

projects-timfalken-com allianties

Files

allianties / src / main.js

main.js

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