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