Factorize some duplicated CSS
[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", () => {
157 this.loadMore("import", adjustAndSetDisplay);
158 })
159 );
160 }
161 }
162 );
163 }
164 else {
165 this.loadMore("live", () => {
166 this.loadMore("import", adjustAndSetDisplay);
167 });
168 }
169 });
170 },
171 beforeDestroy: function() {
172 this.cleanBeforeDestroy();
173 },
174 methods: {
175 cleanBeforeDestroy: function() {
176 clearInterval(this.socketCloseListener);
177 window.removeEventListener("beforeunload", this.cleanBeforeDestroy);
178 this.conn.removeEventListener("message", this.socketMessageListener);
179 this.conn.send(JSON.stringify({code: "disconnect"}));
180 this.conn = null;
181 },
182 setDisplay: function(type, e) {
183 this.display = type;
184 localStorage.setItem("type-myGames", type);
185 let elt = e ? e.target : document.getElementById(type + "Games");
186 elt.classList.add("active");
187 elt.classList.remove("somethingnew"); //in case of
188 for (let t of ["live","corr","import"]) {
189 if (t != type)
190 document.getElementById(t + "Games").classList.remove("active");
191 }
192 },
193 addGameImport(game) {
194 game.type = "import";
195 ImportgameStorage.add(game, (err) => {
196 if (!!err) {
197 if (err.message.indexOf("Key already exists") < 0) {
198 alert(this.st.tr["An error occurred. Try again!"]);
199 return;
200 }
201 // NOTE: since a random new ID is generated for imported games,
202 // this error will not occur.
203 else alert(this.st.tr["The game was already imported"]);
204 }
205 this.$router.push("/game/" + game.id);
206 });
207 },
208 tryShowNewsIndicator: function(type) {
209 if (
210 (type == "live" && this.display != "live") ||
211 (type == "corr" && this.display != "corr")
212 ) {
213 document
214 .getElementById(type + "Games")
215 .classList.add("somethingnew");
216 }
217 },
218 // Called at loading to augment games with myColor + myTurn infos
219 decorate: function(games) {
220 games.forEach(g => {
221 g.myColor =
222 (g.type == "corr" && g.players[0].id == this.st.user.id) ||
223 (g.type == "live" && g.players[0].sid == this.st.user.sid)
224 ? 'w'
225 : 'b';
226 // If game is over, myTurn doesn't exist:
227 if (g.score == "*") {
228 const rem = g.movesCount % 2;
229 if ((rem == 0 && g.myColor == 'w') || (rem == 1 && g.myColor == 'b'))
230 g.myTurn = true;
231 }
232 });
233 },
234 socketMessageListener: function(msg) {
235 if (!this.conn) return;
236 const data = JSON.parse(msg.data);
237 // NOTE: no imported games here
238 let gamesArrays = {
239 "corr": this.corrGames,
240 "live": this.liveGames
241 };
242 switch (data.code) {
243 case "notifyturn":
244 case "notifyscore": {
245 const info = data.data;
246 const type = (!!parseInt(info.gid) ? "corr" : "live");
247 let game = gamesArrays[type].find(g => g.id == info.gid);
248 // "notifything" --> "thing":
249 const thing = data.code.substr(6);
250 game[thing] = info[thing];
251 if (thing == "turn") {
252 game.myTurn = !game.myTurn;
253 if (game.myTurn) this.tryShowNewsIndicator(type);
254 } else game.myTurn = false;
255 // TODO: forcing refresh like that is ugly and wrong.
256 // How to do it cleanly?
257 this.$refs[type + "games"].$forceUpdate();
258 break;
259 }
260 case "notifynewgame": {
261 const gameInfo = data.data;
262 // st.variants might be uninitialized,
263 // if unlucky and newgame right after connect:
264 const v = this.st.variants.find(v => v.id == gameInfo.vid);
265 const vname = !!v ? v.name : "";
266 const type = (gameInfo.cadence.indexOf('d') >= 0 ? "corr": "live");
267 let game = Object.assign(
268 {
269 vname: vname,
270 type: type,
271 score: "*",
272 created: Date.now()
273 },
274 gameInfo
275 );
276 game.myTurn =
277 (type == "corr" && game.players[0].id == this.st.user.id) ||
278 (type == "live" && game.players[0].sid == this.st.user.sid);
279 gamesArrays[type].push(game);
280 if (game.myTurn) this.tryShowNewsIndicator(type);
281 // TODO: cleaner refresh
282 this.$refs[type + "games"].$forceUpdate();
283 break;
284 }
285 }
286 },
287 showGame: function(game) {
288 if (game.type != "corr" || !game.myTurn) {
289 this.$router.push("/game/" + game.id);
290 return;
291 }
292 // It's my turn in this game. Are there others?
293 let nextIds = "";
294 let otherCorrGamesMyTurn = this.corrGames.filter(g =>
295 g.id != game.id && !!g.myTurn);
296 if (otherCorrGamesMyTurn.length > 0) {
297 nextIds += "/?next=[";
298 otherCorrGamesMyTurn.forEach(g => { nextIds += g.id + ","; });
299 // Remove last comma and close array:
300 nextIds = nextIds.slice(0, -1) + "]";
301 }
302 this.$router.push("/game/" + game.id + nextIds);
303 },
304 abortGame: function(game) {
305 // Special "trans-pages" case: from MyGames to Game
306 // TODO: also for corr games? (It's less important)
307 if (game.type == "live") {
308 const oppsid =
309 game.players[0].sid == this.st.user.sid
310 ? game.players[1].sid
311 : game.players[0].sid;
312 if (!!this.conn) {
313 this.conn.send(
314 JSON.stringify(
315 {
316 code: "mabort",
317 gid: game.id,
318 // NOTE: target might not be online
319 target: oppsid
320 }
321 )
322 );
323 }
324 }
325 // NOTE: no imported games here
326 else if (!game.deletedByWhite || !game.deletedByBlack) {
327 // Set score if game isn't deleted on server:
328 ajax(
329 "/games",
330 "PUT",
331 {
332 data: {
333 gid: game.id,
334 newObj: {
335 score: "?",
336 scoreMsg: getScoreMessage("?")
337 }
338 }
339 }
340 );
341 }
342 },
343 loadMore: function(type, cb) {
344 if (type == "corr" && this.st.user.id > 0) {
345 ajax(
346 "/completedgames",
347 "GET",
348 {
349 credentials: true,
350 data: { cursor: this.cursor["corr"] },
351 success: (res) => {
352 const L = res.games.length;
353 if (L > 0) {
354 this.cursor["corr"] = res.games[L - 1].created;
355 let moreGames = res.games;
356 moreGames.forEach(g => g.type = "corr");
357 this.decorate(moreGames);
358 this.corrGames = this.corrGames.concat(moreGames);
359 } else this.hasMore["corr"] = false;
360 if (!!cb) cb();
361 }
362 }
363 );
364 }
365 else if (type == "live") {
366 GameStorage.getNext(this.cursor["live"], localGames => {
367 const L = localGames.length;
368 if (L > 0) {
369 // Add "-1" because IDBKeyRange.upperBound includes boundary
370 this.cursor["live"] = localGames[L - 1].created - 1;
371 localGames.forEach(g => g.type = "live");
372 this.decorate(localGames);
373 this.liveGames = this.liveGames.concat(localGames);
374 } else this.hasMore["live"] = false;
375 if (!!cb) cb();
376 });
377 }
378 else if (type == "import") {
379 ImportgameStorage.getNext(this.cursor["import"], importGames => {
380 const L = importGames.length;
381 if (L > 0) {
382 // Add "-1" because IDBKeyRange.upperBound includes boundary
383 this.cursor["import"] = importGames[L - 1].created - 1;
384 importGames.forEach(g => g.type = "import");
385 this.importGames = this.importGames.concat(importGames);
386 } else this.hasMore["import"] = false;
387 if (!!cb) cb();
388 });
389 }
390 }
391 }
392 };
393 </script>
394
395 <style lang="sass" scoped>
396 .active
397 color: #42a983
398
399 .tabbtn
400 background-color: #f9faee
401
402 table.game-list
403 max-height: 100%
404
405 button#loadMoreBtn
406 display: block
407 margin: 0 auto
408
409 .somethingnew
410 background-color: #c5fefe !important
411 </style>