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