Attempt to get rid of unwanted trans-rooms socket listen/message...
[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 }}
afde7666
BA
18 .diagram(
19 v-if="!!curChallToAccept.fen"
20 v-html="tchallDiag"
21 )
22 .button-group#buttonsTchall(:style="tchallButtonsMargin()")
5b4de147
BA
23 button.acceptBtn(@click="decisionChallenge(true)")
24 span {{ st.tr["Accept challenge?"] }}
25 button.refuseBtn(@click="decisionChallenge(false)")
26 span {{ st.tr["Refuse"] }}
09d37571
BA
27 input#modalNewgame.modal(
28 type="checkbox"
29 @change="cadenceFocusIfOpened($event)"
30 )
910d631b
BA
31 div#newgameDiv(
32 role="dialog"
33 data-checkbox="modalNewgame"
34 )
89021f18 35 .card
5b020e73 36 label#closeNewgame.modal-close(for="modalNewgame")
28b32b4f 37 div(@keyup.enter="issueNewChallenge()")
89021f18
BA
38 fieldset
39 label(for="selectVariant") {{ st.tr["Variant"] }} *
725da57f
BA
40 select#selectVariant(
41 @change="loadNewchallVariant(trySetNewchallDiag)"
42 v-model="newchallenge.vid"
43 )
910d631b
BA
44 option(
45 v-for="v in st.variants"
46 :value="v.id"
47 :selected="newchallenge.vid==v.id"
48 )
89021f18
BA
49 | {{ v.name }}
50 fieldset
51 label(for="cadence") {{ st.tr["Cadence"] }} *
52 div#predefinedCadences
8477e53d 53 button(type="button") 15+5
8aa418f6 54 button(type="button") 45+30
92240cf0
BA
55 button(type="button") 3d
56 button(type="button") 7d
910d631b
BA
57 input#cadence(
58 type="text"
59 v-model="newchallenge.cadence"
92240cf0 60 placeholder="5+0, 1h+30s, 5d ..."
910d631b 61 )
7ba4a5bc 62 fieldset
b5aa30b5 63 label(for="selectRandomLevel") {{ st.tr["Randomness"] }} *
7ba4a5bc
BA
64 select#selectRandomLevel(v-model="newchallenge.randomness")
65 option(value="0") {{ st.tr["Deterministic"] }}
66 option(value="1") {{ st.tr["Symmetric random"] }}
67 option(value="2") {{ st.tr["Asymmetric random"] }}
28b32b4f 68 fieldset
b83a675a 69 label(for="memorizeChall") {{ st.tr["Memorize"] }}
28b32b4f
BA
70 input#memorizeChall(
71 type="checkbox"
72 v-model="newchallenge.memorize"
73 )
89021f18 74 fieldset(v-if="st.user.id > 0")
b83a675a 75 label(for="selectPlayers") {{ st.tr["Play with"] }}
6f2f9437
BA
76 select#selectPlayersInList(
77 v-model="newchallenge.to"
78 @change="changeChallTarget()"
79 )
b83a675a
BA
80 option(value="")
81 option(
82 v-for="p in Object.values(people)"
305ede7e 83 v-if="!!p.name"
b83a675a
BA
84 :value="p.name"
85 )
86 | {{ p.name }}
910d631b
BA
87 input#selectPlayers(
88 type="text"
89 v-model="newchallenge.to"
90 )
89021f18 91 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
910d631b 92 input#inputFen(
725da57f
BA
93 placeholder="FEN"
94 @input="trySetNewchallDiag()"
910d631b
BA
95 type="text"
96 v-model="newchallenge.fen"
97 )
725da57f 98 .diagram(v-html="newchallenge.diag")
28b32b4f 99 button(@click="issueNewChallenge()") {{ st.tr["Send challenge"] }}
910d631b
BA
100 input#modalPeople.modal(
101 type="checkbox"
efdfb4c7 102 @click="resetSocialColor()"
910d631b
BA
103 )
104 div#peopleWrap(
105 role="dialog"
106 data-checkbox="modalPeople"
107 )
bd76b456
BA
108 .card
109 label.modal-close(for="modalPeople")
110 #people
111 #players
910d631b
BA
112 p(
113 v-for="sid in Object.keys(people)"
f9c36b2d 114 v-if="!!people[sid].name"
910d631b 115 )
bd76b456 116 span {{ people[sid].name }}
910d631b 117 button.player-action(
6d6f45bc
BA
118 v-if="isGamer(sid)"
119 @click="watchGame(sid)"
910d631b 120 )
6d6f45bc
BA
121 | {{ st.tr["Observe"] }}
122 button.player-action(
a041d5d8 123 v-else-if="isFocusedOnHall(sid)"
6d6f45bc
BA
124 @click="challenge(sid)"
125 )
126 | {{ st.tr["Challenge"] }}
f1c9d707 127 p.anonymous @nonymous ({{ anonymousCount() }})
bd76b456 128 #chat
910d631b 129 Chat(
95a66034 130 ref="chatcomp"
910d631b
BA
131 @mychat="processChat"
132 :pastChats="[]"
133 )
bd76b456 134 .clearer
9d58ef95 135 .row
bd76b456
BA
136 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
137 .button-group
95a66034 138 button#peopleBtn(@click="openModalPeople()")
8a0f881d 139 | {{ st.tr["Who's there?"] }}
afde7666 140 button(@click="showNewchallengeForm()")
910d631b 141 | {{ st.tr["New game"] }}
28b32b4f
BA
142 .row(v-if="presetChalls.length > 0")
143 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
144 h4.text-center {{ st.tr["Preset challenges"] }}
145 table
146 thead
147 tr
148 th {{ st.tr["Variant"] }}
149 th {{ st.tr["Cadence"] }}
150 th {{ st.tr["Random?"] }}
151 th
152 tbody
153 tr(
154 v-for="pc in presetChalls"
155 @click="newChallFromPreset(pc)"
156 )
157 td {{ pc.vname }}
158 td {{ pc.cadence }}
159 td(:class="getRandomnessClass(pc)")
160 td.remove-preset(@click="removePresetChall($event, pc)")
161 img(src="/images/icons/delete.svg")
9d58ef95 162 .row
9ca1e26b 163 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
2f258c37 164 div#div2
ed06d9e9 165 .button-group
2f258c37 166 button.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
602d6bef 167 | {{ st.tr["Live challenges"] }}
2f258c37 168 button.tabbtn#btnCcorr(@click="setDisplay('c','corr',$event)")
602d6bef 169 | {{ st.tr["Correspondance challenges"] }}
910d631b
BA
170 ChallengeList(
171 v-show="cdisplay=='live'"
172 :challenges="filterChallenges('live')"
173 @click-challenge="clickChallenge"
174 )
175 ChallengeList(
176 v-show="cdisplay=='corr'"
177 :challenges="filterChallenges('corr')"
178 @click-challenge="clickChallenge"
179 )
2f258c37 180 div#div3
ed06d9e9 181 .button-group
2f258c37 182 button.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
602d6bef 183 | {{ st.tr["Live games"] }}
2f258c37 184 button.tabbtn#btnGcorr(@click="setDisplay('g','corr',$event)")
602d6bef 185 | {{ st.tr["Correspondance games"] }}
910d631b
BA
186 GameList(
187 v-show="gdisplay=='live'"
188 :games="filterGames('live')"
189 :showBoth="true"
190 @show-game="showGame"
191 )
0234201f
BA
192 div(v-show="gdisplay=='corr'")
193 GameList(
194 :games="filterGames('corr')"
195 :showBoth="true"
196 @show-game="showGame"
197 )
198 button#loadMoreBtn(
199 v-if="hasMore"
95a66034 200 @click="loadMoreCorr()"
0234201f
BA
201 )
202 | {{ st.tr["Load more"] }}
625022fd
BA
203</template>
204
205<script>
5b020e73 206import { store } from "@/store";
9d58ef95
BA
207import { checkChallenge } from "@/data/challengeCheck";
208import { ArrayFun } from "@/utils/array";
03608482 209import { ajax } from "@/utils/ajax";
8418f0d7 210import params from "@/parameters";
4b0384fa 211import { getRandString, shuffle } from "@/utils/alea";
725da57f 212import { getDiagram } from "@/utils/printDiagram";
603b8a8b 213import Chat from "@/components/Chat.vue";
5b020e73
BA
214import GameList from "@/components/GameList.vue";
215import ChallengeList from "@/components/ChallengeList.vue";
967a2686 216import { GameStorage } from "@/utils/gameStorage";
602d6bef 217import { processModalClick } from "@/utils/modalClick";
625022fd 218export default {
cf2343ce 219 name: "my-hall",
5b020e73 220 components: {
603b8a8b 221 Chat,
5b020e73 222 GameList,
6808d7a1 223 ChallengeList
5b020e73 224 },
6808d7a1 225 data: function() {
fb54f098 226 return {
5b020e73 227 st: store.state,
6855163c 228 cdisplay: "live", //or corr
fb54f098 229 gdisplay: "live",
0234201f
BA
230 // timestamp of last showed (oldest) corr game:
231 cursor: Number.MAX_SAFE_INTEGER,
232 // hasMore == TRUE: a priori there could be more games to load
233 hasMore: true,
6855163c 234 games: [],
b4d619d1 235 challenges: [],
71468011 236 people: {},
3d55deea 237 infoMessage: "",
9d58ef95 238 newchallenge: {
fb54f098 239 fen: "",
725da57f 240 vid: parseInt(localStorage.getItem("vid")) || 0,
6fba6e0c 241 to: "", //name of challenged player (if any)
725da57f 242 cadence: localStorage.getItem("cadence") || "",
f2adb3d0 243 randomness: parseInt(localStorage.getItem("challRandomness")) || 2,
725da57f
BA
244 // VariantRules object, stored to not interfere with
245 // diagrams of targetted challenges:
246 V: null,
247 vname: "",
28b32b4f
BA
248 diag: "", //visualizing FEN
249 memorize: false //put settings in localStorage
fb54f098 250 },
725da57f
BA
251 tchallDiag: "",
252 curChallToAccept: {from: {}},
28b32b4f 253 presetChalls: JSON.parse(localStorage.getItem("presetChalls") || "[]"),
8418f0d7 254 conn: null,
51d87b52
BA
255 connexionString: "",
256 // Related to (killing of) self multi-connects:
257 newConnect: {},
6808d7a1 258 killed: {}
fb54f098
BA
259 };
260 },
fd7aea36
BA
261 watch: {
262 // st.variants changes only once, at loading from [] to [...]
6808d7a1 263 "st.variants": function() {
fd7aea36 264 // Set potential challenges and games variant names:
71468011 265 this.challenges.concat(this.games).forEach(o => {
f9c36b2d 266 if (!o.vname) o.vname = this.getVname(o.vid);
fd7aea36 267 });
725da57f
BA
268 if (!this.newchallenge.V && this.newchallenge.vid > 0)
269 this.loadNewchallVariant();
1112f1fd
BA
270 },
271 $route: function(to, from) {
272 if (to.path != "/") this.cleanBeforeDestroy();
6808d7a1 273 }
fd7aea36 274 },
9d58ef95 275 created: function() {
1112f1fd
BA
276 document.addEventListener('visibilitychange', this.visibilityChange);
277 window.addEventListener("beforeunload", this.cleanBeforeDestroy);
725da57f
BA
278 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
279 this.loadNewchallVariant();
66d03f23 280 const my = this.st.user;
a041d5d8
BA
281 this.$set(
282 this.people,
283 my.sid,
284 {
285 id: my.id,
286 name: my.name,
287 pages: [{ path: "/", focus: true }]
288 }
289 );
e5a5d331
BA
290 const connectAndPoll = () => {
291 this.send("connect");
292 this.send("pollclientsandgamers");
293 };
294 // Initialize connection
295 this.connexionString =
296 params.socketUrl +
297 "/?sid=" +
298 this.st.user.sid +
299 "&id=" +
300 this.st.user.id +
301 "&tmpId=" +
302 getRandString() +
303 "&page=" +
304 // Hall: path is "/" (could be hard-coded as well)
305 encodeURIComponent(this.$route.path);
306 this.conn = new WebSocket(this.connexionString);
307 this.conn.onopen = connectAndPoll;
3f22c2c3
BA
308 this.conn.addEventListener("message", this.socketMessageListener);
309 this.conn.addEventListener("close", this.socketCloseListener);
e5a5d331
BA
310 },
311 mounted: function() {
e5a5d331
BA
312 ["peopleWrap", "infoDiv", "newgameDiv"].forEach(eltName => {
313 document.getElementById(eltName)
314 .addEventListener("click", processModalClick);
315 });
316 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
317 b.addEventListener("click", () => {
318 this.newchallenge.cadence = b.innerHTML;
319 });
320 });
321 const dispCorr = this.$route.query["disp"];
322 const showCtype =
323 dispCorr || localStorage.getItem("type-challenges") || "live";
324 const showGtype =
325 dispCorr || localStorage.getItem("type-games") || "live";
326 this.setDisplay('c', showCtype);
327 this.setDisplay('g', showGtype);
3d55deea 328 // Ask server for current corr games (all but mines)
95a66034 329 this.loadMoreCorr();
fe4c7e67 330 // Also ask for corr challenges (open + sent by/to me)
95a66034 331 // List them all, because they are not supposed to be that many (TODO?)
e57c4de4
BA
332 ajax(
333 "/challenges",
334 "GET",
335 {
336 data: { uid: this.st.user.id },
337 success: (response) => {
e5a5d331
BA
338 if (
339 response.challenges.length > 0 &&
340 this.challenges.length == 0 &&
341 this.cdisplay == "live"
342 ) {
343 document
344 .getElementById("btnCcorr")
345 .classList.add("somethingnew");
346 }
e57c4de4
BA
347 // Gather all senders names, and then retrieve full identity:
348 // (TODO [perf]: some might be online...)
349 let names = {};
350 response.challenges.forEach(c => {
351 if (c.uid != this.st.user.id) names[c.uid] = "";
352 else if (!!c.target && c.target != this.st.user.id)
353 names[c.target] = "";
354 });
355 const addChallenges = () => {
356 names[this.st.user.id] = this.st.user.name; //in case of
357 this.challenges = this.challenges.concat(
358 response.challenges.map(c => {
359 const from = { name: names[c.uid], id: c.uid }; //or just name
360 const type = this.classifyObject(c);
361 const vname = this.getVname(c.vid);
362 return Object.assign(
363 {},
364 {
365 type: type,
366 vname: vname,
367 from: from,
368 to: c.target ? names[c.target] : ""
369 },
370 c
371 );
372 })
373 );
374 };
375 if (Object.keys(names).length > 0) {
376 ajax(
377 "/users",
378 "GET",
6808d7a1 379 {
e57c4de4
BA
380 data: { ids: Object.keys(names).join(",") },
381 success: (response2) => {
382 response2.users.forEach(u => {
383 names[u.id] = u.name;
384 });
385 addChallenges();
386 }
387 }
6808d7a1 388 );
e57c4de4
BA
389 } else addChallenges();
390 }
391 }
392 );
25d18342 393 },
8418f0d7 394 beforeDestroy: function() {
1112f1fd 395 this.cleanBeforeDestroy();
8418f0d7 396 },
fb54f098 397 methods: {
1112f1fd
BA
398 cleanBeforeDestroy: function() {
399 document.removeEventListener('visibilitychange', this.visibilityChange);
400 window.removeEventListener("beforeunload", this.cleanBeforeDestroy);
68e3aa8c
BA
401 this.conn.removeEventListener("message", this.socketMessageListener);
402 this.conn.removeEventListener("close", this.socketCloseListener);
1112f1fd 403 this.send("disconnect");
68e3aa8c 404 this.conn = null;
1112f1fd 405 },
28b32b4f
BA
406 getRandomnessClass: function(pc) {
407 return {
408 ["random-" + pc.randomness]: true
409 };
410 },
95a66034
BA
411 openModalPeople: function() {
412 window.doClick("modalPeople");
413 document.getElementById("inputChat").focus();
414 },
f1c9d707
BA
415 anonymousCount: function() {
416 let count = 0;
417 Object.values(this.people).forEach(p => {
418 // Do not cound people who did not send their identity yet:
419 count += (!p.name && p.id === 0) ? 1 : 0;
420 });
421 return count;
422 },
a041d5d8
BA
423 visibilityChange: function() {
424 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
425 this.send(
426 document.visibilityState == "visible"
427 ? "getfocus"
428 : "losefocus"
429 );
430 },
afde7666
BA
431 partialResetNewchallenge: function() {
432 // Reset potential target and custom FEN:
433 this.newchallenge.to = "";
434 this.newchallenge.fen = "";
435 this.newchallenge.diag = "";
28b32b4f 436 this.newchallenge.memorize = false;
afde7666
BA
437 },
438 showNewchallengeForm: function() {
439 this.partialResetNewchallenge();
440 window.doClick("modalNewgame");
441 },
28b32b4f
BA
442 addPresetChall: function(chall) {
443 // Add only if not already existing:
444 if (this.presetChalls.some(c =>
445 c.vid == chall.vid &&
446 c.cadence == chall.cadence &&
447 c.randomness == chall.randomness
448 )) {
449 return;
450 }
451 const L = this.presetChalls.length;
452 this.presetChalls.push({
453 index: L,
454 vid: chall.vid,
455 vname: chall.vname, //redundant, but easier
456 cadence: chall.cadence,
457 randomness: chall.randomness
458 });
459 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
460 },
461 removePresetChall: function(e, pchall) {
462 e.stopPropagation();
463 const pchallIdx = this.presetChalls.findIndex(pc => pc.index == pchall.index);
464 this.presetChalls.splice(pchallIdx, 1);
465 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
466 },
afde7666
BA
467 tchallButtonsMargin: function() {
468 if (!!this.curChallToAccept.fen) return { "margin-top": "10px" };
469 return {};
470 },
6f2f9437
BA
471 changeChallTarget: function() {
472 if (!this.newchallenge.to) {
473 // Reset potential FEN + diagram
474 this.newchallenge.fen = "";
475 this.newchallenge.diag = "";
476 }
477 },
09d37571
BA
478 cadenceFocusIfOpened: function() {
479 if (event.target.checked)
480 document.getElementById("cadence").focus();
481 },
71468011 482 send: function(code, obj) {
f9c36b2d 483 if (!!this.conn) {
6808d7a1 484 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
51d87b52 485 }
71468011
BA
486 },
487 getVname: function(vid) {
488 const variant = this.st.variants.find(v => v.id == vid);
489 // this.st.variants might be uninitialized (variant == null)
6808d7a1 490 return variant ? variant.name : "";
71468011 491 },
6855163c
BA
492 filterChallenges: function(type) {
493 return this.challenges.filter(c => c.type == type);
494 },
495 filterGames: function(type) {
a9b131f1 496 return this.games.filter(g => g.type == type);
6855163c 497 },
6808d7a1 498 classifyObject: function(o) {
28b32b4f 499 // o: challenge or game
6808d7a1 500 return o.cadence.indexOf("d") === -1 ? "live" : "corr";
a6bddfc6 501 },
5bcc9b31
BA
502 setDisplay: function(letter, type, e) {
503 this[letter + "display"] = type;
6808d7a1
BA
504 localStorage.setItem(
505 "type-" + (letter == "c" ? "challenges" : "games"),
506 type
507 );
508 let elt = e
7f36b53a
BA
509 ? e.target
510 : document.getElementById("btn" + letter.toUpperCase() + type);
511 elt.classList.add("active");
2f258c37 512 elt.classList.remove("somethingnew"); //in case of
f9c36b2d 513 if (!!elt.previousElementSibling)
7f36b53a 514 elt.previousElementSibling.classList.remove("active");
6808d7a1 515 else elt.nextElementSibling.classList.remove("active");
7f36b53a
BA
516 },
517 isGamer: function(sid) {
a041d5d8
BA
518 return this.people[sid].pages
519 .some(p => p.focus && p.path.indexOf("/game/") >= 0);
520 },
521 isFocusedOnHall: function(sid) {
522 return (
523 // This is meant to challenge people, thus the next 2 conditions:
524 this.st.user.id > 0 &&
525 sid != this.st.user.sid &&
526 this.people[sid].pages.some(p => p.path == "/" && p.focus)
527 );
7f36b53a 528 },
6d6f45bc 529 challenge: function(sid) {
afde7666
BA
530 this.partialResetNewchallenge();
531 // Available, in Hall
6d6f45bc 532 this.newchallenge.to = this.people[sid].name;
28b32b4f 533 // TODO: also store target sid to not re-search for it
6d6f45bc
BA
534 document.getElementById("modalPeople").checked = false;
535 window.doClick("modalNewgame");
ac8f441c 536 },
6d6f45bc
BA
537 watchGame: function(sid) {
538 // In some game, maybe playing maybe not: show a random one
539 let gids = [];
540 this.people[sid].pages.forEach(p => {
a041d5d8
BA
541 if (p.focus) {
542 const matchGid = p.path.match(/[a-zA-Z0-9]+$/);
543 if (!!matchGid) gids.push(matchGid[0]);
544 }
6d6f45bc
BA
545 });
546 const gid = gids[Math.floor(Math.random() * gids.length)];
547 const game = this.games.find(g => g.id == gid);
f9c36b2d 548 if (!!game) this.showGame(game);
6d6f45bc 549 else this.$router.push("/game/" + gid); //game vs. me
71468011 550 },
51d87b52 551 showGame: function(g) {
71468011
BA
552 // NOTE: we are an observer, since only games I don't play are shown here
553 // ==> Moves sent by connected remote player(s) if live game
f54f4c26 554 this.$router.push("/game/" + g.id);
71468011 555 },
efdfb4c7 556 resetSocialColor: function() {
bd76b456 557 // TODO: this is called twice, once on opening an once on closing
2f258c37 558 document.getElementById("peopleBtn").classList.remove("somethingnew");
bd76b456 559 },
71468011 560 processChat: function(chat) {
6808d7a1 561 this.send("newchat", { data: chat });
a6bddfc6 562 },
f91bc5b0
BA
563 getOppsid: function(c) {
564 let oppsid = c.from.sid; //may not be defined if corr + offline opp
565 if (!oppsid) {
566 oppsid = Object.keys(this.people).find(
567 sid => this.people[sid].id == c.from.id
568 );
569 }
570 return oppsid;
571 },
a6bddfc6 572 // Messaging center:
9d58ef95 573 socketMessageListener: function(msg) {
6808d7a1 574 if (!this.conn) return;
9d58ef95 575 const data = JSON.parse(msg.data);
6808d7a1
BA
576 switch (data.code) {
577 case "pollclientsandgamers": {
51d87b52
BA
578 // Since people can be both in Hall and Game,
579 // need to track "askIdentity" requests:
71468011 580 let identityAsked = {};
934f7f70
BA
581 // TODO: shuffling and random filtering on server, if
582 // the room is really crowded.
71468011 583 data.sockIds.forEach(s => {
7f36b53a 584 const page = s.page || "/";
6808d7a1 585 if (s.sid != this.st.user.sid && !identityAsked[s.sid]) {
6808d7a1 586 this.send("askidentity", { target: s.sid, page: page });
efdfb4c7 587 identityAsked[s.sid] = true;
71468011 588 }
a041d5d8 589 if (!this.people[s.sid]) {
efdfb4c7 590 // Do not set name or id: identity unknown yet
a041d5d8
BA
591 this.people[s.sid] = { pages: [{path: page, focus: true}] };
592 }
593 else if (!(this.people[s.sid].pages.find(p => p.path == page)))
594 this.people[s.sid].pages.push({ path: page, focus: true });
6808d7a1 595 if (!s.page)
efdfb4c7 596 // Peer is in Hall
28b32b4f 597 this.send("askchallenges", { target: s.sid });
f14572c4
BA
598 // Peer is in Game: ask only if live game
599 else if (!page.match(/\/[0-9]+$/))
600 this.send("askgame", { target: s.sid, page: page });
5a3da968 601 });
ac8f441c 602 break;
71468011
BA
603 }
604 case "connect":
6808d7a1 605 case "gconnect": {
7f36b53a 606 const page = data.page || "/";
f54f4c26
BA
607 if (data.code == "connect") {
608 // Ask challenges only on first connexion:
609 if (!this.people[data.from])
28b32b4f 610 this.send("askchallenges", { target: data.from });
f54f4c26
BA
611 }
612 // Ask game only if live:
613 else if (!page.match(/\/[0-9]+$/))
614 this.send("askgame", { target: data.from, page: page });
615 if (!this.people[data.from])
616 this.people[data.from] = { pages: [{ path: page, focus: true }] };
617 else {
efdfb4c7 618 // Append page if not already in list
a2bd587a
BA
619 let ppage = this.people[data.from].pages.find(p => p.path == page);
620 if (!ppage)
a041d5d8 621 this.people[data.from].pages.push({ path: page, focus: true });
a2bd587a
BA
622 else ppage.focus = true;
623 this.$forceUpdate(); //TODO: shouldn't be required
71468011 624 }
efdfb4c7
BA
625 if (!this.people[data.from].name && this.people[data.from].id !== 0) {
626 // Identity not known yet
51d87b52 627 this.newConnect[data.from] = true; //for self multi-connects tests
6808d7a1 628 this.send("askidentity", { target: data.from, page: page });
51d87b52 629 }
71468011 630 break;
7f36b53a 631 }
71468011 632 case "disconnect":
6808d7a1 633 case "gdisconnect": {
092de306
BA
634 // If the user reloads the page twice very quickly (experienced with Firefox),
635 // the first reload won't have time to connect but will trigger a "close" event anyway.
636 // ==> Next check is required.
6808d7a1 637 if (!this.people[data.from]) return;
f54f4c26
BA
638 const page = data.page || "/";
639 ArrayFun.remove(this.people[data.from].pages, p => p.path == page);
640 if (this.people[data.from].pages.length == 0)
641 this.$delete(this.people, data.from);
a2bd587a 642 else this.$forceUpdate(); //TODO: shouldn't be required
71468011 643 // Disconnect means no more tmpIds:
6808d7a1 644 if (data.code == "disconnect") {
28b32b4f 645 // Remove the live challenges sent by this player:
e33e50fa
BA
646 ArrayFun.remove(
647 this.challenges,
28b32b4f
BA
648 c => c.type == "live" && c.from.sid == data.from,
649 "all"
e33e50fa 650 );
6808d7a1 651 } else {
51d87b52 652 // Remove the matching live game if now unreachable
f54f4c26 653 const gid = page.match(/[a-zA-Z0-9]+$/)[0];
585d0955
BA
654 // Corr games are always reachable:
655 if (!gid.match(/^[0-9]+$/)) {
f54f4c26
BA
656 // Live games are reachable as long as someone is on the game page
657 if (Object.values(this.people).every(p =>
658 p.pages.every(pg => pg.path != page))) {
659 ArrayFun.remove(this.games, g => g.id == gid);
51d87b52 660 }
71468011
BA
661 }
662 }
51d87b52 663 break;
6808d7a1 664 }
a041d5d8
BA
665 case "getfocus":
666 // If user reload a page, focus may arrive earlier than connect
667 if (!!this.people[data.from]) {
668 this.people[data.from].pages
669 .find(p => p.path == data.page).focus = true;
670 this.$forceUpdate(); //TODO: shouldn't be required
671 }
672 break;
673 case "losefocus":
674 if (!!this.people[data.from]) {
675 this.people[data.from].pages
676 .find(p => p.path == data.page).focus = false;
677 this.$forceUpdate(); //TODO: shouldn't be required
678 }
679 break;
51d87b52
BA
680 case "killed":
681 // I logged in elsewhere:
3f22c2c3
BA
682 this.conn.removeEventListener("message", this.socketMessageListener);
683 this.conn.removeEventListener("close", this.socketCloseListener);
51d87b52 684 this.conn = null;
09d37571 685 alert(this.st.tr["New connexion detected: tab now offline"]);
5a3da968 686 break;
6808d7a1 687 case "askidentity": {
585d0955 688 // Request for identification
51d87b52
BA
689 const me = {
690 // Decompose to avoid revealing email
691 name: this.st.user.name,
692 sid: this.st.user.sid,
6808d7a1 693 id: this.st.user.id
51d87b52 694 };
6808d7a1 695 this.send("identity", { data: me, target: data.from });
5a3da968 696 break;
51d87b52 697 }
6808d7a1 698 case "identity": {
71468011 699 const user = data.data;
a041d5d8
BA
700 let player = this.people[user.sid];
701 // player.pages is already set
702 player.id = user.id;
703 player.name = user.name;
704 // TODO: this.$set(people, ...) fails. So forceUpdate.
705 // But this shouldn't be like that!
706 this.$forceUpdate();
f9c36b2d
BA
707 // If I multi-connect, kill current connexion if no mark (I'm older)
708 if (this.newConnect[user.sid]) {
6808d7a1 709 if (
6808d7a1
BA
710 user.id > 0 &&
711 user.id == this.st.user.id &&
f9c36b2d
BA
712 user.sid != this.st.user.sid &&
713 !this.killed[this.st.user.sid]
6808d7a1 714 ) {
6808d7a1 715 this.send("killme", { sid: this.st.user.sid });
51d87b52 716 this.killed[this.st.user.sid] = true;
51d87b52 717 }
f9c36b2d 718 delete this.newConnect[user.sid];
51d87b52 719 }
dcd68c41 720 break;
71468011 721 }
28b32b4f
BA
722 case "askchallenges": {
723 // Send my current live challenges (if any)
724 const myChallenges = this.challenges
725 .filter(c =>
726 c.from.sid == this.st.user.sid && c.type == "live"
727 )
728 .map(c => {
729 // NOTE: in principle, should only send targeted challenge to the target.
730 // But we may not know yet the identity of the target (just name),
731 // so cannot decide if data.from is the target or not.
732 return {
733 id: c.id,
734 from: this.st.user.sid,
735 to: c.to,
736 randomness: c.randomness,
737 fen: c.fen,
738 vid: c.vid,
739 cadence: c.cadence,
740 added: c.added
741 };
742 });
743 if (myChallenges.length > 0)
744 this.send("challenges", { data: myChallenges, target: data.from });
81d9ce72 745 break;
1efe1d79 746 }
28b32b4f
BA
747 case "challenges": //after "askchallenges"
748 data.data.forEach(this.addChallenge);
749 break;
750 case "newchallenge":
751 this.addChallenge(data.data);
81d9ce72 752 break;
6808d7a1 753 case "refusechallenge": {
71468011
BA
754 const cid = data.data;
755 ArrayFun.remove(this.challenges, c => c.id == cid);
756 alert(this.st.tr["Challenge declined"]);
757 break;
758 }
28b32b4f
BA
759 case "deletechallenge_s": {
760 // NOTE: the challenge(s) may be already removed
761 const cref = data.data;
762 if (!!cref.cid) ArrayFun.remove(this.challenges, c => c.id == cref.cid);
763 else if (!!cref.sids) {
764 cref.sids.forEach(s => {
765 ArrayFun.remove(
766 this.challenges,
767 c => c.type == "live" && c.from.sid == s,
768 "all"
769 );
770 });
771 }
71468011
BA
772 break;
773 }
f14572c4
BA
774 case "game": // Individual request
775 case "newgame": {
71468011 776 const game = data.data;
f54f4c26
BA
777 // Ignore games where I play (will go in MyGames page),
778 // and also games that I already received.
779 if (
780 game.players.every(p =>
781 p.sid != this.st.user.sid && p.id != this.st.user.id) &&
782 this.games.findIndex(g => g.id == game.id) == -1
783 ) {
784 let newGame = game;
785 newGame.type = this.classifyObject(game);
786 newGame.vname = this.getVname(game.vid);
787 if (!game.score)
788 // New game from Hall
789 newGame.score = "*";
790 this.games.push(newGame);
791 if (
792 (newGame.type == "live" && this.gdisplay == "corr") ||
793 (newGame.type == "corr" && this.gdisplay == "live")
794 ) {
795 document
796 .getElementById("btnG" + newGame.type)
797 .classList.add("somethingnew");
2f258c37 798 }
51d87b52 799 }
81d9ce72 800 break;
1efe1d79 801 }
6808d7a1 802 case "result": {
48ab808f 803 let g = this.games.find(g => g.id == data.gid);
28b32b4f 804 if (!!g) g.score = data.score;
48ab808f
BA
805 break;
806 }
6808d7a1 807 case "startgame": {
c292ebb2 808 // New game just started, I'm involved
71468011
BA
809 const gameInfo = data.data;
810 if (this.classifyObject(gameInfo) == "live")
811 this.startNewGame(gameInfo);
6808d7a1
BA
812 else {
813 this.infoMessage =
814 this.st.tr["New correspondance game:"] +
815 " <a href='#/game/" +
816 gameInfo.id +
817 "'>" +
818 "#/game/" +
819 gameInfo.id +
820 "</a>";
c292ebb2 821 document.getElementById("modalInfo").checked = true;
5d04793e 822 }
9d58ef95 823 break;
71468011 824 }
ac8f441c 825 case "newchat":
95a66034 826 this.$refs["chatcomp"].newChat(data.data);
bd76b456 827 if (!document.getElementById("modalPeople").checked)
2f258c37 828 document.getElementById("peopleBtn").classList.add("somethingnew");
9d58ef95
BA
829 break;
830 }
831 },
51d87b52 832 socketCloseListener: function() {
6808d7a1 833 if (!this.conn) return;
51d87b52
BA
834 this.conn = new WebSocket(this.connexionString);
835 this.conn.addEventListener("message", this.socketMessageListener);
836 this.conn.addEventListener("close", this.socketCloseListener);
837 },
95a66034 838 loadMoreCorr: function() {
0234201f
BA
839 ajax(
840 "/observedgames",
841 "GET",
842 {
843 data: {
844 uid: this.st.user.id,
845 cursor: this.cursor
846 },
847 success: (res) => {
68e19a44
BA
848 const L = res.games.length;
849 if (L > 0) {
95a66034
BA
850 if (
851 this.cursor == Number.MAX_SAFE_INTEGER &&
852 this.games.length == 0 &&
853 this.gdisplay == "live"
854 ) {
855 // First loading: show indicators
856 document
857 .getElementById("btnGcorr")
858 .classList.add("somethingnew");
859 }
0234201f
BA
860 this.cursor = res.games[L - 1].created;
861 let moreGames = res.games.map(g => {
862 const vname = this.getVname(g.vid);
863 return Object.assign(
864 {},
865 g,
866 {
867 type: "corr",
868 vname: vname
869 }
870 );
871 });
872 this.games = this.games.concat(moreGames);
873 } else this.hasMore = false;
874 }
875 }
876 );
877 },
a6bddfc6 878 // Challenge lifecycle:
28b32b4f
BA
879 addChallenge: function(chall) {
880 // NOTE about next condition: see "askchallenges" case.
881 if (
882 !chall.to ||
883 (this.people[chall.from].id > 0 &&
884 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
885 ) {
886 let newChall = Object.assign({}, chall);
887 newChall.type = this.classifyObject(chall);
888 newChall.randomness = chall.randomness;
889 newChall.added = Date.now();
890 let fromValues = Object.assign({}, this.people[chall.from]);
891 delete fromValues["pages"]; //irrelevant in this context
892 newChall.from = Object.assign({ sid: chall.from }, fromValues);
893 newChall.vname = this.getVname(newChall.vid);
894 this.challenges.push(newChall);
895 if (
896 (newChall.type == "live" && this.cdisplay == "corr") ||
897 (newChall.type == "corr" && this.cdisplay == "live")
898 ) {
899 document
900 .getElementById("btnC" + newChall.type)
901 .classList.add("somethingnew");
902 }
903 }
904 },
725da57f
BA
905 loadNewchallVariant: async function(cb) {
906 const vname = this.getVname(this.newchallenge.vid);
32f6285e
BA
907 await import("@/variants/" + vname + ".js")
908 .then((vModule) => {
909 window.V = vModule[vname + "Rules"];
910 this.newchallenge.V = window.V;
911 this.newchallenge.vname = vname;
912 if (!!cb) cb();
913 });
725da57f
BA
914 },
915 trySetNewchallDiag: function() {
916 if (!this.newchallenge.fen) {
917 this.newchallenge.diag = "";
918 return;
919 }
920 // If vid > 0 then the variant is loaded (function above):
921 window.V = this.newchallenge.V;
922 if (
923 this.newchallenge.vid > 0 &&
f9c36b2d 924 !!this.newchallenge.fen &&
725da57f
BA
925 V.IsGoodFen(this.newchallenge.fen)
926 ) {
927 const parsedFen = V.ParseFen(this.newchallenge.fen);
928 this.newchallenge.diag = getDiagram({
929 position: parsedFen.position,
5b4de147 930 orientation: parsedFen.turn
725da57f 931 });
6f2f9437 932 } else this.newchallenge.diag = "";
725da57f 933 },
28b32b4f
BA
934 newChallFromPreset(pchall) {
935 this.partialResetNewchallenge();
936 this.newchallenge.vid = pchall.vid;
937 this.newchallenge.cadence = pchall.cadence;
938 this.newchallenge.randomness = pchall.randomness;
41c5b662 939 this.loadNewchallVariant(this.issueNewChallenge);
28b32b4f
BA
940 },
941 issueNewChallenge: async function() {
188b4a8f 942 if (!!(this.newchallenge.cadence.match(/^[0-9]+$/)))
8477e53d
BA
943 this.newchallenge.cadence += "+0"; //assume minutes, no increment
944 const ctype = this.classifyObject(this.newchallenge);
945 // TODO: cadence still unchecked so ctype could be wrong...
6808d7a1 946 let error = "";
8477e53d 947 if (!this.newchallenge.vid)
6808d7a1 948 error = this.st.tr["Please select a variant"];
8477e53d
BA
949 else if (ctype == "corr" && this.st.user.id <= 0)
950 error = this.st.tr["Please log in to play correspondance games"];
f9c36b2d 951 else if (!!this.newchallenge.to) {
8477e53d
BA
952 if (this.newchallenge.to == this.st.user.name)
953 error = this.st.tr["Self-challenge is forbidden"];
954 else if (
955 ctype == "live" &&
956 Object.values(this.people).every(p => p.name != this.newchallenge.to)
585d0955 957 ) {
8477e53d 958 error = this.newchallenge.to + " " + this.st.tr["is not online"];
585d0955 959 }
8477e53d 960 }
6808d7a1
BA
961 if (error) {
962 alert(error);
963 return;
964 }
725da57f 965 window.V = this.newchallenge.V;
6808d7a1 966 error = checkChallenge(this.newchallenge);
6808d7a1
BA
967 if (error) {
968 alert(error);
969 return;
970 }
bb7dd7db 971 // NOTE: "from" information is not required here
a7808884 972 let chall = Object.assign({}, this.newchallenge);
28b32b4f
BA
973 // Add only if not already issued (not counting target or FEN):
974 if (this.challenges.some(c =>
975 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) &&
976 c.vid == chall.vid &&
977 c.cadence == chall.cadence &&
978 c.randomness == chall.randomness
979 )) {
980 alert(this.st.tr["Challenge already exists"]);
981 return;
982 }
983 if (this.newchallenge.memorize) this.addPresetChall(this.newchallenge);
7ba4a5bc
BA
984 delete chall["V"];
985 delete chall["diag"];
6808d7a1 986 const finishAddChallenge = cid => {
1efe1d79 987 chall.id = cid || "c" + getRandString();
28b32b4f
BA
988 const MAX_ALLOWED_CHALLS = 3;
989 // Remove oldest challenge if 3 found: only 3 at a time of a given type
990 let countMyChalls = 0;
991 let challToDelIdx = 0;
992 let oldestAdded = Number.MAX_SAFE_INTEGER;
993 for (let i=0; i<this.challenges.length; i++) {
994 const c = this.challenges[i];
995 if (
996 c.type == ctype &&
997 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id)
998 ) {
999 countMyChalls++;
1000 if (c.added < oldestAdded) {
1001 challToDelIdx = i;
1002 oldestAdded = c.added;
1003 }
1004 }
1005 }
1006 if (countMyChalls >= MAX_ALLOWED_CHALLS) {
1007 this.send(
1008 "deletechallenge_s",
1009 { data: { cid: this.challenges[challToDelIdx].id } }
1010 );
6808d7a1 1011 if (ctype == "corr") {
e57c4de4
BA
1012 ajax(
1013 "/challenges",
1014 "DELETE",
28b32b4f 1015 { data: { id: this.challenges[challToDelIdx].id } }
e57c4de4 1016 );
5ea8d113 1017 }
28b32b4f 1018 this.challenges.splice(challToDelIdx, 1);
5ea8d113 1019 }
6808d7a1
BA
1020 this.send("newchallenge", {
1021 data: Object.assign({ from: this.st.user.sid }, chall)
1022 });
5ea8d113 1023 // Add new challenge:
6808d7a1 1024 chall.from = {
dcd68c41
BA
1025 sid: this.st.user.sid,
1026 id: this.st.user.id,
6808d7a1 1027 name: this.st.user.name
dcd68c41 1028 };
71468011
BA
1029 chall.added = Date.now();
1030 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
1031 chall.type = ctype;
725da57f 1032 chall.vname = this.newchallenge.vname;
1efe1d79 1033 this.challenges.push(chall);
71468011
BA
1034 // Remember cadence + vid for quicker further challenges:
1035 localStorage.setItem("cadence", chall.cadence);
25d18342 1036 localStorage.setItem("vid", chall.vid);
6b7b2cf7 1037 localStorage.setItem("challRandomness", chall.randomness);
b4d619d1 1038 document.getElementById("modalNewgame").checked = false;
db1f1f9a
BA
1039 // Show the challenge if not on current display
1040 if (
1041 (ctype == "live" && this.cdisplay == "corr") ||
1042 (ctype == "corr" && this.cdisplay == "live")
1043 ) {
1044 this.setDisplay('c', ctype);
1045 }
b4d619d1 1046 };
6808d7a1 1047 if (ctype == "live") {
1efe1d79 1048 // Live challenges have a random ID
71468011 1049 finishAddChallenge(null);
6808d7a1 1050 } else {
b4d619d1 1051 // Correspondance game: send challenge to server
e57c4de4
BA
1052 ajax(
1053 "/challenges",
1054 "POST",
1055 {
1056 data: { chall: chall },
1057 success: (response) => {
f14572c4 1058 finishAddChallenge(response.id);
e57c4de4
BA
1059 }
1060 }
1061 );
9d58ef95 1062 }
fb54f098 1063 },
725da57f
BA
1064 // Callback function after a diagram was showed to accept
1065 // or refuse targetted challenge:
1066 decisionChallenge: function(accepted) {
1067 this.curChallToAccept.accepted = accepted;
1068 this.finishProcessingChallenge(this.curChallToAccept);
1069 document.getElementById("modalAccept").checked = false;
1070 },
1071 finishProcessingChallenge: function(c) {
1072 if (c.accepted) {
1073 c.seat = {
725da57f
BA
1074 sid: this.st.user.sid,
1075 id: this.st.user.id,
1076 name: this.st.user.name
1077 };
1078 this.launchGame(c);
28b32b4f
BA
1079 if (c.type == "live")
1080 // Remove all live challenges of both players
1081 this.send("deletechallenge_s", { data: { sids: [c.from.sid, c.seat.sid] } });
1082 else
1083 // Corr challenge: just remove the challenge
1084 this.send("deletechallenge_s", { data: { cid: c.id } });
725da57f 1085 } else {
f91bc5b0 1086 const oppsid = this.getOppsid(c);
f9c36b2d 1087 if (!!oppsid)
f91bc5b0 1088 this.send("refusechallenge", { data: c.id, target: oppsid });
e57c4de4
BA
1089 if (c.type == "corr") {
1090 ajax(
1091 "/challenges",
1092 "DELETE",
1093 { data: { id: c.id } }
1094 );
1095 }
28b32b4f 1096 this.send("deletechallenge_s", { data: { cid: c.id } });
725da57f 1097 }
725da57f 1098 },
e727fe31 1099 // TODO: if several players click same challenge at the same time: problem
725da57f 1100 clickChallenge: async function(c) {
6808d7a1
BA
1101 const myChallenge =
1102 c.from.sid == this.st.user.sid || //live
1103 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
1104 if (!myChallenge) {
1105 if (c.type == "corr" && this.st.user.id <= 0) {
1106 alert(this.st.tr["Please log in to accept corr challenges"]);
1107 return;
1108 }
a6bddfc6 1109 c.accepted = true;
32f6285e
BA
1110 await import("@/variants/" + c.vname + ".js")
1111 .then((vModule) => {
1112 window.V = vModule[c.vname + "Rules"];
1113 if (!!c.to) {
1114 // c.to == this.st.user.name (connected)
1115 if (!!c.fen) {
1116 const parsedFen = V.ParseFen(c.fen);
1117 c.mycolor = V.GetOppCol(parsedFen.turn);
1118 this.tchallDiag = getDiagram({
1119 position: parsedFen.position,
1120 orientation: c.mycolor
1121 });
1122 }
1123 this.curChallToAccept = c;
1124 document.getElementById("modalAccept").checked = true;
725da57f 1125 }
32f6285e
BA
1126 else this.finishProcessingChallenge(c);
1127 });
725da57f 1128 }
6808d7a1 1129 else {
725da57f 1130 // My challenge
e57c4de4
BA
1131 if (c.type == "corr") {
1132 ajax(
1133 "/challenges",
1134 "DELETE",
1135 { data: { id: c.id } }
1136 );
1137 }
28b32b4f 1138 this.send("deletechallenge_s", { data: { cid: c.id } });
485fccd5 1139 }
5ea8d113 1140 // In all cases, the challenge is consumed:
3d55deea 1141 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
a6bddfc6 1142 },
a64d9122 1143 // NOTE: when launching game, the challenge is already being deleted
725da57f 1144 launchGame: function(c) {
f14572c4
BA
1145 // White player index 0, black player index 1:
1146 const players =
584f81b9
BA
1147 !!c.mycolor
1148 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
1149 : shuffle([c.from, c.seat]);
71468011 1150 // These game informations will be shared
6808d7a1 1151 let gameInfo = {
11667c79 1152 id: getRandString(),
7ba4a5bc 1153 fen: c.fen || V.GenRandInitFen(c.randomness),
0234201f 1154 randomness: c.randomness, //for rematch
f14572c4 1155 players: players,
a6bddfc6 1156 vid: c.vid,
6808d7a1 1157 cadence: c.cadence
a6bddfc6 1158 };
71468011 1159 const notifyNewgame = () => {
f91bc5b0 1160 const oppsid = this.getOppsid(c);
f9c36b2d 1161 if (!!oppsid)
c292ebb2 1162 // Opponent is online
6808d7a1 1163 this.send("startgame", { data: gameInfo, target: oppsid });
f14572c4
BA
1164 // If new corr game, notify Hall (except opponent and me)
1165 if (c.type == "corr") {
1166 this.send(
1167 "newgame",
1168 {
1169 data: gameInfo,
1170 excluded: [this.st.user.sid, oppsid]
1171 }
1172 );
1173 }
585d0955 1174 // Notify MyGames page:
cafe0166
BA
1175 this.send(
1176 "notifynewgame",
1177 {
1178 data: gameInfo,
f14572c4 1179 targets: gameInfo.players
cafe0166
BA
1180 }
1181 );
585d0955
BA
1182 // NOTE: no need to send the game to the room, since I'll connect
1183 // on game just after, the main Hall will be notified.
411d23cd 1184 };
6808d7a1 1185 if (c.type == "live") {
71468011 1186 notifyNewgame();
485fccd5 1187 this.startNewGame(gameInfo);
c292ebb2
BA
1188 } else {
1189 // corr: game only on server
485fccd5
BA
1190 ajax(
1191 "/games",
1192 "POST",
e57c4de4
BA
1193 {
1194 // cid is useful to delete the challenge:
f14572c4
BA
1195 data: {
1196 gameInfo: gameInfo,
1197 cid: c.id
1198 },
e57c4de4 1199 success: (response) => {
f14572c4 1200 gameInfo.id = response.id;
e57c4de4 1201 notifyNewgame();
f14572c4 1202 this.$router.push("/game/" + response.id);
e57c4de4 1203 }
411d23cd 1204 }
485fccd5
BA
1205 );
1206 }
fb54f098 1207 },
a9b131f1 1208 // NOTE: for live games only (corr games start on the server)
42c15a75 1209 startNewGame: function(gameInfo) {
c292ebb2
BA
1210 const game = Object.assign(
1211 {},
1212 gameInfo,
1213 {
1214 // (other) Game infos: constant
1215 fenStart: gameInfo.fen,
1216 vname: this.getVname(gameInfo.vid),
1217 created: Date.now(),
1218 // Game state (including FEN): will be updated
1219 moves: [],
1220 clocks: [-1, -1], //-1 = unstarted
c292ebb2 1221 score: "*"
8477e53d 1222 }
c292ebb2
BA
1223 );
1224 setTimeout(
1225 () => {
1226 GameStorage.add(game, (err) => {
1227 // If an error occurred, game is not added: a tab already
0234201f
BA
1228 // added the game. Maybe a focused one, maybe not.
1229 // We know for sure that it emitted the gong start sound.
1230 // ==> Do not play it again.
1231 if (!err && this.st.settings.sound)
1232 new Audio("/sounds/newgame.flac").play().catch(() => {});
1233 this.$router.push("/game/" + gameInfo.id);
c292ebb2
BA
1234 });
1235 },
1236 document.hidden ? 500 + 1000 * Math.random() : 0
1237 );
6808d7a1
BA
1238 }
1239 }
85e5b5c1 1240};
ccd4a2b7 1241</script>
85e5b5c1 1242
41c80bb6 1243<style lang="sass" scoped>
5bcc9b31
BA
1244.active
1245 color: #42a983
a154d45e
BA
1246
1247#infoDiv > .card
f854c94f
BA
1248 padding: 15px 0
1249 max-width: 430px
a154d45e 1250
725da57f 1251#newgameDiv > .card, #acceptDiv > .card
a154d45e
BA
1252 max-width: 767px
1253 max-height: 100%
1254
bd76b456
BA
1255div#peopleWrap > .card
1256 max-height: 100%
1257
1258@media screen and (min-width: 1281px)
1259 div#peopleWrap > .card
1260 max-width: 66.67%
1261
1262@media screen and (max-width: 1280px)
1263 div#peopleWrap > .card
1264 max-width: 83.33%
1265
1266@media screen and (max-width: 767px)
1267 div#peopleWrap > .card
1268 max-width: 100%
1269
ed06d9e9
BA
1270#players
1271 width: 50%
1272 position: relative
1273 float: left
910d631b 1274
ed06d9e9
BA
1275#chat
1276 width: 50%
1277 float: left
1278 position: relative
910d631b 1279
ed06d9e9
BA
1280@media screen and (max-width: 767px)
1281 #players, #chats
1282 width: 100%
910d631b 1283
72ccbd67
BA
1284#chat > .card
1285 max-width: 100%
1286 margin: 0;
1287 border: none;
910d631b 1288
41c80bb6 1289#players > p
ed06d9e9 1290 margin-left: 5px
910d631b 1291
dcd68c41
BA
1292.anonymous
1293 font-style: italic
910d631b 1294
dcd68c41 1295button.player-action
41c80bb6 1296 margin-left: 32px
2f258c37
BA
1297
1298.somethingnew
1299 background-color: #c5fefe !important
1300
1301.tabbtn
5fe7e71c 1302 background-color: #f9faee
2f258c37 1303
725da57f
BA
1304button.acceptBtn
1305 background-color: lightgreen
1306button.refuseBtn
1307 background-color: red
1308
1309#buttonsTchall
afde7666 1310 // margin-top set dynamically (depends if diagram showed or not)
5b4de147
BA
1311 & > button > span
1312 width: 100%
1313 text-align: center
725da57f
BA
1314
1315.variantName
1316 font-weight: bold
1317
1318.diagram
1319 margin: 0 auto
1320 max-width: 400px
5b4de147
BA
1321 // width: 100% required for Firefox
1322 width: 100%
725da57f
BA
1323
1324#inputFen
1325 width: 100%
1326
2f258c37
BA
1327#div2, #div3
1328 margin-top: 15px
1329@media screen and (max-width: 767px)
1330 #div2, #div3
1331 margin-top: 0
28b32b4f
BA
1332
1333tr > td
1334 &.random-0
1335 background-color: #FF5733
1336 &.random-1
1337 background-color: #2B63B4
1338 &.random-2
1339 background-color: #33B42B
1340
4222cf78
BA
1341@media screen and (max-width: 767px)
1342 h4
1343 margin: 5px 0
1344
0234201f 1345button#loadMoreBtn
f14572c4
BA
1346 display: block
1347 margin: 0 auto
0234201f 1348
28b32b4f
BA
1349td.remove-preset
1350 background-color: lightgrey
1351 text-align: center
1352 & > img
1353 height: 1em
85e5b5c1 1354</style>