Add some TODOs for simultaneous games support
[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 );
e57c4de4
BA
444 } else addChallenges();
445 }
446 }
447 );
25d18342 448 },
8418f0d7 449 beforeDestroy: function() {
1112f1fd 450 this.cleanBeforeDestroy();
8418f0d7 451 },
fb54f098 452 methods: {
1112f1fd 453 cleanBeforeDestroy: function() {
882ec6fe 454 clearInterval(this.socketCloseListener);
1112f1fd 455 document.removeEventListener('visibilitychange', this.visibilityChange);
f5768809
BA
456 window.removeEventListener('focus', this.onFocus);
457 window.removeEventListener('blur', this.onBlur);
1112f1fd 458 window.removeEventListener("beforeunload", this.cleanBeforeDestroy);
68e3aa8c 459 this.conn.removeEventListener("message", this.socketMessageListener);
1112f1fd 460 this.send("disconnect");
68e3aa8c 461 this.conn = null;
1112f1fd 462 },
28b32b4f
BA
463 getRandomnessClass: function(pc) {
464 return {
465 ["random-" + pc.randomness]: true
466 };
467 },
f1c9d707
BA
468 anonymousCount: function() {
469 let count = 0;
470 Object.values(this.people).forEach(p => {
471 // Do not cound people who did not send their identity yet:
472 count += (!p.name && p.id === 0) ? 1 : 0;
473 });
474 return count;
475 },
a041d5d8
BA
476 visibilityChange: function() {
477 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
f5768809
BA
478 this.focus = (document.visibilityState == "visible");
479 this.send(this.focus ? "getfocus" : "losefocus");
480 },
481 onFocus: function() {
482 this.focus = true;
483 this.send("getfocus");
484 },
485 onBlur: function() {
486 this.focus = false;
487 this.send("losefocus");
a041d5d8 488 },
13227d61
BA
489 invColor: function(c) {
490 if (c == 'w') return this.st.tr["Black"];
491 return this.tr.tr["White"];
492 },
afde7666
BA
493 partialResetNewchallenge: function() {
494 // Reset potential target and custom FEN:
495 this.newchallenge.to = "";
13227d61 496 this.newchallenge.color = '';
afde7666
BA
497 this.newchallenge.fen = "";
498 this.newchallenge.diag = "";
28b32b4f 499 this.newchallenge.memorize = false;
afde7666
BA
500 },
501 showNewchallengeForm: function() {
502 this.partialResetNewchallenge();
503 window.doClick("modalNewgame");
504 },
28b32b4f
BA
505 addPresetChall: function(chall) {
506 // Add only if not already existing:
507 if (this.presetChalls.some(c =>
508 c.vid == chall.vid &&
509 c.cadence == chall.cadence &&
510 c.randomness == chall.randomness
511 )) {
512 return;
513 }
514 const L = this.presetChalls.length;
515 this.presetChalls.push({
516 index: L,
517 vid: chall.vid,
518 vname: chall.vname, //redundant, but easier
519 cadence: chall.cadence,
520 randomness: chall.randomness
521 });
522 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
523 },
524 removePresetChall: function(e, pchall) {
525 e.stopPropagation();
2c5d7b20
BA
526 const pchallIdx =
527 this.presetChalls.findIndex(pc => pc.index == pchall.index);
28b32b4f
BA
528 this.presetChalls.splice(pchallIdx, 1);
529 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
530 },
afde7666
BA
531 tchallButtonsMargin: function() {
532 if (!!this.curChallToAccept.fen) return { "margin-top": "10px" };
533 return {};
534 },
6f2f9437
BA
535 changeChallTarget: function() {
536 if (!this.newchallenge.to) {
537 // Reset potential FEN + diagram
538 this.newchallenge.fen = "";
13227d61 539 this.newchallenge.color = '';
6f2f9437
BA
540 this.newchallenge.diag = "";
541 }
542 },
09d37571
BA
543 cadenceFocusIfOpened: function() {
544 if (event.target.checked)
545 document.getElementById("cadence").focus();
546 },
71468011 547 send: function(code, obj) {
5a187b07 548 if (!!this.conn && this.conn.readyState == 1) {
6808d7a1 549 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
51d87b52 550 }
71468011
BA
551 },
552 getVname: function(vid) {
553 const variant = this.st.variants.find(v => v.id == vid);
554 // this.st.variants might be uninitialized (variant == null)
6808d7a1 555 return variant ? variant.name : "";
71468011 556 },
6855163c
BA
557 filterChallenges: function(type) {
558 return this.challenges.filter(c => c.type == type);
559 },
560 filterGames: function(type) {
a9b131f1 561 return this.games.filter(g => g.type == type);
6855163c 562 },
c74b3e5c 563 // o: challenge or game
6808d7a1 564 classifyObject: function(o) {
bf588c57
BA
565 // No imported games here
566 return (
7805351e 567 o.cadence.indexOf("d") >= 0
bf588c57 568 ? "corr"
7805351e 569 : (o.cadence.indexOf("/") >= 0 ? "simul" : "live")
bf588c57 570 );
a6bddfc6 571 },
5bcc9b31
BA
572 setDisplay: function(letter, type, e) {
573 this[letter + "display"] = type;
6808d7a1
BA
574 localStorage.setItem(
575 "type-" + (letter == "c" ? "challenges" : "games"),
576 type
577 );
578 let elt = e
7f36b53a
BA
579 ? e.target
580 : document.getElementById("btn" + letter.toUpperCase() + type);
581 elt.classList.add("active");
2f258c37 582 elt.classList.remove("somethingnew"); //in case of
f9c36b2d 583 if (!!elt.previousElementSibling)
7f36b53a 584 elt.previousElementSibling.classList.remove("active");
6808d7a1 585 else elt.nextElementSibling.classList.remove("active");
7f36b53a
BA
586 },
587 isGamer: function(sid) {
7ebc0408
BA
588 return Object.values(this.people[sid].tmpIds)
589 .some(v => v.focus && v.page.indexOf("/game/") >= 0);
a041d5d8
BA
590 },
591 isFocusedOnHall: function(sid) {
592 return (
593 // This is meant to challenge people, thus the next 2 conditions:
594 this.st.user.id > 0 &&
595 sid != this.st.user.sid &&
2c5d7b20
BA
596 Object.values(this.people[sid].tmpIds)
597 .some(v => v.focus && v.page == "/")
a041d5d8 598 );
7f36b53a 599 },
6d6f45bc 600 challenge: function(sid) {
afde7666
BA
601 this.partialResetNewchallenge();
602 // Available, in Hall
6d6f45bc 603 this.newchallenge.to = this.people[sid].name;
28b32b4f 604 // TODO: also store target sid to not re-search for it
6d6f45bc
BA
605 document.getElementById("modalPeople").checked = false;
606 window.doClick("modalNewgame");
ac8f441c 607 },
6d6f45bc
BA
608 watchGame: function(sid) {
609 // In some game, maybe playing maybe not: show a random one
610 let gids = [];
7ebc0408
BA
611 Object.values(this.people[sid].tmpIds).forEach(v => {
612 if (v.focus) {
613 const matchGid = v.page.match(/[a-zA-Z0-9]+$/);
a041d5d8
BA
614 if (!!matchGid) gids.push(matchGid[0]);
615 }
6d6f45bc
BA
616 });
617 const gid = gids[Math.floor(Math.random() * gids.length)];
1c15969e 618 window.open("/#/game/" + gid, "_blank");
71468011 619 },
51d87b52 620 showGame: function(g) {
71468011
BA
621 // NOTE: we are an observer, since only games I don't play are shown here
622 // ==> Moves sent by connected remote player(s) if live game
1c15969e 623 window.open("/#/game/" + g.id, "_blank");
71468011 624 },
077ba344
BA
625 toggleSocialColor: function(action) {
626 if (!action && document.getElementById("modalPeople").checked)
627 document.getElementById("inputChat").focus();
628 else
629 document.getElementById("peopleBtn").classList.remove("somethingnew");
bd76b456 630 },
71468011 631 processChat: function(chat) {
6808d7a1 632 this.send("newchat", { data: chat });
a6bddfc6 633 },
f91bc5b0
BA
634 getOppsid: function(c) {
635 let oppsid = c.from.sid; //may not be defined if corr + offline opp
636 if (!oppsid) {
637 oppsid = Object.keys(this.people).find(
638 sid => this.people[sid].id == c.from.id
639 );
640 }
641 return oppsid;
642 },
a6bddfc6 643 // Messaging center:
9d58ef95 644 socketMessageListener: function(msg) {
6808d7a1 645 if (!this.conn) return;
9d58ef95 646 const data = JSON.parse(msg.data);
6808d7a1
BA
647 switch (data.code) {
648 case "pollclientsandgamers": {
7ebc0408
BA
649 // TODO: shuffling and random filtering on server,
650 // if the room is really crowded.
651 Object.keys(data.sockIds).forEach(sid => {
7ebc0408
BA
652 if (sid != this.st.user.sid) {
653 // Pick a target tmpId (+page) at random:
654 const pt = Object.values(data.sockIds[sid]);
655 const randPage = pt[randInt(pt.length)].page;
656 this.send(
657 "askidentity",
658 {
659 target: sid,
660 page: randPage
661 }
662 );
71468011 663 }
7ebc0408 664 if (!this.people[sid])
efdfb4c7 665 // Do not set name or id: identity unknown yet
7ebc0408
BA
666 this.people[sid] = { tmpIds: data.sockIds[sid] };
667 else
882ec6fe 668 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
7ebc0408 669 if (Object.values(data.sockIds[sid]).some(v => v.page == "/"))
efdfb4c7 670 // Peer is in Hall
7ebc0408
BA
671 this.send("askchallenges", { target: sid });
672 Object.values(data.sockIds[sid]).forEach(v => {
673 if (
674 v.page.indexOf("/game/") >= 0 &&
675 !v.page.match(/\/[0-9]+$/)
676 ) {
677 // Peer is in Game: ask only if live game
678 this.send("askgame", { target: sid, page: v.page });
679 }
680 });
5a3da968 681 });
ac8f441c 682 break;
71468011
BA
683 }
684 case "connect":
6808d7a1 685 case "gconnect": {
7f36b53a 686 const page = data.page || "/";
f54f4c26
BA
687 if (data.code == "connect") {
688 // Ask challenges only on first connexion:
49dad261 689 if (!this.people[data.from[0]])
7ebc0408 690 this.send("askchallenges", { target: data.from[0] });
f54f4c26
BA
691 }
692 // Ask game only if live:
693 else if (!page.match(/\/[0-9]+$/))
7ebc0408 694 this.send("askgame", { target: data.from[0], page: page });
49dad261 695 if (!this.people[data.from[0]]) {
7ebc0408
BA
696 this.$set(
697 this.people,
698 data.from[0],
699 {
700 tmpIds: {
701 [data.from[1]]: { page: page, focus: true }
702 }
703 }
704 );
49dad261
BA
705 // For self multi-connects tests:
706 this.newConnect[data.from[0]] = true;
7ebc0408
BA
707 this.send("askidentity", { target: data.from[0], page: page });
708 } else {
709 this.people[data.from[0]].tmpIds[data.from[1]] =
710 { page: page, focus: true };
711 this.$forceUpdate(); //TODO: shouldn't be required
51d87b52 712 }
71468011 713 break;
7f36b53a 714 }
71468011 715 case "disconnect":
6808d7a1 716 case "gdisconnect": {
2c5d7b20
BA
717 // If the user reloads the page twice very quickly
718 // (experienced with Firefox), the first reload won't have time to
719 // connect but will trigger a "close" event anyway.
092de306 720 // ==> Next check is required.
7ebc0408
BA
721 if (!this.people[data.from[0]]) return;
722 delete this.people[data.from[0]].tmpIds[data.from[1]];
723 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
724 this.$delete(this.people, data.from[0]);
a2bd587a 725 else this.$forceUpdate(); //TODO: shouldn't be required
6808d7a1 726 if (data.code == "disconnect") {
aef58d08
BA
727 // Remove the live challenges sent by this player, if
728 // he isn't connected on another tab:
729 if (
730 !this.people[data.from[0]] ||
731 Object.values(this.people[data.from[0]].tmpIds)
732 .every(v => v.page != "/")
733 ) {
734 ArrayFun.remove(
735 this.challenges,
736 c => c.type == "live" && c.from.sid == data.from[0],
737 "all"
738 );
739 }
6808d7a1 740 } else {
51d87b52 741 // Remove the matching live game if now unreachable
7ebc0408 742 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
585d0955
BA
743 // Corr games are always reachable:
744 if (!gid.match(/^[0-9]+$/)) {
2c5d7b20 745 // Live games are reachable if someone is on the game page
f54f4c26 746 if (Object.values(this.people).every(p =>
7ebc0408
BA
747 Object.values(p.tmpIds).every(v => v.page != data.page))
748 ) {
f54f4c26 749 ArrayFun.remove(this.games, g => g.id == gid);
51d87b52 750 }
71468011
BA
751 }
752 }
51d87b52 753 break;
6808d7a1 754 }
7ebc0408
BA
755 case "getfocus": {
756 let player = this.people[data.from[0]];
a041d5d8 757 // If user reload a page, focus may arrive earlier than connect
7ebc0408
BA
758 if (!!player) {
759 player.tmpIds[data.from[1]].focus = true;
a041d5d8
BA
760 this.$forceUpdate(); //TODO: shouldn't be required
761 }
762 break;
7ebc0408
BA
763 }
764 case "losefocus": {
765 let player = this.people[data.from[0]];
766 if (!!player) {
767 player.tmpIds[data.from[1]].focus = false;
a041d5d8
BA
768 this.$forceUpdate(); //TODO: shouldn't be required
769 }
770 break;
7ebc0408 771 }
6808d7a1 772 case "askidentity": {
585d0955 773 // Request for identification
51d87b52
BA
774 const me = {
775 // Decompose to avoid revealing email
776 name: this.st.user.name,
777 sid: this.st.user.sid,
6808d7a1 778 id: this.st.user.id
51d87b52 779 };
6808d7a1 780 this.send("identity", { data: me, target: data.from });
5a3da968 781 break;
51d87b52 782 }
6808d7a1 783 case "identity": {
71468011 784 const user = data.data;
a041d5d8 785 let player = this.people[user.sid];
7ebc0408 786 // player.tmpIds is already set
a041d5d8
BA
787 player.id = user.id;
788 player.name = user.name;
789 // TODO: this.$set(people, ...) fails. So forceUpdate.
790 // But this shouldn't be like that!
791 this.$forceUpdate();
f9c36b2d
BA
792 // If I multi-connect, kill current connexion if no mark (I'm older)
793 if (this.newConnect[user.sid]) {
49dad261 794 delete this.newConnect[user.sid];
6808d7a1 795 if (
6808d7a1
BA
796 user.id > 0 &&
797 user.id == this.st.user.id &&
49dad261 798 user.sid != this.st.user.sid
6808d7a1 799 ) {
49dad261
BA
800 // I logged in elsewhere:
801 this.cleanBeforeDestroy();
802 alert(this.st.tr["New connexion detected: tab now offline"]);
51d87b52 803 }
51d87b52 804 }
dcd68c41 805 break;
71468011 806 }
28b32b4f
BA
807 case "askchallenges": {
808 // Send my current live challenges (if any)
809 const myChallenges = this.challenges
810 .filter(c =>
811 c.from.sid == this.st.user.sid && c.type == "live"
812 )
813 .map(c => {
2c5d7b20
BA
814 // NOTE: in principle, should only send targeted challenge to the
815 // target. But we may not know yet the identity of the target
816 // (just name), so can't decide if data.from is the target.
28b32b4f
BA
817 return {
818 id: c.id,
819 from: this.st.user.sid,
820 to: c.to,
821 randomness: c.randomness,
822 fen: c.fen,
823 vid: c.vid,
824 cadence: c.cadence,
825 added: c.added
826 };
827 });
828 if (myChallenges.length > 0)
829 this.send("challenges", { data: myChallenges, target: data.from });
81d9ce72 830 break;
1efe1d79 831 }
28b32b4f
BA
832 case "challenges": //after "askchallenges"
833 data.data.forEach(this.addChallenge);
834 break;
835 case "newchallenge":
836 this.addChallenge(data.data);
81d9ce72 837 break;
6808d7a1 838 case "refusechallenge": {
71468011
BA
839 const cid = data.data;
840 ArrayFun.remove(this.challenges, c => c.id == cid);
841 alert(this.st.tr["Challenge declined"]);
842 break;
843 }
28b32b4f
BA
844 case "deletechallenge_s": {
845 // NOTE: the challenge(s) may be already removed
846 const cref = data.data;
2c5d7b20
BA
847 if (!!cref.cid)
848 ArrayFun.remove(this.challenges, c => c.id == cref.cid);
28b32b4f
BA
849 else if (!!cref.sids) {
850 cref.sids.forEach(s => {
851 ArrayFun.remove(
852 this.challenges,
853 c => c.type == "live" && c.from.sid == s,
854 "all"
855 );
856 });
857 }
71468011
BA
858 break;
859 }
beda3dd0
BA
860 case "entersimul":
861 // TODO: confirm box accept/refuse.
862 // If accept, update seat (array in this case)
863 break;
f14572c4
BA
864 case "game": // Individual request
865 case "newgame": {
71468011 866 const game = data.data;
f54f4c26
BA
867 // Ignore games where I play (will go in MyGames page),
868 // and also games that I already received.
869 if (
6c7cbfed 870 this.games.findIndex(g => g.id == game.id) == -1 &&
50bd1184
BA
871 game.players.every(p => {
872 return (
873 p.sid != this.st.user.sid &&
874 (p.id == 0 || p.id != this.st.user.id)
875 );
6c7cbfed 876 })
f54f4c26
BA
877 ) {
878 let newGame = game;
879 newGame.type = this.classifyObject(game);
880 newGame.vname = this.getVname(game.vid);
881 if (!game.score)
882 // New game from Hall
883 newGame.score = "*";
884 this.games.push(newGame);
885 if (
6c7cbfed 886 newGame.score == '*' &&
f54f4c26
BA
887 (newGame.type == "live" && this.gdisplay == "corr") ||
888 (newGame.type == "corr" && this.gdisplay == "live")
889 ) {
890 document
891 .getElementById("btnG" + newGame.type)
892 .classList.add("somethingnew");
2f258c37 893 }
51d87b52 894 }
81d9ce72 895 break;
1efe1d79 896 }
6808d7a1 897 case "result": {
48ab808f 898 let g = this.games.find(g => g.id == data.gid);
28b32b4f 899 if (!!g) g.score = data.score;
48ab808f
BA
900 break;
901 }
6808d7a1 902 case "startgame": {
c292ebb2 903 // New game just started, I'm involved
71468011
BA
904 const gameInfo = data.data;
905 if (this.classifyObject(gameInfo) == "live")
906 this.startNewGame(gameInfo);
6808d7a1
BA
907 else {
908 this.infoMessage =
b70a32d4 909 this.st.tr["New correspondence game:"] + " " +
7ebc0408
BA
910 "<a href='#/game/" + gameInfo.id + "'>" +
911 "#/game/" + gameInfo.id + "</a>";
c292ebb2 912 document.getElementById("modalInfo").checked = true;
5d04793e 913 }
9d58ef95 914 break;
71468011 915 }
ac8f441c 916 case "newchat":
95a66034 917 this.$refs["chatcomp"].newChat(data.data);
bd76b456 918 if (!document.getElementById("modalPeople").checked)
2f258c37 919 document.getElementById("peopleBtn").classList.add("somethingnew");
9d58ef95
BA
920 break;
921 }
922 },
95a66034 923 loadMoreCorr: function() {
0234201f
BA
924 ajax(
925 "/observedgames",
926 "GET",
927 {
928 data: {
929 uid: this.st.user.id,
930 cursor: this.cursor
931 },
932 success: (res) => {
68e19a44
BA
933 const L = res.games.length;
934 if (L > 0) {
95a66034
BA
935 if (
936 this.cursor == Number.MAX_SAFE_INTEGER &&
937 this.games.length == 0 &&
6c7cbfed
BA
938 this.gdisplay == "live" &&
939 res.games.some(g => g.score == '*')
95a66034
BA
940 ) {
941 // First loading: show indicators
942 document
943 .getElementById("btnGcorr")
944 .classList.add("somethingnew");
945 }
0234201f
BA
946 this.cursor = res.games[L - 1].created;
947 let moreGames = res.games.map(g => {
948 const vname = this.getVname(g.vid);
949 return Object.assign(
950 {},
951 g,
952 {
953 type: "corr",
954 vname: vname
955 }
956 );
957 });
958 this.games = this.games.concat(moreGames);
959 } else this.hasMore = false;
960 }
961 }
962 );
963 },
a6bddfc6 964 // Challenge lifecycle:
28b32b4f
BA
965 addChallenge: function(chall) {
966 // NOTE about next condition: see "askchallenges" case.
967 if (
968 !chall.to ||
969 (this.people[chall.from].id > 0 &&
970 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
971 ) {
972 let newChall = Object.assign({}, chall);
973 newChall.type = this.classifyObject(chall);
974 newChall.randomness = chall.randomness;
975 newChall.added = Date.now();
976 let fromValues = Object.assign({}, this.people[chall.from]);
977 delete fromValues["pages"]; //irrelevant in this context
978 newChall.from = Object.assign({ sid: chall.from }, fromValues);
979 newChall.vname = this.getVname(newChall.vid);
980 this.challenges.push(newChall);
981 if (
982 (newChall.type == "live" && this.cdisplay == "corr") ||
983 (newChall.type == "corr" && this.cdisplay == "live")
984 ) {
985 document
986 .getElementById("btnC" + newChall.type)
987 .classList.add("somethingnew");
988 }
bfa7d993
BA
989 if (!!chall.to) {
990 notify(
991 "New challenge",
992 // fromValues.name should exist since the player is online, but
993 // let's consider there is some chance that the challenge arrives
994 // right after we connected and before receiving the poll result:
995 { body: "from " + (fromValues.name || "unknown yet...") }
996 );
997 }
28b32b4f
BA
998 }
999 },
13227d61
BA
1000 loadNewchallVariant: async function(cb, vname) {
1001 vname = vname || this.getVname(this.newchallenge.vid);
32f6285e
BA
1002 await import("@/variants/" + vname + ".js")
1003 .then((vModule) => {
1004 window.V = vModule[vname + "Rules"];
1005 this.newchallenge.V = window.V;
1006 this.newchallenge.vname = vname;
1007 if (!!cb) cb();
1008 });
725da57f
BA
1009 },
1010 trySetNewchallDiag: function() {
1011 if (!this.newchallenge.fen) {
1012 this.newchallenge.diag = "";
1013 return;
1014 }
1015 // If vid > 0 then the variant is loaded (function above):
1016 window.V = this.newchallenge.V;
1017 if (
1018 this.newchallenge.vid > 0 &&
f9c36b2d 1019 !!this.newchallenge.fen &&
725da57f
BA
1020 V.IsGoodFen(this.newchallenge.fen)
1021 ) {
1022 const parsedFen = V.ParseFen(this.newchallenge.fen);
1023 this.newchallenge.diag = getDiagram({
13227d61
BA
1024 position: parsedFen.position
1025 //,orientation: parsedFen.turn
725da57f 1026 });
6f2f9437 1027 } else this.newchallenge.diag = "";
725da57f 1028 },
28b32b4f
BA
1029 newChallFromPreset(pchall) {
1030 this.partialResetNewchallenge();
1031 this.newchallenge.vid = pchall.vid;
1032 this.newchallenge.cadence = pchall.cadence;
1033 this.newchallenge.randomness = pchall.randomness;
41c5b662 1034 this.loadNewchallVariant(this.issueNewChallenge);
28b32b4f
BA
1035 },
1036 issueNewChallenge: async function() {
188b4a8f 1037 if (!!(this.newchallenge.cadence.match(/^[0-9]+$/)))
8477e53d
BA
1038 this.newchallenge.cadence += "+0"; //assume minutes, no increment
1039 const ctype = this.classifyObject(this.newchallenge);
1040 // TODO: cadence still unchecked so ctype could be wrong...
6808d7a1 1041 let error = "";
8477e53d 1042 if (!this.newchallenge.vid)
6808d7a1 1043 error = this.st.tr["Please select a variant"];
8477e53d 1044 else if (ctype == "corr" && this.st.user.id <= 0)
b70a32d4 1045 error = this.st.tr["Please log in to play correspondence games"];
13227d61
BA
1046 else if (!this.newchallenge.to && !!this.newchallenge.color)
1047 error = this.st.tr["Color option only for targeted challenge"];
f9c36b2d 1048 else if (!!this.newchallenge.to) {
8477e53d
BA
1049 if (this.newchallenge.to == this.st.user.name)
1050 error = this.st.tr["Self-challenge is forbidden"];
1051 else if (
1052 ctype == "live" &&
1053 Object.values(this.people).every(p => p.name != this.newchallenge.to)
585d0955 1054 ) {
8477e53d 1055 error = this.newchallenge.to + " " + this.st.tr["is not online"];
585d0955 1056 }
13227d61
BA
1057 if (
1058 !!this.newchallenge.color &&
1059 !['w', 'b'].includes(this.newchallenge.color)
1060 ) {
1061 error = this.st.tr["Wrong color"];
1062 }
8477e53d 1063 }
13227d61 1064 if (!!error) {
6808d7a1
BA
1065 alert(error);
1066 return;
1067 }
725da57f 1068 window.V = this.newchallenge.V;
6808d7a1 1069 error = checkChallenge(this.newchallenge);
6808d7a1
BA
1070 if (error) {
1071 alert(error);
1072 return;
1073 }
bb7dd7db 1074 // NOTE: "from" information is not required here
a7808884 1075 let chall = Object.assign({}, this.newchallenge);
13227d61 1076 // Add only if not already issued (not counting FEN):
28b32b4f 1077 if (this.challenges.some(c =>
50bd1184
BA
1078 (
1079 c.from.sid == this.st.user.sid ||
1080 (c.from.id > 0 && c.from.id == this.st.user.id)
1081 )
1082 &&
13227d61
BA
1083 (
1084 (!c.to && !chall.to) ||
1085 c.to == chall.to
1086 )
1087 &&
28b32b4f
BA
1088 c.vid == chall.vid &&
1089 c.cadence == chall.cadence &&
1090 c.randomness == chall.randomness
1091 )) {
1092 alert(this.st.tr["Challenge already exists"]);
1093 return;
1094 }
1095 if (this.newchallenge.memorize) this.addPresetChall(this.newchallenge);
7ba4a5bc
BA
1096 delete chall["V"];
1097 delete chall["diag"];
6808d7a1 1098 const finishAddChallenge = cid => {
1efe1d79 1099 chall.id = cid || "c" + getRandString();
28b32b4f
BA
1100 const MAX_ALLOWED_CHALLS = 3;
1101 // Remove oldest challenge if 3 found: only 3 at a time of a given type
1102 let countMyChalls = 0;
1103 let challToDelIdx = 0;
1104 let oldestAdded = Number.MAX_SAFE_INTEGER;
1105 for (let i=0; i<this.challenges.length; i++) {
1106 const c = this.challenges[i];
1107 if (
1108 c.type == ctype &&
50bd1184
BA
1109 (
1110 c.from.sid == this.st.user.sid ||
1111 (c.from.id > 0 && c.from.id == this.st.user.id)
1112 )
28b32b4f
BA
1113 ) {
1114 countMyChalls++;
1115 if (c.added < oldestAdded) {
1116 challToDelIdx = i;
1117 oldestAdded = c.added;
1118 }
1119 }
1120 }
1121 if (countMyChalls >= MAX_ALLOWED_CHALLS) {
1122 this.send(
1123 "deletechallenge_s",
1124 { data: { cid: this.challenges[challToDelIdx].id } }
1125 );
6808d7a1 1126 if (ctype == "corr") {
e57c4de4
BA
1127 ajax(
1128 "/challenges",
1129 "DELETE",
28b32b4f 1130 { data: { id: this.challenges[challToDelIdx].id } }
e57c4de4 1131 );
5ea8d113 1132 }
28b32b4f 1133 this.challenges.splice(challToDelIdx, 1);
5ea8d113 1134 }
6808d7a1
BA
1135 this.send("newchallenge", {
1136 data: Object.assign({ from: this.st.user.sid }, chall)
1137 });
5ea8d113 1138 // Add new challenge:
6808d7a1 1139 chall.from = {
dcd68c41
BA
1140 sid: this.st.user.sid,
1141 id: this.st.user.id,
6808d7a1 1142 name: this.st.user.name
dcd68c41 1143 };
71468011 1144 chall.added = Date.now();
2c5d7b20 1145 // NOTE: vname and type are redundant (deduced from cadence + vid)
71468011 1146 chall.type = ctype;
725da57f 1147 chall.vname = this.newchallenge.vname;
1efe1d79 1148 this.challenges.push(chall);
71468011
BA
1149 // Remember cadence + vid for quicker further challenges:
1150 localStorage.setItem("cadence", chall.cadence);
25d18342 1151 localStorage.setItem("vid", chall.vid);
6b7b2cf7 1152 localStorage.setItem("challRandomness", chall.randomness);
b4d619d1 1153 document.getElementById("modalNewgame").checked = false;
db1f1f9a
BA
1154 // Show the challenge if not on current display
1155 if (
1156 (ctype == "live" && this.cdisplay == "corr") ||
1157 (ctype == "corr" && this.cdisplay == "live")
1158 ) {
1159 this.setDisplay('c', ctype);
1160 }
b4d619d1 1161 };
6808d7a1 1162 if (ctype == "live") {
1efe1d79 1163 // Live challenges have a random ID
71468011 1164 finishAddChallenge(null);
6808d7a1 1165 } else {
b70a32d4 1166 // Correspondence game: send challenge to server
e57c4de4
BA
1167 ajax(
1168 "/challenges",
1169 "POST",
1170 {
1171 data: { chall: chall },
1172 success: (response) => {
f14572c4 1173 finishAddChallenge(response.id);
e57c4de4
BA
1174 }
1175 }
1176 );
9d58ef95 1177 }
fb54f098 1178 },
725da57f
BA
1179 // Callback function after a diagram was showed to accept
1180 // or refuse targetted challenge:
1181 decisionChallenge: function(accepted) {
1182 this.curChallToAccept.accepted = accepted;
1183 this.finishProcessingChallenge(this.curChallToAccept);
1184 document.getElementById("modalAccept").checked = false;
1185 },
1186 finishProcessingChallenge: function(c) {
1187 if (c.accepted) {
1188 c.seat = {
725da57f
BA
1189 sid: this.st.user.sid,
1190 id: this.st.user.id,
1191 name: this.st.user.name
1192 };
1193 this.launchGame(c);
2c5d7b20 1194 if (c.type == "live") {
28b32b4f 1195 // Remove all live challenges of both players
2c5d7b20
BA
1196 this.send(
1197 "deletechallenge_s",
1198 { data: { sids: [c.from.sid, c.seat.sid] } }
1199 );
1200 }
28b32b4f
BA
1201 else
1202 // Corr challenge: just remove the challenge
1203 this.send("deletechallenge_s", { data: { cid: c.id } });
725da57f 1204 } else {
f91bc5b0 1205 const oppsid = this.getOppsid(c);
f9c36b2d 1206 if (!!oppsid)
f91bc5b0 1207 this.send("refusechallenge", { data: c.id, target: oppsid });
e57c4de4
BA
1208 if (c.type == "corr") {
1209 ajax(
1210 "/challenges",
1211 "DELETE",
1212 { data: { id: c.id } }
1213 );
1214 }
28b32b4f 1215 this.send("deletechallenge_s", { data: { cid: c.id } });
725da57f 1216 }
725da57f 1217 },
e727fe31 1218 // TODO: if several players click same challenge at the same time: problem
725da57f 1219 clickChallenge: async function(c) {
6808d7a1
BA
1220 const myChallenge =
1221 c.from.sid == this.st.user.sid || //live
1222 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
1223 if (!myChallenge) {
1224 if (c.type == "corr" && this.st.user.id <= 0) {
1225 alert(this.st.tr["Please log in to accept corr challenges"]);
1226 return;
1227 }
beda3dd0
BA
1228 if (c.type == "simul") {
1229 // Just notify that I wanna enter the simultaneous game(s)
1230 // TODO: dans défi, indiquer si positions aleatoires, si tjours blancs ou noirs
1231 // --> /w30 ou b1h ou juste 30 (random, sans préfixe).
1232 // => message "entersimul" to c.from
1233 return;
1234 }
1235 else {
1236 c.accepted = true;
1237 await import("@/variants/" + c.vname + ".js")
1238 .then((vModule) => {
1239 window.V = vModule[c.vname + "Rules"];
1240 if (!!c.to) {
1241 // c.to == this.st.user.name (connected)
1242 if (!!c.fen) {
1243 const parsedFen = V.ParseFen(c.fen);
1244 this.tchallDiag = getDiagram({
1245 position: parsedFen.position,
1246 orientation: parsedFen.turn
1247 });
1248 }
1249 this.curChallToAccept = c;
1250 document.getElementById("modalAccept").checked = true;
32f6285e 1251 }
beda3dd0
BA
1252 else this.finishProcessingChallenge(c);
1253 });
1254 }
725da57f 1255 }
6808d7a1 1256 else {
725da57f 1257 // My challenge
e57c4de4
BA
1258 if (c.type == "corr") {
1259 ajax(
1260 "/challenges",
1261 "DELETE",
1262 { data: { id: c.id } }
1263 );
1264 }
beda3dd0
BA
1265 else if (c.type == "simul" && !!c.seat && Array.isArray(c.seat))
1266 // TODO: if some players entered, start game
1267 this.launchSimultaneous(c);
28b32b4f 1268 this.send("deletechallenge_s", { data: { cid: c.id } });
485fccd5 1269 }
5ea8d113 1270 // In all cases, the challenge is consumed:
3d55deea 1271 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
a6bddfc6 1272 },
a64d9122 1273 // NOTE: when launching game, the challenge is already being deleted
beda3dd0
BA
1274 // TODO: adapt for simultaneous games, or just write a new function (better)
1275 launchSimultaneous: function(c) {
1276 // TODO
1277 },
725da57f 1278 launchGame: function(c) {
f14572c4 1279 // White player index 0, black player index 1:
3d65195b 1280 let players =
13227d61
BA
1281 !!c.color
1282 ? (c.color == "w" ? [c.from, c.seat] : [c.seat, c.from])
584f81b9 1283 : shuffle([c.from, c.seat]);
3d65195b
BA
1284 players.forEach(p => {
1285 if (!!p["tmpIds"]) delete p["tmpIds"];
1286 });
71468011 1287 // These game informations will be shared
6808d7a1 1288 let gameInfo = {
11667c79 1289 id: getRandString(),
7ba4a5bc 1290 fen: c.fen || V.GenRandInitFen(c.randomness),
0234201f 1291 randomness: c.randomness, //for rematch
f14572c4 1292 players: players,
a6bddfc6 1293 vid: c.vid,
6808d7a1 1294 cadence: c.cadence
a6bddfc6 1295 };
71468011 1296 const notifyNewgame = () => {
f91bc5b0 1297 const oppsid = this.getOppsid(c);
f9c36b2d 1298 if (!!oppsid)
c292ebb2 1299 // Opponent is online
6808d7a1 1300 this.send("startgame", { data: gameInfo, target: oppsid });
f14572c4
BA
1301 // If new corr game, notify Hall (except opponent and me)
1302 if (c.type == "corr") {
1303 this.send(
1304 "newgame",
1305 {
1306 data: gameInfo,
1307 excluded: [this.st.user.sid, oppsid]
1308 }
1309 );
1310 }
585d0955 1311 // Notify MyGames page:
cafe0166
BA
1312 this.send(
1313 "notifynewgame",
1314 {
1315 data: gameInfo,
f14572c4 1316 targets: gameInfo.players
cafe0166
BA
1317 }
1318 );
585d0955
BA
1319 // NOTE: no need to send the game to the room, since I'll connect
1320 // on game just after, the main Hall will be notified.
411d23cd 1321 };
6808d7a1 1322 if (c.type == "live") {
71468011 1323 notifyNewgame();
485fccd5 1324 this.startNewGame(gameInfo);
c292ebb2
BA
1325 } else {
1326 // corr: game only on server
485fccd5
BA
1327 ajax(
1328 "/games",
1329 "POST",
e57c4de4
BA
1330 {
1331 // cid is useful to delete the challenge:
f14572c4
BA
1332 data: {
1333 gameInfo: gameInfo,
1334 cid: c.id
1335 },
e57c4de4 1336 success: (response) => {
f14572c4 1337 gameInfo.id = response.id;
e57c4de4 1338 notifyNewgame();
f14572c4 1339 this.$router.push("/game/" + response.id);
e57c4de4 1340 }
411d23cd 1341 }
485fccd5
BA
1342 );
1343 }
fb54f098 1344 },
a9b131f1 1345 // NOTE: for live games only (corr games start on the server)
42c15a75 1346 startNewGame: function(gameInfo) {
c292ebb2
BA
1347 const game = Object.assign(
1348 {},
1349 gameInfo,
1350 {
1351 // (other) Game infos: constant
1352 fenStart: gameInfo.fen,
1353 vname: this.getVname(gameInfo.vid),
1354 created: Date.now(),
1355 // Game state (including FEN): will be updated
1356 moves: [],
1357 clocks: [-1, -1], //-1 = unstarted
1a021529 1358 chats: [],
c292ebb2 1359 score: "*"
8477e53d 1360 }
c292ebb2
BA
1361 );
1362 setTimeout(
1363 () => {
f5768809 1364 const myIdx = (game.players[0].sid == this.st.user.sid ? 0 : 1);
c292ebb2 1365 GameStorage.add(game, (err) => {
57078452
BA
1366 // If an error occurred, game is not added: the focused tab
1367 // already added the game.
f5768809 1368 if (!this.focus) {
57078452
BA
1369 if (this.st.settings.sound)
1370 // This will be played several times if several hidden tabs
1371 // on Hall... TODO: fix that (how ?!)
1372 new Audio("/sounds/newgame.flac").play().catch(() => {});
f5768809
BA
1373 notify(
1374 "New live game",
1375 { body: "vs " + game.players[1-myIdx].name || "@nonymous" }
1376 );
1377 }
4f524197 1378 this.$router.push("/game/" + gameInfo.id);
c292ebb2
BA
1379 });
1380 },
1f6bf26c 1381 this.focus ? 0 : 500 + 1000 * Math.random()
c292ebb2 1382 );
6808d7a1
BA
1383 }
1384 }
85e5b5c1 1385};
ccd4a2b7 1386</script>
85e5b5c1 1387
41c80bb6 1388<style lang="sass" scoped>
5bcc9b31 1389.active
5fbc0680 1390 color: #388e3c
a154d45e
BA
1391
1392#infoDiv > .card
f854c94f
BA
1393 padding: 15px 0
1394 max-width: 430px
a154d45e 1395
725da57f 1396#newgameDiv > .card, #acceptDiv > .card
a154d45e
BA
1397 max-width: 767px
1398 max-height: 100%
1399
bd76b456
BA
1400div#peopleWrap > .card
1401 max-height: 100%
1402
1403@media screen and (min-width: 1281px)
1404 div#peopleWrap > .card
1405 max-width: 66.67%
1406
1407@media screen and (max-width: 1280px)
1408 div#peopleWrap > .card
1409 max-width: 83.33%
1410
1411@media screen and (max-width: 767px)
1412 div#peopleWrap > .card
1413 max-width: 100%
1414
ed06d9e9
BA
1415#players
1416 width: 50%
1417 position: relative
1418 float: left
910d631b 1419
ed06d9e9
BA
1420#chat
1421 width: 50%
1422 float: left
1423 position: relative
910d631b 1424
ed06d9e9
BA
1425@media screen and (max-width: 767px)
1426 #players, #chats
1427 width: 100%
910d631b 1428
72ccbd67
BA
1429#chat > .card
1430 max-width: 100%
1431 margin: 0;
1432 border: none;
910d631b 1433
41c80bb6 1434#players > p
ed06d9e9 1435 margin-left: 5px
910d631b 1436
dcd68c41
BA
1437.anonymous
1438 font-style: italic
910d631b 1439
dcd68c41 1440button.player-action
41c80bb6 1441 margin-left: 32px
56c40600
BA
1442 &.focused
1443 background-color: #E6D271
2f258c37
BA
1444
1445.somethingnew
107dc1bd 1446 background-color: #90C4EC !important
2f258c37
BA
1447
1448.tabbtn
5fe7e71c 1449 background-color: #f9faee
2f258c37 1450
725da57f
BA
1451button.acceptBtn
1452 background-color: lightgreen
1453button.refuseBtn
1454 background-color: red
1455
1456#buttonsTchall
afde7666 1457 // margin-top set dynamically (depends if diagram showed or not)
5b4de147
BA
1458 & > button > span
1459 width: 100%
1460 text-align: center
725da57f
BA
1461
1462.variantName
1463 font-weight: bold
1464
1465.diagram
1466 margin: 0 auto
1467 max-width: 400px
5b4de147
BA
1468 // width: 100% required for Firefox
1469 width: 100%
725da57f
BA
1470
1471#inputFen
1472 width: 100%
1473
2f258c37
BA
1474#div2, #div3
1475 margin-top: 15px
1476@media screen and (max-width: 767px)
1477 #div2, #div3
1478 margin-top: 0
28b32b4f 1479
80b38d46
BA
1480.user-bio
1481 display: inline
1482
28b32b4f
BA
1483tr > td
1484 &.random-0
1485 background-color: #FF5733
1486 &.random-1
1487 background-color: #2B63B4
1488 &.random-2
1489 background-color: #33B42B
1490
4222cf78
BA
1491@media screen and (max-width: 767px)
1492 h4
1493 margin: 5px 0
1494
0234201f 1495button#loadMoreBtn
f14572c4
BA
1496 display: block
1497 margin: 0 auto
0234201f 1498
28b32b4f
BA
1499td.remove-preset
1500 background-color: lightgrey
1501 text-align: center
1502 & > img
1503 height: 1em
85e5b5c1 1504</style>