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