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="isFocusedOnHall(sid)"
132 @click="challenge(sid)"
134 | {{ st.tr["Challenge"] }}
135 p.anonymous @nonymous ({{ anonymousCount() }})
139 @mychat="processChat"
144 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
146 button#peopleBtn(onClick="window.doClick('modalPeople')")
147 | {{ st.tr["Who's there?"] }}
148 button(@click="showNewchallengeForm()")
149 | {{ st.tr["New game"] }}
150 .row(v-if="presetChalls.length > 0")
151 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
152 h4.text-center {{ st.tr["Preset challenges"] }}
156 th {{ st.tr["Variant"] }}
157 th {{ st.tr["Cadence"] }}
158 th {{ st.tr["Random?"] }}
162 v-for="pc in presetChalls"
163 @click="newChallFromPreset(pc)"
167 td(:class="getRandomnessClass(pc)")
168 td.remove-preset(@click="removePresetChall($event, pc)")
169 img(src="/images/icons/delete.svg")
171 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
174 button.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
175 | {{ st.tr["Live challenges"] }}
176 button.tabbtn#btnCcorr(@click="setDisplay('c','corr',$event)")
177 | {{ st.tr["Correspondence challenges"] }}
179 v-show="cdisplay=='live'"
180 :challenges="filterChallenges('live')"
181 @click-challenge="clickChallenge"
184 v-show="cdisplay=='corr'"
185 :challenges="filterChallenges('corr')"
186 @click-challenge="clickChallenge"
190 button.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
191 | {{ st.tr["Live games"] }}
192 button.tabbtn#btnGcorr(@click="setDisplay('g','corr',$event)")
193 | {{ st.tr["Correspondence games"] }}
195 v-show="gdisplay=='live'"
196 :games="filterGames('live')"
198 @show-game="showGame"
200 div(v-show="gdisplay=='corr'")
202 :games="filterGames('corr')"
204 @show-game="showGame"
208 @click="loadMoreCorr()"
210 | {{ st.tr["Load more"] }}
214 import { store } from "@/store";
215 import { checkChallenge } from "@/data/challengeCheck";
216 import { notify } from "@/utils/notifications";
217 import { ArrayFun } from "@/utils/array";
218 import { ajax } from "@/utils/ajax";
219 import params from "@/parameters";
220 import { getRandString, shuffle, randInt } from "@/utils/alea";
221 import { getDiagram } from "@/utils/printDiagram";
222 import Chat from "@/components/Chat.vue";
223 import UserBio from "@/components/UserBio.vue";
224 import GameList from "@/components/GameList.vue";
225 import ChallengeList from "@/components/ChallengeList.vue";
226 import { GameStorage } from "@/utils/gameStorage";
227 import { processModalClick } from "@/utils/modalClick";
239 cdisplay: "live", //or corr
241 // timestamp of last showed (oldest) corr game:
242 cursor: Number.MAX_SAFE_INTEGER,
243 // hasMore == TRUE: a priori there could be more games to load
251 vid: parseInt(localStorage.getItem("vid"), 10) || 0,
252 to: "", //name of challenged player (if any)
254 cadence: localStorage.getItem("cadence") || "",
256 // Warning: randomness can be 0, then !!randomness is false
257 (parseInt(localStorage.getItem("challRandomness"),10)+1 || 3) - 1,
258 // VariantRules object, stored to not interfere with
259 // diagrams of targetted challenges:
262 diag: "", //visualizing FEN
263 memorize: false //put settings in localStorage
267 curChallToAccept: { from: {} },
268 presetChalls: JSON.parse(localStorage.getItem("presetChalls") || "[]"),
271 socketCloseListener: 0,
272 // Related to (killing of) self multi-connects:
277 // st.variants changes only once, at loading from [] to [...]
278 "st.variants": function() {
279 // Set potential challenges and games variant names:
280 this.challenges.concat(this.games).forEach(o => {
281 if (!o.vname) o.vname = this.getVname(o.vid);
283 if (!this.newchallenge.V && this.newchallenge.vid > 0)
284 this.loadNewchallVariant();
286 $route: function(to, from) {
287 if (to.path != "/") this.cleanBeforeDestroy();
290 created: function() {
291 document.addEventListener('visibilitychange', this.visibilityChange);
292 window.addEventListener('focus', this.onFocus);
293 window.addEventListener('blur', this.onBlur);
294 window.addEventListener("beforeunload", this.cleanBeforeDestroy);
295 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
296 this.loadNewchallVariant();
297 const my = this.st.user;
298 const tmpId = getRandString();
306 tmpId: { page: "/", focus: true }
310 const connectAndPoll = () => {
311 this.send("connect");
312 this.send("pollclientsandgamers");
313 if (!!this.$route.query["challenge"]) {
314 // Automatic challenge sending, for tournaments
315 this.loadNewchallVariant(
317 this.newchallenge = {
321 .find(v => v.name == this.$route.query["variant"])
323 to: this.$route.query["challenge"],
324 color: this.$route.query["color"] || '',
325 cadence: this.$route.query["cadence"],
326 // Tournament: no randomness (TODO: for now at least)
330 this.issueNewChallenge();
332 this.$route.query["variant"]
336 // Initialize connection
337 this.connexionString =
339 "/?sid=" + this.st.user.sid +
340 "&id=" + this.st.user.id +
343 // Hall: path is "/" (TODO: could be hard-coded as well)
344 encodeURIComponent(this.$route.path);
345 this.conn = new WebSocket(this.connexionString);
346 this.conn.onopen = connectAndPoll;
347 this.conn.addEventListener("message", this.socketMessageListener);
348 this.socketCloseListener = setInterval(
350 if (this.conn.readyState == 3) {
351 this.conn.removeEventListener("message", this.socketMessageListener);
352 this.conn = new WebSocket(this.connexionString);
353 this.conn.addEventListener("message", this.socketMessageListener);
359 mounted: function() {
360 document.getElementById("peopleWrap")
361 .addEventListener("click", (e) => {
362 processModalClick(e, () => {
363 this.toggleSocialColor("close")
366 ["infoDiv", "newgameDiv"].forEach(eltName => {
367 document.getElementById(eltName)
368 .addEventListener("click", processModalClick);
370 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
371 b.addEventListener("click", () => {
372 this.newchallenge.cadence = b.innerHTML;
375 const dispCorr = this.$route.query["disp"];
377 dispCorr || localStorage.getItem("type-challenges") || "live";
379 dispCorr || localStorage.getItem("type-games") || "live";
380 this.setDisplay('c', showCtype);
381 this.setDisplay('g', showGtype);
382 // Ask server for current corr games (all but mines)
384 // Also ask for corr challenges (open + sent by/to me)
385 // List them all, because they are not supposed to be that many (TODO?)
390 data: { uid: this.st.user.id },
391 success: (response) => {
393 response.challenges.length > 0 &&
394 this.challenges.length == 0 &&
395 this.cdisplay == "live"
398 .getElementById("btnCcorr")
399 .classList.add("somethingnew");
401 // Gather all senders names, and then retrieve full identity:
402 // (TODO [perf]: some might be online...)
404 response.challenges.forEach(c => {
405 if (c.uid != this.st.user.id) names[c.uid] = "";
406 else if (!!c.target && c.target != this.st.user.id)
407 names[c.target] = "";
409 const addChallenges = () => {
410 names[this.st.user.id] = this.st.user.name; //in case of
411 this.challenges = this.challenges.concat(
412 response.challenges.map(c => {
413 const from = { name: names[c.uid], id: c.uid }; //or just name
414 const type = this.classifyObject(c);
415 const vname = this.getVname(c.vid);
416 return Object.assign(
422 to: c.target ? names[c.target] : ""
429 if (Object.keys(names).length > 0) {
434 data: { ids: Object.keys(names).join(",") },
435 success: (response2) => {
436 response2.users.forEach(u => {
437 names[u.id] = u.name;
443 } else addChallenges();
448 beforeDestroy: function() {
449 this.cleanBeforeDestroy();
452 cleanBeforeDestroy: function() {
453 clearInterval(this.socketCloseListener);
454 document.removeEventListener('visibilitychange', this.visibilityChange);
455 window.removeEventListener('focus', this.onFocus);
456 window.removeEventListener('blur', this.onBlur);
457 window.removeEventListener("beforeunload", this.cleanBeforeDestroy);
458 this.conn.removeEventListener("message", this.socketMessageListener);
459 this.send("disconnect");
462 getRandomnessClass: function(pc) {
464 ["random-" + pc.randomness]: true
467 anonymousCount: function() {
469 Object.values(this.people).forEach(p => {
470 // Do not cound people who did not send their identity yet:
471 count += (!p.name && p.id === 0) ? 1 : 0;
475 visibilityChange: function() {
476 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
477 this.focus = (document.visibilityState == "visible");
478 this.send(this.focus ? "getfocus" : "losefocus");
480 onFocus: function() {
482 this.send("getfocus");
486 this.send("losefocus");
488 invColor: function(c) {
489 if (c == 'w') return this.st.tr["Black"];
490 return this.tr.tr["White"];
492 partialResetNewchallenge: function() {
493 // Reset potential target and custom FEN:
494 this.newchallenge.to = "";
495 this.newchallenge.color = '';
496 this.newchallenge.fen = "";
497 this.newchallenge.diag = "";
498 this.newchallenge.memorize = false;
500 showNewchallengeForm: function() {
501 this.partialResetNewchallenge();
502 window.doClick("modalNewgame");
504 addPresetChall: function(chall) {
505 // Add only if not already existing:
506 if (this.presetChalls.some(c =>
507 c.vid == chall.vid &&
508 c.cadence == chall.cadence &&
509 c.randomness == chall.randomness
513 const L = this.presetChalls.length;
514 this.presetChalls.push({
517 vname: chall.vname, //redundant, but easier
518 cadence: chall.cadence,
519 randomness: chall.randomness
521 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
523 removePresetChall: function(e, pchall) {
526 this.presetChalls.findIndex(pc => pc.index == pchall.index);
527 this.presetChalls.splice(pchallIdx, 1);
528 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
530 tchallButtonsMargin: function() {
531 if (!!this.curChallToAccept.fen) return { "margin-top": "10px" };
534 changeChallTarget: function() {
535 if (!this.newchallenge.to) {
536 // Reset potential FEN + diagram
537 this.newchallenge.fen = "";
538 this.newchallenge.color = '';
539 this.newchallenge.diag = "";
542 cadenceFocusIfOpened: function() {
543 if (event.target.checked)
544 document.getElementById("cadence").focus();
546 send: function(code, obj) {
547 if (!!this.conn && this.conn.readyState == 1) {
548 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
551 getVname: function(vid) {
552 const variant = this.st.variants.find(v => v.id == vid);
553 // this.st.variants might be uninitialized (variant == null)
554 return variant ? variant.name : "";
556 filterChallenges: function(type) {
557 return this.challenges.filter(c => c.type == type);
559 filterGames: function(type) {
560 return this.games.filter(g => g.type == type);
562 // o: challenge or game
563 classifyObject: function(o) {
564 // Consider imports as live games (TODO)
565 if (!!o.id && !!o.id.toString().match(/^i/)) return "live";
566 return o.cadence.indexOf("d") === -1 ? "live" : "corr";
568 setDisplay: function(letter, type, e) {
569 this[letter + "display"] = type;
570 localStorage.setItem(
571 "type-" + (letter == "c" ? "challenges" : "games"),
576 : document.getElementById("btn" + letter.toUpperCase() + type);
577 elt.classList.add("active");
578 elt.classList.remove("somethingnew"); //in case of
579 if (!!elt.previousElementSibling)
580 elt.previousElementSibling.classList.remove("active");
581 else elt.nextElementSibling.classList.remove("active");
583 isGamer: function(sid) {
584 return Object.values(this.people[sid].tmpIds)
585 .some(v => v.focus && v.page.indexOf("/game/") >= 0);
587 isFocusedOnHall: function(sid) {
589 // This is meant to challenge people, thus the next 2 conditions:
590 this.st.user.id > 0 &&
591 sid != this.st.user.sid &&
592 Object.values(this.people[sid].tmpIds)
593 .some(v => v.focus && v.page == "/")
596 challenge: function(sid) {
597 this.partialResetNewchallenge();
598 // Available, in Hall
599 this.newchallenge.to = this.people[sid].name;
600 // TODO: also store target sid to not re-search for it
601 document.getElementById("modalPeople").checked = false;
602 window.doClick("modalNewgame");
604 watchGame: function(sid) {
605 // In some game, maybe playing maybe not: show a random one
607 Object.values(this.people[sid].tmpIds).forEach(v => {
609 const matchGid = v.page.match(/[a-zA-Z0-9]+$/);
610 if (!!matchGid) gids.push(matchGid[0]);
613 const gid = gids[Math.floor(Math.random() * gids.length)];
614 window.open("/#/game/" + gid, "_blank");
616 showGame: function(g) {
617 // NOTE: we are an observer, since only games I don't play are shown here
618 // ==> Moves sent by connected remote player(s) if live game
619 window.open("/#/game/" + g.id, "_blank");
621 toggleSocialColor: function(action) {
622 if (!action && document.getElementById("modalPeople").checked)
623 document.getElementById("inputChat").focus();
625 document.getElementById("peopleBtn").classList.remove("somethingnew");
627 processChat: function(chat) {
628 this.send("newchat", { data: chat });
630 getOppsid: function(c) {
631 let oppsid = c.from.sid; //may not be defined if corr + offline opp
633 oppsid = Object.keys(this.people).find(
634 sid => this.people[sid].id == c.from.id
640 socketMessageListener: function(msg) {
641 if (!this.conn) return;
642 const data = JSON.parse(msg.data);
644 case "pollclientsandgamers": {
645 // TODO: shuffling and random filtering on server,
646 // if the room is really crowded.
647 Object.keys(data.sockIds).forEach(sid => {
648 if (sid != this.st.user.sid) {
649 // Pick a target tmpId (+page) at random:
650 const pt = Object.values(data.sockIds[sid]);
651 const randPage = pt[randInt(pt.length)].page;
660 if (!this.people[sid])
661 // Do not set name or id: identity unknown yet
662 this.people[sid] = { tmpIds: data.sockIds[sid] };
664 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
665 if (Object.values(data.sockIds[sid]).some(v => v.page == "/"))
667 this.send("askchallenges", { target: sid });
668 Object.values(data.sockIds[sid]).forEach(v => {
670 v.page.indexOf("/game/") >= 0 &&
671 !v.page.match(/\/[0-9]+$/)
673 // Peer is in Game: ask only if live game
674 this.send("askgame", { target: sid, page: v.page });
682 const page = data.page || "/";
683 if (data.code == "connect") {
684 // Ask challenges only on first connexion:
685 if (!this.people[data.from[0]])
686 this.send("askchallenges", { target: data.from[0] });
688 // Ask game only if live:
689 else if (!page.match(/\/[0-9]+$/))
690 this.send("askgame", { target: data.from[0], page: page });
691 if (!this.people[data.from[0]]) {
697 [data.from[1]]: { page: page, focus: true }
701 // For self multi-connects tests:
702 this.newConnect[data.from[0]] = true;
703 this.send("askidentity", { target: data.from[0], page: page });
705 this.people[data.from[0]].tmpIds[data.from[1]] =
706 { page: page, focus: true };
707 this.$forceUpdate(); //TODO: shouldn't be required
712 case "gdisconnect": {
713 // If the user reloads the page twice very quickly
714 // (experienced with Firefox), the first reload won't have time to
715 // connect but will trigger a "close" event anyway.
716 // ==> Next check is required.
717 if (!this.people[data.from[0]]) return;
718 delete this.people[data.from[0]].tmpIds[data.from[1]];
719 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
720 this.$delete(this.people, data.from[0]);
721 else this.$forceUpdate(); //TODO: shouldn't be required
722 if (data.code == "disconnect") {
723 // Remove the live challenges sent by this player, if
724 // he isn't connected on another tab:
726 !this.people[data.from[0]] ||
727 Object.values(this.people[data.from[0]].tmpIds)
728 .every(v => v.page != "/")
732 c => c.type == "live" && c.from.sid == data.from[0],
737 // Remove the matching live game if now unreachable
738 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
739 // Corr games are always reachable:
740 if (!gid.match(/^[0-9]+$/)) {
741 // Live games are reachable if someone is on the game page
742 if (Object.values(this.people).every(p =>
743 Object.values(p.tmpIds).every(v => v.page != data.page))
745 ArrayFun.remove(this.games, g => g.id == gid);
752 let player = this.people[data.from[0]];
753 // If user reload a page, focus may arrive earlier than connect
755 player.tmpIds[data.from[1]].focus = true;
756 this.$forceUpdate(); //TODO: shouldn't be required
761 let player = this.people[data.from[0]];
763 player.tmpIds[data.from[1]].focus = false;
764 this.$forceUpdate(); //TODO: shouldn't be required
768 case "askidentity": {
769 // Request for identification
771 // Decompose to avoid revealing email
772 name: this.st.user.name,
773 sid: this.st.user.sid,
776 this.send("identity", { data: me, target: data.from });
780 const user = data.data;
781 let player = this.people[user.sid];
782 // player.tmpIds is already set
784 player.name = user.name;
785 // TODO: this.$set(people, ...) fails. So forceUpdate.
786 // But this shouldn't be like that!
788 // If I multi-connect, kill current connexion if no mark (I'm older)
789 if (this.newConnect[user.sid]) {
790 delete this.newConnect[user.sid];
793 user.id == this.st.user.id &&
794 user.sid != this.st.user.sid
796 // I logged in elsewhere:
797 this.cleanBeforeDestroy();
798 alert(this.st.tr["New connexion detected: tab now offline"]);
803 case "askchallenges": {
804 // Send my current live challenges (if any)
805 const myChallenges = this.challenges
807 c.from.sid == this.st.user.sid && c.type == "live"
810 // NOTE: in principle, should only send targeted challenge to the
811 // target. But we may not know yet the identity of the target
812 // (just name), so can't decide if data.from is the target.
815 from: this.st.user.sid,
817 randomness: c.randomness,
824 if (myChallenges.length > 0)
825 this.send("challenges", { data: myChallenges, target: data.from });
828 case "challenges": //after "askchallenges"
829 data.data.forEach(this.addChallenge);
832 this.addChallenge(data.data);
834 case "refusechallenge": {
835 const cid = data.data;
836 ArrayFun.remove(this.challenges, c => c.id == cid);
837 alert(this.st.tr["Challenge declined"]);
840 case "deletechallenge_s": {
841 // NOTE: the challenge(s) may be already removed
842 const cref = data.data;
844 ArrayFun.remove(this.challenges, c => c.id == cref.cid);
845 else if (!!cref.sids) {
846 cref.sids.forEach(s => {
849 c => c.type == "live" && c.from.sid == s,
856 case "game": // Individual request
858 const game = data.data;
859 // Ignore games where I play (will go in MyGames page),
860 // and also games that I already received.
862 this.games.findIndex(g => g.id == game.id) == -1 &&
863 game.players.every(p => {
865 p.sid != this.st.user.sid &&
866 (p.id == 0 || p.id != this.st.user.id)
871 newGame.type = this.classifyObject(game);
872 newGame.vname = this.getVname(game.vid);
874 // New game from Hall
876 this.games.push(newGame);
878 newGame.score == '*' &&
879 (newGame.type == "live" && this.gdisplay == "corr") ||
880 (newGame.type == "corr" && this.gdisplay == "live")
883 .getElementById("btnG" + newGame.type)
884 .classList.add("somethingnew");
890 let g = this.games.find(g => g.id == data.gid);
891 if (!!g) g.score = data.score;
895 // New game just started, I'm involved
896 const gameInfo = data.data;
897 if (this.classifyObject(gameInfo) == "live")
898 this.startNewGame(gameInfo);
901 this.st.tr["New correspondence game:"] + " " +
902 "<a href='#/game/" + gameInfo.id + "'>" +
903 "#/game/" + gameInfo.id + "</a>";
904 document.getElementById("modalInfo").checked = true;
909 this.$refs["chatcomp"].newChat(data.data);
910 if (!document.getElementById("modalPeople").checked)
911 document.getElementById("peopleBtn").classList.add("somethingnew");
915 loadMoreCorr: function() {
921 uid: this.st.user.id,
925 const L = res.games.length;
928 this.cursor == Number.MAX_SAFE_INTEGER &&
929 this.games.length == 0 &&
930 this.gdisplay == "live" &&
931 res.games.some(g => g.score == '*')
933 // First loading: show indicators
935 .getElementById("btnGcorr")
936 .classList.add("somethingnew");
938 this.cursor = res.games[L - 1].created;
939 let moreGames = res.games.map(g => {
940 const vname = this.getVname(g.vid);
941 return Object.assign(
950 this.games = this.games.concat(moreGames);
951 } else this.hasMore = false;
956 // Challenge lifecycle:
957 addChallenge: function(chall) {
958 // NOTE about next condition: see "askchallenges" case.
961 (this.people[chall.from].id > 0 &&
962 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
964 let newChall = Object.assign({}, chall);
965 newChall.type = this.classifyObject(chall);
966 newChall.randomness = chall.randomness;
967 newChall.added = Date.now();
968 let fromValues = Object.assign({}, this.people[chall.from]);
969 delete fromValues["pages"]; //irrelevant in this context
970 newChall.from = Object.assign({ sid: chall.from }, fromValues);
971 newChall.vname = this.getVname(newChall.vid);
972 this.challenges.push(newChall);
974 (newChall.type == "live" && this.cdisplay == "corr") ||
975 (newChall.type == "corr" && this.cdisplay == "live")
978 .getElementById("btnC" + newChall.type)
979 .classList.add("somethingnew");
984 // fromValues.name should exist since the player is online, but
985 // let's consider there is some chance that the challenge arrives
986 // right after we connected and before receiving the poll result:
987 { body: "from " + (fromValues.name || "unknown yet...") }
992 loadNewchallVariant: async function(cb, vname) {
993 vname = vname || this.getVname(this.newchallenge.vid);
994 await import("@/variants/" + vname + ".js")
996 window.V = vModule[vname + "Rules"];
997 this.newchallenge.V = window.V;
998 this.newchallenge.vname = vname;
1002 trySetNewchallDiag: function() {
1003 if (!this.newchallenge.fen) {
1004 this.newchallenge.diag = "";
1007 // If vid > 0 then the variant is loaded (function above):
1008 window.V = this.newchallenge.V;
1010 this.newchallenge.vid > 0 &&
1011 !!this.newchallenge.fen &&
1012 V.IsGoodFen(this.newchallenge.fen)
1014 const parsedFen = V.ParseFen(this.newchallenge.fen);
1015 this.newchallenge.diag = getDiagram({
1016 position: parsedFen.position
1017 //,orientation: parsedFen.turn
1019 } else this.newchallenge.diag = "";
1021 newChallFromPreset(pchall) {
1022 this.partialResetNewchallenge();
1023 this.newchallenge.vid = pchall.vid;
1024 this.newchallenge.cadence = pchall.cadence;
1025 this.newchallenge.randomness = pchall.randomness;
1026 this.loadNewchallVariant(this.issueNewChallenge);
1028 issueNewChallenge: async function() {
1029 if (!!(this.newchallenge.cadence.match(/^[0-9]+$/)))
1030 this.newchallenge.cadence += "+0"; //assume minutes, no increment
1031 const ctype = this.classifyObject(this.newchallenge);
1032 // TODO: cadence still unchecked so ctype could be wrong...
1034 if (!this.newchallenge.vid)
1035 error = this.st.tr["Please select a variant"];
1036 else if (ctype == "corr" && this.st.user.id <= 0)
1037 error = this.st.tr["Please log in to play correspondence games"];
1038 else if (!this.newchallenge.to && !!this.newchallenge.color)
1039 error = this.st.tr["Color option only for targeted challenge"];
1040 else if (!!this.newchallenge.to) {
1041 if (this.newchallenge.to == this.st.user.name)
1042 error = this.st.tr["Self-challenge is forbidden"];
1045 Object.values(this.people).every(p => p.name != this.newchallenge.to)
1047 error = this.newchallenge.to + " " + this.st.tr["is not online"];
1050 !!this.newchallenge.color &&
1051 !['w', 'b'].includes(this.newchallenge.color)
1053 error = this.st.tr["Wrong color"];
1060 window.V = this.newchallenge.V;
1061 error = checkChallenge(this.newchallenge);
1066 // NOTE: "from" information is not required here
1067 let chall = Object.assign({}, this.newchallenge);
1068 // Add only if not already issued (not counting FEN):
1069 if (this.challenges.some(c =>
1071 c.from.sid == this.st.user.sid ||
1072 (c.from.id > 0 && c.from.id == this.st.user.id)
1076 (!c.to && !chall.to) ||
1080 c.vid == chall.vid &&
1081 c.cadence == chall.cadence &&
1082 c.randomness == chall.randomness
1084 alert(this.st.tr["Challenge already exists"]);
1087 if (this.newchallenge.memorize) this.addPresetChall(this.newchallenge);
1089 delete chall["diag"];
1090 const finishAddChallenge = cid => {
1091 chall.id = cid || "c" + getRandString();
1092 const MAX_ALLOWED_CHALLS = 3;
1093 // Remove oldest challenge if 3 found: only 3 at a time of a given type
1094 let countMyChalls = 0;
1095 let challToDelIdx = 0;
1096 let oldestAdded = Number.MAX_SAFE_INTEGER;
1097 for (let i=0; i<this.challenges.length; i++) {
1098 const c = this.challenges[i];
1102 c.from.sid == this.st.user.sid ||
1103 (c.from.id > 0 && c.from.id == this.st.user.id)
1107 if (c.added < oldestAdded) {
1109 oldestAdded = c.added;
1113 if (countMyChalls >= MAX_ALLOWED_CHALLS) {
1115 "deletechallenge_s",
1116 { data: { cid: this.challenges[challToDelIdx].id } }
1118 if (ctype == "corr") {
1122 { data: { id: this.challenges[challToDelIdx].id } }
1125 this.challenges.splice(challToDelIdx, 1);
1127 this.send("newchallenge", {
1128 data: Object.assign({ from: this.st.user.sid }, chall)
1130 // Add new challenge:
1132 sid: this.st.user.sid,
1133 id: this.st.user.id,
1134 name: this.st.user.name
1136 chall.added = Date.now();
1137 // NOTE: vname and type are redundant (deduced from cadence + vid)
1139 chall.vname = this.newchallenge.vname;
1140 this.challenges.push(chall);
1141 // Remember cadence + vid for quicker further challenges:
1142 localStorage.setItem("cadence", chall.cadence);
1143 localStorage.setItem("vid", chall.vid);
1144 localStorage.setItem("challRandomness", chall.randomness);
1145 document.getElementById("modalNewgame").checked = false;
1146 // Show the challenge if not on current display
1148 (ctype == "live" && this.cdisplay == "corr") ||
1149 (ctype == "corr" && this.cdisplay == "live")
1151 this.setDisplay('c', ctype);
1154 if (ctype == "live") {
1155 // Live challenges have a random ID
1156 finishAddChallenge(null);
1158 // Correspondence game: send challenge to server
1163 data: { chall: chall },
1164 success: (response) => {
1165 finishAddChallenge(response.id);
1171 // Callback function after a diagram was showed to accept
1172 // or refuse targetted challenge:
1173 decisionChallenge: function(accepted) {
1174 this.curChallToAccept.accepted = accepted;
1175 this.finishProcessingChallenge(this.curChallToAccept);
1176 document.getElementById("modalAccept").checked = false;
1178 finishProcessingChallenge: function(c) {
1181 sid: this.st.user.sid,
1182 id: this.st.user.id,
1183 name: this.st.user.name
1186 if (c.type == "live") {
1187 // Remove all live challenges of both players
1189 "deletechallenge_s",
1190 { data: { sids: [c.from.sid, c.seat.sid] } }
1194 // Corr challenge: just remove the challenge
1195 this.send("deletechallenge_s", { data: { cid: c.id } });
1197 const oppsid = this.getOppsid(c);
1199 this.send("refusechallenge", { data: c.id, target: oppsid });
1200 if (c.type == "corr") {
1204 { data: { id: c.id } }
1207 this.send("deletechallenge_s", { data: { cid: c.id } });
1210 // TODO: if several players click same challenge at the same time: problem
1211 clickChallenge: async function(c) {
1213 c.from.sid == this.st.user.sid || //live
1214 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
1216 if (c.type == "corr" && this.st.user.id <= 0) {
1217 alert(this.st.tr["Please log in to accept corr challenges"]);
1221 await import("@/variants/" + c.vname + ".js")
1222 .then((vModule) => {
1223 window.V = vModule[c.vname + "Rules"];
1225 // c.to == this.st.user.name (connected)
1227 const parsedFen = V.ParseFen(c.fen);
1228 this.tchallDiag = getDiagram({
1229 position: parsedFen.position,
1230 orientation: parsedFen.turn
1233 this.curChallToAccept = c;
1234 document.getElementById("modalAccept").checked = true;
1236 else this.finishProcessingChallenge(c);
1241 if (c.type == "corr") {
1245 { data: { id: c.id } }
1248 this.send("deletechallenge_s", { data: { cid: c.id } });
1250 // In all cases, the challenge is consumed:
1251 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
1253 // NOTE: when launching game, the challenge is already being deleted
1254 launchGame: function(c) {
1255 // White player index 0, black player index 1:
1258 ? (c.color == "w" ? [c.from, c.seat] : [c.seat, c.from])
1259 : shuffle([c.from, c.seat]);
1260 players.forEach(p => {
1261 if (!!p["tmpIds"]) delete p["tmpIds"];
1263 // These game informations will be shared
1265 id: getRandString(),
1266 fen: c.fen || V.GenRandInitFen(c.randomness),
1267 randomness: c.randomness, //for rematch
1272 const notifyNewgame = () => {
1273 const oppsid = this.getOppsid(c);
1275 // Opponent is online
1276 this.send("startgame", { data: gameInfo, target: oppsid });
1277 // If new corr game, notify Hall (except opponent and me)
1278 if (c.type == "corr") {
1283 excluded: [this.st.user.sid, oppsid]
1287 // Notify MyGames page:
1292 targets: gameInfo.players
1295 // NOTE: no need to send the game to the room, since I'll connect
1296 // on game just after, the main Hall will be notified.
1298 if (c.type == "live") {
1300 this.startNewGame(gameInfo);
1302 // corr: game only on server
1307 // cid is useful to delete the challenge:
1312 success: (response) => {
1313 gameInfo.id = response.id;
1315 this.$router.push("/game/" + response.id);
1321 // NOTE: for live games only (corr games start on the server)
1322 startNewGame: function(gameInfo) {
1323 const game = Object.assign(
1327 // (other) Game infos: constant
1328 fenStart: gameInfo.fen,
1329 vname: this.getVname(gameInfo.vid),
1330 created: Date.now(),
1331 // Game state (including FEN): will be updated
1333 clocks: [-1, -1], //-1 = unstarted
1340 const myIdx = (game.players[0].sid == this.st.user.sid ? 0 : 1);
1341 GameStorage.add(game, (err) => {
1342 // If an error occurred, game is not added: the focused tab
1343 // already added the game.
1345 if (this.st.settings.sound)
1346 // This will be played several times if several hidden tabs
1347 // on Hall... TODO: fix that (how ?!)
1348 new Audio("/sounds/newgame.flac").play().catch(() => {});
1351 { body: "vs " + game.players[1-myIdx].name || "@nonymous" }
1354 this.$router.push("/game/" + gameInfo.id);
1357 this.focus ? 0 : 500 + 1000 * Math.random()
1364 <style lang="sass" scoped>
1372 #newgameDiv > .card, #acceptDiv > .card
1376 div#peopleWrap > .card
1379 @media screen and (min-width: 1281px)
1380 div#peopleWrap > .card
1383 @media screen and (max-width: 1280px)
1384 div#peopleWrap > .card
1387 @media screen and (max-width: 767px)
1388 div#peopleWrap > .card
1401 @media screen and (max-width: 767px)
1416 button.player-action
1420 background-color: #90C4EC !important
1423 background-color: #f9faee
1426 background-color: lightgreen
1428 background-color: red
1431 // margin-top set dynamically (depends if diagram showed or not)
1442 // width: 100% required for Firefox
1450 @media screen and (max-width: 767px)
1459 background-color: #FF5733
1461 background-color: #2B63B4
1463 background-color: #33B42B
1465 @media screen and (max-width: 767px)
1474 background-color: lightgrey