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