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