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