debugging attempt
[vchess.git] / client / src / views / Hall.vue
CommitLineData
ccd4a2b7 1<template lang="pug">
9d58ef95 2main
dce792f6 3 input#modalInfo.modal(type="checkbox")
910d631b
BA
4 div#infoDiv(
5 role="dialog"
6 data-checkbox="modalInfo"
7 )
a154d45e 8 .card.text-center
dce792f6 9 label.modal-close(for="modalInfo")
a154d45e 10 p(v-html="infoMessage")
725da57f
BA
11 input#modalAccept.modal(type="checkbox")
12 div#acceptDiv(role="dialog")
13 .card.text-center
14 p
15 span.variantName {{ curChallToAccept.vname }}
16 span {{ curChallToAccept.cadence }}
17 span {{ st.tr["with"] + " " + curChallToAccept.from.name }}
18 .diagram(v-html="tchallDiag")
19 .button-group#buttonsTchall
20 button.acceptBtn(@click="decisionChallenge(true)") {{ st.tr["Accept challenge?"] }}
21 button.refuseBtn(@click="decisionChallenge(false)") {{ st.tr["Refuse"] }}
09d37571
BA
22 input#modalNewgame.modal(
23 type="checkbox"
24 @change="cadenceFocusIfOpened($event)"
25 )
910d631b
BA
26 div#newgameDiv(
27 role="dialog"
28 data-checkbox="modalNewgame"
29 )
89021f18 30 .card
5b020e73 31 label#closeNewgame.modal-close(for="modalNewgame")
725da57f 32 div(@keyup.enter="newChallenge()")
89021f18
BA
33 fieldset
34 label(for="selectVariant") {{ st.tr["Variant"] }} *
725da57f
BA
35 select#selectVariant(
36 @change="loadNewchallVariant(trySetNewchallDiag)"
37 v-model="newchallenge.vid"
38 )
910d631b
BA
39 option(
40 v-for="v in st.variants"
41 :value="v.id"
42 :selected="newchallenge.vid==v.id"
43 )
89021f18
BA
44 | {{ v.name }}
45 fieldset
46 label(for="cadence") {{ st.tr["Cadence"] }} *
47 div#predefinedCadences
8477e53d 48 button(type="button") 15+5
8aa418f6 49 button(type="button") 45+30
92240cf0
BA
50 button(type="button") 3d
51 button(type="button") 7d
910d631b
BA
52 input#cadence(
53 type="text"
54 v-model="newchallenge.cadence"
92240cf0 55 placeholder="5+0, 1h+30s, 5d ..."
910d631b 56 )
7ba4a5bc
BA
57 fieldset
58 label(for="selectRandomLevel") {{ st.tr["Randomness"] }}
59 select#selectRandomLevel(v-model="newchallenge.randomness")
60 option(value="0") {{ st.tr["Deterministic"] }}
61 option(value="1") {{ st.tr["Symmetric random"] }}
62 option(value="2") {{ st.tr["Asymmetric random"] }}
89021f18
BA
63 fieldset(v-if="st.user.id > 0")
64 label(for="selectPlayers") {{ st.tr["Play with?"] }}
910d631b
BA
65 input#selectPlayers(
66 type="text"
67 v-model="newchallenge.to"
68 )
89021f18 69 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
910d631b 70 input#inputFen(
725da57f
BA
71 placeholder="FEN"
72 @input="trySetNewchallDiag()"
910d631b
BA
73 type="text"
74 v-model="newchallenge.fen"
75 )
725da57f 76 .diagram(v-html="newchallenge.diag")
9ddaf8da 77 button(@click="newChallenge()") {{ st.tr["Send challenge"] }}
910d631b
BA
78 input#modalPeople.modal(
79 type="checkbox"
efdfb4c7 80 @click="resetSocialColor()"
910d631b
BA
81 )
82 div#peopleWrap(
83 role="dialog"
84 data-checkbox="modalPeople"
85 )
bd76b456
BA
86 .card
87 label.modal-close(for="modalPeople")
88 #people
89 #players
910d631b
BA
90 p(
91 v-for="sid in Object.keys(people)"
efdfb4c7 92 v-if="people[sid].name"
910d631b 93 )
bd76b456 94 span {{ people[sid].name }}
910d631b 95 button.player-action(
21771bb9 96 v-if="isGamer(sid) || (st.user.id > 0 && sid!=st.user.sid)"
910d631b
BA
97 @click="challOrWatch(sid)"
98 )
bd76b456
BA
99 | {{ getActionLabel(sid) }}
100 p.anonymous @nonymous ({{ anonymousCount }})
101 #chat
910d631b
BA
102 Chat(
103 :newChat="newChat"
104 @mychat="processChat"
105 :pastChats="[]"
106 )
bd76b456 107 .clearer
9d58ef95 108 .row
bd76b456
BA
109 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
110 .button-group
910d631b 111 button#peopleBtn(onClick="window.doClick('modalPeople')")
8a0f881d 112 | {{ st.tr["Who's there?"] }}
910d631b
BA
113 button(onClick="window.doClick('modalNewgame')")
114 | {{ st.tr["New game"] }}
9d58ef95 115 .row
9ca1e26b 116 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
2f258c37 117 div#div2
ed06d9e9 118 .button-group
2f258c37 119 button.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
602d6bef 120 | {{ st.tr["Live challenges"] }}
2f258c37 121 button.tabbtn#btnCcorr(@click="setDisplay('c','corr',$event)")
602d6bef 122 | {{ st.tr["Correspondance challenges"] }}
910d631b
BA
123 ChallengeList(
124 v-show="cdisplay=='live'"
125 :challenges="filterChallenges('live')"
126 @click-challenge="clickChallenge"
127 )
128 ChallengeList(
129 v-show="cdisplay=='corr'"
130 :challenges="filterChallenges('corr')"
131 @click-challenge="clickChallenge"
132 )
2f258c37 133 div#div3
ed06d9e9 134 .button-group
2f258c37 135 button.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
602d6bef 136 | {{ st.tr["Live games"] }}
2f258c37 137 button.tabbtn#btnGcorr(@click="setDisplay('g','corr',$event)")
602d6bef 138 | {{ st.tr["Correspondance games"] }}
910d631b
BA
139 GameList(
140 v-show="gdisplay=='live'"
141 :games="filterGames('live')"
142 :showBoth="true"
143 @show-game="showGame"
144 )
145 GameList(
146 v-show="gdisplay=='corr'"
147 :games="filterGames('corr')"
148 :showBoth="true"
149 @show-game="showGame"
150 )
625022fd
BA
151</template>
152
153<script>
5b020e73 154import { store } from "@/store";
9d58ef95
BA
155import { checkChallenge } from "@/data/challengeCheck";
156import { ArrayFun } from "@/utils/array";
03608482 157import { ajax } from "@/utils/ajax";
8418f0d7 158import params from "@/parameters";
4b0384fa 159import { getRandString, shuffle } from "@/utils/alea";
725da57f 160import { getDiagram } from "@/utils/printDiagram";
603b8a8b 161import Chat from "@/components/Chat.vue";
5b020e73
BA
162import GameList from "@/components/GameList.vue";
163import ChallengeList from "@/components/ChallengeList.vue";
967a2686 164import { GameStorage } from "@/utils/gameStorage";
602d6bef 165import { processModalClick } from "@/utils/modalClick";
625022fd 166export default {
cf2343ce 167 name: "my-hall",
5b020e73 168 components: {
603b8a8b 169 Chat,
5b020e73 170 GameList,
6808d7a1 171 ChallengeList
5b020e73 172 },
6808d7a1 173 data: function() {
fb54f098 174 return {
5b020e73 175 st: store.state,
6855163c 176 cdisplay: "live", //or corr
fb54f098 177 gdisplay: "live",
6855163c 178 games: [],
b4d619d1 179 challenges: [],
71468011 180 people: {},
3d55deea 181 infoMessage: "",
9d58ef95 182 newchallenge: {
fb54f098 183 fen: "",
725da57f 184 vid: parseInt(localStorage.getItem("vid")) || 0,
6fba6e0c 185 to: "", //name of challenged player (if any)
725da57f 186 cadence: localStorage.getItem("cadence") || "",
7ba4a5bc 187 randomness: parseInt(localStorage.getItem("randomness")) || 2,
725da57f
BA
188 // VariantRules object, stored to not interfere with
189 // diagrams of targetted challenges:
190 V: null,
191 vname: "",
192 diag: "" //visualizing FEN
fb54f098 193 },
725da57f
BA
194 tchallDiag: "",
195 curChallToAccept: {from: {}},
ac8f441c 196 newChat: "",
8418f0d7 197 conn: null,
51d87b52
BA
198 connexionString: "",
199 // Related to (killing of) self multi-connects:
200 newConnect: {},
6808d7a1 201 killed: {}
fb54f098
BA
202 };
203 },
fd7aea36
BA
204 watch: {
205 // st.variants changes only once, at loading from [] to [...]
6808d7a1 206 "st.variants": function() {
fd7aea36 207 // Set potential challenges and games variant names:
71468011 208 this.challenges.concat(this.games).forEach(o => {
6808d7a1 209 if (o.vname == "") o.vname = this.getVname(o.vid);
fd7aea36 210 });
725da57f
BA
211 if (!this.newchallenge.V && this.newchallenge.vid > 0)
212 this.loadNewchallVariant();
6808d7a1 213 }
fd7aea36 214 },
b4d619d1 215 computed: {
ed06d9e9
BA
216 anonymousCount: function() {
217 let count = 0;
6808d7a1 218 Object.values(this.people).forEach(p => {
efdfb4c7
BA
219 // Do not cound people who did not send their identity yet:
220 count += (!p.name && p.id === 0) ? 1 : 0;
6808d7a1 221 });
ed06d9e9 222 return count;
6808d7a1 223 }
b4d619d1 224 },
9d58ef95 225 created: function() {
725da57f
BA
226 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
227 this.loadNewchallVariant();
66d03f23 228 const my = this.st.user;
6808d7a1 229 this.$set(this.people, my.sid, { id: my.id, name: my.name, pages: ["/"] });
3d55deea
BA
230 // Ask server for current corr games (all but mines)
231 ajax(
232 "/games",
233 "GET",
6808d7a1 234 { uid: this.st.user.id, excluded: true },
3d55deea 235 response => {
6808d7a1
BA
236 this.games = this.games.concat(
237 response.games.map(g => {
238 const type = this.classifyObject(g);
239 const vname = this.getVname(g.vid);
240 return Object.assign({}, g, { type: type, vname: vname });
241 })
242 );
3d55deea
BA
243 }
244 );
fe4c7e67 245 // Also ask for corr challenges (open + sent by/to me)
6808d7a1
BA
246 ajax("/challenges", "GET", { uid: this.st.user.id }, response => {
247 // Gather all senders names, and then retrieve full identity:
248 // (TODO [perf]: some might be online...)
249 let names = {};
250 response.challenges.forEach(c => {
251 if (c.uid != this.st.user.id) names[c.uid] = "";
6808d7a1
BA
252 else if (!!c.target && c.target != this.st.user.id)
253 names[c.target] = "";
254 });
255 const addChallenges = () => {
256 names[this.st.user.id] = this.st.user.name; //in case of
257 this.challenges = this.challenges.concat(
258 response.challenges.map(c => {
259 const from = { name: names[c.uid], id: c.uid }; //or just name
260 const type = this.classifyObject(c);
261 const vname = this.getVname(c.vid);
262 return Object.assign(
263 {},
264 {
265 type: type,
266 vname: vname,
267 from: from,
268 to: c.target ? names[c.target] : ""
269 },
270 c
271 );
272 })
273 );
274 };
275 if (Object.keys(names).length > 0) {
276 ajax(
277 "/users",
278 "GET",
279 { ids: Object.keys(names).join(",") },
280 response2 => {
281 response2.users.forEach(u => {
282 names[u.id] = u.name;
283 });
284 addChallenges();
285 }
286 );
287 } else addChallenges();
288 });
71468011
BA
289 const connectAndPoll = () => {
290 this.send("connect");
291 this.send("pollclientsandgamers");
4d64881e 292 };
8418f0d7 293 // Initialize connection
6808d7a1
BA
294 this.connexionString =
295 params.socketUrl +
296 "/?sid=" +
297 this.st.user.sid +
298 "&tmpId=" +
299 getRandString() +
300 "&page=" +
301 encodeURIComponent(this.$route.path);
51d87b52 302 this.conn = new WebSocket(this.connexionString);
71468011 303 this.conn.onopen = connectAndPoll;
8418f0d7 304 this.conn.onmessage = this.socketMessageListener;
51d87b52 305 this.conn.onclose = this.socketCloseListener;
9d58ef95 306 },
25d18342 307 mounted: function() {
6808d7a1 308 ["peopleWrap", "infoDiv", "newgameDiv"].forEach(eltName => {
bd76b456
BA
309 let elt = document.getElementById(eltName);
310 elt.addEventListener("click", processModalClick);
311 });
6808d7a1
BA
312 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
313 b.addEventListener("click", () => {
314 this.newchallenge.cadence = b.innerHTML;
315 });
316 });
8a0f881d
BA
317 const dispCorr = this.$route.query["disp"];
318 const showCtype =
319 dispCorr || localStorage.getItem("type-challenges") || "live";
320 const showGtype =
321 dispCorr || localStorage.getItem("type-games") || "live";
6808d7a1
BA
322 this.setDisplay("c", showCtype);
323 this.setDisplay("g", showGtype);
25d18342 324 },
8418f0d7 325 beforeDestroy: function() {
71468011 326 this.send("disconnect");
8418f0d7 327 },
fb54f098 328 methods: {
a6bddfc6 329 // Helpers:
09d37571
BA
330 cadenceFocusIfOpened: function() {
331 if (event.target.checked)
332 document.getElementById("cadence").focus();
333 },
71468011 334 send: function(code, obj) {
6808d7a1
BA
335 if (this.conn) {
336 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
51d87b52 337 }
71468011
BA
338 },
339 getVname: function(vid) {
340 const variant = this.st.variants.find(v => v.id == vid);
341 // this.st.variants might be uninitialized (variant == null)
6808d7a1 342 return variant ? variant.name : "";
71468011 343 },
6855163c
BA
344 filterChallenges: function(type) {
345 return this.challenges.filter(c => c.type == type);
346 },
347 filterGames: function(type) {
a9b131f1 348 return this.games.filter(g => g.type == type);
6855163c 349 },
6808d7a1
BA
350 classifyObject: function(o) {
351 //challenge or game
352 return o.cadence.indexOf("d") === -1 ? "live" : "corr";
a6bddfc6 353 },
5bcc9b31
BA
354 setDisplay: function(letter, type, e) {
355 this[letter + "display"] = type;
6808d7a1
BA
356 localStorage.setItem(
357 "type-" + (letter == "c" ? "challenges" : "games"),
358 type
359 );
360 let elt = e
7f36b53a
BA
361 ? e.target
362 : document.getElementById("btn" + letter.toUpperCase() + type);
363 elt.classList.add("active");
2f258c37 364 elt.classList.remove("somethingnew"); //in case of
6808d7a1 365 if (elt.previousElementSibling)
7f36b53a 366 elt.previousElementSibling.classList.remove("active");
6808d7a1 367 else elt.nextElementSibling.classList.remove("active");
7f36b53a
BA
368 },
369 isGamer: function(sid) {
370 return this.people[sid].pages.some(p => p.indexOf("/game/") >= 0);
371 },
71468011 372 getActionLabel: function(sid) {
38c1dda1
BA
373
374
375console.log(this.people[sid]);
376
377
71468011
BA
378 return this.people[sid].pages.some(p => p == "/")
379 ? "Challenge"
380 : "Observe";
ac8f441c 381 },
71468011 382 challOrWatch: function(sid) {
6808d7a1 383 if (this.people[sid].pages.some(p => p == "/")) {
71468011
BA
384 // Available, in Hall
385 this.newchallenge.to = this.people[sid].name;
3e4e742c 386 document.getElementById("modalPeople").checked = false;
6808d7a1
BA
387 window.doClick("modalNewgame");
388 } else {
7f36b53a
BA
389 // In some game, maybe playing maybe not: show a random one
390 let gids = [];
391 this.people[sid].pages.forEach(p => {
392 const matchGid = p.match(/[a-zA-Z0-9]+$/);
6808d7a1 393 if (matchGid) gids.push(matchGid[0]);
7f36b53a
BA
394 });
395 const gid = gids[Math.floor(Math.random() * gids.length)];
26f70eee
BA
396 const game = this.games.find(g => g.id == gid);
397 if (game) this.showGame(game);
398 else this.$router.push("/game/" + gid); //game vs. me
71468011
BA
399 }
400 },
51d87b52 401 showGame: function(g) {
71468011
BA
402 // NOTE: we are an observer, since only games I don't play are shown here
403 // ==> Moves sent by connected remote player(s) if live game
404 let url = "/game/" + g.id;
405 if (g.type == "live")
51d87b52 406 url += "?rid=" + g.rids[Math.floor(Math.random() * g.rids.length)];
71468011
BA
407 this.$router.push(url);
408 },
efdfb4c7 409 resetSocialColor: function() {
bd76b456 410 // TODO: this is called twice, once on opening an once on closing
2f258c37 411 document.getElementById("peopleBtn").classList.remove("somethingnew");
bd76b456 412 },
71468011 413 processChat: function(chat) {
6808d7a1 414 this.send("newchat", { data: chat });
a6bddfc6
BA
415 },
416 // Messaging center:
9d58ef95 417 socketMessageListener: function(msg) {
6808d7a1 418 if (!this.conn) return;
9d58ef95 419 const data = JSON.parse(msg.data);
6808d7a1
BA
420 switch (data.code) {
421 case "pollclientsandgamers": {
51d87b52
BA
422 // Since people can be both in Hall and Game,
423 // need to track "askIdentity" requests:
71468011
BA
424 let identityAsked = {};
425 data.sockIds.forEach(s => {
7f36b53a 426 const page = s.page || "/";
6808d7a1 427 if (s.sid != this.st.user.sid && !identityAsked[s.sid]) {
6808d7a1 428 this.send("askidentity", { target: s.sid, page: page });
efdfb4c7 429 identityAsked[s.sid] = true;
71468011
BA
430 }
431 if (!this.people[s.sid])
efdfb4c7
BA
432 // Do not set name or id: identity unknown yet
433 this.$set(this.people, s.sid, { pages: [page] });
7f36b53a
BA
434 else if (this.people[s.sid].pages.indexOf(page) < 0)
435 this.people[s.sid].pages.push(page);
6808d7a1 436 if (!s.page)
efdfb4c7 437 // Peer is in Hall
6808d7a1 438 this.send("askchallenge", { target: s.sid });
efdfb4c7 439 // Peer is in Game
6808d7a1 440 else this.send("askgame", { target: s.sid, page: page });
5a3da968 441 });
ac8f441c 442 break;
71468011
BA
443 }
444 case "connect":
6808d7a1 445 case "gconnect": {
7f36b53a 446 const page = data.page || "/";
71468011
BA
447 // NOTE: player could have been polled earlier, but might have logged in then
448 // So it's a good idea to ask identity if he was anonymous.
449 // But only ask game / challenge if currently disconnected.
6808d7a1 450 if (!this.people[data.from]) {
efdfb4c7 451 this.$set(this.people, data.from, { pages: [page] });
71468011 452 if (data.code == "connect")
6808d7a1
BA
453 this.send("askchallenge", { target: data.from });
454 else this.send("askgame", { target: data.from, page: page });
455 } else {
efdfb4c7 456 // Append page if not already in list
7f36b53a
BA
457 if (this.people[data.from].pages.indexOf(page) < 0)
458 this.people[data.from].pages.push(page);
71468011 459 }
efdfb4c7
BA
460 if (!this.people[data.from].name && this.people[data.from].id !== 0) {
461 // Identity not known yet
51d87b52 462 this.newConnect[data.from] = true; //for self multi-connects tests
6808d7a1 463 this.send("askidentity", { target: data.from, page: page });
51d87b52 464 }
71468011 465 break;
7f36b53a 466 }
71468011 467 case "disconnect":
6808d7a1 468 case "gdisconnect": {
092de306
BA
469 // If the user reloads the page twice very quickly (experienced with Firefox),
470 // the first reload won't have time to connect but will trigger a "close" event anyway.
471 // ==> Next check is required.
6808d7a1 472 if (!this.people[data.from]) return;
71468011 473 // Disconnect means no more tmpIds:
6808d7a1 474 if (data.code == "disconnect") {
51d87b52 475 // Remove the live challenge sent by this player:
71468011 476 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
6808d7a1 477 } else {
51d87b52
BA
478 // Remove the matching live game if now unreachable
479 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
480 const gidx = this.games.findIndex(g => g.id == gid);
6808d7a1 481 if (gidx >= 0) {
51d87b52 482 const game = this.games[gidx];
6808d7a1
BA
483 if (
484 game.type == "live" &&
485 game.rids.length == 1 &&
486 game.rids[0] == data.from
487 ) {
51d87b52
BA
488 this.games.splice(gidx, 1);
489 }
71468011
BA
490 }
491 }
51d87b52
BA
492 const page = data.page || "/";
493 ArrayFun.remove(this.people[data.from].pages, p => p == page);
494 if (this.people[data.from].pages.length == 0)
495 this.$delete(this.people, data.from);
496 break;
6808d7a1 497 }
51d87b52
BA
498 case "killed":
499 // I logged in elsewhere:
51d87b52 500 this.conn = null;
09d37571 501 alert(this.st.tr["New connexion detected: tab now offline"]);
5a3da968 502 break;
6808d7a1 503 case "askidentity": {
51d87b52
BA
504 // Request for identification (TODO: anonymous shouldn't need to reply)
505 const me = {
506 // Decompose to avoid revealing email
507 name: this.st.user.name,
508 sid: this.st.user.sid,
6808d7a1 509 id: this.st.user.id
51d87b52 510 };
6808d7a1 511 this.send("identity", { data: me, target: data.from });
5a3da968 512 break;
51d87b52 513 }
6808d7a1 514 case "identity": {
71468011 515 const user = data.data;
efdfb4c7
BA
516 this.$set(this.people, user.sid, {
517 id: user.id,
518 name: user.name,
519 pages: this.people[user.sid].pages
520 });
6808d7a1 521 if (user.name) {
51d87b52 522 // If I multi-connect, kill current connexion if no mark (I'm older)
6808d7a1
BA
523 if (
524 this.newConnect[user.sid] &&
525 user.id > 0 &&
526 user.id == this.st.user.id &&
527 user.sid != this.st.user.sid
528 ) {
529 if (!this.killed[this.st.user.sid]) {
530 this.send("killme", { sid: this.st.user.sid });
51d87b52
BA
531 this.killed[this.st.user.sid] = true;
532 }
533 }
51d87b52
BA
534 }
535 delete this.newConnect[user.sid];
dcd68c41 536 break;
71468011 537 }
6808d7a1 538 case "askchallenge": {
6855163c 539 // Send my current live challenge (if any)
6808d7a1
BA
540 const cIdx = this.challenges.findIndex(
541 c => c.from.sid == this.st.user.sid && c.type == "live"
542 );
543 if (cIdx >= 0) {
dd75774d 544 const c = this.challenges[cIdx];
71468011
BA
545 // NOTE: in principle, should only send targeted challenge to the target.
546 // But we may not know yet the identity of the target (just name),
547 // so cannot decide if data.from is the target or not.
6808d7a1 548 const myChallenge = {
2ada153c 549 id: c.id,
71468011 550 from: this.st.user.sid,
81d9ce72 551 to: c.to,
7ba4a5bc 552 randomness: c.randomness,
81d9ce72
BA
553 fen: c.fen,
554 vid: c.vid,
71468011 555 cadence: c.cadence,
6808d7a1 556 added: c.added
dd75774d 557 };
6808d7a1 558 this.send("challenge", { data: myChallenge, target: data.from });
81d9ce72
BA
559 }
560 break;
1efe1d79 561 }
71468011 562 case "challenge": //after "askchallenge"
6808d7a1 563 case "newchallenge": {
a64d9122 564 // NOTE about next condition: see "askchallenge" case.
71468011 565 const chall = data.data;
6808d7a1
BA
566 if (
567 !chall.to ||
568 (this.people[chall.from].id > 0 &&
569 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
570 ) {
71468011
BA
571 let newChall = Object.assign({}, chall);
572 newChall.type = this.classifyObject(chall);
7ba4a5bc 573 newChall.randomness = chall.randomness;
71468011
BA
574 newChall.added = Date.now();
575 let fromValues = Object.assign({}, this.people[chall.from]);
576 delete fromValues["pages"]; //irrelevant in this context
6808d7a1 577 newChall.from = Object.assign({ sid: chall.from }, fromValues);
a64d9122
BA
578 newChall.vname = this.getVname(newChall.vid);
579 this.challenges.push(newChall);
6808d7a1
BA
580 if (
581 (newChall.type == "live" && this.cdisplay == "corr") ||
582 (newChall.type == "corr" && this.cdisplay == "live")
583 ) {
584 document
585 .getElementById("btnC" + newChall.type)
586 .classList.add("somethingnew");
2f258c37 587 }
a64d9122 588 }
81d9ce72 589 break;
71468011 590 }
6808d7a1 591 case "refusechallenge": {
71468011
BA
592 const cid = data.data;
593 ArrayFun.remove(this.challenges, c => c.id == cid);
594 alert(this.st.tr["Challenge declined"]);
595 break;
596 }
6808d7a1 597 case "deletechallenge": {
71468011
BA
598 // NOTE: the challenge may be already removed
599 const cid = data.data;
600 ArrayFun.remove(this.challenges, c => c.id == cid);
601 break;
602 }
603 case "game": //individual request
6808d7a1 604 case "newgame": {
71468011
BA
605 // NOTE: it may be live or correspondance
606 const game = data.data;
866842c3 607 // Ignore games where I play (corr games)
bd5c8a78
BA
608 if (game.players.every(p =>
609 p.sid != this.st.user.sid || p.id != this.st.user.id))
866842c3
BA
610 {
611 let locGame = this.games.find(g => g.id == game.id);
612 if (!locGame) {
613 let newGame = game;
614 newGame.type = this.classifyObject(game);
615 newGame.vname = this.getVname(game.vid);
616 if (!game.score)
617 //if new game from Hall
618 newGame.score = "*";
619 newGame.rids = [game.rid];
620 delete newGame["rid"];
621 this.games.push(newGame);
622 if (
623 (newGame.type == "live" && this.gdisplay == "corr") ||
624 (newGame.type == "corr" && this.gdisplay == "live")
625 ) {
626 document
627 .getElementById("btnG" + newGame.type)
628 .classList.add("somethingnew");
629 }
630 } else {
631 // Append rid (if not already in list)
632 if (!locGame.rids.includes(game.rid)) locGame.rids.push(game.rid);
2f258c37 633 }
51d87b52 634 }
81d9ce72 635 break;
1efe1d79 636 }
6808d7a1 637 case "result": {
48ab808f 638 let g = this.games.find(g => g.id == data.gid);
6808d7a1 639 if (g) g.score = data.score;
48ab808f
BA
640 break;
641 }
6808d7a1 642 case "startgame": {
5d04793e 643 // New game just started: data contain all information
71468011
BA
644 const gameInfo = data.data;
645 if (this.classifyObject(gameInfo) == "live")
646 this.startNewGame(gameInfo);
6808d7a1
BA
647 else {
648 this.infoMessage =
649 this.st.tr["New correspondance game:"] +
650 " <a href='#/game/" +
651 gameInfo.id +
652 "'>" +
653 "#/game/" +
654 gameInfo.id +
655 "</a>";
dce792f6
BA
656 let modalBox = document.getElementById("modalInfo");
657 modalBox.checked = true;
5d04793e 658 }
9d58ef95 659 break;
71468011 660 }
ac8f441c 661 case "newchat":
71468011 662 this.newChat = data.data;
bd76b456 663 if (!document.getElementById("modalPeople").checked)
2f258c37 664 document.getElementById("peopleBtn").classList.add("somethingnew");
9d58ef95
BA
665 break;
666 }
667 },
51d87b52 668 socketCloseListener: function() {
6808d7a1 669 if (!this.conn) return;
51d87b52
BA
670 this.conn = new WebSocket(this.connexionString);
671 this.conn.addEventListener("message", this.socketMessageListener);
672 this.conn.addEventListener("close", this.socketCloseListener);
673 },
a6bddfc6 674 // Challenge lifecycle:
725da57f
BA
675 loadNewchallVariant: async function(cb) {
676 const vname = this.getVname(this.newchallenge.vid);
677 const vModule = await import("@/variants/" + vname + ".js");
678 this.newchallenge.V = vModule.VariantRules;
679 this.newchallenge.vname = vname;
680 if (cb)
681 cb();
682 },
683 trySetNewchallDiag: function() {
684 if (!this.newchallenge.fen) {
685 this.newchallenge.diag = "";
686 return;
687 }
688 // If vid > 0 then the variant is loaded (function above):
689 window.V = this.newchallenge.V;
690 if (
691 this.newchallenge.vid > 0 &&
692 this.newchallenge.fen &&
693 V.IsGoodFen(this.newchallenge.fen)
694 ) {
695 const parsedFen = V.ParseFen(this.newchallenge.fen);
696 this.newchallenge.diag = getDiagram({
697 position: parsedFen.position,
698 orientation: V.GetOppCol(parsedFen.turn)
699 });
700 }
701 },
9d58ef95 702 newChallenge: async function() {
8477e53d
BA
703 if (this.newchallenge.cadence.match(/^[0-9]+$/))
704 this.newchallenge.cadence += "+0"; //assume minutes, no increment
705 const ctype = this.classifyObject(this.newchallenge);
706 // TODO: cadence still unchecked so ctype could be wrong...
6808d7a1 707 let error = "";
8477e53d 708 if (!this.newchallenge.vid)
6808d7a1 709 error = this.st.tr["Please select a variant"];
8477e53d
BA
710 else if (ctype == "corr" && this.st.user.id <= 0)
711 error = this.st.tr["Please log in to play correspondance games"];
712 else if (this.newchallenge.to) {
713 if (this.newchallenge.to == this.st.user.name)
714 error = this.st.tr["Self-challenge is forbidden"];
715 else if (
716 ctype == "live" &&
717 Object.values(this.people).every(p => p.name != this.newchallenge.to)
718 )
719 error = this.newchallenge.to + " " + this.st.tr["is not online"];
720 }
6808d7a1
BA
721 if (error) {
722 alert(error);
723 return;
724 }
725da57f 725 window.V = this.newchallenge.V;
6808d7a1 726 error = checkChallenge(this.newchallenge);
6808d7a1
BA
727 if (error) {
728 alert(error);
729 return;
730 }
bb7dd7db 731 // NOTE: "from" information is not required here
a7808884 732 let chall = Object.assign({}, this.newchallenge);
7ba4a5bc
BA
733 delete chall["V"];
734 delete chall["diag"];
6808d7a1 735 const finishAddChallenge = cid => {
1efe1d79 736 chall.id = cid || "c" + getRandString();
fe4c7e67 737 // Remove old challenge if any (only one at a time of a given type):
6808d7a1
BA
738 const cIdx = this.challenges.findIndex(
739 c =>
740 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) &&
741 c.type == ctype
742 );
743 if (cIdx >= 0) {
5ea8d113 744 // Delete current challenge (will be replaced now)
6808d7a1
BA
745 this.send("deletechallenge", { data: this.challenges[cIdx].id });
746 if (ctype == "corr") {
747 ajax("/challenges", "DELETE", { id: this.challenges[cIdx].id });
5ea8d113
BA
748 }
749 this.challenges.splice(cIdx, 1);
750 }
6808d7a1
BA
751 this.send("newchallenge", {
752 data: Object.assign({ from: this.st.user.sid }, chall)
753 });
5ea8d113 754 // Add new challenge:
6808d7a1 755 chall.from = {
725da57f 756 // Decompose to avoid revealing email
dcd68c41
BA
757 sid: this.st.user.sid,
758 id: this.st.user.id,
6808d7a1 759 name: this.st.user.name
dcd68c41 760 };
71468011
BA
761 chall.added = Date.now();
762 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
763 chall.type = ctype;
725da57f 764 chall.vname = this.newchallenge.vname;
1efe1d79 765 this.challenges.push(chall);
71468011
BA
766 // Remember cadence + vid for quicker further challenges:
767 localStorage.setItem("cadence", chall.cadence);
25d18342 768 localStorage.setItem("vid", chall.vid);
7ba4a5bc 769 localStorage.setItem("randomness", chall.randomness);
b4d619d1 770 document.getElementById("modalNewgame").checked = false;
db1f1f9a
BA
771 // Show the challenge if not on current display
772 if (
773 (ctype == "live" && this.cdisplay == "corr") ||
774 (ctype == "corr" && this.cdisplay == "live")
775 ) {
776 this.setDisplay('c', ctype);
777 }
b4d619d1 778 };
6808d7a1 779 if (ctype == "live") {
1efe1d79 780 // Live challenges have a random ID
71468011 781 finishAddChallenge(null);
6808d7a1 782 } else {
b4d619d1 783 // Correspondance game: send challenge to server
6808d7a1
BA
784 ajax("/challenges", "POST", { chall: chall }, response => {
785 finishAddChallenge(response.cid);
786 });
9d58ef95 787 }
fb54f098 788 },
725da57f
BA
789 // Callback function after a diagram was showed to accept
790 // or refuse targetted challenge:
791 decisionChallenge: function(accepted) {
792 this.curChallToAccept.accepted = accepted;
793 this.finishProcessingChallenge(this.curChallToAccept);
794 document.getElementById("modalAccept").checked = false;
795 },
796 finishProcessingChallenge: function(c) {
797 if (c.accepted) {
798 c.seat = {
799 // Again, avoid c.seat = st.user to not reveal email
800 sid: this.st.user.sid,
801 id: this.st.user.id,
802 name: this.st.user.name
803 };
804 this.launchGame(c);
805 } else {
806 this.send("refusechallenge", { data: c.id, target: c.from.sid });
807 }
808 this.send("deletechallenge", { data: c.id });
809 },
810 clickChallenge: async function(c) {
6808d7a1
BA
811 const myChallenge =
812 c.from.sid == this.st.user.sid || //live
813 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
814 if (!myChallenge) {
815 if (c.type == "corr" && this.st.user.id <= 0) {
816 alert(this.st.tr["Please log in to accept corr challenges"]);
817 return;
818 }
a6bddfc6 819 c.accepted = true;
725da57f
BA
820 const vModule = await import("@/variants/" + c.vname + ".js");
821 window.V = vModule.VariantRules;
6808d7a1 822 if (c.to) {
725da57f
BA
823 // c.to == this.st.user.name (connected)
824 if (c.fen) {
825 const parsedFen = V.ParseFen(c.fen);
0cd02605 826 c.mycolor = V.GetOppCol(parsedFen.turn);
725da57f
BA
827 this.tchallDiag = getDiagram({
828 position: parsedFen.position,
0cd02605 829 orientation: c.mycolor
725da57f
BA
830 });
831 this.curChallToAccept = c;
832 document.getElementById("modalAccept").checked = true;
833 }
834 else {
835 if (!confirm(this.st.tr["Accept challenge?"]))
836 c.accepted = false;
837 this.finishProcessingChallenge(c);
838 }
485fccd5 839 }
725da57f
BA
840 else
841 this.finishProcessingChallenge(c);
842 }
6808d7a1 843 else {
725da57f 844 // My challenge
6808d7a1
BA
845 if (c.type == "corr") {
846 ajax("/challenges", "DELETE", { id: c.id });
36093eba 847 }
6808d7a1 848 this.send("deletechallenge", { data: c.id });
485fccd5 849 }
5ea8d113 850 // In all cases, the challenge is consumed:
3d55deea 851 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
a6bddfc6 852 },
a64d9122 853 // NOTE: when launching game, the challenge is already being deleted
725da57f 854 launchGame: function(c) {
71468011 855 // These game informations will be shared
6808d7a1 856 let gameInfo = {
11667c79 857 id: getRandString(),
7ba4a5bc 858 fen: c.fen || V.GenRandInitFen(c.randomness),
0cd02605
BA
859 // White player index 0, black player index 1:
860 players: c.mycolor
861 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
862 : shuffle([c.from, c.seat]),
a6bddfc6 863 vid: c.vid,
6808d7a1 864 cadence: c.cadence
a6bddfc6 865 };
5ea8d113 866 let oppsid = c.from.sid; //may not be defined if corr + offline opp
6808d7a1
BA
867 if (!oppsid) {
868 oppsid = Object.keys(this.people).find(
869 sid => this.people[sid].id == c.from.id
870 );
8c564f46 871 }
71468011 872 const notifyNewgame = () => {
6808d7a1
BA
873 if (oppsid)
874 //opponent is online
875 this.send("startgame", { data: gameInfo, target: oppsid });
71468011 876 // Send game info (only if live) to everyone except me in this tab
6808d7a1 877 this.send("newgame", { data: gameInfo });
411d23cd 878 };
6808d7a1 879 if (c.type == "live") {
71468011 880 notifyNewgame();
485fccd5 881 this.startNewGame(gameInfo);
6808d7a1
BA
882 } //corr: game only on server
883 else {
485fccd5
BA
884 ajax(
885 "/games",
886 "POST",
6808d7a1 887 { gameInfo: gameInfo, cid: c.id }, //cid useful to delete challenge
411d23cd 888 response => {
11667c79 889 gameInfo.id = response.gameId;
71468011 890 notifyNewgame();
411d23cd
BA
891 this.$router.push("/game/" + response.gameId);
892 }
485fccd5
BA
893 );
894 }
fb54f098 895 },
a9b131f1 896 // NOTE: for live games only (corr games start on the server)
42c15a75 897 startNewGame: function(gameInfo) {
25996aed
BA
898 const game = Object.assign({}, gameInfo, {
899 // (other) Game infos: constant
6d01bb17 900 fenStart: gameInfo.fen,
71468011
BA
901 vname: this.getVname(gameInfo.vid),
902 created: Date.now(),
25996aed 903 // Game state (including FEN): will be updated
967a2686 904 moves: [],
a9b131f1 905 clocks: [-1, -1], //-1 = unstarted
66d03f23 906 initime: [0, 0], //initialized later
6808d7a1 907 score: "*"
a7808884 908 });
8477e53d
BA
909 GameStorage.add(game, (err) => {
910 // If an error occurred, game is not added: abort
911 if (!err) {
db1f1f9a 912 if (this.st.settings.sound)
1fc6df1e 913 new Audio("/sounds/newgame.flac").play().catch(() => {});
8477e53d
BA
914 this.$router.push("/game/" + gameInfo.id);
915 }
916 });
6808d7a1
BA
917 }
918 }
85e5b5c1 919};
ccd4a2b7 920</script>
85e5b5c1 921
41c80bb6 922<style lang="sass" scoped>
5bcc9b31
BA
923.active
924 color: #42a983
a154d45e
BA
925
926#infoDiv > .card
f854c94f
BA
927 padding: 15px 0
928 max-width: 430px
a154d45e 929
725da57f 930#newgameDiv > .card, #acceptDiv > .card
a154d45e
BA
931 max-width: 767px
932 max-height: 100%
933
bd76b456
BA
934div#peopleWrap > .card
935 max-height: 100%
936
937@media screen and (min-width: 1281px)
938 div#peopleWrap > .card
939 max-width: 66.67%
940
941@media screen and (max-width: 1280px)
942 div#peopleWrap > .card
943 max-width: 83.33%
944
945@media screen and (max-width: 767px)
946 div#peopleWrap > .card
947 max-width: 100%
948
ed06d9e9
BA
949#players
950 width: 50%
951 position: relative
952 float: left
910d631b 953
ed06d9e9
BA
954#chat
955 width: 50%
956 float: left
957 position: relative
910d631b 958
ed06d9e9
BA
959@media screen and (max-width: 767px)
960 #players, #chats
961 width: 100%
910d631b 962
72ccbd67
BA
963#chat > .card
964 max-width: 100%
965 margin: 0;
966 border: none;
910d631b 967
41c80bb6 968#players > p
ed06d9e9 969 margin-left: 5px
910d631b 970
dcd68c41
BA
971.anonymous
972 font-style: italic
910d631b 973
dcd68c41 974button.player-action
41c80bb6 975 margin-left: 32px
2f258c37
BA
976
977.somethingnew
978 background-color: #c5fefe !important
979
980.tabbtn
5fe7e71c 981 background-color: #f9faee
2f258c37 982
725da57f
BA
983button.acceptBtn
984 background-color: lightgreen
985button.refuseBtn
986 background-color: red
987
988#buttonsTchall
989 margin-top: 10px
990
991.variantName
992 font-weight: bold
993
994.diagram
995 margin: 0 auto
996 max-width: 400px
997
998#inputFen
999 width: 100%
1000
2f258c37
BA
1001#div2, #div3
1002 margin-top: 15px
1003@media screen and (max-width: 767px)
1004 #div2, #div3
1005 margin-top: 0
85e5b5c1 1006</style>