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