Fixing attempt: clients now track tmpIds to know who is online/onfocus. Bug fixed...
[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=" +
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 this.loadMore("live", adjustAndSetDisplay);
133 });
134 },
135 beforeDestroy: function() {
136 this.cleanBeforeDestroy();
137 },
138 methods: {
139 cleanBeforeDestroy: function() {
140 window.removeEventListener("beforeunload", this.cleanBeforeDestroy);
141 this.conn.removeEventListener("message", this.socketMessageListener);
142 this.conn.removeEventListener("close", this.socketCloseListener);
143 this.conn.send(JSON.stringify({code: "disconnect"}));
144 this.conn = null;
145 },
146 setDisplay: function(type, e) {
147 this.display = type;
148 localStorage.setItem("type-myGames", type);
149 let elt = e ? e.target : document.getElementById(type + "Games");
150 elt.classList.add("active");
151 elt.classList.remove("somethingnew"); //in case of
152 if (elt.previousElementSibling)
153 elt.previousElementSibling.classList.remove("active");
154 else elt.nextElementSibling.classList.remove("active");
155 },
156 tryShowNewsIndicator: function(type) {
157 if (
158 (type == "live" && this.display == "corr") ||
159 (type == "corr" && this.display == "live")
160 ) {
161 document
162 .getElementById(type + "Games")
163 .classList.add("somethingnew");
164 }
165 },
166 // Called at loading to augment games with myColor + myTurn infos
167 decorate: function(games) {
168 games.forEach(g => {
169 g.myColor =
170 (g.type == "corr" && g.players[0].id == this.st.user.id) ||
171 (g.type == "live" && g.players[0].sid == this.st.user.sid)
172 ? 'w'
173 : 'b';
174 // If game is over, myTurn doesn't exist:
175 if (g.score == "*") {
176 const rem = g.movesCount % 2;
177 if ((rem == 0 && g.myColor == 'w') || (rem == 1 && g.myColor == 'b'))
178 g.myTurn = true;
179 }
180 });
181 },
182 socketMessageListener: function(msg) {
183 if (!this.conn) return;
184 const data = JSON.parse(msg.data);
185 let gamesArrays = {
186 "corr": this.corrGames,
187 "live": this.liveGames
188 };
189 switch (data.code) {
190 case "notifyturn":
191 case "notifyscore": {
192 const info = data.data;
193 const type = (!!parseInt(info.gid) ? "corr" : "live");
194 let game = gamesArrays[type].find(g => g.id == info.gid);
195 // "notifything" --> "thing":
196 const thing = data.code.substr(6);
197 game[thing] = info[thing];
198 if (thing == "turn") {
199 game.myTurn = !game.myTurn;
200 if (game.myTurn) this.tryShowNewsIndicator(type);
201 } else game.myTurn = false;
202 // TODO: forcing refresh like that is ugly and wrong.
203 // How to do it cleanly?
204 this.$refs[type + "games"].$forceUpdate();
205 break;
206 }
207 case "notifynewgame": {
208 const gameInfo = data.data;
209 // st.variants might be uninitialized,
210 // if unlucky and newgame right after connect:
211 const v = this.st.variants.find(v => v.id == gameInfo.vid);
212 const vname = !!v ? v.name : "";
213 const type = (gameInfo.cadence.indexOf('d') >= 0 ? "corr": "live");
214 let game = Object.assign(
215 {
216 vname: vname,
217 type: type,
218 score: "*",
219 created: Date.now()
220 },
221 gameInfo
222 );
223 game.myTurn =
224 (type == "corr" && game.players[0].id == this.st.user.id) ||
225 (type == "live" && game.players[0].sid == this.st.user.sid);
226 gamesArrays[type].push(game);
227 if (game.myTurn) this.tryShowNewsIndicator(type);
228 // TODO: cleaner refresh
229 this.$refs[type + "games"].$forceUpdate();
230 break;
231 }
232 }
233 },
234 socketCloseListener: function() {
235 this.conn = new WebSocket(this.connexionString);
236 this.conn.addEventListener("message", this.socketMessageListener);
237 this.conn.addEventListener("close", this.socketCloseListener);
238 },
239 showGame: function(game) {
240 if (game.type == "live" || !game.myTurn) {
241 this.$router.push("/game/" + game.id);
242 return;
243 }
244 // It's my turn in this game. Are there others?
245 let nextIds = "";
246 let otherCorrGamesMyTurn = this.corrGames.filter(g =>
247 g.id != game.id && !!g.myTurn);
248 if (otherCorrGamesMyTurn.length > 0) {
249 nextIds += "/?next=[";
250 otherCorrGamesMyTurn.forEach(g => { nextIds += g.id + ","; });
251 // Remove last comma and close array:
252 nextIds = nextIds.slice(0, -1) + "]";
253 }
254 this.$router.push("/game/" + game.id + nextIds);
255 },
256 abortGame: function(game) {
257 // Special "trans-pages" case: from MyGames to Game
258 // TODO: also for corr games? (It's less important)
259 if (game.type == "live") {
260 const oppsid =
261 game.players[0].sid == this.st.user.sid
262 ? game.players[1].sid
263 : game.players[0].sid;
264 if (!!this.conn) {
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 }
277 else if (!game.deletedByWhite || !game.deletedByBlack) {
278 // Set score if game isn't deleted on server:
279 ajax(
280 "/games",
281 "PUT",
282 {
283 data: {
284 gid: game.id,
285 newObj: {
286 score: "?",
287 scoreMsg: getScoreMessage("?")
288 }
289 }
290 }
291 );
292 }
293 },
294 loadMore: function(type, cb) {
295 if (type == "corr" && this.st.user.id > 0) {
296 ajax(
297 "/completedgames",
298 "GET",
299 {
300 credentials: true,
301 data: { cursor: this.cursor["corr"] },
302 success: (res) => {
303 const L = res.games.length;
304 if (L > 0) {
305 this.cursor["corr"] = res.games[L - 1].created;
306 let moreGames = res.games;
307 moreGames.forEach(g => g.type = "corr");
308 this.decorate(moreGames);
309 this.corrGames = this.corrGames.concat(moreGames);
310 } else this.hasMore["corr"] = false;
311 if (!!cb) cb();
312 }
313 }
314 );
315 } else if (type == "live") {
316 GameStorage.getNext(this.cursor["live"], localGames => {
317 const L = localGames.length;
318 if (L > 0) {
319 // Add "-1" because IDBKeyRange.upperBound seems to include boundary
320 this.cursor["live"] = localGames[L - 1].created - 1;
321 localGames.forEach(g => g.type = "live");
322 this.decorate(localGames);
323 this.liveGames = this.liveGames.concat(localGames);
324 } else this.hasMore["live"] = false;
325 if (!!cb) cb();
326 });
327 }
328 }
329 }
330 };
331 </script>
332
333 <style lang="sass">
334 .active
335 color: #42a983
336
337 .tabbtn
338 background-color: #f9faee
339
340 table.game-list
341 max-height: 100%
342
343 button#loadMoreBtn
344 display: block
345 margin: 0 auto
346
347 .somethingnew
348 background-color: #c5fefe !important
349 </style>