BlueGit

projects-timfalken-com allianties

Files

allianties / src / main.js

main.js

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