3 input#modalInfo.modal(type="checkbox")
4 div#infoDiv(role="dialog" data-checkbox="modalInfo" aria-labelledby="infoMessage")
5 .card.smallpad.small-modal.text-center
6 label.modal-close(for="modalInfo")
8 p(v-html="infoMessage")
9 input#modalNewgame.modal(type="checkbox")
10 div#newgameDiv(role="dialog" data-checkbox="modalNewgame"
11 aria-labelledby="titleFenedit")
12 .card.smallpad(@keyup.enter="newChallenge()")
13 label#closeNewgame.modal-close(for="modalNewgame")
15 label(for="selectVariant") {{ st.tr["Variant"] }} *
16 select#selectVariant(v-model="newchallenge.vid")
17 option(v-for="v in st.variants" :value="v.id"
18 :selected="newchallenge.vid==v.id")
21 label(for="cadence") {{ st.tr["Cadence"] }} *
22 div#predefinedCadences
26 input#cadence(type="text" v-model="newchallenge.cadence"
27 placeholder="5+0, 1h+30s, 7d+1d ...")
28 fieldset(v-if="st.user.id > 0")
29 label(for="selectPlayers") {{ st.tr["Play with?"] }}
30 input#selectPlayers(type="text" v-model="newchallenge.to")
31 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
32 label(for="inputFen") FEN
33 input#inputFen(type="text" v-model="newchallenge.fen")
34 button(@click="newChallenge()") {{ st.tr["Send challenge"] }}
37 button#newGame(onClick="doClick('modalNewgame')") {{ st.tr["New game"] }}
39 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
42 button(@click="setDisplay('c','live',$event)" class="active")
43 | {{ st.tr["Live challenges"] }}
44 button(@click="setDisplay('c','corr',$event)")
45 | {{ st.tr["Correspondance challenges"] }}
46 ChallengeList(v-show="cdisplay=='live'"
47 :challenges="filterChallenges('live')" @click-challenge="clickChallenge")
48 ChallengeList(v-show="cdisplay=='corr'"
49 :challenges="filterChallenges('corr')" @click-challenge="clickChallenge")
51 h3.text-center {{ st.tr["Who's there?"] }}
53 p(v-for="sid in Object.keys(people)" v-if="!!people[sid].name")
54 span {{ people[sid].name }}
55 // Check: anonymous players cannot send individual challenges or be challenged individually
57 v-if="sid != st.user.sid && !!st.user.name && people[sid].id > 0"
58 @click="challOrWatch(sid)"
60 | {{ getActionLabel(sid) }}
61 p.anonymous @nonymous ({{ anonymousCount }})
63 Chat(:newChat="newChat" @mychat="processChat" :pastChats="[]")
67 button(@click="setDisplay('g','live',$event)" class="active")
68 | {{ st.tr["Live games"] }}
69 button(@click="setDisplay('g','corr',$event)")
70 | {{ st.tr["Correspondance games"] }}
71 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
72 @show-game="showGame")
73 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
74 @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] : ""),
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 [document.getElementById("infoDiv"),document.getElementById("newgameDiv")]
216 .forEach(elt => elt.addEventListener("click", processModalClick));
217 document.querySelectorAll("#predefinedCadences > button").forEach(
218 (b) => { b.addEventListener("click",
219 () => { this.newchallenge.cadence = b.innerHTML; }
223 beforeDestroy: function() {
224 this.send("disconnect");
228 send: function(code, obj) {
231 this.conn.send(JSON.stringify(
239 getVname: function(vid) {
240 const variant = this.st.variants.find(v => v.id == vid);
241 // this.st.variants might be uninitialized (variant == null)
242 return (!!variant ? variant.name : "");
244 filterChallenges: function(type) {
245 return this.challenges.filter(c => c.type == type);
247 filterGames: function(type) {
248 return this.games.filter(g => g.type == type);
250 classifyObject: function(o) { //challenge or game
251 return (o.cadence.indexOf('d') === -1 ? "live" : "corr");
253 setDisplay: function(letter, type, e) {
254 this[letter + "display"] = type;
255 e.target.classList.add("active");
256 if (!!e.target.previousElementSibling)
257 e.target.previousElementSibling.classList.remove("active");
259 e.target.nextElementSibling.classList.remove("active");
261 getActionLabel: function(sid) {
262 return this.people[sid].pages.some(p => p == "/")
266 challOrWatch: function(sid) {
267 if (this.people[sid].pages.some(p => p == "/"))
269 // Available, in Hall
270 this.newchallenge.to = this.people[sid].name;
271 doClick("modalNewgame");
275 // In some game, maybe playing maybe not
276 const gid = this.people[sid].page.match(/[a-zA-Z0-9]+$/)[0];
277 this.showGame(this.games.find(g => g.id == gid));
280 showGame: function(g) {
281 // NOTE: we are an observer, since only games I don't play are shown here
282 // ==> Moves sent by connected remote player(s) if live game
283 let url = "/game/" + g.id;
284 if (g.type == "live")
285 url += "?rid=" + g.rids[Math.floor(Math.random() * g.rids.length)];
286 this.$router.push(url);
288 processChat: function(chat) {
289 this.send("newchat", {data:chat});
292 socketMessageListener: function(msg) {
295 const data = JSON.parse(msg.data);
298 case "pollclientsandgamers":
300 // Since people can be both in Hall and Game,
301 // need to track "askIdentity" requests:
302 let identityAsked = {};
303 data.sockIds.forEach(s => {
304 if (s.sid != this.st.user.sid && !identityAsked[s.sid])
306 identityAsked[s.sid] = true;
307 this.send("askidentity", {target:s.sid});
309 if (!this.people[s.sid])
310 this.$set(this.people, s.sid, {id:0, name:"", pages:[s.page || "/"]});
311 else if (!!s.page && this.people[s.sid].pages.indexOf(s.page) < 0)
312 this.people[s.sid].pages.push(s.page);
313 if (!s.page) //peer is in Hall
314 this.send("askchallenge", {target:s.sid});
315 else //peer is in Game
316 this.send("askgame", {target:s.sid});
322 // NOTE: player could have been polled earlier, but might have logged in then
323 // So it's a good idea to ask identity if he was anonymous.
324 // But only ask game / challenge if currently disconnected.
325 if (!this.people[data.from])
327 this.$set(this.people, data.from, {name:"", id:0, pages:[data.page]});
328 if (data.code == "connect")
329 this.send("askchallenge", {target:data.from});
331 this.send("askgame", {target:data.from});
335 // append page if not already in list
336 if (this.people[data.from].pages.indexOf(data.page) < 0)
337 this.people[data.from].pages.push(data.page);
339 if (this.people[data.from].id == 0)
341 this.newConnect[data.from] = true; //for self multi-connects tests
342 this.send("askidentity", {target:data.from});
347 // Disconnect means no more tmpIds:
348 if (data.code == "disconnect")
350 // Remove the live challenge sent by this player:
351 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
355 // Remove the matching live game if now unreachable
356 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
357 const gidx = this.games.findIndex(g => g.id == gid);
360 const game = this.games[gidx];
361 if (game.type == "live" &&
362 game.rids.length == 1 && game.rids[0] == data.from)
364 this.games.splice(gidx, 1);
368 const page = data.page || "/";
369 ArrayFun.remove(this.people[data.from].pages, p => p == page);
370 if (this.people[data.from].pages.length == 0)
371 this.$delete(this.people, data.from);
374 // I logged in elsewhere:
375 alert(this.st.tr["New connexion detected: tab now offline"]);
376 // TODO: this fails. See https://github.com/websockets/ws/issues/489
377 //this.conn.removeEventListener("message", this.socketMessageListener);
378 //this.conn.removeEventListener("close", this.socketCloseListener);
384 // Request for identification (TODO: anonymous shouldn't need to reply)
386 // Decompose to avoid revealing email
387 name: this.st.user.name,
388 sid: this.st.user.sid,
391 this.send("identity", {data:me, target:data.from});
396 const user = data.data;
397 if (!!user.name) //otherwise anonymous
399 // If I multi-connect, kill current connexion if no mark (I'm older)
400 if (this.newConnect[user.sid] && user.id > 0
401 && user.id == this.st.user.id && user.sid != this.st.user.sid)
403 if (!this.killed[this.st.user.sid])
405 this.send("killme", {sid:this.st.user.sid});
406 this.killed[this.st.user.sid] = true;
409 if (user.sid != this.st.user.sid) //I already know my identity...
411 this.$set(this.people, user.sid,
415 pages: this.people[user.sid].pages,
419 delete this.newConnect[user.sid];
424 // Send my current live challenge (if any)
425 const cIdx = this.challenges.findIndex(c =>
426 c.from.sid == this.st.user.sid && c.type == "live");
429 const c = this.challenges[cIdx];
430 // NOTE: in principle, should only send targeted challenge to the target.
431 // But we may not know yet the identity of the target (just name),
432 // so cannot decide if data.from is the target or not.
436 from: this.st.user.sid,
443 this.send("challenge", {data:myChallenge, target:data.from});
447 case "challenge": //after "askchallenge"
450 // NOTE about next condition: see "askchallenge" case.
451 const chall = data.data;
452 if (!chall.to || (this.people[chall.from].id > 0 &&
453 (chall.from == this.st.user.sid || chall.to == this.st.user.name)))
455 let newChall = Object.assign({}, chall);
456 newChall.type = this.classifyObject(chall);
457 newChall.added = Date.now();
458 let fromValues = Object.assign({}, this.people[chall.from]);
459 delete fromValues["pages"]; //irrelevant in this context
460 newChall.from = Object.assign({sid:chall.from}, fromValues);
461 newChall.vname = this.getVname(newChall.vid);
462 this.challenges.push(newChall);
466 case "refusechallenge":
468 const cid = data.data;
469 ArrayFun.remove(this.challenges, c => c.id == cid);
470 alert(this.st.tr["Challenge declined"]);
473 case "deletechallenge":
475 // NOTE: the challenge may be already removed
476 const cid = data.data;
477 ArrayFun.remove(this.challenges, c => c.id == cid);
480 case "game": //individual request
483 // NOTE: it may be live or correspondance
484 const game = data.data;
485 let locGame = this.games.find(g => g.id == game.id);
489 newGame.type = this.classifyObject(game);
490 newGame.vname = this.getVname(game.vid);
491 if (!game.score) //if new game from Hall
493 this.games.push(newGame);
497 // Append rid (if not already in list)
498 if (!locGame.rids.includes(game.rid))
499 locGame.rids.push(game.rid);
505 // New game just started: data contain all information
506 const gameInfo = data.data;
507 if (this.classifyObject(gameInfo) == "live")
508 this.startNewGame(gameInfo);
511 this.infoMessage = this.st.tr["New correspondance game:"] +
512 " <a href='#/game/" + gameInfo.id + "'>" +
513 "#/game/" + gameInfo.id + "</a>";
514 let modalBox = document.getElementById("modalInfo");
515 modalBox.checked = true;
516 setTimeout(() => { modalBox.checked = false; }, 3000);
521 this.newChat = data.data;
525 socketCloseListener: function() {
528 this.conn = new WebSocket(this.connexionString);
529 this.conn.addEventListener("message", this.socketMessageListener);
530 this.conn.addEventListener("close", this.socketCloseListener);
532 // Challenge lifecycle:
533 newChallenge: async function() {
534 if (this.newchallenge.vid == "")
535 return alert(this.st.tr["Please select a variant"]);
536 if (!!this.newchallenge.to && this.newchallenge.to == this.st.user.name)
537 return alert(this.st.tr["Self-challenge is forbidden"]);
538 const vname = this.getVname(this.newchallenge.vid);
539 const vModule = await import("@/variants/" + vname + ".js");
540 window.V = vModule.VariantRules;
541 if (!!this.newchallenge.cadence.match(/^[0-9]+$/))
542 this.newchallenge.cadence += "+0"; //assume minutes, no increment
543 const error = checkChallenge(this.newchallenge);
546 const ctype = this.classifyObject(this.newchallenge);
547 if (ctype == "corr" && this.st.user.id <= 0)
548 return alert(this.st.tr["Please log in to play correspondance games"]);
549 // NOTE: "from" information is not required here
550 let chall = Object.assign({}, this.newchallenge);
551 const finishAddChallenge = (cid) => {
552 chall.id = cid || "c" + getRandString();
553 // Remove old challenge if any (only one at a time of a given type):
554 const cIdx = this.challenges.findIndex(c =>
555 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) && c.type == ctype);
558 // Delete current challenge (will be replaced now)
559 this.send("deletechallenge", {data:this.challenges[cIdx].id});
565 {id: this.challenges[cIdx].id}
568 this.challenges.splice(cIdx, 1);
570 this.send("newchallenge", {data:Object.assign({from:this.st.user.sid}, chall)});
571 // Add new challenge:
572 chall.from = { //decompose to avoid revealing email
573 sid: this.st.user.sid,
575 name: this.st.user.name,
577 chall.added = Date.now();
578 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
581 this.challenges.push(chall);
582 // Remember cadence + vid for quicker further challenges:
583 localStorage.setItem("cadence", chall.cadence);
584 localStorage.setItem("vid", chall.vid);
585 document.getElementById("modalNewgame").checked = false;
589 // Live challenges have a random ID
590 finishAddChallenge(null);
594 // Correspondance game: send challenge to server
599 response => { finishAddChallenge(response.cid); }
603 clickChallenge: function(c) {
604 const myChallenge = (c.from.sid == this.st.user.sid //live
605 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
608 if (c.type == "corr" && this.st.user.id <= 0)
609 return alert(this.st.tr["Please log in to accept corr challenges"]);
611 if (!!c.to) //c.to == this.st.user.name (connected)
613 // TODO: if special FEN, show diagram after loading variant
614 c.accepted = confirm("Accept challenge?");
618 c.seat = { //again, avoid c.seat = st.user to not reveal email
619 sid: this.st.user.sid,
621 name: this.st.user.name,
627 this.send("refusechallenge", {data:c.id, target:c.from.sid});
629 this.send("deletechallenge", {data:c.id});
633 if (c.type == "corr")
641 this.send("deletechallenge", {data:c.id});
643 // In all cases, the challenge is consumed:
644 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
646 // NOTE: when launching game, the challenge is already being deleted
647 launchGame: async function(c) {
648 const vModule = await import("@/variants/" + c.vname + ".js");
649 window.V = vModule.VariantRules;
650 // These game informations will be shared
654 fen: c.fen || V.GenRandInitFen(),
655 players: shuffle([c.from, c.seat]), //white then black
659 let oppsid = c.from.sid; //may not be defined if corr + offline opp
662 oppsid = Object.keys(this.people).find(sid =>
663 this.people[sid].id == c.from.id);
665 const notifyNewgame = () => {
666 if (!!oppsid) //opponent is online
667 this.send("startgame", {data:gameInfo, target:oppsid});
668 // Send game info (only if live) to everyone except me in this tab
669 this.send("newgame", {data:gameInfo});
671 if (c.type == "live")
674 this.startNewGame(gameInfo);
676 else //corr: game only on server
681 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
683 gameInfo.id = response.gameId;
685 this.$router.push("/game/" + response.gameId);
690 // NOTE: for live games only (corr games start on the server)
691 startNewGame: function(gameInfo) {
692 const game = Object.assign({}, gameInfo, {
693 // (other) Game infos: constant
694 fenStart: gameInfo.fen,
695 vname: this.getVname(gameInfo.vid),
697 // Game state (including FEN): will be updated
699 clocks: [-1, -1], //-1 = unstarted
700 initime: [0, 0], //initialized later
703 GameStorage.add(game);
704 if (this.st.settings.sound >= 1)
705 new Audio("/sounds/newgame.mp3").play().catch(err => {});
706 this.$router.push("/game/" + gameInfo.id);
712 <style lang="sass" scoped>
717 margin: 10px auto 5px auto
728 @media screen and (max-width: 767px)