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