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