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