Fix pieces values and notation for Ball variant. Add quick description of Doublearmy...
[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 GameList(
11 ref="livegames"
12 v-show="display=='live'"
13 :games="liveGames"
14 @show-game="showGame"
15 @abortgame="abortGame"
16 )
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"] }}
29 </template>
30
31 <script>
32 import { store } from "@/store";
33 import { GameStorage } from "@/utils/gameStorage";
34 import { ajax } from "@/utils/ajax";
35 import { getScoreMessage } from "@/utils/scoring";
36 import params from "@/parameters";
37 import { getRandString } from "@/utils/alea";
38 import GameList from "@/components/GameList.vue";
39 export default {
40 name: "my-my-games",
41 components: {
42 GameList
43 },
44 data: function() {
45 return {
46 st: store.state,
47 display: "live",
48 liveGames: [],
49 corrGames: [],
50 // timestamp of last showed (oldest) game:
51 cursor: {
52 live: Number.MAX_SAFE_INTEGER,
53 corr: Number.MAX_SAFE_INTEGER
54 },
55 // hasMore == TRUE: a priori there could be more games to load
56 hasMore: { live: true, corr: store.state.user.id > 0 },
57 conn: null,
58 connexionString: ""
59 };
60 },
61 watch: {
62 $route: function(to, from) {
63 if (to.path != "/mygames") this.cleanBeforeDestroy();
64 }
65 },
66 created: function() {
67 window.addEventListener("beforeunload", this.cleanBeforeDestroy);
68 // Initialize connection
69 this.connexionString =
70 params.socketUrl +
71 "/?sid=" + this.st.user.sid +
72 "&id=" + this.st.user.id +
73 "&tmpId=" + getRandString() +
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;
79 },
80 mounted: function() {
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 };
102 GameStorage.getRunning(localGames => {
103 localGames.forEach(g => g.type = "live");
104 this.decorate(localGames);
105 this.liveGames = localGames;
106 if (this.st.user.id > 0) {
107 // Ask running corr games first
108 ajax(
109 "/runninggames",
110 "GET",
111 {
112 credentials: true,
113 success: (res) => {
114 // These games are garanteed to not be deleted
115 this.corrGames = res.games;
116 this.corrGames.forEach(g => {
117 g.type = "corr";
118 g.score = "*";
119 });
120 this.decorate(this.corrGames);
121 // Now ask completed games (partial list)
122 this.loadMore(
123 "live",
124 () => this.loadMore("corr", adjustAndSetDisplay)
125 );
126 }
127 }
128 );
129 } else this.loadMore("live", adjustAndSetDisplay);
130 });
131 },
132 beforeDestroy: function() {
133 this.cleanBeforeDestroy();
134 },
135 methods: {
136 cleanBeforeDestroy: function() {
137 window.removeEventListener("beforeunload", this.cleanBeforeDestroy);
138 this.conn.removeEventListener("message", this.socketMessageListener);
139 this.conn.removeEventListener("close", this.socketCloseListener);
140 this.conn.send(JSON.stringify({code: "disconnect"}));
141 this.conn = null;
142 },
143 setDisplay: function(type, e) {
144 this.display = type;
145 localStorage.setItem("type-myGames", type);
146 let elt = e ? e.target : document.getElementById(type + "Games");
147 elt.classList.add("active");
148 elt.classList.remove("somethingnew"); //in case of
149 if (elt.previousElementSibling)
150 elt.previousElementSibling.classList.remove("active");
151 else elt.nextElementSibling.classList.remove("active");
152 },
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 },
163 // Called at loading to augment games with myColor + myTurn infos
164 decorate: function(games) {
165 games.forEach(g => {
166 g.myColor =
167 (g.type == "corr" && g.players[0].id == this.st.user.id) ||
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:
172 if (g.score == "*") {
173 const rem = g.movesCount % 2;
174 if ((rem == 0 && g.myColor == 'w') || (rem == 1 && g.myColor == 'b'))
175 g.myTurn = true;
176 }
177 });
178 },
179 socketMessageListener: function(msg) {
180 if (!this.conn) return;
181 const data = JSON.parse(msg.data);
182 let gamesArrays = {
183 "corr": this.corrGames,
184 "live": this.liveGames
185 };
186 switch (data.code) {
187 case "notifyturn":
188 case "notifyscore": {
189 const info = data.data;
190 const type = (!!parseInt(info.gid) ? "corr" : "live");
191 let game = gamesArrays[type].find(g => g.id == info.gid);
192 // "notifything" --> "thing":
193 const thing = data.code.substr(6);
194 game[thing] = info[thing];
195 if (thing == "turn") {
196 game.myTurn = !game.myTurn;
197 if (game.myTurn) this.tryShowNewsIndicator(type);
198 } else game.myTurn = false;
199 // TODO: forcing refresh like that is ugly and wrong.
200 // How to do it cleanly?
201 this.$refs[type + "games"].$forceUpdate();
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 : "";
210 const type = (gameInfo.cadence.indexOf('d') >= 0 ? "corr": "live");
211 let game = Object.assign(
212 {
213 vname: vname,
214 type: type,
215 score: "*",
216 created: Date.now()
217 },
218 gameInfo
219 );
220 game.myTurn =
221 (type == "corr" && game.players[0].id == this.st.user.id) ||
222 (type == "live" && game.players[0].sid == this.st.user.sid);
223 gamesArrays[type].push(game);
224 if (game.myTurn) this.tryShowNewsIndicator(type);
225 // TODO: cleaner refresh
226 this.$refs[type + "games"].$forceUpdate();
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);
235 },
236 showGame: function(game) {
237 if (game.type == "live" || !game.myTurn) {
238 this.$router.push("/game/" + game.id);
239 return;
240 }
241 // It's my turn in this game. Are there others?
242 let nextIds = "";
243 let otherCorrGamesMyTurn = this.corrGames.filter(g =>
244 g.id != game.id && !!g.myTurn);
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);
252 },
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;
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 }
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 {
280 data: {
281 gid: game.id,
282 newObj: {
283 score: "?",
284 scoreMsg: getScoreMessage("?")
285 }
286 }
287 }
288 );
289 }
290 },
291 loadMore: function(type, cb) {
292 if (type == "corr" && this.st.user.id > 0) {
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 }
310 }
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 }
325 }
326 }
327 };
328 </script>
329
330 <style lang="sass">
331 .active
332 color: #42a983
333
334 .tabbtn
335 background-color: #f9faee
336
337 table.game-list
338 max-height: 100%
339
340 button#loadMoreBtn
341 display: block
342 margin: 0 auto
343
344 .somethingnew
345 background-color: #c5fefe !important
346 </style>