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