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