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")
11 label#closeNewgame.modal-close(for="modalNewgame")
12 form(@submit.prevent="newChallenge()" @keyup.enter="newChallenge()")
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"
17 :selected="newchallenge.vid==v.id")
20 label(for="cadence") {{ st.tr["Cadence"] }} *
21 div#predefinedCadences
25 input#cadence(type="text" v-model="newchallenge.cadence"
26 placeholder="5+0, 1h+30s, 7d+1d ...")
27 fieldset(v-if="st.user.id > 0")
28 label(for="selectPlayers") {{ st.tr["Play with?"] }}
29 input#selectPlayers(type="text" v-model="newchallenge.to")
30 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
31 label(for="inputFen") FEN
32 input#inputFen(type="text" v-model="newchallenge.fen")
33 button(@click="newChallenge()") {{ st.tr["Send challenge"] }}
34 input#modalPeople.modal(type="checkbox" @click="resetChatColor()")
35 div#peopleWrap(role="dialog" data-checkbox="modalPeople")
37 label.modal-close(for="modalPeople")
40 p(v-for="sid in Object.keys(people)" v-if="!!people[sid].name")
41 span {{ people[sid].name }}
42 button.player-action(v-if="sid!=st.user.sid || isGamer(sid)" @click="challOrWatch(sid)")
43 | {{ getActionLabel(sid) }}
44 p.anonymous @nonymous ({{ anonymousCount }})
46 Chat(:newChat="newChat" @mychat="processChat" :pastChats="[]")
49 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
51 button#peopleBtn(onClick="doClick('modalPeople')") {{ st.tr["Social"] }}
52 button(onClick="doClick('modalNewgame')") {{ st.tr["New game"] }}
54 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
57 button#btnClive(@click="setDisplay('c','live',$event)" class="active")
58 | {{ st.tr["Live challenges"] }}
59 button#btnCcorr(@click="setDisplay('c','corr',$event)")
60 | {{ st.tr["Correspondance challenges"] }}
61 ChallengeList(v-show="cdisplay=='live'"
62 :challenges="filterChallenges('live')" @click-challenge="clickChallenge")
63 ChallengeList(v-show="cdisplay=='corr'"
64 :challenges="filterChallenges('corr')" @click-challenge="clickChallenge")
67 button#btnGlive(@click="setDisplay('g','live',$event)" class="active")
68 | {{ st.tr["Live games"] }}
69 button#btnGcorr(@click="setDisplay('g','corr',$event)")
70 | {{ st.tr["Correspondance games"] }}
71 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
72 :showBoth="true" @show-game="showGame")
73 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
74 :showBoth="true" @show-game="showGame")
78 import { store } from "@/store";
79 import { checkChallenge } from "@/data/challengeCheck";
80 import { ArrayFun } from "@/utils/array";
81 import { ajax } from "@/utils/ajax";
82 import params from "@/parameters";
83 import { getRandString, shuffle } from "@/utils/alea";
84 import Chat from "@/components/Chat.vue";
85 import GameList from "@/components/GameList.vue";
86 import ChallengeList from "@/components/ChallengeList.vue";
87 import { GameStorage } from "@/utils/gameStorage";
88 import { processModalClick } from "@/utils/modalClick";
99 cdisplay: "live", //or corr
107 vid: localStorage.getItem("vid") || "",
108 to: "", //name of challenged player (if any)
109 cadence: localStorage.getItem("cadence") || "",
114 // Related to (killing of) self multi-connects:
120 // st.variants changes only once, at loading from [] to [...]
121 "st.variants": function(variantArray) {
122 // Set potential challenges and games variant names:
123 this.challenges.concat(this.games).forEach(o => {
125 o.vname = this.getVname(o.vid);
130 anonymousCount: function() {
132 Object.values(this.people).forEach(p => { count += (!p.name ? 1 : 0); });
136 created: function() {
137 const my = this.st.user;
138 this.$set(this.people, my.sid, {id:my.id, name:my.name, pages:["/"]});
139 // Ask server for current corr games (all but mines)
143 {uid: this.st.user.id, excluded: true},
145 // Show corr tab with timeout, to let enough time for (socket) polling
148 if (response.games.length > 0 &&
149 this.games.length == response.games.length)
151 this.setDisplay('g', "corr");
156 this.games = this.games.concat(response.games.map(g => {
157 const type = this.classifyObject(g);
158 const vname = this.getVname(g.vid);
159 return Object.assign({}, g, {type: type, vname: vname});
163 // Also ask for corr challenges (open + sent by/to me)
167 {uid: this.st.user.id},
171 if (response.challenges.length > 0 &&
172 this.challenges.length == response.challenges.length)
174 this.setDisplay('c', "corr");
179 // Gather all senders names, and then retrieve full identity:
180 // (TODO [perf]: some might be online...)
182 response.challenges.forEach(c => {
183 if (c.uid != this.st.user.id)
184 names[c.uid] = ""; //unknwon for now
185 else if (!!c.target && c.target != this.st.user.id)
186 names[c.target] = "";
188 const addChallenges = (newChalls) => {
189 names[this.st.user.id] = this.st.user.name; //in case of
190 this.challenges = this.challenges.concat(
191 response.challenges.map(c => {
192 const from = {name: names[c.uid], id: c.uid}; //or just name
193 const type = this.classifyObject(c);
194 const vname = this.getVname(c.vid);
195 return Object.assign({},
200 to: (!!c.target ? names[c.target] : ""),
206 if (Object.keys(names).length > 0)
210 { ids: Object.keys(names).join(",") },
212 response2.users.forEach(u => {names[u.id] = u.name});
221 const connectAndPoll = () => {
222 this.send("connect");
223 this.send("pollclientsandgamers");
225 // Initialize connection
226 this.connexionString = params.socketUrl +
227 "/?sid=" + this.st.user.sid +
228 "&tmpId=" + getRandString() +
229 "&page=" + encodeURIComponent(this.$route.path);
230 this.conn = new WebSocket(this.connexionString);
231 this.conn.onopen = connectAndPoll;
232 this.conn.onmessage = this.socketMessageListener;
233 this.conn.onclose = this.socketCloseListener;
235 mounted: function() {
236 ["peopleWrap","infoDiv","newgameDiv"].forEach(eltName => {
237 let elt = document.getElementById(eltName);
238 elt.addEventListener("click", processModalClick);
240 document.querySelectorAll("#predefinedCadences > button").forEach(
241 (b) => { b.addEventListener("click",
242 () => { this.newchallenge.cadence = b.innerHTML; }
246 beforeDestroy: function() {
247 this.send("disconnect");
251 send: function(code, obj) {
254 this.conn.send(JSON.stringify(
262 getVname: function(vid) {
263 const variant = this.st.variants.find(v => v.id == vid);
264 // this.st.variants might be uninitialized (variant == null)
265 return (!!variant ? variant.name : "");
267 filterChallenges: function(type) {
268 return this.challenges.filter(c => c.type == type);
270 filterGames: function(type) {
271 return this.games.filter(g => g.type == type);
273 classifyObject: function(o) { //challenge or game
274 return (o.cadence.indexOf('d') === -1 ? "live" : "corr");
276 setDisplay: function(letter, type, e) {
277 this[letter + "display"] = type;
280 : document.getElementById("btn" + letter.toUpperCase() + type);
281 // WARNING: this method is called at created in a setTimeout:
282 // => the page could have changed and element no longer defined.
285 elt.classList.add("active");
286 if (!!elt.previousElementSibling)
287 elt.previousElementSibling.classList.remove("active");
289 elt.nextElementSibling.classList.remove("active");
291 isGamer: function(sid) {
292 return this.people[sid].pages.some(p => p.indexOf("/game/") >= 0);
294 getActionLabel: function(sid) {
295 return this.people[sid].pages.some(p => p == "/")
299 challOrWatch: function(sid) {
300 if (this.people[sid].pages.some(p => p == "/"))
302 // Available, in Hall
303 this.newchallenge.to = this.people[sid].name;
304 document.getElementById("modalPeople").checked = false;
305 doClick("modalNewgame");
309 // In some game, maybe playing maybe not: show a random one
311 this.people[sid].pages.forEach(p => {
312 const matchGid = p.match(/[a-zA-Z0-9]+$/);
314 gids.push(matchGid[0]);
316 const gid = gids[Math.floor(Math.random() * gids.length)];
317 this.showGame(this.games.find(g => g.id == gid));
320 showGame: function(g) {
321 // NOTE: we are an observer, since only games I don't play are shown here
322 // ==> Moves sent by connected remote player(s) if live game
323 let url = "/game/" + g.id;
324 if (g.type == "live")
325 url += "?rid=" + g.rids[Math.floor(Math.random() * g.rids.length)];
326 this.$router.push(url);
328 resetChatColor: function() {
329 // TODO: this is called twice, once on opening an once on closing
330 document.getElementById("peopleBtn").style.backgroundColor = "#e2e2e2";
332 processChat: function(chat) {
333 this.send("newchat", {data:chat});
336 socketMessageListener: function(msg) {
339 const data = JSON.parse(msg.data);
342 case "pollclientsandgamers":
344 // Since people can be both in Hall and Game,
345 // need to track "askIdentity" requests:
346 let identityAsked = {};
347 data.sockIds.forEach(s => {
348 const page = s.page || "/";
349 if (s.sid != this.st.user.sid && !identityAsked[s.sid])
351 identityAsked[s.sid] = true;
352 this.send("askidentity", {target:s.sid, page:page});
354 if (!this.people[s.sid])
355 this.$set(this.people, s.sid, {id:0, name:"", pages:[page]});
356 else if (this.people[s.sid].pages.indexOf(page) < 0)
357 this.people[s.sid].pages.push(page);
358 if (!s.page) //peer is in Hall
359 this.send("askchallenge", {target:s.sid});
360 else //peer is in Game
361 this.send("askgame", {target:s.sid, page:page});
368 const page = data.page || "/";
369 // NOTE: player could have been polled earlier, but might have logged in then
370 // So it's a good idea to ask identity if he was anonymous.
371 // But only ask game / challenge if currently disconnected.
372 if (!this.people[data.from])
374 this.$set(this.people, data.from, {name:"", id:0, pages:[page]});
375 if (data.code == "connect")
376 this.send("askchallenge", {target:data.from});
378 this.send("askgame", {target:data.from, page:page});
382 // append page if not already in list
383 if (this.people[data.from].pages.indexOf(page) < 0)
384 this.people[data.from].pages.push(page);
386 if (this.people[data.from].id == 0)
388 this.newConnect[data.from] = true; //for self multi-connects tests
389 this.send("askidentity", {target:data.from, page:page});
395 // If the user reloads the page twice very quickly (experienced with Firefox),
396 // the first reload won't have time to connect but will trigger a "close" event anyway.
397 // ==> Next check is required.
398 if (!this.people[data.from])
400 // Disconnect means no more tmpIds:
401 if (data.code == "disconnect")
403 // Remove the live challenge sent by this player:
404 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
408 // Remove the matching live game if now unreachable
409 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
410 const gidx = this.games.findIndex(g => g.id == gid);
413 const game = this.games[gidx];
414 if (game.type == "live" &&
415 game.rids.length == 1 && game.rids[0] == data.from)
417 this.games.splice(gidx, 1);
421 const page = data.page || "/";
422 ArrayFun.remove(this.people[data.from].pages, p => p == page);
423 if (this.people[data.from].pages.length == 0)
424 this.$delete(this.people, data.from);
427 // I logged in elsewhere:
428 alert(this.st.tr["New connexion detected: tab now offline"]);
429 // TODO: this fails. See https://github.com/websockets/ws/issues/489
430 //this.conn.removeEventListener("message", this.socketMessageListener);
431 //this.conn.removeEventListener("close", this.socketCloseListener);
437 // Request for identification (TODO: anonymous shouldn't need to reply)
439 // Decompose to avoid revealing email
440 name: this.st.user.name,
441 sid: this.st.user.sid,
444 this.send("identity", {data:me, target:data.from});
449 const user = data.data;
450 if (!!user.name) //otherwise anonymous
452 // If I multi-connect, kill current connexion if no mark (I'm older)
453 if (this.newConnect[user.sid] && user.id > 0
454 && user.id == this.st.user.id && user.sid != this.st.user.sid)
456 if (!this.killed[this.st.user.sid])
458 this.send("killme", {sid:this.st.user.sid});
459 this.killed[this.st.user.sid] = true;
462 if (user.sid != this.st.user.sid) //I already know my identity...
464 this.$set(this.people, user.sid,
468 pages: this.people[user.sid].pages,
472 delete this.newConnect[user.sid];
477 // Send my current live challenge (if any)
478 const cIdx = this.challenges.findIndex(c =>
479 c.from.sid == this.st.user.sid && c.type == "live");
482 const c = this.challenges[cIdx];
483 // NOTE: in principle, should only send targeted challenge to the target.
484 // But we may not know yet the identity of the target (just name),
485 // so cannot decide if data.from is the target or not.
489 from: this.st.user.sid,
496 this.send("challenge", {data:myChallenge, target:data.from});
500 case "challenge": //after "askchallenge"
503 // NOTE about next condition: see "askchallenge" case.
504 const chall = data.data;
505 if (!chall.to || (this.people[chall.from].id > 0 &&
506 (chall.from == this.st.user.sid || chall.to == this.st.user.name)))
508 let newChall = Object.assign({}, chall);
509 newChall.type = this.classifyObject(chall);
510 newChall.added = Date.now();
511 let fromValues = Object.assign({}, this.people[chall.from]);
512 delete fromValues["pages"]; //irrelevant in this context
513 newChall.from = Object.assign({sid:chall.from}, fromValues);
514 newChall.vname = this.getVname(newChall.vid);
515 this.challenges.push(newChall);
517 if (newChall.type == "live" && this.cdisplay == "corr" && !this.challenges.some(c => c.type == "corr"))
518 this.setDisplay('c', "live");
519 else if (newChall.type == "corr" && this.cdisplay == "live" && !this.challenges.some(c => c.type == "live"))
520 this.setDisplay('c', "corr");
524 case "refusechallenge":
526 const cid = data.data;
527 ArrayFun.remove(this.challenges, c => c.id == cid);
528 alert(this.st.tr["Challenge declined"]);
531 case "deletechallenge":
533 // NOTE: the challenge may be already removed
534 const cid = data.data;
535 ArrayFun.remove(this.challenges, c => c.id == cid);
538 case "game": //individual request
541 // NOTE: it may be live or correspondance
542 const game = data.data;
543 let locGame = this.games.find(g => g.id == game.id);
547 newGame.type = this.classifyObject(game);
548 newGame.vname = this.getVname(game.vid);
549 if (!game.score) //if new game from Hall
551 newGame.rids = [game.rid];
552 delete newGame["rid"];
553 this.games.push(newGame);
555 if (newGame.type == "live" && this.gdisplay == "corr" && !this.games.some(g => g.type == "corr"))
556 this.setDisplay('g', "live");
557 else if (newGame.type == "live" && this.gdisplay == "live" && !this.games.some(g => g.type == "live"))
558 this.setDisplay('g', "corr");
562 // Append rid (if not already in list)
563 if (!locGame.rids.includes(game.rid))
564 locGame.rids.push(game.rid);
570 let g = this.games.find(g => g.id == data.gid);
572 g.score = data.score;
577 // New game just started: data contain all information
578 const gameInfo = data.data;
579 if (this.classifyObject(gameInfo) == "live")
580 this.startNewGame(gameInfo);
583 this.infoMessage = this.st.tr["New correspondance game:"] +
584 " <a href='#/game/" + gameInfo.id + "'>" +
585 "#/game/" + gameInfo.id + "</a>";
586 let modalBox = document.getElementById("modalInfo");
587 modalBox.checked = true;
592 this.newChat = data.data;
593 if (!document.getElementById("modalPeople").checked)
594 document.getElementById("peopleBtn").style.backgroundColor = "#c5fefe";
598 socketCloseListener: function() {
601 this.conn = new WebSocket(this.connexionString);
602 this.conn.addEventListener("message", this.socketMessageListener);
603 this.conn.addEventListener("close", this.socketCloseListener);
605 // Challenge lifecycle:
606 newChallenge: async function() {
607 if (this.newchallenge.vid == "")
608 return alert(this.st.tr["Please select a variant"]);
609 if (!!this.newchallenge.to && this.newchallenge.to == this.st.user.name)
610 return alert(this.st.tr["Self-challenge is forbidden"]);
611 const vname = this.getVname(this.newchallenge.vid);
612 const vModule = await import("@/variants/" + vname + ".js");
613 window.V = vModule.VariantRules;
614 if (!!this.newchallenge.cadence.match(/^[0-9]+$/))
615 this.newchallenge.cadence += "+0"; //assume minutes, no increment
616 const error = checkChallenge(this.newchallenge);
619 const ctype = this.classifyObject(this.newchallenge);
620 if (ctype == "corr" && this.st.user.id <= 0)
621 return alert(this.st.tr["Please log in to play correspondance games"]);
622 // NOTE: "from" information is not required here
623 let chall = Object.assign({}, this.newchallenge);
624 const finishAddChallenge = (cid) => {
625 chall.id = cid || "c" + getRandString();
626 // Remove old challenge if any (only one at a time of a given type):
627 const cIdx = this.challenges.findIndex(c =>
628 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) && c.type == ctype);
631 // Delete current challenge (will be replaced now)
632 this.send("deletechallenge", {data:this.challenges[cIdx].id});
638 {id: this.challenges[cIdx].id}
641 this.challenges.splice(cIdx, 1);
643 this.send("newchallenge", {data:Object.assign({from:this.st.user.sid}, chall)});
644 // Add new challenge:
645 chall.from = { //decompose to avoid revealing email
646 sid: this.st.user.sid,
648 name: this.st.user.name,
650 chall.added = Date.now();
651 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
654 this.challenges.push(chall);
655 // Remember cadence + vid for quicker further challenges:
656 localStorage.setItem("cadence", chall.cadence);
657 localStorage.setItem("vid", chall.vid);
658 document.getElementById("modalNewgame").checked = false;
662 // Live challenges have a random ID
663 finishAddChallenge(null);
667 // Correspondance game: send challenge to server
672 response => { finishAddChallenge(response.cid); }
676 clickChallenge: function(c) {
677 const myChallenge = (c.from.sid == this.st.user.sid //live
678 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
681 if (c.type == "corr" && this.st.user.id <= 0)
682 return alert(this.st.tr["Please log in to accept corr challenges"]);
684 if (!!c.to) //c.to == this.st.user.name (connected)
686 // TODO: if special FEN, show diagram after loading variant
687 c.accepted = confirm("Accept challenge?");
691 c.seat = { //again, avoid c.seat = st.user to not reveal email
692 sid: this.st.user.sid,
694 name: this.st.user.name,
700 this.send("refusechallenge", {data:c.id, target:c.from.sid});
702 this.send("deletechallenge", {data:c.id});
706 if (c.type == "corr")
714 this.send("deletechallenge", {data:c.id});
716 // In all cases, the challenge is consumed:
717 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
719 // NOTE: when launching game, the challenge is already being deleted
720 launchGame: async function(c) {
721 const vModule = await import("@/variants/" + c.vname + ".js");
722 window.V = vModule.VariantRules;
723 // These game informations will be shared
727 fen: c.fen || V.GenRandInitFen(),
728 players: shuffle([c.from, c.seat]), //white then black
732 let oppsid = c.from.sid; //may not be defined if corr + offline opp
735 oppsid = Object.keys(this.people).find(sid =>
736 this.people[sid].id == c.from.id);
738 const notifyNewgame = () => {
739 if (!!oppsid) //opponent is online
740 this.send("startgame", {data:gameInfo, target:oppsid});
741 // Send game info (only if live) to everyone except me in this tab
742 this.send("newgame", {data:gameInfo});
744 if (c.type == "live")
747 this.startNewGame(gameInfo);
749 else //corr: game only on server
754 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
756 gameInfo.id = response.gameId;
758 this.$router.push("/game/" + response.gameId);
763 // NOTE: for live games only (corr games start on the server)
764 startNewGame: function(gameInfo) {
765 const game = Object.assign({}, gameInfo, {
766 // (other) Game infos: constant
767 fenStart: gameInfo.fen,
768 vname: this.getVname(gameInfo.vid),
770 // Game state (including FEN): will be updated
772 clocks: [-1, -1], //-1 = unstarted
773 initime: [0, 0], //initialized later
776 GameStorage.add(game);
777 if (this.st.settings.sound >= 1)
778 new Audio("/sounds/newgame.mp3").play().catch(err => {});
779 this.$router.push("/game/" + gameInfo.id);
785 <style lang="sass" scoped>
797 div#peopleWrap > .card
800 @media screen and (min-width: 1281px)
801 div#peopleWrap > .card
804 @media screen and (max-width: 1280px)
805 div#peopleWrap > .card
808 @media screen and (max-width: 767px)
809 div#peopleWrap > .card
820 @media screen and (max-width: 767px)