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