Add unambiguous section in the PGN + some fixes + code formatting and fix typos
[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 socketCloseListener: 0
60 };
61 },
62 watch: {
63 $route: function(to, from) {
64 if (to.path != "/mygames") this.cleanBeforeDestroy();
65 }
66 },
67 created: function() {
68 window.addEventListener("beforeunload", this.cleanBeforeDestroy);
69 // Initialize connection
70 this.connexionString =
71 params.socketUrl +
72 "/?sid=" + this.st.user.sid +
73 "&id=" + this.st.user.id +
74 "&tmpId=" + getRandString() +
75 "&page=" +
76 encodeURIComponent(this.$route.path);
77 this.conn = new WebSocket(this.connexionString);
78 this.conn.onmessage = this.socketMessageListener;
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 );
90 },
91 mounted: function() {
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 };
113 GameStorage.getRunning(localGames => {
114 localGames.forEach(g => g.type = "live");
115 this.decorate(localGames);
116 this.liveGames = localGames;
117 if (this.st.user.id > 0) {
118 // Ask running corr games first
119 ajax(
120 "/runninggames",
121 "GET",
122 {
123 credentials: true,
124 success: (res) => {
125 // These games are garanteed to not be deleted
126 this.corrGames = res.games;
127 this.corrGames.forEach(g => {
128 g.type = "corr";
129 g.score = "*";
130 });
131 this.decorate(this.corrGames);
132 // Now ask completed games (partial list)
133 this.loadMore(
134 "live",
135 () => this.loadMore("corr", adjustAndSetDisplay)
136 );
137 }
138 }
139 );
140 } else this.loadMore("live", adjustAndSetDisplay);
141 });
142 },
143 beforeDestroy: function() {
144 this.cleanBeforeDestroy();
145 },
146 methods: {
147 cleanBeforeDestroy: function() {
148 clearInterval(this.socketCloseListener);
149 window.removeEventListener("beforeunload", this.cleanBeforeDestroy);
150 this.conn.removeEventListener("message", this.socketMessageListener);
151 this.conn.send(JSON.stringify({code: "disconnect"}));
152 this.conn = null;
153 },
154 setDisplay: function(type, e) {
155 this.display = type;
156 localStorage.setItem("type-myGames", type);
157 let elt = e ? e.target : document.getElementById(type + "Games");
158 elt.classList.add("active");
159 elt.classList.remove("somethingnew"); //in case of
160 if (elt.previousElementSibling)
161 elt.previousElementSibling.classList.remove("active");
162 else elt.nextElementSibling.classList.remove("active");
163 },
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 },
174 // Called at loading to augment games with myColor + myTurn infos
175 decorate: function(games) {
176 games.forEach(g => {
177 g.myColor =
178 (g.type == "corr" && g.players[0].id == this.st.user.id) ||
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:
183 if (g.score == "*") {
184 const rem = g.movesCount % 2;
185 if ((rem == 0 && g.myColor == 'w') || (rem == 1 && g.myColor == 'b'))
186 g.myTurn = true;
187 }
188 });
189 },
190 socketMessageListener: function(msg) {
191 if (!this.conn) return;
192 const data = JSON.parse(msg.data);
193 let gamesArrays = {
194 "corr": this.corrGames,
195 "live": this.liveGames
196 };
197 switch (data.code) {
198 case "notifyturn":
199 case "notifyscore": {
200 const info = data.data;
201 const type = (!!parseInt(info.gid) ? "corr" : "live");
202 let game = gamesArrays[type].find(g => g.id == info.gid);
203 // "notifything" --> "thing":
204 const thing = data.code.substr(6);
205 game[thing] = info[thing];
206 if (thing == "turn") {
207 game.myTurn = !game.myTurn;
208 if (game.myTurn) this.tryShowNewsIndicator(type);
209 } else game.myTurn = false;
210 // TODO: forcing refresh like that is ugly and wrong.
211 // How to do it cleanly?
212 this.$refs[type + "games"].$forceUpdate();
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 : "";
221 const type = (gameInfo.cadence.indexOf('d') >= 0 ? "corr": "live");
222 let game = Object.assign(
223 {
224 vname: vname,
225 type: type,
226 score: "*",
227 created: Date.now()
228 },
229 gameInfo
230 );
231 game.myTurn =
232 (type == "corr" && game.players[0].id == this.st.user.id) ||
233 (type == "live" && game.players[0].sid == this.st.user.sid);
234 gamesArrays[type].push(game);
235 if (game.myTurn) this.tryShowNewsIndicator(type);
236 // TODO: cleaner refresh
237 this.$refs[type + "games"].$forceUpdate();
238 break;
239 }
240 }
241 },
242 showGame: function(game) {
243 if (game.type == "live" || !game.myTurn) {
244 this.$router.push("/game/" + game.id);
245 return;
246 }
247 // It's my turn in this game. Are there others?
248 let nextIds = "";
249 let otherCorrGamesMyTurn = this.corrGames.filter(g =>
250 g.id != game.id && !!g.myTurn);
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);
258 },
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;
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 }
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 {
286 data: {
287 gid: game.id,
288 newObj: {
289 score: "?",
290 scoreMsg: getScoreMessage("?")
291 }
292 }
293 }
294 );
295 }
296 },
297 loadMore: function(type, cb) {
298 if (type == "corr" && this.st.user.id > 0) {
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 }
316 }
317 );
318 } else if (type == "live") {
319 GameStorage.getNext(this.cursor["live"], localGames => {
320 const L = localGames.length;
321 if (L > 0) {
322 // Add "-1" because IDBKeyRange.upperBound includes boundary
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 }
331 }
332 }
333 };
334 </script>
335
336 <style lang="sass">
337 .active
338 color: #42a983
339
340 .tabbtn
341 background-color: #f9faee
342
343 table.game-list
344 max-height: 100%
345
346 button#loadMoreBtn
347 display: block
348 margin: 0 auto
349
350 .somethingnew
351 background-color: #c5fefe !important
352 </style>