Small fixes + early draft of Eightpieces variant
[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,
2a8a94c9
BA
144 score: "*",
145 turn: "w"
cafe0166
BA
146 },
147 gameInfo
148 );
2a8a94c9
BA
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);
cafe0166
BA
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);
afd3240d 164 },
feaf1bf7
BA
165 showGame: function(game) {
166 // TODO: "isMyTurn" is duplicated (see GameList component). myColor also
167 const isMyTurn = (g) => {
dc821737 168 if (g.score != "*") return false;
feaf1bf7
BA
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";
2a8a94c9 174 if (!!g.turn) return g.turn == myColor;
feaf1bf7
BA
175 const rem = g.movesCount % 2;
176 return (
177 (rem == 0 && myColor == "w") ||
178 (rem == 1 && myColor == "b")
179 );
180 };
620a88ed 181 if (game.type == "live" || !isMyTurn(game)) {
feaf1bf7 182 this.$router.push("/game/" + game.id);
620a88ed
BA
183 return;
184 }
feaf1bf7
BA
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);
db1f1f9a 196 },
aae89b49
BA
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 {
e57c4de4
BA
222 data: {
223 gid: game.id,
224 newObj: {
225 score: "?",
226 scoreMsg: getScoreMessage("?")
227 }
aae89b49
BA
228 }
229 }
230 );
231 }
6808d7a1
BA
232 }
233 }
afd3240d
BA
234};
235</script>
2f258c37 236
e2590fa8 237<style lang="sass">
2f258c37
BA
238.active
239 color: #42a983
5fe7e71c
BA
240
241.tabbtn
242 background-color: #f9faee
e2590fa8
BA
243
244table.game-list
245 max-height: 100%
23ecf008
BA
246
247.somethingnew
248 background-color: #c5fefe !important
2f258c37 249</style>