Better time control in correspondance games
[vchess.git] / client / src / views / Hall.vue
1 <template lang="pug">
2 main
3 input#modalInfo.modal(type="checkbox")
4 div#infoDiv(
5 role="dialog"
6 data-checkbox="modalInfo"
7 )
8 .card.text-center
9 label.modal-close(for="modalInfo")
10 p(v-html="infoMessage")
11 input#modalAccept.modal(type="checkbox")
12 div#acceptDiv(role="dialog")
13 .card.text-center
14 p
15 span.variantName {{ curChallToAccept.vname }}
16 span {{ curChallToAccept.cadence }}
17 span {{ st.tr["with"] + " " + curChallToAccept.from.name }}
18 .diagram(v-html="tchallDiag")
19 .button-group#buttonsTchall
20 button.acceptBtn(@click="decisionChallenge(true)") {{ st.tr["Accept challenge?"] }}
21 button.refuseBtn(@click="decisionChallenge(false)") {{ st.tr["Refuse"] }}
22 input#modalNewgame.modal(
23 type="checkbox"
24 @change="cadenceFocusIfOpened($event)"
25 )
26 div#newgameDiv(
27 role="dialog"
28 data-checkbox="modalNewgame"
29 )
30 .card
31 label#closeNewgame.modal-close(for="modalNewgame")
32 div(@keyup.enter="newChallenge()")
33 fieldset
34 label(for="selectVariant") {{ st.tr["Variant"] }} *
35 select#selectVariant(
36 @change="loadNewchallVariant(trySetNewchallDiag)"
37 v-model="newchallenge.vid"
38 )
39 option(
40 v-for="v in st.variants"
41 :value="v.id"
42 :selected="newchallenge.vid==v.id"
43 )
44 | {{ v.name }}
45 fieldset
46 label(for="cadence") {{ st.tr["Cadence"] }} *
47 div#predefinedCadences
48 button(type="button") 15+5
49 button(type="button") 45+30
50 button(type="button") 3d
51 button(type="button") 7d
52 input#cadence(
53 type="text"
54 v-model="newchallenge.cadence"
55 placeholder="5+0, 1h+30s, 5d ..."
56 )
57 fieldset(v-if="st.user.id > 0")
58 label(for="selectPlayers") {{ st.tr["Play with?"] }}
59 input#selectPlayers(
60 type="text"
61 v-model="newchallenge.to"
62 )
63 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
64 input#inputFen(
65 placeholder="FEN"
66 @input="trySetNewchallDiag()"
67 type="text"
68 v-model="newchallenge.fen"
69 )
70 .diagram(v-html="newchallenge.diag")
71 button(@click="newChallenge()") {{ st.tr["Send challenge"] }}
72 input#modalPeople.modal(
73 type="checkbox"
74 @click="resetChatColor()"
75 )
76 div#peopleWrap(
77 role="dialog"
78 data-checkbox="modalPeople"
79 )
80 .card
81 label.modal-close(for="modalPeople")
82 #people
83 #players
84 p(
85 v-for="sid in Object.keys(people)"
86 v-if="!!people[sid].name"
87 )
88 span {{ people[sid].name }}
89 button.player-action(
90 v-if="isGamer(sid) || (st.user.id > 0 && sid!=st.user.sid)"
91 @click="challOrWatch(sid)"
92 )
93 | {{ getActionLabel(sid) }}
94 p.anonymous @nonymous ({{ anonymousCount }})
95 #chat
96 Chat(
97 :newChat="newChat"
98 @mychat="processChat"
99 :pastChats="[]"
100 )
101 .clearer
102 .row
103 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
104 .button-group
105 button#peopleBtn(onClick="window.doClick('modalPeople')")
106 | {{ st.tr["Who's there?"] }}
107 button(onClick="window.doClick('modalNewgame')")
108 | {{ st.tr["New game"] }}
109 .row
110 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
111 div#div2
112 .button-group
113 button.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
114 | {{ st.tr["Live challenges"] }}
115 button.tabbtn#btnCcorr(@click="setDisplay('c','corr',$event)")
116 | {{ st.tr["Correspondance challenges"] }}
117 ChallengeList(
118 v-show="cdisplay=='live'"
119 :challenges="filterChallenges('live')"
120 @click-challenge="clickChallenge"
121 )
122 ChallengeList(
123 v-show="cdisplay=='corr'"
124 :challenges="filterChallenges('corr')"
125 @click-challenge="clickChallenge"
126 )
127 div#div3
128 .button-group
129 button.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
130 | {{ st.tr["Live games"] }}
131 button.tabbtn#btnGcorr(@click="setDisplay('g','corr',$event)")
132 | {{ st.tr["Correspondance games"] }}
133 GameList(
134 v-show="gdisplay=='live'"
135 :games="filterGames('live')"
136 :showBoth="true"
137 @show-game="showGame"
138 )
139 GameList(
140 v-show="gdisplay=='corr'"
141 :games="filterGames('corr')"
142 :showBoth="true"
143 @show-game="showGame"
144 )
145 </template>
146
147 <script>
148 import { store } from "@/store";
149 import { checkChallenge } from "@/data/challengeCheck";
150 import { ArrayFun } from "@/utils/array";
151 import { ajax } from "@/utils/ajax";
152 import params from "@/parameters";
153 import { getRandString, shuffle } from "@/utils/alea";
154 import { getDiagram } from "@/utils/printDiagram";
155 import Chat from "@/components/Chat.vue";
156 import GameList from "@/components/GameList.vue";
157 import ChallengeList from "@/components/ChallengeList.vue";
158 import { GameStorage } from "@/utils/gameStorage";
159 import { processModalClick } from "@/utils/modalClick";
160 export default {
161 name: "my-hall",
162 components: {
163 Chat,
164 GameList,
165 ChallengeList
166 },
167 data: function() {
168 return {
169 st: store.state,
170 cdisplay: "live", //or corr
171 gdisplay: "live",
172 games: [],
173 challenges: [],
174 people: {},
175 infoMessage: "",
176 newchallenge: {
177 fen: "",
178 vid: parseInt(localStorage.getItem("vid")) || 0,
179 to: "", //name of challenged player (if any)
180 cadence: localStorage.getItem("cadence") || "",
181 // VariantRules object, stored to not interfere with
182 // diagrams of targetted challenges:
183 V: null,
184 vname: "",
185 diag: "" //visualizing FEN
186 },
187 tchallDiag: "",
188 curChallToAccept: {from: {}},
189 newChat: "",
190 conn: null,
191 connexionString: "",
192 // Related to (killing of) self multi-connects:
193 newConnect: {},
194 killed: {}
195 };
196 },
197 watch: {
198 // st.variants changes only once, at loading from [] to [...]
199 "st.variants": function() {
200 // Set potential challenges and games variant names:
201 this.challenges.concat(this.games).forEach(o => {
202 if (o.vname == "") o.vname = this.getVname(o.vid);
203 });
204 if (!this.newchallenge.V && this.newchallenge.vid > 0)
205 this.loadNewchallVariant();
206 }
207 },
208 computed: {
209 anonymousCount: function() {
210 let count = 0;
211 Object.values(this.people).forEach(p => {
212 count += !p.name ? 1 : 0;
213 });
214 return count;
215 }
216 },
217 created: function() {
218 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
219 this.loadNewchallVariant();
220 const my = this.st.user;
221 this.$set(this.people, my.sid, { id: my.id, name: my.name, pages: ["/"] });
222 // Ask server for current corr games (all but mines)
223 ajax(
224 "/games",
225 "GET",
226 { uid: this.st.user.id, excluded: true },
227 response => {
228 this.games = this.games.concat(
229 response.games.map(g => {
230 const type = this.classifyObject(g);
231 const vname = this.getVname(g.vid);
232 return Object.assign({}, g, { type: type, vname: vname });
233 })
234 );
235 }
236 );
237 // Also ask for corr challenges (open + sent by/to me)
238 ajax("/challenges", "GET", { uid: this.st.user.id }, response => {
239 // Gather all senders names, and then retrieve full identity:
240 // (TODO [perf]: some might be online...)
241 let names = {};
242 response.challenges.forEach(c => {
243 if (c.uid != this.st.user.id) names[c.uid] = "";
244 else if (!!c.target && c.target != this.st.user.id)
245 names[c.target] = "";
246 });
247 const addChallenges = () => {
248 names[this.st.user.id] = this.st.user.name; //in case of
249 this.challenges = this.challenges.concat(
250 response.challenges.map(c => {
251 const from = { name: names[c.uid], id: c.uid }; //or just name
252 const type = this.classifyObject(c);
253 const vname = this.getVname(c.vid);
254 return Object.assign(
255 {},
256 {
257 type: type,
258 vname: vname,
259 from: from,
260 to: c.target ? names[c.target] : ""
261 },
262 c
263 );
264 })
265 );
266 };
267 if (Object.keys(names).length > 0) {
268 ajax(
269 "/users",
270 "GET",
271 { ids: Object.keys(names).join(",") },
272 response2 => {
273 response2.users.forEach(u => {
274 names[u.id] = u.name;
275 });
276 addChallenges();
277 }
278 );
279 } else addChallenges();
280 });
281 const connectAndPoll = () => {
282 this.send("connect");
283 this.send("pollclientsandgamers");
284 };
285 // Initialize connection
286 this.connexionString =
287 params.socketUrl +
288 "/?sid=" +
289 this.st.user.sid +
290 "&tmpId=" +
291 getRandString() +
292 "&page=" +
293 encodeURIComponent(this.$route.path);
294 this.conn = new WebSocket(this.connexionString);
295 this.conn.onopen = connectAndPoll;
296 this.conn.onmessage = this.socketMessageListener;
297 this.conn.onclose = this.socketCloseListener;
298 },
299 mounted: function() {
300 ["peopleWrap", "infoDiv", "newgameDiv"].forEach(eltName => {
301 let elt = document.getElementById(eltName);
302 elt.addEventListener("click", processModalClick);
303 });
304 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
305 b.addEventListener("click", () => {
306 this.newchallenge.cadence = b.innerHTML;
307 });
308 });
309 const dispCorr = this.$route.query["disp"];
310 const showCtype =
311 dispCorr || localStorage.getItem("type-challenges") || "live";
312 const showGtype =
313 dispCorr || localStorage.getItem("type-games") || "live";
314 this.setDisplay("c", showCtype);
315 this.setDisplay("g", showGtype);
316 },
317 beforeDestroy: function() {
318 this.send("disconnect");
319 },
320 methods: {
321 // Helpers:
322 cadenceFocusIfOpened: function() {
323 if (event.target.checked)
324 document.getElementById("cadence").focus();
325 },
326 send: function(code, obj) {
327 if (this.conn) {
328 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
329 }
330 },
331 getVname: function(vid) {
332 const variant = this.st.variants.find(v => v.id == vid);
333 // this.st.variants might be uninitialized (variant == null)
334 return variant ? variant.name : "";
335 },
336 filterChallenges: function(type) {
337 return this.challenges.filter(c => c.type == type);
338 },
339 filterGames: function(type) {
340 return this.games.filter(g => g.type == type);
341 },
342 classifyObject: function(o) {
343 //challenge or game
344 return o.cadence.indexOf("d") === -1 ? "live" : "corr";
345 },
346 setDisplay: function(letter, type, e) {
347 this[letter + "display"] = type;
348 localStorage.setItem(
349 "type-" + (letter == "c" ? "challenges" : "games"),
350 type
351 );
352 let elt = e
353 ? e.target
354 : document.getElementById("btn" + letter.toUpperCase() + type);
355 elt.classList.add("active");
356 elt.classList.remove("somethingnew"); //in case of
357 if (elt.previousElementSibling)
358 elt.previousElementSibling.classList.remove("active");
359 else elt.nextElementSibling.classList.remove("active");
360 },
361 isGamer: function(sid) {
362 return this.people[sid].pages.some(p => p.indexOf("/game/") >= 0);
363 },
364 getActionLabel: function(sid) {
365 return this.people[sid].pages.some(p => p == "/")
366 ? "Challenge"
367 : "Observe";
368 },
369 challOrWatch: function(sid) {
370 if (this.people[sid].pages.some(p => p == "/")) {
371 // Available, in Hall
372 this.newchallenge.to = this.people[sid].name;
373 document.getElementById("modalPeople").checked = false;
374 window.doClick("modalNewgame");
375 } else {
376 // In some game, maybe playing maybe not: show a random one
377 let gids = [];
378 this.people[sid].pages.forEach(p => {
379 const matchGid = p.match(/[a-zA-Z0-9]+$/);
380 if (matchGid) gids.push(matchGid[0]);
381 });
382 const gid = gids[Math.floor(Math.random() * gids.length)];
383 const game = this.games.find(g => g.id == gid);
384 if (game) this.showGame(game);
385 else this.$router.push("/game/" + gid); //game vs. me
386 }
387 },
388 showGame: function(g) {
389 // NOTE: we are an observer, since only games I don't play are shown here
390 // ==> Moves sent by connected remote player(s) if live game
391 let url = "/game/" + g.id;
392 if (g.type == "live")
393 url += "?rid=" + g.rids[Math.floor(Math.random() * g.rids.length)];
394 this.$router.push(url);
395 },
396 resetChatColor: function() {
397 // TODO: this is called twice, once on opening an once on closing
398 document.getElementById("peopleBtn").classList.remove("somethingnew");
399 },
400 processChat: function(chat) {
401 this.send("newchat", { data: chat });
402 },
403 // Messaging center:
404 socketMessageListener: function(msg) {
405 if (!this.conn) return;
406 const data = JSON.parse(msg.data);
407 switch (data.code) {
408 case "pollclientsandgamers": {
409 // Since people can be both in Hall and Game,
410 // need to track "askIdentity" requests:
411 let identityAsked = {};
412 data.sockIds.forEach(s => {
413 const page = s.page || "/";
414 if (s.sid != this.st.user.sid && !identityAsked[s.sid]) {
415 identityAsked[s.sid] = true;
416 this.send("askidentity", { target: s.sid, page: page });
417 }
418 if (!this.people[s.sid])
419 this.$set(this.people, s.sid, { id: 0, name: "", pages: [page] });
420 else if (this.people[s.sid].pages.indexOf(page) < 0)
421 this.people[s.sid].pages.push(page);
422 if (!s.page)
423 //peer is in Hall
424 this.send("askchallenge", { target: s.sid });
425 //peer is in Game
426 else this.send("askgame", { target: s.sid, page: page });
427 });
428 break;
429 }
430 case "connect":
431 case "gconnect": {
432 const page = data.page || "/";
433 // NOTE: player could have been polled earlier, but might have logged in then
434 // So it's a good idea to ask identity if he was anonymous.
435 // But only ask game / challenge if currently disconnected.
436 if (!this.people[data.from]) {
437 this.$set(this.people, data.from, {
438 name: "",
439 id: 0,
440 pages: [page]
441 });
442 if (data.code == "connect")
443 this.send("askchallenge", { target: data.from });
444 else this.send("askgame", { target: data.from, page: page });
445 } else {
446 // append page if not already in list
447 if (this.people[data.from].pages.indexOf(page) < 0)
448 this.people[data.from].pages.push(page);
449 }
450 if (this.people[data.from].id == 0) {
451 this.newConnect[data.from] = true; //for self multi-connects tests
452 this.send("askidentity", { target: data.from, page: page });
453 }
454 break;
455 }
456 case "disconnect":
457 case "gdisconnect": {
458 // If the user reloads the page twice very quickly (experienced with Firefox),
459 // the first reload won't have time to connect but will trigger a "close" event anyway.
460 // ==> Next check is required.
461 if (!this.people[data.from]) return;
462 // Disconnect means no more tmpIds:
463 if (data.code == "disconnect") {
464 // Remove the live challenge sent by this player:
465 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
466 } else {
467 // Remove the matching live game if now unreachable
468 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
469 const gidx = this.games.findIndex(g => g.id == gid);
470 if (gidx >= 0) {
471 const game = this.games[gidx];
472 if (
473 game.type == "live" &&
474 game.rids.length == 1 &&
475 game.rids[0] == data.from
476 ) {
477 this.games.splice(gidx, 1);
478 }
479 }
480 }
481 const page = data.page || "/";
482 ArrayFun.remove(this.people[data.from].pages, p => p == page);
483 if (this.people[data.from].pages.length == 0)
484 this.$delete(this.people, data.from);
485 break;
486 }
487 case "killed":
488 // I logged in elsewhere:
489 // TODO: this fails. See https://github.com/websockets/ws/issues/489
490 //this.conn.removeEventListener("message", this.socketMessageListener);
491 //this.conn.removeEventListener("close", this.socketCloseListener);
492 //this.conn.close();
493 this.conn = null;
494 alert(this.st.tr["New connexion detected: tab now offline"]);
495 break;
496 case "askidentity": {
497 // Request for identification (TODO: anonymous shouldn't need to reply)
498 const me = {
499 // Decompose to avoid revealing email
500 name: this.st.user.name,
501 sid: this.st.user.sid,
502 id: this.st.user.id
503 };
504 this.send("identity", { data: me, target: data.from });
505 break;
506 }
507 case "identity": {
508 const user = data.data;
509 if (user.name) {
510 // If I multi-connect, kill current connexion if no mark (I'm older)
511 if (
512 this.newConnect[user.sid] &&
513 user.id > 0 &&
514 user.id == this.st.user.id &&
515 user.sid != this.st.user.sid
516 ) {
517 if (!this.killed[this.st.user.sid]) {
518 this.send("killme", { sid: this.st.user.sid });
519 this.killed[this.st.user.sid] = true;
520 }
521 }
522 if (user.sid != this.st.user.sid) {
523 //I already know my identity...
524 this.$set(this.people, user.sid, {
525 id: user.id,
526 name: user.name,
527 pages: this.people[user.sid].pages
528 });
529 }
530 }
531 delete this.newConnect[user.sid];
532 break;
533 }
534 case "askchallenge": {
535 // Send my current live challenge (if any)
536 const cIdx = this.challenges.findIndex(
537 c => c.from.sid == this.st.user.sid && c.type == "live"
538 );
539 if (cIdx >= 0) {
540 const c = this.challenges[cIdx];
541 // NOTE: in principle, should only send targeted challenge to the target.
542 // But we may not know yet the identity of the target (just name),
543 // so cannot decide if data.from is the target or not.
544 const myChallenge = {
545 id: c.id,
546 from: this.st.user.sid,
547 to: c.to,
548 fen: c.fen,
549 vid: c.vid,
550 cadence: c.cadence,
551 added: c.added
552 };
553 this.send("challenge", { data: myChallenge, target: data.from });
554 }
555 break;
556 }
557 case "challenge": //after "askchallenge"
558 case "newchallenge": {
559 // NOTE about next condition: see "askchallenge" case.
560 const chall = data.data;
561 if (
562 !chall.to ||
563 (this.people[chall.from].id > 0 &&
564 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
565 ) {
566 let newChall = Object.assign({}, chall);
567 newChall.type = this.classifyObject(chall);
568 newChall.added = Date.now();
569 let fromValues = Object.assign({}, this.people[chall.from]);
570 delete fromValues["pages"]; //irrelevant in this context
571 newChall.from = Object.assign({ sid: chall.from }, fromValues);
572 newChall.vname = this.getVname(newChall.vid);
573 this.challenges.push(newChall);
574 if (
575 (newChall.type == "live" && this.cdisplay == "corr") ||
576 (newChall.type == "corr" && this.cdisplay == "live")
577 ) {
578 document
579 .getElementById("btnC" + newChall.type)
580 .classList.add("somethingnew");
581 }
582 }
583 break;
584 }
585 case "refusechallenge": {
586 const cid = data.data;
587 ArrayFun.remove(this.challenges, c => c.id == cid);
588 alert(this.st.tr["Challenge declined"]);
589 break;
590 }
591 case "deletechallenge": {
592 // NOTE: the challenge may be already removed
593 const cid = data.data;
594 ArrayFun.remove(this.challenges, c => c.id == cid);
595 break;
596 }
597 case "game": //individual request
598 case "newgame": {
599 // NOTE: it may be live or correspondance
600 const game = data.data;
601 // Ignore games where I play (corr games)
602 if (game.players.every(p => p.id != this.st.user.id))
603 {
604 let locGame = this.games.find(g => g.id == game.id);
605 if (!locGame) {
606 let newGame = game;
607 newGame.type = this.classifyObject(game);
608 newGame.vname = this.getVname(game.vid);
609 if (!game.score)
610 //if new game from Hall
611 newGame.score = "*";
612 newGame.rids = [game.rid];
613 delete newGame["rid"];
614 this.games.push(newGame);
615 if (
616 (newGame.type == "live" && this.gdisplay == "corr") ||
617 (newGame.type == "corr" && this.gdisplay == "live")
618 ) {
619 document
620 .getElementById("btnG" + newGame.type)
621 .classList.add("somethingnew");
622 }
623 } else {
624 // Append rid (if not already in list)
625 if (!locGame.rids.includes(game.rid)) locGame.rids.push(game.rid);
626 }
627 }
628 break;
629 }
630 case "result": {
631 let g = this.games.find(g => g.id == data.gid);
632 if (g) g.score = data.score;
633 break;
634 }
635 case "startgame": {
636 // New game just started: data contain all information
637 const gameInfo = data.data;
638 if (this.classifyObject(gameInfo) == "live")
639 this.startNewGame(gameInfo);
640 else {
641 this.infoMessage =
642 this.st.tr["New correspondance game:"] +
643 " <a href='#/game/" +
644 gameInfo.id +
645 "'>" +
646 "#/game/" +
647 gameInfo.id +
648 "</a>";
649 let modalBox = document.getElementById("modalInfo");
650 modalBox.checked = true;
651 }
652 break;
653 }
654 case "newchat":
655 this.newChat = data.data;
656 if (!document.getElementById("modalPeople").checked)
657 document.getElementById("peopleBtn").classList.add("somethingnew");
658 break;
659 }
660 },
661 socketCloseListener: function() {
662 if (!this.conn) return;
663 this.conn = new WebSocket(this.connexionString);
664 this.conn.addEventListener("message", this.socketMessageListener);
665 this.conn.addEventListener("close", this.socketCloseListener);
666 },
667 // Challenge lifecycle:
668 loadNewchallVariant: async function(cb) {
669 const vname = this.getVname(this.newchallenge.vid);
670 const vModule = await import("@/variants/" + vname + ".js");
671 this.newchallenge.V = vModule.VariantRules;
672 this.newchallenge.vname = vname;
673 if (cb)
674 cb();
675 },
676 trySetNewchallDiag: function() {
677 if (!this.newchallenge.fen) {
678 this.newchallenge.diag = "";
679 return;
680 }
681 // If vid > 0 then the variant is loaded (function above):
682 window.V = this.newchallenge.V;
683 if (
684 this.newchallenge.vid > 0 &&
685 this.newchallenge.fen &&
686 V.IsGoodFen(this.newchallenge.fen)
687 ) {
688 const parsedFen = V.ParseFen(this.newchallenge.fen);
689 this.newchallenge.diag = getDiagram({
690 position: parsedFen.position,
691 orientation: V.GetOppCol(parsedFen.turn)
692 });
693 }
694 },
695 newChallenge: async function() {
696 if (this.newchallenge.cadence.match(/^[0-9]+$/))
697 this.newchallenge.cadence += "+0"; //assume minutes, no increment
698 const ctype = this.classifyObject(this.newchallenge);
699 // TODO: cadence still unchecked so ctype could be wrong...
700 let error = "";
701 if (!this.newchallenge.vid)
702 error = this.st.tr["Please select a variant"];
703 else if (ctype == "corr" && this.st.user.id <= 0)
704 error = this.st.tr["Please log in to play correspondance games"];
705 else if (this.newchallenge.to) {
706 if (this.newchallenge.to == this.st.user.name)
707 error = this.st.tr["Self-challenge is forbidden"];
708 else if (
709 ctype == "live" &&
710 Object.values(this.people).every(p => p.name != this.newchallenge.to)
711 )
712 error = this.newchallenge.to + " " + this.st.tr["is not online"];
713 }
714 if (error) {
715 alert(error);
716 return;
717 }
718 window.V = this.newchallenge.V;
719 error = checkChallenge(this.newchallenge);
720 if (error) {
721 alert(error);
722 return;
723 }
724 // NOTE: "from" information is not required here
725 let chall = Object.assign({}, this.newchallenge);
726 const finishAddChallenge = cid => {
727 chall.id = cid || "c" + getRandString();
728 // Remove old challenge if any (only one at a time of a given type):
729 const cIdx = this.challenges.findIndex(
730 c =>
731 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) &&
732 c.type == ctype
733 );
734 if (cIdx >= 0) {
735 // Delete current challenge (will be replaced now)
736 this.send("deletechallenge", { data: this.challenges[cIdx].id });
737 if (ctype == "corr") {
738 ajax("/challenges", "DELETE", { id: this.challenges[cIdx].id });
739 }
740 this.challenges.splice(cIdx, 1);
741 }
742 this.send("newchallenge", {
743 data: Object.assign({ from: this.st.user.sid }, chall)
744 });
745 // Add new challenge:
746 chall.from = {
747 // Decompose to avoid revealing email
748 sid: this.st.user.sid,
749 id: this.st.user.id,
750 name: this.st.user.name
751 };
752 chall.added = Date.now();
753 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
754 chall.type = ctype;
755 chall.vname = this.newchallenge.vname;
756 this.challenges.push(chall);
757 // Remember cadence + vid for quicker further challenges:
758 localStorage.setItem("cadence", chall.cadence);
759 localStorage.setItem("vid", chall.vid);
760 document.getElementById("modalNewgame").checked = false;
761 // Show the challenge if not on current display
762 if (
763 (ctype == "live" && this.cdisplay == "corr") ||
764 (ctype == "corr" && this.cdisplay == "live")
765 ) {
766 this.setDisplay('c', ctype);
767 }
768 };
769 if (ctype == "live") {
770 // Live challenges have a random ID
771 finishAddChallenge(null);
772 } else {
773 // Correspondance game: send challenge to server
774 ajax("/challenges", "POST", { chall: chall }, response => {
775 finishAddChallenge(response.cid);
776 });
777 }
778 },
779 // Callback function after a diagram was showed to accept
780 // or refuse targetted challenge:
781 decisionChallenge: function(accepted) {
782 this.curChallToAccept.accepted = accepted;
783 this.finishProcessingChallenge(this.curChallToAccept);
784 document.getElementById("modalAccept").checked = false;
785 },
786 finishProcessingChallenge: function(c) {
787 if (c.accepted) {
788 c.seat = {
789 // Again, avoid c.seat = st.user to not reveal email
790 sid: this.st.user.sid,
791 id: this.st.user.id,
792 name: this.st.user.name
793 };
794 this.launchGame(c);
795 } else {
796 this.send("refusechallenge", { data: c.id, target: c.from.sid });
797 }
798 this.send("deletechallenge", { data: c.id });
799 },
800 clickChallenge: async function(c) {
801 const myChallenge =
802 c.from.sid == this.st.user.sid || //live
803 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
804 if (!myChallenge) {
805 if (c.type == "corr" && this.st.user.id <= 0) {
806 alert(this.st.tr["Please log in to accept corr challenges"]);
807 return;
808 }
809 c.accepted = true;
810 const vModule = await import("@/variants/" + c.vname + ".js");
811 window.V = vModule.VariantRules;
812 if (c.to) {
813 // c.to == this.st.user.name (connected)
814 if (c.fen) {
815 const parsedFen = V.ParseFen(c.fen);
816 c.mycolor = V.GetOppCol(parsedFen.turn);
817 this.tchallDiag = getDiagram({
818 position: parsedFen.position,
819 orientation: c.mycolor
820 });
821 this.curChallToAccept = c;
822 document.getElementById("modalAccept").checked = true;
823 }
824 else {
825 if (!confirm(this.st.tr["Accept challenge?"]))
826 c.accepted = false;
827 this.finishProcessingChallenge(c);
828 }
829 }
830 else
831 this.finishProcessingChallenge(c);
832 }
833 else {
834 // My challenge
835 if (c.type == "corr") {
836 ajax("/challenges", "DELETE", { id: c.id });
837 }
838 this.send("deletechallenge", { data: c.id });
839 }
840 // In all cases, the challenge is consumed:
841 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
842 },
843 // NOTE: when launching game, the challenge is already being deleted
844 launchGame: function(c) {
845 // These game informations will be shared
846 let gameInfo = {
847 id: getRandString(),
848 fen: c.fen || V.GenRandInitFen(),
849 // White player index 0, black player index 1:
850 players: c.mycolor
851 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
852 : shuffle([c.from, c.seat]),
853 vid: c.vid,
854 cadence: c.cadence
855 };
856 let oppsid = c.from.sid; //may not be defined if corr + offline opp
857 if (!oppsid) {
858 oppsid = Object.keys(this.people).find(
859 sid => this.people[sid].id == c.from.id
860 );
861 }
862 const notifyNewgame = () => {
863 if (oppsid)
864 //opponent is online
865 this.send("startgame", { data: gameInfo, target: oppsid });
866 // Send game info (only if live) to everyone except me in this tab
867 this.send("newgame", { data: gameInfo });
868 };
869 if (c.type == "live") {
870 notifyNewgame();
871 this.startNewGame(gameInfo);
872 } //corr: game only on server
873 else {
874 ajax(
875 "/games",
876 "POST",
877 { gameInfo: gameInfo, cid: c.id }, //cid useful to delete challenge
878 response => {
879 gameInfo.id = response.gameId;
880 notifyNewgame();
881 this.$router.push("/game/" + response.gameId);
882 }
883 );
884 }
885 },
886 // NOTE: for live games only (corr games start on the server)
887 startNewGame: function(gameInfo) {
888 const game = Object.assign({}, gameInfo, {
889 // (other) Game infos: constant
890 fenStart: gameInfo.fen,
891 vname: this.getVname(gameInfo.vid),
892 created: Date.now(),
893 // Game state (including FEN): will be updated
894 moves: [],
895 clocks: [-1, -1], //-1 = unstarted
896 initime: [0, 0], //initialized later
897 score: "*"
898 });
899 GameStorage.add(game, (err) => {
900 // If an error occurred, game is not added: abort
901 if (!err) {
902 if (this.st.settings.sound)
903 new Audio("/sounds/newgame.wav").play().catch(() => {});
904 this.$router.push("/game/" + gameInfo.id);
905 }
906 });
907 }
908 }
909 };
910 </script>
911
912 <style lang="sass" scoped>
913 .active
914 color: #42a983
915
916 #infoDiv > .card
917 padding: 15px 0
918 max-width: 430px
919
920 #newgameDiv > .card, #acceptDiv > .card
921 max-width: 767px
922 max-height: 100%
923
924 div#peopleWrap > .card
925 max-height: 100%
926
927 @media screen and (min-width: 1281px)
928 div#peopleWrap > .card
929 max-width: 66.67%
930
931 @media screen and (max-width: 1280px)
932 div#peopleWrap > .card
933 max-width: 83.33%
934
935 @media screen and (max-width: 767px)
936 div#peopleWrap > .card
937 max-width: 100%
938
939 #players
940 width: 50%
941 position: relative
942 float: left
943
944 #chat
945 width: 50%
946 float: left
947 position: relative
948
949 @media screen and (max-width: 767px)
950 #players, #chats
951 width: 100%
952
953 #chat > .card
954 max-width: 100%
955 margin: 0;
956 border: none;
957
958 #players > p
959 margin-left: 5px
960
961 .anonymous
962 font-style: italic
963
964 button.player-action
965 margin-left: 32px
966
967 .somethingnew
968 background-color: #c5fefe !important
969
970 .tabbtn
971 background-color: #f9faee
972
973 button.acceptBtn
974 background-color: lightgreen
975 button.refuseBtn
976 background-color: red
977
978 #buttonsTchall
979 margin-top: 10px
980
981 .variantName
982 font-weight: bold
983
984 .diagram
985 margin: 0 auto
986 max-width: 400px
987
988 #inputFen
989 width: 100%
990
991 #div2, #div3
992 margin-top: 15px
993 @media screen and (max-width: 767px)
994 #div2, #div3
995 margin-top: 0
996 </style>