Attempt for better connection indicators
[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);
146 this.conn.send(JSON.stringify({code: "disconnect"}));
147 },
2f258c37
BA
148 setDisplay: function(type, e) {
149 this.display = type;
150 localStorage.setItem("type-myGames", type);
6808d7a1 151 let elt = e ? e.target : document.getElementById(type + "Games");
2f258c37 152 elt.classList.add("active");
23ecf008 153 elt.classList.remove("somethingnew"); //in case of
6808d7a1 154 if (elt.previousElementSibling)
2f258c37 155 elt.previousElementSibling.classList.remove("active");
6808d7a1 156 else elt.nextElementSibling.classList.remove("active");
2f258c37 157 },
cafe0166
BA
158 tryShowNewsIndicator: function(type) {
159 if (
160 (type == "live" && this.display == "corr") ||
161 (type == "corr" && this.display == "live")
162 ) {
163 document
164 .getElementById(type + "Games")
165 .classList.add("somethingnew");
166 }
167 },
28b32b4f 168 // Called at loading to augment games with myColor + myTurn infos
e727fe31
BA
169 decorate: function(games) {
170 games.forEach(g => {
6b7b2cf7 171 g.myColor =
0234201f 172 (g.type == "corr" && g.players[0].id == this.st.user.id) ||
6b7b2cf7
BA
173 (g.type == "live" && g.players[0].sid == this.st.user.sid)
174 ? 'w'
175 : 'b';
176 // If game is over, myTurn doesn't exist:
e727fe31 177 if (g.score == "*") {
e727fe31 178 const rem = g.movesCount % 2;
6b7b2cf7 179 if ((rem == 0 && g.myColor == 'w') || (rem == 1 && g.myColor == 'b'))
e727fe31 180 g.myTurn = true;
e727fe31
BA
181 }
182 });
183 },
cafe0166
BA
184 socketMessageListener: function(msg) {
185 const data = JSON.parse(msg.data);
e727fe31
BA
186 let gamesArrays = {
187 "corr": this.corrGames,
188 "live": this.liveGames
189 };
cafe0166 190 switch (data.code) {
cafe0166
BA
191 case "notifyturn":
192 case "notifyscore": {
193 const info = data.data;
e727fe31
BA
194 const type = (!!parseInt(info.gid) ? "corr" : "live");
195 let game = gamesArrays[type].find(g => g.id == info.gid);
cafe0166
BA
196 // "notifything" --> "thing":
197 const thing = data.code.substr(6);
e727fe31 198 game[thing] = info[thing];
585d0955
BA
199 if (thing == "turn") {
200 game.myTurn = !game.myTurn;
201 if (game.myTurn) this.tryShowNewsIndicator(type);
f14572c4 202 } else game.myTurn = false;
585d0955
BA
203 // TODO: forcing refresh like that is ugly and wrong.
204 // How to do it cleanly?
205 this.$refs[type + "games"].$forceUpdate();
cafe0166
BA
206 break;
207 }
208 case "notifynewgame": {
209 const gameInfo = data.data;
210 // st.variants might be uninitialized,
211 // if unlucky and newgame right after connect:
212 const v = this.st.variants.find(v => v.id == gameInfo.vid);
213 const vname = !!v ? v.name : "";
e727fe31
BA
214 const type = (gameInfo.cadence.indexOf('d') >= 0 ? "corr": "live");
215 let game = Object.assign(
cafe0166
BA
216 {
217 vname: vname,
218 type: type,
2a8a94c9 219 score: "*",
e727fe31 220 created: Date.now()
cafe0166
BA
221 },
222 gameInfo
223 );
28b32b4f 224 game.myTurn =
0234201f 225 (type == "corr" && game.players[0].id == this.st.user.id) ||
28b32b4f 226 (type == "live" && game.players[0].sid == this.st.user.sid);
e727fe31 227 gamesArrays[type].push(game);
585d0955
BA
228 if (game.myTurn) this.tryShowNewsIndicator(type);
229 // TODO: cleaner refresh
230 this.$refs[type + "games"].$forceUpdate();
cafe0166
BA
231 break;
232 }
233 }
234 },
235 socketCloseListener: function() {
236 this.conn = new WebSocket(this.connexionString);
237 this.conn.addEventListener("message", this.socketMessageListener);
238 this.conn.addEventListener("close", this.socketCloseListener);
afd3240d 239 },
feaf1bf7 240 showGame: function(game) {
e727fe31 241 if (game.type == "live" || !game.myTurn) {
feaf1bf7 242 this.$router.push("/game/" + game.id);
620a88ed
BA
243 return;
244 }
feaf1bf7
BA
245 // It's my turn in this game. Are there others?
246 let nextIds = "";
e727fe31
BA
247 let otherCorrGamesMyTurn = this.corrGames.filter(g =>
248 g.id != game.id && !!g.myTurn);
feaf1bf7
BA
249 if (otherCorrGamesMyTurn.length > 0) {
250 nextIds += "/?next=[";
251 otherCorrGamesMyTurn.forEach(g => { nextIds += g.id + ","; });
252 // Remove last comma and close array:
253 nextIds = nextIds.slice(0, -1) + "]";
254 }
255 this.$router.push("/game/" + game.id + nextIds);
db1f1f9a 256 },
aae89b49
BA
257 abortGame: function(game) {
258 // Special "trans-pages" case: from MyGames to Game
259 // TODO: also for corr games? (It's less important)
260 if (game.type == "live") {
261 const oppsid =
262 game.players[0].sid == this.st.user.sid
263 ? game.players[1].sid
264 : game.players[0].sid;
265 this.conn.send(
266 JSON.stringify(
267 {
268 code: "mabort",
269 gid: game.id,
270 // NOTE: target might not be online
271 target: oppsid
272 }
273 )
274 );
275 }
276 else if (!game.deletedByWhite || !game.deletedByBlack) {
277 // Set score if game isn't deleted on server:
278 ajax(
279 "/games",
280 "PUT",
281 {
e57c4de4
BA
282 data: {
283 gid: game.id,
284 newObj: {
285 score: "?",
286 scoreMsg: getScoreMessage("?")
287 }
aae89b49
BA
288 }
289 }
290 );
291 }
0234201f 292 },
934f7f70
BA
293 loadMore: function(type, cb) {
294 if (type == "corr") {
295 ajax(
296 "/completedgames",
297 "GET",
298 {
299 credentials: true,
300 data: { cursor: this.cursor["corr"] },
301 success: (res) => {
302 const L = res.games.length;
303 if (L > 0) {
304 this.cursor["corr"] = res.games[L - 1].created;
305 let moreGames = res.games;
306 moreGames.forEach(g => g.type = "corr");
307 this.decorate(moreGames);
308 this.corrGames = this.corrGames.concat(moreGames);
309 } else this.hasMore["corr"] = false;
310 if (!!cb) cb();
311 }
0234201f 312 }
934f7f70
BA
313 );
314 } else if (type == "live") {
315 GameStorage.getNext(this.cursor["live"], localGames => {
316 const L = localGames.length;
317 if (L > 0) {
318 // Add "-1" because IDBKeyRange.upperBound seems to include boundary
319 this.cursor["live"] = localGames[L - 1].created - 1;
320 localGames.forEach(g => g.type = "live");
321 this.decorate(localGames);
322 this.liveGames = this.liveGames.concat(localGames);
323 } else this.hasMore["live"] = false;
324 if (!!cb) cb();
325 });
326 }
6808d7a1
BA
327 }
328 }
afd3240d
BA
329};
330</script>
2f258c37 331
e2590fa8 332<style lang="sass">
2f258c37
BA
333.active
334 color: #42a983
5fe7e71c
BA
335
336.tabbtn
337 background-color: #f9faee
e2590fa8
BA
338
339table.game-list
340 max-height: 100%
23ecf008 341
0234201f 342button#loadMoreBtn
f14572c4
BA
343 display: block
344 margin: 0 auto
0234201f 345
23ecf008
BA
346.somethingnew
347 background-color: #c5fefe !important
2f258c37 348</style>