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