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