890d9395192b57d6b0c342c88af5e8277972a19b
[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 UploadGame(
27 v-show="display=='import'"
28 @game-uploaded="addGameImport"
29 )
30 GameList(
31 v-show="display=='import'"
32 ref="importgames"
33 :games="importGames"
34 @show-game="showGame"
35 )
36 button#loadMoreBtn(
37 v-show="hasMore[display]"
38 @click="loadMore(display)"
39 )
40 | {{ st.tr["Load more"] }}
41 </template>
42
43 <script>
44 import { store } from "@/store";
45 import { GameStorage } from "@/utils/gameStorage";
46 import { ImportgameStorage } from "@/utils/importgameStorage";
47 import { ajax } from "@/utils/ajax";
48 import { getScoreMessage } from "@/utils/scoring";
49 import params from "@/parameters";
50 import { getRandString } from "@/utils/alea";
51 import GameList from "@/components/GameList.vue";
52 import UploadGame from "@/components/UploadGame.vue";
53 export default {
54 name: "my-my-games",
55 components: {
56 GameList,
57 UploadGame
58 },
59 data: function() {
60 return {
61 st: store.state,
62 display: "live",
63 liveGames: [],
64 corrGames: [],
65 importGames: [],
66 // timestamp of last showed (oldest) game:
67 cursor: {
68 live: Number.MAX_SAFE_INTEGER,
69 "import": Number.MAX_SAFE_INTEGER,
70 corr: Number.MAX_SAFE_INTEGER
71 },
72 // hasMore == TRUE: a priori there could be more games to load
73 hasMore: {
74 live: true,
75 "import": true,
76 corr: (store.state.user.id > 0)
77 },
78 conn: null,
79 connexionString: "",
80 socketCloseListener: 0
81 };
82 },
83 watch: {
84 $route: function(to, from) {
85 if (to.path != "/mygames") this.cleanBeforeDestroy();
86 }
87 },
88 created: function() {
89 window.addEventListener("beforeunload", this.cleanBeforeDestroy);
90 // Initialize connection
91 this.connexionString =
92 params.socketUrl +
93 "/?sid=" + this.st.user.sid +
94 "&id=" + this.st.user.id +
95 "&tmpId=" + getRandString() +
96 "&page=" +
97 encodeURIComponent(this.$route.path);
98 this.conn = new WebSocket(this.connexionString);
99 this.conn.onmessage = this.socketMessageListener;
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 );
111 },
112 mounted: function() {
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 };
134 GameStorage.getRunning(localGames => {
135 localGames.forEach(g => g.type = "live");
136 this.decorate(localGames);
137 this.liveGames = localGames;
138 if (this.st.user.id > 0) {
139 // Ask running corr games first
140 ajax(
141 "/runninggames",
142 "GET",
143 {
144 credentials: true,
145 success: (res) => {
146 // These games are garanteed to not be deleted
147 this.corrGames = res.games;
148 this.corrGames.forEach(g => {
149 g.type = "corr";
150 g.score = "*";
151 });
152 this.decorate(this.corrGames);
153 // Now ask completed games (partial list)
154 this.loadMore(
155 "live",
156 () => this.loadMore("corr", adjustAndSetDisplay)
157 );
158 }
159 }
160 );
161 } else this.loadMore("live", adjustAndSetDisplay);
162 });
163 },
164 beforeDestroy: function() {
165 this.cleanBeforeDestroy();
166 },
167 methods: {
168 cleanBeforeDestroy: function() {
169 clearInterval(this.socketCloseListener);
170 window.removeEventListener("beforeunload", this.cleanBeforeDestroy);
171 this.conn.removeEventListener("message", this.socketMessageListener);
172 this.conn.send(JSON.stringify({code: "disconnect"}));
173 this.conn = null;
174 },
175 setDisplay: function(type, e) {
176 this.display = type;
177 localStorage.setItem("type-myGames", type);
178 let elt = e ? e.target : document.getElementById(type + "Games");
179 elt.classList.add("active");
180 elt.classList.remove("somethingnew"); //in case of
181 for (let t of ["live","corr","import"]) {
182 if (t != type)
183 document.getElementById(t + "Games").classList.remove("active");
184 }
185 },
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 },
193 tryShowNewsIndicator: function(type) {
194 if (
195 (type == "live" && this.display != "live") ||
196 (type == "corr" && this.display != "corr")
197 ) {
198 document
199 .getElementById(type + "Games")
200 .classList.add("somethingnew");
201 }
202 },
203 // Called at loading to augment games with myColor + myTurn infos
204 decorate: function(games) {
205 games.forEach(g => {
206 g.myColor =
207 (g.type == "corr" && g.players[0].id == this.st.user.id) ||
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:
212 if (g.score == "*") {
213 const rem = g.movesCount % 2;
214 if ((rem == 0 && g.myColor == 'w') || (rem == 1 && g.myColor == 'b'))
215 g.myTurn = true;
216 }
217 });
218 },
219 socketMessageListener: function(msg) {
220 if (!this.conn) return;
221 const data = JSON.parse(msg.data);
222 // NOTE: no imported games here
223 let gamesArrays = {
224 "corr": this.corrGames,
225 "live": this.liveGames
226 };
227 switch (data.code) {
228 case "notifyturn":
229 case "notifyscore": {
230 const info = data.data;
231 const type = (!!parseInt(info.gid) ? "corr" : "live");
232 let game = gamesArrays[type].find(g => g.id == info.gid);
233 // "notifything" --> "thing":
234 const thing = data.code.substr(6);
235 game[thing] = info[thing];
236 if (thing == "turn") {
237 game.myTurn = !game.myTurn;
238 if (game.myTurn) this.tryShowNewsIndicator(type);
239 } else game.myTurn = false;
240 // TODO: forcing refresh like that is ugly and wrong.
241 // How to do it cleanly?
242 this.$refs[type + "games"].$forceUpdate();
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 : "";
251 const type = (gameInfo.cadence.indexOf('d') >= 0 ? "corr": "live");
252 let game = Object.assign(
253 {
254 vname: vname,
255 type: type,
256 score: "*",
257 created: Date.now()
258 },
259 gameInfo
260 );
261 game.myTurn =
262 (type == "corr" && game.players[0].id == this.st.user.id) ||
263 (type == "live" && game.players[0].sid == this.st.user.sid);
264 gamesArrays[type].push(game);
265 if (game.myTurn) this.tryShowNewsIndicator(type);
266 // TODO: cleaner refresh
267 this.$refs[type + "games"].$forceUpdate();
268 break;
269 }
270 }
271 },
272 showGame: function(game) {
273 if (game.type != "corr" || !game.myTurn) {
274 this.$router.push("/game/" + game.id);
275 return;
276 }
277 // It's my turn in this game. Are there others?
278 let nextIds = "";
279 let otherCorrGamesMyTurn = this.corrGames.filter(g =>
280 g.id != game.id && !!g.myTurn);
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);
288 },
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;
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 }
309 }
310 // NOTE: no imported games here
311 else if (!game.deletedByWhite || !game.deletedByBlack) {
312 // Set score if game isn't deleted on server:
313 ajax(
314 "/games",
315 "PUT",
316 {
317 data: {
318 gid: game.id,
319 newObj: {
320 score: "?",
321 scoreMsg: getScoreMessage("?")
322 }
323 }
324 }
325 );
326 }
327 },
328 loadMore: function(type, cb) {
329 if (type == "corr" && this.st.user.id > 0) {
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 }
347 }
348 );
349 }
350 else if (type == "live") {
351 GameStorage.getNext(this.cursor["live"], localGames => {
352 const L = localGames.length;
353 if (L > 0) {
354 // Add "-1" because IDBKeyRange.upperBound includes boundary
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 }
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 }
375 }
376 }
377 };
378 </script>
379
380 <style lang="sass">
381 .active
382 color: #42a983
383
384 .tabbtn
385 background-color: #f9faee
386
387 table.game-list
388 max-height: 100%
389
390 button#loadMoreBtn
391 display: block
392 margin: 0 auto
393
394 .somethingnew
395 background-color: #c5fefe !important
396 </style>