3 input#modalInfo.modal(type="checkbox")
4 div#infoDiv(role="dialog" data-checkbox="modalInfo")
6 label.modal-close(for="modalInfo")
7 p(v-html="infoMessage")
8 input#modalNewgame.modal(type="checkbox")
9 div#newgameDiv(role="dialog" data-checkbox="modalNewgame")
10 .card(@keyup.enter="newChallenge()")
11 label#closeNewgame.modal-close(for="modalNewgame")
13 label(for="selectVariant") {{ st.tr["Variant"] }} *
14 select#selectVariant(v-model="newchallenge.vid")
15 option(v-for="v in st.variants" :value="v.id"
16 :selected="newchallenge.vid==v.id")
19 label(for="cadence") {{ st.tr["Cadence"] }} *
20 div#predefinedCadences
24 input#cadence(type="text" v-model="newchallenge.cadence"
25 placeholder="5+0, 1h+30s, 7d+1d ...")
26 fieldset(v-if="st.user.id > 0")
27 label(for="selectPlayers") {{ st.tr["Play with?"] }}
28 input#selectPlayers(type="text" v-model="newchallenge.to")
29 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
30 label(for="inputFen") FEN
31 input#inputFen(type="text" v-model="newchallenge.fen")
32 button(@click="newChallenge()") {{ st.tr["Send challenge"] }}
35 button#newGame(onClick="doClick('modalNewgame')") {{ st.tr["New game"] }}
37 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
40 button#btnClive(@click="setDisplay('c','live',$event)" class="active")
41 | {{ st.tr["Live challenges"] }}
42 button#btnCcorr(@click="setDisplay('c','corr',$event)")
43 | {{ st.tr["Correspondance challenges"] }}
44 ChallengeList(v-show="cdisplay=='live'"
45 :challenges="filterChallenges('live')" @click-challenge="clickChallenge")
46 ChallengeList(v-show="cdisplay=='corr'"
47 :challenges="filterChallenges('corr')" @click-challenge="clickChallenge")
49 h3.text-center {{ st.tr["Who's there?"] }}
51 p(v-for="sid in Object.keys(people)" v-if="!!people[sid].name")
52 span {{ people[sid].name }}
53 button.player-action(v-if="showPlayerActionBtn(sid)" @click="challOrWatch(sid)")
54 | {{ getActionLabel(sid) }}
55 p.anonymous @nonymous ({{ anonymousCount }})
57 Chat(:newChat="newChat" @mychat="processChat" :pastChats="[]")
61 button#btnGlive(@click="setDisplay('g','live',$event)" class="active")
62 | {{ st.tr["Live games"] }}
63 button#btnGcorr(@click="setDisplay('g','corr',$event)")
64 | {{ st.tr["Correspondance games"] }}
65 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
66 @show-game="showGame")
67 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
68 @show-game="showGame")
72 import { store } from "@/store";
73 import { checkChallenge } from "@/data/challengeCheck";
74 import { ArrayFun } from "@/utils/array";
75 import { ajax } from "@/utils/ajax";
76 import params from "@/parameters";
77 import { getRandString, shuffle } from "@/utils/alea";
78 import Chat from "@/components/Chat.vue";
79 import GameList from "@/components/GameList.vue";
80 import ChallengeList from "@/components/ChallengeList.vue";
81 import { GameStorage } from "@/utils/gameStorage";
82 import { processModalClick } from "@/utils/modalClick";
93 cdisplay: "live", //or corr
101 vid: localStorage.getItem("vid") || "",
102 to: "", //name of challenged player (if any)
103 cadence: localStorage.getItem("cadence") || "",
108 // Related to (killing of) self multi-connects:
114 // st.variants changes only once, at loading from [] to [...]
115 "st.variants": function(variantArray) {
116 // Set potential challenges and games variant names:
117 this.challenges.concat(this.games).forEach(o => {
119 o.vname = this.getVname(o.vid);
124 anonymousCount: function() {
126 Object.values(this.people).forEach(p => { count += (!p.name ? 1 : 0); });
130 created: function() {
131 const my = this.st.user;
132 this.$set(this.people, my.sid, {id:my.id, name:my.name, pages:["/"]});
133 // Ask server for current corr games (all but mines)
137 {uid: this.st.user.id, excluded: true},
139 // Show corr tab with timeout, to let enough time for (socket) polling
141 if (this.games.length == response.games.length)
142 this.setDisplay('g', "corr");
144 this.games = this.games.concat(response.games.map(g => {
145 const type = this.classifyObject(g);
146 const vname = this.getVname(g.vid);
147 return Object.assign({}, g, {type: type, vname: vname});
151 // Also ask for corr challenges (open + sent by/to me)
155 {uid: this.st.user.id},
158 if (this.challenges.length == response.challenges.length)
159 this.setDisplay('c', "corr");
161 // Gather all senders names, and then retrieve full identity:
162 // (TODO [perf]: some might be online...)
164 response.challenges.forEach(c => {
165 if (c.uid != this.st.user.id)
166 names[c.uid] = ""; //unknwon for now
167 else if (!!c.target && c.target != this.st.user.id)
168 names[c.target] = "";
170 const addChallenges = (newChalls) => {
171 names[this.st.user.id] = this.st.user.name; //in case of
172 this.challenges = this.challenges.concat(
173 response.challenges.map(c => {
174 const from = {name: names[c.uid], id: c.uid}; //or just name
175 const type = this.classifyObject(c);
176 const vname = this.getVname(c.vid);
177 return Object.assign({},
182 to: (!!c.target ? names[c.target] : ""),
192 { ids: Object.keys(names).join(",") },
194 response2.users.forEach(u => {names[u.id] = u.name});
203 const connectAndPoll = () => {
204 this.send("connect");
205 this.send("pollclientsandgamers");
207 // Initialize connection
208 this.connexionString = params.socketUrl +
209 "/?sid=" + this.st.user.sid +
210 "&tmpId=" + getRandString() +
211 "&page=" + encodeURIComponent(this.$route.path);
212 this.conn = new WebSocket(this.connexionString);
213 this.conn.onopen = connectAndPoll;
214 this.conn.onmessage = this.socketMessageListener;
215 this.conn.onclose = this.socketCloseListener;
217 mounted: function() {
218 [document.getElementById("infoDiv"),document.getElementById("newgameDiv")]
219 .forEach(elt => elt.addEventListener("click", processModalClick));
220 document.querySelectorAll("#predefinedCadences > button").forEach(
221 (b) => { b.addEventListener("click",
222 () => { this.newchallenge.cadence = b.innerHTML; }
226 beforeDestroy: function() {
227 this.send("disconnect");
231 send: function(code, obj) {
234 this.conn.send(JSON.stringify(
242 getVname: function(vid) {
243 const variant = this.st.variants.find(v => v.id == vid);
244 // this.st.variants might be uninitialized (variant == null)
245 return (!!variant ? variant.name : "");
247 filterChallenges: function(type) {
248 return this.challenges.filter(c => c.type == type);
250 filterGames: function(type) {
251 return this.games.filter(g => g.type == type);
253 classifyObject: function(o) { //challenge or game
254 return (o.cadence.indexOf('d') === -1 ? "live" : "corr");
256 setDisplay: function(letter, type, e) {
257 this[letter + "display"] = type;
260 : document.getElementById("btn" + letter.toUpperCase() + type);
261 elt.classList.add("active");
262 if (!!elt.previousElementSibling)
263 elt.previousElementSibling.classList.remove("active");
265 elt.nextElementSibling.classList.remove("active");
267 isGamer: function(sid) {
268 return this.people[sid].pages.some(p => p.indexOf("/game/") >= 0);
270 showPlayerActionBtn: function(sid) {
271 // Do not show action btn if I'm anonymous and target isn't playing,
272 // or target is anonymous and not playing,
273 // or target is me and I don't play anywhere.
274 const targetIsGamer = this.isGamer(sid);
275 if ((!this.st.user.name && !targetIsGamer) ||
276 (!this.people[sid].name && !this.isGamer(this.st.user.sid)) ||
277 (sid == this.st.user.sid && !targetIsGamer))
283 getActionLabel: function(sid) {
284 return this.people[sid].pages.some(p => p == "/")
288 challOrWatch: function(sid) {
289 if (this.people[sid].pages.some(p => p == "/"))
291 // Available, in Hall
292 this.newchallenge.to = this.people[sid].name;
293 doClick("modalNewgame");
297 // In some game, maybe playing maybe not: show a random one
299 this.people[sid].pages.forEach(p => {
300 const matchGid = p.match(/[a-zA-Z0-9]+$/);
302 gids.push(matchGid[0]);
304 const gid = gids[Math.floor(Math.random() * gids.length)];
305 this.showGame(this.games.find(g => g.id == gid));
308 showGame: function(g) {
309 // NOTE: we are an observer, since only games I don't play are shown here
310 // ==> Moves sent by connected remote player(s) if live game
311 let url = "/game/" + g.id;
312 if (g.type == "live")
313 url += "?rid=" + g.rids[Math.floor(Math.random() * g.rids.length)];
314 this.$router.push(url);
316 processChat: function(chat) {
317 this.send("newchat", {data:chat});
320 socketMessageListener: function(msg) {
323 const data = JSON.parse(msg.data);
326 case "pollclientsandgamers":
328 // Since people can be both in Hall and Game,
329 // need to track "askIdentity" requests:
330 let identityAsked = {};
331 data.sockIds.forEach(s => {
332 const page = s.page || "/";
333 if (s.sid != this.st.user.sid && !identityAsked[s.sid])
335 identityAsked[s.sid] = true;
336 this.send("askidentity", {target:s.sid, page:page});
338 if (!this.people[s.sid])
339 this.$set(this.people, s.sid, {id:0, name:"", pages:[page]});
340 else if (this.people[s.sid].pages.indexOf(page) < 0)
341 this.people[s.sid].pages.push(page);
342 if (!s.page) //peer is in Hall
343 this.send("askchallenge", {target:s.sid});
344 else //peer is in Game
345 this.send("askgame", {target:s.sid, page:page});
352 const page = data.page || "/";
353 // NOTE: player could have been polled earlier, but might have logged in then
354 // So it's a good idea to ask identity if he was anonymous.
355 // But only ask game / challenge if currently disconnected.
356 if (!this.people[data.from])
358 this.$set(this.people, data.from, {name:"", id:0, pages:[page]});
359 if (data.code == "connect")
360 this.send("askchallenge", {target:data.from});
362 this.send("askgame", {target:data.from, page:page});
366 // append page if not already in list
367 if (this.people[data.from].pages.indexOf(page) < 0)
368 this.people[data.from].pages.push(page);
370 if (this.people[data.from].id == 0)
372 this.newConnect[data.from] = true; //for self multi-connects tests
373 this.send("askidentity", {target:data.from, page:page});
379 if (!this.people[data.from])
380 return; //TODO: solve this bug
381 // (anonymous reloads page, onclose event triggered twice...)
382 // Disconnect means no more tmpIds:
383 if (data.code == "disconnect")
385 // Remove the live challenge sent by this player:
386 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
390 // Remove the matching live game if now unreachable
391 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
392 const gidx = this.games.findIndex(g => g.id == gid);
395 const game = this.games[gidx];
396 if (game.type == "live" &&
397 game.rids.length == 1 && game.rids[0] == data.from)
399 this.games.splice(gidx, 1);
403 const page = data.page || "/";
404 ArrayFun.remove(this.people[data.from].pages, p => p == page);
405 if (this.people[data.from].pages.length == 0)
406 this.$delete(this.people, data.from);
409 // I logged in elsewhere:
410 alert(this.st.tr["New connexion detected: tab now offline"]);
411 // TODO: this fails. See https://github.com/websockets/ws/issues/489
412 //this.conn.removeEventListener("message", this.socketMessageListener);
413 //this.conn.removeEventListener("close", this.socketCloseListener);
419 // Request for identification (TODO: anonymous shouldn't need to reply)
421 // Decompose to avoid revealing email
422 name: this.st.user.name,
423 sid: this.st.user.sid,
426 this.send("identity", {data:me, target:data.from});
431 const user = data.data;
432 if (!!user.name) //otherwise anonymous
434 // If I multi-connect, kill current connexion if no mark (I'm older)
435 if (this.newConnect[user.sid] && user.id > 0
436 && user.id == this.st.user.id && user.sid != this.st.user.sid)
438 if (!this.killed[this.st.user.sid])
440 this.send("killme", {sid:this.st.user.sid});
441 this.killed[this.st.user.sid] = true;
444 if (user.sid != this.st.user.sid) //I already know my identity...
446 this.$set(this.people, user.sid,
450 pages: this.people[user.sid].pages,
454 delete this.newConnect[user.sid];
459 // Send my current live challenge (if any)
460 const cIdx = this.challenges.findIndex(c =>
461 c.from.sid == this.st.user.sid && c.type == "live");
464 const c = this.challenges[cIdx];
465 // NOTE: in principle, should only send targeted challenge to the target.
466 // But we may not know yet the identity of the target (just name),
467 // so cannot decide if data.from is the target or not.
471 from: this.st.user.sid,
478 this.send("challenge", {data:myChallenge, target:data.from});
482 case "challenge": //after "askchallenge"
485 // NOTE about next condition: see "askchallenge" case.
486 const chall = data.data;
487 if (!chall.to || (this.people[chall.from].id > 0 &&
488 (chall.from == this.st.user.sid || chall.to == this.st.user.name)))
490 let newChall = Object.assign({}, chall);
491 newChall.type = this.classifyObject(chall);
492 newChall.added = Date.now();
493 let fromValues = Object.assign({}, this.people[chall.from]);
494 delete fromValues["pages"]; //irrelevant in this context
495 newChall.from = Object.assign({sid:chall.from}, fromValues);
496 newChall.vname = this.getVname(newChall.vid);
497 this.challenges.push(newChall);
499 if (newChall.type == "live" && this.cdisplay == "corr" && !this.challenges.some(c => c.type == "corr"))
500 this.setDisplay('c', "live");
501 else if (newChall.type == "corr" && this.cdisplay == "live" && !this.challenges.some(c => c.type == "live"))
502 this.setDisplay('c', "corr");
506 case "refusechallenge":
508 const cid = data.data;
509 ArrayFun.remove(this.challenges, c => c.id == cid);
510 alert(this.st.tr["Challenge declined"]);
513 case "deletechallenge":
515 // NOTE: the challenge may be already removed
516 const cid = data.data;
517 ArrayFun.remove(this.challenges, c => c.id == cid);
520 case "game": //individual request
523 // NOTE: it may be live or correspondance
524 const game = data.data;
525 let locGame = this.games.find(g => g.id == game.id);
529 newGame.type = this.classifyObject(game);
530 newGame.vname = this.getVname(game.vid);
531 if (!game.score) //if new game from Hall
533 newGame.rids = [game.rid];
534 delete newGame["rid"];
535 this.games.push(newGame);
537 if (newGame.type == "live" && this.gdisplay == "corr" && !this.games.some(g => g.type == "corr"))
538 this.setDisplay('g', "live");
539 else if (newGame.type == "live" && this.gdisplay == "live" && !this.games.some(g => g.type == "live"))
540 this.setDisplay('g', "corr");
544 // Append rid (if not already in list)
545 if (!locGame.rids.includes(game.rid))
546 locGame.rids.push(game.rid);
552 // New game just started: data contain all information
553 const gameInfo = data.data;
554 if (this.classifyObject(gameInfo) == "live")
555 this.startNewGame(gameInfo);
558 this.infoMessage = this.st.tr["New correspondance game:"] +
559 " <a href='#/game/" + gameInfo.id + "'>" +
560 "#/game/" + gameInfo.id + "</a>";
561 let modalBox = document.getElementById("modalInfo");
562 modalBox.checked = true;
567 this.newChat = data.data;
571 socketCloseListener: function() {
574 this.conn = new WebSocket(this.connexionString);
575 this.conn.addEventListener("message", this.socketMessageListener);
576 this.conn.addEventListener("close", this.socketCloseListener);
578 // Challenge lifecycle:
579 newChallenge: async function() {
580 if (this.newchallenge.vid == "")
581 return alert(this.st.tr["Please select a variant"]);
582 if (!!this.newchallenge.to && this.newchallenge.to == this.st.user.name)
583 return alert(this.st.tr["Self-challenge is forbidden"]);
584 const vname = this.getVname(this.newchallenge.vid);
585 const vModule = await import("@/variants/" + vname + ".js");
586 window.V = vModule.VariantRules;
587 if (!!this.newchallenge.cadence.match(/^[0-9]+$/))
588 this.newchallenge.cadence += "+0"; //assume minutes, no increment
589 const error = checkChallenge(this.newchallenge);
592 const ctype = this.classifyObject(this.newchallenge);
593 if (ctype == "corr" && this.st.user.id <= 0)
594 return alert(this.st.tr["Please log in to play correspondance games"]);
595 // NOTE: "from" information is not required here
596 let chall = Object.assign({}, this.newchallenge);
597 const finishAddChallenge = (cid) => {
598 chall.id = cid || "c" + getRandString();
599 // Remove old challenge if any (only one at a time of a given type):
600 const cIdx = this.challenges.findIndex(c =>
601 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) && c.type == ctype);
604 // Delete current challenge (will be replaced now)
605 this.send("deletechallenge", {data:this.challenges[cIdx].id});
611 {id: this.challenges[cIdx].id}
614 this.challenges.splice(cIdx, 1);
616 this.send("newchallenge", {data:Object.assign({from:this.st.user.sid}, chall)});
617 // Add new challenge:
618 chall.from = { //decompose to avoid revealing email
619 sid: this.st.user.sid,
621 name: this.st.user.name,
623 chall.added = Date.now();
624 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
627 this.challenges.push(chall);
628 // Remember cadence + vid for quicker further challenges:
629 localStorage.setItem("cadence", chall.cadence);
630 localStorage.setItem("vid", chall.vid);
631 document.getElementById("modalNewgame").checked = false;
635 // Live challenges have a random ID
636 finishAddChallenge(null);
640 // Correspondance game: send challenge to server
645 response => { finishAddChallenge(response.cid); }
649 clickChallenge: function(c) {
650 const myChallenge = (c.from.sid == this.st.user.sid //live
651 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
654 if (c.type == "corr" && this.st.user.id <= 0)
655 return alert(this.st.tr["Please log in to accept corr challenges"]);
657 if (!!c.to) //c.to == this.st.user.name (connected)
659 // TODO: if special FEN, show diagram after loading variant
660 c.accepted = confirm("Accept challenge?");
664 c.seat = { //again, avoid c.seat = st.user to not reveal email
665 sid: this.st.user.sid,
667 name: this.st.user.name,
673 this.send("refusechallenge", {data:c.id, target:c.from.sid});
675 this.send("deletechallenge", {data:c.id});
679 if (c.type == "corr")
687 this.send("deletechallenge", {data:c.id});
689 // In all cases, the challenge is consumed:
690 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
692 // NOTE: when launching game, the challenge is already being deleted
693 launchGame: async function(c) {
694 const vModule = await import("@/variants/" + c.vname + ".js");
695 window.V = vModule.VariantRules;
696 // These game informations will be shared
700 fen: c.fen || V.GenRandInitFen(),
701 players: shuffle([c.from, c.seat]), //white then black
705 let oppsid = c.from.sid; //may not be defined if corr + offline opp
708 oppsid = Object.keys(this.people).find(sid =>
709 this.people[sid].id == c.from.id);
711 const notifyNewgame = () => {
712 if (!!oppsid) //opponent is online
713 this.send("startgame", {data:gameInfo, target:oppsid});
714 // Send game info (only if live) to everyone except me in this tab
715 this.send("newgame", {data:gameInfo});
717 if (c.type == "live")
720 this.startNewGame(gameInfo);
722 else //corr: game only on server
727 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
729 gameInfo.id = response.gameId;
731 this.$router.push("/game/" + response.gameId);
736 // NOTE: for live games only (corr games start on the server)
737 startNewGame: function(gameInfo) {
738 const game = Object.assign({}, gameInfo, {
739 // (other) Game infos: constant
740 fenStart: gameInfo.fen,
741 vname: this.getVname(gameInfo.vid),
743 // Game state (including FEN): will be updated
745 clocks: [-1, -1], //-1 = unstarted
746 initime: [0, 0], //initialized later
749 GameStorage.add(game);
750 if (this.st.settings.sound >= 1)
751 new Audio("/sounds/newgame.mp3").play().catch(err => {});
752 this.$router.push("/game/" + gameInfo.id);
758 <style lang="sass" scoped>
763 margin: 10px auto 5px auto
783 @media screen and (max-width: 767px)