Small fixes + early draft of Eightpieces variant
[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 v-show="display=='live'"
12 :games="liveGames"
13 @show-game="showGame"
14 @abortgame="abortGame"
15 )
16 GameList(
17 v-show="display=='corr'"
18 :games="corrGames"
19 @show-game="showGame"
20 @abortgame="abortGame"
21 )
22 </template>
23
24 <script>
25 import { store } from "@/store";
26 import { GameStorage } from "@/utils/gameStorage";
27 import { ajax } from "@/utils/ajax";
28 import { getScoreMessage } from "@/utils/scoring";
29 import params from "@/parameters";
30 import { getRandString } from "@/utils/alea";
31 import GameList from "@/components/GameList.vue";
32 export default {
33 name: "my-my-games",
34 components: {
35 GameList
36 },
37 data: function() {
38 return {
39 st: store.state,
40 display: "live",
41 liveGames: [],
42 corrGames: [],
43 conn: null,
44 connexionString: ""
45 };
46 },
47 created: function() {
48 GameStorage.getAll(true, localGames => {
49 localGames.forEach(g => g.type = "live");
50 this.liveGames = localGames;
51 });
52 if (this.st.user.id > 0) {
53 ajax(
54 "/games",
55 "GET",
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 );
71 }
72 // Initialize connection
73 this.connexionString =
74 params.socketUrl +
75 "/?sid=" +
76 this.st.user.sid +
77 "&id=" +
78 this.st.user.id +
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;
86 },
87 mounted: function() {
88 const showType = localStorage.getItem("type-myGames") || "live";
89 this.setDisplay(showType);
90 },
91 beforeDestroy: function() {
92 this.conn.send(JSON.stringify({code: "disconnect"}));
93 },
94 methods: {
95 setDisplay: function(type, e) {
96 this.display = type;
97 localStorage.setItem("type-myGames", type);
98 let elt = e ? e.target : document.getElementById(type + "Games");
99 elt.classList.add("active");
100 elt.classList.remove("somethingnew"); //in case of
101 if (elt.previousElementSibling)
102 elt.previousElementSibling.classList.remove("active");
103 else elt.nextElementSibling.classList.remove("active");
104 },
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 turn: "w"
146 },
147 gameInfo
148 );
149 // TODO: the new game isn't sorted. Maybe apply a different strategy:
150 // 1) Sort all at loading,
151 // 2) Insert in place when new games arrive,
152 // 3) Change position when score or turn change.
153 // And GameList just show list unsorted.
154 this[type + "Games"].unshift(game);
155 this.tryShowNewsIndicator(type);
156 break;
157 }
158 }
159 },
160 socketCloseListener: function() {
161 this.conn = new WebSocket(this.connexionString);
162 this.conn.addEventListener("message", this.socketMessageListener);
163 this.conn.addEventListener("close", this.socketCloseListener);
164 },
165 showGame: function(game) {
166 // TODO: "isMyTurn" is duplicated (see GameList component). myColor also
167 const isMyTurn = (g) => {
168 if (g.score != "*") return false;
169 const myColor =
170 g.players[0].uid == this.st.user.id ||
171 g.players[0].sid == this.st.user.sid
172 ? "w"
173 : "b";
174 if (!!g.turn) return g.turn == myColor;
175 const rem = g.movesCount % 2;
176 return (
177 (rem == 0 && myColor == "w") ||
178 (rem == 1 && myColor == "b")
179 );
180 };
181 if (game.type == "live" || !isMyTurn(game)) {
182 this.$router.push("/game/" + game.id);
183 return;
184 }
185 // It's my turn in this game. Are there others?
186 let nextIds = "";
187 let otherCorrGamesMyTurn = this.corrGames.filter(
188 g => g.id != game.id && isMyTurn(g));
189 if (otherCorrGamesMyTurn.length > 0) {
190 nextIds += "/?next=[";
191 otherCorrGamesMyTurn.forEach(g => { nextIds += g.id + ","; });
192 // Remove last comma and close array:
193 nextIds = nextIds.slice(0, -1) + "]";
194 }
195 this.$router.push("/game/" + game.id + nextIds);
196 },
197 abortGame: function(game) {
198 // Special "trans-pages" case: from MyGames to Game
199 // TODO: also for corr games? (It's less important)
200 if (game.type == "live") {
201 const oppsid =
202 game.players[0].sid == this.st.user.sid
203 ? game.players[1].sid
204 : game.players[0].sid;
205 this.conn.send(
206 JSON.stringify(
207 {
208 code: "mabort",
209 gid: game.id,
210 // NOTE: target might not be online
211 target: oppsid
212 }
213 )
214 );
215 }
216 else if (!game.deletedByWhite || !game.deletedByBlack) {
217 // Set score if game isn't deleted on server:
218 ajax(
219 "/games",
220 "PUT",
221 {
222 data: {
223 gid: game.id,
224 newObj: {
225 score: "?",
226 scoreMsg: getScoreMessage("?")
227 }
228 }
229 }
230 );
231 }
232 }
233 }
234 };
235 </script>
236
237 <style lang="sass">
238 .active
239 color: #42a983
240
241 .tabbtn
242 background-color: #f9faee
243
244 table.game-list
245 max-height: 100%
246
247 .somethingnew
248 background-color: #c5fefe !important
249 </style>