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