MyGames page is now dynamic (experimental, not much tested)
[vchess.git] / client / src / views / MyGames.vue
CommitLineData
afd3240d
BA
1<template lang="pug">
2main
3 .row
4 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
5 .button-group
910d631b
BA
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 v-show="display=='live'"
12 :games="liveGames"
13 @show-game="showGame"
3b0f26c1 14 @abortgame="abortGame"
910d631b
BA
15 )
16 GameList(
17 v-show="display=='corr'"
18 :games="corrGames"
19 @show-game="showGame"
3b0f26c1 20 @abortgame="abortGame"
910d631b 21 )
afd3240d
BA
22</template>
23
24<script>
afd3240d
BA
25import { store } from "@/store";
26import { GameStorage } from "@/utils/gameStorage";
27import { ajax } from "@/utils/ajax";
aae89b49 28import { getScoreMessage } from "@/utils/scoring";
23ecf008
BA
29import params from "@/parameters";
30import { getRandString } from "@/utils/alea";
afd3240d
BA
31import GameList from "@/components/GameList.vue";
32export default {
89021f18 33 name: "my-my-games",
afd3240d 34 components: {
6808d7a1 35 GameList
afd3240d
BA
36 },
37 data: function() {
38 return {
39 st: store.state,
dac39588 40 display: "live",
2f258c37 41 liveGames: [],
db1f1f9a
BA
42 corrGames: [],
43 conn: null,
44 connexionString: ""
afd3240d
BA
45 };
46 },
47 created: function() {
db1f1f9a 48 GameStorage.getAll(true, localGames => {
aae89b49 49 localGames.forEach(g => g.type = "live");
2f258c37 50 this.liveGames = localGames;
afd3240d 51 });
6808d7a1 52 if (this.st.user.id > 0) {
aae89b49
BA
53 ajax(
54 "/games",
55 "GET",
e57c4de4
BA
56 {
57 data: { uid: this.st.user.id },
58 success: (res) => {
59 let serverGames = res.games.filter(g => {
60 const mySide =
61 g.players[0].uid == this.st.user.id
62 ? "White"
63 : "Black";
64 return !g["deletedBy" + mySide];
65 });
66 serverGames.forEach(g => g.type = "corr");
67 this.corrGames = serverGames;
68 }
69 }
70 );
afd3240d 71 }
db1f1f9a
BA
72 // Initialize connection
73 this.connexionString =
74 params.socketUrl +
75 "/?sid=" +
76 this.st.user.sid +
cafe0166
BA
77 "&id=" +
78 this.st.user.id +
db1f1f9a
BA
79 "&tmpId=" +
80 getRandString() +
81 "&page=" +
82 encodeURIComponent(this.$route.path);
83 this.conn = new WebSocket(this.connexionString);
84 this.conn.onmessage = this.socketMessageListener;
85 this.conn.onclose = this.socketCloseListener;
afd3240d 86 },
2f258c37
BA
87 mounted: function() {
88 const showType = localStorage.getItem("type-myGames") || "live";
89 this.setDisplay(showType);
90 },
23ecf008
BA
91 beforeDestroy: function() {
92 this.conn.send(JSON.stringify({code: "disconnect"}));
93 },
afd3240d 94 methods: {
2f258c37
BA
95 setDisplay: function(type, e) {
96 this.display = type;
97 localStorage.setItem("type-myGames", type);
6808d7a1 98 let elt = e ? e.target : document.getElementById(type + "Games");
2f258c37 99 elt.classList.add("active");
23ecf008 100 elt.classList.remove("somethingnew"); //in case of
6808d7a1 101 if (elt.previousElementSibling)
2f258c37 102 elt.previousElementSibling.classList.remove("active");
6808d7a1 103 else elt.nextElementSibling.classList.remove("active");
2f258c37 104 },
cafe0166
BA
105 tryShowNewsIndicator: function(type) {
106 if (
107 (type == "live" && this.display == "corr") ||
108 (type == "corr" && this.display == "live")
109 ) {
110 document
111 .getElementById(type + "Games")
112 .classList.add("somethingnew");
113 }
114 },
115 socketMessageListener: function(msg) {
116 const data = JSON.parse(msg.data);
117 switch (data.code) {
118 // NOTE: no need to increment movesCount: unused if turn is provided
119 case "notifyturn":
120 case "notifyscore": {
121 const info = data.data;
122 let games =
123 !!parseInt(info.gid)
124 ? this.corrGames
125 : this.liveGames;
126 let g = games.find(g => g.id == info.gid);
127 // "notifything" --> "thing":
128 const thing = data.code.substr(6);
129 this.$set(g, thing, info[thing]);
130 this.tryShowNewsIndicator(g.type);
131 break;
132 }
133 case "notifynewgame": {
134 const gameInfo = data.data;
135 // st.variants might be uninitialized,
136 // if unlucky and newgame right after connect:
137 const v = this.st.variants.find(v => v.id == gameInfo.vid);
138 const vname = !!v ? v.name : "";
139 const type = gameInfo.cadence.indexOf('d') >= 0 ? "corr": "live";
140 const game = Object.assign(
141 {
142 vname: vname,
143 type: type,
144 score: "*"
145 },
146 gameInfo
147 );
148 this[type + "Games"].push(game);
149 this.tryShowNewsIndicator(type);
150 break;
151 }
152 }
153 },
154 socketCloseListener: function() {
155 this.conn = new WebSocket(this.connexionString);
156 this.conn.addEventListener("message", this.socketMessageListener);
157 this.conn.addEventListener("close", this.socketCloseListener);
afd3240d 158 },
feaf1bf7
BA
159 showGame: function(game) {
160 // TODO: "isMyTurn" is duplicated (see GameList component). myColor also
161 const isMyTurn = (g) => {
dc821737 162 if (g.score != "*") return false;
feaf1bf7
BA
163 const myColor =
164 g.players[0].uid == this.st.user.id ||
165 g.players[0].sid == this.st.user.sid
166 ? "w"
167 : "b";
168 const rem = g.movesCount % 2;
169 return (
170 (rem == 0 && myColor == "w") ||
171 (rem == 1 && myColor == "b")
172 );
173 };
620a88ed 174 if (game.type == "live" || !isMyTurn(game)) {
feaf1bf7 175 this.$router.push("/game/" + game.id);
620a88ed
BA
176 return;
177 }
feaf1bf7
BA
178 // It's my turn in this game. Are there others?
179 let nextIds = "";
180 let otherCorrGamesMyTurn = this.corrGames.filter(
181 g => g.id != game.id && isMyTurn(g));
182 if (otherCorrGamesMyTurn.length > 0) {
183 nextIds += "/?next=[";
184 otherCorrGamesMyTurn.forEach(g => { nextIds += g.id + ","; });
185 // Remove last comma and close array:
186 nextIds = nextIds.slice(0, -1) + "]";
187 }
188 this.$router.push("/game/" + game.id + nextIds);
db1f1f9a 189 },
aae89b49
BA
190 abortGame: function(game) {
191 // Special "trans-pages" case: from MyGames to Game
192 // TODO: also for corr games? (It's less important)
193 if (game.type == "live") {
194 const oppsid =
195 game.players[0].sid == this.st.user.sid
196 ? game.players[1].sid
197 : game.players[0].sid;
198 this.conn.send(
199 JSON.stringify(
200 {
201 code: "mabort",
202 gid: game.id,
203 // NOTE: target might not be online
204 target: oppsid
205 }
206 )
207 );
208 }
209 else if (!game.deletedByWhite || !game.deletedByBlack) {
210 // Set score if game isn't deleted on server:
211 ajax(
212 "/games",
213 "PUT",
214 {
e57c4de4
BA
215 data: {
216 gid: game.id,
217 newObj: {
218 score: "?",
219 scoreMsg: getScoreMessage("?")
220 }
aae89b49
BA
221 }
222 }
223 );
224 }
6808d7a1
BA
225 }
226 }
afd3240d
BA
227};
228</script>
2f258c37 229
e2590fa8 230<style lang="sass">
2f258c37
BA
231.active
232 color: #42a983
5fe7e71c
BA
233
234.tabbtn
235 background-color: #f9faee
e2590fa8
BA
236
237table.game-list
238 max-height: 100%
23ecf008
BA
239
240.somethingnew
241 background-color: #c5fefe !important
2f258c37 242</style>