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