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