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