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