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