3 input#modalInfo.modal(type="checkbox")
6 data-checkbox="modalInfo"
9 label.modal-close(for="modalInfo")
10 p(v-html="infoMessage")
11 input#modalNewgame.modal(type="checkbox")
14 data-checkbox="modalNewgame"
17 label#closeNewgame.modal-close(for="modalNewgame")
18 form(@submit.prevent="newChallenge()" @keyup.enter="newChallenge()")
20 label(for="selectVariant") {{ st.tr["Variant"] }} *
21 select#selectVariant(v-model="newchallenge.vid")
23 v-for="v in st.variants"
25 :selected="newchallenge.vid==v.id"
29 label(for="cadence") {{ st.tr["Cadence"] }} *
30 div#predefinedCadences
36 v-model="newchallenge.cadence"
37 placeholder="5+0, 1h+30s, 7d+1d ..."
39 fieldset(v-if="st.user.id > 0")
40 label(for="selectPlayers") {{ st.tr["Play with?"] }}
43 v-model="newchallenge.to"
45 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
46 label(for="inputFen") FEN
49 v-model="newchallenge.fen"
51 button(@click="newChallenge()") {{ st.tr["Send challenge"] }}
52 input#modalPeople.modal(
54 @click="resetChatColor()"
58 data-checkbox="modalPeople"
61 label.modal-close(for="modalPeople")
65 v-for="sid in Object.keys(people)"
66 v-if="!!people[sid].name"
68 span {{ people[sid].name }}
70 v-if="sid!=st.user.sid || isGamer(sid)"
71 @click="challOrWatch(sid)"
73 | {{ getActionLabel(sid) }}
74 p.anonymous @nonymous ({{ anonymousCount }})
83 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
85 button#peopleBtn(onClick="window.doClick('modalPeople')")
86 | {{ st.tr["Social"] }}
87 button(onClick="window.doClick('modalNewgame')")
88 | {{ st.tr["New game"] }}
90 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
93 button.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
94 | {{ st.tr["Live challenges"] }}
95 button.tabbtn#btnCcorr(@click="setDisplay('c','corr',$event)")
96 | {{ st.tr["Correspondance challenges"] }}
98 v-show="cdisplay=='live'"
99 :challenges="filterChallenges('live')"
100 @click-challenge="clickChallenge"
103 v-show="cdisplay=='corr'"
104 :challenges="filterChallenges('corr')"
105 @click-challenge="clickChallenge"
109 button.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
110 | {{ st.tr["Live games"] }}
111 button.tabbtn#btnGcorr(@click="setDisplay('g','corr',$event)")
112 | {{ st.tr["Correspondance games"] }}
114 v-show="gdisplay=='live'"
115 :games="filterGames('live')"
117 @show-game="showGame"
120 v-show="gdisplay=='corr'"
121 :games="filterGames('corr')"
123 @show-game="showGame"
128 import { store } from "@/store";
129 import { checkChallenge } from "@/data/challengeCheck";
130 import { ArrayFun } from "@/utils/array";
131 import { ajax } from "@/utils/ajax";
132 import params from "@/parameters";
133 import { getRandString, shuffle } from "@/utils/alea";
134 import Chat from "@/components/Chat.vue";
135 import GameList from "@/components/GameList.vue";
136 import ChallengeList from "@/components/ChallengeList.vue";
137 import { GameStorage } from "@/utils/gameStorage";
138 import { processModalClick } from "@/utils/modalClick";
149 cdisplay: "live", //or corr
157 vid: localStorage.getItem("vid") || "",
158 to: "", //name of challenged player (if any)
159 cadence: localStorage.getItem("cadence") || ""
164 // Related to (killing of) self multi-connects:
170 // st.variants changes only once, at loading from [] to [...]
171 "st.variants": function() {
172 // Set potential challenges and games variant names:
173 this.challenges.concat(this.games).forEach(o => {
174 if (o.vname == "") o.vname = this.getVname(o.vid);
179 anonymousCount: function() {
181 Object.values(this.people).forEach(p => {
182 count += !p.name ? 1 : 0;
187 created: function() {
188 const my = this.st.user;
189 this.$set(this.people, my.sid, { id: my.id, name: my.name, pages: ["/"] });
190 // Ask server for current corr games (all but mines)
194 { uid: this.st.user.id, excluded: true },
196 this.games = this.games.concat(
197 response.games.map(g => {
198 const type = this.classifyObject(g);
199 const vname = this.getVname(g.vid);
200 return Object.assign({}, g, { type: type, vname: vname });
205 // Also ask for corr challenges (open + sent by/to me)
206 ajax("/challenges", "GET", { uid: this.st.user.id }, response => {
207 // Gather all senders names, and then retrieve full identity:
208 // (TODO [perf]: some might be online...)
210 response.challenges.forEach(c => {
211 if (c.uid != this.st.user.id) names[c.uid] = "";
213 else if (!!c.target && c.target != this.st.user.id)
214 names[c.target] = "";
216 const addChallenges = () => {
217 names[this.st.user.id] = this.st.user.name; //in case of
218 this.challenges = this.challenges.concat(
219 response.challenges.map(c => {
220 const from = { name: names[c.uid], id: c.uid }; //or just name
221 const type = this.classifyObject(c);
222 const vname = this.getVname(c.vid);
223 return Object.assign(
229 to: c.target ? names[c.target] : ""
236 if (Object.keys(names).length > 0) {
240 { ids: Object.keys(names).join(",") },
242 response2.users.forEach(u => {
243 names[u.id] = u.name;
248 } else addChallenges();
250 const connectAndPoll = () => {
251 this.send("connect");
252 this.send("pollclientsandgamers");
254 // Initialize connection
255 this.connexionString =
262 encodeURIComponent(this.$route.path);
263 this.conn = new WebSocket(this.connexionString);
264 this.conn.onopen = connectAndPoll;
265 this.conn.onmessage = this.socketMessageListener;
266 this.conn.onclose = this.socketCloseListener;
268 mounted: function() {
269 ["peopleWrap", "infoDiv", "newgameDiv"].forEach(eltName => {
270 let elt = document.getElementById(eltName);
271 elt.addEventListener("click", processModalClick);
273 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
274 b.addEventListener("click", () => {
275 this.newchallenge.cadence = b.innerHTML;
278 const showCtype = localStorage.getItem("type-challenges") || "live";
279 const showGtype = localStorage.getItem("type-games") || "live";
280 this.setDisplay("c", showCtype);
281 this.setDisplay("g", showGtype);
283 beforeDestroy: function() {
284 this.send("disconnect");
288 send: function(code, obj) {
290 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
293 getVname: function(vid) {
294 const variant = this.st.variants.find(v => v.id == vid);
295 // this.st.variants might be uninitialized (variant == null)
296 return variant ? variant.name : "";
298 filterChallenges: function(type) {
299 return this.challenges.filter(c => c.type == type);
301 filterGames: function(type) {
302 return this.games.filter(g => g.type == type);
304 classifyObject: function(o) {
306 return o.cadence.indexOf("d") === -1 ? "live" : "corr";
308 setDisplay: function(letter, type, e) {
309 this[letter + "display"] = type;
310 localStorage.setItem(
311 "type-" + (letter == "c" ? "challenges" : "games"),
316 : document.getElementById("btn" + letter.toUpperCase() + type);
317 elt.classList.add("active");
318 elt.classList.remove("somethingnew"); //in case of
319 if (elt.previousElementSibling)
320 elt.previousElementSibling.classList.remove("active");
321 else elt.nextElementSibling.classList.remove("active");
323 isGamer: function(sid) {
324 return this.people[sid].pages.some(p => p.indexOf("/game/") >= 0);
326 getActionLabel: function(sid) {
327 return this.people[sid].pages.some(p => p == "/")
331 challOrWatch: function(sid) {
332 if (this.people[sid].pages.some(p => p == "/")) {
333 // Available, in Hall
334 this.newchallenge.to = this.people[sid].name;
335 document.getElementById("modalPeople").checked = false;
336 window.doClick("modalNewgame");
338 // In some game, maybe playing maybe not: show a random one
340 this.people[sid].pages.forEach(p => {
341 const matchGid = p.match(/[a-zA-Z0-9]+$/);
342 if (matchGid) gids.push(matchGid[0]);
344 const gid = gids[Math.floor(Math.random() * gids.length)];
345 const game = this.games.find(g => g.id == gid);
346 if (game) this.showGame(game);
347 else this.$router.push("/game/" + gid); //game vs. me
350 showGame: function(g) {
351 // NOTE: we are an observer, since only games I don't play are shown here
352 // ==> Moves sent by connected remote player(s) if live game
353 let url = "/game/" + g.id;
354 if (g.type == "live")
355 url += "?rid=" + g.rids[Math.floor(Math.random() * g.rids.length)];
356 this.$router.push(url);
358 resetChatColor: function() {
359 // TODO: this is called twice, once on opening an once on closing
360 document.getElementById("peopleBtn").classList.remove("somethingnew");
362 processChat: function(chat) {
363 this.send("newchat", { data: chat });
366 socketMessageListener: function(msg) {
367 if (!this.conn) return;
368 const data = JSON.parse(msg.data);
370 case "pollclientsandgamers": {
371 // Since people can be both in Hall and Game,
372 // need to track "askIdentity" requests:
373 let identityAsked = {};
374 data.sockIds.forEach(s => {
375 const page = s.page || "/";
376 if (s.sid != this.st.user.sid && !identityAsked[s.sid]) {
377 identityAsked[s.sid] = true;
378 this.send("askidentity", { target: s.sid, page: page });
380 if (!this.people[s.sid])
381 this.$set(this.people, s.sid, { id: 0, name: "", pages: [page] });
382 else if (this.people[s.sid].pages.indexOf(page) < 0)
383 this.people[s.sid].pages.push(page);
386 this.send("askchallenge", { target: s.sid });
388 else this.send("askgame", { target: s.sid, page: page });
394 const page = data.page || "/";
395 // NOTE: player could have been polled earlier, but might have logged in then
396 // So it's a good idea to ask identity if he was anonymous.
397 // But only ask game / challenge if currently disconnected.
398 if (!this.people[data.from]) {
399 this.$set(this.people, data.from, {
404 if (data.code == "connect")
405 this.send("askchallenge", { target: data.from });
406 else this.send("askgame", { target: data.from, page: page });
408 // append page if not already in list
409 if (this.people[data.from].pages.indexOf(page) < 0)
410 this.people[data.from].pages.push(page);
412 if (this.people[data.from].id == 0) {
413 this.newConnect[data.from] = true; //for self multi-connects tests
414 this.send("askidentity", { target: data.from, page: page });
419 case "gdisconnect": {
420 // If the user reloads the page twice very quickly (experienced with Firefox),
421 // the first reload won't have time to connect but will trigger a "close" event anyway.
422 // ==> Next check is required.
423 if (!this.people[data.from]) return;
424 // Disconnect means no more tmpIds:
425 if (data.code == "disconnect") {
426 // Remove the live challenge sent by this player:
427 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
429 // Remove the matching live game if now unreachable
430 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
431 const gidx = this.games.findIndex(g => g.id == gid);
433 const game = this.games[gidx];
435 game.type == "live" &&
436 game.rids.length == 1 &&
437 game.rids[0] == data.from
439 this.games.splice(gidx, 1);
443 const page = data.page || "/";
444 ArrayFun.remove(this.people[data.from].pages, p => p == page);
445 if (this.people[data.from].pages.length == 0)
446 this.$delete(this.people, data.from);
450 // I logged in elsewhere:
451 alert(this.st.tr["New connexion detected: tab now offline"]);
452 // TODO: this fails. See https://github.com/websockets/ws/issues/489
453 //this.conn.removeEventListener("message", this.socketMessageListener);
454 //this.conn.removeEventListener("close", this.socketCloseListener);
458 case "askidentity": {
459 // Request for identification (TODO: anonymous shouldn't need to reply)
461 // Decompose to avoid revealing email
462 name: this.st.user.name,
463 sid: this.st.user.sid,
466 this.send("identity", { data: me, target: data.from });
470 const user = data.data;
472 // If I multi-connect, kill current connexion if no mark (I'm older)
474 this.newConnect[user.sid] &&
476 user.id == this.st.user.id &&
477 user.sid != this.st.user.sid
479 if (!this.killed[this.st.user.sid]) {
480 this.send("killme", { sid: this.st.user.sid });
481 this.killed[this.st.user.sid] = true;
484 if (user.sid != this.st.user.sid) {
485 //I already know my identity...
486 this.$set(this.people, user.sid, {
489 pages: this.people[user.sid].pages
493 delete this.newConnect[user.sid];
496 case "askchallenge": {
497 // Send my current live challenge (if any)
498 const cIdx = this.challenges.findIndex(
499 c => c.from.sid == this.st.user.sid && c.type == "live"
502 const c = this.challenges[cIdx];
503 // NOTE: in principle, should only send targeted challenge to the target.
504 // But we may not know yet the identity of the target (just name),
505 // so cannot decide if data.from is the target or not.
506 const myChallenge = {
508 from: this.st.user.sid,
515 this.send("challenge", { data: myChallenge, target: data.from });
519 case "challenge": //after "askchallenge"
520 case "newchallenge": {
521 // NOTE about next condition: see "askchallenge" case.
522 const chall = data.data;
525 (this.people[chall.from].id > 0 &&
526 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
528 let newChall = Object.assign({}, chall);
529 newChall.type = this.classifyObject(chall);
530 newChall.added = Date.now();
531 let fromValues = Object.assign({}, this.people[chall.from]);
532 delete fromValues["pages"]; //irrelevant in this context
533 newChall.from = Object.assign({ sid: chall.from }, fromValues);
534 newChall.vname = this.getVname(newChall.vid);
535 this.challenges.push(newChall);
537 (newChall.type == "live" && this.cdisplay == "corr") ||
538 (newChall.type == "corr" && this.cdisplay == "live")
541 .getElementById("btnC" + newChall.type)
542 .classList.add("somethingnew");
547 case "refusechallenge": {
548 const cid = data.data;
549 ArrayFun.remove(this.challenges, c => c.id == cid);
550 alert(this.st.tr["Challenge declined"]);
553 case "deletechallenge": {
554 // NOTE: the challenge may be already removed
555 const cid = data.data;
556 ArrayFun.remove(this.challenges, c => c.id == cid);
559 case "game": //individual request
561 // NOTE: it may be live or correspondance
562 const game = data.data;
563 let locGame = this.games.find(g => g.id == game.id);
566 newGame.type = this.classifyObject(game);
567 newGame.vname = this.getVname(game.vid);
569 //if new game from Hall
571 newGame.rids = [game.rid];
572 delete newGame["rid"];
573 this.games.push(newGame);
575 (newGame.type == "live" && this.gdisplay == "corr") ||
576 (newGame.type == "corr" && this.gdisplay == "live")
579 .getElementById("btnG" + newGame.type)
580 .classList.add("somethingnew");
583 // Append rid (if not already in list)
584 if (!locGame.rids.includes(game.rid)) locGame.rids.push(game.rid);
589 let g = this.games.find(g => g.id == data.gid);
590 if (g) g.score = data.score;
594 // New game just started: data contain all information
595 const gameInfo = data.data;
596 if (this.classifyObject(gameInfo) == "live")
597 this.startNewGame(gameInfo);
600 this.st.tr["New correspondance game:"] +
601 " <a href='#/game/" +
607 let modalBox = document.getElementById("modalInfo");
608 modalBox.checked = true;
613 this.newChat = data.data;
614 if (!document.getElementById("modalPeople").checked)
615 document.getElementById("peopleBtn").classList.add("somethingnew");
619 socketCloseListener: function() {
620 if (!this.conn) return;
621 this.conn = new WebSocket(this.connexionString);
622 this.conn.addEventListener("message", this.socketMessageListener);
623 this.conn.addEventListener("close", this.socketCloseListener);
625 // Challenge lifecycle:
626 newChallenge: async function() {
628 if (this.newchallenge.vid == "")
629 error = this.st.tr["Please select a variant"];
630 else if (!!this.newchallenge.to && this.newchallenge.to == this.st.user.name)
631 error = this.st.tr["Self-challenge is forbidden"];
636 const vname = this.getVname(this.newchallenge.vid);
637 const vModule = await import("@/variants/" + vname + ".js");
638 window.V = vModule.VariantRules;
639 if (this.newchallenge.cadence.match(/^[0-9]+$/))
640 this.newchallenge.cadence += "+0"; //assume minutes, no increment
641 const ctype = this.classifyObject(this.newchallenge);
642 error = checkChallenge(this.newchallenge);
643 if (!error && ctype == "corr" && this.st.user.id <= 0)
644 error = this.st.tr["Please log in to play correspondance games"];
649 // NOTE: "from" information is not required here
650 let chall = Object.assign({}, this.newchallenge);
651 const finishAddChallenge = cid => {
652 chall.id = cid || "c" + getRandString();
653 // Remove old challenge if any (only one at a time of a given type):
654 const cIdx = this.challenges.findIndex(
656 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) &&
660 // Delete current challenge (will be replaced now)
661 this.send("deletechallenge", { data: this.challenges[cIdx].id });
662 if (ctype == "corr") {
663 ajax("/challenges", "DELETE", { id: this.challenges[cIdx].id });
665 this.challenges.splice(cIdx, 1);
667 this.send("newchallenge", {
668 data: Object.assign({ from: this.st.user.sid }, chall)
670 // Add new challenge:
672 //decompose to avoid revealing email
673 sid: this.st.user.sid,
675 name: this.st.user.name
677 chall.added = Date.now();
678 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
681 this.challenges.push(chall);
682 // Remember cadence + vid for quicker further challenges:
683 localStorage.setItem("cadence", chall.cadence);
684 localStorage.setItem("vid", chall.vid);
685 document.getElementById("modalNewgame").checked = false;
687 if (ctype == "live") {
688 // Live challenges have a random ID
689 finishAddChallenge(null);
691 // Correspondance game: send challenge to server
692 ajax("/challenges", "POST", { chall: chall }, response => {
693 finishAddChallenge(response.cid);
697 clickChallenge: function(c) {
699 c.from.sid == this.st.user.sid || //live
700 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
702 if (c.type == "corr" && this.st.user.id <= 0) {
703 alert(this.st.tr["Please log in to accept corr challenges"]);
708 //c.to == this.st.user.name (connected)
709 // TODO: if special FEN, show diagram after loading variant
710 c.accepted = confirm("Accept challenge?");
714 //again, avoid c.seat = st.user to not reveal email
715 sid: this.st.user.sid,
717 name: this.st.user.name
721 this.send("refusechallenge", { data: c.id, target: c.from.sid });
723 this.send("deletechallenge", { data: c.id });
726 if (c.type == "corr") {
727 ajax("/challenges", "DELETE", { id: c.id });
729 this.send("deletechallenge", { data: c.id });
731 // In all cases, the challenge is consumed:
732 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
734 // NOTE: when launching game, the challenge is already being deleted
735 launchGame: async function(c) {
736 const vModule = await import("@/variants/" + c.vname + ".js");
737 window.V = vModule.VariantRules;
738 // These game informations will be shared
741 fen: c.fen || V.GenRandInitFen(),
742 players: shuffle([c.from, c.seat]), //white then black
746 let oppsid = c.from.sid; //may not be defined if corr + offline opp
748 oppsid = Object.keys(this.people).find(
749 sid => this.people[sid].id == c.from.id
752 const notifyNewgame = () => {
755 this.send("startgame", { data: gameInfo, target: oppsid });
756 // Send game info (only if live) to everyone except me in this tab
757 this.send("newgame", { data: gameInfo });
759 if (c.type == "live") {
761 this.startNewGame(gameInfo);
762 } //corr: game only on server
767 { gameInfo: gameInfo, cid: c.id }, //cid useful to delete challenge
769 gameInfo.id = response.gameId;
771 this.$router.push("/game/" + response.gameId);
776 // NOTE: for live games only (corr games start on the server)
777 startNewGame: function(gameInfo) {
778 const game = Object.assign({}, gameInfo, {
779 // (other) Game infos: constant
780 fenStart: gameInfo.fen,
781 vname: this.getVname(gameInfo.vid),
783 // Game state (including FEN): will be updated
785 clocks: [-1, -1], //-1 = unstarted
786 initime: [0, 0], //initialized later
789 GameStorage.add(game);
790 if (this.st.settings.sound >= 1)
791 new Audio("/sounds/newgame.mp3").play().catch(() => {});
792 this.$router.push("/game/" + gameInfo.id);
798 <style lang="sass" scoped>
810 div#peopleWrap > .card
813 @media screen and (min-width: 1281px)
814 div#peopleWrap > .card
817 @media screen and (max-width: 1280px)
818 div#peopleWrap > .card
821 @media screen and (max-width: 767px)
822 div#peopleWrap > .card
835 @media screen and (max-width: 767px)
854 background-color: #c5fefe !important
857 background-color: #f9faee
861 @media screen and (max-width: 767px)