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