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