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() {
122 // Set potential challenges and games variant names:
123 this.challenges.concat(this.games).forEach(o => {
124 if (o.vname == "") o.vname = this.getVname(o.vid);
129 anonymousCount: function() {
131 Object.values(this.people).forEach(p => {
132 count += !p.name ? 1 : 0;
137 created: function() {
138 const my = this.st.user;
139 this.$set(this.people, my.sid, { id: my.id, name: my.name, pages: ["/"] });
140 // Ask server for current corr games (all but mines)
144 { uid: this.st.user.id, excluded: true },
146 this.games = this.games.concat(
147 response.games.map(g => {
148 const type = this.classifyObject(g);
149 const vname = this.getVname(g.vid);
150 return Object.assign({}, g, { type: type, vname: vname });
155 // Also ask for corr challenges (open + sent by/to me)
156 ajax("/challenges", "GET", { uid: this.st.user.id }, response => {
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) names[c.uid] = "";
163 else if (!!c.target && c.target != this.st.user.id)
164 names[c.target] = "";
166 const addChallenges = () => {
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(
179 to: c.target ? names[c.target] : ""
186 if (Object.keys(names).length > 0) {
190 { ids: Object.keys(names).join(",") },
192 response2.users.forEach(u => {
193 names[u.id] = u.name;
198 } else addChallenges();
200 const connectAndPoll = () => {
201 this.send("connect");
202 this.send("pollclientsandgamers");
204 // Initialize connection
205 this.connexionString =
212 encodeURIComponent(this.$route.path);
213 this.conn = new WebSocket(this.connexionString);
214 this.conn.onopen = connectAndPoll;
215 this.conn.onmessage = this.socketMessageListener;
216 this.conn.onclose = this.socketCloseListener;
218 mounted: function() {
219 ["peopleWrap", "infoDiv", "newgameDiv"].forEach(eltName => {
220 let elt = document.getElementById(eltName);
221 elt.addEventListener("click", processModalClick);
223 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
224 b.addEventListener("click", () => {
225 this.newchallenge.cadence = b.innerHTML;
228 const showCtype = localStorage.getItem("type-challenges") || "live";
229 const showGtype = localStorage.getItem("type-games") || "live";
230 this.setDisplay("c", showCtype);
231 this.setDisplay("g", showGtype);
233 beforeDestroy: function() {
234 this.send("disconnect");
238 send: function(code, obj) {
240 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
243 getVname: function(vid) {
244 const variant = this.st.variants.find(v => v.id == vid);
245 // this.st.variants might be uninitialized (variant == null)
246 return variant ? variant.name : "";
248 filterChallenges: function(type) {
249 return this.challenges.filter(c => c.type == type);
251 filterGames: function(type) {
252 return this.games.filter(g => g.type == type);
254 classifyObject: function(o) {
256 return o.cadence.indexOf("d") === -1 ? "live" : "corr";
258 setDisplay: function(letter, type, e) {
259 this[letter + "display"] = type;
260 localStorage.setItem(
261 "type-" + (letter == "c" ? "challenges" : "games"),
266 : document.getElementById("btn" + letter.toUpperCase() + type);
267 elt.classList.add("active");
268 elt.classList.remove("somethingnew"); //in case of
269 if (elt.previousElementSibling)
270 elt.previousElementSibling.classList.remove("active");
271 else elt.nextElementSibling.classList.remove("active");
273 isGamer: function(sid) {
274 return this.people[sid].pages.some(p => p.indexOf("/game/") >= 0);
276 getActionLabel: function(sid) {
277 return this.people[sid].pages.some(p => p == "/")
281 challOrWatch: function(sid) {
282 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 window.doClick("modalNewgame");
288 // In some game, maybe playing maybe not: show a random one
290 this.people[sid].pages.forEach(p => {
291 const matchGid = p.match(/[a-zA-Z0-9]+$/);
292 if (matchGid) gids.push(matchGid[0]);
294 const gid = gids[Math.floor(Math.random() * gids.length)];
295 this.showGame(this.games.find(g => g.id == gid));
298 showGame: function(g) {
299 // NOTE: we are an observer, since only games I don't play are shown here
300 // ==> Moves sent by connected remote player(s) if live game
301 let url = "/game/" + g.id;
302 if (g.type == "live")
303 url += "?rid=" + g.rids[Math.floor(Math.random() * g.rids.length)];
304 this.$router.push(url);
306 resetChatColor: function() {
307 // TODO: this is called twice, once on opening an once on closing
308 document.getElementById("peopleBtn").classList.remove("somethingnew");
310 processChat: function(chat) {
311 this.send("newchat", { data: chat });
314 socketMessageListener: function(msg) {
315 if (!this.conn) return;
316 const data = JSON.parse(msg.data);
318 case "pollclientsandgamers": {
319 // Since people can be both in Hall and Game,
320 // need to track "askIdentity" requests:
321 let identityAsked = {};
322 data.sockIds.forEach(s => {
323 const page = s.page || "/";
324 if (s.sid != this.st.user.sid && !identityAsked[s.sid]) {
325 identityAsked[s.sid] = true;
326 this.send("askidentity", { target: s.sid, page: page });
328 if (!this.people[s.sid])
329 this.$set(this.people, s.sid, { id: 0, name: "", pages: [page] });
330 else if (this.people[s.sid].pages.indexOf(page) < 0)
331 this.people[s.sid].pages.push(page);
334 this.send("askchallenge", { target: s.sid });
336 else this.send("askgame", { target: s.sid, page: page });
342 const page = data.page || "/";
343 // NOTE: player could have been polled earlier, but might have logged in then
344 // So it's a good idea to ask identity if he was anonymous.
345 // But only ask game / challenge if currently disconnected.
346 if (!this.people[data.from]) {
347 this.$set(this.people, data.from, {
352 if (data.code == "connect")
353 this.send("askchallenge", { target: data.from });
354 else this.send("askgame", { target: data.from, page: page });
356 // append page if not already in list
357 if (this.people[data.from].pages.indexOf(page) < 0)
358 this.people[data.from].pages.push(page);
360 if (this.people[data.from].id == 0) {
361 this.newConnect[data.from] = true; //for self multi-connects tests
362 this.send("askidentity", { target: data.from, page: page });
367 case "gdisconnect": {
368 // If the user reloads the page twice very quickly (experienced with Firefox),
369 // the first reload won't have time to connect but will trigger a "close" event anyway.
370 // ==> Next check is required.
371 if (!this.people[data.from]) return;
372 // Disconnect means no more tmpIds:
373 if (data.code == "disconnect") {
374 // Remove the live challenge sent by this player:
375 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
377 // Remove the matching live game if now unreachable
378 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
379 const gidx = this.games.findIndex(g => g.id == gid);
381 const game = this.games[gidx];
383 game.type == "live" &&
384 game.rids.length == 1 &&
385 game.rids[0] == data.from
387 this.games.splice(gidx, 1);
391 const page = data.page || "/";
392 ArrayFun.remove(this.people[data.from].pages, p => p == page);
393 if (this.people[data.from].pages.length == 0)
394 this.$delete(this.people, data.from);
398 // I logged in elsewhere:
399 alert(this.st.tr["New connexion detected: tab now offline"]);
400 // TODO: this fails. See https://github.com/websockets/ws/issues/489
401 //this.conn.removeEventListener("message", this.socketMessageListener);
402 //this.conn.removeEventListener("close", this.socketCloseListener);
406 case "askidentity": {
407 // Request for identification (TODO: anonymous shouldn't need to reply)
409 // Decompose to avoid revealing email
410 name: this.st.user.name,
411 sid: this.st.user.sid,
414 this.send("identity", { data: me, target: data.from });
418 const user = data.data;
420 //otherwise anonymous
421 // If I multi-connect, kill current connexion if no mark (I'm older)
423 this.newConnect[user.sid] &&
425 user.id == this.st.user.id &&
426 user.sid != this.st.user.sid
428 if (!this.killed[this.st.user.sid]) {
429 this.send("killme", { sid: this.st.user.sid });
430 this.killed[this.st.user.sid] = true;
433 if (user.sid != this.st.user.sid) {
434 //I already know my identity...
435 this.$set(this.people, user.sid, {
438 pages: this.people[user.sid].pages
442 delete this.newConnect[user.sid];
445 case "askchallenge": {
446 // Send my current live challenge (if any)
447 const cIdx = this.challenges.findIndex(
448 c => c.from.sid == this.st.user.sid && c.type == "live"
451 const c = this.challenges[cIdx];
452 // NOTE: in principle, should only send targeted challenge to the target.
453 // But we may not know yet the identity of the target (just name),
454 // so cannot decide if data.from is the target or not.
455 const myChallenge = {
457 from: this.st.user.sid,
464 this.send("challenge", { data: myChallenge, target: data.from });
468 case "challenge": //after "askchallenge"
469 case "newchallenge": {
470 // NOTE about next condition: see "askchallenge" case.
471 const chall = data.data;
474 (this.people[chall.from].id > 0 &&
475 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
477 let newChall = Object.assign({}, chall);
478 newChall.type = this.classifyObject(chall);
479 newChall.added = Date.now();
480 let fromValues = Object.assign({}, this.people[chall.from]);
481 delete fromValues["pages"]; //irrelevant in this context
482 newChall.from = Object.assign({ sid: chall.from }, fromValues);
483 newChall.vname = this.getVname(newChall.vid);
484 this.challenges.push(newChall);
486 (newChall.type == "live" && this.cdisplay == "corr") ||
487 (newChall.type == "corr" && this.cdisplay == "live")
490 .getElementById("btnC" + newChall.type)
491 .classList.add("somethingnew");
496 case "refusechallenge": {
497 const cid = data.data;
498 ArrayFun.remove(this.challenges, c => c.id == cid);
499 alert(this.st.tr["Challenge declined"]);
502 case "deletechallenge": {
503 // NOTE: the challenge may be already removed
504 const cid = data.data;
505 ArrayFun.remove(this.challenges, c => c.id == cid);
508 case "game": //individual request
510 // NOTE: it may be live or correspondance
511 const game = data.data;
512 let locGame = this.games.find(g => g.id == game.id);
515 newGame.type = this.classifyObject(game);
516 newGame.vname = this.getVname(game.vid);
518 //if new game from Hall
520 newGame.rids = [game.rid];
521 delete newGame["rid"];
522 this.games.push(newGame);
524 (newGame.type == "live" && this.gdisplay == "corr") ||
525 (newGame.type == "corr" && this.gdisplay == "live")
528 .getElementById("btnG" + newGame.type)
529 .classList.add("somethingnew");
532 // Append rid (if not already in list)
533 if (!locGame.rids.includes(game.rid)) locGame.rids.push(game.rid);
538 let g = this.games.find(g => g.id == data.gid);
539 if (g) g.score = data.score;
543 // New game just started: data contain all information
544 const gameInfo = data.data;
545 if (this.classifyObject(gameInfo) == "live")
546 this.startNewGame(gameInfo);
549 this.st.tr["New correspondance game:"] +
550 " <a href='#/game/" +
556 let modalBox = document.getElementById("modalInfo");
557 modalBox.checked = true;
562 this.newChat = data.data;
563 if (!document.getElementById("modalPeople").checked)
564 document.getElementById("peopleBtn").classList.add("somethingnew");
568 socketCloseListener: function() {
569 if (!this.conn) return;
570 this.conn = new WebSocket(this.connexionString);
571 this.conn.addEventListener("message", this.socketMessageListener);
572 this.conn.addEventListener("close", this.socketCloseListener);
574 // Challenge lifecycle:
575 newChallenge: async function() {
577 if (this.newchallenge.vid == "")
578 error = this.st.tr["Please select a variant"];
579 else if (!!this.newchallenge.to && this.newchallenge.to == this.st.user.name)
580 error = this.st.tr["Self-challenge is forbidden"];
585 const vname = this.getVname(this.newchallenge.vid);
586 const vModule = await import("@/variants/" + vname + ".js");
587 window.V = vModule.VariantRules;
588 if (this.newchallenge.cadence.match(/^[0-9]+$/))
589 this.newchallenge.cadence += "+0"; //assume minutes, no increment
590 const ctype = this.classifyObject(this.newchallenge);
591 error = checkChallenge(this.newchallenge);
592 if (!error && ctype == "corr" && this.st.user.id <= 0)
593 error = this.st.tr["Please log in to play correspondance games"];
598 // NOTE: "from" information is not required here
599 let chall = Object.assign({}, this.newchallenge);
600 const finishAddChallenge = cid => {
601 chall.id = cid || "c" + getRandString();
602 // Remove old challenge if any (only one at a time of a given type):
603 const cIdx = this.challenges.findIndex(
605 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) &&
609 // Delete current challenge (will be replaced now)
610 this.send("deletechallenge", { data: this.challenges[cIdx].id });
611 if (ctype == "corr") {
612 ajax("/challenges", "DELETE", { id: this.challenges[cIdx].id });
614 this.challenges.splice(cIdx, 1);
616 this.send("newchallenge", {
617 data: Object.assign({ from: this.st.user.sid }, chall)
619 // Add new challenge:
621 //decompose to avoid revealing email
622 sid: this.st.user.sid,
624 name: this.st.user.name
626 chall.added = Date.now();
627 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
630 this.challenges.push(chall);
631 // Remember cadence + vid for quicker further challenges:
632 localStorage.setItem("cadence", chall.cadence);
633 localStorage.setItem("vid", chall.vid);
634 document.getElementById("modalNewgame").checked = false;
636 if (ctype == "live") {
637 // Live challenges have a random ID
638 finishAddChallenge(null);
640 // Correspondance game: send challenge to server
641 ajax("/challenges", "POST", { chall: chall }, response => {
642 finishAddChallenge(response.cid);
646 clickChallenge: function(c) {
648 c.from.sid == this.st.user.sid || //live
649 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
651 if (c.type == "corr" && this.st.user.id <= 0) {
652 alert(this.st.tr["Please log in to accept corr challenges"]);
657 //c.to == this.st.user.name (connected)
658 // TODO: if special FEN, show diagram after loading variant
659 c.accepted = confirm("Accept challenge?");
663 //again, avoid c.seat = st.user to not reveal email
664 sid: this.st.user.sid,
666 name: this.st.user.name
670 this.send("refusechallenge", { data: c.id, target: c.from.sid });
672 this.send("deletechallenge", { data: c.id });
675 if (c.type == "corr") {
676 ajax("/challenges", "DELETE", { id: c.id });
678 this.send("deletechallenge", { data: c.id });
680 // In all cases, the challenge is consumed:
681 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
683 // NOTE: when launching game, the challenge is already being deleted
684 launchGame: async function(c) {
685 const vModule = await import("@/variants/" + c.vname + ".js");
686 window.V = vModule.VariantRules;
687 // These game informations will be shared
690 fen: c.fen || V.GenRandInitFen(),
691 players: shuffle([c.from, c.seat]), //white then black
695 let oppsid = c.from.sid; //may not be defined if corr + offline opp
697 oppsid = Object.keys(this.people).find(
698 sid => this.people[sid].id == c.from.id
701 const notifyNewgame = () => {
704 this.send("startgame", { data: gameInfo, target: oppsid });
705 // Send game info (only if live) to everyone except me in this tab
706 this.send("newgame", { data: gameInfo });
708 if (c.type == "live") {
710 this.startNewGame(gameInfo);
711 } //corr: game only on server
716 { gameInfo: gameInfo, cid: c.id }, //cid useful to delete challenge
718 gameInfo.id = response.gameId;
720 this.$router.push("/game/" + response.gameId);
725 // NOTE: for live games only (corr games start on the server)
726 startNewGame: function(gameInfo) {
727 const game = Object.assign({}, gameInfo, {
728 // (other) Game infos: constant
729 fenStart: gameInfo.fen,
730 vname: this.getVname(gameInfo.vid),
732 // Game state (including FEN): will be updated
734 clocks: [-1, -1], //-1 = unstarted
735 initime: [0, 0], //initialized later
738 GameStorage.add(game);
739 if (this.st.settings.sound >= 1)
740 new Audio("/sounds/newgame.mp3").play().catch(() => {});
741 this.$router.push("/game/" + gameInfo.id);
747 <style lang="sass" scoped>
759 div#peopleWrap > .card
762 @media screen and (min-width: 1281px)
763 div#peopleWrap > .card
766 @media screen and (max-width: 1280px)
767 div#peopleWrap > .card
770 @media screen and (max-width: 767px)
771 div#peopleWrap > .card
782 @media screen and (max-width: 767px)
797 background-color: #c5fefe !important
800 background-color: #f9faee
804 @media screen and (max-width: 767px)