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