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