Add unambiguous section in the PGN + some fixes + code formatting and fix typos
[vchess.git] / client / src / views / MyGames.vue
index 1f1da59..3c3b9b5 100644 (file)
@@ -14,18 +14,18 @@ main
         @show-game="showGame"
         @abortgame="abortGame"
       )
-      div(v-show="display=='corr'")
-        GameList(
-          ref="corrgames"
-          :games="corrGames"
-          @show-game="showGame"
-          @abortgame="abortGame"
-        )
-        button#loadMoreBtn(
-          v-if="hasMore"
-          @click="loadMore()"
-        )
-          | {{ st.tr["Load more"] }}
+      GameList(
+        v-show="display=='corr'"
+        ref="corrgames"
+        :games="corrGames"
+        @show-game="showGame"
+        @abortgame="abortGame"
+      )
+      button#loadMoreBtn(
+        v-show="hasMore[display]"
+        @click="loadMore(display)"
+      )
+        | {{ st.tr["Load more"] }}
 </template>
 
 <script>
@@ -47,29 +47,46 @@ export default {
       display: "live",
       liveGames: [],
       corrGames: [],
-      // timestamp of last showed (oldest) corr game:
-      cursor: Number.MAX_SAFE_INTEGER,
+      // timestamp of last showed (oldest) game:
+      cursor: {
+        live: Number.MAX_SAFE_INTEGER,
+        corr: Number.MAX_SAFE_INTEGER
+      },
       // hasMore == TRUE: a priori there could be more games to load
-      hasMore: true,
+      hasMore: { live: true, corr: store.state.user.id > 0 },
       conn: null,
-      connexionString: ""
+      connexionString: "",
+      socketCloseListener: 0
     };
   },
+  watch: {
+    $route: function(to, from) {
+      if (to.path != "/mygames") this.cleanBeforeDestroy();
+    }
+  },
   created: function() {
+    window.addEventListener("beforeunload", this.cleanBeforeDestroy);
     // Initialize connection
     this.connexionString =
       params.socketUrl +
-      "/?sid=" +
-      this.st.user.sid +
-      "&id=" +
-      this.st.user.id +
-      "&tmpId=" +
-      getRandString() +
+      "/?sid=" + this.st.user.sid +
+      "&id=" + this.st.user.id +
+      "&tmpId=" + getRandString() +
       "&page=" +
       encodeURIComponent(this.$route.path);
     this.conn = new WebSocket(this.connexionString);
     this.conn.onmessage = this.socketMessageListener;
-    this.conn.onclose = this.socketCloseListener;
+    this.socketCloseListener = setInterval(
+      () => {
+        if (this.conn.readyState == 3) {
+          // Connexion is closed: re-open
+          this.conn.removeEventListener("message", this.socketMessageListener);
+          this.conn = new WebSocket(this.connexionString);
+          this.conn.addEventListener("message", this.socketMessageListener);
+        }
+      },
+      1000
+    );
   },
   mounted: function() {
     const adjustAndSetDisplay = () => {
@@ -93,7 +110,7 @@ export default {
       }
       this.setDisplay(showType);
     };
-    GameStorage.getAll(localGames => {
+    GameStorage.getRunning(localGames => {
       localGames.forEach(g => g.type = "live");
       this.decorate(localGames);
       this.liveGames = localGames;
@@ -113,35 +130,27 @@ export default {
               });
               this.decorate(this.corrGames);
               // Now ask completed games (partial list)
-              ajax(
-                "/completedgames",
-                "GET",
-                {
-                  credentials: true,
-                  data: { cursor: this.cursor },
-                  success: (res2) => {
-                    if (res2.games.length > 0) {
-                      const L = res2.games.length;
-                      this.cursor = res2.games[L - 1].created;
-                      let completedGames = res2.games;
-                      completedGames.forEach(g => g.type = "corr");
-                      this.decorate(completedGames);
-                      this.corrGames = this.corrGames.concat(completedGames);
-                      adjustAndSetDisplay();
-                    }
-                  }
-                }
+              this.loadMore(
+                "live",
+                () => this.loadMore("corr", adjustAndSetDisplay)
               );
             }
           }
         );
-      } else adjustAndSetDisplay();
+      } else this.loadMore("live", adjustAndSetDisplay);
     });
   },
   beforeDestroy: function() {
-    this.conn.send(JSON.stringify({code: "disconnect"}));
+    this.cleanBeforeDestroy();
   },
   methods: {
+    cleanBeforeDestroy: function() {
+      clearInterval(this.socketCloseListener);
+      window.removeEventListener("beforeunload", this.cleanBeforeDestroy);
+      this.conn.removeEventListener("message", this.socketMessageListener);
+      this.conn.send(JSON.stringify({code: "disconnect"}));
+      this.conn = null;
+    },
     setDisplay: function(type, e) {
       this.display = type;
       localStorage.setItem("type-myGames", type);
@@ -179,6 +188,7 @@ export default {
       });
     },
     socketMessageListener: function(msg) {
+      if (!this.conn) return;
       const data = JSON.parse(msg.data);
       let gamesArrays = {
         "corr": this.corrGames,
@@ -229,11 +239,6 @@ export default {
         }
       }
     },
