3 input#modalInfo.modal(type="checkbox")
6 data-checkbox="modalInfo"
9 label.modal-close(for="modalInfo")
10 p(v-html="infoMessage")
11 input#modalAccept.modal(type="checkbox")
12 div#acceptDiv(role="dialog")
16 | {{ curChallToAccept.vname }}
17 | {{ curChallToAccept.options.abridged || '' }}
18 span {{ curChallToAccept.cadence }}
19 span {{ st.tr["with"] + " " + curChallToAccept.from.name }}
20 p.text-center(v-if="!!curChallToAccept.color")
21 | {{ st.tr["Your color:"] + " " + invColor(curChallToAccept.color) }}
23 v-if="!!curChallToAccept.fen"
26 .button-group#buttonsTchall(:style="tchallButtonsMargin()")
27 button.acceptBtn(@click="decisionChallenge(true)")
28 span {{ st.tr["Accept challenge?"] }}
29 button.refuseBtn(@click="decisionChallenge(false)")
30 span {{ st.tr["Refuse"] }}
31 input#modalNewgame.modal(
33 @change="cadenceFocusIfOpened($event)"
37 data-checkbox="modalNewgame"
40 label#closeNewgame.modal-close(for="modalNewgame")
41 div(@keyup.enter="issueNewChallenge()")
43 label(for="selectVariant") {{ st.tr["Variant"] }} *
45 @change="loadNewchallVariant(trySetNewchallDiag)"
46 v-model="newchallenge.vid"
49 v-for="v in st.variants"
51 :selected="newchallenge.vid==v.id"
54 // Variant-specific options (often at least randomness)
55 fieldset(v-if="!!newchallenge.V")
56 div(v-for="select of newchallenge.V.Options.select")
57 label(:for="select.variable + '_opt'") {{ st.tr[select.label] }} *
58 select(:id="select.variable + '_opt'")
60 v-for="o of select.options"
62 :selected="o.value == select.defaut"
64 | {{ st.tr[o.label] }}
65 div(v-for="check of newchallenge.V.Options.check")
66 label(:for="check.variable + '_opt'") {{ st.tr[check.label] }} *
68 :id="check.variable + '_opt'"
70 :checked="check.defaut")
72 label(for="cadence") {{ st.tr["Cadence"] }} *
73 div#predefinedCadences
74 button(type="button") 15+5
75 button(type="button") 45+30
76 button(type="button") 3d
77 button(type="button") 7d
80 v-model="newchallenge.cadence"
81 placeholder="5+0, 1h+30s, 5d ..."
84 label(for="memorizeChall") {{ st.tr["Memorize"] }}
87 v-model="newchallenge.memorize"
89 fieldset(v-if="st.user.id > 0")
90 label(for="selectPlayers") {{ st.tr["Play with"] }}
91 select#selectPlayersInList(
92 v-model="newchallenge.to"
93 @change="changeChallTarget()"
97 v-for="p in Object.values(people)"
104 v-model="newchallenge.to"
106 fieldset(v-show="st.user.id > 0 && newchallenge.to.length > 0")
107 label(for="selectColor") {{ st.tr["Color"] }}
108 select#selectColor(v-model="newchallenge.color")
110 option(value='w') {{ st.tr["White"] }}
111 option(value='b') {{ st.tr["Black"] }}
115 @input="trySetNewchallDiag()"
117 v-model="newchallenge.fen"
119 .diagram(v-html="newchallenge.diag")
120 button(@click="issueNewChallenge()") {{ st.tr["Send challenge"] }}
121 input#modalPeople.modal(
123 @click="toggleSocialColor()"
127 data-checkbox="modalPeople"
130 label.modal-close(for="modalPeople")
134 v-for="sid in Object.keys(people)"
135 v-if="!!people[sid].name"
137 UserBio.user-bio(:uid="people[sid].id" :uname="people[sid].name")
138 button.player-action(
140 @click="watchGame(sid)"
142 | {{ st.tr["Observe"] }}
143 button.player-action(
144 v-else-if="st.user.sid != sid"
145 :class="{focused: isFocusedOnHall(sid)}"
146 @click="challenge(sid)"
148 | {{ st.tr["Challenge"] }}
149 p.anonymous @nonymous ({{ anonymousCount() }})
153 @mychat="processChat"
158 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
160 button#peopleBtn(onClick="window.doClick('modalPeople')")
161 | {{ st.tr["Who's there?"] }}
162 button(@click="showNewchallengeForm()")
163 | {{ st.tr["New game"] }}
164 .row(v-if="presetChalls.length > 0")
165 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
166 h4.text-center {{ st.tr["Preset challenges"] }}
170 th {{ st.tr["Variant"] }}
171 th {{ st.tr["Cadence"] }}
172 th {{ st.tr["Options"] }}
176 v-for="pc in presetChalls"
177 @click="newChallFromPreset(pc)"
181 td(:class="getRandomnessClass(pc)") {{ pc.options.abridged || '' }}
182 td.remove-preset(@click="removePresetChall($event, pc)")
183 img(src="/images/icons/delete.svg")
185 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
188 button.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
189 | {{ st.tr["Live challenges"] }}
190 button.tabbtn#btnCcorr(@click="setDisplay('c','corr',$event)")
191 | {{ st.tr["Correspondence challenges"] }}
193 v-show="cdisplay=='live'"
194 :challenges="filterChallenges('live')"
195 @click-challenge="clickChallenge"
198 v-show="cdisplay=='corr'"
199 :challenges="filterChallenges('corr')"
200 @click-challenge="clickChallenge"
204 button.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
205 | {{ st.tr["Live games"] }}
206 button.tabbtn#btnGcorr(@click="setDisplay('g','corr',$event)")
207 | {{ st.tr["Correspondence games"] }}
209 v-show="gdisplay=='live'"
210 :games="filterGames('live')"
212 @show-game="showGame"
214 div(v-show="gdisplay=='corr'")
216 :games="filterGames('corr')"
218 @show-game="showGame"
222 @click="loadMoreCorr()"
224 | {{ st.tr["Load more"] }}
228 import { store } from "@/store";
229 import { checkChallenge } from "@/data/challengeCheck";
230 import { notify } from "@/utils/notifications";
231 import { ArrayFun } from "@/utils/array";
232 import { ajax } from "@/utils/ajax";
233 import params from "@/parameters";
234 import { getRandString, shuffle, randInt } from "@/utils/alea";
235 import { getDiagram } from "@/utils/printDiagram";
236 import Chat from "@/components/Chat.vue";
237 import UserBio from "@/components/UserBio.vue";
238 import GameList from "@/components/GameList.vue";
239 import ChallengeList from "@/components/ChallengeList.vue";
240 import { GameStorage } from "@/utils/gameStorage";
241 import { processModalClick } from "@/utils/modalClick";
253 cdisplay: "live", //or corr
255 // timestamp of last showed (oldest) corr game:
256 cursor: Number.MAX_SAFE_INTEGER,
257 // hasMore == TRUE: a priori there could be more games to load
265 vid: parseInt(localStorage.getItem("vid"), 10) || 0,
266 to: "", //name of challenged player (if any)
268 cadence: localStorage.getItem("cadence") || "",
270 // VariantRules object, stored to not interfere with
271 // diagrams of targeted challenges:
274 diag: "", //visualizing FEN
275 memorize: false //put settings in localStorage
279 curChallToAccept: { from: {}, options: {} },
280 presetChalls: JSON.parse(localStorage.getItem("presetChalls") || "[]"),
283 socketCloseListener: 0,
284 // Related to (killing of) self multi-connects:
289 // st.variants changes only once, at loading from [] to [...]
290 "st.variants": function() {
291 // Set potential challenges and games variant names:
292 this.challenges.concat(this.games).forEach(o => {
293 if (!o.vname) this.setVname(o);
295 if (!this.newchallenge.V && this.newchallenge.vid > 0)
296 this.loadNewchallVariant();
298 $route: function(to, from) {
299 if (to.path != "/") this.cleanBeforeDestroy();
302 created: function() {
303 // TODO: remove this patch soon:
304 this.presetChalls.forEach(pc => {
305 if (!pc.options) pc.options = { randomness: pc.randomness };
307 document.addEventListener('visibilitychange', this.visibilityChange);
308 window.addEventListener('focus', this.onFocus);
309 window.addEventListener('blur', this.onBlur);
310 window.addEventListener("beforeunload", this.cleanBeforeDestroy);
311 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
312 this.loadNewchallVariant();
313 const my = this.st.user;
314 const tmpId = getRandString();
322 tmpId: { page: "/", focus: true }
326 const connectAndPoll = () => {
327 this.send("connect");
328 this.send("pollclientsandgamers");
329 if (!!this.$route.query["challenge"]) {
330 // Automatic challenge sending, for tournaments
331 this.loadNewchallVariant(
339 .find(v => v.name == this.$route.query["variant"])
341 to: this.$route.query["challenge"],
342 color: this.$route.query["color"] || '',
343 cadence: this.$route.query["cadence"],
348 window.doClick("modalNewgame");
350 this.$route.query["variant"]
354 // Initialize connection
355 this.connexionString =
357 "/?sid=" + this.st.user.sid +
358 "&id=" + this.st.user.id +
361 // Hall: path is "/" (TODO: could be hard-coded as well)
362 encodeURIComponent(this.$route.path);
363 this.conn = new WebSocket(this.connexionString);
364 this.conn.onopen = connectAndPoll;
365 this.conn.addEventListener("message", this.socketMessageListener);
366 this.socketCloseListener = setInterval(
368 if (this.conn.readyState == 3) {
369 this.conn.removeEventListener("message", this.socketMessageListener);
370 this.conn = new WebSocket(this.connexionString);
371 this.conn.addEventListener("message", this.socketMessageListener);
377 mounted: function() {
378 document.getElementById("peopleWrap")
379 .addEventListener("click", (e) => {
380 processModalClick(e, () => {
381 this.toggleSocialColor("close")
384 ["infoDiv", "newgameDiv"].forEach(eltName => {
385 document.getElementById(eltName)
386 .addEventListener("click", processModalClick);
388 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
389 b.addEventListener("click", () => {
390 this.newchallenge.cadence = b.innerHTML;
393 const dispCorr = this.$route.query["disp"];
395 dispCorr || localStorage.getItem("type-challenges") || "live";
397 dispCorr || localStorage.getItem("type-games") || "live";
398 this.setDisplay('c', showCtype);
399 this.setDisplay('g', showGtype);
400 // Ask server for current corr games (all but mines)
402 // Also ask for corr challenges (open + sent by/to me)
403 // List them all, because they are not supposed to be that many (TODO?)
408 data: { uid: this.st.user.id },
409 success: (response) => {
411 response.challenges.length > 0 &&
412 this.challenges.length == 0 &&
413 this.cdisplay == "live"
416 .getElementById("btnCcorr")
417 .classList.add("somethingnew");
419 // Gather all senders names, and then retrieve full identity:
420 // (TODO [perf]: some might be online...)
422 response.challenges.forEach(c => {
423 if (c.uid != this.st.user.id) names[c.uid] = "";
424 else if (!!c.target && c.target != this.st.user.id)
425 names[c.target] = "";
427 const addChallenges = () => {
428 names[this.st.user.id] = this.st.user.name; //in case of
429 this.challenges = this.challenges.concat(
430 response.challenges.map(c => {
431 const from = { name: names[c.uid], id: c.uid }; //or just name
432 const type = this.classifyObject(c);
434 return Object.assign(
440 to: c.target ? names[c.target] : "",
441 options: JSON.parse(c.options)
447 if (Object.keys(names).length > 0) {
452 data: { ids: Object.keys(names).join(",") },
453 success: (response2) => {
454 response2.users.forEach(u => {
455 names[u.id] = u.name;
462 else addChallenges();
467 beforeDestroy: function() {
468 this.cleanBeforeDestroy();
471 cleanBeforeDestroy: function() {
472 clearInterval(this.socketCloseListener);
473 document.removeEventListener('visibilitychange', this.visibilityChange);
474 window.removeEventListener('focus', this.onFocus);
475 window.removeEventListener('blur', this.onBlur);
476 window.removeEventListener("beforeunload", this.cleanBeforeDestroy);
477 this.conn.removeEventListener("message", this.socketMessageListener);
478 this.send("disconnect");
481 getRandomnessClass: function(pc) {
483 // TODO: one extra test here
484 !Number.isInteger(pc.options.randomness) &&
485 !parseInt(pc.options.randomness, 10)
490 ["random-" + pc.options.randomness]: true
493 anonymousCount: function() {
495 Object.values(this.people).forEach(p => {
496 // Do not cound people who did not send their identity yet:
497 count += (!p.name && p.id === 0) ? 1 : 0;
501 visibilityChange: function() {
502 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
503 this.focus = (document.visibilityState == "visible");
504 this.send(this.focus ? "getfocus" : "losefocus");
506 onFocus: function() {
508 this.send("getfocus");
512 this.send("losefocus");
514 invColor: function(c) {
515 if (c == 'w') return this.st.tr["Black"];
516 return this.tr.tr["White"];
518 partialResetNewchallenge: function() {
519 // Reset potential target and custom FEN:
520 this.newchallenge.to = "";
521 this.newchallenge.color = '';
522 this.newchallenge.fen = "";
523 this.newchallenge.diag = "";
524 this.newchallenge.memorize = false;
526 showNewchallengeForm: function() {
527 this.partialResetNewchallenge();
528 window.doClick("modalNewgame");
530 sameOptions: function(opt1, opt2) {
531 const keys1 = Object.keys(opt1),
532 keys2 = Object.keys(opt2);
533 if (keys1.length != keys2.length) return false;
534 for (const key1 of keys1) {
535 if (!keys2.includes(key1)) return false;
536 if (opt1[key1] != opt2[key1]) return false;
540 addPresetChall: function(chall) {
541 // Add only if not already existing:
542 if (this.presetChalls.some(c =>
543 c.vid == chall.vid &&
544 c.cadence == chall.cadence &&
545 this.sameOptions(c.options, chall.options)
549 const L = this.presetChalls.length;
550 this.presetChalls.push({
553 vname: chall.vname, //redundant, but easier
554 cadence: chall.cadence,
555 options: chall.options
557 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
559 removePresetChall: function(e, pchall) {
562 this.presetChalls.findIndex(pc => pc.index == pchall.index);
563 this.presetChalls.splice(pchallIdx, 1);
564 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
566 tchallButtonsMargin: function() {
567 if (!!this.curChallToAccept.fen) return { "margin-top": "10px" };
570 changeChallTarget: function() {
571 if (!this.newchallenge.to) {
572 // Reset potential FEN + diagram
573 this.newchallenge.fen = "";
574 this.newchallenge.color = '';
575 this.newchallenge.diag = "";
578 cadenceFocusIfOpened: function() {
579 if (event.target.checked)
580 document.getElementById("cadence").focus();
582 send: function(code, obj) {
583 if (!!this.conn && this.conn.readyState == 1) {
584 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
587 setVname: function(obj) {
588 const variant = this.st.variants.find(v => v.id == obj.vid);
589 // this.st.variants might be uninitialized (variant == null)
591 obj.vname = variant.name;
592 obj.vdisp = variant.display;
594 // NOTE: Next line is used in loadNewchallVariant
595 return (!variant ? "" : variant.name);
597 filterChallenges: function(type) {
598 return this.challenges.filter(c => c.type == type);
600 filterGames: function(type) {
601 return this.games.filter(g => g.type == type);
603 // o: challenge or game
604 classifyObject: function(o) {
605 // No imported games here
606 return (o.cadence.indexOf("d") >= 0 ? "corr" : "live");
608 setDisplay: function(letter, type, e) {
609 this[letter + "display"] = type;
610 localStorage.setItem(
611 "type-" + (letter == "c" ? "challenges" : "games"),
616 : document.getElementById("btn" + letter.toUpperCase() + type);
617 elt.classList.add("active");
618 elt.classList.remove("somethingnew"); //in case of
619 if (!!elt.previousElementSibling)
620 elt.previousElementSibling.classList.remove("active");
621 else elt.nextElementSibling.classList.remove("active");
623 isGamer: function(sid) {
624 return Object.values(this.people[sid].tmpIds)
625 .some(v => v.focus && v.page.indexOf("/game/") >= 0);
627 isFocusedOnHall: function(sid) {
629 // This is meant to challenge people, thus the next 2 conditions:
630 this.st.user.id > 0 &&
631 sid != this.st.user.sid &&
632 Object.values(this.people[sid].tmpIds)
633 .some(v => v.focus && v.page == "/")
636 challenge: function(sid) {
637 this.partialResetNewchallenge();
638 // Available, in Hall
639 this.newchallenge.to = this.people[sid].name;
640 // TODO: also store target sid to not re-search for it
641 document.getElementById("modalPeople").checked = false;
642 window.doClick("modalNewgame");
644 watchGame: function(sid) {
645 // In some game, maybe playing maybe not: show a random one
647 Object.values(this.people[sid].tmpIds).forEach(v => {
649 const matchGid = v.page.match(/[a-zA-Z0-9]+$/);
650 if (!!matchGid) gids.push(matchGid[0]);
653 const gid = gids[Math.floor(Math.random() * gids.length)];
654 window.open("/#/game/" + gid, "_blank");
656 showGame: function(g) {
657 // NOTE: we are an observer, since only games I don't play are shown here
658 // ==> Moves sent by connected remote player(s) if live game
659 window.open("/#/game/" + g.id, "_blank");
661 toggleSocialColor: function(action) {
662 if (!action && document.getElementById("modalPeople").checked)
663 document.getElementById("inputChat").focus();
665 document.getElementById("peopleBtn").classList.remove("somethingnew");
667 processChat: function(chat) {
668 this.send("newchat", { data: chat });
670 getOppsid: function(c) {
671 let oppsid = c.from.sid; //may not be defined if corr + offline opp
673 oppsid = Object.keys(this.people).find(
674 sid => this.people[sid].id == c.from.id
680 socketMessageListener: function(msg) {
681 if (!this.conn) return;
682 const data = JSON.parse(msg.data);
684 case "pollclientsandgamers": {
685 // TODO: shuffling and random filtering on server,
686 // if the room is really crowded.
687 Object.keys(data.sockIds).forEach(sid => {
688 if (sid != this.st.user.sid) {
689 // Pick a target tmpId (+page) at random:
690 const pt = Object.values(data.sockIds[sid]);
691 const randPage = pt[randInt(pt.length)].page;
700 if (!this.people[sid])
701 // Do not set name or id: identity unknown yet
702 this.people[sid] = { tmpIds: data.sockIds[sid] };
704 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
705 if (Object.values(data.sockIds[sid]).some(v => v.page == "/"))
707 this.send("askchallenges", { target: sid });
708 Object.values(data.sockIds[sid]).forEach(v => {
710 v.page.indexOf("/game/") >= 0 &&
711 !v.page.match(/\/[0-9]+$/)
713 // Peer is in Game: ask only if live game
714 this.send("askgame", { target: sid, page: v.page });
722 const page = data.page || "/";
723 if (data.code == "connect") {
724 // Ask challenges only on first connexion:
725 if (!this.people[data.from[0]])
726 this.send("askchallenges", { target: data.from[0] });
728 // Ask game only if live:
729 else if (!page.match(/\/[0-9]+$/))
730 this.send("askgame", { target: data.from[0], page: page });
731 if (!this.people[data.from[0]]) {
737 [data.from[1]]: { page: page, focus: true }
741 // For self multi-connects tests:
742 this.newConnect[data.from[0]] = true;
743 this.send("askidentity", { target: data.from[0], page: page });
746 this.people[data.from[0]].tmpIds[data.from[1]] =
747 { page: page, focus: true };
748 this.$forceUpdate(); //TODO: shouldn't be required
753 case "gdisconnect": {
754 // If the user reloads the page twice very quickly
755 // (experienced with Firefox), the first reload won't have time to
756 // connect but will trigger a "close" event anyway.
757 // ==> Next check is required.
758 if (!this.people[data.from[0]]) return;
759 delete this.people[data.from[0]].tmpIds[data.from[1]];
760 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
761 this.$delete(this.people, data.from[0]);
762 else this.$forceUpdate(); //TODO: shouldn't be required
763 if (data.code == "disconnect") {
764 // Remove the live challenges sent by this player, if
765 // he isn't connected on another tab:
767 !this.people[data.from[0]] ||
768 Object.values(this.people[data.from[0]].tmpIds)
769 .every(v => v.page != "/")
773 c => c.type == "live" && c.from.sid == data.from[0],
779 // Remove the matching live game if now unreachable
780 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
781 // Corr games are always reachable:
782 if (!gid.match(/^[0-9]+$/)) {
783 // Live games are reachable if someone is on the game page
784 if (Object.values(this.people).every(p =>
785 Object.values(p.tmpIds).every(v => v.page != data.page))
787 ArrayFun.remove(this.games, g => g.id == gid);
794 let player = this.people[data.from[0]];
795 // If user reload a page, focus may arrive earlier than connect
797 player.tmpIds[data.from[1]].focus = true;
798 this.$forceUpdate(); //TODO: shouldn't be required
803 let player = this.people[data.from[0]];
805 player.tmpIds[data.from[1]].focus = false;
806 this.$forceUpdate(); //TODO: shouldn't be required
810 case "askidentity": {
811 // Request for identification
813 // Decompose to avoid revealing email
814 name: this.st.user.name,
815 sid: this.st.user.sid,
818 this.send("identity", { data: me, target: data.from });
822 const user = data.data;
823 let player = this.people[user.sid];
824 // player.tmpIds is already set
826 player.name = user.name;
827 // TODO: this.$set(people, ...) fails. So forceUpdate.
828 // But this shouldn't be like that!
830 // If I multi-connect, kill current connexion if no mark (I'm older)
831 if (this.newConnect[user.sid]) {
832 delete this.newConnect[user.sid];
835 user.id == this.st.user.id &&
836 user.sid != this.st.user.sid
838 // I logged in elsewhere:
839 this.cleanBeforeDestroy();
840 alert(this.st.tr["New connexion detected: tab now offline"]);
845 case "askchallenges": {
846 // Send my current live challenges (if any)
847 const myChallenges = this.challenges
849 c.from.sid == this.st.user.sid && c.type == "live"
852 // NOTE: in principle, should only send targeted challenge to the
853 // target. But we may not know yet the identity of the target
854 // (just name), so can't decide if data.from is the target.
857 from: this.st.user.sid,
866 if (myChallenges.length > 0)
867 this.send("challenges", { data: myChallenges, target: data.from });
870 case "challenges": //after "askchallenges"
871 data.data.forEach(this.addChallenge);
874 this.addChallenge(data.data);
876 case "refusechallenge": {
877 const cid = data.data;
878 ArrayFun.remove(this.challenges, c => c.id == cid);
879 alert(this.st.tr["Challenge declined"]);
882 case "deletechallenge_s": {
883 // NOTE: the challenge(s) may be already removed
884 const cref = data.data;
886 ArrayFun.remove(this.challenges, c => c.id == cref.cid);
887 else if (!!cref.sids) {
888 cref.sids.forEach(s => {
891 c => c.type == "live" && c.from.sid == s,
898 case "game": // Individual request
900 const game = data.data;
901 // Ignore games where I play (will go in MyGames page),
902 // and also games that I already received.
904 this.games.findIndex(g => g.id == game.id) == -1 &&
905 game.players.every(p => {
907 p.sid != this.st.user.sid &&
908 (p.id == 0 || p.id != this.st.user.id)
913 newGame.type = this.classifyObject(game);
916 // New game from Hall
918 this.games.push(newGame);
920 newGame.score == '*' &&
921 (newGame.type == "live" && this.gdisplay == "corr") ||
922 (newGame.type == "corr" && this.gdisplay == "live")
925 .getElementById("btnG" + newGame.type)
926 .classList.add("somethingnew");
932 let g = this.games.find(g => g.id == data.gid);
933 if (!!g) g.score = data.score;
937 // New game just started, I'm involved
938 const gameInfo = data.data;
939 if (this.classifyObject(gameInfo) == "live")
940 this.startNewGame(gameInfo);
943 this.st.tr["New correspondence game:"] + " " +
944 "<a href='#/game/" + gameInfo.id + "'>" +
945 "#/game/" + gameInfo.id + "</a>";
946 document.getElementById("modalInfo").checked = true;
951 this.$refs["chatcomp"].newChat(data.data);
952 if (!document.getElementById("modalPeople").checked)
953 document.getElementById("peopleBtn").classList.add("somethingnew");
957 loadMoreCorr: function() {
963 uid: this.st.user.id,
967 const L = res.games.length;
970 this.cursor == Number.MAX_SAFE_INTEGER &&
971 this.games.length == 0 &&
972 this.gdisplay == "live" &&
973 res.games.some(g => g.score == '*')
975 // First loading: show indicators
977 .getElementById("btnGcorr")
978 .classList.add("somethingnew");
980 this.cursor = res.games[L - 1].created;
981 let moreGames = res.games.map(g => {
986 this.games = this.games.concat(moreGames);
988 else this.hasMore = false;
993 // Challenge lifecycle:
994 addChallenge: function(chall) {
995 // NOTE about next condition: see "askchallenges" case.
998 (this.people[chall.from].id > 0 &&
999 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
1001 let newChall = Object.assign({}, chall);
1002 newChall.type = this.classifyObject(chall);
1003 newChall.options = chall.options;
1004 newChall.added = Date.now();
1005 let fromValues = Object.assign({}, this.people[chall.from]);
1006 delete fromValues["pages"]; //irrelevant in this context
1007 newChall.from = Object.assign({ sid: chall.from }, fromValues);
1008 this.setVname(newChall);
1009 this.challenges.push(newChall);
1011 (newChall.type == "live" && this.cdisplay == "corr") ||
1012 (newChall.type == "corr" && this.cdisplay == "live")
1015 .getElementById("btnC" + newChall.type)
1016 .classList.add("somethingnew");
1018 if (!!chall.to && chall.to == this.st.user.name) {
1021 // fromValues.name should exist since the player is online, but
1022 // let's consider there is some chance that the challenge arrives
1023 // right after we connected and before receiving the poll result:
1024 { body: "from " + (fromValues.name || "@nonymous") }
1029 loadNewchallVariant: async function(cb, vname) {
1030 vname = vname || this.setVname(this.newchallenge);
1031 await import("@/variants/" + vname + ".js")
1032 .then((vModule) => {
1033 window.V = vModule[vname + "Rules"];
1034 this.newchallenge.V = window.V;
1038 trySetNewchallDiag: function() {
1039 if (!this.newchallenge.fen) {
1040 this.newchallenge.diag = "";
1043 // If vid > 0 then the variant is loaded (function above):
1044 window.V = this.newchallenge.V;
1046 this.newchallenge.vid > 0 &&
1047 !!this.newchallenge.fen &&
1048 V.IsGoodFen(this.newchallenge.fen)
1050 const parsedFen = V.ParseFen(this.newchallenge.fen);
1051 this.newchallenge.diag = getDiagram({
1052 position: parsedFen.position
1053 //,orientation: parsedFen.turn
1056 else this.newchallenge.diag = "";
1058 newChallFromPreset(pchall) {
1059 this.partialResetNewchallenge();
1060 this.newchallenge.vid = pchall.vid;
1061 this.newchallenge.cadence = pchall.cadence;
1062 this.newchallenge.options = pchall.options;
1063 this.loadNewchallVariant(this.issueNewChallenge);
1065 issueNewChallenge: async function() {
1066 if (!!(this.newchallenge.cadence.match(/^[0-9]+$/)))
1067 this.newchallenge.cadence += "+0"; //assume minutes, no increment
1068 const ctype = this.classifyObject(this.newchallenge);
1069 // TODO: cadence still unchecked so ctype could be wrong...
1071 if (!this.newchallenge.vid)
1072 error = this.st.tr["Please select a variant"];
1073 else if (ctype == "corr" && this.st.user.id <= 0)
1074 error = this.st.tr["Please log in to play correspondence games"];
1075 else if (!this.newchallenge.to && !!this.newchallenge.color)
1076 error = this.st.tr["Color option only for targeted challenge"];
1077 else if (!!this.newchallenge.to) {
1078 if (this.newchallenge.to == this.st.user.name)
1079 error = this.st.tr["Self-challenge is forbidden"];
1082 Object.values(this.people).every(p => p.name != this.newchallenge.to)
1084 error = this.newchallenge.to + " " + this.st.tr["is not online"];
1087 !!this.newchallenge.color &&
1088 !['w', 'b'].includes(this.newchallenge.color)
1090 error = this.st.tr["Wrong color"];
1097 window.V = this.newchallenge.V;
1098 error = checkChallenge(this.newchallenge);
1103 // NOTE: "from" information is not required here
1104 let chall = Object.assign({}, this.newchallenge);
1106 // Get/set options variables (if any) / TODO: v-model?!
1107 for (const check of this.newchallenge.V.Options.check) {
1108 const elt = document.getElementById(check.variable + "_opt");
1109 if (elt.checked) chall.options[check.variable] = true;
1111 for (const select of this.newchallenge.V.Options.select) {
1112 const elt = document.getElementById(select.variable + "_opt");
1113 chall.options[select.variable] = elt.value;
1115 chall.options.abridged = V.AbbreviateOptions(chall.options);
1116 // Add only if not already issued (not counting FEN):
1117 if (this.challenges.some(c =>
1119 c.from.sid == this.st.user.sid ||
1120 (c.from.id > 0 && c.from.id == this.st.user.id)
1124 (!c.to && !chall.to) ||
1128 c.vid == chall.vid &&
1129 c.cadence == chall.cadence &&
1130 this.sameOptions(c.options, chall.options)
1132 alert(this.st.tr["Challenge already exists"]);
1135 if (this.newchallenge.memorize) this.addPresetChall(this.newchallenge);
1137 delete chall["diag"];
1138 const finishAddChallenge = cid => {
1139 chall.id = cid || "c" + getRandString();
1140 const MAX_ALLOWED_CHALLS = 3;
1141 // Remove oldest challenge if 3 found: only 3 at a time of a given type
1142 let countMyChalls = 0;
1143 let challToDelIdx = 0;
1144 let oldestAdded = Number.MAX_SAFE_INTEGER;
1145 for (let i=0; i<this.challenges.length; i++) {
1146 const c = this.challenges[i];
1150 c.from.sid == this.st.user.sid ||
1151 (c.from.id > 0 && c.from.id == this.st.user.id)
1155 if (c.added < oldestAdded) {
1157 oldestAdded = c.added;
1161 if (countMyChalls >= MAX_ALLOWED_CHALLS) {
1163 "deletechallenge_s",
1164 { data: { cid: this.challenges[challToDelIdx].id } }
1166 if (ctype == "corr") {
1170 { data: { id: this.challenges[challToDelIdx].id } }
1173 this.challenges.splice(challToDelIdx, 1);
1175 this.send("newchallenge", {
1176 data: Object.assign(
1177 // Temporarily add sender infos to display challenge on Discord.
1178 { from: this.st.user.sid, sender: this.st.user.name }, chall)
1180 // Add new challenge:
1182 sid: this.st.user.sid,
1183 id: this.st.user.id,
1184 name: this.st.user.name
1186 chall.added = Date.now();
1187 // NOTE: vname and type are redundant (deduced from cadence + vid)
1189 chall.vname = this.newchallenge.vname;
1190 this.challenges.push(chall);
1191 // Remember cadence + vid for quicker further challenges:
1192 localStorage.setItem("cadence", chall.cadence);
1193 localStorage.setItem("vid", chall.vid);
1194 document.getElementById("modalNewgame").checked = false;
1195 // Show the challenge if not on current display
1197 (ctype == "live" && this.cdisplay == "corr") ||
1198 (ctype == "corr" && this.cdisplay == "live")
1200 this.setDisplay('c', ctype);
1203 if (ctype == "live") {
1204 // Live challenges have a random ID
1205 finishAddChallenge(null);
1208 // Correspondence game: send challenge to server
1214 chall: Object.assign(
1217 { options: JSON.stringify(chall.options) }
1220 success: (response) => {
1221 finishAddChallenge(response.id);
1227 // Callback function after a diagram was showed to accept
1228 // or refuse targetted challenge:
1229 decisionChallenge: function(accepted) {
1230 this.curChallToAccept.accepted = accepted;
1231 this.finishProcessingChallenge(this.curChallToAccept);
1232 document.getElementById("modalAccept").checked = false;
1234 finishProcessingChallenge: function(c) {
1237 sid: this.st.user.sid,
1238 id: this.st.user.id,
1239 name: this.st.user.name
1242 if (c.type == "live") {
1243 // Remove all live challenges of both players
1245 "deletechallenge_s",
1246 { data: { sids: [c.from.sid, c.seat.sid] } }
1250 // Corr challenge: just remove the challenge
1251 this.send("deletechallenge_s", { data: { cid: c.id } });
1254 const oppsid = this.getOppsid(c);
1256 this.send("refusechallenge", { data: c.id, target: oppsid });
1257 if (c.type == "corr") {
1261 { data: { id: c.id } }
1264 this.send("deletechallenge_s", { data: { cid: c.id } });
1267 // TODO: if several players click same challenge at the same time: problem
1268 clickChallenge: async function(c) {
1270 c.from.sid == this.st.user.sid || //live
1271 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
1273 if (c.type == "corr" && this.st.user.id <= 0) {
1274 alert(this.st.tr["Please log in to accept corr challenges"]);
1279 await import("@/variants/" + c.vname + ".js")
1280 .then((vModule) => {
1281 window.V = vModule[c.vname + "Rules"];
1283 // c.to == this.st.user.name (connected)
1285 const parsedFen = V.ParseFen(c.fen);
1286 this.tchallDiag = getDiagram({
1287 position: parsedFen.position,
1288 orientation: parsedFen.turn
1291 this.curChallToAccept = c;
1292 document.getElementById("modalAccept").checked = true;
1294 else this.finishProcessingChallenge(c);
1300 if (c.type == "corr") {
1304 { data: { id: c.id } }
1307 this.send("deletechallenge_s", { data: { cid: c.id } });
1309 // In all cases, the challenge is consumed:
1310 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
1312 // NOTE: when launching game, the challenge is already being deleted
1313 launchGame: function(c) {
1314 // White player index 0, black player index 1:
1317 ? (c.color == "w" ? [c.from, c.seat] : [c.seat, c.from])
1318 : shuffle([c.from, c.seat]);
1319 players.forEach(p => {
1320 if (!!p["tmpIds"]) delete p["tmpIds"];
1322 // These game informations will be shared
1324 id: getRandString(),
1325 fen: c.fen || V.GenRandInitFen(c.options),
1326 options: c.options, //for rematch
1331 const notifyNewgame = () => {
1332 const oppsid = this.getOppsid(c);
1334 // Opponent is online
1335 this.send("startgame", { data: gameInfo, target: oppsid });
1336 // If new corr game, notify Hall (except opponent and me)
1337 if (c.type == "corr") {
1342 excluded: [this.st.user.sid, oppsid]
1346 // Notify MyGames page:
1351 targets: gameInfo.players
1354 // NOTE: no need to send the game to the room, since I'll connect
1355 // on game just after, the main Hall will be notified.
1357 if (c.type == "live") {
1358 // TODO: ask my IP + opp IP, to add to game infos? (potential bans)
1360 this.startNewGame(gameInfo);
1361 // Increment game stats counter in DB
1365 { data: { vid: gameInfo.vid } }
1369 // corr: game only on server
1374 // cid is useful to delete the challenge:
1376 gameInfo: Object.assign(
1379 { options: JSON.stringify(gameInfo.options) }
1383 success: (response) => {
1384 gameInfo.id = response.id;
1386 this.$router.push("/game/" + response.id);
1392 // NOTE: for live games only (corr games start on the server)
1393 startNewGame: function(gameInfo) {
1394 this.setVname(gameInfo);
1395 const game = Object.assign(
1399 // (other) Game infos: constant
1400 fenStart: gameInfo.fen,
1401 created: Date.now(),
1402 // Game state (including FEN): will be updated
1404 clocks: [-1, -1], //-1 = unstarted
1411 const myIdx = (game.players[0].sid == this.st.user.sid ? 0 : 1);
1412 GameStorage.add(game, (err) => {
1413 // If an error occurred, game is not added: the focused tab
1414 // already added the game.
1416 if (this.st.settings.sound)
1417 // This will be played several times if several hidden tabs
1418 // on Hall... TODO: fix that (how ?!)
1419 new Audio("/sounds/newgame.flac").play().catch(() => {});
1422 { body: "vs " + (game.players[1-myIdx].name || "@nonymous") }
1425 this.$router.push("/game/" + gameInfo.id);
1428 this.focus ? 0 : 500 + 1000 * Math.random()
1435 <style lang="sass" scoped>
1443 #newgameDiv > .card, #acceptDiv > .card
1447 div#peopleWrap > .card
1450 @media screen and (min-width: 1281px)
1451 div#peopleWrap > .card
1454 @media screen and (max-width: 1280px)
1455 div#peopleWrap > .card
1458 @media screen and (max-width: 767px)
1459 div#peopleWrap > .card
1472 @media screen and (max-width: 767px)
1487 button.player-action
1490 background-color: #E6D271
1493 background-color: #90C4EC !important
1496 background-color: #f9faee
1499 background-color: lightgreen
1501 background-color: red
1504 // margin-top set dynamically (depends if diagram showed or not)
1515 // width: 100% required for Firefox
1523 @media screen and (max-width: 767px)
1532 background-color: #FEAF9E
1534 background-color: #9EB2FE
1536 background-color: #A5FE9E
1538 @media screen and (max-width: 767px)
1547 background-color: lightgrey