09d7815ca68518be2b8b5c944b76682ca4214fd3
[xogo.git] / app.js
1 let $ = document; //shortcut
2
3 ///////////////////
4 // Initialisations
5
6 // https://stackoverflow.com/a/27747377/12660887
7 function generateId (len) {
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('');
12 }
13
14 // Populate variants dropdown list
15 let dropdown = $.getElementById("selectVariant");
16 dropdown[0] = new Option("? ? ?", "_random", true, true);
17 dropdown[0].title = "Random variant";
18 for (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
26 if (!localStorage.getItem("sid"))
27 localStorage.setItem("sid", generateId(8));
28 if (!localStorage.getItem("name"))
29 localStorage.setItem("name", "@non" + generateId(4));
30 const sid = localStorage.getItem("sid");
31 $.getElementById("myName").value = localStorage.getItem("name");
32
33 // "Material" input field name
34 let inputName = document.getElementById("myName");
35 let formField = document.getElementById("ng-name");
36 const setActive = (active) => {
37 if (active)
38 formField.classList.add("form-field--is-active");
39 else {
40 formField.classList.remove("form-field--is-active");
41 inputName.value == ''
42 ? formField.classList.remove("form-field--is-filled")
43 : formField.classList.add("form-field--is-filled");
44 }
45 };
46 setActive(true);
47 inputName.onblur = () => setActive(false);
48 inputName.onfocus = () => setActive(true);
49
50 /////////
51 // Utils
52
53 function setName() {
54 // 'onChange' event on name input text field [HTML]
55 localStorage.setItem("name", $.getElementById("myName").value);
56 }
57
58 // Turn a "tab" on, and "close" all others
59 function toggleVisible(element) {
60 for (elt of document.querySelectorAll("main > div")) {
61 if (elt.id != element)
62 elt.style.display = "none";
63 else
64 elt.style.display = "block";
65 }
66 if (element == "boardContainer") {
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";
74 // Workaround "superposed texts" effect:
75 if (element == "newGame")
76 setActive(false);
77 }
78 }
79
80 let seek_vname;
81 function seekGame() {
82 seek_vname = $.getElementById("selectVariant").value;
83 if (send("seekgame",
84 {vname: seek_vname, name: localStorage.getItem("name")})
85 ) {
86 toggleVisible("pendingSeek");
87 }
88 }
89 function cancelSeek() {
90 if (send("cancelseek", {vname: seek_vname}))
91 toggleVisible("newGame");
92 }
93
94 function sendRematch(random) {
95 if (send("rematch", {gid: gid, random: !!random}))
96 toggleVisible("pendingRematch");
97 }
98 function cancelRematch() {
99 if (send("norematch", {gid: gid}))
100 toggleVisible("newGame");
101 }
102
103 // Play with a friend (or not ^^)
104 function showNewGameForm() {
105 const vname = $.getElementById("selectVariant").value;
106 if (vname == "_random")
107 alert("Select a variant first");
108 else {
109 $.getElementById("gameLink").innerHTML = "";
110 $.getElementById("selectColor").selectedIndex = 0;
111 toggleVisible("newGameForm");
112 import(`/variants/${vname}/class.js`).then(module => {
113 window.V = module.default;
114 for (const [k, v] of Object.entries(V.Aliases))
115 window[k] = v;
116 prepareOptions();
117 });
118 }
119 }
120 function backToNormalSeek() {
121 toggleVisible("newGame");
122 }
123
124 function toggleStyle(event, obj) {
125 const word = obj.innerHTML;
126 options[word] = !options[word];
127 event.target.classList.toggle("highlight-word");
128 }
129
130 let options;
131 function prepareOptions() {
132 options = {};
133 let optHtml = "";
134 if (V.Options.select) {
135 optHtml += V.Options.select.map(select => { return `
136 <div class="option-select">
137 <label for="var_${select.variable}">${select.label}</label>
138 <div class="select">
139 <select id="var_${select.variable}">` +
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>`;
152 }).join("");
153 }
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}"
160 ${input.type == "checkbox" && input.defaut
161 ? "checked"
162 : 'value="' + input.defaut + '"'}
163 />
164 <span class="spacer"></span>
165 <span>${input.label}</span>
166 </label>
167 </div>`;
168 }).join("");
169 }
170 if (V.Options.styles) {
171 optHtml += '<div class="words">';
172 let i = 0;
173 const stylesLength = V.Options.styles.length;
174 while (i < stylesLength) {
175 optHtml += '<div class="row">';
176 for (let j=i; j<i+4; j++) {
177 if (j == stylesLength)
178 break;
179 const style = V.Options.styles[j];
180 optHtml += `<span onClick="toggleStyle(event, this)">${style}</span>`;
181 }
182 optHtml += "</div>";
183 i += 4;
184 }
185 optHtml += "</div>";
186 }
187 $.getElementById("gameOptions").innerHTML = optHtml;
188 }
189
190 function getGameLink() {
191 const vname = $.getElementById("selectVariant").value;
192 const color = $.getElementById("selectColor").value;
193 for (const select of $.querySelectorAll("#gameOptions select")) {
194 const value = parseInt(select.value, 10) || select.value;
195 options[ select.id.split("_")[1] ] = value;
196 }
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;
203 }
204 send("creategame", {
205 vname: vname,
206 player: {sid: sid, name: localStorage.getItem("name"), color: color},
207 options: options
208 });
209 }
210
211 function fillGameInfos(gameInfos, oppIndex) {
212 fetch(`/variants/${gameInfos.vname}/rules.html`)
213 .then(res => res.text())
214 .then(txt => {
215 let htmlContent = `
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++) {
229 if (j == options.length)
230 break;
231 const opt = options[j];
232 if (!opt[1])
233 continue;
234 htmlContent +=
235 '<span class="option">' +
236 (opt[1] === true ? opt[0] : `${opt[0]}:${opt[1]}`) + " " +
237 "</span>";
238 }
239 htmlContent += "</div>";
240 i += 4;
241 }
242 htmlContent += "</div>";
243 }
244 htmlContent += `
245 <div class="rules">${txt}</div>
246 <div class="btn-wrap">
247 <button onClick="toggleGameInfos()">Back to game</button>
248 </div>`;
249 $.getElementById("gameInfos").innerHTML = htmlContent;
250 });
251 }
252
253 ////////////////
254 // Communication
255
256 let socket, gid, recoAttempt = 0;
257 const autoReconnectDelay = () => {
258 return [100, 200, 500, 1000, 3000, 10000, 30000][Math.min(recoAttempt, 6)];
259 };
260
261 function 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)));
266 if (opts.success)
267 opts.success();
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 () => {
279 if (trySend() || ++sendAttempt >= 3)
280 clearInterval(retryLoop);
281 if (sendAttempt >= 3 && opts.error)
282 opts.error();
283 },
284 1000
285 );
286 }
287 else if (opts.error)
288 opts.error();
289 }
290 return firstTry;
291 }
292
293 function copyClipboard(msg) {
294 navigator.clipboard.writeText(msg);
295 }
296 function getWhatsApp(msg) {
297 return `https://api.whatsapp.com/send?text=${encodeURIComponent(msg)}`;
298 }
299
300 const tryResumeGame = () => {
301 recoAttempt = 0;
302 // If a game is found, resume it:
303 if (localStorage.getItem("gid")) {
304 gid = localStorage.getItem("gid");
305 send("getgame",
306 {gid: gid},
307 {
308 retry: true,
309 error: () => alert("Cannot load game: no connection")
310 });
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];
318 localStorage.setItem("gid", gid);
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 });
326 }
327 }
328 };
329
330 const messageCenter = (msg) => {
331 const obj = JSON.parse(msg.data);
332 switch (obj.code) {
333 // Start new game:
334 case "gamestart": {
335 if (document.hidden)
336 notifyMe("game");
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 /
348 <span onClick="copyClipboard('${link}')">ToClipboard</span>
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":
368 // Basic check: was it really opponent's turn?
369 if (vr.turn == playerColor)
370 break;
371 if (document.hidden)
372 notifyMe("move");
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 }
378 else
379 toggleTurnIndicator(true);
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
394 const handleError = (err) => {
395 if (err.code === "ECONNREFUSED") {
396 removeAllListeners();
397 alert("Server refused connection. Please reload page later");
398 }
399 socket.close();
400 };
401
402 const handleClose = () => {
403 setTimeout(() => {
404 removeAllListeners();
405 connectToWSS();
406 }, autoReconnectDelay());
407 };
408
409 function removeAllListeners() {
410 socket.removeEventListener("open", tryResumeGame);
411 socket.removeEventListener("message", messageCenter);
412 socket.removeEventListener("error", handleError);
413 socket.removeEventListener("close", handleClose);
414 }
415
416 function connectToWSS() {
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);
423 recoAttempt++;
424 }
425 connectToWSS();
426
427 ///////////
428 // Playing
429
430 function toggleTurnIndicator(myTurn) {
431 let indicator =
432 $.getElementById("boardContainer").querySelector(".chessboard");
433 if (myTurn)
434 indicator.style.outline = "thick solid green";
435 else
436 indicator.style.outline = "thick solid lightgrey";
437 }
438
439 function 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 }
445 if (Notification.permission === "granted")
446 doNotify();
447 else if (Notification.permission !== "denied") {
448 Notification.requestPermission().then(permission => {
449 if (permission === "granted")
450 doNotify();
451 });
452 }
453 }
454
455 let curMoves = [],
456 lastFen;
457 const afterPlay = (move_s) => {
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 };
468 // Pack into one moves array, then send
469 if (Array.isArray(move_s))
470 // Array of simple moves (e.g. Chakart)
471 Array.prototype.push.apply(curMoves, move_s);
472 else
473 // Usual case
474 curMoves.push(move_s);
475 if (vr.turn != playerColor) {
476 toggleTurnIndicator(false);
477 send("newmove",
478 {gid: gid, moves: curMoves, fen: vr.getFen()},
479 {
480 retry: true,
481 success: callbackAfterSend,
482 error: () => alert("Move not sent: reload page")
483 });
484 }
485 };
486
487 let vr, playerColor;
488 function initializeGame(obj) {
489 const options = obj.options || {};
490 import(`/variants/${obj.vname}/class.js`).then(module => {
491 window.V = module.default;
492 for (const [k, v] of Object.entries(V.Aliases))
493 window[k] = v;
494 // Load CSS. Avoid loading twice the same stylesheet:
495 const allIds = [].slice.call($.styleSheets).map(s => s.id);
496 const newId = obj.vname + "_css";
497 if (!allIds.includes(newId)) {
498 $.getElementsByTagName("head")[0].insertAdjacentHTML(
499 "beforeend",
500 `<link id="${newId}" rel="stylesheet"
501 href="/variants/${obj.vname}/style.css"/>`);
502 }
503 playerColor = (sid == obj.players[0].sid ? "w" : "b");
504 // Init + remove potential extra DOM elements from a previous game:
505 document.getElementById("boardContainer").innerHTML = `
506 <div id="upLeftInfos"
507 onClick="toggleGameInfos()">
508 <svg version="1.1"
509 viewBox="0.5 0.5 100 100">
510 <g>
511 <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"/>
512 </g>
513 </svg>
514 </div>
515 <div id="upRightStop"
516 onClick="confirmStopGame()">
517 <svg version="1.1"
518 viewBox="0 0 533.333 533.333">
519 <g>
520 <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"/>
521 </g>
522 </svg>
523 </div>
524 <div class="chessboard"></div>`;
525 vr = new V({
526 seed: obj.seed, //may be null if FEN already exists (running game)
527 fen: obj.fen,
528 element: "boardContainer",
529 color: playerColor,
530 afterPlay: afterPlay,
531 options: options
532 });
533 if (!obj.fen) {
534 // Game creation: both players set FEN, in case of one is offline
535 send("setfen", {gid: obj.gid, fen: vr.getFen()});
536 localStorage.setItem("gid", obj.gid);
537 }
538 const select = $.getElementById("selectVariant");
539 obj.vdisp = "";
540 for (let i=0; i<select.options.length; i++) {
541 if (select.options[i].value == obj.vname) {
542 obj.vdisp = select.options[i].text;
543 break;
544 }
545 }
546 fillGameInfos(obj, playerColor == "w" ? 1 : 0);
547 if (obj.randvar)
548 toggleVisible("gameInfos");
549 else
550 toggleVisible("boardContainer");
551 toggleTurnIndicator(vr.turn == playerColor);
552 });
553 }
554
555 function confirmStopGame() {
556 if (confirm("Stop game?") && send("gameover", {gid: gid, relay: true})) {
557 localStorage.removeItem("gid");
558 toggleVisible("gameStopped");
559 }
560 }
561
562 function toggleGameInfos() {
563 if ($.getElementById("gameInfos").style.display == "none")
564 toggleVisible("gameInfos");
565 else
566 toggleVisible("boardContainer");
567 }
568
569 $.body.addEventListener("keydown", (e) => {
570 if (!localStorage.getItem("gid"))
571 return;
572 if (e.keyCode == 27)
573 confirmStopGame();
574 else if (e.keyCode == 32) {
575 e.preventDefault();
576 toggleGameInfos();
577 }
578 });