Attempt to prevent 'lost moves'...
[xogo.git] / app.js
diff --git a/app.js b/app.js
index c553ce5..a46ceb3 100644 (file)
--- a/app.js
+++ b/app.js
@@ -30,6 +30,22 @@ if (!localStorage.getItem("name"))
 const sid = localStorage.getItem("sid");
 $.getElementById("myName").value = localStorage.getItem("name");
 
+// "Material" input field name
+let inputName = document.getElementById("myName");
+let formField = document.getElementById("ng-name");
+const setActive = (active) => {
+  if (active) formField.classList.add("form-field--is-active");
+  else {
+    formField.classList.remove("form-field--is-active");
+    inputName.value === "" ?
+      formField.classList.remove("form-field--is-filled") :
+       formField.classList.add("form-field--is-filled");
+  }
+};
+inputName.onblur = () => setActive(false);
+inputName.onfocus = () => setActive(true);
+inputName.focus();
+
 /////////
 // Utils
 
@@ -39,10 +55,24 @@ function setName() {
 
 // Turn a "tab" on, and "close" all others
 function toggleVisible(element) {
-  for (elt of document.querySelectorAll('body > div')) {
+  for (elt of document.querySelectorAll('main > div')) {
     if (elt.id != element) elt.style.display = "none";
     else elt.style.display = "block";
   }
+  if (element == "boardContainer") {
+    // Avoid smartphone scrolling effects (TODO?)
+    document.querySelector("html").style.overflow = "hidden";
+    document.body.style.overflow = "hidden";
+  }
+  else {
+    document.querySelector("html").style.overflow = "visible";
+    document.body.style.overflow = "visible";
+    if (element == "newGame") {
+      // Workaround "superposed texts" effect
+      inputName.focus();
+      inputName.blur();
+    }
+  }
 }
 
 let seek_vname;
@@ -74,8 +104,8 @@ function showNewGameForm() {
     $.getElementById("selectColor").selectedIndex = 0;
     toggleVisible("newGameForm");
     import(`/variants/${vname}/class.js`).then(module => {
-      const Rules = module.default;
-      prepareOptions(Rules);
+      window.V = module.default;
+      prepareOptions();
     });
   }
 }
@@ -87,50 +117,68 @@ function toggleStyle(e, word) {
 }
 
 let options;
-function prepareOptions(Rules) {
+function prepareOptions() {
   options = {};
-  let optHtml = "";
-  for (let select of Rules.Options.select) {
-    optHtml += `
-      <label for="var_${select.variable}">${select.label}</label>
-      <select id="var_${select.variable}" data-numeric="1">`;
-    for (option of select.options) {
-      const defaut = option.value == select.defaut;
-      optHtml += `<option value="${option.value}"`;
-      if (defaut) optHtml += 'selected="true"';
-      optHtml += `>${option.label}</option>`;
+  let optHtml = V.Options.select.map(select => { return `
+      <div class="option-select">
+        <label for="var_${select.variable}">${select.label}</label>
+        <div class="select">
+          <select id="var_${select.variable}" data-numeric="1">` +
+          select.options.map(option => { return `
+            <option
+              value="${option.value}"
+              ${option.value == select.defaut ? " selected" : ""}
+            >
+              ${option.label}
+            </option>`;
+          }).join("") + `
+          </select>
+          <span class="focus"></span>
+        </div>
+      </div>`;
+  }).join("");
+  optHtml += V.Options.check.map(check => {
+    return `
+      <div class="option-check">
+        <label class="checkbox">
+          <input id="var_${check.variable}"
+                 type="checkbox"${check.defaut ? " checked" : ""}/>
+          <span class="spacer"></span>
+          <span>${check.label}</span>
+        </label>
+      </div>`;
+  }).join("");
+  if (V.Options.styles.length >= 1) {
+    optHtml += '<div class="words">';
+    let i = 0;
+    const stylesLength = V.Options.styles.length;
+    while (i < stylesLength) {
+      optHtml += '<div class="row">';
+      for (let j=i; j<i+4; j++) {
+        if (j == stylesLength) break;
+        const style = V.Options.styles[j];
+        optHtml +=
+          `<span onClick="toggleStyle(event, '${style}')">${style}</span>`;
+      }
+      optHtml += "</div>";
+      i += 4;
     }
-    optHtml += '</select>';
+    optHtml += "</div>";
   }
-  for (let check of Rules.Options.check) {
-    optHtml += `
-      <label for="var_${check.variable}">${check.label}</label>
-      <input id="var_${check.variable}"
-             type="checkbox"`;
-    if (check.defaut) optHtml += 'checked="true"';
-    optHtml += '/>';
-  }
-  if (Rules.Options.styles.length >= 1) optHtml += "<p>";
-  for (let style of Rules.Options.styles) {
-    optHtml += `
-      <span class="word" onClick="toggleStyle(event, '${style}')">
-        ${style}
-      </span>`;
-  }
-  if (Rules.Options.styles.length >= 1) optHtml += "</p>";
   $.getElementById("gameOptions").innerHTML = optHtml;
 }
 
 function getGameLink() {
   const vname = $.getElementById("selectVariant").value;
   const color = $.getElementById("selectColor").value;
-  for (const select of $.querySelectorAll("#gameOptions select")) {
+  for (const select of $.querySelectorAll("#gameOptions select")) {
     let value = select.value;
     if (select.attributes["data-numeric"]) value = parseInt(value, 10);
-    options[ select.id.split("_")[1] ] = value;
+    if (value) options[ select.id.split("_")[1] ] = value;
+  }
+  for (const check of $.querySelectorAll("#gameOptions input")) {
+    if (check.checked) options[ check.id.split("_")[1] ] = check.checked;
   }
-  for (const check of $.querySelectorAll("#gameOptions > input"))
-    options[ check.id.split("_")[1] ] = check.checked;
   send("creategame", {
     vname: vname,
     player: { sid: sid, name: localStorage.getItem("name"), color: color },
@@ -143,28 +191,36 @@ const fillGameInfos = (gameInfos, oppIndex) => {
   .then(res => res.text())
   .then(txt => {
     let htmlContent = `
-      <p>
-        <strong>${gameInfos.vdisp}</strong>
-        <span>vs. ${gameInfos.players[oppIndex].name}</span>
-      </p>
-      <hr>
-      <p>`;
-    htmlContent +=
-      Object.entries(gameInfos.options).map(opt => {
-        return (
-          '<span class="option">' +
-          (opt[1] === true ? opt[0] : `${opt[0]}:${opt[1]}`) +
-          '</span>'
-        );
-      })
-      .join(", ");
+      <div class="players-info">
+        <p>
+          <span class="bold">${gameInfos.vdisp}</span>
+          <span>vs. ${gameInfos.players[oppIndex].name}</span>
+        </p>
+      </div>`;
+    const options = Object.entries(gameInfos.options);
+    if (options.length > 0) {
+      htmlContent += '<div class="options-info">';
+      let i = 0;
+      while (i < options.length) {
+        htmlContent += '<div class="row">';
+        for (let j=i; j<i+4; j++) {
+          if (j == options.length) break;
+          const opt = options[j];
+          htmlContent +=
+            '<span class="option">' +
+            (opt[1] === true ? opt[0] : `${opt[0]}:${opt[1]}`) + " " +
+            '</span>';
+        }
+        htmlContent += "</div>";
+        i += 4;
+      }
+      htmlContent += "</div>";
+    }
     htmlContent += `
-      </p>
-      <hr>
-      <div class="rules">
-        ${txt}
-      </div>
-      <button onClick="toggleGameInfos()">Back to game</button>`;
+      <div class="rules">${txt}</div>
+      <div class="btn-wrap">
+        <button onClick="toggleGameInfos()">Back to game</button>
+      </div>`;
     $.getElementById("gameInfos").innerHTML = htmlContent;
   });
 };
@@ -207,7 +263,7 @@ const messageCenter = (msg) => {
   switch (obj.code) {
     // Start new game:
     case "gamestart": {
-      if (!$.hasFocus()) notifyMe("game");
+      if (document.hidden) notifyMe("game");
       gid = obj.gid;
       initializeGame(obj);
       break;
@@ -239,7 +295,10 @@ const messageCenter = (msg) => {
       break;
     // Receive opponent's move:
     case "newmove":
-      if (!$.hasFocus()) notifyMe("move");
+      send("gotmove", {fen: obj.fen, gid: gid});
+      if (obj.fen == lastFen) break; //got this move already
+      lastFen = obj.fen;
+      if (document.hidden) notifyMe("move");
       vr.playReceivedMove(obj.moves, () => {
         if (vr.getCurrentScore(obj.moves[obj.moves.length-1]) != "*") {
           localStorage.removeItem("gid");
@@ -248,6 +307,16 @@ const messageCenter = (msg) => {
         else toggleTurnIndicator(true);
       });
       break;
+    // The server notifies that it got our move:
+    case "gotmove":
+      if (obj.fen == lastFen) {
+        curMoves = [];
+        clearTimeout(timeout1);
+        clearTimeout(timeout2);
+        clearTimeout(timeout3);
+        callbackAfterConfirmation();
+      }
+      break;
     // Opponent stopped game (draw, abort, resign...)
     case "gameover":
       toggleVisible("gameStopped");
@@ -314,31 +383,45 @@ function notifyMe(code) {
   }
   if (Notification.permission === 'granted') doNotify();
   else if (Notification.permission !== 'denied') {
-    Notification.requestPermission().then((permission) => {
+    Notification.requestPermission().then(permission => {
       if (permission === 'granted') doNotify();
     });
   }
 }
 
-let curMoves = [];
-const afterPlay = (move) => { //pack into one moves array, then send
+let curMoves = [],
+    lastFen, lastMove,
+    timeout1, timeout2, timeout3;
+const callbackAfterConfirmation = () => {
+  const result = vr.getCurrentScore(lastMove);
+  if (result != "*") {
+    setTimeout( () => {
+      toggleVisible("gameStopped");
+      send("gameover", { gid: gid });
+    }, 2000);
+  }
+};
+const afterPlay = (move) => {
+  // Pack into one moves array, then send
   curMoves.push({
     appear: move.appear,
     vanish: move.vanish,
     start: move.start,
     end: move.end
   });
+  lastMove = move;
   if (vr.turn != playerColor) {
     toggleTurnIndicator(false);
-    send("newmove", { gid: gid, moves: curMoves, fen: vr.getFen() });
-    curMoves = [];
-    const result = vr.getCurrentScore(move);
-    if (result != "*") {
-      setTimeout( () => {
-        toggleVisible("gameStopped");
-        send("gameover", { gid: gid });
-      }, 2000);
-    }
+    lastFen = vr.getFen();
+    const sendMove =
+      () => send("newmove", {gid: gid, moves: curMoves, fen: lastFen});
+    // Send move until we obtain confirmation or timeout, then callback
+    sendMove();
+    timeout1 = setTimeout(sendMove, 500);
+    timeout2 = setTimeout(sendMove, 1500);
+    timeout3 = setTimeout(
+      () => alert("The move may be lost :( Please reload"),
+      3000);
   }
 };
 
@@ -358,21 +441,31 @@ let vr, playerColor;
 function initializeGame(obj) {
   const options = obj.options || {};
   import(`/variants/${obj.vname}/class.js`).then(module => {
-    const Rules = module.default;
+    window.V = module.default;
     conditionalLoadCSS(obj.vname);
     playerColor = (sid == obj.players[0].sid ? "w" : "b");
     // Init + remove potential extra DOM elements from a previous game:
     document.getElementById("boardContainer").innerHTML = `
       <div id="upLeftInfos"
            onClick="toggleGameInfos()">
-        <img src="/assets/icon_infos.svg"/>
+        <svg version="1.1"
+             viewBox="0.5 0.5 100 100">
+          <g>
+            <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"/>
+          </g>
+        </svg>
       </div>
       <div id="upRightStop"
            onClick="confirmStopGame()">
-        <img src="/assets/icon_close.svg"/>
+        <svg version="1.1"
+             viewBox="0 0 533.333 533.333">
+          <g>
+            <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"/>
+          </g>
+        </svg>
       </div>
       <div class="resizeable" id="chessboard"></div>`;
-    vr = new Rules({
+    vr = new V({
       seed: obj.seed, //may be null if FEN already exists (running game)
       fen: obj.fen,
       element: "chessboard",