Fixes, 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 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
2f258c37 55 div#div2
ed06d9e9 56 .button-group
2f258c37 57 button.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
602d6bef 58 | {{ st.tr["Live challenges"] }}
2f258c37 59 button.tabbtn#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")
2f258c37 65 div#div3
ed06d9e9 66 .button-group
2f258c37 67 button.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
602d6bef 68 | {{ st.tr["Live games"] }}
2f258c37 69 button.tabbtn#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 => {
145 this.games = this.games.concat(response.games.map(g => {
146 const type = this.classifyObject(g);
147 const vname = this.getVname(g.vid);
148 return Object.assign({}, g, {type: type, vname: vname});
149 }));
150 }
151 );
fe4c7e67 152 // Also ask for corr challenges (open + sent by/to me)
3d55deea
BA
153 ajax(
154 "/challenges",
155 "GET",
156 {uid: this.st.user.id},
157 response => {
158 // Gather all senders names, and then retrieve full identity:
159 // (TODO [perf]: some might be online...)
fe4c7e67
BA
160 let names = {};
161 response.challenges.forEach(c => {
162 if (c.uid != this.st.user.id)
163 names[c.uid] = ""; //unknwon for now
164 else if (!!c.target && c.target != this.st.user.id)
165 names[c.target] = "";
166 });
167 const addChallenges = (newChalls) => {
168 names[this.st.user.id] = this.st.user.name; //in case of
169 this.challenges = this.challenges.concat(
170 response.challenges.map(c => {
171 const from = {name: names[c.uid], id: c.uid}; //or just name
172 const type = this.classifyObject(c);
173 const vname = this.getVname(c.vid);
174 return Object.assign({},
175 {
176 type: type,
177 vname: vname,
178 from: from,
179 to: (!!c.target ? names[c.target] : ""),
180 },
181 c);
182 })
183 );
184 };
bd76b456 185 if (Object.keys(names).length > 0)
fe4c7e67
BA
186 {
187 ajax("/users",
188 "GET",
189 { ids: Object.keys(names).join(",") },
190 response2 => {
191 response2.users.forEach(u => {names[u.id] = u.name});
192 addChallenges();
193 }
194 );
195 }
196 else
197 addChallenges();
3d55deea
BA
198 }
199 );
71468011
BA
200 const connectAndPoll = () => {
201 this.send("connect");
202 this.send("pollclientsandgamers");
4d64881e 203 };
8418f0d7 204 // Initialize connection
51d87b52 205 this.connexionString = params.socketUrl +
8418f0d7 206 "/?sid=" + this.st.user.sid +
71468011
BA
207 "&tmpId=" + getRandString() +
208 "&page=" + encodeURIComponent(this.$route.path);
51d87b52 209 this.conn = new WebSocket(this.connexionString);
71468011 210 this.conn.onopen = connectAndPoll;
8418f0d7 211 this.conn.onmessage = this.socketMessageListener;
51d87b52 212 this.conn.onclose = this.socketCloseListener;
9d58ef95 213 },
25d18342 214 mounted: function() {
bd76b456
BA
215 ["peopleWrap","infoDiv","newgameDiv"].forEach(eltName => {
216 let elt = document.getElementById(eltName);
217 elt.addEventListener("click", processModalClick);
218 });
71468011 219 document.querySelectorAll("#predefinedCadences > button").forEach(
25d18342 220 (b) => { b.addEventListener("click",
71468011 221 () => { this.newchallenge.cadence = b.innerHTML; }
25d18342
BA
222 )}
223 );
2f258c37
BA
224 const showCtype = localStorage.getItem("type-challenges") || "live";
225 const showGtype = localStorage.getItem("type-games") || "live";
226 this.setDisplay('c', showCtype);
227 this.setDisplay('g', showGtype);
25d18342 228 },
8418f0d7 229 beforeDestroy: function() {
71468011 230 this.send("disconnect");
8418f0d7 231 },
fb54f098 232 methods: {
a6bddfc6 233 // Helpers:
71468011 234 send: function(code, obj) {
51d87b52
BA
235 if (!!this.conn)
236 {
237 this.conn.send(JSON.stringify(
238 Object.assign(
239 {code: code},
240 obj,
241 )
242 ));
243 }
71468011
BA
244 },
245 getVname: function(vid) {
246 const variant = this.st.variants.find(v => v.id == vid);
247 // this.st.variants might be uninitialized (variant == null)
248 return (!!variant ? variant.name : "");
249 },
6855163c
BA
250 filterChallenges: function(type) {
251 return this.challenges.filter(c => c.type == type);
252 },
253 filterGames: function(type) {
a9b131f1 254 return this.games.filter(g => g.type == type);
6855163c 255 },
2ada153c 256 classifyObject: function(o) { //challenge or game
71468011 257 return (o.cadence.indexOf('d') === -1 ? "live" : "corr");
a6bddfc6 258 },
5bcc9b31
BA
259 setDisplay: function(letter, type, e) {
260 this[letter + "display"] = type;
2f258c37 261 localStorage.setItem("type-" + (letter == 'c' ? "challenges" : "games"), type);
7f36b53a
BA
262 let elt = !!e
263 ? e.target
264 : document.getElementById("btn" + letter.toUpperCase() + type);
265 elt.classList.add("active");
2f258c37 266 elt.classList.remove("somethingnew"); //in case of
7f36b53a
BA
267 if (!!elt.previousElementSibling)
268 elt.previousElementSibling.classList.remove("active");
5bcc9b31 269 else
7f36b53a
BA
270 elt.nextElementSibling.classList.remove("active");
271 },
272 isGamer: function(sid) {
273 return this.people[sid].pages.some(p => p.indexOf("/game/") >= 0);
274 },
71468011
BA
275 getActionLabel: function(sid) {
276 return this.people[sid].pages.some(p => p == "/")
277 ? "Challenge"
278 : "Observe";
ac8f441c 279 },
71468011
BA
280 challOrWatch: function(sid) {
281 if (this.people[sid].pages.some(p => p == "/"))
a6bddfc6 282 {
71468011
BA
283 // Available, in Hall
284 this.newchallenge.to = this.people[sid].name;
3e4e742c 285 document.getElementById("modalPeople").checked = false;
71468011 286 doClick("modalNewgame");
a6bddfc6 287 }
9335d45b
BA
288 else
289 {
7f36b53a
BA
290 // In some game, maybe playing maybe not: show a random one
291 let gids = [];
292 this.people[sid].pages.forEach(p => {
293 const matchGid = p.match(/[a-zA-Z0-9]+$/);
294 if (!!matchGid)
295 gids.push(matchGid[0]);
296 });
297 const gid = gids[Math.floor(Math.random() * gids.length)];
51d87b52 298 this.showGame(this.games.find(g => g.id == gid));
71468011
BA
299 }
300 },
51d87b52 301 showGame: function(g) {
71468011
BA
302 // NOTE: we are an observer, since only games I don't play are shown here
303 // ==> Moves sent by connected remote player(s) if live game
304 let url = "/game/" + g.id;
305 if (g.type == "live")
51d87b52 306 url += "?rid=" + g.rids[Math.floor(Math.random() * g.rids.length)];
71468011
BA
307 this.$router.push(url);
308 },
bd76b456
BA
309 resetChatColor: function() {
310 // TODO: this is called twice, once on opening an once on closing
2f258c37 311 document.getElementById("peopleBtn").classList.remove("somethingnew");
bd76b456 312 },
71468011
BA
313 processChat: function(chat) {
314 this.send("newchat", {data:chat});
a6bddfc6
BA
315 },
316 // Messaging center:
9d58ef95 317 socketMessageListener: function(msg) {
51d87b52
BA
318 if (!this.conn)
319 return;
9d58ef95
BA
320 const data = JSON.parse(msg.data);
321 switch (data.code)
322 {
71468011
BA
323 case "pollclientsandgamers":
324 {
51d87b52
BA
325 // Since people can be both in Hall and Game,
326 // need to track "askIdentity" requests:
71468011
BA
327 let identityAsked = {};
328 data.sockIds.forEach(s => {
7f36b53a 329 const page = s.page || "/";
71468011
BA
330 if (s.sid != this.st.user.sid && !identityAsked[s.sid])
331 {
332 identityAsked[s.sid] = true;
7f36b53a 333 this.send("askidentity", {target:s.sid, page:page});
71468011
BA
334 }
335 if (!this.people[s.sid])
7f36b53a
BA
336 this.$set(this.people, s.sid, {id:0, name:"", pages:[page]});
337 else if (this.people[s.sid].pages.indexOf(page) < 0)
338 this.people[s.sid].pages.push(page);
51d87b52 339 if (!s.page) //peer is in Hall
71468011 340 this.send("askchallenge", {target:s.sid});
51d87b52 341 else //peer is in Game
7f36b53a 342 this.send("askgame", {target:s.sid, page:page});
5a3da968 343 });
ac8f441c 344 break;
71468011
BA
345 }
346 case "connect":
347 case "gconnect":
7f36b53a
BA
348 {
349 const page = data.page || "/";
71468011
BA
350 // NOTE: player could have been polled earlier, but might have logged in then
351 // So it's a good idea to ask identity if he was anonymous.
352 // But only ask game / challenge if currently disconnected.
353 if (!this.people[data.from])
354 {
7f36b53a 355 this.$set(this.people, data.from, {name:"", id:0, pages:[page]});
71468011
BA
356 if (data.code == "connect")
357 this.send("askchallenge", {target:data.from});
358 else
7f36b53a 359 this.send("askgame", {target:data.from, page:page});
71468011
BA
360 }
361 else
362 {
363 // append page if not already in list
7f36b53a
BA
364 if (this.people[data.from].pages.indexOf(page) < 0)
365 this.people[data.from].pages.push(page);
71468011
BA
366 }
367 if (this.people[data.from].id == 0)
51d87b52
BA
368 {
369 this.newConnect[data.from] = true; //for self multi-connects tests
7f36b53a 370 this.send("askidentity", {target:data.from, page:page});
51d87b52 371 }
71468011 372 break;
7f36b53a 373 }
71468011
BA
374 case "disconnect":
375 case "gdisconnect":
092de306
BA
376 // If the user reloads the page twice very quickly (experienced with Firefox),
377 // the first reload won't have time to connect but will trigger a "close" event anyway.
378 // ==> Next check is required.
7f36b53a 379 if (!this.people[data.from])
092de306 380 return;
71468011
BA
381 // Disconnect means no more tmpIds:
382 if (data.code == "disconnect")
383 {
51d87b52 384 // Remove the live challenge sent by this player:
71468011
BA
385 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
386 }
387 else
388 {
51d87b52
BA
389 // Remove the matching live game if now unreachable
390 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
391 const gidx = this.games.findIndex(g => g.id == gid);
392 if (gidx >= 0)
71468011 393 {
51d87b52
BA
394 const game = this.games[gidx];
395 if (game.type == "live" &&
396 game.rids.length == 1 && game.rids[0] == data.from)
397 {
398 this.games.splice(gidx, 1);
399 }
71468011
BA
400 }
401 }
51d87b52
BA
402 const page = data.page || "/";
403 ArrayFun.remove(this.people[data.from].pages, p => p == page);
404 if (this.people[data.from].pages.length == 0)
405 this.$delete(this.people, data.from);
406 break;
407 case "killed":
408 // I logged in elsewhere:
409 alert(this.st.tr["New connexion detected: tab now offline"]);
410 // TODO: this fails. See https://github.com/websockets/ws/issues/489
411 //this.conn.removeEventListener("message", this.socketMessageListener);
412 //this.conn.removeEventListener("close", this.socketCloseListener);
413 //this.conn.close();
414 this.conn = null;
5a3da968 415 break;
81d9ce72 416 case "askidentity":
51d87b52
BA
417 {
418 // Request for identification (TODO: anonymous shouldn't need to reply)
419 const me = {
420 // Decompose to avoid revealing email
421 name: this.st.user.name,
422 sid: this.st.user.sid,
423 id: this.st.user.id,
424 };
425 this.send("identity", {data:me, target:data.from});
5a3da968 426 break;
51d87b52 427 }
dcd68c41 428 case "identity":
71468011
BA
429 {
430 const user = data.data;
51d87b52
BA
431 if (!!user.name) //otherwise anonymous
432 {
433 // If I multi-connect, kill current connexion if no mark (I'm older)
434 if (this.newConnect[user.sid] && user.id > 0
435 && user.id == this.st.user.id && user.sid != this.st.user.sid)
9335d45b 436 {
51d87b52
BA
437 if (!this.killed[this.st.user.sid])
438 {
439 this.send("killme", {sid:this.st.user.sid});
440 this.killed[this.st.user.sid] = true;
441 }
442 }
443 if (user.sid != this.st.user.sid) //I already know my identity...
444 {
445 this.$set(this.people, user.sid,
446 {
447 id: user.id,
448 name: user.name,
449 pages: this.people[user.sid].pages,
450 });
451 }
452 }
453 delete this.newConnect[user.sid];
dcd68c41 454 break;
71468011 455 }
dd75774d 456 case "askchallenge":
1efe1d79 457 {
6855163c 458 // Send my current live challenge (if any)
5ea8d113
BA
459 const cIdx = this.challenges.findIndex(c =>
460 c.from.sid == this.st.user.sid && c.type == "live");
dd75774d
BA
461 if (cIdx >= 0)
462 {
463 const c = this.challenges[cIdx];
71468011
BA
464 // NOTE: in principle, should only send targeted challenge to the target.
465 // But we may not know yet the identity of the target (just name),
466 // so cannot decide if data.from is the target or not.
dd75774d
BA
467 const myChallenge =
468 {
2ada153c 469 id: c.id,
71468011 470 from: this.st.user.sid,
81d9ce72
BA
471 to: c.to,
472 fen: c.fen,
473 vid: c.vid,
71468011 474 cadence: c.cadence,
a64d9122 475 added: c.added,
dd75774d 476 };
71468011 477 this.send("challenge", {data:myChallenge, target:data.from});
81d9ce72
BA
478 }
479 break;
1efe1d79 480 }
71468011
BA
481 case "challenge": //after "askchallenge"
482 case "newchallenge":
483 {
a64d9122 484 // NOTE about next condition: see "askchallenge" case.
71468011
BA
485 const chall = data.data;
486 if (!chall.to || (this.people[chall.from].id > 0 &&
487 (chall.from == this.st.user.sid || chall.to == this.st.user.name)))
a64d9122 488 {
71468011
BA
489 let newChall = Object.assign({}, chall);
490 newChall.type = this.classifyObject(chall);
491 newChall.added = Date.now();
492 let fromValues = Object.assign({}, this.people[chall.from]);
493 delete fromValues["pages"]; //irrelevant in this context
494 newChall.from = Object.assign({sid:chall.from}, fromValues);
a64d9122
BA
495 newChall.vname = this.getVname(newChall.vid);
496 this.challenges.push(newChall);
2f258c37
BA
497 if ((newChall.type == "live" && this.cdisplay == "corr") ||
498 (newChall.type == "corr" && this.cdisplay == "live"))
499 {
500 document.getElementById("btnC" + newChall.type).classList.add("somethingnew");
501 }
a64d9122 502 }
81d9ce72 503 break;
71468011
BA
504 }
505 case "refusechallenge":
1efe1d79 506 {
71468011
BA
507 const cid = data.data;
508 ArrayFun.remove(this.challenges, c => c.id == cid);
509 alert(this.st.tr["Challenge declined"]);
510 break;
511 }
512 case "deletechallenge":
513 {
514 // NOTE: the challenge may be already removed
515 const cid = data.data;
516 ArrayFun.remove(this.challenges, c => c.id == cid);
517 break;
518 }
519 case "game": //individual request
520 case "newgame":
521 {
522 // NOTE: it may be live or correspondance
523 const game = data.data;
51d87b52
BA
524 let locGame = this.games.find(g => g.id == game.id);
525 if (!locGame)
d9b86b16 526 {
71468011
BA
527 let newGame = game;
528 newGame.type = this.classifyObject(game);
529 newGame.vname = this.getVname(game.vid);
530 if (!game.score) //if new game from Hall
a64d9122 531 newGame.score = "*";
f5f51daf
BA
532 newGame.rids = [game.rid];
533 delete newGame["rid"];
d9b86b16 534 this.games.push(newGame);
2f258c37
BA
535 if ((newGame.type == "live" && this.gdisplay == "corr") ||
536 (newGame.type == "corr" && this.gdisplay == "live"))
537 {
538 document.getElementById("btnG" + newGame.type).classList.add("somethingnew");
539 }
d9b86b16 540 }
51d87b52
BA
541 else
542 {
543 // Append rid (if not already in list)
544 if (!locGame.rids.includes(game.rid))
545 locGame.rids.push(game.rid);
546 }
81d9ce72 547 break;
1efe1d79 548 }
48ab808f
BA
549 case "result":
550 {
551 let g = this.games.find(g => g.id == data.gid);
552 if (!!g)
553 g.score = data.score;
554 break;
555 }
71468011
BA
556 case "startgame":
557 {
5d04793e 558 // New game just started: data contain all information
71468011
BA
559 const gameInfo = data.data;
560 if (this.classifyObject(gameInfo) == "live")
561 this.startNewGame(gameInfo);
5d04793e
BA
562 else
563 {
71468011
BA
564 this.infoMessage = this.st.tr["New correspondance game:"] +
565 " <a href='#/game/" + gameInfo.id + "'>" +
566 "#/game/" + gameInfo.id + "</a>";
dce792f6
BA
567 let modalBox = document.getElementById("modalInfo");
568 modalBox.checked = true;
5d04793e 569 }
9d58ef95 570 break;
71468011 571 }
ac8f441c 572 case "newchat":
71468011 573 this.newChat = data.data;
bd76b456 574 if (!document.getElementById("modalPeople").checked)
2f258c37 575 document.getElementById("peopleBtn").classList.add("somethingnew");
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
a154d45e
BA
769
770#infoDiv > .card
f854c94f
BA
771 padding: 15px 0
772 max-width: 430px
a154d45e
BA
773
774#newgameDiv > .card
775 max-width: 767px
776 max-height: 100%
777
bd76b456
BA
778div#peopleWrap > .card
779 max-height: 100%
780
781@media screen and (min-width: 1281px)
782 div#peopleWrap > .card
783 max-width: 66.67%
784
785@media screen and (max-width: 1280px)
786 div#peopleWrap > .card
787 max-width: 83.33%
788
789@media screen and (max-width: 767px)
790 div#peopleWrap > .card
791 max-width: 100%
792
ed06d9e9
BA
793#players
794 width: 50%
795 position: relative
796 float: left
797#chat
798 width: 50%
799 float: left
800 position: relative
801@media screen and (max-width: 767px)
802 #players, #chats
803 width: 100%
72ccbd67
BA
804#chat > .card
805 max-width: 100%
806 margin: 0;
807 border: none;
41c80bb6 808#players > p
ed06d9e9 809 margin-left: 5px
dcd68c41
BA
810.anonymous
811 font-style: italic
812button.player-action
41c80bb6 813 margin-left: 32px
2f258c37
BA
814
815.somethingnew
816 background-color: #c5fefe !important
817
818.tabbtn
819 background-color: white
820
821#div2, #div3
822 margin-top: 15px
823@media screen and (max-width: 767px)
824 #div2, #div3
825 margin-top: 0
85e5b5c1 826</style>