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"] }}
36 button#newGame(onClick="doClick('modalNewgame')") {{ st.tr["New game"] }}
38 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
41 button#btnClive(@click="setDisplay('c','live',$event)" class="active")
42 | {{ st.tr["Live challenges"] }}
43 button#btnCcorr(@click="setDisplay('c','corr',$event)")
44 | {{ st.tr["Correspondance challenges"] }}
45 ChallengeList(v-show="cdisplay=='live'"
46 :challenges="filterChallenges('live')" @click-challenge="clickChallenge")
47 ChallengeList(v-show="cdisplay=='corr'"
48 :challenges="filterChallenges('corr')" @click-challenge="clickChallenge")
50 h3.text-center {{ st.tr["Who's there?"] }}
52 p(v-for="sid in Object.keys(people)" v-if="!!people[sid].name")
53 span {{ people[sid].name }}
54 button.player-action(v-if="sid!=st.user.sid || isGamer(sid)" @click="challOrWatch(sid)")
55 | {{ getActionLabel(sid) }}
56 p.anonymous @nonymous ({{ anonymousCount }})
58 Chat(:newChat="newChat" @mychat="processChat" :pastChats="[]")
62 button#btnGlive(@click="setDisplay('g','live',$event)" class="active")
63 | {{ st.tr["Live games"] }}
64 button#btnGcorr(@click="setDisplay('g','corr',$event)")
65 | {{ st.tr["Correspondance games"] }}
66 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
67 @show-game="showGame")
68 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
69 @show-game="showGame")
73 import { store } from "@/store";
74 import { checkChallenge } from "@/data/challengeCheck";
75 import { ArrayFun } from "@/utils/array";
76 import { ajax } from "@/utils/ajax";
77 import params from "@/parameters";
78 import { getRandString, shuffle } from "@/utils/alea";
79 import Chat from "@/components/Chat.vue";
80 import GameList from "@/components/GameList.vue";
81 import ChallengeList from "@/components/ChallengeList.vue";
82 import { GameStorage } from "@/utils/gameStorage";
83 import { processModalClick } from "@/utils/modalClick";
94 cdisplay: "live", //or corr
102 vid: localStorage.getItem("vid") || "",
103 to: "", //name of challenged player (if any)
104 cadence: localStorage.getItem("cadence") || "",
109 // Related to (killing of) self multi-connects:
115 // st.variants changes only once, at loading from [] to [...]
116 "st.variants": function(variantArray) {
117 // Set potential challenges and games variant names:
118 this.challenges.concat(this.games).forEach(o => {
120 o.vname = this.getVname(o.vid);
125 anonymousCount: function() {
127 Object.values(this.people).forEach(p => { count += (!p.name ? 1 : 0); });
131 created: function() {
132 const my = this.st.user;
133 this.$set(this.people, my.sid, {id:my.id, name:my.name, pages:["/"]});
134 // Ask server for current corr games (all but mines)
138 {uid: this.st.user.id, excluded: true},
140 // Show corr tab with timeout, to let enough time for (socket) polling
143 if (response.games.length > 0 &&
144 this.games.length == response.games.length)
146 this.setDisplay('g', "corr");
151 this.games = this.games.concat(response.games.map(g => {
152 const type = this.classifyObject(g);
153 const vname = this.getVname(g.vid);
154 return Object.assign({}, g, {type: type, vname: vname});
158 // Also ask for corr challenges (open + sent by/to me)
162 {uid: this.st.user.id},
166 if (response.challenges.length > 0 &&
167 this.challenges.length == response.challenges.length)
169 this.setDisplay('c', "corr");
174 // Gather all senders names, and then retrieve full identity:
175 // (TODO [perf]: some might be online...)
177 response.challenges.forEach(c => {
178 if (c.uid != this.st.user.id)
179 names[c.uid] = ""; //unknwon for now
180 else if (!!c.target && c.target != this.st.user.id)
181 names[c.target] = "";
183 const addChallenges = (newChalls) => {
184 names[this.st.user.id] = this.st.user.name; //in case of
185 this.challenges = this.challenges.concat(
186 response.challenges.map(c => {
187 const from = {name: names[c.uid], id: c.uid}; //or just name
188 const type = this.classifyObject(c);
189 const vname = this.getVname(c.vid);
190 return Object.assign({},
195 to: (!!c.target ? names[c.target] : ""),
205 { ids: Object.keys(names).join(",") },
207 response2.users.forEach(u => {names[u.id] = u.name});
216 const connectAndPoll = () => {
217 this.send("connect");
218 this.send("pollclientsandgamers");
220 // Initialize connection
221 this.connexionString = params.socketUrl +
222 "/?sid=" + this.st.user.sid +
223 "&tmpId=" + getRandString() +
224 "&page=" + encodeURIComponent(this.$route.path);
225 this.conn = new WebSocket(this.connexionString);
226 this.conn.onopen = connectAndPoll;
227 this.conn.onmessage = this.socketMessageListener;
228 this.conn.onclose = this.socketCloseListener;
230 mounted: function() {
231 [document.getElementById("infoDiv"),document.getElementById("newgameDiv")]
232 .forEach(elt => elt.addEventListener("click", processModalClick));
233 document.querySelectorAll("#predefinedCadences > button").forEach(
234 (b) => { b.addEventListener("click",
235 () => { this.newchallenge.cadence = b.innerHTML; }
239 beforeDestroy: function() {
240 this.send("disconnect");
244 send: function(code, obj) {
247 this.conn.send(JSON.stringify(
255 getVname: function(vid) {
256 const variant = this.st.variants.find(v => v.id == vid);
257 // this.st.variants might be uninitialized (variant == null)
258 return (!!variant ? variant.name : "");
260 filterChallenges: function(type) {
261 return this.challenges.filter(c => c.type == type);
263 filterGames: function(type) {
264 return this.games.filter(g => g.type == type);
266 classifyObject: function(o) { //challenge or game
267 return (o.cadence.indexOf('d') === -1 ? "live" : "corr");
269 setDisplay: function(letter, type, e) {
270 this[letter + "display"] = type;
273 : document.getElementById("btn" + letter.toUpperCase() + type);
274 elt.classList.add("active");
275 if (!!elt.previousElementSibling)
276 elt.previousElementSibling.classList.remove("active");
278 elt.nextElementSibling.classList.remove("active");
280 isGamer: function(sid) {
281 return this.people[sid].pages.some(p => p.indexOf("/game/") >= 0);
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 the user reloads the page twice very quickly (experienced with Firefox),
380 // the first reload won't have time to connect but will trigger a "close" event anyway.
381 // ==> Next check is required.
382 if (!this.people[data.from])
384 // Disconnect means no more tmpIds:
385 if (data.code == "disconnect")
387 // Remove the live challenge sent by this player:
388 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
392 // Remove the matching live game if now unreachable
393 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
394 const gidx = this.games.findIndex(g => g.id == gid);
397 const game = this.games[gidx];
398 if (game.type == "live" &&
399 game.rids.length == 1 && game.rids[0] == data.from)
401 this.games.splice(gidx, 1);
405 const page = data.page || "/";
406 ArrayFun.remove(this.people[data.from].pages, p => p == page);
407 if (this.people[data.from].pages.length == 0)
408 this.$delete(this.people, data.from);
411 // I logged in elsewhere:
412 alert(this.st.tr["New connexion detected: tab now offline"]);
413 // TODO: this fails. See https://github.com/websockets/ws/issues/489
414 //this.conn.removeEventListener("message", this.socketMessageListener);
415 //this.conn.removeEventListener("close", this.socketCloseListener);
421 // Request for identification (TODO: anonymous shouldn't need to reply)
423 // Decompose to avoid revealing email
424 name: this.st.user.name,
425 sid: this.st.user.sid,
428 this.send("identity", {data:me, target:data.from});
433 const user = data.data;
434 if (!!user.name) //otherwise anonymous
436 // If I multi-connect, kill current connexion if no mark (I'm older)
437 if (this.newConnect[user.sid] && user.id > 0
438 && user.id == this.st.user.id && user.sid != this.st.user.sid)
440 if (!this.killed[this.st.user.sid])
442 this.send("killme", {sid:this.st.user.sid});
443 this.killed[this.st.user.sid] = true;
446 if (user.sid != this.st.user.sid) //I already know my identity...
448 this.$set(this.people, user.sid,
452 pages: this.people[user.sid].pages,
456 delete this.newConnect[user.sid];
461 // Send my current live challenge (if any)
462 const cIdx = this.challenges.findIndex(c =>
463 c.from.sid == this.st.user.sid && c.type == "live");
466 const c = this.challenges[cIdx];
467 // NOTE: in principle, should only send targeted challenge to the target.
468 // But we may not know yet the identity of the target (just name),
469 // so cannot decide if data.from is the target or not.
473 from: this.st.user.sid,
480 this.send("challenge", {data:myChallenge, target:data.from});
484 case "challenge": //after "askchallenge"
487 // NOTE about next condition: see "askchallenge" case.
488 const chall = data.data;
489 if (!chall.to || (this.people[chall.from].id > 0 &&
490 (chall.from == this.st.user.sid || chall.to == this.st.user.name)))
492 let newChall = Object.assign({}, chall);
493 newChall.type = this.classifyObject(chall);
494 newChall.added = Date.now();
495 let fromValues = Object.assign({}, this.people[chall.from]);
496 delete fromValues["pages"]; //irrelevant in this context
497 newChall.from = Object.assign({sid:chall.from}, fromValues);
498 newChall.vname = this.getVname(newChall.vid);
499 this.challenges.push(newChall);
501 if (newChall.type == "live" && this.cdisplay == "corr" && !this.challenges.some(c => c.type == "corr"))
502 this.setDisplay('c', "live");
503 else if (newChall.type == "corr" && this.cdisplay == "live" && !this.challenges.some(c => c.type == "live"))
504 this.setDisplay('c', "corr");
508 case "refusechallenge":
510 const cid = data.data;
511 ArrayFun.remove(this.challenges, c => c.id == cid);
512 alert(this.st.tr["Challenge declined"]);
515 case "deletechallenge":
517 // NOTE: the challenge may be already removed
518 const cid = data.data;
519 ArrayFun.remove(this.challenges, c => c.id == cid);
522 case "game": //individual request
525 // NOTE: it may be live or correspondance
526 const game = data.data;
527 let locGame = this.games.find(g => g.id == game.id);
531 newGame.type = this.classifyObject(game);
532 newGame.vname = this.getVname(game.vid);
533 if (!game.score) //if new game from Hall
535 newGame.rids = [game.rid];
536 delete newGame["rid"];
537 this.games.push(newGame);
539 if (newGame.type == "live" && this.gdisplay == "corr" && !this.games.some(g => g.type == "corr"))
540 this.setDisplay('g', "live");
541 else if (newGame.type == "live" && this.gdisplay == "live" && !this.games.some(g => g.type == "live"))
542 this.setDisplay('g', "corr");
546 // Append rid (if not already in list)
547 if (!locGame.rids.includes(game.rid))
548 locGame.rids.push(game.rid);
554 let g = this.games.find(g => g.id == data.gid);
556 g.score = data.score;
561 // New game just started: data contain all information
562 const gameInfo = data.data;
563 if (this.classifyObject(gameInfo) == "live")
564 this.startNewGame(gameInfo);
567 this.infoMessage = this.st.tr["New correspondance game:"] +
568 " <a href='#/game/" + gameInfo.id + "'>" +
569 "#/game/" + gameInfo.id + "</a>";
570 let modalBox = document.getElementById("modalInfo");
571 modalBox.checked = true;
576 this.newChat = data.data;
580 socketCloseListener: function() {
583 this.conn = new WebSocket(this.connexionString);
584 this.conn.addEventListener("message", this.socketMessageListener);
585 this.conn.addEventListener("close", this.socketCloseListener);
587 // Challenge lifecycle:
588 newChallenge: async function() {
589 if (this.newchallenge.vid == "")
590 return alert(this.st.tr["Please select a variant"]);
591 if (!!this.newchallenge.to && this.newchallenge.to == this.st.user.name)
592 return alert(this.st.tr["Self-challenge is forbidden"]);
593 const vname = this.getVname(this.newchallenge.vid);
594 const vModule = await import("@/variants/" + vname + ".js");
595 window.V = vModule.VariantRules;
596 if (!!this.newchallenge.cadence.match(/^[0-9]+$/))
597 this.newchallenge.cadence += "+0"; //assume minutes, no increment
598 const error = checkChallenge(this.newchallenge);
601 const ctype = this.classifyObject(this.newchallenge);
602 if (ctype == "corr" && this.st.user.id <= 0)
603 return alert(this.st.tr["Please log in to play correspondance games"]);
604 // NOTE: "from" information is not required here
605 let chall = Object.assign({}, this.newchallenge);
606 const finishAddChallenge = (cid) => {
607 chall.id = cid || "c" + getRandString();
608 // Remove old challenge if any (only one at a time of a given type):
609 const cIdx = this.challenges.findIndex(c =>
610 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) && c.type == ctype);
613 // Delete current challenge (will be replaced now)
614 this.send("deletechallenge", {data:this.challenges[cIdx].id});
620 {id: this.challenges[cIdx].id}
623 this.challenges.splice(cIdx, 1);
625 this.send("newchallenge", {data:Object.assign({from:this.st.user.sid}, chall)});
626 // Add new challenge:
627 chall.from = { //decompose to avoid revealing email
628 sid: this.st.user.sid,
630 name: this.st.user.name,
632 chall.added = Date.now();
633 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
636 this.challenges.push(chall);
637 // Remember cadence + vid for quicker further challenges:
638 localStorage.setItem("cadence", chall.cadence);
639 localStorage.setItem("vid", chall.vid);
640 document.getElementById("modalNewgame").checked = false;
644 // Live challenges have a random ID
645 finishAddChallenge(null);
649 // Correspondance game: send challenge to server
654 response => { finishAddChallenge(response.cid); }
658 clickChallenge: function(c) {
659 const myChallenge = (c.from.sid == this.st.user.sid //live
660 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
663 if (c.type == "corr" && this.st.user.id <= 0)
664 return alert(this.st.tr["Please log in to accept corr challenges"]);
666 if (!!c.to) //c.to == this.st.user.name (connected)
668 // TODO: if special FEN, show diagram after loading variant
669 c.accepted = confirm("Accept challenge?");
673 c.seat = { //again, avoid c.seat = st.user to not reveal email
674 sid: this.st.user.sid,
676 name: this.st.user.name,
682 this.send("refusechallenge", {data:c.id, target:c.from.sid});
684 this.send("deletechallenge", {data:c.id});
688 if (c.type == "corr")
696 this.send("deletechallenge", {data:c.id});
698 // In all cases, the challenge is consumed:
699 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
701 // NOTE: when launching game, the challenge is already being deleted
702 launchGame: async function(c) {
703 const vModule = await import("@/variants/" + c.vname + ".js");
704 window.V = vModule.VariantRules;
705 // These game informations will be shared
709 fen: c.fen || V.GenRandInitFen(),
710 players: shuffle([c.from, c.seat]), //white then black
714 let oppsid = c.from.sid; //may not be defined if corr + offline opp
717 oppsid = Object.keys(this.people).find(sid =>
718 this.people[sid].id == c.from.id);
720 const notifyNewgame = () => {
721 if (!!oppsid) //opponent is online
722 this.send("startgame", {data:gameInfo, target:oppsid});
723 // Send game info (only if live) to everyone except me in this tab
724 this.send("newgame", {data:gameInfo});
726 if (c.type == "live")
729 this.startNewGame(gameInfo);
731 else //corr: game only on server
736 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
738 gameInfo.id = response.gameId;
740 this.$router.push("/game/" + response.gameId);
745 // NOTE: for live games only (corr games start on the server)
746 startNewGame: function(gameInfo) {
747 const game = Object.assign({}, gameInfo, {
748 // (other) Game infos: constant
749 fenStart: gameInfo.fen,
750 vname: this.getVname(gameInfo.vid),
752 // Game state (including FEN): will be updated
754 clocks: [-1, -1], //-1 = unstarted
755 initime: [0, 0], //initialized later
758 GameStorage.add(game);
759 if (this.st.settings.sound >= 1)
760 new Audio("/sounds/newgame.mp3").play().catch(err => {});
761 this.$router.push("/game/" + gameInfo.id);
767 <style lang="sass" scoped>
772 margin: 10px auto 5px auto
792 @media screen and (max-width: 767px)