Attempt to get rid of unwanted trans-rooms socket listen/message...
[vchess.git] / client / src / views / MyGames.vue
1 <template lang="pug">
2 main
3 .row
4 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
5 .button-group
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(
11 ref="livegames"
12 v-show="display=='live'"
13 :games="liveGames"
14 @show-game="showGame"
15 @abortgame="abortGame"
16 )
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"] }}
29 </template>
30
31 <script>
32 import { store } from "@/store";
33 import { GameStorage } from "@/utils/gameStorage";
34 import { ajax } from "@/utils/ajax";
35 import { getScoreMessage } from "@/utils/scoring";
36 import params from "@/parameters";
37 import { getRandString } from "@/utils/alea";
38 import GameList from "@/components/GameList.vue";
39 export default {
40 name: "my-my-games",
41 components: {
42 GameList
43 },
44 data: function() {
45 return {
46 st: store.state,
47 display: "live",
48 liveGames: [],
49 corrGames: [],
50 // timestamp of last showed (oldest) game:
51 cursor: {
52 live: Number.MAX_SAFE_INTEGER,
53 corr: Number.MAX_SAFE_INTEGER
54 },
55 // hasMore == TRUE: a priori there could be more games to load
56 hasMore: { live: true, corr: true },
57 conn: null,
58 connexionString: ""
59 };
60 },
61 watch: {
62 $route: function(to, from) {
63 if (to.path != "/mygames") this.cleanBeforeDestroy();
64 }
65 },
66 created: function() {
67 window.addEventListener("beforeunload", this.cleanBeforeDestroy);
68 // Initialize connection
69 this.connexionString =
70 params.socketUrl +
71 "/?sid=" +
72 this.st.user.sid +
73 "&id=" +
74 this.st.user.id +
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;
82 },
83 mounted: function() {
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 };
105 GameStorage.getRunning(localGames => {
106 localGames.forEach(g => g.type = "live");
107 this.decorate(localGames);
108 this.liveGames = localGames;
109 if (this.st.user.id > 0) {
110 // Ask running corr games first
111 ajax(
112 "/runninggames",
113 "GET",
114 {
115 credentials: true,
116 success: (res) => {
117 // These games are garanteed to not be deleted
118 this.corrGames = res.games;
119 this.corrGames.forEach(g => {
120 g.type = "corr";
121 g.score = "*";
122 });
123 this.decorate(this.corrGames);
124 // Now ask completed games (partial list)
125 this.loadMore(
126 "live",
127 () => this.loadMore("corr", adjustAndSetDisplay)
128 );
129 }
130 }
131 );
132 } else {
133 this.loadMore(
134 "live",
135 () => this.loadMore("corr", adjustAndSetDisplay)
136 );
137 }
138 });
139 },
140 beforeDestroy: function() {
141 this.cleanBeforeDestroy();
142 },
143 methods: {
144 cleanBeforeDestroy: function() {
145 window.removeEventListener("beforeunload", this.cleanBeforeDestroy);
146 this.conn.removeEventListener("message", this.socketMessageListener);
147 this.conn.removeEventListener("close", this.socketCloseListener);
148 this.conn.send(JSON.stringify({code: "disconnect"}));
149 this.conn = null;
150 },
151 setDisplay: function(type, e) {
152 this.display = type;
153 localStorage.setItem("type-myGames", type);
154 let elt = e ? e.target : document.getElementById(type + "Games");
155 elt.classList.add("active");
156 elt.classList.remove("somethingnew"); //in case of
157 if (elt.previousElementSibling)
158 elt.previousElementSibling.classList.remove("active");
159 else elt.nextElementSibling.classList.remove("active");
160 },
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 },
171 // Called at loading to augment games with myColor + myTurn infos
172 decorate: function(games) {
173 games.forEach(g => {
174 g.myColor =
175 (g.type == "corr" && g.players[0].id == this.st.user.id) ||
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:
180 if (g.score == "*") {
181 const rem = g.movesCount % 2;
182 if ((rem == 0 && g.myColor == 'w') || (rem == 1 && g.myColor == 'b'))
183 g.myTurn = true;
184 }
185 });
186 },
187 socketMessageListener: function(msg) {
188 if (!this.conn) return;
189 const data = JSON.parse(msg.data);
190 let gamesArrays = {
191 "corr": this.corrGames,
192 "live": this.liveGames
193 };
194 switch (data.code) {
195 case "notifyturn":
196 case "notifyscore": {
197 const info = data.data;
198 const type = (!!parseInt(info.gid) ? "corr" : "live");
199 let game = gamesArrays[type].find(g => g.id == info.gid);
200 // "notifything" --> "thing":
201 const thing = data.code.substr(6);
202 game[thing] = info[thing];
203 if (thing == "turn") {
204 game.myTurn = !game.myTurn;
205 if (game.myTurn) this.tryShowNewsIndicator(type);
206 } else game.myTurn = false;
207 // TODO: forcing refresh like that is ugly and wrong.
208 // How to do it cleanly?
209 this.$refs[type + "games"].$forceUpdate();
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 : "";
218 const type = (gameInfo.cadence.indexOf('d') >= 0 ? "corr": "live");
219 let game = Object.assign(
220 {
221 vname: vname,
222 type: type,
223 score: "*",
224 created: Date.now()
225 },
226 gameInfo
227 );
228 game.myTurn =
229 (type == "corr" && game.players[0].id == this.st.user.id) ||
230 (type == "live" && game.players[0].sid == this.st.user.sid);
231 gamesArrays[type].push(game);
232 if (game.myTurn) this.tryShowNewsIndicator(type);
233 // TODO: cleaner refresh
234 this.$refs[type + "games"].$forceUpdate();
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);
243 },
244 showGame: function(game) {
245 if (game.type == "live" || !game.myTurn) {
246 this.$router.push("/game/" + game.id);
247 return;
248 }
249 // It's my turn in this game. Are there others?
250 let nextIds = "";
251 let otherCorrGamesMyTurn = this.corrGames.filter(g =>
252 g.id != game.id && !!g.myTurn);
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);
260 },
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;
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 }
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 {
288 data: {
289 gid: game.id,
290 newObj: {
291 score: "?",
292 scoreMsg: getScoreMessage("?")
293 }
294 }
295 }
296 );
297 }
298 },
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 }
318 }
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 }
333 }
334 }
335 };
336 </script>
337
338 <style lang="sass">
339 .active
340 color: #42a983
341
342 .tabbtn
343 background-color: #f9faee
344
345 table.game-list
346 max-height: 100%
347
348 button#loadMoreBtn
349 display: block
350 margin: 0 auto
351
352 .somethingnew
353 background-color: #c5fefe !important
354 </style>