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