Small fix
[vchess.git] / client / src / views / MyGames.vue
CommitLineData
afd3240d
BA
1<template lang="pug">
2main
3 .row
4 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
5 .button-group
910d631b
BA
6 button.tabbtn#liveGames(@click="setDisplay('live',$event)")
7 | {{ st.tr["Live games"] }}
8 button.tabbtn#corrGames(@click="setDisplay('corr',$event)")
9 | {{ st.tr["Correspondance games"] }}
5f918a27
BA
10 button.tabbtn#importGames(@click="setDisplay('import',$event)")
11 | {{ st.tr["Imported games"] }}
910d631b 12 GameList(
585d0955 13 ref="livegames"
910d631b
BA
14 v-show="display=='live'"
15 :games="liveGames"
16 @show-game="showGame"
3b0f26c1 17 @abortgame="abortGame"
910d631b 18 )
934f7f70
BA
19 GameList(
20 v-show="display=='corr'"
21 ref="corrgames"
22 :games="corrGames"
23 @show-game="showGame"
24 @abortgame="abortGame"
25 )
5f918a27
BA
26 GameList(
27 v-show="display=='import'"
28 ref="importgames"
29 :games="importGames"
30 @show-game="showGame"
31 )
934f7f70
BA
32 button#loadMoreBtn(
33 v-show="hasMore[display]"
34 @click="loadMore(display)"
35 )
36 | {{ st.tr["Load more"] }}
5f918a27 37 UploadGame(@game-uploaded="addGameImport")
afd3240d
BA
38</template>
39
40<script>
afd3240d
BA
41import { store } from "@/store";
42import { GameStorage } from "@/utils/gameStorage";
5f918a27 43import { ImportgameStorage } from "@/utils/importgameStorage";
afd3240d 44import { ajax } from "@/utils/ajax";
aae89b49 45import { getScoreMessage } from "@/utils/scoring";
23ecf008
BA
46import params from "@/parameters";
47import { getRandString } from "@/utils/alea";
afd3240d 48import GameList from "@/components/GameList.vue";
91777c2c 49import UploadGame from "@/components/UploadGame.vue";
afd3240d 50export default {
89021f18 51 name: "my-my-games",
afd3240d 52 components: {
5f918a27
BA
53 GameList,
54 UploadGame
afd3240d
BA
55 },
56 data: function() {
57 return {
58 st: store.state,
dac39588 59 display: "live",
2f258c37 60 liveGames: [],
db1f1f9a 61 corrGames: [],
5f918a27 62 importGames: [],
934f7f70
BA
63 // timestamp of last showed (oldest) game:
64 cursor: {
65 live: Number.MAX_SAFE_INTEGER,
5f918a27 66 "import": Number.MAX_SAFE_INTEGER,
934f7f70
BA
67 corr: Number.MAX_SAFE_INTEGER
68 },
0234201f 69 // hasMore == TRUE: a priori there could be more games to load
5f918a27
BA
70 hasMore: {
71 live: true,
72 "import": true,
73 corr: (store.state.user.id > 0)
74 },
db1f1f9a 75 conn: null,
882ec6fe
BA
76 connexionString: "",
77 socketCloseListener: 0
afd3240d
BA
78 };
79 },
1112f1fd
BA
80 watch: {
81 $route: function(to, from) {
82 if (to.path != "/mygames") this.cleanBeforeDestroy();
83 }
84 },
afd3240d 85 created: function() {
1112f1fd 86 window.addEventListener("beforeunload", this.cleanBeforeDestroy);
db1f1f9a
BA
87 // Initialize connection
88 this.connexionString =
89 params.socketUrl +
7e476ce4
BA
90 "/?sid=" + this.st.user.sid +
91 "&id=" + this.st.user.id +
92 "&tmpId=" + getRandString() +
db1f1f9a
BA
93 "&page=" +
94 encodeURIComponent(this.$route.path);
95 this.conn = new WebSocket(this.connexionString);
96 this.conn.onmessage = this.socketMessageListener;
882ec6fe
BA
97 this.socketCloseListener = setInterval(
98 () => {
99 if (this.conn.readyState == 3) {
100 // Connexion is closed: re-open
101 this.conn.removeEventListener("message", this.socketMessageListener);
102 this.conn = new WebSocket(this.connexionString);
103 this.conn.addEventListener("message", this.socketMessageListener);
104 }
105 },
106 1000
107 );
afd3240d 108 },
2f258c37 109 mounted: function() {
585d0955
BA
110 const adjustAndSetDisplay = () => {
111 // showType is the last type viwed by the user (default)
112 let showType = localStorage.getItem("type-myGames") || "live";
113 // Live games, my turn: highest priority:
114 if (this.liveGames.some(g => !!g.myTurn)) showType = "live";
115 // Then corr games, my turn:
116 else if (this.corrGames.some(g => !!g.myTurn)) showType = "corr";
117 else {
118 // If a listing is empty, try showing the other (if non-empty)
119 const types = ["corr", "live"];
120 for (let i of [0,1]) {
121 if (
122 this[types[i] + "Games"].length > 0 &&
123 this[types[1-i] + "Games"].length == 0
124 ) {
125 showType = types[i];
126 }
127 }
128 }
129 this.setDisplay(showType);
130 };
934f7f70 131 GameStorage.getRunning(localGames => {
585d0955
BA
132 localGames.forEach(g => g.type = "live");
133 this.decorate(localGames);
134 this.liveGames = localGames;
135 if (this.st.user.id > 0) {
0234201f 136 // Ask running corr games first
585d0955 137 ajax(
0234201f 138 "/runninggames",
585d0955
BA
139 "GET",
140 {
f14572c4 141 credentials: true,
585d0955 142 success: (res) => {
0234201f
BA
143 // These games are garanteed to not be deleted
144 this.corrGames = res.games;
f14572c4
BA
145 this.corrGames.forEach(g => {
146 g.type = "corr";
147 g.score = "*";
148 });
0234201f
BA
149 this.decorate(this.corrGames);
150 // Now ask completed games (partial list)
934f7f70
BA
151 this.loadMore(
152 "live",
153 () => this.loadMore("corr", adjustAndSetDisplay)
0234201f 154 );
585d0955
BA
155 }
156 }
157 );
7ebc0408 158 } else this.loadMore("live", adjustAndSetDisplay);
585d0955 159 });
2f258c37 160 },
23ecf008 161 beforeDestroy: function() {
1112f1fd 162 this.cleanBeforeDestroy();
23ecf008 163 },
afd3240d 164 methods: {
1112f1fd 165 cleanBeforeDestroy: function() {
882ec6fe 166 clearInterval(this.socketCloseListener);
1112f1fd 167 window.removeEventListener("beforeunload", this.cleanBeforeDestroy);
68e3aa8c 168 this.conn.removeEventListener("message", this.socketMessageListener);
1112f1fd 169 this.conn.send(JSON.stringify({code: "disconnect"}));
68e3aa8c 170 this.conn = null;
1112f1fd 171 },
2f258c37
BA
172 setDisplay: function(type, e) {
173 this.display = type;
174 localStorage.setItem("type-myGames", type);
6808d7a1 175 let elt = e ? e.target : document.getElementById(type + "Games");
2f258c37 176 elt.classList.add("active");
23ecf008 177 elt.classList.remove("somethingnew"); //in case of
6808d7a1 178 if (elt.previousElementSibling)
2f258c37 179 elt.previousElementSibling.classList.remove("active");
6808d7a1 180 else elt.nextElementSibling.classList.remove("active");
2f258c37 181 },
5f918a27
BA
182 addGameImport(game) {
183 if (!game.id) {
184 alert(this.st.tr[
185 "No identifier found: use the upload button in analysis mode"]);
186 }
187 else this.importGames.push(game);
188 },
cafe0166
BA
189 tryShowNewsIndicator: function(type) {
190 if (
191 (type == "live" && this.display == "corr") ||
192 (type == "corr" && this.display == "live")
193 ) {
194 document
195 .getElementById(type + "Games")
196 .classList.add("somethingnew");
197 }
198 },
28b32b4f 199 // Called at loading to augment games with myColor + myTurn infos
e727fe31
BA
200 decorate: function(games) {
201 games.forEach(g => {
6b7b2cf7 202 g.myColor =
0234201f 203 (g.type == "corr" && g.players[0].id == this.st.user.id) ||
6b7b2cf7
BA
204 (g.type == "live" && g.players[0].sid == this.st.user.sid)
205 ? 'w'
206 : 'b';
207 // If game is over, myTurn doesn't exist:
e727fe31 208 if (g.score == "*") {
e727fe31 209 const rem = g.movesCount % 2;
6b7b2cf7 210 if ((rem == 0 && g.myColor == 'w') || (rem == 1 && g.myColor == 'b'))
e727fe31 211 g.myTurn = true;
e727fe31
BA
212 }
213 });
214 },
cafe0166 215 socketMessageListener: function(msg) {
68e3aa8c 216 if (!this.conn) return;
cafe0166 217 const data = JSON.parse(msg.data);
5f918a27 218 // NOTE: no imported games here
e727fe31
BA
219 let gamesArrays = {
220 "corr": this.corrGames,
221 "live": this.liveGames
222 };
cafe0166 223 switch (data.code) {
cafe0166
BA
224 case "notifyturn":
225 case "notifyscore": {
226 const info = data.data;
e727fe31
BA
227 const type = (!!parseInt(info.gid) ? "corr" : "live");
228 let game = gamesArrays[type].find(g => g.id == info.gid);
cafe0166
BA
229 // "notifything" --> "thing":
230 const thing = data.code.substr(6);
e727fe31 231 game[thing] = info[thing];
585d0955
BA
232 if (thing == "turn") {
233 game.myTurn = !game.myTurn;
234 if (game.myTurn) this.tryShowNewsIndicator(type);
f14572c4 235 } else game.myTurn = false;
585d0955
BA
236 // TODO: forcing refresh like that is ugly and wrong.
237 // How to do it cleanly?
238 this.$refs[type + "games"].$forceUpdate();
cafe0166
BA
239 break;
240 }
241 case "notifynewgame": {
242 const gameInfo = data.data;
243 // st.variants might be uninitialized,
244 // if unlucky and newgame right after connect:
245 const v = this.st.variants.find(v => v.id == gameInfo.vid);
246 const vname = !!v ? v.name : "";
e727fe31
BA
247 const type = (gameInfo.cadence.indexOf('d') >= 0 ? "corr": "live");
248 let game = Object.assign(
cafe0166
BA
249 {
250 vname: vname,
251 type: type,
2a8a94c9 252 score: "*",
e727fe31 253 created: Date.now()
cafe0166
BA
254 },
255 gameInfo
256 );
28b32b4f 257 game.myTurn =
0234201f 258 (type == "corr" && game.players[0].id == this.st.user.id) ||
28b32b4f 259 (type == "live" && game.players[0].sid == this.st.user.sid);
e727fe31 260 gamesArrays[type].push(game);
585d0955
BA
261 if (game.myTurn) this.tryShowNewsIndicator(type);
262 // TODO: cleaner refresh
263 this.$refs[type + "games"].$forceUpdate();
cafe0166
BA
264 break;
265 }
266 }
267 },
feaf1bf7 268 showGame: function(game) {
5f918a27 269 if (game.type != "corr" || !game.myTurn) {
feaf1bf7 270 this.$router.push("/game/" + game.id);
620a88ed
BA
271 return;
272 }
feaf1bf7
BA
273 // It's my turn in this game. Are there others?
274 let nextIds = "";
e727fe31
BA
275 let otherCorrGamesMyTurn = this.corrGames.filter(g =>
276 g.id != game.id && !!g.myTurn);
feaf1bf7
BA
277 if (otherCorrGamesMyTurn.length > 0) {
278 nextIds += "/?next=[";
279 otherCorrGamesMyTurn.forEach(g => { nextIds += g.id + ","; });
280 // Remove last comma and close array:
281 nextIds = nextIds.slice(0, -1) + "]";
282 }
283 this.$router.push("/game/" + game.id + nextIds);
db1f1f9a 284 },
aae89b49
BA
285 abortGame: function(game) {
286 // Special "trans-pages" case: from MyGames to Game
287 // TODO: also for corr games? (It's less important)
288 if (game.type == "live") {
289 const oppsid =
290 game.players[0].sid == this.st.user.sid
291 ? game.players[1].sid
292 : game.players[0].sid;
68e3aa8c
BA
293 if (!!this.conn) {
294 this.conn.send(
295 JSON.stringify(
296 {
297 code: "mabort",
298 gid: game.id,
299 // NOTE: target might not be online
300 target: oppsid
301 }
302 )
303 );
304 }
aae89b49 305 }
5f918a27 306 // NOTE: no imported games here
aae89b49
BA
307 else if (!game.deletedByWhite || !game.deletedByBlack) {
308 // Set score if game isn't deleted on server:
309 ajax(
310 "/games",
311 "PUT",
312 {
e57c4de4
BA
313 data: {
314 gid: game.id,
315 newObj: {
316 score: "?",
317 scoreMsg: getScoreMessage("?")
318 }
aae89b49
BA
319 }
320 }
321 );
322 }
0234201f 323 },
934f7f70 324 loadMore: function(type, cb) {
7ebc0408 325 if (type == "corr" && this.st.user.id > 0) {
934f7f70
BA
326 ajax(
327 "/completedgames",
328 "GET",
329 {
330 credentials: true,
331 data: { cursor: this.cursor["corr"] },
332 success: (res) => {
333 const L = res.games.length;
334 if (L > 0) {
335 this.cursor["corr"] = res.games[L - 1].created;
336 let moreGames = res.games;
337 moreGames.forEach(g => g.type = "corr");
338 this.decorate(moreGames);
339 this.corrGames = this.corrGames.concat(moreGames);
340 } else this.hasMore["corr"] = false;
341 if (!!cb) cb();
342 }
0234201f 343 }
934f7f70 344 );
5f918a27
BA
345 }
346 else if (type == "live") {
934f7f70
BA
347 GameStorage.getNext(this.cursor["live"], localGames => {
348 const L = localGames.length;
349 if (L > 0) {
2c5d7b20 350 // Add "-1" because IDBKeyRange.upperBound includes boundary
934f7f70
BA
351 this.cursor["live"] = localGames[L - 1].created - 1;
352 localGames.forEach(g => g.type = "live");
353 this.decorate(localGames);
354 this.liveGames = this.liveGames.concat(localGames);
355 } else this.hasMore["live"] = false;
356 if (!!cb) cb();
357 });
358 }
5f918a27
BA
359 else if (type == "import") {
360 ImportgameStorage.getNext(this.cursor["import"], importGames => {
361 const L = importGames.length;
362 if (L > 0) {
363 // Add "-1" because IDBKeyRange.upperBound includes boundary
364 this.cursor["import"] = importGames[L - 1].created - 1;
365 importGames.forEach(g => g.type = "import");
366 this.importGames = this.importGames.concat(importGames);
367 } else this.hasMore["import"] = false;
368 if (!!cb) cb();
369 });
370 }
6808d7a1
BA
371 }
372 }
afd3240d
BA
373};
374</script>
2f258c37 375
e2590fa8 376<style lang="sass">
2f258c37
BA
377.active
378 color: #42a983
5fe7e71c
BA
379
380.tabbtn
381 background-color: #f9faee
e2590fa8
BA
382
383table.game-list
384 max-height: 100%
23ecf008 385
0234201f 386button#loadMoreBtn
f14572c4
BA
387 display: block
388 margin: 0 auto
0234201f 389
23ecf008
BA
390.somethingnew
391 background-color: #c5fefe !important
2f258c37 392</style>