Better arrows drawing
[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
7ebc0408 56 hasMore: { live: true, corr: store.state.user.id > 0 },
db1f1f9a 57 conn: null,
882ec6fe
BA
58 connexionString: "",
59 socketCloseListener: 0
afd3240d
BA
60 };
61 },
1112f1fd
BA
62 watch: {
63 $route: function(to, from) {
64 if (to.path != "/mygames") this.cleanBeforeDestroy();
65 }
66 },
afd3240d 67 created: function() {
1112f1fd 68 window.addEventListener("beforeunload", this.cleanBeforeDestroy);
db1f1f9a
BA
69 // Initialize connection
70 this.connexionString =
71 params.socketUrl +
7e476ce4
BA
72 "/?sid=" + this.st.user.sid +
73 "&id=" + this.st.user.id +
74 "&tmpId=" + getRandString() +
db1f1f9a
BA
75 "&page=" +
76 encodeURIComponent(this.$route.path);
77 this.conn = new WebSocket(this.connexionString);
78 this.conn.onmessage = this.socketMessageListener;
882ec6fe
BA
79 this.socketCloseListener = setInterval(
80 () => {
81 if (this.conn.readyState == 3) {
82 // Connexion is closed: re-open
83 this.conn.removeEventListener("message", this.socketMessageListener);
84 this.conn = new WebSocket(this.connexionString);
85 this.conn.addEventListener("message", this.socketMessageListener);
86 }
87 },
88 1000
89 );
afd3240d 90 },
2f258c37 91 mounted: function() {
585d0955
BA
92 const adjustAndSetDisplay = () => {
93 // showType is the last type viwed by the user (default)
94 let showType = localStorage.getItem("type-myGames") || "live";
95 // Live games, my turn: highest priority:
96 if (this.liveGames.some(g => !!g.myTurn)) showType = "live";
97 // Then corr games, my turn:
98 else if (this.corrGames.some(g => !!g.myTurn)) showType = "corr";
99 else {
100 // If a listing is empty, try showing the other (if non-empty)
101 const types = ["corr", "live"];
102 for (let i of [0,1]) {
103 if (
104 this[types[i] + "Games"].length > 0 &&
105 this[types[1-i] + "Games"].length == 0
106 ) {
107 showType = types[i];
108 }
109 }
110 }
111 this.setDisplay(showType);
112 };
934f7f70 113 GameStorage.getRunning(localGames => {
585d0955
BA
114 localGames.forEach(g => g.type = "live");
115 this.decorate(localGames);
116 this.liveGames = localGames;
117 if (this.st.user.id > 0) {
0234201f 118 // Ask running corr games first
585d0955 119 ajax(
0234201f 120 "/runninggames",
585d0955
BA
121 "GET",
122 {
f14572c4 123 credentials: true,
585d0955 124 success: (res) => {
0234201f
BA
125 // These games are garanteed to not be deleted
126 this.corrGames = res.games;
f14572c4
BA
127 this.corrGames.forEach(g => {
128 g.type = "corr";
129 g.score = "*";
130 });
0234201f
BA
131 this.decorate(this.corrGames);
132 // Now ask completed games (partial list)
934f7f70
BA
133 this.loadMore(
134 "live",
135 () => this.loadMore("corr", adjustAndSetDisplay)
0234201f 136 );
585d0955
BA
137 }
138 }
139 );
7ebc0408 140 } else this.loadMore("live", adjustAndSetDisplay);
585d0955 141 });
2f258c37 142 },
23ecf008 143 beforeDestroy: function() {
1112f1fd 144 this.cleanBeforeDestroy();
23ecf008 145 },
afd3240d 146 methods: {
1112f1fd 147 cleanBeforeDestroy: function() {
882ec6fe 148 clearInterval(this.socketCloseListener);
1112f1fd 149 window.removeEventListener("beforeunload", this.cleanBeforeDestroy);
68e3aa8c 150 this.conn.removeEventListener("message", this.socketMessageListener);
1112f1fd 151 this.conn.send(JSON.stringify({code: "disconnect"}));
68e3aa8c 152 this.conn = null;
1112f1fd 153 },
2f258c37
BA
154 setDisplay: function(type, e) {
155 this.display = type;
156 localStorage.setItem("type-myGames", type);
6808d7a1 157 let elt = e ? e.target : document.getElementById(type + "Games");
2f258c37 158 elt.classList.add("active");
23ecf008 159 elt.classList.remove("somethingnew"); //in case of
6808d7a1 160 if (elt.previousElementSibling)
2f258c37 161 elt.previousElementSibling.classList.remove("active");
6808d7a1 162 else elt.nextElementSibling.classList.remove("active");
2f258c37 163 },
cafe0166
BA
164 tryShowNewsIndicator: function(type) {
165 if (
166 (type == "live" && this.display == "corr") ||
167 (type == "corr" && this.display == "live")
168 ) {
169 document
170 .getElementById(type + "Games")
171 .classList.add("somethingnew");
172 }
173 },
28b32b4f 174 // Called at loading to augment games with myColor + myTurn infos
e727fe31
BA
175 decorate: function(games) {
176 games.forEach(g => {
6b7b2cf7 177 g.myColor =
0234201f 178 (g.type == "corr" && g.players[0].id == this.st.user.id) ||
6b7b2cf7
BA
179 (g.type == "live" && g.players[0].sid == this.st.user.sid)
180 ? 'w'
181 : 'b';
182 // If game is over, myTurn doesn't exist:
e727fe31 183 if (g.score == "*") {
e727fe31 184 const rem = g.movesCount % 2;
6b7b2cf7 185 if ((rem == 0 && g.myColor == 'w') || (rem == 1 && g.myColor == 'b'))
e727fe31 186 g.myTurn = true;
e727fe31
BA
187 }
188 });
189 },
cafe0166 190 socketMessageListener: function(msg) {
68e3aa8c 191 if (!this.conn) return;
cafe0166 192 const data = JSON.parse(msg.data);
e727fe31
BA
193 let gamesArrays = {
194 "corr": this.corrGames,
195 "live": this.liveGames
196 };
cafe0166 197 switch (data.code) {
cafe0166
BA
198 case "notifyturn":
199 case "notifyscore": {
200 const info = data.data;
e727fe31
BA
201 const type = (!!parseInt(info.gid) ? "corr" : "live");
202 let game = gamesArrays[type].find(g => g.id == info.gid);
cafe0166
BA
203 // "notifything" --> "thing":
204 const thing = data.code.substr(6);
e727fe31 205 game[thing] = info[thing];
585d0955
BA
206 if (thing == "turn") {
207 game.myTurn = !game.myTurn;
208 if (game.myTurn) this.tryShowNewsIndicator(type);
f14572c4 209 } else game.myTurn = false;
585d0955
BA
210 // TODO: forcing refresh like that is ugly and wrong.
211 // How to do it cleanly?
212 this.$refs[type + "games"].$forceUpdate();
cafe0166
BA
213 break;
214 }
215 case "notifynewgame": {
216 const gameInfo = data.data;
217 // st.variants might be uninitialized,
218 // if unlucky and newgame right after connect:
219 const v = this.st.variants.find(v => v.id == gameInfo.vid);
220 const vname = !!v ? v.name : "";
e727fe31
BA
221 const type = (gameInfo.cadence.indexOf('d') >= 0 ? "corr": "live");
222 let game = Object.assign(
cafe0166
BA
223 {
224 vname: vname,
225 type: type,
2a8a94c9 226 score: "*",
e727fe31 227 created: Date.now()
cafe0166
BA
228 },
229 gameInfo
230 );
28b32b4f 231 game.myTurn =
0234201f 232 (type == "corr" && game.players[0].id == this.st.user.id) ||
28b32b4f 233 (type == "live" && game.players[0].sid == this.st.user.sid);
e727fe31 234 gamesArrays[type].push(game);
585d0955
BA
235 if (game.myTurn) this.tryShowNewsIndicator(type);
236 // TODO: cleaner refresh
237 this.$refs[type + "games"].$forceUpdate();
cafe0166
BA
238 break;
239 }
240 }
241 },
feaf1bf7 242 showGame: function(game) {
e727fe31 243 if (game.type == "live" || !game.myTurn) {
feaf1bf7 244 this.$router.push("/game/" + game.id);
620a88ed
BA
245 return;
246 }
feaf1bf7
BA
247 // It's my turn in this game. Are there others?
248 let nextIds = "";
e727fe31
BA
249 let otherCorrGamesMyTurn = this.corrGames.filter(g =>
250 g.id != game.id && !!g.myTurn);
feaf1bf7
BA
251 if (otherCorrGamesMyTurn.length > 0) {
252 nextIds += "/?next=[";
253 otherCorrGamesMyTurn.forEach(g => { nextIds += g.id + ","; });
254 // Remove last comma and close array:
255 nextIds = nextIds.slice(0, -1) + "]";
256 }
257 this.$router.push("/game/" + game.id + nextIds);
db1f1f9a 258 },
aae89b49
BA
259 abortGame: function(game) {
260 // Special "trans-pages" case: from MyGames to Game
261 // TODO: also for corr games? (It's less important)
262 if (game.type == "live") {
263 const oppsid =
264 game.players[0].sid == this.st.user.sid
265 ? game.players[1].sid
266 : game.players[0].sid;
68e3aa8c
BA
267 if (!!this.conn) {
268 this.conn.send(
269 JSON.stringify(
270 {
271 code: "mabort",
272 gid: game.id,
273 // NOTE: target might not be online
274 target: oppsid
275 }
276 )
277 );
278 }
aae89b49
BA
279 }
280 else if (!game.deletedByWhite || !game.deletedByBlack) {
281 // Set score if game isn't deleted on server:
282 ajax(
283 "/games",
284 "PUT",
285 {
e57c4de4
BA
286 data: {
287 gid: game.id,
288 newObj: {
289 score: "?",
290 scoreMsg: getScoreMessage("?")
291 }
aae89b49
BA
292 }
293 }
294 );
295 }
0234201f 296 },
934f7f70 297 loadMore: function(type, cb) {
7ebc0408 298 if (type == "corr" && this.st.user.id > 0) {
934f7f70
BA
299 ajax(
300 "/completedgames",
301 "GET",
302 {
303 credentials: true,
304 data: { cursor: this.cursor["corr"] },
305 success: (res) => {
306 const L = res.games.length;
307 if (L > 0) {
308 this.cursor["corr"] = res.games[L - 1].created;
309 let moreGames = res.games;
310 moreGames.forEach(g => g.type = "corr");
311 this.decorate(moreGames);
312 this.corrGames = this.corrGames.concat(moreGames);
313 } else this.hasMore["corr"] = false;
314 if (!!cb) cb();
315 }
0234201f 316 }
934f7f70
BA
317 );
318 } else if (type == "live") {
319 GameStorage.getNext(this.cursor["live"], localGames => {
320 const L = localGames.length;
321 if (L > 0) {
2c5d7b20 322 // Add "-1" because IDBKeyRange.upperBound includes boundary
934f7f70
BA
323 this.cursor["live"] = localGames[L - 1].created - 1;
324 localGames.forEach(g => g.type = "live");
325 this.decorate(localGames);
326 this.liveGames = this.liveGames.concat(localGames);
327 } else this.hasMore["live"] = false;
328 if (!!cb) cb();
329 });
330 }
6808d7a1
BA
331 }
332 }
afd3240d
BA
333};
334</script>
2f258c37 335
e2590fa8 336<style lang="sass">
2f258c37
BA
337.active
338 color: #42a983
5fe7e71c
BA
339
340.tabbtn
341 background-color: #f9faee
e2590fa8
BA
342
343table.game-list
344 max-height: 100%
23ecf008 345
0234201f 346button#loadMoreBtn
f14572c4
BA
347 display: block
348 margin: 0 auto
0234201f 349
23ecf008
BA
350.somethingnew
351 background-color: #c5fefe !important
2f258c37 352</style>