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.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
58 | {{ st.tr["Live challenges"] }}
59 button.tabbtn#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.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
68 | {{ st.tr["Live games"] }}
69 button.tabbtn#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 this.games = this.games.concat(response.games.map(g => {
146 const type = this.classifyObject(g);
147 const vname = this.getVname(g.vid);
148 return Object.assign({}, g, {type: type, vname: vname});
152 // Also ask for corr challenges (open + sent by/to me)
156 {uid: this.st.user.id},
158 // Gather all senders names, and then retrieve full identity:
159 // (TODO [perf]: some might be online...)
161 response.challenges.forEach(c => {
162 if (c.uid != this.st.user.id)
163 names[c.uid] = ""; //unknwon for now
164 else if (!!c.target && c.target != this.st.user.id)
165 names[c.target] = "";
167 const addChallenges = (newChalls) => {
168 names[this.st.user.id] = this.st.user.name; //in case of
169 this.challenges = this.challenges.concat(
170 response.challenges.map(c => {
171 const from = {name: names[c.uid], id: c.uid}; //or just name
172 const type = this.classifyObject(c);
173 const vname = this.getVname(c.vid);
174 return Object.assign({},
179 to: (!!c.target ? names[c.target] : ""),
185 if (Object.keys(names).length > 0)
189 { ids: Object.keys(names).join(",") },
191 response2.users.forEach(u => {names[u.id] = u.name});
200 const connectAndPoll = () => {
201 this.send("connect");
202 this.send("pollclientsandgamers");
204 // Initialize connection
205 this.connexionString = params.socketUrl +
206 "/?sid=" + this.st.user.sid +
207 "&tmpId=" + getRandString() +
208 "&page=" + encodeURIComponent(this.$route.path);
209 this.conn = new WebSocket(this.connexionString);
210 this.conn.onopen = connectAndPoll;
211 this.conn.onmessage = this.socketMessageListener;
212 this.conn.onclose = this.socketCloseListener;
214 mounted: function() {
215 ["peopleWrap","infoDiv","newgameDiv"].forEach(eltName => {
216 let elt = document.getElementById(eltName);
217 elt.addEventListener("click", processModalClick);
219 document.querySelectorAll("#predefinedCadences > button").forEach(
220 (b) => { b.addEventListener("click",
221 () => { this.newchallenge.cadence = b.innerHTML; }
224 const showCtype = localStorage.getItem("type-challenges") || "live";
225 const showGtype = localStorage.getItem("type-games") || "live";
226 this.setDisplay('c', showCtype);
227 this.setDisplay('g', showGtype);
229 beforeDestroy: function() {
230 this.send("disconnect");
234 send: function(code, obj) {
237 this.conn.send(JSON.stringify(
245 getVname: function(vid) {
246 const variant = this.st.variants.find(v => v.id == vid);
247 // this.st.variants might be uninitialized (variant == null)
248 return (!!variant ? variant.name : "");
250 filterChallenges: function(type) {
251 return this.challenges.filter(c => c.type == type);
253 filterGames: function(type) {
254 return this.games.filter(g => g.type == type);
256 classifyObject: function(o) { //challenge or game
257 return (o.cadence.indexOf('d') === -1 ? "live" : "corr");
259 setDisplay: function(letter, type, e) {
260 this[letter + "display"] = type;
261 localStorage.setItem("type-" + (letter == 'c' ? "challenges" : "games"), type);
264 : document.getElementById("btn" + letter.toUpperCase() + type);
265 elt.classList.add("active");
266 elt.classList.remove("somethingnew"); //in case of
267 if (!!elt.previousElementSibling)
268 elt.previousElementSibling.classList.remove("active");
270 elt.nextElementSibling.classList.remove("active");
272 isGamer: function(sid) {
273 return this.people[sid].pages.some(p => p.indexOf("/game/") >= 0);
275 getActionLabel: function(sid) {
276 return this.people[sid].pages.some(p => p == "/")
280 challOrWatch: function(sid) {
281 if (this.people[sid].pages.some(p => p == "/"))
283 // Available, in Hall
284 this.newchallenge.to = this.people[sid].name;
285 document.getElementById("modalPeople").checked = false;
286 doClick("modalNewgame");
290 // In some game, maybe playing maybe not: show a random one
292 this.people[sid].pages.forEach(p => {
293 const matchGid = p.match(/[a-zA-Z0-9]+$/);
295 gids.push(matchGid[0]);
297 const gid = gids[Math.floor(Math.random() * gids.length)];
298 this.showGame(this.games.find(g => g.id == gid));
301 showGame: function(g) {
302 // NOTE: we are an observer, since only games I don't play are shown here
303 // ==> Moves sent by connected remote player(s) if live game
304 let url = "/game/" + g.id;
305 if (g.type == "live")
306 url += "?rid=" + g.rids[Math.floor(Math.random() * g.rids.length)];
307 this.$router.push(url);
309 resetChatColor: function() {
310 // TODO: this is called twice, once on opening an once on closing
311 document.getElementById("peopleBtn").classList.remove("somethingnew");
313 processChat: function(chat) {
314 this.send("newchat", {data:chat});
317 socketMessageListener: function(msg) {
320 const data = JSON.parse(msg.data);
323 case "pollclientsandgamers":
325 // Since people can be both in Hall and Game,
326 // need to track "askIdentity" requests:
327 let identityAsked = {};
328 data.sockIds.forEach(s => {
329 const page = s.page || "/";
330 if (s.sid != this.st.user.sid && !identityAsked[s.sid])
332 identityAsked[s.sid] = true;
333 this.send("askidentity", {target:s.sid, page:page});
335 if (!this.people[s.sid])
336 this.$set(this.people, s.sid, {id:0, name:"", pages:[page]});
337 else if (this.people[s.sid].pages.indexOf(page) < 0)
338 this.people[s.sid].pages.push(page);
339 if (!s.page) //peer is in Hall
340 this.send("askchallenge", {target:s.sid});
341 else //peer is in Game
342 this.send("askgame", {target:s.sid, page:page});
349 const page = data.page || "/";
350 // NOTE: player could have been polled earlier, but might have logged in then
351 // So it's a good idea to ask identity if he was anonymous.
352 // But only ask game / challenge if currently disconnected.
353 if (!this.people[data.from])
355 this.$set(this.people, data.from, {name:"", id:0, pages:[page]});
356 if (data.code == "connect")
357 this.send("askchallenge", {target:data.from});
359 this.send("askgame", {target:data.from, page:page});
363 // append page if not already in list
364 if (this.people[data.from].pages.indexOf(page) < 0)
365 this.people[data.from].pages.push(page);
367 if (this.people[data.from].id == 0)
369 this.newConnect[data.from] = true; //for self multi-connects tests
370 this.send("askidentity", {target:data.from, page:page});
376 // If the user reloads the page twice very quickly (experienced with Firefox),
377 // the first reload won't have time to connect but will trigger a "close" event anyway.
378 // ==> Next check is required.
379 if (!this.people[data.from])
381 // Disconnect means no more tmpIds:
382 if (data.code == "disconnect")
384 // Remove the live challenge sent by this player:
385 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
389 // Remove the matching live game if now unreachable
390 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
391 const gidx = this.games.findIndex(g => g.id == gid);
394 const game = this.games[gidx];
395 if (game.type == "live" &&
396 game.rids.length == 1 && game.rids[0] == data.from)
398 this.games.splice(gidx, 1);
402 const page = data.page || "/";
403 ArrayFun.remove(this.people[data.from].pages, p => p == page);
404 if (this.people[data.from].pages.length == 0)
405 this.$delete(this.people, data.from);
408 // I logged in elsewhere:
409 alert(this.st.tr["New connexion detected: tab now offline"]);
410 // TODO: this fails. See https://github.com/websockets/ws/issues/489
411 //this.conn.removeEventListener("message", this.socketMessageListener);
412 //this.conn.removeEventListener("close", this.socketCloseListener);
418 // Request for identification (TODO: anonymous shouldn't need to reply)
420 // Decompose to avoid revealing email
421 name: this.st.user.name,
422 sid: this.st.user.sid,
425 this.send("identity", {data:me, target:data.from});
430 const user = data.data;
431 if (!!user.name) //otherwise anonymous
433 // If I multi-connect, kill current connexion if no mark (I'm older)
434 if (this.newConnect[user.sid] && user.id > 0
435 && user.id == this.st.user.id && user.sid != this.st.user.sid)
437 if (!this.killed[this.st.user.sid])
439 this.send("killme", {sid:this.st.user.sid});
440 this.killed[this.st.user.sid] = true;
443 if (user.sid != this.st.user.sid) //I already know my identity...
445 this.$set(this.people, user.sid,
449 pages: this.people[user.sid].pages,
453 delete this.newConnect[user.sid];
458 // Send my current live challenge (if any)
459 const cIdx = this.challenges.findIndex(c =>
460 c.from.sid == this.st.user.sid && c.type == "live");
463 const c = this.challenges[cIdx];
464 // NOTE: in principle, should only send targeted challenge to the target.
465 // But we may not know yet the identity of the target (just name),
466 // so cannot decide if data.from is the target or not.
470 from: this.st.user.sid,
477 this.send("challenge", {data:myChallenge, target:data.from});
481 case "challenge": //after "askchallenge"
484 // NOTE about next condition: see "askchallenge" case.
485 const chall = data.data;
486 if (!chall.to || (this.people[chall.from].id > 0 &&
487 (chall.from == this.st.user.sid || chall.to == this.st.user.name)))
489 let newChall = Object.assign({}, chall);
490 newChall.type = this.classifyObject(chall);
491 newChall.added = Date.now();
492 let fromValues = Object.assign({}, this.people[chall.from]);
493 delete fromValues["pages"]; //irrelevant in this context
494 newChall.from = Object.assign({sid:chall.from}, fromValues);
495 newChall.vname = this.getVname(newChall.vid);
496 this.challenges.push(newChall);
497 if ((newChall.type == "live" && this.cdisplay == "corr") ||
498 (newChall.type == "corr" && this.cdisplay == "live"))
500 document.getElementById("btnC" + newChall.type).classList.add("somethingnew");
505 case "refusechallenge":
507 const cid = data.data;
508 ArrayFun.remove(this.challenges, c => c.id == cid);
509 alert(this.st.tr["Challenge declined"]);
512 case "deletechallenge":
514 // NOTE: the challenge may be already removed
515 const cid = data.data;
516 ArrayFun.remove(this.challenges, c => c.id == cid);
519 case "game": //individual request
522 // NOTE: it may be live or correspondance
523 const game = data.data;
524 let locGame = this.games.find(g => g.id == game.id);
528 newGame.type = this.classifyObject(game);
529 newGame.vname = this.getVname(game.vid);
530 if (!game.score) //if new game from Hall
532 newGame.rids = [game.rid];
533 delete newGame["rid"];
534 this.games.push(newGame);
535 if ((newGame.type == "live" && this.gdisplay == "corr") ||
536 (newGame.type == "corr" && this.gdisplay == "live"))
538 document.getElementById("btnG" + newGame.type).classList.add("somethingnew");
543 // Append rid (if not already in list)
544 if (!locGame.rids.includes(game.rid))
545 locGame.rids.push(game.rid);
551 let g = this.games.find(g => g.id == data.gid);
553 g.score = data.score;
558 // New game just started: data contain all information
559 const gameInfo = data.data;
560 if (this.classifyObject(gameInfo) == "live")
561 this.startNewGame(gameInfo);
564 this.infoMessage = this.st.tr["New correspondance game:"] +
565 " <a href='#/game/" + gameInfo.id + "'>" +
566 "#/game/" + gameInfo.id + "</a>";
567 let modalBox = document.getElementById("modalInfo");
568 modalBox.checked = true;
573 this.newChat = data.data;
574 if (!document.getElementById("modalPeople").checked)
575 document.getElementById("peopleBtn").classList.add("somethingnew");
579 socketCloseListener: function() {
582 this.conn = new WebSocket(this.connexionString);
583 this.conn.addEventListener("message", this.socketMessageListener);
584 this.conn.addEventListener("close", this.socketCloseListener);
586 // Challenge lifecycle:
587 newChallenge: async function() {
588 if (this.newchallenge.vid == "")
589 return alert(this.st.tr["Please select a variant"]);
590 if (!!this.newchallenge.to && this.newchallenge.to == this.st.user.name)
591 return alert(this.st.tr["Self-challenge is forbidden"]);
592 const vname = this.getVname(this.newchallenge.vid);
593 const vModule = await import("@/variants/" + vname + ".js");
594 window.V = vModule.VariantRules;
595 if (!!this.newchallenge.cadence.match(/^[0-9]+$/))
596 this.newchallenge.cadence += "+0"; //assume minutes, no increment
597 const error = checkChallenge(this.newchallenge);
600 const ctype = this.classifyObject(this.newchallenge);
601 if (ctype == "corr" && this.st.user.id <= 0)
602 return alert(this.st.tr["Please log in to play correspondance games"]);
603 // NOTE: "from" information is not required here
604 let chall = Object.assign({}, this.newchallenge);
605 const finishAddChallenge = (cid) => {
606 chall.id = cid || "c" + getRandString();
607 // Remove old challenge if any (only one at a time of a given type):
608 const cIdx = this.challenges.findIndex(c =>
609 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) && c.type == ctype);
612 // Delete current challenge (will be replaced now)
613 this.send("deletechallenge", {data:this.challenges[cIdx].id});
619 {id: this.challenges[cIdx].id}
622 this.challenges.splice(cIdx, 1);
624 this.send("newchallenge", {data:Object.assign({from:this.st.user.sid}, chall)});
625 // Add new challenge:
626 chall.from = { //decompose to avoid revealing email
627 sid: this.st.user.sid,
629 name: this.st.user.name,
631 chall.added = Date.now();
632 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
635 this.challenges.push(chall);
636 // Remember cadence + vid for quicker further challenges:
637 localStorage.setItem("cadence", chall.cadence);
638 localStorage.setItem("vid", chall.vid);
639 document.getElementById("modalNewgame").checked = false;
643 // Live challenges have a random ID
644 finishAddChallenge(null);
648 // Correspondance game: send challenge to server
653 response => { finishAddChallenge(response.cid); }
657 clickChallenge: function(c) {
658 const myChallenge = (c.from.sid == this.st.user.sid //live
659 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
662 if (c.type == "corr" && this.st.user.id <= 0)
663 return alert(this.st.tr["Please log in to accept corr challenges"]);
665 if (!!c.to) //c.to == this.st.user.name (connected)
667 // TODO: if special FEN, show diagram after loading variant
668 c.accepted = confirm("Accept challenge?");
672 c.seat = { //again, avoid c.seat = st.user to not reveal email
673 sid: this.st.user.sid,
675 name: this.st.user.name,
681 this.send("refusechallenge", {data:c.id, target:c.from.sid});
683 this.send("deletechallenge", {data:c.id});
687 if (c.type == "corr")
695 this.send("deletechallenge", {data:c.id});
697 // In all cases, the challenge is consumed:
698 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
700 // NOTE: when launching game, the challenge is already being deleted
701 launchGame: async function(c) {
702 const vModule = await import("@/variants/" + c.vname + ".js");
703 window.V = vModule.VariantRules;
704 // These game informations will be shared
708 fen: c.fen || V.GenRandInitFen(),
709 players: shuffle([c.from, c.seat]), //white then black
713 let oppsid = c.from.sid; //may not be defined if corr + offline opp
716 oppsid = Object.keys(this.people).find(sid =>
717 this.people[sid].id == c.from.id);
719 const notifyNewgame = () => {
720 if (!!oppsid) //opponent is online
721 this.send("startgame", {data:gameInfo, target:oppsid});
722 // Send game info (only if live) to everyone except me in this tab
723 this.send("newgame", {data:gameInfo});
725 if (c.type == "live")
728 this.startNewGame(gameInfo);
730 else //corr: game only on server
735 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
737 gameInfo.id = response.gameId;
739 this.$router.push("/game/" + response.gameId);
744 // NOTE: for live games only (corr games start on the server)
745 startNewGame: function(gameInfo) {
746 const game = Object.assign({}, gameInfo, {
747 // (other) Game infos: constant
748 fenStart: gameInfo.fen,
749 vname: this.getVname(gameInfo.vid),
751 // Game state (including FEN): will be updated
753 clocks: [-1, -1], //-1 = unstarted
754 initime: [0, 0], //initialized later
757 GameStorage.add(game);
758 if (this.st.settings.sound >= 1)
759 new Audio("/sounds/newgame.mp3").play().catch(err => {});
760 this.$router.push("/game/" + gameInfo.id);
766 <style lang="sass" scoped>
778 div#peopleWrap > .card
781 @media screen and (min-width: 1281px)
782 div#peopleWrap > .card
785 @media screen and (max-width: 1280px)
786 div#peopleWrap > .card
789 @media screen and (max-width: 767px)
790 div#peopleWrap > .card
801 @media screen and (max-width: 767px)
816 background-color: #c5fefe !important
819 background-color: white
823 @media screen and (max-width: 767px)