-    socketCloseListener: function() {
-      this.conn = new WebSocket(this.connexionString);
-      this.conn.addEventListener("message", this.socketMessageListener);
-      this.conn.addEventListener("close", this.socketCloseListener);
-    },
     showGame: function(game) {
       if (game.type == "live" || !game.myTurn) {
         this.$router.push("/game/" + game.id);
@@ -259,16 +264,18 @@ export default {
           game.players[0].sid == this.st.user.sid
             ? game.players[1].sid
             : game.players[0].sid;
-        this.conn.send(
-          JSON.stringify(
-            {
-              code: "mabort",
-              gid: game.id,
-              // NOTE: target might not be online
-              target: oppsid
-            }
-          )
-        );
+        if (!!this.conn) {
+          this.conn.send(
+            JSON.stringify(
+              {
+                code: "mabort",
+                gid: game.id,
+                // NOTE: target might not be online
+                target: oppsid
+              }
+            )
+          );
+        }
       }
       else if (!game.deletedByWhite || !game.deletedByBlack) {
         // Set score if game isn't deleted on server:
@@ -287,25 +294,40 @@ export default {
         );
       }
     },
-    loadMore: function() {
-      ajax(
-        "/completedgames",
-        "GET",
-        {
-          credentials: true,
-          data: { cursor: this.cursor },
-          success: (res) => {
-            if (res.games.length > 0) {
+    loadMore: function(type, cb) {
+      if (type == "corr" && this.st.user.id > 0) {
+        ajax(
+          "/completedgames",
+          "GET",
+          {
+            credentials: true,
+            data: { cursor: this.cursor["corr"] },
+            success: (res) => {
               const L = res.games.length;
-              this.cursor = res.games[L - 1].created;
-              let moreGames = res.games;
-              moreGames.forEach(g => g.type = "corr");
-              this.decorate(moreGames);
-              this.corrGames = this.corrGames.concat(moreGames);
-            } else this.hasMore = false;
+              if (L > 0) {
+                this.cursor["corr"] = res.games[L - 1].created;
+                let moreGames = res.games;
+                moreGames.forEach(g => g.type = "corr");
+                this.decorate(moreGames);
+                this.corrGames = this.corrGames.concat(moreGames);
+              } else this.hasMore["corr"] = false;
+              if (!!cb) cb();
+            }
           }
-        }
-      );
+        );
+      } else if (type == "live") {
+        GameStorage.getNext(this.cursor["live"], localGames => {
+          const L = localGames.length;
+          if (L > 0) {
+            // Add "-1" because IDBKeyRange.upperBound includes boundary
+            this.cursor["live"] = localGames[L - 1].created - 1;
+            localGames.forEach(g => g.type = "live");
+            this.decorate(localGames);
+            this.liveGames = this.liveGames.concat(localGames);
+          } else this.hasMore["live"] = false;
+          if (!!cb) cb();
+        });
+      }
     }
   }
 };