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 }}
18 p.text-center(v-if="!!curChallToAccept.color")
19 | {{ st.tr["Your color:"] + " " + invColor(curChallToAccept.color) }}
21 v-if="!!curChallToAccept.fen"
24 .button-group#buttonsTchall(:style="tchallButtonsMargin()")
25 button.acceptBtn(@click="decisionChallenge(true)")
26 span {{ st.tr["Accept challenge?"] }}
27 button.refuseBtn(@click="decisionChallenge(false)")
28 span {{ st.tr["Refuse"] }}
29 input#modalNewgame.modal(
31 @change="cadenceFocusIfOpened($event)"
35 data-checkbox="modalNewgame"
38 label#closeNewgame.modal-close(for="modalNewgame")
39 div(@keyup.enter="issueNewChallenge()")
41 label(for="selectVariant") {{ st.tr["Variant"] }} *
43 @change="loadNewchallVariant(trySetNewchallDiag)"
44 v-model="newchallenge.vid"
47 v-for="v in st.variants"
49 :selected="newchallenge.vid==v.id"
53 label(for="cadence") {{ st.tr["Cadence"] }} *
54 div#predefinedCadences
55 button(type="button") 15+5
56 button(type="button") 45+30
57 button(type="button") 3d
58 button(type="button") 7d
61 v-model="newchallenge.cadence"
62 placeholder="5+0, 1h+30s, 5d ..."
65 label(for="selectRandomLevel") {{ st.tr["Randomness"] }} *
66 select#selectRandomLevel(v-model="newchallenge.randomness")
67 option(value="0") {{ st.tr["Deterministic"] }}
68 option(value="1") {{ st.tr["Symmetric random"] }}
69 option(value="2") {{ st.tr["Asymmetric random"] }}
71 label(for="memorizeChall") {{ st.tr["Memorize"] }}
74 v-model="newchallenge.memorize"
76 fieldset(v-if="st.user.id > 0")
77 label(for="selectPlayers") {{ st.tr["Play with"] }}
78 select#selectPlayersInList(
79 v-model="newchallenge.to"
80 @change="changeChallTarget()"
84 v-for="p in Object.values(people)"
91 v-model="newchallenge.to"
93 fieldset(v-show="st.user.id > 0 && newchallenge.to.length > 0")
94 label(for="selectColor") {{ st.tr["Color"] }}
95 select#selectColor(v-model="newchallenge.color")
97 option(value='w') {{ st.tr["White"] }}
98 option(value='b') {{ st.tr["Black"] }}
102 @input="trySetNewchallDiag()"
104 v-model="newchallenge.fen"
106 .diagram(v-html="newchallenge.diag")
107 button(@click="issueNewChallenge()") {{ st.tr["Send challenge"] }}
108 input#modalPeople.modal(
110 @click="toggleSocialColor()"
114 data-checkbox="modalPeople"
117 label.modal-close(for="modalPeople")
121 v-for="sid in Object.keys(people)"
122 v-if="!!people[sid].name"
124 UserBio.user-bio(:uid="people[sid].id" :uname="people[sid].name")
125 button.player-action(
127 @click="watchGame(sid)"
129 | {{ st.tr["Observe"] }}
130 button.player-action(
131 v-else-if="st.user.sid != sid"
132 :class="{focused: isFocusedOnHall(sid)}"
133 @click="challenge(sid)"
135 | {{ st.tr["Challenge"] }}
136 p.anonymous @nonymous ({{ anonymousCount() }})
140 @mychat="processChat"
145 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
147 button#peopleBtn(onClick="window.doClick('modalPeople')")
148 | {{ st.tr["Who's there?"] }}
149 button(@click="showNewchallengeForm()")
150 | {{ st.tr["New game"] }}
151 .row(v-if="presetChalls.length > 0")
152 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
153 h4.text-center {{ st.tr["Preset challenges"] }}
157 th {{ st.tr["Variant"] }}
158 th {{ st.tr["Cadence"] }}
159 th {{ st.tr["Random?"] }}
163 v-for="pc in presetChalls"
164 @click="newChallFromPreset(pc)"
168 td(:class="getRandomnessClass(pc)")
169 td.remove-preset(@click="removePresetChall($event, pc)")
170 img(src="/images/icons/delete.svg")
172 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
175 button.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
176 | {{ st.tr["Live challenges"] }}
177 button.tabbtn#btnCcorr(@click="setDisplay('c','corr',$event)")
178 | {{ st.tr["Correspondence challenges"] }}
180 v-show="cdisplay=='live'"
181 :challenges="filterChallenges('live')"
182 @click-challenge="clickChallenge"
185 v-show="cdisplay=='corr'"
186 :challenges="filterChallenges('corr')"
187 @click-challenge="clickChallenge"
191 button.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
192 | {{ st.tr["Live games"] }}
193 button.tabbtn#btnGcorr(@click="setDisplay('g','corr',$event)")
194 | {{ st.tr["Correspondence games"] }}
196 v-show="gdisplay=='live'"
197 :games="filterGames('live')"
199 @show-game="showGame"
201 div(v-show="gdisplay=='corr'")
203 :games="filterGames('corr')"
205 @show-game="showGame"
209 @click="loadMoreCorr()"
211 | {{ st.tr["Load more"] }}
215 import { store } from "@/store";
216 import { checkChallenge } from "@/data/challengeCheck";
217 import { notify } from "@/utils/notifications";
218 import { ArrayFun } from "@/utils/array";
219 import { ajax } from "@/utils/ajax";
220 import params from "@/parameters";
221 import { getRandString, shuffle, randInt } from "@/utils/alea";
222 import { getDiagram } from "@/utils/printDiagram";
223 import Chat from "@/components/Chat.vue";
224 import UserBio from "@/components/UserBio.vue";
225 import GameList from "@/components/GameList.vue";
226 import ChallengeList from "@/components/ChallengeList.vue";
227 import { GameStorage } from "@/utils/gameStorage";
228 import { processModalClick } from "@/utils/modalClick";
240 cdisplay: "live", //or corr
242 // timestamp of last showed (oldest) corr game:
243 cursor: Number.MAX_SAFE_INTEGER,
244 // hasMore == TRUE: a priori there could be more games to load
252 vid: parseInt(localStorage.getItem("vid"), 10) || 0,
253 to: "", //name of challenged player (if any)
255 cadence: localStorage.getItem("cadence") || "",
257 // Warning: randomness can be 0, then !!randomness is false
258 (parseInt(localStorage.getItem("challRandomness"),10)+1 || 3) - 1,
259 // VariantRules object, stored to not interfere with
260 // diagrams of targetted challenges:
263 diag: "", //visualizing FEN
264 memorize: false //put settings in localStorage
268 curChallToAccept: { from: {} },
269 presetChalls: JSON.parse(localStorage.getItem("presetChalls") || "[]"),
272 socketCloseListener: 0,
273 // Related to (killing of) self multi-connects:
278 // st.variants changes only once, at loading from [] to [...]
279 "st.variants": function() {
280 // Set potential challenges and games variant names:
281 this.challenges.concat(this.games).forEach(o => {
282 if (!o.vname) o.vname = this.getVname(o.vid);
284 if (!this.newchallenge.V && this.newchallenge.vid > 0)
285 this.loadNewchallVariant();
287 $route: function(to, from) {
288 if (to.path != "/") this.cleanBeforeDestroy();
291 created: function() {
292 document.addEventListener('visibilitychange', this.visibilityChange);
293 window.addEventListener('focus', this.onFocus);
294 window.addEventListener('blur', this.onBlur);
295 window.addEventListener("beforeunload", this.cleanBeforeDestroy);
296 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
297 this.loadNewchallVariant();
298 const my = this.st.user;
299 const tmpId = getRandString();
307 tmpId: { page: "/", focus: true }
311 const connectAndPoll = () => {
312 this.send("connect");
313 this.send("pollclientsandgamers");
314 if (!!this.$route.query["challenge"]) {
315 // Automatic challenge sending, for tournaments
316 this.loadNewchallVariant(
318 this.newchallenge = {
322 .find(v => v.name == this.$route.query["variant"])
324 to: this.$route.query["challenge"],
325 color: this.$route.query["color"] || '',
326 cadence: this.$route.query["cadence"],
327 // Tournament: no randomness (TODO: for now at least)
331 this.issueNewChallenge();
333 this.$route.query["variant"]
337 // Initialize connection
338 this.connexionString =
340 "/?sid=" + this.st.user.sid +
341 "&id=" + this.st.user.id +
344 // Hall: path is "/" (TODO: could be hard-coded as well)
345 encodeURIComponent(this.$route.path);
346 this.conn = new WebSocket(this.connexionString);
347 this.conn.onopen = connectAndPoll;
348 this.conn.addEventListener("message", this.socketMessageListener);
349 this.socketCloseListener = setInterval(
351 if (this.conn.readyState == 3) {
352 this.conn.removeEventListener("message", this.socketMessageListener);
353 this.conn = new WebSocket(this.connexionString);
354 this.conn.addEventListener("message", this.socketMessageListener);
360 mounted: function() {
361 document.getElementById("peopleWrap")
362 .addEventListener("click", (e) => {
363 processModalClick(e, () => {
364 this.toggleSocialColor("close")
367 ["infoDiv", "newgameDiv"].forEach(eltName => {
368 document.getElementById(eltName)
369 .addEventListener("click", processModalClick);
371 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
372 b.addEventListener("click", () => {
373 this.newchallenge.cadence = b.innerHTML;
376 const dispCorr = this.$route.query["disp"];
378 dispCorr || localStorage.getItem("type-challenges") || "live";
380 dispCorr || localStorage.getItem("type-games") || "live";
381 this.setDisplay('c', showCtype);
382 this.setDisplay('g', showGtype);
383 // Ask server for current corr games (all but mines)
385 // Also ask for corr challenges (open + sent by/to me)
386 // List them all, because they are not supposed to be that many (TODO?)
391 data: { uid: this.st.user.id },
392 success: (response) => {
394 response.challenges.length > 0 &&
395 this.challenges.length == 0 &&
396 this.cdisplay == "live"
399 .getElementById("btnCcorr")
400 .classList.add("somethingnew");
402 // Gather all senders names, and then retrieve full identity:
403 // (TODO [perf]: some might be online...)
405 response.challenges.forEach(c => {
406 if (c.uid != this.st.user.id) names[c.uid] = "";
407 else if (!!c.target && c.target != this.st.user.id)
408 names[c.target] = "";
410 const addChallenges = () => {
411 names[this.st.user.id] = this.st.user.name; //in case of
412 this.challenges = this.challenges.concat(
413 response.challenges.map(c => {
414 const from = { name: names[c.uid], id: c.uid }; //or just name
415 const type = this.classifyObject(c);
416 const vname = this.getVname(c.vid);
417 return Object.assign(
423 to: c.target ? names[c.target] : ""
430 if (Object.keys(names).length > 0) {
435 data: { ids: Object.keys(names).join(",") },
436 success: (response2) => {
437 response2.users.forEach(u => {
438 names[u.id] = u.name;
444 } else addChallenges();
449 beforeDestroy: function() {
450 this.cleanBeforeDestroy();
453 cleanBeforeDestroy: function() {
454 clearInterval(this.socketCloseListener);
455 document.removeEventListener('visibilitychange', this.visibilityChange);
456 window.removeEventListener('focus', this.onFocus);
457 window.removeEventListener('blur', this.onBlur);
458 window.removeEventListener("beforeunload", this.cleanBeforeDestroy);
459 this.conn.removeEventListener("message", this.socketMessageListener);
460 this.send("disconnect");
463 getRandomnessClass: function(pc) {
465 ["random-" + pc.randomness]: true
468 anonymousCount: function() {
470 Object.values(this.people).forEach(p => {
471 // Do not cound people who did not send their identity yet:
472 count += (!p.name && p.id === 0) ? 1 : 0;
476 visibilityChange: function() {
477 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
478 this.focus = (document.visibilityState == "visible");
479 this.send(this.focus ? "getfocus" : "losefocus");
481 onFocus: function() {
483 this.send("getfocus");
487 this.send("losefocus");
489 invColor: function(c) {
490 if (c == 'w') return this.st.tr["Black"];
491 return this.tr.tr["White"];
493 partialResetNewchallenge: function() {
494 // Reset potential target and custom FEN:
495 this.newchallenge.to = "";
496 this.newchallenge.color = '';
497 this.newchallenge.fen = "";
498 this.newchallenge.diag = "";
499 this.newchallenge.memorize = false;
501 showNewchallengeForm: function() {
502 this.partialResetNewchallenge();
503 window.doClick("modalNewgame");
505 addPresetChall: function(chall) {
506 // Add only if not already existing:
507 if (this.presetChalls.some(c =>
508 c.vid == chall.vid &&
509 c.cadence == chall.cadence &&
510 c.randomness == chall.randomness
514 const L = this.presetChalls.length;
515 this.presetChalls.push({
518 vname: chall.vname, //redundant, but easier
519 cadence: chall.cadence,
520 randomness: chall.randomness
522 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
524 removePresetChall: function(e, pchall) {
527 this.presetChalls.findIndex(pc => pc.index == pchall.index);
528 this.presetChalls.splice(pchallIdx, 1);
529 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
531 tchallButtonsMargin: function() {
532 if (!!this.curChallToAccept.fen) return { "margin-top": "10px" };
535 changeChallTarget: function() {
536 if (!this.newchallenge.to) {
537 // Reset potential FEN + diagram
538 this.newchallenge.fen = "";
539 this.newchallenge.color = '';
540 this.newchallenge.diag = "";
543 cadenceFocusIfOpened: function() {
544 if (event.target.checked)
545 document.getElementById("cadence").focus();
547 send: function(code, obj) {
548 if (!!this.conn && this.conn.readyState == 1) {
549 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
552 getVname: function(vid) {
553 const variant = this.st.variants.find(v => v.id == vid);
554 // this.st.variants might be uninitialized (variant == null)
555 return variant ? variant.name : "";
557 filterChallenges: function(type) {
558 return this.challenges.filter(c => c.type == type);
560 filterGames: function(type) {
561 return this.games.filter(g => g.type == type);
563 // o: challenge or game
564 classifyObject: function(o) {
565 // No imported games here
567 o.cadence.indexOf("d") >= 0
569 : (o.cadence.indexOf("/") >= 0 ? "simul" : "live")
572 setDisplay: function(letter, type, e) {
573 this[letter + "display"] = type;
574 localStorage.setItem(
575 "type-" + (letter == "c" ? "challenges" : "games"),
580 : document.getElementById("btn" + letter.toUpperCase() + type);
581 elt.classList.add("active");
582 elt.classList.remove("somethingnew"); //in case of
583 if (!!elt.previousElementSibling)
584 elt.previousElementSibling.classList.remove("active");
585 else elt.nextElementSibling.classList.remove("active");
587 isGamer: function(sid) {
588 return Object.values(this.people[sid].tmpIds)
589 .some(v => v.focus && v.page.indexOf("/game/") >= 0);
591 isFocusedOnHall: function(sid) {
593 // This is meant to challenge people, thus the next 2 conditions:
594 this.st.user.id > 0 &&
595 sid != this.st.user.sid &&
596 Object.values(this.people[sid].tmpIds)
597 .some(v => v.focus && v.page == "/")
600 challenge: function(sid) {
601 this.partialResetNewchallenge();
602 // Available, in Hall
603 this.newchallenge.to = this.people[sid].name;
604 // TODO: also store target sid to not re-search for it
605 document.getElementById("modalPeople").checked = false;
606 window.doClick("modalNewgame");
608 watchGame: function(sid) {
609 // In some game, maybe playing maybe not: show a random one
611 Object.values(this.people[sid].tmpIds).forEach(v => {
613 const matchGid = v.page.match(/[a-zA-Z0-9]+$/);
614 if (!!matchGid) gids.push(matchGid[0]);
617 const gid = gids[Math.floor(Math.random() * gids.length)];
618 window.open("/#/game/" + gid, "_blank");
620 showGame: function(g) {
621 // NOTE: we are an observer, since only games I don't play are shown here
622 // ==> Moves sent by connected remote player(s) if live game
623 window.open("/#/game/" + g.id, "_blank");
625 toggleSocialColor: function(action) {
626 if (!action && document.getElementById("modalPeople").checked)
627 document.getElementById("inputChat").focus();
629 document.getElementById("peopleBtn").classList.remove("somethingnew");
631 processChat: function(chat) {
632 this.send("newchat", { data: chat });
634 getOppsid: function(c) {
635 let oppsid = c.from.sid; //may not be defined if corr + offline opp
637 oppsid = Object.keys(this.people).find(
638 sid => this.people[sid].id == c.from.id
644 socketMessageListener: function(msg) {
645 if (!this.conn) return;
646 const data = JSON.parse(msg.data);
648 case "pollclientsandgamers": {
649 // TODO: shuffling and random filtering on server,
650 // if the room is really crowded.
651 Object.keys(data.sockIds).forEach(sid => {
652 if (sid != this.st.user.sid) {
653 // Pick a target tmpId (+page) at random:
654 const pt = Object.values(data.sockIds[sid]);
655 const randPage = pt[randInt(pt.length)].page;
664 if (!this.people[sid])
665 // Do not set name or id: identity unknown yet
666 this.people[sid] = { tmpIds: data.sockIds[sid] };
668 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
669 if (Object.values(data.sockIds[sid]).some(v => v.page == "/"))
671 this.send("askchallenges", { target: sid });
672 Object.values(data.sockIds[sid]).forEach(v => {
674 v.page.indexOf("/game/") >= 0 &&
675 !v.page.match(/\/[0-9]+$/)
677 // Peer is in Game: ask only if live game
678 this.send("askgame", { target: sid, page: v.page });
686 const page = data.page || "/";
687 if (data.code == "connect") {
688 // Ask challenges only on first connexion:
689 if (!this.people[data.from[0]])
690 this.send("askchallenges", { target: data.from[0] });
692 // Ask game only if live:
693 else if (!page.match(/\/[0-9]+$/))
694 this.send("askgame", { target: data.from[0], page: page });
695 if (!this.people[data.from[0]]) {
701 [data.from[1]]: { page: page, focus: true }
705 // For self multi-connects tests:
706 this.newConnect[data.from[0]] = true;
707 this.send("askidentity", { target: data.from[0], page: page });
709 this.people[data.from[0]].tmpIds[data.from[1]] =
710 { page: page, focus: true };
711 this.$forceUpdate(); //TODO: shouldn't be required
716 case "gdisconnect": {
717 // If the user reloads the page twice very quickly
718 // (experienced with Firefox), the first reload won't have time to
719 // connect but will trigger a "close" event anyway.
720 // ==> Next check is required.
721 if (!this.people[data.from[0]]) return;
722 delete this.people[data.from[0]].tmpIds[data.from[1]];
723 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
724 this.$delete(this.people, data.from[0]);
725 else this.$forceUpdate(); //TODO: shouldn't be required
726 if (data.code == "disconnect") {
727 // Remove the live challenges sent by this player, if
728 // he isn't connected on another tab:
730 !this.people[data.from[0]] ||
731 Object.values(this.people[data.from[0]].tmpIds)
732 .every(v => v.page != "/")
736 c => c.type == "live" && c.from.sid == data.from[0],
741 // Remove the matching live game if now unreachable
742 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
743 // Corr games are always reachable:
744 if (!gid.match(/^[0-9]+$/)) {
745 // Live games are reachable if someone is on the game page
746 if (Object.values(this.people).every(p =>
747 Object.values(p.tmpIds).every(v => v.page != data.page))
749 ArrayFun.remove(this.games, g => g.id == gid);
756 let player = this.people[data.from[0]];
757 // If user reload a page, focus may arrive earlier than connect
759 player.tmpIds[data.from[1]].focus = true;
760 this.$forceUpdate(); //TODO: shouldn't be required
765 let player = this.people[data.from[0]];
767 player.tmpIds[data.from[1]].focus = false;
768 this.$forceUpdate(); //TODO: shouldn't be required
772 case "askidentity": {
773 // Request for identification
775 // Decompose to avoid revealing email
776 name: this.st.user.name,
777 sid: this.st.user.sid,
780 this.send("identity", { data: me, target: data.from });
784 const user = data.data;
785 let player = this.people[user.sid];
786 // player.tmpIds is already set
788 player.name = user.name;
789 // TODO: this.$set(people, ...) fails. So forceUpdate.
790 // But this shouldn't be like that!
792 // If I multi-connect, kill current connexion if no mark (I'm older)
793 if (this.newConnect[user.sid]) {
794 delete this.newConnect[user.sid];
797 user.id == this.st.user.id &&
798 user.sid != this.st.user.sid
800 // I logged in elsewhere:
801 this.cleanBeforeDestroy();
802 alert(this.st.tr["New connexion detected: tab now offline"]);
807 case "askchallenges": {
808 // Send my current live challenges (if any)
809 const myChallenges = this.challenges
811 c.from.sid == this.st.user.sid && c.type == "live"
814 // NOTE: in principle, should only send targeted challenge to the
815 // target. But we may not know yet the identity of the target
816 // (just name), so can't decide if data.from is the target.
819 from: this.st.user.sid,
821 randomness: c.randomness,
828 if (myChallenges.length > 0)
829 this.send("challenges", { data: myChallenges, target: data.from });
832 case "challenges": //after "askchallenges"
833 data.data.forEach(this.addChallenge);
836 this.addChallenge(data.data);
838 case "refusechallenge": {
839 const cid = data.data;
840 ArrayFun.remove(this.challenges, c => c.id == cid);
841 alert(this.st.tr["Challenge declined"]);
844 case "deletechallenge_s": {
845 // NOTE: the challenge(s) may be already removed
846 const cref = data.data;
848 ArrayFun.remove(this.challenges, c => c.id == cref.cid);
849 else if (!!cref.sids) {
850 cref.sids.forEach(s => {
853 c => c.type == "live" && c.from.sid == s,
860 case "game": // Individual request
862 const game = data.data;
863 // Ignore games where I play (will go in MyGames page),
864 // and also games that I already received.
866 this.games.findIndex(g => g.id == game.id) == -1 &&
867 game.players.every(p => {
869 p.sid != this.st.user.sid &&
870 (p.id == 0 || p.id != this.st.user.id)
875 newGame.type = this.classifyObject(game);
876 newGame.vname = this.getVname(game.vid);
878 // New game from Hall
880 this.games.push(newGame);
882 newGame.score == '*' &&
883 (newGame.type == "live" && this.gdisplay == "corr") ||
884 (newGame.type == "corr" && this.gdisplay == "live")
887 .getElementById("btnG" + newGame.type)
888 .classList.add("somethingnew");
894 let g = this.games.find(g => g.id == data.gid);
895 if (!!g) g.score = data.score;
899 // New game just started, I'm involved
900 const gameInfo = data.data;
901 if (this.classifyObject(gameInfo) == "live")
902 this.startNewGame(gameInfo);
905 this.st.tr["New correspondence game:"] + " " +
906 "<a href='#/game/" + gameInfo.id + "'>" +
907 "#/game/" + gameInfo.id + "</a>";
908 document.getElementById("modalInfo").checked = true;
913 this.$refs["chatcomp"].newChat(data.data);
914 if (!document.getElementById("modalPeople").checked)
915 document.getElementById("peopleBtn").classList.add("somethingnew");
919 loadMoreCorr: function() {
925 uid: this.st.user.id,
929 const L = res.games.length;
932 this.cursor == Number.MAX_SAFE_INTEGER &&
933 this.games.length == 0 &&
934 this.gdisplay == "live" &&
935 res.games.some(g => g.score == '*')
937 // First loading: show indicators
939 .getElementById("btnGcorr")
940 .classList.add("somethingnew");
942 this.cursor = res.games[L - 1].created;
943 let moreGames = res.games.map(g => {
944 const vname = this.getVname(g.vid);
945 return Object.assign(
954 this.games = this.games.concat(moreGames);
955 } else this.hasMore = false;
960 // Challenge lifecycle:
961 addChallenge: function(chall) {
962 // NOTE about next condition: see "askchallenges" case.
965 (this.people[chall.from].id > 0 &&
966 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
968 let newChall = Object.assign({}, chall);
969 newChall.type = this.classifyObject(chall);
970 newChall.randomness = chall.randomness;
971 newChall.added = Date.now();
972 let fromValues = Object.assign({}, this.people[chall.from]);
973 delete fromValues["pages"]; //irrelevant in this context
974 newChall.from = Object.assign({ sid: chall.from }, fromValues);
975 newChall.vname = this.getVname(newChall.vid);
976 this.challenges.push(newChall);
978 (newChall.type == "live" && this.cdisplay == "corr") ||
979 (newChall.type == "corr" && this.cdisplay == "live")
982 .getElementById("btnC" + newChall.type)
983 .classList.add("somethingnew");
988 // fromValues.name should exist since the player is online, but
989 // let's consider there is some chance that the challenge arrives
990 // right after we connected and before receiving the poll result:
991 { body: "from " + (fromValues.name || "unknown yet...") }
996 loadNewchallVariant: async function(cb, vname) {
997 vname = vname || this.getVname(this.newchallenge.vid);
998 await import("@/variants/" + vname + ".js")
1000 window.V = vModule[vname + "Rules"];
1001 this.newchallenge.V = window.V;
1002 this.newchallenge.vname = vname;
1006 trySetNewchallDiag: function() {
1007 if (!this.newchallenge.fen) {
1008 this.newchallenge.diag = "";
1011 // If vid > 0 then the variant is loaded (function above):
1012 window.V = this.newchallenge.V;
1014 this.newchallenge.vid > 0 &&
1015 !!this.newchallenge.fen &&
1016 V.IsGoodFen(this.newchallenge.fen)
1018 const parsedFen = V.ParseFen(this.newchallenge.fen);
1019 this.newchallenge.diag = getDiagram({
1020 position: parsedFen.position
1021 //,orientation: parsedFen.turn
1023 } else this.newchallenge.diag = "";
1025 newChallFromPreset(pchall) {
1026 this.partialResetNewchallenge();
1027 this.newchallenge.vid = pchall.vid;
1028 this.newchallenge.cadence = pchall.cadence;
1029 this.newchallenge.randomness = pchall.randomness;
1030 this.loadNewchallVariant(this.issueNewChallenge);
1032 issueNewChallenge: async function() {
1033 if (!!(this.newchallenge.cadence.match(/^[0-9]+$/)))
1034 this.newchallenge.cadence += "+0"; //assume minutes, no increment
1035 const ctype = this.classifyObject(this.newchallenge);
1036 // TODO: cadence still unchecked so ctype could be wrong...
1038 if (!this.newchallenge.vid)
1039 error = this.st.tr["Please select a variant"];
1040 else if (ctype == "corr" && this.st.user.id <= 0)
1041 error = this.st.tr["Please log in to play correspondence games"];
1042 else if (!this.newchallenge.to && !!this.newchallenge.color)
1043 error = this.st.tr["Color option only for targeted challenge"];
1044 else if (!!this.newchallenge.to) {
1045 if (this.newchallenge.to == this.st.user.name)
1046 error = this.st.tr["Self-challenge is forbidden"];
1049 Object.values(this.people).every(p => p.name != this.newchallenge.to)
1051 error = this.newchallenge.to + " " + this.st.tr["is not online"];
1054 !!this.newchallenge.color &&
1055 !['w', 'b'].includes(this.newchallenge.color)
1057 error = this.st.tr["Wrong color"];
1064 window.V = this.newchallenge.V;
1065 error = checkChallenge(this.newchallenge);
1070 // NOTE: "from" information is not required here
1071 let chall = Object.assign({}, this.newchallenge);
1072 // Add only if not already issued (not counting FEN):
1073 if (this.challenges.some(c =>
1075 c.from.sid == this.st.user.sid ||
1076 (c.from.id > 0 && c.from.id == this.st.user.id)
1080 (!c.to && !chall.to) ||
1084 c.vid == chall.vid &&
1085 c.cadence == chall.cadence &&
1086 c.randomness == chall.randomness
1088 alert(this.st.tr["Challenge already exists"]);
1091 if (this.newchallenge.memorize) this.addPresetChall(this.newchallenge);
1093 delete chall["diag"];
1094 const finishAddChallenge = cid => {
1095 chall.id = cid || "c" + getRandString();
1096 const MAX_ALLOWED_CHALLS = 3;
1097 // Remove oldest challenge if 3 found: only 3 at a time of a given type
1098 let countMyChalls = 0;
1099 let challToDelIdx = 0;
1100 let oldestAdded = Number.MAX_SAFE_INTEGER;
1101 for (let i=0; i<this.challenges.length; i++) {
1102 const c = this.challenges[i];
1106 c.from.sid == this.st.user.sid ||
1107 (c.from.id > 0 && c.from.id == this.st.user.id)
1111 if (c.added < oldestAdded) {
1113 oldestAdded = c.added;
1117 if (countMyChalls >= MAX_ALLOWED_CHALLS) {
1119 "deletechallenge_s",
1120 { data: { cid: this.challenges[challToDelIdx].id } }
1122 if (ctype == "corr") {
1126 { data: { id: this.challenges[challToDelIdx].id } }
1129 this.challenges.splice(challToDelIdx, 1);
1131 this.send("newchallenge", {
1132 data: Object.assign({ from: this.st.user.sid }, chall)
1134 // Add new challenge:
1136 sid: this.st.user.sid,
1137 id: this.st.user.id,
1138 name: this.st.user.name
1140 chall.added = Date.now();
1141 // NOTE: vname and type are redundant (deduced from cadence + vid)
1143 chall.vname = this.newchallenge.vname;
1144 this.challenges.push(chall);
1145 // Remember cadence + vid for quicker further challenges:
1146 localStorage.setItem("cadence", chall.cadence);
1147 localStorage.setItem("vid", chall.vid);
1148 localStorage.setItem("challRandomness", chall.randomness);
1149 document.getElementById("modalNewgame").checked = false;
1150 // Show the challenge if not on current display
1152 (ctype == "live" && this.cdisplay == "corr") ||
1153 (ctype == "corr" && this.cdisplay == "live")
1155 this.setDisplay('c', ctype);
1158 if (ctype == "live") {
1159 // Live challenges have a random ID
1160 finishAddChallenge(null);
1162 // Correspondence game: send challenge to server
1167 data: { chall: chall },
1168 success: (response) => {
1169 finishAddChallenge(response.id);
1175 // Callback function after a diagram was showed to accept
1176 // or refuse targetted challenge:
1177 decisionChallenge: function(accepted) {
1178 this.curChallToAccept.accepted = accepted;
1179 this.finishProcessingChallenge(this.curChallToAccept);
1180 document.getElementById("modalAccept").checked = false;
1182 finishProcessingChallenge: function(c) {
1185 sid: this.st.user.sid,
1186 id: this.st.user.id,
1187 name: this.st.user.name
1190 if (c.type == "live") {
1191 // Remove all live challenges of both players
1193 "deletechallenge_s",
1194 { data: { sids: [c.from.sid, c.seat.sid] } }
1198 // Corr challenge: just remove the challenge
1199 this.send("deletechallenge_s", { data: { cid: c.id } });
1201 const oppsid = this.getOppsid(c);
1203 this.send("refusechallenge", { data: c.id, target: oppsid });
1204 if (c.type == "corr") {
1208 { data: { id: c.id } }
1211 this.send("deletechallenge_s", { data: { cid: c.id } });
1214 // TODO: if several players click same challenge at the same time: problem
1215 clickChallenge: async function(c) {
1217 c.from.sid == this.st.user.sid || //live
1218 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
1220 if (c.type == "corr" && this.st.user.id <= 0) {
1221 alert(this.st.tr["Please log in to accept corr challenges"]);
1225 await import("@/variants/" + c.vname + ".js")
1226 .then((vModule) => {
1227 window.V = vModule[c.vname + "Rules"];
1229 // c.to == this.st.user.name (connected)
1231 const parsedFen = V.ParseFen(c.fen);
1232 this.tchallDiag = getDiagram({
1233 position: parsedFen.position,
1234 orientation: parsedFen.turn
1237 this.curChallToAccept = c;
1238 document.getElementById("modalAccept").checked = true;
1240 else this.finishProcessingChallenge(c);
1245 if (c.type == "corr") {
1249 { data: { id: c.id } }
1252 this.send("deletechallenge_s", { data: { cid: c.id } });
1254 // In all cases, the challenge is consumed:
1255 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
1257 // NOTE: when launching game, the challenge is already being deleted
1258 launchGame: function(c) {
1259 // White player index 0, black player index 1:
1262 ? (c.color == "w" ? [c.from, c.seat] : [c.seat, c.from])
1263 : shuffle([c.from, c.seat]);
1264 players.forEach(p => {
1265 if (!!p["tmpIds"]) delete p["tmpIds"];
1267 // These game informations will be shared
1269 id: getRandString(),
1270 fen: c.fen || V.GenRandInitFen(c.randomness),
1271 randomness: c.randomness, //for rematch
1276 const notifyNewgame = () => {
1277 const oppsid = this.getOppsid(c);
1279 // Opponent is online
1280 this.send("startgame", { data: gameInfo, target: oppsid });
1281 // If new corr game, notify Hall (except opponent and me)
1282 if (c.type == "corr") {
1287 excluded: [this.st.user.sid, oppsid]
1291 // Notify MyGames page:
1296 targets: gameInfo.players
1299 // NOTE: no need to send the game to the room, since I'll connect
1300 // on game just after, the main Hall will be notified.
1302 if (c.type == "live") {
1304 this.startNewGame(gameInfo);
1306 // corr: game only on server
1311 // cid is useful to delete the challenge:
1316 success: (response) => {
1317 gameInfo.id = response.id;
1319 this.$router.push("/game/" + response.id);
1325 // NOTE: for live games only (corr games start on the server)
1326 startNewGame: function(gameInfo) {
1327 const game = Object.assign(
1331 // (other) Game infos: constant
1332 fenStart: gameInfo.fen,
1333 vname: this.getVname(gameInfo.vid),
1334 created: Date.now(),
1335 // Game state (including FEN): will be updated
1337 clocks: [-1, -1], //-1 = unstarted
1344 const myIdx = (game.players[0].sid == this.st.user.sid ? 0 : 1);
1345 GameStorage.add(game, (err) => {
1346 // If an error occurred, game is not added: the focused tab
1347 // already added the game.
1349 if (this.st.settings.sound)
1350 // This will be played several times if several hidden tabs
1351 // on Hall... TODO: fix that (how ?!)
1352 new Audio("/sounds/newgame.flac").play().catch(() => {});
1355 { body: "vs " + game.players[1-myIdx].name || "@nonymous" }
1358 this.$router.push("/game/" + gameInfo.id);
1361 this.focus ? 0 : 500 + 1000 * Math.random()
1368 <style lang="sass" scoped>
1376 #newgameDiv > .card, #acceptDiv > .card
1380 div#peopleWrap > .card
1383 @media screen and (min-width: 1281px)
1384 div#peopleWrap > .card
1387 @media screen and (max-width: 1280px)
1388 div#peopleWrap > .card
1391 @media screen and (max-width: 767px)
1392 div#peopleWrap > .card
1405 @media screen and (max-width: 767px)
1420 button.player-action
1423 background-color: #E6D271
1426 background-color: #90C4EC !important
1429 background-color: #f9faee
1432 background-color: lightgreen
1434 background-color: red
1437 // margin-top set dynamically (depends if diagram showed or not)
1448 // width: 100% required for Firefox
1456 @media screen and (max-width: 767px)
1465 background-color: #FF5733
1467 background-color: #2B63B4
1469 background-color: #33B42B
1471 @media screen and (max-width: 767px)
1480 background-color: lightgrey