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