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