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