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