Experimental multi-tabs support (TODO: prevent multi-connect)
[vchess.git] / client / src / views / Hall.vue
CommitLineData
ccd4a2b7 1<template lang="pug">
9d58ef95 2main
dce792f6 3 input#modalInfo.modal(type="checkbox")
602d6bef 4 div#infoDiv(role="dialog" data-checkbox="modalInfo" aria-labelledby="infoMessage")
dce792f6
BA
5 .card.smallpad.small-modal.text-center
6 label.modal-close(for="modalInfo")
7 h3#infoMessage.section
3d55deea 8 p(v-html="infoMessage")
5b020e73 9 input#modalNewgame.modal(type="checkbox")
602d6bef 10 div#newgameDiv(role="dialog" data-checkbox="modalNewgame"
dcd68c41 11 aria-labelledby="titleFenedit")
c97830ea 12 .card.smallpad(@keyup.enter="newChallenge")
5b020e73
BA
13 label#closeNewgame.modal-close(for="modalNewgame")
14 fieldset
602d6bef 15 label(for="selectVariant") {{ st.tr["Variant"] }} *
9d58ef95 16 select#selectVariant(v-model="newchallenge.vid")
25d18342
BA
17 option(v-for="v in st.variants" :value="v.id"
18 :selected="newchallenge.vid==v.id")
19 | {{ v.name }}
5b020e73 20 fieldset
71468011
BA
21 label(for="cadence") {{ st.tr["Cadence"] }} *
22 div#predefinedCadences
25d18342
BA
23 button 3+2
24 button 5+3
25 button 15+5
71468011 26 input#cadence(type="text" v-model="newchallenge.cadence"
25d18342 27 placeholder="5+0, 1h+30s, 7d+1d ...")
b4d619d1 28 fieldset(v-if="st.user.id > 0")
602d6bef 29 label(for="selectPlayers") {{ st.tr["Play with?"] }}
6fba6e0c 30 input#selectPlayers(type="text" v-model="newchallenge.to")
25d18342 31 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
ac8f441c 32 label(for="inputFen") FEN
9d58ef95 33 input#inputFen(type="text" v-model="newchallenge.fen")
b4d619d1 34 button(@click="newChallenge") {{ st.tr["Send challenge"] }}
9d58ef95 35 .row
9ca1e26b 36 .col-sm-12
602d6bef 37 button#newGame(onClick="doClick('modalNewgame')") {{ st.tr["New game"] }}
9d58ef95 38 .row
9ca1e26b 39 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
ed06d9e9
BA
40 div
41 .button-group
42 button(@click="(e) => setDisplay('c','live',e)" class="active")
602d6bef 43 | {{ st.tr["Live challenges"] }}
ed06d9e9 44 button(@click="(e) => setDisplay('c','corr',e)")
602d6bef 45 | {{ st.tr["Correspondance challenges"] }}
ed06d9e9
BA
46 ChallengeList(v-show="cdisplay=='live'"
47 :challenges="filterChallenges('live')" @click-challenge="clickChallenge")
48 ChallengeList(v-show="cdisplay=='corr'"
49 :challenges="filterChallenges('corr')" @click-challenge="clickChallenge")
50 #people
602d6bef 51 h3.text-center {{ st.tr["Who's there?"] }}
ed06d9e9 52 #players
9335d45b
BA
53 p(v-for="sid in Object.keys(people)" v-if="!!people[sid].name")
54 span {{ people[sid].name }}
71468011 55 // Check: anonymous players cannot send individual challenges or be challenged individually
ed06d9e9 56 button.player-action(
71468011
BA
57 v-if="sid != st.user.sid && !!st.user.name && people[sid].id > 0"
58 @click="challOrWatch(sid)"
ed06d9e9 59 )
71468011 60 | {{ getActionLabel(sid) }}
ed06d9e9
BA
61 p.anonymous @nonymous ({{ anonymousCount }})
62 #chat
ac8f441c 63 Chat(:newChat="newChat" @mychat="processChat")
ed06d9e9
BA
64 .clearer
65 div
66 .button-group
67 button(@click="(e) => setDisplay('g','live',e)" class="active")
602d6bef 68 | {{ st.tr["Live games"] }}
ed06d9e9 69 button(@click="(e) => setDisplay('g','corr',e)")
602d6bef 70 | {{ st.tr["Correspondance games"] }}
ed06d9e9
BA
71 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
72 @show-game="showGame")
73 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
74 @show-game="showGame")
625022fd
BA
75</template>
76
77<script>
5b020e73 78import { store } from "@/store";
9d58ef95
BA
79import { checkChallenge } from "@/data/challengeCheck";
80import { ArrayFun } from "@/utils/array";
03608482 81import { ajax } from "@/utils/ajax";
8418f0d7 82import params from "@/parameters";
4b0384fa 83import { getRandString, shuffle } from "@/utils/alea";
603b8a8b 84import Chat from "@/components/Chat.vue";
5b020e73
BA
85import GameList from "@/components/GameList.vue";
86import ChallengeList from "@/components/ChallengeList.vue";
967a2686 87import { GameStorage } from "@/utils/gameStorage";
602d6bef 88import { processModalClick } from "@/utils/modalClick";
625022fd 89export default {
cf2343ce 90 name: "my-hall",
5b020e73 91 components: {
603b8a8b 92 Chat,
5b020e73
BA
93 GameList,
94 ChallengeList,
95 },
fb54f098
BA
96 data: function () {
97 return {
5b020e73 98 st: store.state,
6855163c 99 cdisplay: "live", //or corr
fb54f098 100 gdisplay: "live",
6855163c 101 games: [],
b4d619d1 102 challenges: [],
71468011 103 people: {},
3d55deea 104 infoMessage: "",
9d58ef95 105 newchallenge: {
fb54f098 106 fen: "",
25d18342 107 vid: localStorage.getItem("vid") || "",
6fba6e0c 108 to: "", //name of challenged player (if any)
71468011 109 cadence: localStorage.getItem("cadence") || "",
fb54f098 110 },
ac8f441c 111 newChat: "",
8418f0d7 112 conn: null,
fb54f098
BA
113 };
114 },
fd7aea36
BA
115 watch: {
116 // st.variants changes only once, at loading from [] to [...]
117 "st.variants": function(variantArray) {
118 // Set potential challenges and games variant names:
71468011
BA
119 this.challenges.concat(this.games).forEach(o => {
120 if (o.vname == "")
121 o.vname = this.getVname(o.vid);
fd7aea36
BA
122 });
123 },
124 },
b4d619d1 125 computed: {
ed06d9e9
BA
126 anonymousCount: function() {
127 let count = 0;
128 Object.values(this.people).forEach(p => { count += (!p.name ? 1 : 0); });
129 return count;
b4d619d1
BA
130 },
131 },
9d58ef95 132 created: function() {
66d03f23 133 const my = this.st.user;
71468011 134 this.$set(this.people, my.sid, {id:my.id, name:my.name, pages:["/"]});
3d55deea
BA
135 // Ask server for current corr games (all but mines)
136 ajax(
137 "/games",
138 "GET",
139 {uid: this.st.user.id, excluded: true},
140 response => {
141 this.games = this.games.concat(response.games.map(g => {
142 const type = this.classifyObject(g);
143 const vname = this.getVname(g.vid);
144 return Object.assign({}, g, {type: type, vname: vname});
145 }));
146 }
147 );
fe4c7e67 148 // Also ask for corr challenges (open + sent by/to me)
3d55deea
BA
149 ajax(
150 "/challenges",
151 "GET",
152 {uid: this.st.user.id},
153 response => {
154 // Gather all senders names, and then retrieve full identity:
155 // (TODO [perf]: some might be online...)
fe4c7e67
BA
156 let names = {};
157 response.challenges.forEach(c => {
158 if (c.uid != this.st.user.id)
159 names[c.uid] = ""; //unknwon for now
160 else if (!!c.target && c.target != this.st.user.id)
161 names[c.target] = "";
162 });
163 const addChallenges = (newChalls) => {
164 names[this.st.user.id] = this.st.user.name; //in case of
165 this.challenges = this.challenges.concat(
166 response.challenges.map(c => {
167 const from = {name: names[c.uid], id: c.uid}; //or just name
168 const type = this.classifyObject(c);
169 const vname = this.getVname(c.vid);
170 return Object.assign({},
171 {
172 type: type,
173 vname: vname,
174 from: from,
175 to: (!!c.target ? names[c.target] : ""),
176 },
177 c);
178 })
179 );
180 };
181 if (names !== {})
182 {
183 ajax("/users",
184 "GET",
185 { ids: Object.keys(names).join(",") },
186 response2 => {
187 response2.users.forEach(u => {names[u.id] = u.name});
188 addChallenges();
189 }
190 );
191 }
192 else
193 addChallenges();
3d55deea
BA
194 }
195 );
71468011
BA
196 const connectAndPoll = () => {
197 this.send("connect");
198 this.send("pollclientsandgamers");
4d64881e 199 };
8418f0d7 200 // Initialize connection
8418f0d7
BA
201 const connexionString = params.socketUrl +
202 "/?sid=" + this.st.user.sid +
71468011
BA
203 "&tmpId=" + getRandString() +
204 "&page=" + encodeURIComponent(this.$route.path);
8418f0d7 205 this.conn = new WebSocket(connexionString);
71468011 206 this.conn.onopen = connectAndPoll;
8418f0d7 207 this.conn.onmessage = this.socketMessageListener;
4d64881e 208 const socketCloseListener = () => {
8418f0d7
BA
209 this.conn = new WebSocket(connexionString);
210 this.conn.addEventListener('message', this.socketMessageListener);
211 this.conn.addEventListener('close', socketCloseListener);
4d64881e 212 };
8418f0d7 213 this.conn.onclose = socketCloseListener;
9d58ef95 214 },
25d18342 215 mounted: function() {
602d6bef
BA
216 [document.getElementById("infoDiv"),document.getElementById("newgameDiv")]
217 .forEach(elt => elt.addEventListener("click", processModalClick));
71468011 218 document.querySelectorAll("#predefinedCadences > button").forEach(
25d18342 219 (b) => { b.addEventListener("click",
71468011 220 () => { this.newchallenge.cadence = b.innerHTML; }
25d18342
BA
221 )}
222 );
223 },
8418f0d7 224 beforeDestroy: function() {
71468011 225 this.send("disconnect");
8418f0d7 226 },
fb54f098 227 methods: {
a6bddfc6 228 // Helpers:
71468011
BA
229 send: function(code, obj) {
230 this.conn.send(JSON.stringify(
231 Object.assign(
232 {code: code},
233 obj,
234 )
235 ));
236 },
237 getVname: function(vid) {
238 const variant = this.st.variants.find(v => v.id == vid);
239 // this.st.variants might be uninitialized (variant == null)
240 return (!!variant ? variant.name : "");
241 },
6855163c
BA
242 filterChallenges: function(type) {
243 return this.challenges.filter(c => c.type == type);
244 },
245 filterGames: function(type) {
a9b131f1 246 return this.games.filter(g => g.type == type);
6855163c 247 },
2ada153c 248 classifyObject: function(o) { //challenge or game
71468011 249 return (o.cadence.indexOf('d') === -1 ? "live" : "corr");
a6bddfc6 250 },
5bcc9b31
BA
251 setDisplay: function(letter, type, e) {
252 this[letter + "display"] = type;
253 e.target.classList.add("active");
254 if (!!e.target.previousElementSibling)
255 e.target.previousElementSibling.classList.remove("active");
256 else
257 e.target.nextElementSibling.classList.remove("active");
258 },
71468011
BA
259 getActionLabel: function(sid) {
260 return this.people[sid].pages.some(p => p == "/")
261 ? "Challenge"
262 : "Observe";
ac8f441c 263 },
71468011
BA
264 challOrWatch: function(sid) {
265 if (this.people[sid].pages.some(p => p == "/"))
a6bddfc6 266 {
71468011
BA
267 // Available, in Hall
268 this.newchallenge.to = this.people[sid].name;
269 doClick("modalNewgame");
a6bddfc6 270 }
9335d45b
BA
271 else
272 {
71468011
BA
273 // In some game, maybe playing maybe not
274 const gid = this.people[sid].page.match(/[a-zA-Z0-9]+$/)[0];
275 this.showGame(this.games.find(g => g.id == gid)), sid;
276 }
277 },
278 showGame: function(g, obsId) {
279 // NOTE: we are an observer, since only games I don't play are shown here
280 // ==> Moves sent by connected remote player(s) if live game
281 let url = "/game/" + g.id;
282 if (g.type == "live")
283 {
284 let rids = [];
285 for (let i of [0,1])
9335d45b 286 {
71468011
BA
287 if (this.people[g.players[i].sid].pages.indexOf(url) >= 0)
288 rids.push(g.players[i].sid);
9335d45b 289 }
71468011
BA
290 if (!!obsId)
291 rids.push(obsId); //observer can provide game too
292 const ridIdx = Math.floor(Math.random() * rids.length);
293 url += "?rid=" + rids[ridIdx];
9335d45b 294 }
71468011
BA
295 this.$router.push(url);
296 },
297 processChat: function(chat) {
298 this.send("newchat", {data:chat});
a6bddfc6
BA
299 },
300 // Messaging center:
9d58ef95
BA
301 socketMessageListener: function(msg) {
302 const data = JSON.parse(msg.data);
303 switch (data.code)
304 {
71468011
BA
305 case "pollclientsandgamers":
306 {
307 let identityAsked = {};
308 data.sockIds.forEach(s => {
309 if (s.sid != this.st.user.sid && !identityAsked[s.sid])
310 {
311 identityAsked[s.sid] = true;
312 this.send("askidentity", {target:s.sid});
313 }
314 if (!this.people[s.sid])
315 this.$set(this.people, s.sid, {id:0, name:"", pages:[s.page || "/"]});
316 else if (!!s.page && this.people[s.sid].pages.indexOf(s.page) < 0)
317 this.people[s.sid].pages.push(s.page);
318 if (!s.page)
319 this.send("askchallenge", {target:s.sid});
320 else
321 this.send("askgame", {target:s.sid});
5a3da968 322 });
ac8f441c 323 break;
71468011
BA
324 }
325 case "connect":
326 case "gconnect":
327 // NOTE: player could have been polled earlier, but might have logged in then
328 // So it's a good idea to ask identity if he was anonymous.
329 // But only ask game / challenge if currently disconnected.
330 if (!this.people[data.from])
331 {
332 this.$set(this.people, data.from, {name:"", id:0, pages:[data.page]});
333 if (data.code == "connect")
334 this.send("askchallenge", {target:data.from});
335 else
336 this.send("askgame", {target:data.from});
337 }
338 else
339 {
340 // append page if not already in list
341 if (this.people[data.from].pages.indexOf(data.page) < 0)
342 this.people[data.from].pages.push(data.page);
343 }
344 if (this.people[data.from].id == 0)
345 this.send("askidentity", {target:data.from});
346 break;
347 case "disconnect":
348 case "gdisconnect":
349 // Disconnect means no more tmpIds:
350 if (data.code == "disconnect")
351 {
352 this.$delete(this.people, data.from);
353 // Also remove all challenges sent by this player:
354 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
355 }
356 else
357 {
358 const pidx = this.people[data.from].pages.indexOf(data.page);
359 this.people[data.from].pages.splice(pageIdx, 1);
360 if (this.people[data.from].pages.length == 0)
361 {
362 this.$delete(this.people, data.from);
363 // And all live games where he plays and no other opponent is online
364 ArrayFun.remove(this.games, g =>
365 g.type == "live" && (g.players.every(p => p.sid == data.from
366 || !this.people[p.sid])), "all");
367 }
368 }
5a3da968 369 break;
81d9ce72 370 case "askidentity":
6855163c
BA
371 // Request for identification: reply if I'm not anonymous
372 if (this.st.user.id > 0)
373 {
71468011
BA
374 const me = {
375 // NOTE: decompose to avoid revealing email
376 name: this.st.user.name,
377 sid: this.st.user.sid,
378 id: this.st.user.id,
379 };
380 this.send("identity", {data:me, target:data.from});
6855163c 381 }
5a3da968 382 break;
dcd68c41 383 case "identity":
71468011
BA
384 {
385 const user = data.data;
386 this.$set(this.people, user.sid,
9335d45b 387 {
71468011
BA
388 id: user.id,
389 name: user.name,
390 pages: this.people[user.sid].pages,
9335d45b 391 });
71468011
BA
392
393// // TODO: smarter, if multi-connect, send to all instances... (several sid's)
394// // Or better: just prevent multi-connect.
395// // Fix anomaly: if registered player multi-connect, should be left only one
396// const anomalies = Object.keys(this.people).filter(sid => this.people[sid].id == user.id);
397// if (anomalies.length == 2)
398// this.$delete(this.people, anomalies[0]);
399// // --> this isn't good, some sid's are just forgetted
400
dcd68c41 401 break;
71468011 402 }
dd75774d 403 case "askchallenge":
1efe1d79 404 {
6855163c 405 // Send my current live challenge (if any)
5ea8d113
BA
406 const cIdx = this.challenges.findIndex(c =>
407 c.from.sid == this.st.user.sid && c.type == "live");
dd75774d
BA
408 if (cIdx >= 0)
409 {
410 const c = this.challenges[cIdx];
71468011
BA
411 // NOTE: in principle, should only send targeted challenge to the target.
412 // But we may not know yet the identity of the target (just name),
413 // so cannot decide if data.from is the target or not.
dd75774d
BA
414 const myChallenge =
415 {
2ada153c 416 id: c.id,
71468011 417 from: this.st.user.sid,
81d9ce72
BA
418 to: c.to,
419 fen: c.fen,
420 vid: c.vid,
71468011 421 cadence: c.cadence,
a64d9122 422 added: c.added,
dd75774d 423 };
71468011 424 this.send("challenge", {data:myChallenge, target:data.from});
81d9ce72
BA
425 }
426 break;
1efe1d79 427 }
71468011
BA
428 case "challenge": //after "askchallenge"
429 case "newchallenge":
430 {
a64d9122 431 // NOTE about next condition: see "askchallenge" case.
71468011
BA
432 const chall = data.data;
433 if (!chall.to || (this.people[chall.from].id > 0 &&
434 (chall.from == this.st.user.sid || chall.to == this.st.user.name)))
a64d9122 435 {
71468011
BA
436 let newChall = Object.assign({}, chall);
437 newChall.type = this.classifyObject(chall);
438 newChall.added = Date.now();
439 let fromValues = Object.assign({}, this.people[chall.from]);
440 delete fromValues["pages"]; //irrelevant in this context
441 newChall.from = Object.assign({sid:chall.from}, fromValues);
a64d9122
BA
442 newChall.vname = this.getVname(newChall.vid);
443 this.challenges.push(newChall);
444 }
81d9ce72 445 break;
71468011
BA
446 }
447 case "refusechallenge":
1efe1d79 448 {
71468011
BA
449 const cid = data.data;
450 ArrayFun.remove(this.challenges, c => c.id == cid);
451 alert(this.st.tr["Challenge declined"]);
452 break;
453 }
454 case "deletechallenge":
455 {
456 // NOTE: the challenge may be already removed
457 const cid = data.data;
458 ArrayFun.remove(this.challenges, c => c.id == cid);
459 break;
460 }
461 case "game": //individual request
462 case "newgame":
463 {
464 // NOTE: it may be live or correspondance
465 const game = data.data;
466 if (this.games.findIndex(g => g.id == game.id) < 0)
d9b86b16 467 {
71468011
BA
468 let newGame = game;
469 newGame.type = this.classifyObject(game);
470 newGame.vname = this.getVname(game.vid);
471 if (!game.score) //if new game from Hall
a64d9122 472 newGame.score = "*";
d9b86b16
BA
473 this.games.push(newGame);
474 }
81d9ce72 475 break;
1efe1d79 476 }
71468011
BA
477 case "startgame":
478 {
5d04793e 479 // New game just started: data contain all information
71468011
BA
480 const gameInfo = data.data;
481 if (this.classifyObject(gameInfo) == "live")
482 this.startNewGame(gameInfo);
5d04793e
BA
483 else
484 {
71468011
BA
485 this.infoMessage = this.st.tr["New correspondance game:"] +
486 " <a href='#/game/" + gameInfo.id + "'>" +
487 "#/game/" + gameInfo.id + "</a>";
dce792f6
BA
488 let modalBox = document.getElementById("modalInfo");
489 modalBox.checked = true;
3d55deea 490 setTimeout(() => { modalBox.checked = false; }, 3000);
5d04793e 491 }
9d58ef95 492 break;
71468011 493 }
ac8f441c 494 case "newchat":
71468011 495 this.newChat = data.data;
9d58ef95
BA
496 break;
497 }
498 },
a6bddfc6 499 // Challenge lifecycle:
9d58ef95 500 newChallenge: async function() {
25d18342 501 if (this.newchallenge.vid == "")
602d6bef 502 return alert(this.st.tr["Please select a variant"]);
a64d9122
BA
503 if (!!this.newchallenge.to && this.newchallenge.to == this.st.user.name)
504 return alert(this.st.tr["Self-challenge is forbidden"]);
bb7dd7db 505 const vname = this.getVname(this.newchallenge.vid);
1efe1d79
BA
506 const vModule = await import("@/variants/" + vname + ".js");
507 window.V = vModule.VariantRules;
71468011
BA
508 if (!!this.newchallenge.cadence.match(/^[0-9]+$/))
509 this.newchallenge.cadence += "+0"; //assume minutes, no increment
9d58ef95
BA
510 const error = checkChallenge(this.newchallenge);
511 if (!!error)
512 return alert(error);
2ada153c 513 const ctype = this.classifyObject(this.newchallenge);
098cd7f1 514 if (ctype == "corr" && this.st.user.id <= 0)
602d6bef 515 return alert(this.st.tr["Please log in to play correspondance games"]);
bb7dd7db 516 // NOTE: "from" information is not required here
a7808884 517 let chall = Object.assign({}, this.newchallenge);
71468011 518 const finishAddChallenge = (cid) => {
1efe1d79 519 chall.id = cid || "c" + getRandString();
fe4c7e67 520 // Remove old challenge if any (only one at a time of a given type):
5ea8d113 521 const cIdx = this.challenges.findIndex(c =>
fe4c7e67 522 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) && c.type == ctype);
5ea8d113
BA
523 if (cIdx >= 0)
524 {
525 // Delete current challenge (will be replaced now)
71468011 526 this.send("deletechallenge", {data:this.challenges[cIdx].id});
5ea8d113
BA
527 if (ctype == "corr")
528 {
529 ajax(
530 "/challenges",
531 "DELETE",
532 {id: this.challenges[cIdx].id}
533 );
534 }
535 this.challenges.splice(cIdx, 1);
536 }
71468011 537 this.send("newchallenge", {data:Object.assign({from:this.st.user.sid}, chall)});
5ea8d113 538 // Add new challenge:
dcd68c41
BA
539 chall.from = { //decompose to avoid revealing email
540 sid: this.st.user.sid,
541 id: this.st.user.id,
542 name: this.st.user.name,
543 };
71468011
BA
544 chall.added = Date.now();
545 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
546 chall.type = ctype;
547 chall.vname = vname;
1efe1d79 548 this.challenges.push(chall);
71468011
BA
549 // Remember cadence + vid for quicker further challenges:
550 localStorage.setItem("cadence", chall.cadence);
25d18342 551 localStorage.setItem("vid", chall.vid);
b4d619d1
BA
552 document.getElementById("modalNewgame").checked = false;
553 };
1efe1d79
BA
554 if (ctype == "live")
555 {
556 // Live challenges have a random ID
71468011 557 finishAddChallenge(null);
03608482 558 }
b4d619d1 559 else
03608482 560 {
b4d619d1 561 // Correspondance game: send challenge to server
03608482 562 ajax(
1efe1d79 563 "/challenges",
03608482 564 "POST",
bebcc8d4 565 { chall: chall },
1efe1d79 566 response => { finishAddChallenge(response.cid); }
03608482 567 );
9d58ef95 568 }
fb54f098 569 },
a6bddfc6 570 clickChallenge: function(c) {
485fccd5
BA
571 const myChallenge = (c.from.sid == this.st.user.sid //live
572 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
573 if (!myChallenge)
a6bddfc6 574 {
3d55deea 575 if (c.type == "corr" && this.st.user.id <= 0)
602d6bef 576 return alert(this.st.tr["Please log in to accept corr challenges"]);
a6bddfc6 577 c.accepted = true;
485fccd5 578 if (!!c.to) //c.to == this.st.user.name (connected)
a6bddfc6
BA
579 {
580 // TODO: if special FEN, show diagram after loading variant
581 c.accepted = confirm("Accept challenge?");
582 }
485fccd5 583 if (c.accepted)
36093eba 584 {
dcd68c41
BA
585 c.seat = { //again, avoid c.seat = st.user to not reveal email
586 sid: this.st.user.sid,
587 id: this.st.user.id,
588 name: this.st.user.name,
589 };
485fccd5
BA
590 this.launchGame(c);
591 }
592 else
593 {
71468011 594 this.send("refusechallenge", {data:c.id, target:c.from.sid});
36093eba 595 }
71468011 596 this.send("deletechallenge", {data:c.id});
a6bddfc6 597 }
2be5d614 598 else //my challenge
485fccd5 599 {
2be5d614
BA
600 if (c.type == "corr")
601 {
602 ajax(
603 "/challenges",
604 "DELETE",
605 {id: c.id}
606 );
607 }
71468011 608 this.send("deletechallenge", {data:c.id});
485fccd5 609 }
5ea8d113 610 // In all cases, the challenge is consumed:
3d55deea 611 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
a6bddfc6 612 },
a64d9122 613 // NOTE: when launching game, the challenge is already being deleted
36093eba 614 launchGame: async function(c) {
a9b131f1 615 const vModule = await import("@/variants/" + c.vname + ".js");
a6bddfc6 616 window.V = vModule.VariantRules;
71468011
BA
617 // These game informations will be shared
618 let gameInfo =
a6bddfc6 619 {
11667c79 620 id: getRandString(),
a6bddfc6 621 fen: c.fen || V.GenRandInitFen(),
5d04793e 622 players: shuffle([c.from, c.seat]), //white then black
a6bddfc6 623 vid: c.vid,
71468011 624 cadence: c.cadence,
a6bddfc6 625 };
5ea8d113
BA
626 let oppsid = c.from.sid; //may not be defined if corr + offline opp
627 if (!oppsid)
8c564f46 628 {
5ea8d113 629 oppsid = Object.keys(this.people).find(sid =>
dcd68c41 630 this.people[sid].id == c.from.id);
8c564f46 631 }
71468011 632 const notifyNewgame = () => {
5ea8d113 633 if (!!oppsid) //opponent is online
71468011
BA
634 this.send("startgame", {data:gameInfo, target:oppsid});
635 // Send game info (only if live) to everyone except me in this tab
636 this.send("newgame", {data:gameInfo});
411d23cd 637 };
485fccd5 638 if (c.type == "live")
411d23cd 639 {
71468011 640 notifyNewgame();
485fccd5 641 this.startNewGame(gameInfo);
411d23cd 642 }
485fccd5
BA
643 else //corr: game only on server
644 {
645 ajax(
646 "/games",
647 "POST",
2be5d614 648 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
411d23cd 649 response => {
11667c79 650 gameInfo.id = response.gameId;
71468011 651 notifyNewgame();
411d23cd
BA
652 this.$router.push("/game/" + response.gameId);
653 }
485fccd5
BA
654 );
655 }
fb54f098 656 },
a9b131f1 657 // NOTE: for live games only (corr games start on the server)
42c15a75 658 startNewGame: function(gameInfo) {
25996aed
BA
659 const game = Object.assign({}, gameInfo, {
660 // (other) Game infos: constant
6d01bb17 661 fenStart: gameInfo.fen,
71468011
BA
662 vname: this.getVname(gameInfo.vid),
663 created: Date.now(),
25996aed 664 // Game state (including FEN): will be updated
967a2686 665 moves: [],
a9b131f1 666 clocks: [-1, -1], //-1 = unstarted
66d03f23 667 initime: [0, 0], //initialized later
967a2686 668 score: "*",
a7808884 669 });
967a2686 670 GameStorage.add(game);
7b626bdd
BA
671 if (this.st.settings.sound >= 1)
672 new Audio("/sounds/newgame.mp3").play().catch(err => {});
11667c79 673 this.$router.push("/game/" + gameInfo.id);
1efe1d79 674 },
fb54f098 675 },
85e5b5c1 676};
ccd4a2b7 677</script>
85e5b5c1 678
41c80bb6 679<style lang="sass" scoped>
5bcc9b31
BA
680.active
681 color: #42a983
9ca1e26b
BA
682#newGame
683 display: block
72ccbd67 684 margin: 10px auto 5px auto
ed06d9e9
BA
685#people
686 width: 100%
687#players
688 width: 50%
689 position: relative
690 float: left
691#chat
692 width: 50%
693 float: left
694 position: relative
695@media screen and (max-width: 767px)
696 #players, #chats
697 width: 100%
72ccbd67
BA
698#chat > .card
699 max-width: 100%
700 margin: 0;
701 border: none;
41c80bb6 702#players > p
ed06d9e9 703 margin-left: 5px
dcd68c41
BA
704.anonymous
705 font-style: italic
706button.player-action
41c80bb6 707 margin-left: 32px
85e5b5c1 708</style>