Some thoughts in views/Hall.js
[vchess.git] / client / src / views / Hall.vue
CommitLineData
ccd4a2b7 1<template lang="pug">
9d58ef95 2main
5b020e73
BA
3 input#modalNewgame.modal(type="checkbox")
4 div(role="dialog" aria-labelledby="titleFenedit")
5 .card.smallpad
6 label#closeNewgame.modal-close(for="modalNewgame")
7 fieldset
8 label(for="selectVariant") {{ st.tr["Variant"] }}
9d58ef95 9 select#selectVariant(v-model="newchallenge.vid")
85e5b5c1 10 option(v-for="v in st.variants" :value="v.id") {{ v.name }}
5b020e73 11 fieldset
b4d619d1 12 label(for="timeControl") {{ st.tr["Time control"] }}
9d58ef95 13 input#timeControl(type="text" v-model="newchallenge.timeControl"
b4d619d1
BA
14 placeholder="3m+2s, 1h+30s, 7d+1d ...")
15 fieldset(v-if="st.user.id > 0")
9d58ef95 16 label(for="selectPlayers") {{ st.tr["Play with? (optional)"] }}
6fba6e0c 17 input#selectPlayers(type="text" v-model="newchallenge.to")
b4d619d1 18 fieldset(v-if="st.user.id > 0")
9d58ef95
BA
19 label(for="inputFen") {{ st.tr["FEN (optional)"] }}
20 input#inputFen(type="text" v-model="newchallenge.fen")
b4d619d1 21 button(@click="newChallenge") {{ st.tr["Send challenge"] }}
9d58ef95
BA
22 .row
23 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
24 button(onClick="doClick('modalNewgame')") New game
25 .row
1efe1d79 26 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
6855163c
BA
27 .collapse
28 input#challengeSection(type="radio" checked aria-hidden="true" name="accordion")
29 label(for="challengeSection" aria-hidden="true") Challenges
30 div
31 .button-group
32 button(@click="cdisplay='live'") Live Challenges
33 button(@click="cdisplay='corr'") Correspondance challenges
34 ChallengeList(v-show="cdisplay=='live'"
35 :challenges="filterChallenges('live')" @click-challenge="clickChallenge")
36 ChallengeList(v-show="cdisplay=='corr'"
37 :challenges="filterChallenges('corr')" @click-challenge="clickChallenge")
1efe1d79 38 input#peopleSection(type="radio" aria-hidden="true" name="accordion")
6855163c
BA
39 label(for="peopleSection" aria-hidden="true") People
40 div
1efe1d79
BA
41 .button-group
42 button(@click="pdisplay='players'") Players
43 button(@click="pdisplay='chat'") Chat
6855163c
BA
44 #players(v-show="pdisplay=='players'")
45 h3 Online players
46 .player(v-for="p in uniquePlayers" @click="tryChallenge(p)"
47 :class="{anonymous: !!p.count}"
48 )
49 | {{ p.name + (!!p.count ? " ("+p.count+")" : "") }}
50 #chat(v-show="pdisplay=='chat'")
51 h3 Chat (TODO)
1efe1d79 52 input#gameSection(type="radio" aria-hidden="true" name="accordion")
6855163c
BA
53 label(for="gameSection" aria-hidden="true") Games
54 div
55 .button-group
56 button(@click="gdisplay='live'") Live games
57 button(@click="gdisplay='corr'") Correspondance games
58 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
59 @show-game="showGame")
60 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
61 @show-game="showGame")
625022fd
BA
62</template>
63
64<script>
5b020e73 65import { store } from "@/store";
9d58ef95
BA
66import { checkChallenge } from "@/data/challengeCheck";
67import { ArrayFun } from "@/utils/array";
03608482 68import { ajax } from "@/utils/ajax";
4b0384fa 69import { getRandString, shuffle } from "@/utils/alea";
5b020e73
BA
70import GameList from "@/components/GameList.vue";
71import ChallengeList from "@/components/ChallengeList.vue";
967a2686
BA
72import { GameStorage } from "@/utils/gameStorage";
73import { extractTime } from "@/utils/timeControl";
625022fd 74export default {
cf2343ce 75 name: "my-hall",
5b020e73
BA
76 components: {
77 GameList,
78 ChallengeList,
79 },
fb54f098
BA
80 data: function () {
81 return {
5b020e73 82 st: store.state,
6855163c
BA
83 cdisplay: "live", //or corr
84 pdisplay: "players", //or chat
fb54f098 85 gdisplay: "live",
6855163c 86 games: [],
b4d619d1 87 challenges: [],
6fba6e0c 88 people: [], //(all) online players
9d58ef95 89 newchallenge: {
fb54f098
BA
90 fen: "",
91 vid: 0,
6fba6e0c 92 to: "", //name of challenged player (if any)
6faa92f2 93 timeControl: "", //"2m+2s" ...etc
fb54f098
BA
94 },
95 };
96 },
b4d619d1
BA
97 computed: {
98 uniquePlayers: function() {
6855163c 99 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
4d64881e
BA
100 let anonymous = {id:0, name:"@nonymous", count:0};
101 let playerList = [];
6fba6e0c 102 this.people.forEach(p => {
b4d619d1
BA
103 if (p.id > 0)
104 playerList.push(p);
105 else
4d64881e 106 anonymous.count++;
b4d619d1 107 });
4d64881e
BA
108 if (anonymous.count > 0)
109 playerList.push(anonymous);
b4d619d1
BA
110 return playerList;
111 },
112 },
9d58ef95 113 created: function() {
4d64881e 114 // Always add myself to players' list
6fba6e0c 115 this.people.push(this.st.user);
f6f2bef1
BA
116 // Retrieve live challenge (not older than 30 minute) if any:
117 const chall = JSON.parse(localStorage.getItem("challenge") || "false");
118 if (!!chall)
119 {
120 if ((Date.now() - chall.added)/1000 <= 30*60)
121 this.challenges.push(chall);
122 else
123 localStorage.removeItem("challenge");
124 }
98f48579
BA
125 if (this.st.user.id > 0)
126 {
5d04793e
BA
127 // Ask server for current corr games (all but mines)
128 ajax(
129 "/games",
130 "GET",
131 {uid: this.st.user.id, excluded: true},
132 response => {
25996aed
BA
133 this.games = this.games.concat(response.games.map(g => {
134 const tc =
135 return Object.assign({}, g, {mainT
136 });
5d04793e
BA
137 }
138 );
139 // Also ask for corr challenges (open + sent to me)
98f48579
BA
140 ajax(
141 "/challenges",
142 "GET",
143 {uid: this.st.user.id},
144 response => {
145 console.log(response.challenges);
146 // TODO: post-treatment on challenges ?
40477190 147 Array.prototype.push.apply(this.challenges, response.challenges);
98f48579
BA
148 }
149 );
150 }
2ada153c 151 // 0.1] Ask server for room composition:
7b01e447 152 const funcPollClients = () => {
81d9ce72 153 this.st.conn.send(JSON.stringify({code:"pollclients"}));
4d64881e 154 };
7b01e447
BA
155 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
156 funcPollClients();
157 else //socket not ready yet (initial loading)
3cb412e9 158 this.st.conn.onopen = funcPollClients;
4d64881e
BA
159 this.st.conn.onmessage = this.socketMessageListener;
160 const socketCloseListener = () => {
cdb34c93 161 store.socketCloseListener(); //reinitialize connexion (in store.js)
4d64881e
BA
162 this.st.conn.addEventListener('message', this.socketMessageListener);
163 this.st.conn.addEventListener('close', socketCloseListener);
164 };
165 this.st.conn.onclose = socketCloseListener;
9d58ef95 166 },
fb54f098 167 methods: {
a6bddfc6 168 // Helpers:
6855163c
BA
169 filterChallenges: function(type) {
170 return this.challenges.filter(c => c.type == type);
171 },
172 filterGames: function(type) {
173 return this.games.filter(c => c.type == type);
174 },
2ada153c 175 classifyObject: function(o) { //challenge or game
6855163c 176 // Heuristic: should work for most cases... (TODO)
2ada153c 177 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
6855163c 178 },
2ada153c 179 showGame: function(g) {
5bd05dba 180 // NOTE: we are an observer, since only games I don't play are shown here
2ada153c 181 // ==> Moves sent by connected remote player(s) if live game
d9b86b16 182 let url = "/game/" + g.id;
2ada153c
BA
183 if (g.type == "live")
184 {
d9b86b16
BA
185 const remotes = g.players.filter(p => this.people.some(pl => pl.sid == p.sid));
186 const rIdx = (remotes.length == 1 ? 0 : Math.floor(Math.random()*2));
187 url += "?rid=" + remotes[rIdx].sid;
2ada153c
BA
188 }
189 this.$router.push(url);
a6bddfc6 190 },
a7808884 191 // TODO: ...filter(...)[0].name, one-line, just remove this function
a6bddfc6
BA
192 getVname: function(vid) {
193 const vIdx = this.st.variants.findIndex(v => v.id == vid);
194 return this.st.variants[vIdx].name;
195 },
196 getSid: function(pname) {
6fba6e0c
BA
197 const pIdx = this.people.findIndex(pl => pl.name == pname);
198 return (pIdx === -1 ? null : this.people[pIdx].sid);
a6bddfc6 199 },
5bd05dba 200 getPname: function(sid) {
6fba6e0c
BA
201 const pIdx = this.people.findIndex(pl => pl.sid == sid);
202 return (pIdx === -1 ? null : this.people[pIdx].name);
5bd05dba 203 },
a6bddfc6
BA
204 sendSomethingTo: function(to, code, obj, warnDisconnected) {
205 const doSend = (code, obj, sid) => {
206 this.st.conn.send(JSON.stringify(Object.assign(
207 {},
208 {code: code},
209 obj,
210 {target: sid}
211 )));
212 };
c9695cb1 213 if (!!to)
a6bddfc6 214 {
c9695cb1
BA
215 // Challenge with targeted players
216 const targetSid = this.getSid(to);
217 if (!targetSid)
218 {
219 if (!!warnDisconnected)
220 alert("Warning: " + pname + " is not connected");
221 }
222 else
223 doSend(code, obj, targetSid);
a6bddfc6
BA
224 }
225 else
226 {
227 // Open challenge: send to all connected players (except us)
6fba6e0c 228 this.people.forEach(p => {
a6bddfc6
BA
229 if (p.sid != this.st.user.sid) //only sid is always set
230 doSend(code, obj, p.sid);
231 });
232 }
233 },
234 // Messaging center:
9d58ef95
BA
235 socketMessageListener: function(msg) {
236 const data = JSON.parse(msg.data);
237 switch (data.code)
238 {
f4f4c03c 239 // 0.2] Receive clients list (just socket IDs)
81d9ce72 240 case "pollclients":
1efe1d79 241 {
5a3da968 242 data.sockIds.forEach(sid => {
6fba6e0c 243 this.people.push({sid:sid, id:0, name:""});
81d9ce72 244 // Ask identity, challenges and game(s)
5a3da968 245 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
2ada153c 246 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
81d9ce72 247 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
5a3da968
BA
248 });
249 break;
1efe1d79 250 }
81d9ce72 251 case "askidentity":
1efe1d79 252 {
6855163c
BA
253 // Request for identification: reply if I'm not anonymous
254 if (this.st.user.id > 0)
255 {
256 this.st.conn.send(JSON.stringify(
257 {code:"identity", user:this.st.user, target:data.from}));
258 }
5a3da968 259 break;
1efe1d79 260 }
dd75774d 261 case "askchallenge":
1efe1d79 262 {
6855163c 263 // Send my current live challenge (if any)
dd75774d 264 const cIdx = this.challenges
6855163c 265 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
dd75774d
BA
266 if (cIdx >= 0)
267 {
268 const c = this.challenges[cIdx];
269 const myChallenge =
270 {
81d9ce72 271 // Minimal challenge informations: (from not required)
2ada153c 272 id: c.id,
81d9ce72
BA
273 to: c.to,
274 fen: c.fen,
275 vid: c.vid,
276 timeControl: c.timeControl
dd75774d
BA
277 };
278 this.st.conn.send(JSON.stringify({code:"challenge",
42c15a75 279 chall:myChallenge, target:data.from}));
81d9ce72
BA
280 }
281 break;
1efe1d79 282 }
81d9ce72 283 case "askgame":
1efe1d79 284 {
42c15a75
BA
285 // Send my current live game (if any)
286 GameStorage.getCurrent((game) => {
287 if (!!game)
288 {
289 const myGame =
290 {
291 // Minimal game informations:
292 id: game.id,
293 players: game.players.map(p => p.name),
294 vname: game.vname,
295 timeControl: game.timeControl,
296 };
297 this.st.conn.send(JSON.stringify({code:"game",
298 game:myGame, target:data.from}));
299 }
300 });
81d9ce72 301 break;
1efe1d79 302 }
5a3da968 303 case "identity":
1efe1d79 304 {
6fba6e0c
BA
305 const pIdx = this.people.findIndex(p => p.sid == data.user.sid);
306 this.people[pIdx].id = data.user.id;
307 this.people[pIdx].name = data.user.name;
5a3da968 308 break;
1efe1d79 309 }
dd75774d 310 case "challenge":
1efe1d79 311 {
dd75774d 312 // Receive challenge from some player (+sid)
6855163c 313 let newChall = data.chall;
2ada153c 314 newChall.type = this.classifyObject(data.chall);
6fba6e0c
BA
315 const pIdx = this.people.findIndex(p => p.sid == data.from);
316 newChall.from = this.people[pIdx]; //may be anonymous
42c15a75 317 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
25996aed 318 newChall.vname = this.getVname(newChall.vid);
6855163c 319 this.challenges.push(newChall);
81d9ce72 320 break;
1efe1d79 321 }
dd75774d 322 case "game":
1efe1d79 323 {
6855163c 324 // Receive game from some player (+sid)
6855163c 325 // NOTE: it may be correspondance (if newgame while we are connected)
d9b86b16
BA
326 if (!this.games.some(g => g.id == data.game.id)) //ignore duplicates
327 {
328 let newGame = data.game;
329 newGame.type = this.classifyObject(data.game);
330 newGame.rid = data.from;
331 newGame.score = "*";
332 this.games.push(newGame);
333 }
81d9ce72 334 break;
1efe1d79 335 }
9d58ef95 336 case "newgame":
1efe1d79 337 {
5d04793e
BA
338 // New game just started: data contain all information
339 if (data.gameInfo.type == "live")
340 {
341 this.startNewGame(data.gameInfo);
342 // TODO: redirect to game
343 }
344 else
345 {
346 // TODO: notify with game link but do not redirect
347 }
9d58ef95 348 break;
1efe1d79 349 }
bb7dd7db
BA
350 case "refusechallenge":
351 {
485fccd5 352 alert(this.getPname(data.from) + " declined your challenge");
5bd05dba 353 ArrayFun.remove(this.challenges, c => c.id == data.cid);
bb7dd7db
BA
354 break;
355 }
1efe1d79
BA
356 case "deletechallenge":
357 {
1ba761c8 358 // NOTE: the challenge may be already removed
9d58ef95
BA
359 ArrayFun.remove(this.challenges, c => c.id == data.cid);
360 break;
1efe1d79 361 }
b4d619d1 362 case "connect":
1efe1d79 363 {
6fba6e0c 364 this.people.push({name:"", id:0, sid:data.sid});
5a3da968 365 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
f05815d7
BA
366 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.sid}));
367 this.st.conn.send(JSON.stringify({code:"askgame", target:data.sid}));
9d58ef95 368 break;
1efe1d79 369 }
b4d619d1 370 case "disconnect":
1efe1d79 371 {
6fba6e0c 372 ArrayFun.remove(this.people, p => p.sid == data.sid);
a6bddfc6 373 // Also remove all challenges sent by this player:
2ada153c
BA
374 ArrayFun.remove(this.challenges, c => c.from.sid == data.sid);
375 // And all live games where he plays and no other opponent is online
376 ArrayFun.remove(this.games, g =>
377 g.type == "live" && (g.players.every(p => p.sid == data.sid
6fba6e0c 378 || !this.people.some(pl => pl.sid == p.sid))), "all");
9d58ef95 379 break;
1efe1d79 380 }
9d58ef95
BA
381 }
382 },
a6bddfc6 383 // Challenge lifecycle:
b4d619d1
BA
384 tryChallenge: function(player) {
385 if (player.id == 0)
386 return; //anonymous players cannot be challenged
a7808884 387 this.newchallenge.to = player.name;
b4d619d1 388 doClick("modalNewgame");
fb54f098 389 },
9d58ef95 390 newChallenge: async function() {
bb7dd7db 391 const vname = this.getVname(this.newchallenge.vid);
1efe1d79
BA
392 const vModule = await import("@/variants/" + vname + ".js");
393 window.V = vModule.VariantRules;
9d58ef95
BA
394 const error = checkChallenge(this.newchallenge);
395 if (!!error)
396 return alert(error);
2ada153c 397 const ctype = this.classifyObject(this.newchallenge);
bb7dd7db 398 // NOTE: "from" information is not required here
a7808884 399 let chall = Object.assign({}, this.newchallenge);
2ada153c 400 const finishAddChallenge = (cid,warnDisconnected) => {
1efe1d79 401 chall.id = cid || "c" + getRandString();
2ada153c 402 // Send challenge to peers (if connected)
c9695cb1 403 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
1efe1d79 404 chall.added = Date.now();
bb7dd7db
BA
405 chall.type = ctype;
406 chall.vname = vname;
25996aed
BA
407
408
409
410
411// TODO: vname and type are redundant (can be deduced from timeControl + vid)
412
413
414
415
bb7dd7db 416 chall.from = this.st.user;
1efe1d79 417 this.challenges.push(chall);
f6f2bef1 418 localStorage.setItem("challenge", JSON.stringify(chall));
b4d619d1
BA
419 document.getElementById("modalNewgame").checked = false;
420 };
1efe1d79
BA
421 const cIdx = this.challenges.findIndex(
422 c => c.from.sid == this.st.user.sid && c.type == ctype);
423 if (cIdx >= 0)
b4d619d1 424 {
1efe1d79 425 // Delete current challenge (will be replaced now)
bb7dd7db 426 this.sendSomethingTo(this.challenges[cIdx].to,
1efe1d79
BA
427 "deletechallenge", {cid:this.challenges[cIdx].id});
428 if (ctype == "corr")
429 {
430 ajax(
431 "/challenges",
432 "DELETE",
433 {id: this.challenges[cIdx].id}
434 );
435 }
436 this.challenges.splice(cIdx, 1);
437 }
438 if (ctype == "live")
439 {
440 // Live challenges have a random ID
2ada153c 441 finishAddChallenge(null, "warnDisconnected");
03608482 442 }
b4d619d1 443 else
03608482 444 {
b4d619d1 445 // Correspondance game: send challenge to server
03608482 446 ajax(
1efe1d79 447 "/challenges",
03608482 448 "POST",
052d17ea 449 chall,
1efe1d79 450 response => { finishAddChallenge(response.cid); }
03608482 451 );
9d58ef95 452 }
fb54f098 453 },
a6bddfc6 454 clickChallenge: function(c) {
485fccd5
BA
455 const myChallenge = (c.from.sid == this.st.user.sid //live
456 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
457 if (!myChallenge)
a6bddfc6
BA
458 {
459 c.accepted = true;
485fccd5 460 if (!!c.to) //c.to == this.st.user.name (connected)
a6bddfc6
BA
461 {
462 // TODO: if special FEN, show diagram after loading variant
463 c.accepted = confirm("Accept challenge?");
464 }
485fccd5 465 if (c.accepted)
36093eba 466 {
485fccd5
BA
467 c.seat = this.st.user;
468 this.launchGame(c);
469 }
470 else
471 {
472 this.st.conn.send(JSON.stringify({
473 code: "refusechallenge",
474 cid: c.id, target: c.from.sid}));
36093eba 475 }
a6bddfc6 476 }
3cb412e9
BA
477 else
478 localStorage.removeItem("challenge");
485fccd5
BA
479 // In all cases, the challenge is consumed:
480 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
481 // NOTE: deletechallenge event might be redundant (but it's easier this way)
482 this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
483 if (c.type == "corr")
484 {
485 ajax(
486 "/challenges",
487 "DELETE",
488 {id: this.challenges[cIdx].id}
489 );
490 }
a6bddfc6 491 },
485fccd5 492 // NOTE: when launching game, the challenge is already deleted
36093eba 493 launchGame: async function(c) {
a6bddfc6
BA
494 const vname = this.getVname(c.vid);
495 const vModule = await import("@/variants/" + vname + ".js");
496 window.V = vModule.VariantRules;
4b0384fa
BA
497 // These game informations will be sent to other players
498 const gameInfo =
a6bddfc6 499 {
4b0384fa 500 gameId: getRandString(),
a6bddfc6 501 fen: c.fen || V.GenRandInitFen(),
5d04793e 502 players: shuffle([c.from, c.seat]), //white then black
a6bddfc6 503 vid: c.vid,
a7808884 504 timeControl: tc.timeControl,
a6bddfc6 505 };
6fba6e0c 506 this.st.conn.send(JSON.stringify({code:"newgame",
485fccd5
BA
507 gameInfo:gameInfo, target:c.seat.sid}));
508 if (c.type == "live")
509 this.startNewGame(gameInfo);
510 else //corr: game only on server
511 {
512 ajax(
513 "/games",
514 "POST",
515 {gameInfo: gameInfo}
516 );
517 }
fb54f098 518 },
7b626bdd 519 // NOTE: for live games only (corr games are launched on server)
42c15a75 520 startNewGame: function(gameInfo) {
25996aed
BA
521 // Extract times (in [milli]seconds), set clocks
522 const tc = extractTime(c.timeControl);
523 const game = Object.assign({}, gameInfo, {
524 // (other) Game infos: constant
6d01bb17 525 fenStart: gameInfo.fen,
25996aed 526 // Game state (including FEN): will be updated
967a2686 527 moves: [],
a7808884
BA
528 clocks: [tc.mainTime, tc.mainTime],
529 initime: [Date.now(), 0],
967a2686 530 score: "*",
a7808884 531 });
967a2686 532 GameStorage.add(game);
7b626bdd
BA
533 if (this.st.settings.sound >= 1)
534 new Audio("/sounds/newgame.mp3").play().catch(err => {});
a6088c90 535 // TODO: redirect to game
1efe1d79 536 },
fb54f098 537 },
85e5b5c1 538};
ccd4a2b7 539</script>
85e5b5c1
BA
540
541<style lang="sass">
542// TODO
543</style>