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