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")
15 span.variantName {{ curChallToAccept.vname }}
16 span {{ curChallToAccept.cadence }}
17 span {{ st.tr["with"] + " " + curChallToAccept.from.name }}
19 v-if="!!curChallToAccept.fen"
22 .button-group#buttonsTchall(:style="tchallButtonsMargin()")
23 button.acceptBtn(@click="decisionChallenge(true)")
24 span {{ st.tr["Accept challenge?"] }}
25 button.refuseBtn(@click="decisionChallenge(false)")
26 span {{ st.tr["Refuse"] }}
27 input#modalNewgame.modal(
29 @change="cadenceFocusIfOpened($event)"
33 data-checkbox="modalNewgame"
36 label#closeNewgame.modal-close(for="modalNewgame")
37 div(@keyup.enter="issueNewChallenge()")
39 label(for="selectVariant") {{ st.tr["Variant"] }} *
41 @change="loadNewchallVariant(trySetNewchallDiag)"
42 v-model="newchallenge.vid"
45 v-for="v in st.variants"
47 :selected="newchallenge.vid==v.id"
51 label(for="cadence") {{ st.tr["Cadence"] }} *
52 div#predefinedCadences
53 button(type="button") 15+5
54 button(type="button") 45+30
55 button(type="button") 3d
56 button(type="button") 7d
59 v-model="newchallenge.cadence"
60 placeholder="5+0, 1h+30s, 5d ..."
63 label(for="selectRandomLevel") {{ st.tr["Randomness"] }} *
64 select#selectRandomLevel(v-model="newchallenge.randomness")
65 option(value="0") {{ st.tr["Deterministic"] }}
66 option(value="1") {{ st.tr["Symmetric random"] }}
67 option(value="2") {{ st.tr["Asymmetric random"] }}
69 label(for="memorizeChall") {{ st.tr["Memorize"] }}
72 v-model="newchallenge.memorize"
74 fieldset(v-if="st.user.id > 0")
75 label(for="selectPlayers") {{ st.tr["Play with"] }}
76 select#selectPlayersInList(
77 v-model="newchallenge.to"
78 @change="changeChallTarget()"
82 v-for="p in Object.values(people)"
89 v-model="newchallenge.to"
91 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
94 @input="trySetNewchallDiag()"
96 v-model="newchallenge.fen"
98 .diagram(v-html="newchallenge.diag")
99 button(@click="issueNewChallenge()") {{ st.tr["Send challenge"] }}
100 input#modalPeople.modal(
102 @click="toggleSocialColor()"
106 data-checkbox="modalPeople"
109 label.modal-close(for="modalPeople")
113 v-for="sid in Object.keys(people)"
114 v-if="!!people[sid].name"
116 span {{ people[sid].name }}
117 button.player-action(
119 @click="watchGame(sid)"
121 | {{ st.tr["Observe"] }}
122 button.player-action(
123 v-else-if="isFocusedOnHall(sid)"
124 @click="challenge(sid)"
126 | {{ st.tr["Challenge"] }}
127 p.anonymous @nonymous ({{ anonymousCount() }})
131 @mychat="processChat"
136 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
138 button#peopleBtn(onClick="window.doClick('modalPeople')")
139 | {{ st.tr["Who's there?"] }}
140 button(@click="showNewchallengeForm()")
141 | {{ st.tr["New game"] }}
142 .row(v-if="presetChalls.length > 0")
143 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
144 h4.text-center {{ st.tr["Preset challenges"] }}
148 th {{ st.tr["Variant"] }}
149 th {{ st.tr["Cadence"] }}
150 th {{ st.tr["Random?"] }}
154 v-for="pc in presetChalls"
155 @click="newChallFromPreset(pc)"
159 td(:class="getRandomnessClass(pc)")
160 td.remove-preset(@click="removePresetChall($event, pc)")
161 img(src="/images/icons/delete.svg")
163 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
166 button.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
167 | {{ st.tr["Live challenges"] }}
168 button.tabbtn#btnCcorr(@click="setDisplay('c','corr',$event)")
169 | {{ st.tr["Correspondance challenges"] }}
171 v-show="cdisplay=='live'"
172 :challenges="filterChallenges('live')"
173 @click-challenge="clickChallenge"
176 v-show="cdisplay=='corr'"
177 :challenges="filterChallenges('corr')"
178 @click-challenge="clickChallenge"
182 button.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
183 | {{ st.tr["Live games"] }}
184 button.tabbtn#btnGcorr(@click="setDisplay('g','corr',$event)")
185 | {{ st.tr["Correspondance games"] }}
187 v-show="gdisplay=='live'"
188 :games="filterGames('live')"
190 @show-game="showGame"
192 div(v-show="gdisplay=='corr'")
194 :games="filterGames('corr')"
196 @show-game="showGame"
200 @click="loadMoreCorr()"
202 | {{ st.tr["Load more"] }}
206 import { store } from "@/store";
207 import { checkChallenge } from "@/data/challengeCheck";
208 import { notify } from "@/utils/notifications";
209 import { ArrayFun } from "@/utils/array";
210 import { ajax } from "@/utils/ajax";
211 import params from "@/parameters";
212 import { getRandString, shuffle, randInt } from "@/utils/alea";
213 import { getDiagram } from "@/utils/printDiagram";
214 import Chat from "@/components/Chat.vue";
215 import GameList from "@/components/GameList.vue";
216 import ChallengeList from "@/components/ChallengeList.vue";
217 import { GameStorage } from "@/utils/gameStorage";
218 import { processModalClick } from "@/utils/modalClick";
229 cdisplay: "live", //or corr
231 // timestamp of last showed (oldest) corr game:
232 cursor: Number.MAX_SAFE_INTEGER,
233 // hasMore == TRUE: a priori there could be more games to load
241 vid: parseInt(localStorage.getItem("vid")) || 0,
242 to: "", //name of challenged player (if any)
243 cadence: localStorage.getItem("cadence") || "",
244 randomness: parseInt(localStorage.getItem("challRandomness")) || 2,
245 // VariantRules object, stored to not interfere with
246 // diagrams of targetted challenges:
249 diag: "", //visualizing FEN
250 memorize: false //put settings in localStorage
254 curChallToAccept: {from: {}},
255 presetChalls: JSON.parse(localStorage.getItem("presetChalls") || "[]"),
258 socketCloseListener: 0,
259 // Related to (killing of) self multi-connects:
264 // st.variants changes only once, at loading from [] to [...]
265 "st.variants": function() {
266 // Set potential challenges and games variant names:
267 this.challenges.concat(this.games).forEach(o => {
268 if (!o.vname) o.vname = this.getVname(o.vid);
270 if (!this.newchallenge.V && this.newchallenge.vid > 0)
271 this.loadNewchallVariant();
273 $route: function(to, from) {
274 if (to.path != "/") this.cleanBeforeDestroy();
277 created: function() {
278 document.addEventListener('visibilitychange', this.visibilityChange);
279 window.addEventListener('focus', this.onFocus);
280 window.addEventListener('blur', this.onBlur);
281 window.addEventListener("beforeunload", this.cleanBeforeDestroy);
282 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
283 this.loadNewchallVariant();
284 const my = this.st.user;
285 const tmpId = getRandString();
293 tmpId: { page: "/", focus: true }
297 const connectAndPoll = () => {
298 this.send("connect");
299 this.send("pollclientsandgamers");
301 // Initialize connection
302 this.connexionString =
304 "/?sid=" + this.st.user.sid +
305 "&id=" + this.st.user.id +
308 // Hall: path is "/" (TODO: could be hard-coded as well)
309 encodeURIComponent(this.$route.path);
310 this.conn = new WebSocket(this.connexionString);
311 this.conn.onopen = connectAndPoll;
312 this.conn.addEventListener("message", this.socketMessageListener);
313 this.socketCloseListener = setInterval(
315 if (this.conn.readyState == 3) {
316 this.conn.removeEventListener("message", this.socketMessageListener);
317 this.conn = new WebSocket(this.connexionString);
318 this.conn.addEventListener("message", this.socketMessageListener);
324 mounted: function() {
325 document.getElementById("peopleWrap")
326 .addEventListener("click", (e) => {
327 processModalClick(e, () => {
328 this.toggleSocialColor("close")
331 ["infoDiv", "newgameDiv"].forEach(eltName => {
332 document.getElementById(eltName)
333 .addEventListener("click", processModalClick);
335 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
336 b.addEventListener("click", () => {
337 this.newchallenge.cadence = b.innerHTML;
340 const dispCorr = this.$route.query["disp"];
342 dispCorr || localStorage.getItem("type-challenges") || "live";
344 dispCorr || localStorage.getItem("type-games") || "live";
345 this.setDisplay('c', showCtype);
346 this.setDisplay('g', showGtype);
347 // Ask server for current corr games (all but mines)
349 // Also ask for corr challenges (open + sent by/to me)
350 // List them all, because they are not supposed to be that many (TODO?)
355 data: { uid: this.st.user.id },
356 success: (response) => {
358 response.challenges.length > 0 &&
359 this.challenges.length == 0 &&
360 this.cdisplay == "live"
363 .getElementById("btnCcorr")
364 .classList.add("somethingnew");
366 // Gather all senders names, and then retrieve full identity:
367 // (TODO [perf]: some might be online...)
369 response.challenges.forEach(c => {
370 if (c.uid != this.st.user.id) names[c.uid] = "";
371 else if (!!c.target && c.target != this.st.user.id)
372 names[c.target] = "";
374 const addChallenges = () => {
375 names[this.st.user.id] = this.st.user.name; //in case of
376 this.challenges = this.challenges.concat(
377 response.challenges.map(c => {
378 const from = { name: names[c.uid], id: c.uid }; //or just name
379 const type = this.classifyObject(c);
380 const vname = this.getVname(c.vid);
381 return Object.assign(
387 to: c.target ? names[c.target] : ""
394 if (Object.keys(names).length > 0) {
399 data: { ids: Object.keys(names).join(",") },
400 success: (response2) => {
401 response2.users.forEach(u => {
402 names[u.id] = u.name;
408 } else addChallenges();
413 beforeDestroy: function() {
414 this.cleanBeforeDestroy();
417 cleanBeforeDestroy: function() {
418 clearInterval(this.socketCloseListener);
419 document.removeEventListener('visibilitychange', this.visibilityChange);
420 window.removeEventListener('focus', this.onFocus);
421 window.removeEventListener('blur', this.onBlur);
422 window.removeEventListener("beforeunload", this.cleanBeforeDestroy);
423 this.conn.removeEventListener("message", this.socketMessageListener);
424 this.send("disconnect");
427 getRandomnessClass: function(pc) {
429 ["random-" + pc.randomness]: true
432 anonymousCount: function() {
434 Object.values(this.people).forEach(p => {
435 // Do not cound people who did not send their identity yet:
436 count += (!p.name && p.id === 0) ? 1 : 0;
440 visibilityChange: function() {
441 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
442 this.focus = (document.visibilityState == "visible");
443 this.send(this.focus ? "getfocus" : "losefocus");
445 onFocus: function() {
447 this.send("getfocus");
451 this.send("losefocus");
453 partialResetNewchallenge: function() {
454 // Reset potential target and custom FEN:
455 this.newchallenge.to = "";
456 this.newchallenge.fen = "";
457 this.newchallenge.diag = "";
458 this.newchallenge.memorize = false;
460 showNewchallengeForm: function() {
461 this.partialResetNewchallenge();
462 window.doClick("modalNewgame");
464 addPresetChall: function(chall) {
465 // Add only if not already existing:
466 if (this.presetChalls.some(c =>
467 c.vid == chall.vid &&
468 c.cadence == chall.cadence &&
469 c.randomness == chall.randomness
473 const L = this.presetChalls.length;
474 this.presetChalls.push({
477 vname: chall.vname, //redundant, but easier
478 cadence: chall.cadence,
479 randomness: chall.randomness
481 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
483 removePresetChall: function(e, pchall) {
486 this.presetChalls.findIndex(pc => pc.index == pchall.index);
487 this.presetChalls.splice(pchallIdx, 1);
488 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
490 tchallButtonsMargin: function() {
491 if (!!this.curChallToAccept.fen) return { "margin-top": "10px" };
494 changeChallTarget: function() {
495 if (!this.newchallenge.to) {
496 // Reset potential FEN + diagram
497 this.newchallenge.fen = "";
498 this.newchallenge.diag = "";
501 cadenceFocusIfOpened: function() {
502 if (event.target.checked)
503 document.getElementById("cadence").focus();
505 send: function(code, obj) {
506 if (!!this.conn && this.conn.readyState == 1) {
507 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
510 getVname: function(vid) {
511 const variant = this.st.variants.find(v => v.id == vid);
512 // this.st.variants might be uninitialized (variant == null)
513 return variant ? variant.name : "";
515 filterChallenges: function(type) {
516 return this.challenges.filter(c => c.type == type);
518 filterGames: function(type) {
519 return this.games.filter(g => g.type == type);
521 // o: challenge or game
522 classifyObject: function(o) {
523 // Consider imports as live games (TODO)
524 if (!!o.id && !!o.id.toString().match(/^i/)) return "live";
525 return o.cadence.indexOf("d") === -1 ? "live" : "corr";
527 setDisplay: function(letter, type, e) {
528 this[letter + "display"] = type;
529 localStorage.setItem(
530 "type-" + (letter == "c" ? "challenges" : "games"),
535 : document.getElementById("btn" + letter.toUpperCase() + type);
536 elt.classList.add("active");
537 elt.classList.remove("somethingnew"); //in case of
538 if (!!elt.previousElementSibling)
539 elt.previousElementSibling.classList.remove("active");
540 else elt.nextElementSibling.classList.remove("active");
542 isGamer: function(sid) {
543 return Object.values(this.people[sid].tmpIds)
544 .some(v => v.focus && v.page.indexOf("/game/") >= 0);
546 isFocusedOnHall: function(sid) {
548 // This is meant to challenge people, thus the next 2 conditions:
549 this.st.user.id > 0 &&
550 sid != this.st.user.sid &&
551 Object.values(this.people[sid].tmpIds)
552 .some(v => v.focus && v.page == "/")
555 challenge: function(sid) {
556 this.partialResetNewchallenge();
557 // Available, in Hall
558 this.newchallenge.to = this.people[sid].name;
559 // TODO: also store target sid to not re-search for it
560 document.getElementById("modalPeople").checked = false;
561 window.doClick("modalNewgame");
563 watchGame: function(sid) {
564 // In some game, maybe playing maybe not: show a random one
566 Object.values(this.people[sid].tmpIds).forEach(v => {
568 const matchGid = v.page.match(/[a-zA-Z0-9]+$/);
569 if (!!matchGid) gids.push(matchGid[0]);
572 const gid = gids[Math.floor(Math.random() * gids.length)];
573 const game = this.games.find(g => g.id == gid);
574 if (!!game) this.showGame(game);
575 else this.$router.push("/game/" + gid); //game vs. me
577 showGame: function(g) {
578 // NOTE: we are an observer, since only games I don't play are shown here
579 // ==> Moves sent by connected remote player(s) if live game
580 this.$router.push("/game/" + g.id);
582 toggleSocialColor: function(action) {
583 if (!action && document.getElementById("modalPeople").checked)
584 document.getElementById("inputChat").focus();
586 document.getElementById("peopleBtn").classList.remove("somethingnew");
588 processChat: function(chat) {
589 this.send("newchat", { data: chat });
591 getOppsid: function(c) {
592 let oppsid = c.from.sid; //may not be defined if corr + offline opp
594 oppsid = Object.keys(this.people).find(
595 sid => this.people[sid].id == c.from.id
601 socketMessageListener: function(msg) {
602 if (!this.conn) return;
603 const data = JSON.parse(msg.data);
605 case "pollclientsandgamers": {
606 // TODO: shuffling and random filtering on server,
607 // if the room is really crowded.
608 Object.keys(data.sockIds).forEach(sid => {
609 if (sid != this.st.user.sid) {
610 // Pick a target tmpId (+page) at random:
611 const pt = Object.values(data.sockIds[sid]);
612 const randPage = pt[randInt(pt.length)].page;
621 if (!this.people[sid])
622 // Do not set name or id: identity unknown yet
623 this.people[sid] = { tmpIds: data.sockIds[sid] };
625 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
626 if (Object.values(data.sockIds[sid]).some(v => v.page == "/"))
628 this.send("askchallenges", { target: sid });
629 Object.values(data.sockIds[sid]).forEach(v => {
631 v.page.indexOf("/game/") >= 0 &&
632 !v.page.match(/\/[0-9]+$/)
634 // Peer is in Game: ask only if live game
635 this.send("askgame", { target: sid, page: v.page });
643 const page = data.page || "/";
644 if (data.code == "connect") {
645 // Ask challenges only on first connexion:
646 if (!this.people[data.from[0]])
647 this.send("askchallenges", { target: data.from[0] });
649 // Ask game only if live:
650 else if (!page.match(/\/[0-9]+$/))
651 this.send("askgame", { target: data.from[0], page: page });
652 if (!this.people[data.from[0]]) {
658 [data.from[1]]: { page: page, focus: true }
662 // For self multi-connects tests:
663 this.newConnect[data.from[0]] = true;
664 this.send("askidentity", { target: data.from[0], page: page });
666 this.people[data.from[0]].tmpIds[data.from[1]] =
667 { page: page, focus: true };
668 this.$forceUpdate(); //TODO: shouldn't be required
673 case "gdisconnect": {
674 // If the user reloads the page twice very quickly
675 // (experienced with Firefox), the first reload won't have time to
676 // connect but will trigger a "close" event anyway.
677 // ==> Next check is required.
678 if (!this.people[data.from[0]]) return;
679 delete this.people[data.from[0]].tmpIds[data.from[1]];
680 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
681 this.$delete(this.people, data.from[0]);
682 else this.$forceUpdate(); //TODO: shouldn't be required
683 if (data.code == "disconnect") {
684 // Remove the live challenges sent by this player, if
685 // he isn't connected on another tab:
687 !this.people[data.from[0]] ||
688 Object.values(this.people[data.from[0]].tmpIds)
689 .every(v => v.page != "/")
693 c => c.type == "live" && c.from.sid == data.from[0],
698 // Remove the matching live game if now unreachable
699 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
700 // Corr games are always reachable:
701 if (!gid.match(/^[0-9]+$/)) {
702 // Live games are reachable if someone is on the game page
703 if (Object.values(this.people).every(p =>
704 Object.values(p.tmpIds).every(v => v.page != data.page))
706 ArrayFun.remove(this.games, g => g.id == gid);
713 let player = this.people[data.from[0]];
714 // If user reload a page, focus may arrive earlier than connect
716 player.tmpIds[data.from[1]].focus = true;
717 this.$forceUpdate(); //TODO: shouldn't be required
722 let player = this.people[data.from[0]];
724 player.tmpIds[data.from[1]].focus = false;
725 this.$forceUpdate(); //TODO: shouldn't be required
729 case "askidentity": {
730 // Request for identification
732 // Decompose to avoid revealing email
733 name: this.st.user.name,
734 sid: this.st.user.sid,
737 this.send("identity", { data: me, target: data.from });
741 const user = data.data;
742 let player = this.people[user.sid];
743 // player.tmpIds is already set
745 player.name = user.name;
746 // TODO: this.$set(people, ...) fails. So forceUpdate.
747 // But this shouldn't be like that!
749 // If I multi-connect, kill current connexion if no mark (I'm older)
750 if (this.newConnect[user.sid]) {
751 delete this.newConnect[user.sid];
754 user.id == this.st.user.id &&
755 user.sid != this.st.user.sid
757 // I logged in elsewhere:
758 this.cleanBeforeDestroy();
759 alert(this.st.tr["New connexion detected: tab now offline"]);
764 case "askchallenges": {
765 // Send my current live challenges (if any)
766 const myChallenges = this.challenges
768 c.from.sid == this.st.user.sid && c.type == "live"
771 // NOTE: in principle, should only send targeted challenge to the
772 // target. But we may not know yet the identity of the target
773 // (just name), so can't decide if data.from is the target.
776 from: this.st.user.sid,
778 randomness: c.randomness,
785 if (myChallenges.length > 0)
786 this.send("challenges", { data: myChallenges, target: data.from });
789 case "challenges": //after "askchallenges"
790 data.data.forEach(this.addChallenge);
793 this.addChallenge(data.data);
795 case "refusechallenge": {
796 const cid = data.data;
797 ArrayFun.remove(this.challenges, c => c.id == cid);
798 alert(this.st.tr["Challenge declined"]);
801 case "deletechallenge_s": {
802 // NOTE: the challenge(s) may be already removed
803 const cref = data.data;
805 ArrayFun.remove(this.challenges, c => c.id == cref.cid);
806 else if (!!cref.sids) {
807 cref.sids.forEach(s => {
810 c => c.type == "live" && c.from.sid == s,
817 case "game": // Individual request
819 const game = data.data;
820 // Ignore games where I play (will go in MyGames page),
821 // and also games that I already received.
823 game.players.every(p =>
824 p.sid != this.st.user.sid && p.id != this.st.user.id) &&
825 this.games.findIndex(g => g.id == game.id) == -1
828 newGame.type = this.classifyObject(game);
829 newGame.vname = this.getVname(game.vid);
831 // New game from Hall
833 this.games.push(newGame);
835 (newGame.type == "live" && this.gdisplay == "corr") ||
836 (newGame.type == "corr" && this.gdisplay == "live")
839 .getElementById("btnG" + newGame.type)
840 .classList.add("somethingnew");
846 let g = this.games.find(g => g.id == data.gid);
847 if (!!g) g.score = data.score;
851 // New game just started, I'm involved
852 const gameInfo = data.data;
853 if (this.classifyObject(gameInfo) == "live")
854 this.startNewGame(gameInfo);
857 this.st.tr["New correspondance game:"] + " " +
858 "<a href='#/game/" + gameInfo.id + "'>" +
859 "#/game/" + gameInfo.id + "</a>";
860 document.getElementById("modalInfo").checked = true;
865 this.$refs["chatcomp"].newChat(data.data);
866 if (!document.getElementById("modalPeople").checked)
867 document.getElementById("peopleBtn").classList.add("somethingnew");
871 loadMoreCorr: function() {
877 uid: this.st.user.id,
881 const L = res.games.length;
884 this.cursor == Number.MAX_SAFE_INTEGER &&
885 this.games.length == 0 &&
886 this.gdisplay == "live"
888 // First loading: show indicators
890 .getElementById("btnGcorr")
891 .classList.add("somethingnew");
893 this.cursor = res.games[L - 1].created;
894 let moreGames = res.games.map(g => {
895 const vname = this.getVname(g.vid);
896 return Object.assign(
905 this.games = this.games.concat(moreGames);
906 } else this.hasMore = false;
911 // Challenge lifecycle:
912 addChallenge: function(chall) {
913 // NOTE about next condition: see "askchallenges" case.
916 (this.people[chall.from].id > 0 &&
917 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
919 let newChall = Object.assign({}, chall);
920 newChall.type = this.classifyObject(chall);
921 newChall.randomness = chall.randomness;
922 newChall.added = Date.now();
923 let fromValues = Object.assign({}, this.people[chall.from]);
924 delete fromValues["pages"]; //irrelevant in this context
925 newChall.from = Object.assign({ sid: chall.from }, fromValues);
926 newChall.vname = this.getVname(newChall.vid);
927 this.challenges.push(newChall);
929 (newChall.type == "live" && this.cdisplay == "corr") ||
930 (newChall.type == "corr" && this.cdisplay == "live")
933 .getElementById("btnC" + newChall.type)
934 .classList.add("somethingnew");
939 // fromValues.name should exist since the player is online, but
940 // let's consider there is some chance that the challenge arrives
941 // right after we connected and before receiving the poll result:
942 { body: "from " + (fromValues.name || "unknown yet...") }
947 loadNewchallVariant: async function(cb) {
948 const vname = this.getVname(this.newchallenge.vid);
949 await import("@/variants/" + vname + ".js")
951 window.V = vModule[vname + "Rules"];
952 this.newchallenge.V = window.V;
953 this.newchallenge.vname = vname;
957 trySetNewchallDiag: function() {
958 if (!this.newchallenge.fen) {
959 this.newchallenge.diag = "";
962 // If vid > 0 then the variant is loaded (function above):
963 window.V = this.newchallenge.V;
965 this.newchallenge.vid > 0 &&
966 !!this.newchallenge.fen &&
967 V.IsGoodFen(this.newchallenge.fen)
969 const parsedFen = V.ParseFen(this.newchallenge.fen);
970 this.newchallenge.diag = getDiagram({
971 position: parsedFen.position,
972 orientation: parsedFen.turn
974 } else this.newchallenge.diag = "";
976 newChallFromPreset(pchall) {
977 this.partialResetNewchallenge();
978 this.newchallenge.vid = pchall.vid;
979 this.newchallenge.cadence = pchall.cadence;
980 this.newchallenge.randomness = pchall.randomness;
981 this.loadNewchallVariant(this.issueNewChallenge);
983 issueNewChallenge: async function() {
984 if (!!(this.newchallenge.cadence.match(/^[0-9]+$/)))
985 this.newchallenge.cadence += "+0"; //assume minutes, no increment
986 const ctype = this.classifyObject(this.newchallenge);
987 // TODO: cadence still unchecked so ctype could be wrong...
989 if (!this.newchallenge.vid)
990 error = this.st.tr["Please select a variant"];
991 else if (ctype == "corr" && this.st.user.id <= 0)
992 error = this.st.tr["Please log in to play correspondance games"];
993 else if (!!this.newchallenge.to) {
994 if (this.newchallenge.to == this.st.user.name)
995 error = this.st.tr["Self-challenge is forbidden"];
998 Object.values(this.people).every(p => p.name != this.newchallenge.to)
1000 error = this.newchallenge.to + " " + this.st.tr["is not online"];
1007 window.V = this.newchallenge.V;
1008 error = checkChallenge(this.newchallenge);
1013 // NOTE: "from" information is not required here
1014 let chall = Object.assign({}, this.newchallenge);
1015 // Add only if not already issued (not counting target or FEN):
1016 if (this.challenges.some(c =>
1017 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) &&
1018 c.vid == chall.vid &&
1019 c.cadence == chall.cadence &&
1020 c.randomness == chall.randomness
1022 alert(this.st.tr["Challenge already exists"]);
1025 if (this.newchallenge.memorize) this.addPresetChall(this.newchallenge);
1027 delete chall["diag"];
1028 const finishAddChallenge = cid => {
1029 chall.id = cid || "c" + getRandString();
1030 const MAX_ALLOWED_CHALLS = 3;
1031 // Remove oldest challenge if 3 found: only 3 at a time of a given type
1032 let countMyChalls = 0;
1033 let challToDelIdx = 0;
1034 let oldestAdded = Number.MAX_SAFE_INTEGER;
1035 for (let i=0; i<this.challenges.length; i++) {
1036 const c = this.challenges[i];
1039 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id)
1042 if (c.added < oldestAdded) {
1044 oldestAdded = c.added;
1048 if (countMyChalls >= MAX_ALLOWED_CHALLS) {
1050 "deletechallenge_s",
1051 { data: { cid: this.challenges[challToDelIdx].id } }
1053 if (ctype == "corr") {
1057 { data: { id: this.challenges[challToDelIdx].id } }
1060 this.challenges.splice(challToDelIdx, 1);
1062 this.send("newchallenge", {
1063 data: Object.assign({ from: this.st.user.sid }, chall)
1065 // Add new challenge:
1067 sid: this.st.user.sid,
1068 id: this.st.user.id,
1069 name: this.st.user.name
1071 chall.added = Date.now();
1072 // NOTE: vname and type are redundant (deduced from cadence + vid)
1074 chall.vname = this.newchallenge.vname;
1075 this.challenges.push(chall);
1076 // Remember cadence + vid for quicker further challenges:
1077 localStorage.setItem("cadence", chall.cadence);
1078 localStorage.setItem("vid", chall.vid);
1079 localStorage.setItem("challRandomness", chall.randomness);
1080 document.getElementById("modalNewgame").checked = false;
1081 // Show the challenge if not on current display
1083 (ctype == "live" && this.cdisplay == "corr") ||
1084 (ctype == "corr" && this.cdisplay == "live")
1086 this.setDisplay('c', ctype);
1089 if (ctype == "live") {
1090 // Live challenges have a random ID
1091 finishAddChallenge(null);
1093 // Correspondance game: send challenge to server
1098 data: { chall: chall },
1099 success: (response) => {
1100 finishAddChallenge(response.id);
1106 // Callback function after a diagram was showed to accept
1107 // or refuse targetted challenge:
1108 decisionChallenge: function(accepted) {
1109 this.curChallToAccept.accepted = accepted;
1110 this.finishProcessingChallenge(this.curChallToAccept);
1111 document.getElementById("modalAccept").checked = false;
1113 finishProcessingChallenge: function(c) {
1116 sid: this.st.user.sid,
1117 id: this.st.user.id,
1118 name: this.st.user.name
1121 if (c.type == "live") {
1122 // Remove all live challenges of both players
1124 "deletechallenge_s",
1125 { data: { sids: [c.from.sid, c.seat.sid] } }
1129 // Corr challenge: just remove the challenge
1130 this.send("deletechallenge_s", { data: { cid: c.id } });
1132 const oppsid = this.getOppsid(c);
1134 this.send("refusechallenge", { data: c.id, target: oppsid });
1135 if (c.type == "corr") {
1139 { data: { id: c.id } }
1142 this.send("deletechallenge_s", { data: { cid: c.id } });
1145 // TODO: if several players click same challenge at the same time: problem
1146 clickChallenge: async function(c) {
1148 c.from.sid == this.st.user.sid || //live
1149 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
1151 if (c.type == "corr" && this.st.user.id <= 0) {
1152 alert(this.st.tr["Please log in to accept corr challenges"]);
1156 await import("@/variants/" + c.vname + ".js")
1157 .then((vModule) => {
1158 window.V = vModule[c.vname + "Rules"];
1160 // c.to == this.st.user.name (connected)
1162 const parsedFen = V.ParseFen(c.fen);
1163 c.mycolor = V.GetOppCol(parsedFen.turn);
1164 this.tchallDiag = getDiagram({
1165 position: parsedFen.position,
1166 orientation: c.mycolor
1169 this.curChallToAccept = c;
1170 document.getElementById("modalAccept").checked = true;
1172 else this.finishProcessingChallenge(c);
1177 if (c.type == "corr") {
1181 { data: { id: c.id } }
1184 this.send("deletechallenge_s", { data: { cid: c.id } });
1186 // In all cases, the challenge is consumed:
1187 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
1189 // NOTE: when launching game, the challenge is already being deleted
1190 launchGame: function(c) {
1191 // White player index 0, black player index 1:
1194 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
1195 : shuffle([c.from, c.seat]);
1196 players.forEach(p => {
1197 if (!!p["tmpIds"]) delete p["tmpIds"];
1199 // These game informations will be shared
1201 id: getRandString(),
1202 fen: c.fen || V.GenRandInitFen(c.randomness),
1203 randomness: c.randomness, //for rematch
1208 const notifyNewgame = () => {
1209 const oppsid = this.getOppsid(c);
1211 // Opponent is online
1212 this.send("startgame", { data: gameInfo, target: oppsid });
1213 // If new corr game, notify Hall (except opponent and me)
1214 if (c.type == "corr") {
1219 excluded: [this.st.user.sid, oppsid]
1223 // Notify MyGames page:
1228 targets: gameInfo.players
1231 // NOTE: no need to send the game to the room, since I'll connect
1232 // on game just after, the main Hall will be notified.
1234 if (c.type == "live") {
1236 this.startNewGame(gameInfo);
1238 // corr: game only on server
1243 // cid is useful to delete the challenge:
1248 success: (response) => {
1249 gameInfo.id = response.id;
1251 this.$router.push("/game/" + response.id);
1257 // NOTE: for live games only (corr games start on the server)
1258 startNewGame: function(gameInfo) {
1259 const game = Object.assign(
1263 // (other) Game infos: constant
1264 fenStart: gameInfo.fen,
1265 vname: this.getVname(gameInfo.vid),
1266 created: Date.now(),
1267 // Game state (including FEN): will be updated
1269 clocks: [-1, -1], //-1 = unstarted
1276 const myIdx = (game.players[0].sid == this.st.user.sid ? 0 : 1);
1277 GameStorage.add(game, (err) => {
1278 // If an error occurred, game is not added: a tab already
1279 // added the game. Maybe a focused one, maybe not.
1280 // We know for sure that it emitted the gong start sound.
1281 // ==> Do not play it again.
1282 if (!err && this.st.settings.sound)
1283 new Audio("/sounds/newgame.flac").play().catch(() => {});
1287 { body: "vs " + game.players[1-myIdx].name || "@nonymous" }
1290 this.$router.push("/game/" + gameInfo.id);
1293 this.focus ? 500 + 1000 * Math.random() : 0
1300 <style lang="sass" scoped>
1308 #newgameDiv > .card, #acceptDiv > .card
1312 div#peopleWrap > .card
1315 @media screen and (min-width: 1281px)
1316 div#peopleWrap > .card
1319 @media screen and (max-width: 1280px)
1320 div#peopleWrap > .card
1323 @media screen and (max-width: 767px)
1324 div#peopleWrap > .card
1337 @media screen and (max-width: 767px)
1352 button.player-action
1356 background-color: #c5fefe !important
1359 background-color: #f9faee
1362 background-color: lightgreen
1364 background-color: red
1367 // margin-top set dynamically (depends if diagram showed or not)
1378 // width: 100% required for Firefox
1386 @media screen and (max-width: 767px)
1392 background-color: #FF5733
1394 background-color: #2B63B4
1396 background-color: #33B42B
1398 @media screen and (max-width: 767px)
1407 background-color: lightgrey