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