Move 'anonymousCount' which was computed to a method in Hall. Seems more accurate
[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 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"] }}
199 </template>
200
201 <script>
202 import { store } from "@/store";
203 import { checkChallenge } from "@/data/challengeCheck";
204 import { ArrayFun } from "@/utils/array";
205 import { ajax } from "@/utils/ajax";
206 import params from "@/parameters";
207 import { getRandString, shuffle } from "@/utils/alea";
208 import { getDiagram } from "@/utils/printDiagram";
209 import Chat from "@/components/Chat.vue";
210 import GameList from "@/components/GameList.vue";
211 import ChallengeList from "@/components/ChallengeList.vue";
212 import { GameStorage } from "@/utils/gameStorage";
213 import { processModalClick } from "@/utils/modalClick";
214 export default {
215 name: "my-hall",
216 components: {
217 Chat,
218 GameList,
219 ChallengeList
220 },
221 data: function() {
222 return {
223 st: store.state,
224 cdisplay: "live", //or corr
225 gdisplay: "live",
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,
230 games: [],
231 challenges: [],
232 people: {},
233 infoMessage: "",
234 newchallenge: {
235 fen: "",
236 vid: parseInt(localStorage.getItem("vid")) || 0,
237 to: "", //name of challenged player (if any)
238 cadence: localStorage.getItem("cadence") || "",
239 randomness: parseInt(localStorage.getItem("challRandomness")) || 2,
240 // VariantRules object, stored to not interfere with
241 // diagrams of targetted challenges:
242 V: null,
243 vname: "",
244 diag: "", //visualizing FEN
245 memorize: false //put settings in localStorage
246 },
247 tchallDiag: "",
248 curChallToAccept: {from: {}},
249 presetChalls: JSON.parse(localStorage.getItem("presetChalls") || "[]"),
250 newChat: "",
251 conn: null,
252 connexionString: "",
253 // Related to (killing of) self multi-connects:
254 newConnect: {},
255 killed: {}
256 };
257 },
258 watch: {
259 // st.variants changes only once, at loading from [] to [...]
260 "st.variants": function() {
261 // Set potential challenges and games variant names:
262 this.challenges.concat(this.games).forEach(o => {
263 if (!o.vname) o.vname = this.getVname(o.vid);
264 });
265 if (!this.newchallenge.V && this.newchallenge.vid > 0)
266 this.loadNewchallVariant();
267 }
268 },
269 created: function() {
270 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
271 this.loadNewchallVariant();
272 const my = this.st.user;
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 );
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);
321 // Ask server for current corr games (all but mines)
322 ajax(
323 "/observedgames",
324 "GET",
325 {
326 data: {
327 uid: this.st.user.id,
328 cursor: this.cursor
329 },
330 success: (response) => {
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 }
339 }
340 this.games = this.games.concat(
341 response.games.map(g => {
342 const vname = this.getVname(g.vid);
343 return Object.assign(
344 {},
345 g,
346 {
347 type: "corr",
348 vname: vname
349 }
350 );
351 })
352 );
353 }
354 }
355 );
356 // Also ask for corr challenges (open + sent by/to me)
357 ajax(
358 "/challenges",
359 "GET",
360 {
361 data: { uid: this.st.user.id },
362 success: (response) => {
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 }
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",
404 {
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 }
413 );
414 } else addChallenges();
415 }
416 }
417 );
418 },
419 beforeDestroy: function() {
420 document.removeEventListener('visibilitychange', this.visibilityChange);
421 this.send("disconnect");
422 },
423 methods: {
424 getRandomnessClass: function(pc) {
425 return {
426 ["random-" + pc.randomness]: true
427 };
428 },
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 },
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 },
445 partialResetNewchallenge: function() {
446 // Reset potential target and custom FEN:
447 this.newchallenge.to = "";
448 this.newchallenge.fen = "";
449 this.newchallenge.diag = "";
450 this.newchallenge.memorize = false;
451 },
452 showNewchallengeForm: function() {
453 this.partialResetNewchallenge();
454 window.doClick("modalNewgame");
455 },
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 },
481 tchallButtonsMargin: function() {
482 if (!!this.curChallToAccept.fen) return { "margin-top": "10px" };
483 return {};
484 },
485 cadenceFocusIfOpened: function() {
486 if (event.target.checked)
487 document.getElementById("cadence").focus();
488 },
489 send: function(code, obj) {
490 if (!!this.conn) {
491 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
492 }
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)
497 return variant ? variant.name : "";
498 },
499 filterChallenges: function(type) {
500 return this.challenges.filter(c => c.type == type);
501 },
502 filterGames: function(type) {
503 return this.games.filter(g => g.type == type);
504 },
505 classifyObject: function(o) {
506 // o: challenge or game
507 return o.cadence.indexOf("d") === -1 ? "live" : "corr";
508 },
509 setDisplay: function(letter, type, e) {
510 this[letter + "display"] = type;
511 localStorage.setItem(
512 "type-" + (letter == "c" ? "challenges" : "games"),
513 type
514 );
515 let elt = e
516 ? e.target
517 : document.getElementById("btn" + letter.toUpperCase() + type);
518 elt.classList.add("active");
519 elt.classList.remove("somethingnew"); //in case of
520 if (!!elt.previousElementSibling)
521 elt.previousElementSibling.classList.remove("active");
522 else elt.nextElementSibling.classList.remove("active");
523 },
524 isGamer: function(sid) {
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 );
535 },
536 challenge: function(sid) {
537 this.partialResetNewchallenge();
538 // Available, in Hall
539 this.newchallenge.to = this.people[sid].name;
540 // TODO: also store target sid to not re-search for it
541 document.getElementById("modalPeople").checked = false;
542 window.doClick("modalNewgame");
543 },
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 => {
548 if (p.focus) {
549 const matchGid = p.path.match(/[a-zA-Z0-9]+$/);
550 if (!!matchGid) gids.push(matchGid[0]);
551 }
552 });
553 const gid = gids[Math.floor(Math.random() * gids.length)];
554 const game = this.games.find(g => g.id == gid);
555 if (!!game) this.showGame(game);
556 else this.$router.push("/game/" + gid); //game vs. me
557 },
558 showGame: function(g) {
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")
563 url += "?rid=" + g.rids[Math.floor(Math.random() * g.rids.length)];
564 this.$router.push(url);
565 },
566 resetSocialColor: function() {
567 // TODO: this is called twice, once on opening an once on closing
568 document.getElementById("peopleBtn").classList.remove("somethingnew");
569 },
570 processChat: function(chat) {
571 this.send("newchat", { data: chat });
572 },
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 },
582 // Messaging center:
583 socketMessageListener: function(msg) {
584 if (!this.conn) return;
585 const data = JSON.parse(msg.data);
586 switch (data.code) {
587 case "pollclientsandgamers": {
588 // Since people can be both in Hall and Game,
589 // need to track "askIdentity" requests:
590 let identityAsked = {};
591 data.sockIds.forEach(s => {
592 const page = s.page || "/";
593 if (s.sid != this.st.user.sid && !identityAsked[s.sid]) {
594 this.send("askidentity", { target: s.sid, page: page });
595 identityAsked[s.sid] = true;
596 }
597 if (!this.people[s.sid]) {
598 // Do not set name or id: identity unknown yet
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 });
603 if (!s.page)
604 // Peer is in Hall
605 this.send("askchallenges", { target: s.sid });
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 });
609 });
610 break;
611 }
612 case "connect":
613 case "gconnect": {
614 const page = data.page || "/";
615 // Only ask game / challenges if first connexion:
616 if (!this.people[data.from]) {
617 this.people[data.from] = { pages: [{ path: page, focus: true }] };
618 if (data.code == "connect")
619 this.send("askchallenges", { target: data.from });
620 // Ask game only if live:
621 else if (!page.match(/\/[0-9]+$/))
622 this.send("askgame", { target: data.from, page: page });
623 } else {
624 // Append page if not already in list
625 if (!(this.people[data.from].pages.find(p => p.path == page)))
626 this.people[data.from].pages.push({ path: page, focus: true });
627 }
628 if (!this.people[data.from].name && this.people[data.from].id !== 0) {
629 // Identity not known yet
630 this.newConnect[data.from] = true; //for self multi-connects tests
631 this.send("askidentity", { target: data.from, page: page });
632 }
633 break;
634 }
635 case "disconnect":
636 case "gdisconnect": {
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.
640 if (!this.people[data.from]) return;
641 // Disconnect means no more tmpIds:
642 if (data.code == "disconnect") {
643 // Remove the live challenges sent by this player:
644 ArrayFun.remove(
645 this.challenges,
646 c => c.type == "live" && c.from.sid == data.from,
647 "all"
648 );
649 } else {
650 // Remove the matching live game if now unreachable
651 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
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);
660 }
661 }
662 }
663 const page = data.page || "/";
664 ArrayFun.remove(this.people[data.from].pages, p => p.path == page);
665 if (this.people[data.from].pages.length == 0)
666 this.$delete(this.people, data.from);
667 break;
668 }
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;
684 case "killed":
685 // I logged in elsewhere:
686 this.conn = null;
687 alert(this.st.tr["New connexion detected: tab now offline"]);
688 break;
689 case "askidentity": {
690 // Request for identification
691 const me = {
692 // Decompose to avoid revealing email
693 name: this.st.user.name,
694 sid: this.st.user.sid,
695 id: this.st.user.id
696 };
697 this.send("identity", { data: me, target: data.from });
698 break;
699 }
700 case "identity": {
701 const user = data.data;
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();
709 // If I multi-connect, kill current connexion if no mark (I'm older)
710 if (this.newConnect[user.sid]) {
711 if (
712 user.id > 0 &&
713 user.id == this.st.user.id &&
714 user.sid != this.st.user.sid &&
715 !this.killed[this.st.user.sid]
716 ) {
717 this.send("killme", { sid: this.st.user.sid });
718 this.killed[this.st.user.sid] = true;
719 }
720 delete this.newConnect[user.sid];
721 }
722 break;
723 }
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 });
747 break;
748 }
749 case "challenges": //after "askchallenges"
750 data.data.forEach(this.addChallenge);
751 break;
752 case "newchallenge":
753 this.addChallenge(data.data);
754 break;
755 case "refusechallenge": {
756 const cid = data.data;
757 ArrayFun.remove(this.challenges, c => c.id == cid);
758 alert(this.st.tr["Challenge declined"]);
759 break;
760 }
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 }
774 break;
775 }
776 case "game": // Individual request
777 case "newgame": {
778 const game = data.data;
779 // Ignore games where I play (will go in MyGames page)
780 if (game.players.every(p =>
781 p.sid != this.st.user.sid && p.id != this.st.user.id))
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)
789 // New game from Hall
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);
805 }
806 }
807 break;
808 }
809 case "result": {
810 let g = this.games.find(g => g.id == data.gid);
811 if (!!g) g.score = data.score;
812 break;
813 }
814 case "startgame": {
815 // New game just started, I'm involved
816 const gameInfo = data.data;
817 if (this.classifyObject(gameInfo) == "live")
818 this.startNewGame(gameInfo);
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>";
828 document.getElementById("modalInfo").checked = true;
829 }
830 break;
831 }
832 case "newchat":
833 this.newChat = data.data;
834 if (!document.getElementById("modalPeople").checked)
835 document.getElementById("peopleBtn").classList.add("somethingnew");
836 break;
837 }
838 },
839 socketCloseListener: function() {
840 if (!this.conn) return;
841 this.conn = new WebSocket(this.connexionString);
842 this.conn.addEventListener("message", this.socketMessageListener);
843 this.conn.addEventListener("close", this.socketCloseListener);
844 },
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) => {
855 const L = res.games.length;
856 if (L > 0) {
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 },
875 // Challenge lifecycle:
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 },
902 loadNewchallVariant: async function(cb) {
903 const vname = this.getVname(this.newchallenge.vid);
904 const vModule = await import("@/variants/" + vname + ".js");
905 this.newchallenge.V = vModule.VariantRules;
906 this.newchallenge.vname = vname;
907 if (!!cb) cb();
908 },
909 trySetNewchallDiag: function() {
910 if (!this.newchallenge.fen) {
911 this.newchallenge.diag = "";
912 return;
913 }
914 // If vid > 0 then the variant is loaded (function above):
915 window.V = this.newchallenge.V;
916 if (
917 this.newchallenge.vid > 0 &&
918 !!this.newchallenge.fen &&
919 V.IsGoodFen(this.newchallenge.fen)
920 ) {
921 const parsedFen = V.ParseFen(this.newchallenge.fen);
922 this.newchallenge.diag = getDiagram({
923 position: parsedFen.position,
924 orientation: parsedFen.turn
925 });
926 }
927 },
928 newChallFromPreset(pchall) {
929 this.partialResetNewchallenge();
930 this.newchallenge.vid = pchall.vid;
931 this.newchallenge.cadence = pchall.cadence;
932 this.newchallenge.randomness = pchall.randomness;
933 this.loadNewchallVariant(this.issueNewChallenge);
934 },
935 issueNewChallenge: async function() {
936 if (!!(this.newchallenge.cadence.match(/^[0-9]+$/)))
937 this.newchallenge.cadence += "+0"; //assume minutes, no increment
938 const ctype = this.classifyObject(this.newchallenge);
939 // TODO: cadence still unchecked so ctype could be wrong...
940 let error = "";
941 if (!this.newchallenge.vid)
942 error = this.st.tr["Please select a variant"];
943 else if (ctype == "corr" && this.st.user.id <= 0)
944 error = this.st.tr["Please log in to play correspondance games"];
945 else if (!!this.newchallenge.to) {
946 if (this.newchallenge.to == this.st.user.name)
947 error = this.st.tr["Self-challenge is forbidden"];
948 else if (
949 ctype == "live" &&
950 Object.values(this.people).every(p => p.name != this.newchallenge.to)
951 ) {
952 error = this.newchallenge.to + " " + this.st.tr["is not online"];
953 }
954 }
955 if (error) {
956 alert(error);
957 return;
958 }
959 window.V = this.newchallenge.V;
960 error = checkChallenge(this.newchallenge);
961 if (error) {
962 alert(error);
963 return;
964 }
965 // NOTE: "from" information is not required here
966 let chall = Object.assign({}, this.newchallenge);
967 // Add only if not already issued (not counting target or FEN):
968 if (this.challenges.some(c =>
969 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) &&
970 c.vid == chall.vid &&
971 c.cadence == chall.cadence &&
972 c.randomness == chall.randomness
973 )) {
974 alert(this.st.tr["Challenge already exists"]);
975 return;
976 }
977 if (this.newchallenge.memorize) this.addPresetChall(this.newchallenge);
978 delete chall["V"];
979 delete chall["diag"];
980 const finishAddChallenge = cid => {
981 chall.id = cid || "c" + getRandString();
982 const MAX_ALLOWED_CHALLS = 3;
983 // Remove oldest challenge if 3 found: only 3 at a time of a given type
984 let countMyChalls = 0;
985 let challToDelIdx = 0;
986 let oldestAdded = Number.MAX_SAFE_INTEGER;
987 for (let i=0; i<this.challenges.length; i++) {
988 const c = this.challenges[i];
989 if (
990 c.type == ctype &&
991 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id)
992 ) {
993 countMyChalls++;
994 if (c.added < oldestAdded) {
995 challToDelIdx = i;
996 oldestAdded = c.added;
997 }
998 }
999 }
1000 if (countMyChalls >= MAX_ALLOWED_CHALLS) {
1001 this.send(
1002 "deletechallenge_s",
1003 { data: { cid: this.challenges[challToDelIdx].id } }
1004 );
1005 if (ctype == "corr") {
1006 ajax(
1007 "/challenges",
1008 "DELETE",
1009 { data: { id: this.challenges[challToDelIdx].id } }
1010 );
1011 }
1012 this.challenges.splice(challToDelIdx, 1);
1013 }
1014 this.send("newchallenge", {
1015 data: Object.assign({ from: this.st.user.sid }, chall)
1016 });
1017 // Add new challenge:
1018 chall.from = {
1019 sid: this.st.user.sid,
1020 id: this.st.user.id,
1021 name: this.st.user.name
1022 };
1023 chall.added = Date.now();
1024 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
1025 chall.type = ctype;
1026 chall.vname = this.newchallenge.vname;
1027 this.challenges.push(chall);
1028 // Remember cadence + vid for quicker further challenges:
1029 localStorage.setItem("cadence", chall.cadence);
1030 localStorage.setItem("vid", chall.vid);
1031 localStorage.setItem("challRandomness", chall.randomness);
1032 document.getElementById("modalNewgame").checked = false;
1033 // Show the challenge if not on current display
1034 if (
1035 (ctype == "live" && this.cdisplay == "corr") ||
1036 (ctype == "corr" && this.cdisplay == "live")
1037 ) {
1038 this.setDisplay('c', ctype);
1039 }
1040 };
1041 if (ctype == "live") {
1042 // Live challenges have a random ID
1043 finishAddChallenge(null);
1044 } else {
1045 // Correspondance game: send challenge to server
1046 ajax(
1047 "/challenges",
1048 "POST",
1049 {
1050 data: { chall: chall },
1051 success: (response) => {
1052 finishAddChallenge(response.id);
1053 }
1054 }
1055 );
1056 }
1057 },
1058 // Callback function after a diagram was showed to accept
1059 // or refuse targetted challenge:
1060 decisionChallenge: function(accepted) {
1061 this.curChallToAccept.accepted = accepted;
1062 this.finishProcessingChallenge(this.curChallToAccept);
1063 document.getElementById("modalAccept").checked = false;
1064 },
1065 finishProcessingChallenge: function(c) {
1066 if (c.accepted) {
1067 c.seat = {
1068 sid: this.st.user.sid,
1069 id: this.st.user.id,
1070 name: this.st.user.name
1071 };
1072 this.launchGame(c);
1073 if (c.type == "live")
1074 // Remove all live challenges of both players
1075 this.send("deletechallenge_s", { data: { sids: [c.from.sid, c.seat.sid] } });
1076 else
1077 // Corr challenge: just remove the challenge
1078 this.send("deletechallenge_s", { data: { cid: c.id } });
1079 } else {
1080 const oppsid = this.getOppsid(c);
1081 if (!!oppsid)
1082 this.send("refusechallenge", { data: c.id, target: oppsid });
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 },
1093 // TODO: if several players click same challenge at the same time: problem
1094 clickChallenge: async function(c) {
1095 const myChallenge =
1096 c.from.sid == this.st.user.sid || //live
1097 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
1098 if (!myChallenge) {
1099 if (c.type == "corr" && this.st.user.id <= 0) {
1100 alert(this.st.tr["Please log in to accept corr challenges"]);
1101 return;
1102 }
1103 c.accepted = true;
1104 const vModule = await import("@/variants/" + c.vname + ".js");
1105 window.V = vModule.VariantRules;
1106 if (!!c.to) {
1107 // c.to == this.st.user.name (connected)
1108 if (!!c.fen) {
1109 const parsedFen = V.ParseFen(c.fen);
1110 c.mycolor = V.GetOppCol(parsedFen.turn);
1111 this.tchallDiag = getDiagram({
1112 position: parsedFen.position,
1113 orientation: c.mycolor
1114 });
1115 }
1116 this.curChallToAccept = c;
1117 document.getElementById("modalAccept").checked = true;
1118 }
1119 else this.finishProcessingChallenge(c);
1120 }
1121 else {
1122 // My challenge
1123 if (c.type == "corr") {
1124 ajax(
1125 "/challenges",
1126 "DELETE",
1127 { data: { id: c.id } }
1128 );
1129 }
1130 this.send("deletechallenge_s", { data: { cid: c.id } });
1131 }
1132 // In all cases, the challenge is consumed:
1133 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
1134 },
1135 // NOTE: when launching game, the challenge is already being deleted
1136 launchGame: function(c) {
1137 // White player index 0, black player index 1:
1138 const players =
1139 !!c.mycolor
1140 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
1141 : shuffle([c.from, c.seat]);
1142 // These game informations will be shared
1143 let gameInfo = {
1144 id: getRandString(),
1145 fen: c.fen || V.GenRandInitFen(c.randomness),
1146 randomness: c.randomness, //for rematch
1147 players: players,
1148 vid: c.vid,
1149 cadence: c.cadence
1150 };
1151 const notifyNewgame = () => {
1152 const oppsid = this.getOppsid(c);
1153 if (!!oppsid)
1154 // Opponent is online
1155 this.send("startgame", { data: gameInfo, target: oppsid });
1156 // If new corr game, notify Hall (except opponent and me)
1157 if (c.type == "corr") {
1158 this.send(
1159 "newgame",
1160 {
1161 data: gameInfo,
1162 excluded: [this.st.user.sid, oppsid]
1163 }
1164 );
1165 }
1166 // Notify MyGames page:
1167 this.send(
1168 "notifynewgame",
1169 {
1170 data: gameInfo,
1171 targets: gameInfo.players
1172 }
1173 );
1174 // NOTE: no need to send the game to the room, since I'll connect
1175 // on game just after, the main Hall will be notified.
1176 };
1177 if (c.type == "live") {
1178 notifyNewgame();
1179 this.startNewGame(gameInfo);
1180 } else {
1181 // corr: game only on server
1182 ajax(
1183 "/games",
1184 "POST",
1185 {
1186 // cid is useful to delete the challenge:
1187 data: {
1188 gameInfo: gameInfo,
1189 cid: c.id
1190 },
1191 success: (response) => {
1192 gameInfo.id = response.id;
1193 notifyNewgame();
1194 this.$router.push("/game/" + response.id);
1195 }
1196 }
1197 );
1198 }
1199 },
1200 // NOTE: for live games only (corr games start on the server)
1201 startNewGame: function(gameInfo) {
1202 const game = Object.assign(
1203 {},
1204 gameInfo,
1205 {
1206 // (other) Game infos: constant
1207 fenStart: gameInfo.fen,
1208 vname: this.getVname(gameInfo.vid),
1209 created: Date.now(),
1210 // Game state (including FEN): will be updated
1211 moves: [],
1212 clocks: [-1, -1], //-1 = unstarted
1213 initime: [0, 0], //initialized later
1214 score: "*"
1215 }
1216 );
1217 setTimeout(
1218 () => {
1219 GameStorage.add(game, (err) => {
1220 // If an error occurred, game is not added: a tab already
1221 // added the game. Maybe a focused one, maybe not.
1222 // We know for sure that it emitted the gong start sound.
1223 // ==> Do not play it again.
1224 if (!err && this.st.settings.sound)
1225 new Audio("/sounds/newgame.flac").play().catch(() => {});
1226 this.$router.push("/game/" + gameInfo.id);
1227 });
1228 },
1229 document.hidden ? 500 + 1000 * Math.random() : 0
1230 );
1231 }
1232 }
1233 };
1234 </script>
1235
1236 <style lang="sass" scoped>
1237 .active
1238 color: #42a983
1239
1240 #infoDiv > .card
1241 padding: 15px 0
1242 max-width: 430px
1243
1244 #newgameDiv > .card, #acceptDiv > .card
1245 max-width: 767px
1246 max-height: 100%
1247
1248 div#peopleWrap > .card
1249 max-height: 100%
1250
1251 @media screen and (min-width: 1281px)
1252 div#peopleWrap > .card
1253 max-width: 66.67%
1254
1255 @media screen and (max-width: 1280px)
1256 div#peopleWrap > .card
1257 max-width: 83.33%
1258
1259 @media screen and (max-width: 767px)
1260 div#peopleWrap > .card
1261 max-width: 100%
1262
1263 #players
1264 width: 50%
1265 position: relative
1266 float: left
1267
1268 #chat
1269 width: 50%
1270 float: left
1271 position: relative
1272
1273 @media screen and (max-width: 767px)
1274 #players, #chats
1275 width: 100%
1276
1277 #chat > .card
1278 max-width: 100%
1279 margin: 0;
1280 border: none;
1281
1282 #players > p
1283 margin-left: 5px
1284
1285 .anonymous
1286 font-style: italic
1287
1288 button.player-action
1289 margin-left: 32px
1290
1291 .somethingnew
1292 background-color: #c5fefe !important
1293
1294 .tabbtn
1295 background-color: #f9faee
1296
1297 button.acceptBtn
1298 background-color: lightgreen
1299 button.refuseBtn
1300 background-color: red
1301
1302 #buttonsTchall
1303 // margin-top set dynamically (depends if diagram showed or not)
1304 & > button > span
1305 width: 100%
1306 text-align: center
1307
1308 .variantName
1309 font-weight: bold
1310
1311 .diagram
1312 margin: 0 auto
1313 max-width: 400px
1314 // width: 100% required for Firefox
1315 width: 100%
1316
1317 #inputFen
1318 width: 100%
1319
1320 #div2, #div3
1321 margin-top: 15px
1322 @media screen and (max-width: 767px)
1323 #div2, #div3
1324 margin-top: 0
1325
1326 tr > td
1327 &.random-0
1328 background-color: #FF5733
1329 &.random-1
1330 background-color: #2B63B4
1331 &.random-2
1332 background-color: #33B42B
1333
1334 @media screen and (max-width: 767px)
1335 h4
1336 margin: 5px 0
1337
1338 button#loadMoreBtn
1339 display: block
1340 margin: 0 auto
1341
1342 td.remove-preset
1343 background-color: lightgrey
1344 text-align: center
1345 & > img
1346 height: 1em
1347 </style>