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