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