Maybe we can finally get rid of these code bits which shouldn't be required ?
[xogo.git] / app.js
CommitLineData
41534b92
BA
1let $ = document; //shortcut
2
3///////////////////
4// Initialisations
5
6// https://stackoverflow.com/a/27747377/12660887
41534b92 7function generateId (len) {
f46a68b8
BA
8 const dec2hex = (dec) => dec.toString(16).padStart(2, "0");
9 let arr = new Uint8Array(len / 2); //len/2 because 2 chars per hex value
10 window.crypto.getRandomValues(arr); //fill with random integers
11 return Array.from(arr, dec2hex).join('');
41534b92
BA
12}
13
14// Populate variants dropdown list
15let dropdown = $.getElementById("selectVariant");
16dropdown[0] = new Option("? ? ?", "_random", true, true);
17dropdown[0].title = "Random variant";
18for (let i = 0; i < variants.length; i++) {
19 let newOption = new Option(
20 variants[i].disp || variants[i].name, variants[i].name, false, false);
21 newOption.title = variants[i].desc;
22 dropdown[dropdown.length] = newOption;
23}
24
25// Ensure that I have a socket ID and a name
26if (!localStorage.getItem("sid"))
27 localStorage.setItem("sid", generateId(8));
28if (!localStorage.getItem("name"))
29 localStorage.setItem("name", "@non" + generateId(4));
30const sid = localStorage.getItem("sid");
31$.getElementById("myName").value = localStorage.getItem("name");
32
86f3c2cd
BA
33// "Material" input field name
34let inputName = document.getElementById("myName");
35let formField = document.getElementById("ng-name");
36const setActive = (active) => {
b4ae3ff6
BA
37 if (active)
38 formField.classList.add("form-field--is-active");
86f3c2cd
BA
39 else {
40 formField.classList.remove("form-field--is-active");
f46a68b8
BA
41 inputName.value == ''
42 ? formField.classList.remove("form-field--is-filled")
43 : formField.classList.add("form-field--is-filled");
86f3c2cd
BA
44 }
45};
f46a68b8 46setActive(true);
86f3c2cd
BA
47inputName.onblur = () => setActive(false);
48inputName.onfocus = () => setActive(true);
86f3c2cd 49
41534b92
BA
50/////////
51// Utils
52
53function setName() {
f46a68b8 54 // 'onChange' event on name input text field [HTML]
41534b92
BA
55 localStorage.setItem("name", $.getElementById("myName").value);
56}
57
58// Turn a "tab" on, and "close" all others
59function toggleVisible(element) {
f46a68b8 60 for (elt of document.querySelectorAll("main > div")) {
b4ae3ff6
BA
61 if (elt.id != element)
62 elt.style.display = "none";
63 else
64 elt.style.display = "block";
41534b92 65 }
a77150a1 66 if (element == "boardContainer") {
8022d544
BA
67 // Avoid smartphone scrolling effects (TODO?)
68 document.querySelector("html").style.overflow = "hidden";
69 document.body.style.overflow = "hidden";
70 }
71 else {
72 document.querySelector("html").style.overflow = "visible";
73 document.body.style.overflow = "visible";
f46a68b8 74 // Workaround "superposed texts" effect:
b4ae3ff6
BA
75 if (element == "newGame")
76 setActive(false);
86f3c2cd 77 }
41534b92
BA
78}
79
80let seek_vname;
81function seekGame() {
82 seek_vname = $.getElementById("selectVariant").value;
f46a68b8
BA
83 if (send("seekgame",
84 {vname: seek_vname, name: localStorage.getItem("name")})
85 ) {
86 toggleVisible("pendingSeek");
87 }
41534b92
BA
88}
89function cancelSeek() {
b4ae3ff6
BA
90 if (send("cancelseek", {vname: seek_vname}))
91 toggleVisible("newGame");
41534b92
BA
92}
93
32f57b42
BA
94function sendRematch(random) {
95 if (send("rematch", {gid: gid, random: !!random}))
96 toggleVisible("pendingRematch");
41534b92
BA
97}
98function cancelRematch() {
b4ae3ff6
BA
99 if (send("norematch", {gid: gid}))
100 toggleVisible("newGame");
41534b92
BA
101}
102
103// Play with a friend (or not ^^)
104function showNewGameForm() {
105 const vname = $.getElementById("selectVariant").value;
b4ae3ff6
BA
106 if (vname == "_random")
107 alert("Select a variant first");
41534b92
BA
108 else {
109 $.getElementById("gameLink").innerHTML = "";
110 $.getElementById("selectColor").selectedIndex = 0;
111 toggleVisible("newGameForm");
112 import(`/variants/${vname}/class.js`).then(module => {
cc2c7183 113 window.V = module.default;
b4ae3ff6
BA
114 for (const [k, v] of Object.entries(V.Aliases))
115 window[k] = v;
cc2c7183 116 prepareOptions();
41534b92
BA
117 });
118 }
119}
f46a68b8
BA
120function backToNormalSeek() {
121 toggleVisible("newGame");
122}
41534b92 123
f46a68b8
BA
124function toggleStyle(event, obj) {
125 const word = obj.innerHTML;
41534b92 126 options[word] = !options[word];
f46a68b8 127 event.target.classList.toggle("highlight-word");
41534b92
BA
128}
129
130let options;
cc2c7183 131function prepareOptions() {
41534b92 132 options = {};
d621e620
BA
133 let optHtml = "";
134 if (V.Options.select) {
135 optHtml += V.Options.select.map(select => { return `
86f3c2cd
BA
136 <div class="option-select">
137 <label for="var_${select.variable}">${select.label}</label>
138 <div class="select">
535c464b 139 <select id="var_${select.variable}">` +
86f3c2cd
BA
140 select.options.map(option => { return `
141 <option
142 value="${option.value}"
143 ${option.value == select.defaut ? " selected" : ""}
144 >
145 ${option.label}
146 </option>`;
147 }).join("") + `
148 </select>
149 <span class="focus"></span>
150 </div>
151 </div>`;
d621e620
BA
152 }).join("");
153 }
d621e620
BA
154 if (V.Options.input) {
155 optHtml += V.Options.input.map(input => { return `
156 <div class="option-input">
157 <label class="input">
158 <input id="var_${input.variable}"
159 type="${input.type}"
535c464b
BA
160 ${input.type == "checkbox" && input.defaut
161 ? "checked"
162 : 'value="' + input.defaut + '"'}
163 />
d621e620
BA
164 <span class="spacer"></span>
165 <span>${input.label}</span>
166 </label>
167 </div>`;
168 }).join("");
169 }
170 if (V.Options.styles) {
86f3c2cd
BA
171 optHtml += '<div class="words">';
172 let i = 0;
cc2c7183 173 const stylesLength = V.Options.styles.length;
86f3c2cd
BA
174 while (i < stylesLength) {
175 optHtml += '<div class="row">';
176 for (let j=i; j<i+4; j++) {
b4ae3ff6
BA
177 if (j == stylesLength)
178 break;
cc2c7183 179 const style = V.Options.styles[j];
f46a68b8 180 optHtml += `<span onClick="toggleStyle(event, this)">${style}</span>`;
86f3c2cd
BA
181 }
182 optHtml += "</div>";
183 i += 4;
41534b92 184 }
86f3c2cd 185 optHtml += "</div>";
41534b92 186 }
41534b92
BA
187 $.getElementById("gameOptions").innerHTML = optHtml;
188}
189
190function getGameLink() {
191 const vname = $.getElementById("selectVariant").value;
192 const color = $.getElementById("selectColor").value;
86f3c2cd 193 for (const select of $.querySelectorAll("#gameOptions select")) {
535c464b
BA
194 const value = parseInt(select.value, 10) || select.value;
195 options[ select.id.split("_")[1] ] = value;
cc2c7183 196 }
535c464b
BA
197 for (const input of $.querySelectorAll("#gameOptions input")) {
198 const variable = input.id.split("_")[1];
199 if (input.type == "number")
200 options[variable] = parseInt(input.value, 10); //TODO: real numbers?
201 else if (input.type == "checkbox")
202 options[variable] = input.checked;
41534b92 203 }
41534b92
BA
204 send("creategame", {
205 vname: vname,
f46a68b8 206 player: {sid: sid, name: localStorage.getItem("name"), color: color},
41534b92
BA
207 options: options
208 });
209}
210
f46a68b8 211function fillGameInfos(gameInfos, oppIndex) {
41534b92
BA
212 fetch(`/variants/${gameInfos.vname}/rules.html`)
213 .then(res => res.text())
214 .then(txt => {
215 let htmlContent = `
86f3c2cd
BA
216 <div class="players-info">
217 <p>
218 <span class="bold">${gameInfos.vdisp}</span>
219 <span>vs. ${gameInfos.players[oppIndex].name}</span>
220 </p>
221 </div>`;
222 const options = Object.entries(gameInfos.options);
223 if (options.length > 0) {
224 htmlContent += '<div class="options-info">';
225 let i = 0;
226 while (i < options.length) {
227 htmlContent += '<div class="row">';
228 for (let j=i; j<i+4; j++) {
b4ae3ff6
BA
229 if (j == options.length)
230 break;
86f3c2cd 231 const opt = options[j];
b4ae3ff6
BA
232 if (!opt[1])
233 continue;
86f3c2cd
BA
234 htmlContent +=
235 '<span class="option">' +
236 (opt[1] === true ? opt[0] : `${opt[0]}:${opt[1]}`) + " " +
f46a68b8 237 "</span>";
86f3c2cd
BA
238 }
239 htmlContent += "</div>";
240 i += 4;
241 }
242 htmlContent += "</div>";
243 }
41534b92 244 htmlContent += `
86f3c2cd
BA
245 <div class="rules">${txt}</div>
246 <div class="btn-wrap">
247 <button onClick="toggleGameInfos()">Back to game</button>
248 </div>`;
41534b92
BA
249 $.getElementById("gameInfos").innerHTML = htmlContent;
250 });
f46a68b8 251}
41534b92
BA
252
253////////////////
254// Communication
255
f46a68b8 256let socket, gid, recoAttempt = 0;
41534b92 257const autoReconnectDelay = () => {
f46a68b8 258 return [100, 200, 500, 1000, 3000, 10000, 30000][Math.min(recoAttempt, 6)];
41534b92
BA
259};
260
f46a68b8
BA
261function send(code, data, opts) {
262 opts = opts || {};
263 const trySend = () => {
264 if (socket.readyState == 1) {
265 socket.send(JSON.stringify(Object.assign({code: code}, data)));
b4ae3ff6
BA
266 if (opts.success)
267 opts.success();
f46a68b8
BA
268 return true;
269 }
270 return false;
271 };
272 const firstTry = trySend();
273 if (!firstTry) {
274 if (opts.retry) {
275 // Retry for a few seconds (sending move)
276 let sendAttempt = 1;
277 const retryLoop = setInterval(
278 () => {
b4ae3ff6
BA
279 if (trySend() || ++sendAttempt >= 3)
280 clearInterval(retryLoop);
281 if (sendAttempt >= 3 && opts.error)
282 opts.error();
f46a68b8
BA
283 },
284 1000
285 );
286 }
b4ae3ff6
BA
287 else if (opts.error)
288 opts.error();
f46a68b8
BA
289 }
290 return firstTry;
291}
292
293function copyClipboard(msg) {
294 navigator.clipboard.writeText(msg);
295}
41534b92
BA
296function getWhatsApp(msg) {
297 return `https://api.whatsapp.com/send?text=${encodeURIComponent(msg)}`;
298}
299
300const tryResumeGame = () => {
f46a68b8 301 recoAttempt = 0;
41534b92
BA
302 // If a game is found, resume it:
303 if (localStorage.getItem("gid")) {
304 gid = localStorage.getItem("gid");
f46a68b8
BA
305 send("getgame",
306 {gid: gid},
307 {
308 retry: true,
309 error: () => alert("Cannot load game: no connection")
310 });
41534b92
BA
311 }
312 else {
313 // If URL indicates "play with a friend", start game:
314 const hashIdx = document.URL.indexOf('#');
315 if (hashIdx >= 0) {
316 const urlParts = $.URL.split('#');
317 gid = urlParts[1];
41534b92 318 localStorage.setItem("gid", gid);
f46a68b8
BA
319 history.replaceState(null, '', urlParts[0]); //hide game ID
320 send("joingame",
321 {gid: gid, name: localStorage.getItem("name")},
322 {
323 retry: true,
324 error: () => alert("Cannot load game: no connection")
325 });
41534b92
BA
326 }
327 }
328};
329
330const messageCenter = (msg) => {
331 const obj = JSON.parse(msg.data);
332 switch (obj.code) {
333 // Start new game:
334 case "gamestart": {
b4ae3ff6
BA
335 if (document.hidden)
336 notifyMe("game");
41534b92
BA
337 gid = obj.gid;
338 initializeGame(obj);
339 break;
340 }
341 // Game vs. friend just created on server: share link now
342 case "gamecreated": {
343 const link = `${Params.http_server}/#${obj.gid}`;
344 $.getElementById("gameLink").innerHTML = `
345 <p>
346 <a href="${getWhatsApp(link)}">WhatsApp</a>
347 /
f46a68b8 348 <span onClick="copyClipboard('${link}')">ToClipboard</span>
41534b92
BA
349 </p>
350 <p>${link}</p>
351 `;
352 break;
353 }
354 // Game vs. friend joined after 1 minute (try again!)
355 case "jointoolate":
356 alert("Game no longer available");
357 break;
358 // Get infos of a running game (already launched)
359 case "gameinfo":
360 initializeGame(obj);
361 break;
362 // Tried to resume a game which is now gone:
363 case "nogame":
364 localStorage.removeItem("gid");
365 break;
366 // Receive opponent's move:
367 case "newmove":
f46a68b8 368 // Basic check: was it really opponent's turn?
b4ae3ff6
BA
369 if (vr.turn == playerColor)
370 break;
371 if (document.hidden)
372 notifyMe("move");
41534b92
BA
373 vr.playReceivedMove(obj.moves, () => {
374 if (vr.getCurrentScore(obj.moves[obj.moves.length-1]) != "*") {
375 localStorage.removeItem("gid");
376 setTimeout( () => toggleVisible("gameStopped"), 2000 );
377 }
b4ae3ff6
BA
378 else
379 toggleTurnIndicator(true);
41534b92
BA
380 });
381 break;
382 // Opponent stopped game (draw, abort, resign...)
383 case "gameover":
384 toggleVisible("gameStopped");
385 localStorage.removeItem("gid");
386 break;
387 // Opponent cancelled rematch:
388 case "closerematch":
389 toggleVisible("newGame");
390 break;
391 }
392};
393
394const handleError = (err) => {
f46a68b8 395 if (err.code === "ECONNREFUSED") {
41534b92
BA
396 removeAllListeners();
397 alert("Server refused connection. Please reload page later");
398 }
399 socket.close();
400};
401
402const handleClose = () => {
403 setTimeout(() => {
404 removeAllListeners();
405 connectToWSS();
406 }, autoReconnectDelay());
407};
408
f46a68b8 409function removeAllListeners() {
41534b92
BA
410 socket.removeEventListener("open", tryResumeGame);
411 socket.removeEventListener("message", messageCenter);
412 socket.removeEventListener("error", handleError);
413 socket.removeEventListener("close", handleClose);
f46a68b8 414}
41534b92 415
f46a68b8 416function connectToWSS() {
41534b92
BA
417 socket =
418 new WebSocket(`${Params.socket_server}${Params.socket_path}?sid=${sid}`);
419 socket.addEventListener("open", tryResumeGame);
420 socket.addEventListener("message", messageCenter);
421 socket.addEventListener("error", handleError);
422 socket.addEventListener("close", handleClose);
f46a68b8
BA
423 recoAttempt++;
424}
41534b92
BA
425connectToWSS();
426
41534b92
BA
427///////////
428// Playing
429
430function toggleTurnIndicator(myTurn) {
3c61449b
BA
431 let indicator =
432 $.getElementById("boardContainer").querySelector(".chessboard");
b4ae3ff6
BA
433 if (myTurn)
434 indicator.style.outline = "thick solid green";
435 else
436 indicator.style.outline = "thick solid lightgrey";
41534b92
BA
437}
438
439function notifyMe(code) {
440 const doNotify = () => {
441 // NOTE: empty body (TODO?)
442 new Notification("New " + code, { vibrate: [200, 100, 200] });
443 new Audio("/assets/new_" + code + ".mp3").play();
444 }
b4ae3ff6
BA
445 if (Notification.permission === "granted")
446 doNotify();
f46a68b8 447 else if (Notification.permission !== "denied") {
016306e3 448 Notification.requestPermission().then(permission => {
b4ae3ff6
BA
449 if (permission === "granted")
450 doNotify();
41534b92
BA
451 });
452 }
453}
454
8a9f61ce 455let curMoves = [],
f46a68b8 456 lastFen;
8a9f61ce 457const afterPlay = (move) => {
f46a68b8
BA
458 const callbackAfterSend = () => {
459 curMoves = [];
460 const result = vr.getCurrentScore(move);
461 if (result != "*") {
462 setTimeout(() => {
463 toggleVisible("gameStopped");
464 send("gameover", {gid: gid});
465 }, 2000);
466 }
467 };
8a9f61ce 468 // Pack into one moves array, then send
f8b43ef7 469 curMoves.push(move);
21e8e712 470 if (vr.turn != playerColor) {
41534b92 471 toggleTurnIndicator(false);
f46a68b8
BA
472 send("newmove",
473 {gid: gid, moves: curMoves, fen: vr.getFen()},
474 {
475 retry: true,
476 success: callbackAfterSend,
477 error: () => alert("Move not sent: reload page")
478 });
41534b92
BA
479 }
480};
481
21e8e712 482let vr, playerColor;
41534b92
BA
483function initializeGame(obj) {
484 const options = obj.options || {};
485 import(`/variants/${obj.vname}/class.js`).then(module => {
cc2c7183 486 window.V = module.default;
b4ae3ff6
BA
487 for (const [k, v] of Object.entries(V.Aliases))
488 window[k] = v;
f46a68b8
BA
489 // Load CSS. Avoid loading twice the same stylesheet:
490 const allIds = [].slice.call($.styleSheets).map(s => s.id);
491 const newId = obj.vname + "_css";
492 if (!allIds.includes(newId)) {
493 $.getElementsByTagName("head")[0].insertAdjacentHTML(
494 "beforeend",
495 `<link id="${newId}" rel="stylesheet"
496 href="/variants/${obj.vname}/style.css"/>`);
497 }
21e8e712 498 playerColor = (sid == obj.players[0].sid ? "w" : "b");
41534b92
BA
499 // Init + remove potential extra DOM elements from a previous game:
500 document.getElementById("boardContainer").innerHTML = `
501 <div id="upLeftInfos"
502 onClick="toggleGameInfos()">
cc2c7183
BA
503 <svg version="1.1"
504 viewBox="0.5 0.5 100 100">
505 <g>
506 <path d="M50.5,0.5c-27.614,0-50,22.386-50,50c0,27.614,22.386,50,50,50s50-22.386,50-50C100.5,22.886,78.114,0.5,50.5,0.5z M60.5,85.5h-20v-40h20V85.5z M50.5,35.5c-5.523,0-10-4.477-10-10s4.477-10,10-10c5.522,0,10,4.477,10,10S56.022,35.5,50.5,35.5z"/>
507 </g>
508 </svg>
41534b92
BA
509 </div>
510 <div id="upRightStop"
511 onClick="confirmStopGame()">
cc2c7183
BA
512 <svg version="1.1"
513 viewBox="0 0 533.333 533.333">
514 <g>
515 <path d="M528.468,428.468c-0.002-0.002-0.004-0.004-0.006-0.005L366.667,266.666l161.795-161.797 c0.002-0.002,0.004-0.003,0.006-0.005c1.741-1.742,3.001-3.778,3.809-5.946c2.211-5.925,0.95-12.855-3.814-17.62l-76.431-76.43 c-4.765-4.763-11.694-6.024-17.619-3.812c-2.167,0.807-4.203,2.066-5.946,3.807c0,0.002-0.002,0.003-0.005,0.005L266.667,166.666 L104.87,4.869c-0.002-0.002-0.003-0.003-0.005-0.005c-1.743-1.74-3.778-3-5.945-3.807C92.993-1.156,86.065,0.105,81.3,4.869 L4.869,81.3c-4.764,4.765-6.024,11.694-3.813,17.619c0.808,2.167,2.067,4.205,3.808,5.946c0.002,0.001,0.003,0.003,0.005,0.005 l161.797,161.796L4.869,428.464c-0.001,0.002-0.003,0.003-0.004,0.005c-1.741,1.742-3,3.778-3.809,5.945 c-2.212,5.924-0.951,12.854,3.813,17.619L81.3,528.464c4.766,4.765,11.694,6.025,17.62,3.813c2.167-0.809,4.203-2.068,5.946-3.809 c0.001-0.002,0.003-0.003,0.005-0.005l161.796-161.797l161.795,161.797c0.003,0.001,0.005,0.003,0.007,0.004 c1.743,1.741,3.778,3.001,5.944,3.81c5.927,2.212,12.856,0.951,17.619-3.813l76.43-76.432c4.766-4.765,6.026-11.696,3.815-17.62 C531.469,432.246,530.209,430.21,528.468,428.468z"/>
516 </g>
517 </svg>
41534b92 518 </div>
c4e9bb92 519 <div class="chessboard"></div>`;
cc2c7183 520 vr = new V({
41534b92
BA
521 seed: obj.seed, //may be null if FEN already exists (running game)
522 fen: obj.fen,
3c61449b 523 element: "boardContainer",
21e8e712 524 color: playerColor,
41534b92
BA
525 afterPlay: afterPlay,
526 options: options
527 });
528 if (!obj.fen) {
f46a68b8
BA
529 // Game creation: both players set FEN, in case of one is offline
530 send("setfen", {gid: obj.gid, fen: vr.getFen()});
41534b92
BA
531 localStorage.setItem("gid", obj.gid);
532 }
533 const select = $.getElementById("selectVariant");
534 obj.vdisp = "";
535 for (let i=0; i<select.options.length; i++) {
536 if (select.options[i].value == obj.vname) {
537 obj.vdisp = select.options[i].text;
538 break;
539 }
540 }
21e8e712 541 fillGameInfos(obj, playerColor == "w" ? 1 : 0);
b4ae3ff6
BA
542 if (obj.randvar)
543 toggleVisible("gameInfos");
544 else
545 toggleVisible("boardContainer");
21e8e712 546 toggleTurnIndicator(vr.turn == playerColor);
41534b92
BA
547 });
548}
549
550function confirmStopGame() {
f46a68b8 551 if (confirm("Stop game?") && send("gameover", {gid: gid, relay: true})) {
41534b92
BA
552 localStorage.removeItem("gid");
553 toggleVisible("gameStopped");
554 }
555}
556
557function toggleGameInfos() {
558 if ($.getElementById("gameInfos").style.display == "none")
559 toggleVisible("gameInfos");
b4ae3ff6
BA
560 else
561 toggleVisible("boardContainer");
41534b92
BA
562}
563
564$.body.addEventListener("keydown", (e) => {
b4ae3ff6
BA
565 if (!localStorage.getItem("gid"))
566 return;
567 if (e.keyCode == 27)
568 confirmStopGame();
41534b92
BA
569 else if (e.keyCode == 32) {
570 e.preventDefault();
571 toggleGameInfos();
572 }
573});