3 input#modalInfo.modal(type="checkbox")
4 div#infoDiv(role="dialog" data-checkbox="modalInfo")
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 .card(@keyup.enter="newChallenge()")
12 label#closeNewgame.modal-close(for="modalNewgame")
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(@click="setDisplay('c','live',$event)" class="active")
42 | {{ st.tr["Live challenges"] }}
43 button(@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 // Check: anonymous players cannot send individual challenges or be challenged individually
56 v-if="sid != st.user.sid && !!st.user.name && people[sid].id > 0"
57 @click="challOrWatch(sid)"
59 | {{ getActionLabel(sid) }}
60 p.anonymous @nonymous ({{ anonymousCount }})
62 Chat(:newChat="newChat" @mychat="processChat" :pastChats="[]")
66 button(@click="setDisplay('g','live',$event)" class="active")
67 | {{ st.tr["Live games"] }}
68 button(@click="setDisplay('g','corr',$event)")
69 | {{ st.tr["Correspondance games"] }}
70 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
71 @show-game="showGame")
72 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
73 @show-game="showGame")
77 import { store } from "@/store";
78 import { checkChallenge } from "@/data/challengeCheck";
79 import { ArrayFun } from "@/utils/array";
80 import { ajax } from "@/utils/ajax";
81 import params from "@/parameters";
82 import { getRandString, shuffle } from "@/utils/alea";
83 import Chat from "@/components/Chat.vue";
84 import GameList from "@/components/GameList.vue";
85 import ChallengeList from "@/components/ChallengeList.vue";
86 import { GameStorage } from "@/utils/gameStorage";
87 import { processModalClick } from "@/utils/modalClick";
98 cdisplay: "live", //or corr
106 vid: localStorage.getItem("vid") || "",
107 to: "", //name of challenged player (if any)
108 cadence: localStorage.getItem("cadence") || "",
113 // Related to (killing of) self multi-connects:
119 // st.variants changes only once, at loading from [] to [...]
120 "st.variants": function(variantArray) {
121 // Set potential challenges and games variant names:
122 this.challenges.concat(this.games).forEach(o => {
124 o.vname = this.getVname(o.vid);
129 anonymousCount: function() {
131 Object.values(this.people).forEach(p => { count += (!p.name ? 1 : 0); });
135 created: function() {
136 const my = this.st.user;
137 this.$set(this.people, my.sid, {id:my.id, name:my.name, pages:["/"]});
138 // Ask server for current corr games (all but mines)
142 {uid: this.st.user.id, excluded: true},
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},
157 // Gather all senders names, and then retrieve full identity:
158 // (TODO [perf]: some might be online...)
160 response.challenges.forEach(c => {
161 if (c.uid != this.st.user.id)
162 names[c.uid] = ""; //unknwon for now
163 else if (!!c.target && c.target != this.st.user.id)
164 names[c.target] = "";
166 const addChallenges = (newChalls) => {
167 names[this.st.user.id] = this.st.user.name; //in case of
168 this.challenges = this.challenges.concat(
169 response.challenges.map(c => {
170 const from = {name: names[c.uid], id: c.uid}; //or just name
171 const type = this.classifyObject(c);
172 const vname = this.getVname(c.vid);
173 return Object.assign({},
178 to: (!!c.target ? names[c.target] : ""),
188 { ids: Object.keys(names).join(",") },
190 response2.users.forEach(u => {names[u.id] = u.name});
199 const connectAndPoll = () => {
200 this.send("connect");
201 this.send("pollclientsandgamers");
203 // Initialize connection
204 this.connexionString = params.socketUrl +
205 "/?sid=" + this.st.user.sid +
206 "&tmpId=" + getRandString() +
207 "&page=" + encodeURIComponent(this.$route.path);
208 this.conn = new WebSocket(this.connexionString);
209 this.conn.onopen = connectAndPoll;
210 this.conn.onmessage = this.socketMessageListener;
211 this.conn.onclose = this.socketCloseListener;
213 mounted: function() {
214 [document.getElementById("infoDiv"),document.getElementById("newgameDiv")]
215 .forEach(elt => elt.addEventListener("click", processModalClick));
216 document.querySelectorAll("#predefinedCadences > button").forEach(
217 (b) => { b.addEventListener("click",
218 () => { this.newchallenge.cadence = b.innerHTML; }
222 beforeDestroy: function() {
223 this.send("disconnect");
227 send: function(code, obj) {
230 this.conn.send(JSON.stringify(
238 getVname: function(vid) {
239 const variant = this.st.variants.find(v => v.id == vid);
240 // this.st.variants might be uninitialized (variant == null)
241 return (!!variant ? variant.name : "");
243 filterChallenges: function(type) {
244 return this.challenges.filter(c => c.type == type);
246 filterGames: function(type) {
247 return this.games.filter(g => g.type == type);
249 classifyObject: function(o) { //challenge or game
250 return (o.cadence.indexOf('d') === -1 ? "live" : "corr");
252 setDisplay: function(letter, type, e) {
253 this[letter + "display"] = type;
254 e.target.classList.add("active");
255 if (!!e.target.previousElementSibling)
256 e.target.previousElementSibling.classList.remove("active");
258 e.target.nextElementSibling.classList.remove("active");
260 getActionLabel: function(sid) {
261 return this.people[sid].pages.some(p => p == "/")
265 challOrWatch: function(sid) {
266 if (this.people[sid].pages.some(p => p == "/"))
268 // Available, in Hall
269 this.newchallenge.to = this.people[sid].name;
270 doClick("modalNewgame");
274 // In some game, maybe playing maybe not
275 const gid = this.people[sid].page.match(/[a-zA-Z0-9]+$/)[0];
276 this.showGame(this.games.find(g => g.id == gid));
279 showGame: function(g) {
280 // NOTE: we are an observer, since only games I don't play are shown here
281 // ==> Moves sent by connected remote player(s) if live game
282 let url = "/game/" + g.id;
283 if (g.type == "live")
284 url += "?rid=" + g.rids[Math.floor(Math.random() * g.rids.length)];
285 this.$router.push(url);
287 processChat: function(chat) {
288 this.send("newchat", {data:chat});
291 socketMessageListener: function(msg) {
294 const data = JSON.parse(msg.data);
297 case "pollclientsandgamers":
299 // Since people can be both in Hall and Game,
300 // need to track "askIdentity" requests:
301 let identityAsked = {};
302 data.sockIds.forEach(s => {
303 if (s.sid != this.st.user.sid && !identityAsked[s.sid])
305 identityAsked[s.sid] = true;
306 this.send("askidentity", {target:s.sid});
308 if (!this.people[s.sid])
309 this.$set(this.people, s.sid, {id:0, name:"", pages:[s.page || "/"]});
310 else if (!!s.page && this.people[s.sid].pages.indexOf(s.page) < 0)
311 this.people[s.sid].pages.push(s.page);
312 if (!s.page) //peer is in Hall
313 this.send("askchallenge", {target:s.sid});
314 else //peer is in Game
315 this.send("askgame", {target:s.sid});
321 // NOTE: player could have been polled earlier, but might have logged in then
322 // So it's a good idea to ask identity if he was anonymous.
323 // But only ask game / challenge if currently disconnected.
324 if (!this.people[data.from])
326 this.$set(this.people, data.from, {name:"", id:0, pages:[data.page]});
327 if (data.code == "connect")
328 this.send("askchallenge", {target:data.from});
330 this.send("askgame", {target:data.from});
334 // append page if not already in list
335 if (this.people[data.from].pages.indexOf(data.page) < 0)
336 this.people[data.from].pages.push(data.page);
338 if (this.people[data.from].id == 0)
340 this.newConnect[data.from] = true; //for self multi-connects tests
341 this.send("askidentity", {target:data.from});
346 // Disconnect means no more tmpIds:
347 if (data.code == "disconnect")
349 // Remove the live challenge sent by this player:
350 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
354 // Remove the matching live game if now unreachable
355 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
356 const gidx = this.games.findIndex(g => g.id == gid);
359 const game = this.games[gidx];
360 if (game.type == "live" &&
361 game.rids.length == 1 && game.rids[0] == data.from)
363 this.games.splice(gidx, 1);
367 const page = data.page || "/";
368 ArrayFun.remove(this.people[data.from].pages, p => p == page);
369 if (this.people[data.from].pages.length == 0)
370 this.$delete(this.people, data.from);
373 // I logged in elsewhere:
374 alert(this.st.tr["New connexion detected: tab now offline"]);
375 // TODO: this fails. See https://github.com/websockets/ws/issues/489
376 //this.conn.removeEventListener("message", this.socketMessageListener);
377 //this.conn.removeEventListener("close", this.socketCloseListener);
383 // Request for identification (TODO: anonymous shouldn't need to reply)
385 // Decompose to avoid revealing email
386 name: this.st.user.name,
387 sid: this.st.user.sid,
390 this.send("identity", {data:me, target:data.from});
395 const user = data.data;
396 if (!!user.name) //otherwise anonymous
398 // If I multi-connect, kill current connexion if no mark (I'm older)
399 if (this.newConnect[user.sid] && user.id > 0
400 && user.id == this.st.user.id && user.sid != this.st.user.sid)
402 if (!this.killed[this.st.user.sid])
404 this.send("killme", {sid:this.st.user.sid});
405 this.killed[this.st.user.sid] = true;
408 if (user.sid != this.st.user.sid) //I already know my identity...
410 this.$set(this.people, user.sid,
414 pages: this.people[user.sid].pages,
418 delete this.newConnect[user.sid];
423 // Send my current live challenge (if any)
424 const cIdx = this.challenges.findIndex(c =>
425 c.from.sid == this.st.user.sid && c.type == "live");
428 const c = this.challenges[cIdx];
429 // NOTE: in principle, should only send targeted challenge to the target.
430 // But we may not know yet the identity of the target (just name),
431 // so cannot decide if data.from is the target or not.
435 from: this.st.user.sid,
442 this.send("challenge", {data:myChallenge, target:data.from});
446 case "challenge": //after "askchallenge"
449 // NOTE about next condition: see "askchallenge" case.
450 const chall = data.data;
451 if (!chall.to || (this.people[chall.from].id > 0 &&
452 (chall.from == this.st.user.sid || chall.to == this.st.user.name)))
454 let newChall = Object.assign({}, chall);
455 newChall.type = this.classifyObject(chall);
456 newChall.added = Date.now();
457 let fromValues = Object.assign({}, this.people[chall.from]);
458 delete fromValues["pages"]; //irrelevant in this context
459 newChall.from = Object.assign({sid:chall.from}, fromValues);
460 newChall.vname = this.getVname(newChall.vid);
461 this.challenges.push(newChall);
465 case "refusechallenge":
467 const cid = data.data;
468 ArrayFun.remove(this.challenges, c => c.id == cid);
469 alert(this.st.tr["Challenge declined"]);
472 case "deletechallenge":
474 // NOTE: the challenge may be already removed
475 const cid = data.data;
476 ArrayFun.remove(this.challenges, c => c.id == cid);
479 case "game": //individual request
482 // NOTE: it may be live or correspondance
483 const game = data.data;
484 let locGame = this.games.find(g => g.id == game.id);
488 newGame.type = this.classifyObject(game);
489 newGame.vname = this.getVname(game.vid);
490 if (!game.score) //if new game from Hall
492 this.games.push(newGame);
496 // Append rid (if not already in list)
497 if (!locGame.rids.includes(game.rid))
498 locGame.rids.push(game.rid);
504 // New game just started: data contain all information
505 const gameInfo = data.data;
506 if (this.classifyObject(gameInfo) == "live")
507 this.startNewGame(gameInfo);
510 this.infoMessage = this.st.tr["New correspondance game:"] +
511 " <a href='#/game/" + gameInfo.id + "'>" +
512 "#/game/" + gameInfo.id + "</a>";
513 let modalBox = document.getElementById("modalInfo");
514 modalBox.checked = true;
515 setTimeout(() => { modalBox.checked = false; }, 3000);
520 this.newChat = data.data;
524 socketCloseListener: function() {
527 this.conn = new WebSocket(this.connexionString);
528 this.conn.addEventListener("message", this.socketMessageListener);
529 this.conn.addEventListener("close", this.socketCloseListener);
531 // Challenge lifecycle:
532 newChallenge: async function() {
533 if (this.newchallenge.vid == "")
534 return alert(this.st.tr["Please select a variant"]);
535 if (!!this.newchallenge.to && this.newchallenge.to == this.st.user.name)
536 return alert(this.st.tr["Self-challenge is forbidden"]);
537 const vname = this.getVname(this.newchallenge.vid);
538 const vModule = await import("@/variants/" + vname + ".js");
539 window.V = vModule.VariantRules;
540 if (!!this.newchallenge.cadence.match(/^[0-9]+$/))
541 this.newchallenge.cadence += "+0"; //assume minutes, no increment
542 const error = checkChallenge(this.newchallenge);
545 const ctype = this.classifyObject(this.newchallenge);
546 if (ctype == "corr" && this.st.user.id <= 0)
547 return alert(this.st.tr["Please log in to play correspondance games"]);
548 // NOTE: "from" information is not required here
549 let chall = Object.assign({}, this.newchallenge);
550 const finishAddChallenge = (cid) => {
551 chall.id = cid || "c" + getRandString();
552 // Remove old challenge if any (only one at a time of a given type):
553 const cIdx = this.challenges.findIndex(c =>
554 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) && c.type == ctype);
557 // Delete current challenge (will be replaced now)
558 this.send("deletechallenge", {data:this.challenges[cIdx].id});
564 {id: this.challenges[cIdx].id}
567 this.challenges.splice(cIdx, 1);
569 this.send("newchallenge", {data:Object.assign({from:this.st.user.sid}, chall)});
570 // Add new challenge:
571 chall.from = { //decompose to avoid revealing email
572 sid: this.st.user.sid,
574 name: this.st.user.name,
576 chall.added = Date.now();
577 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
580 this.challenges.push(chall);
581 // Remember cadence + vid for quicker further challenges:
582 localStorage.setItem("cadence", chall.cadence);
583 localStorage.setItem("vid", chall.vid);
584 document.getElementById("modalNewgame").checked = false;
588 // Live challenges have a random ID
589 finishAddChallenge(null);
593 // Correspondance game: send challenge to server
598 response => { finishAddChallenge(response.cid); }
602 clickChallenge: function(c) {
603 const myChallenge = (c.from.sid == this.st.user.sid //live
604 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
607 if (c.type == "corr" && this.st.user.id <= 0)
608 return alert(this.st.tr["Please log in to accept corr challenges"]);
610 if (!!c.to) //c.to == this.st.user.name (connected)
612 // TODO: if special FEN, show diagram after loading variant
613 c.accepted = confirm("Accept challenge?");
617 c.seat = { //again, avoid c.seat = st.user to not reveal email
618 sid: this.st.user.sid,
620 name: this.st.user.name,
626 this.send("refusechallenge", {data:c.id, target:c.from.sid});
628 this.send("deletechallenge", {data:c.id});
632 if (c.type == "corr")
640 this.send("deletechallenge", {data:c.id});
642 // In all cases, the challenge is consumed:
643 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
645 // NOTE: when launching game, the challenge is already being deleted
646 launchGame: async function(c) {
647 const vModule = await import("@/variants/" + c.vname + ".js");
648 window.V = vModule.VariantRules;
649 // These game informations will be shared
653 fen: c.fen || V.GenRandInitFen(),
654 players: shuffle([c.from, c.seat]), //white then black
658 let oppsid = c.from.sid; //may not be defined if corr + offline opp
661 oppsid = Object.keys(this.people).find(sid =>
662 this.people[sid].id == c.from.id);
664 const notifyNewgame = () => {
665 if (!!oppsid) //opponent is online
666 this.send("startgame", {data:gameInfo, target:oppsid});
667 // Send game info (only if live) to everyone except me in this tab
668 this.send("newgame", {data:gameInfo});
670 if (c.type == "live")
673 this.startNewGame(gameInfo);
675 else //corr: game only on server
680 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
682 gameInfo.id = response.gameId;
684 this.$router.push("/game/" + response.gameId);
689 // NOTE: for live games only (corr games start on the server)
690 startNewGame: function(gameInfo) {
691 const game = Object.assign({}, gameInfo, {
692 // (other) Game infos: constant
693 fenStart: gameInfo.fen,
694 vname: this.getVname(gameInfo.vid),
696 // Game state (including FEN): will be updated
698 clocks: [-1, -1], //-1 = unstarted
699 initime: [0, 0], //initialized later
702 GameStorage.add(game);
703 if (this.st.settings.sound >= 1)
704 new Audio("/sounds/newgame.mp3").play().catch(err => {});
705 this.$router.push("/game/" + gameInfo.id);
711 <style lang="sass" scoped>
716 margin: 10px auto 5px auto
735 @media screen and (max-width: 767px)