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