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