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