Fix last fix :)
[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) => {
37 if (active) formField.classList.add("form-field--is-active");
38 else {
39 formField.classList.remove("form-field--is-active");
f46a68b8
BA
40 inputName.value == ''
41 ? formField.classList.remove("form-field--is-filled")
42 : formField.classList.add("form-field--is-filled");
86f3c2cd
BA
43 }
44};
f46a68b8 45setActive(true);
86f3c2cd
BA
46inputName.onblur = () => setActive(false);
47inputName.onfocus = () => setActive(true);
86f3c2cd 48
41534b92
BA
49/////////
50// Utils
51
52function setName() {
f46a68b8 53 // 'onChange' event on name input text field [HTML]
41534b92
BA
54 localStorage.setItem("name", $.getElementById("myName").value);
55}
56
57// Turn a "tab" on, and "close" all others
58function toggleVisible(element) {
f46a68b8 59 for (elt of document.querySelectorAll("main > div")) {
41534b92
BA
60 if (elt.id != element) elt.style.display = "none";
61 else elt.style.display = "block";
62 }
a77150a1 63 if (element == "boardContainer") {
8022d544
BA
64 // Avoid smartphone scrolling effects (TODO?)
65 document.querySelector("html").style.overflow = "hidden";
66 document.body.style.overflow = "hidden";
67 }
68 else {
69 document.querySelector("html").style.overflow = "visible";
70 document.body.style.overflow = "visible";
f46a68b8
BA
71 // Workaround "superposed texts" effect:
72 if (element == "newGame") setActive(false);
86f3c2cd 73 }
41534b92
BA
74}
75
76let seek_vname;
77function seekGame() {
78 seek_vname = $.getElementById("selectVariant").value;
f46a68b8
BA
79 if (send("seekgame",
80 {vname: seek_vname, name: localStorage.getItem("name")})
81 ) {
82 toggleVisible("pendingSeek");
83 }
41534b92
BA
84}
85function cancelSeek() {
f46a68b8 86 if (send("cancelseek", {vname: seek_vname})) toggleVisible("newGame");
41534b92
BA
87}
88
89function sendRematch() {
f46a68b8 90 if (send("rematch", {gid: gid})) toggleVisible("pendingRematch");
41534b92
BA
91}
92function cancelRematch() {
f46a68b8 93 if (send("norematch", {gid: gid})) toggleVisible("newGame");
41534b92
BA
94}
95
96// Play with a friend (or not ^^)
97function showNewGameForm() {
98 const vname = $.getElementById("selectVariant").value;
99 if (vname == "_random") alert("Select a variant first");
100 else {
101 $.getElementById("gameLink").innerHTML = "";
102 $.getElementById("selectColor").selectedIndex = 0;
103 toggleVisible("newGameForm");
104 import(`/variants/${vname}/class.js`).then(module => {
cc2c7183 105 window.V = module.default;
3caec36f 106 for (const [k, v] of Object.entries(V.Aliases)) window[k] = v;
cc2c7183 107 prepareOptions();
41534b92
BA
108 });
109 }
110}
f46a68b8
BA
111function backToNormalSeek() {
112 toggleVisible("newGame");
113}
41534b92 114
f46a68b8
BA
115function toggleStyle(event, obj) {
116 const word = obj.innerHTML;
41534b92 117 options[word] = !options[word];
f46a68b8 118 event.target.classList.toggle("highlight-word");
41534b92
BA
119}
120
121let options;
cc2c7183 122function prepareOptions() {
41534b92 123 options = {};
cc2c7183 124 let optHtml = V.Options.select.map(select => { return `
86f3c2cd
BA
125 <div class="option-select">
126 <label for="var_${select.variable}">${select.label}</label>
127 <div class="select">
128 <select id="var_${select.variable}" data-numeric="1">` +
129 select.options.map(option => { return `
130 <option
131 value="${option.value}"
132 ${option.value == select.defaut ? " selected" : ""}
133 >
134 ${option.label}
135 </option>`;
136 }).join("") + `
137 </select>
138 <span class="focus"></span>
139 </div>
140 </div>`;
141 }).join("");
cc2c7183 142 optHtml += V.Options.check.map(check => {
86f3c2cd
BA
143 return `
144 <div class="option-check">
145 <label class="checkbox">
146 <input id="var_${check.variable}"
147 type="checkbox"${check.defaut ? " checked" : ""}/>
148 <span class="spacer"></span>
149 <span>${check.label}</span>
150 </label>
151 </div>`;
152 }).join("");
cc2c7183 153 if (V.Options.styles.length >= 1) {
86f3c2cd
BA
154 optHtml += '<div class="words">';
155 let i = 0;
cc2c7183 156 const stylesLength = V.Options.styles.length;
86f3c2cd
BA
157 while (i < stylesLength) {
158 optHtml += '<div class="row">';
159 for (let j=i; j<i+4; j++) {
160 if (j == stylesLength) break;
cc2c7183 161 const style = V.Options.styles[j];
f46a68b8 162 optHtml += `<span onClick="toggleStyle(event, this)">${style}</span>`;
86f3c2cd
BA
163 }
164 optHtml += "</div>";
165 i += 4;
41534b92 166 }
86f3c2cd 167 optHtml += "</div>";
41534b92 168 }
41534b92
BA
169 $.getElementById("gameOptions").innerHTML = optHtml;
170}
171
172function getGameLink() {
173 const vname = $.getElementById("selectVariant").value;
174 const color = $.getElementById("selectColor").value;
86f3c2cd 175 for (const select of $.querySelectorAll("#gameOptions select")) {
41534b92
BA
176 let value = select.value;
177 if (select.attributes["data-numeric"]) value = parseInt(value, 10);
cc2c7183
BA
178 if (value) options[ select.id.split("_")[1] ] = value;
179 }
180 for (const check of $.querySelectorAll("#gameOptions input")) {
181 if (check.checked) options[ check.id.split("_")[1] ] = check.checked;
41534b92 182 }
41534b92
BA
183 send("creategame", {
184 vname: vname,
f46a68b8 185 player: {sid: sid, name: localStorage.getItem("name"), color: color},
41534b92
BA
186 options: options
187 });
188}
189
f46a68b8 190function fillGameInfos(gameInfos, oppIndex) {
41534b92
BA
191 fetch(`/variants/${gameInfos.vname}/rules.html`)
192 .then(res => res.text())
193 .then(txt => {
194 let htmlContent = `
86f3c2cd
BA
195 <div class="players-info">
196 <p>
197 <span class="bold">${gameInfos.vdisp}</span>
198 <span>vs. ${gameInfos.players[oppIndex].name}</span>
199 </p>
200 </div>`;
201 const options = Object.entries(gameInfos.options);
202 if (options.length > 0) {
203 htmlContent += '<div class="options-info">';
204 let i = 0;
205 while (i < options.length) {
206 htmlContent += '<div class="row">';
207 for (let j=i; j<i+4; j++) {
208 if (j == options.length) break;
209 const opt = options[j];
f8b43ef7 210 if (!opt[1]) continue;
86f3c2cd
BA
211 htmlContent +=
212 '<span class="option">' +
213 (opt[1] === true ? opt[0] : `${opt[0]}:${opt[1]}`) + " " +
f46a68b8 214 "</span>";
86f3c2cd
BA
215 }
216 htmlContent += "</div>";
217 i += 4;
218 }
219 htmlContent += "</div>";
220 }
41534b92 221 htmlContent += `
86f3c2cd
BA
222 <div class="rules">${txt}</div>
223 <div class="btn-wrap">
224 <button onClick="toggleGameInfos()">Back to game</button>
225 </div>`;
41534b92
BA
226 $.getElementById("gameInfos").innerHTML = htmlContent;
227 });
f46a68b8 228}
41534b92
BA
229
230////////////////
231// Communication
232
f46a68b8 233let socket, gid, recoAttempt = 0;
41534b92 234const autoReconnectDelay = () => {
f46a68b8 235 return [100, 200, 500, 1000, 3000, 10000, 30000][Math.min(recoAttempt, 6)];
41534b92
BA
236};
237
f46a68b8
BA
238function send(code, data, opts) {
239 opts = opts || {};
240 const trySend = () => {
241 if (socket.readyState == 1) {
242 socket.send(JSON.stringify(Object.assign({code: code}, data)));
243 if (opts.success) opts.success();
244 return true;
245 }
246 return false;
247 };
248 const firstTry = trySend();
249 if (!firstTry) {
250 if (opts.retry) {
251 // Retry for a few seconds (sending move)
252 let sendAttempt = 1;
253 const retryLoop = setInterval(
254 () => {
255 if (trySend() || ++sendAttempt >= 3) clearInterval(retryLoop);
256 if (sendAttempt >= 3 && opts.error) opts.error();
257 },
258 1000
259 );
260 }
261 else if (opt.error) opts.error();
262 }
263 return firstTry;
264}
265
266function copyClipboard(msg) {
267 navigator.clipboard.writeText(msg);
268}
41534b92
BA
269function getWhatsApp(msg) {
270 return `https://api.whatsapp.com/send?text=${encodeURIComponent(msg)}`;
271}
272
273const tryResumeGame = () => {
f46a68b8 274 recoAttempt = 0;
41534b92
BA
275 // If a game is found, resume it:
276 if (localStorage.getItem("gid")) {
277 gid = localStorage.getItem("gid");
f46a68b8
BA
278 send("getgame",
279 {gid: gid},
280 {
281 retry: true,
282 error: () => alert("Cannot load game: no connection")
283 });
41534b92
BA
284 }
285 else {
286 // If URL indicates "play with a friend", start game:
287 const hashIdx = document.URL.indexOf('#');
288 if (hashIdx >= 0) {
289 const urlParts = $.URL.split('#');
290 gid = urlParts[1];
41534b92 291 localStorage.setItem("gid", gid);
f46a68b8
BA
292 history.replaceState(null, '', urlParts[0]); //hide game ID
293 send("joingame",
294 {gid: gid, name: localStorage.getItem("name")},
295 {
296 retry: true,
297 error: () => alert("Cannot load game: no connection")
298 });
41534b92
BA
299 }
300 }
301};
302
303const messageCenter = (msg) => {
304 const obj = JSON.parse(msg.data);
305 switch (obj.code) {
306 // Start new game:
307 case "gamestart": {
016306e3 308 if (document.hidden) notifyMe("game");
41534b92
BA
309 gid = obj.gid;
310 initializeGame(obj);
311 break;
312 }
313 // Game vs. friend just created on server: share link now
314 case "gamecreated": {
315 const link = `${Params.http_server}/#${obj.gid}`;
316 $.getElementById("gameLink").innerHTML = `
317 <p>
318 <a href="${getWhatsApp(link)}">WhatsApp</a>
319 /
f46a68b8 320 <span onClick="copyClipboard('${link}')">ToClipboard</span>
41534b92
BA
321 </p>
322 <p>${link}</p>
323 `;
324 break;
325 }
326 // Game vs. friend joined after 1 minute (try again!)
327 case "jointoolate":
328 alert("Game no longer available");
329 break;
330 // Get infos of a running game (already launched)
331 case "gameinfo":
332 initializeGame(obj);
333 break;
334 // Tried to resume a game which is now gone:
335 case "nogame":
336 localStorage.removeItem("gid");
337 break;
338 // Receive opponent's move:
339 case "newmove":
f46a68b8
BA
340 // Basic check: was it really opponent's turn?
341 if (vr.turn == playerColor) break;
016306e3 342 if (document.hidden) notifyMe("move");
41534b92
BA
343 vr.playReceivedMove(obj.moves, () => {
344 if (vr.getCurrentScore(obj.moves[obj.moves.length-1]) != "*") {
345 localStorage.removeItem("gid");
346 setTimeout( () => toggleVisible("gameStopped"), 2000 );
347 }
348 else toggleTurnIndicator(true);
349 });
350 break;
351 // Opponent stopped game (draw, abort, resign...)
352 case "gameover":
353 toggleVisible("gameStopped");
354 localStorage.removeItem("gid");
355 break;
356 // Opponent cancelled rematch:
357 case "closerematch":
358 toggleVisible("newGame");
359 break;
360 }
361};
362
363const handleError = (err) => {
f46a68b8 364 if (err.code === "ECONNREFUSED") {
41534b92
BA
365 removeAllListeners();
366 alert("Server refused connection. Please reload page later");
367 }
368 socket.close();
369};
370
371const handleClose = () => {
372 setTimeout(() => {
373 removeAllListeners();
374 connectToWSS();
375 }, autoReconnectDelay());
376};
377
f46a68b8 378function removeAllListeners() {
41534b92
BA
379 socket.removeEventListener("open", tryResumeGame);
380 socket.removeEventListener("message", messageCenter);
381 socket.removeEventListener("error", handleError);
382 socket.removeEventListener("close", handleClose);
f46a68b8 383}
41534b92 384
f46a68b8 385function connectToWSS() {
41534b92
BA
386 socket =
387 new WebSocket(`${Params.socket_server}${Params.socket_path}?sid=${sid}`);
388 socket.addEventListener("open", tryResumeGame);
389 socket.addEventListener("message", messageCenter);
390 socket.addEventListener("error", handleError);
391 socket.addEventListener("close", handleClose);
f46a68b8
BA
392 recoAttempt++;
393}
41534b92
BA
394connectToWSS();
395
41534b92
BA
396///////////
397// Playing
398
399function toggleTurnIndicator(myTurn) {
400 let indicator = $.getElementById("chessboard");
401 if (myTurn) indicator.style.outline = "thick solid green";
402 else indicator.style.outline = "thick solid lightgrey";
403}
404
405function notifyMe(code) {
406 const doNotify = () => {
407 // NOTE: empty body (TODO?)
408 new Notification("New " + code, { vibrate: [200, 100, 200] });
409 new Audio("/assets/new_" + code + ".mp3").play();
410 }
f46a68b8
BA
411 if (Notification.permission === "granted") doNotify();
412 else if (Notification.permission !== "denied") {
016306e3 413 Notification.requestPermission().then(permission => {
f46a68b8 414 if (permission === "granted") doNotify();
41534b92
BA
415 });
416 }
417}
418
8a9f61ce 419let curMoves = [],
f46a68b8 420 lastFen;
8a9f61ce 421const afterPlay = (move) => {
f46a68b8
BA
422 const callbackAfterSend = () => {
423 curMoves = [];
424 const result = vr.getCurrentScore(move);
425 if (result != "*") {
426 setTimeout(() => {
427 toggleVisible("gameStopped");
428 send("gameover", {gid: gid});
429 }, 2000);
430 }
431 };
8a9f61ce 432 // Pack into one moves array, then send
f8b43ef7 433 curMoves.push(move);
21e8e712 434 if (vr.turn != playerColor) {
41534b92 435 toggleTurnIndicator(false);
f46a68b8
BA
436 send("newmove",
437 {gid: gid, moves: curMoves, fen: vr.getFen()},
438 {
439 retry: true,
440 success: callbackAfterSend,
441 error: () => alert("Move not sent: reload page")
442 });
41534b92
BA
443 }
444};
445
21e8e712 446let vr, playerColor;
41534b92
BA
447function initializeGame(obj) {
448 const options = obj.options || {};
449 import(`/variants/${obj.vname}/class.js`).then(module => {
cc2c7183 450 window.V = module.default;
3caec36f 451 for (const [k, v] of Object.entries(V.Aliases)) window[k] = v;
f46a68b8
BA
452 // Load CSS. Avoid loading twice the same stylesheet:
453 const allIds = [].slice.call($.styleSheets).map(s => s.id);
454 const newId = obj.vname + "_css";
455 if (!allIds.includes(newId)) {
456 $.getElementsByTagName("head")[0].insertAdjacentHTML(
457 "beforeend",
458 `<link id="${newId}" rel="stylesheet"
459 href="/variants/${obj.vname}/style.css"/>`);
460 }
21e8e712 461 playerColor = (sid == obj.players[0].sid ? "w" : "b");
41534b92
BA
462 // Init + remove potential extra DOM elements from a previous game:
463 document.getElementById("boardContainer").innerHTML = `
464 <div id="upLeftInfos"
465 onClick="toggleGameInfos()">
cc2c7183
BA
466 <svg version="1.1"
467 viewBox="0.5 0.5 100 100">
468 <g>
469 <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"/>
470 </g>
471 </svg>
41534b92
BA
472 </div>
473 <div id="upRightStop"
474 onClick="confirmStopGame()">
cc2c7183
BA
475 <svg version="1.1"
476 viewBox="0 0 533.333 533.333">
477 <g>
478 <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"/>
479 </g>
480 </svg>
41534b92
BA
481 </div>
482 <div class="resizeable" id="chessboard"></div>`;
cc2c7183 483 vr = new V({
41534b92
BA
484 seed: obj.seed, //may be null if FEN already exists (running game)
485 fen: obj.fen,
486 element: "chessboard",
21e8e712 487 color: playerColor,
41534b92
BA
488 afterPlay: afterPlay,
489 options: options
490 });
491 if (!obj.fen) {
f46a68b8
BA
492 // Game creation: both players set FEN, in case of one is offline
493 send("setfen", {gid: obj.gid, fen: vr.getFen()});
41534b92
BA
494 localStorage.setItem("gid", obj.gid);
495 }
496 const select = $.getElementById("selectVariant");
497 obj.vdisp = "";
498 for (let i=0; i<select.options.length; i++) {
499 if (select.options[i].value == obj.vname) {
500 obj.vdisp = select.options[i].text;
501 break;
502 }
503 }
21e8e712 504 fillGameInfos(obj, playerColor == "w" ? 1 : 0);
41534b92
BA
505 if (obj.randvar) toggleVisible("gameInfos");
506 else toggleVisible("boardContainer");
21e8e712 507 toggleTurnIndicator(vr.turn == playerColor);
41534b92
BA
508 });
509}
510
511function confirmStopGame() {
f46a68b8 512 if (confirm("Stop game?") && send("gameover", {gid: gid, relay: true})) {
41534b92
BA
513 localStorage.removeItem("gid");
514 toggleVisible("gameStopped");
515 }
516}
517
518function toggleGameInfos() {
519 if ($.getElementById("gameInfos").style.display == "none")
520 toggleVisible("gameInfos");
f46a68b8 521 else toggleVisible("boardContainer");
41534b92
BA
522}
523
524$.body.addEventListener("keydown", (e) => {
525 if (!localStorage.getItem("gid")) return;
526 if (e.keyCode == 27) confirmStopGame();
527 else if (e.keyCode == 32) {
528 e.preventDefault();
529 toggleGameInfos();
530 }
531});