133a5f9e9ced98cc58dd59bd69292faa88260556
[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 span {{ 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["Correspondance 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["Correspondance 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 GameList from "@/components/GameList.vue";
216 import ChallengeList from "@/components/ChallengeList.vue";
217 import { GameStorage } from "@/utils/gameStorage";
218 import { processModalClick } from "@/utils/modalClick";
219 export default {
220 name: "my-hall",
221 components: {
222 Chat,
223 GameList,
224 ChallengeList
225 },
226 data: function() {
227 return {
228 st: store.state,
229 cdisplay: "live", //or corr
230 gdisplay: "live",
231 // timestamp of last showed (oldest) corr game:
232 cursor: Number.MAX_SAFE_INTEGER,
233 // hasMore == TRUE: a priori there could be more games to load
234 hasMore: true,
235 games: [],
236 challenges: [],
237 people: {},
238 infoMessage: "",
239 newchallenge: {
240 fen: "",
241 vid: parseInt(localStorage.getItem("vid")) || 0,
242 to: "", //name of challenged player (if any)
243 cadence: localStorage.getItem("cadence") || "",
244 randomness:
245 // Warning: randomness can be 0, then !!randomness is false
246 (parseInt(localStorage.getItem("challRandomness"))+1 || 3) - 1,
247 // VariantRules object, stored to not interfere with
248 // diagrams of targetted challenges:
249 V: null,
250 vname: "",
251 diag: "", //visualizing FEN
252 memorize: false //put settings in localStorage
253 },
254 focus: true,
255 tchallDiag: "",
256 curChallToAccept: {from: {}},
257 presetChalls: JSON.parse(localStorage.getItem("presetChalls") || "[]"),
258 conn: null,
259 connexionString: "",
260 socketCloseListener: 0,
261 // Related to (killing of) self multi-connects:
262 newConnect: {}
263 };
264 },
265 watch: {
266 // st.variants changes only once, at loading from [] to [...]
267 "st.variants": function() {
268 // Set potential challenges and games variant names:
269 this.challenges.concat(this.games).forEach(o => {
270 if (!o.vname) o.vname = this.getVname(o.vid);
271 });
272 if (!this.newchallenge.V && this.newchallenge.vid > 0)
273 this.loadNewchallVariant();
274 },
275 $route: function(to, from) {
276 if (to.path != "/") this.cleanBeforeDestroy();
277 }
278 },
279 created: function() {
280 document.addEventListener('visibilitychange', this.visibilityChange);
281 window.addEventListener('focus', this.onFocus);
282 window.addEventListener('blur', this.onBlur);
283 window.addEventListener("beforeunload", this.cleanBeforeDestroy);
284 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
285 this.loadNewchallVariant();
286 const my = this.st.user;
287 const tmpId = getRandString();
288 this.$set(
289 this.people,
290 my.sid,
291 {
292 id: my.id,
293 name: my.name,
294 tmpIds: {
295 tmpId: { page: "/", focus: true }
296 }
297 }
298 );
299 const connectAndPoll = () => {
300 this.send("connect");
301 this.send("pollclientsandgamers");
302 };
303 // Initialize connection
304 this.connexionString =
305 params.socketUrl +
306 "/?sid=" + this.st.user.sid +
307 "&id=" + this.st.user.id +
308 "&tmpId=" + tmpId +
309 "&page=" +
310 // Hall: path is "/" (TODO: could be hard-coded as well)
311 encodeURIComponent(this.$route.path);
312 this.conn = new WebSocket(this.connexionString);
313 this.conn.onopen = connectAndPoll;
314 this.conn.addEventListener("message", this.socketMessageListener);
315 this.socketCloseListener = setInterval(
316 () => {
317 if (this.conn.readyState == 3) {
318 this.conn.removeEventListener("message", this.socketMessageListener);
319 this.conn = new WebSocket(this.connexionString);
320 this.conn.addEventListener("message", this.socketMessageListener);
321 }
322 },
323 1000
324 );
325 },
326 mounted: function() {
327 document.getElementById("peopleWrap")
328 .addEventListener("click", (e) => {
329 processModalClick(e, () => {
330 this.toggleSocialColor("close")
331 });
332 });
333 ["infoDiv", "newgameDiv"].forEach(eltName => {
334 document.getElementById(eltName)
335 .addEventListener("click", processModalClick);
336 });
337 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
338 b.addEventListener("click", () => {
339 this.newchallenge.cadence = b.innerHTML;
340 });
341 });
342 const dispCorr = this.$route.query["disp"];
343 const showCtype =
344 dispCorr || localStorage.getItem("type-challenges") || "live";
345 const showGtype =
346 dispCorr || localStorage.getItem("type-games") || "live";
347 this.setDisplay('c', showCtype);
348 this.setDisplay('g', showGtype);
349 // Ask server for current corr games (all but mines)
350 this.loadMoreCorr();
351 // Also ask for corr challenges (open + sent by/to me)
352 // List them all, because they are not supposed to be that many (TODO?)
353 ajax(
354 "/challenges",
355 "GET",
356 {
357 data: { uid: this.st.user.id },
358 success: (response) => {
359 if (
360 response.challenges.length > 0 &&
361 this.challenges.length == 0 &&
362 this.cdisplay == "live"
363 ) {
364 document
365 .getElementById("btnCcorr")
366 .classList.add("somethingnew");
367 }
368 // Gather all senders names, and then retrieve full identity:
369 // (TODO [perf]: some might be online...)
370 let names = {};
371 response.challenges.forEach(c => {
372 if (c.uid != this.st.user.id) names[c.uid] = "";
373 else if (!!c.target && c.target != this.st.user.id)
374 names[c.target] = "";
375 });
376 const addChallenges = () => {
377 names[this.st.user.id] = this.st.user.name; //in case of
378 this.challenges = this.challenges.concat(
379 response.challenges.map(c => {
380 const from = { name: names[c.uid], id: c.uid }; //or just name
381 const type = this.classifyObject(c);
382 const vname = this.getVname(c.vid);
383 return Object.assign(
384 {},
385 {
386 type: type,
387 vname: vname,
388 from: from,
389 to: c.target ? names[c.target] : ""
390 },
391 c
392 );
393 })
394 );
395 };
396 if (Object.keys(names).length > 0) {
397 ajax(
398 "/users",
399 "GET",
400 {
401 data: { ids: Object.keys(names).join(",") },
402 success: (response2) => {
403 response2.users.forEach(u => {
404 names[u.id] = u.name;
405 });
406 addChallenges();
407 }
408 }
409 );
410 } else addChallenges();
411 }
412 }
413 );
414 },
415 beforeDestroy: function() {
416 this.cleanBeforeDestroy();
417 },
418 methods: {
419 cleanBeforeDestroy: function() {
420 clearInterval(this.socketCloseListener);
421 document.removeEventListener('visibilitychange', this.visibilityChange);
422 window.removeEventListener('focus', this.onFocus);
423 window.removeEventListener('blur', this.onBlur);
424 window.removeEventListener("beforeunload", this.cleanBeforeDestroy);
425 this.conn.removeEventListener("message", this.socketMessageListener);
426 this.send("disconnect");
427 this.conn = null;
428 },
429 getRandomnessClass: function(pc) {
430 return {
431 ["random-" + pc.randomness]: true
432 };
433 },
434 anonymousCount: function() {
435 let count = 0;
436 Object.values(this.people).forEach(p => {
437 // Do not cound people who did not send their identity yet:
438 count += (!p.name && p.id === 0) ? 1 : 0;
439 });
440 return count;
441 },
442 visibilityChange: function() {
443 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
444 this.focus = (document.visibilityState == "visible");
445 this.send(this.focus ? "getfocus" : "losefocus");
446 },
447 onFocus: function() {
448 this.focus = true;
449 this.send("getfocus");
450 },
451 onBlur: function() {
452 this.focus = false;
453 this.send("losefocus");
454 },
455 partialResetNewchallenge: function() {
456 // Reset potential target and custom FEN:
457 this.newchallenge.to = "";
458 this.newchallenge.fen = "";
459 this.newchallenge.diag = "";
460 this.newchallenge.memorize = false;
461 },
462 showNewchallengeForm: function() {
463 this.partialResetNewchallenge();
464 window.doClick("modalNewgame");
465 },
466 addPresetChall: function(chall) {
467 // Add only if not already existing:
468 if (this.presetChalls.some(c =>
469 c.vid == chall.vid &&
470 c.cadence == chall.cadence &&
471 c.randomness == chall.randomness
472 )) {
473 return;
474 }
475 const L = this.presetChalls.length;
476 this.presetChalls.push({
477 index: L,
478 vid: chall.vid,
479 vname: chall.vname, //redundant, but easier
480 cadence: chall.cadence,
481 randomness: chall.randomness
482 });
483 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
484 },
485 removePresetChall: function(e, pchall) {
486 e.stopPropagation();
487 const pchallIdx =
488 this.presetChalls.findIndex(pc => pc.index == pchall.index);
489 this.presetChalls.splice(pchallIdx, 1);
490 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
491 },
492 tchallButtonsMargin: function() {
493 if (!!this.curChallToAccept.fen) return { "margin-top": "10px" };
494 return {};
495 },
496 changeChallTarget: function() {
497 if (!this.newchallenge.to) {
498 // Reset potential FEN + diagram
499 this.newchallenge.fen = "";
500 this.newchallenge.diag = "";
501 }
502 },
503 cadenceFocusIfOpened: function() {
504 if (event.target.checked)
505 document.getElementById("cadence").focus();
506 },
507 send: function(code, obj) {
508 if (!!this.conn && this.conn.readyState == 1) {
509 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
510 }
511 },
512 getVname: function(vid) {
513 const variant = this.st.variants.find(v => v.id == vid);
514 // this.st.variants might be uninitialized (variant == null)
515 return variant ? variant.name : "";
516 },
517 filterChallenges: function(type) {
518 return this.challenges.filter(c => c.type == type);
519 },
520 filterGames: function(type) {
521 return this.games.filter(g => g.type == type);
522 },
523 // o: challenge or game
524 classifyObject: function(o) {
525 // Consider imports as live games (TODO)
526 if (!!o.id && !!o.id.toString().match(/^i/)) return "live";
527 return o.cadence.indexOf("d") === -1 ? "live" : "corr";
528 },
529 setDisplay: function(letter, type, e) {
530 this[letter + "display"] = type;
531 localStorage.setItem(
532 "type-" + (letter == "c" ? "challenges" : "games"),
533 type
534 );
535 let elt = e
536 ? e.target
537 : document.getElementById("btn" + letter.toUpperCase() + type);
538 elt.classList.add("active");
539 elt.classList.remove("somethingnew"); //in case of
540 if (!!elt.previousElementSibling)
541 elt.previousElementSibling.classList.remove("active");
542 else elt.nextElementSibling.classList.remove("active");
543 },
544 isGamer: function(sid) {
545 return Object.values(this.people[sid].tmpIds)
546 .some(v => v.focus && v.page.indexOf("/game/") >= 0);
547 },
548 isFocusedOnHall: function(sid) {
549 return (
550 // This is meant to challenge people, thus the next 2 conditions:
551 this.st.user.id > 0 &&
552 sid != this.st.user.sid &&
553 Object.values(this.people[sid].tmpIds)
554 .some(v => v.focus && v.page == "/")
555 );
556 },
557 challenge: function(sid) {
558 this.partialResetNewchallenge();
559 // Available, in Hall
560 this.newchallenge.to = this.people[sid].name;
561 // TODO: also store target sid to not re-search for it
562 document.getElementById("modalPeople").checked = false;
563 window.doClick("modalNewgame");
564 },
565 watchGame: function(sid) {
566 // In some game, maybe playing maybe not: show a random one
567 let gids = [];
568 Object.values(this.people[sid].tmpIds).forEach(v => {
569 if (v.focus) {
570 const matchGid = v.page.match(/[a-zA-Z0-9]+$/);
571 if (!!matchGid) gids.push(matchGid[0]);
572 }
573 });
574 const gid = gids[Math.floor(Math.random() * gids.length)];
575 const game = this.games.find(g => g.id == gid);
576 if (!!game) this.showGame(game);
577 else this.$router.push("/game/" + gid); //game vs. me
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 this.$router.push("/game/" + g.id);
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 game.players.every(p => {
826 return (
827 p.sid != this.st.user.sid &&
828 (p.id == 0 || p.id != this.st.user.id)
829 );
830 }) && this.games.findIndex(g => g.id == game.id) == -1
831 ) {
832 let newGame = game;
833 newGame.type = this.classifyObject(game);
834 newGame.vname = this.getVname(game.vid);
835 if (!game.score)
836 // New game from Hall
837 newGame.score = "*";
838 this.games.push(newGame);
839 if (
840 (newGame.type == "live" && this.gdisplay == "corr") ||
841 (newGame.type == "corr" && this.gdisplay == "live")
842 ) {
843 document
844 .getElementById("btnG" + newGame.type)
845 .classList.add("somethingnew");
846 }
847 }
848 break;
849 }
850 case "result": {
851 let g = this.games.find(g => g.id == data.gid);
852 if (!!g) g.score = data.score;
853 break;
854 }
855 case "startgame": {
856 // New game just started, I'm involved
857 const gameInfo = data.data;
858 if (this.classifyObject(gameInfo) == "live")
859 this.startNewGame(gameInfo);
860 else {
861 this.infoMessage =
862 this.st.tr["New correspondance game:"] + " " +
863 "<a href='#/game/" + gameInfo.id + "'>" +
864 "#/game/" + gameInfo.id + "</a>";
865 document.getElementById("modalInfo").checked = true;
866 }
867 break;
868 }
869 case "newchat":
870 this.$refs["chatcomp"].newChat(data.data);
871 if (!document.getElementById("modalPeople").checked)
872 document.getElementById("peopleBtn").classList.add("somethingnew");
873 break;
874 }
875 },
876 loadMoreCorr: function() {
877 ajax(
878 "/observedgames",
879 "GET",
880 {
881 data: {
882 uid: this.st.user.id,
883 cursor: this.cursor
884 },
885 success: (res) => {
886 const L = res.games.length;
887 if (L > 0) {
888 if (
889 this.cursor == Number.MAX_SAFE_INTEGER &&
890 this.games.length == 0 &&
891 this.gdisplay == "live"
892 ) {
893 // First loading: show indicators
894 document
895 .getElementById("btnGcorr")
896 .classList.add("somethingnew");
897 }
898 this.cursor = res.games[L - 1].created;
899 let moreGames = res.games.map(g => {
900 const vname = this.getVname(g.vid);
901 return Object.assign(
902 {},
903 g,
904 {
905 type: "corr",
906 vname: vname
907 }
908 );
909 });
910 this.games = this.games.concat(moreGames);
911 } else this.hasMore = false;
912 }
913 }
914 );
915 },
916 // Challenge lifecycle:
917 addChallenge: function(chall) {
918 // NOTE about next condition: see "askchallenges" case.
919 if (
920 !chall.to ||
921 (this.people[chall.from].id > 0 &&
922 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
923 ) {
924 let newChall = Object.assign({}, chall);
925 newChall.type = this.classifyObject(chall);
926 newChall.randomness = chall.randomness;
927 newChall.added = Date.now();
928 let fromValues = Object.assign({}, this.people[chall.from]);
929 delete fromValues["pages"]; //irrelevant in this context
930 newChall.from = Object.assign({ sid: chall.from }, fromValues);
931 newChall.vname = this.getVname(newChall.vid);
932 this.challenges.push(newChall);
933 if (
934 (newChall.type == "live" && this.cdisplay == "corr") ||
935 (newChall.type == "corr" && this.cdisplay == "live")
936 ) {
937 document
938 .getElementById("btnC" + newChall.type)
939 .classList.add("somethingnew");
940 }
941 if (!!chall.to) {
942 notify(
943 "New challenge",
944 // fromValues.name should exist since the player is online, but
945 // let's consider there is some chance that the challenge arrives
946 // right after we connected and before receiving the poll result:
947 { body: "from " + (fromValues.name || "unknown yet...") }
948 );
949 }
950 }
951 },
952 loadNewchallVariant: async function(cb) {
953 const vname = this.getVname(this.newchallenge.vid);
954 await import("@/variants/" + vname + ".js")
955 .then((vModule) => {
956 window.V = vModule[vname + "Rules"];
957 this.newchallenge.V = window.V;
958 this.newchallenge.vname = vname;
959 if (!!cb) cb();
960 });
961 },
962 trySetNewchallDiag: function() {
963 if (!this.newchallenge.fen) {
964 this.newchallenge.diag = "";
965 return;
966 }
967 // If vid > 0 then the variant is loaded (function above):
968 window.V = this.newchallenge.V;
969 if (
970 this.newchallenge.vid > 0 &&
971 !!this.newchallenge.fen &&
972 V.IsGoodFen(this.newchallenge.fen)
973 ) {
974 const parsedFen = V.ParseFen(this.newchallenge.fen);
975 this.newchallenge.diag = getDiagram({
976 position: parsedFen.position,
977 orientation: parsedFen.turn
978 });
979 } else this.newchallenge.diag = "";
980 },
981 newChallFromPreset(pchall) {
982 this.partialResetNewchallenge();
983 this.newchallenge.vid = pchall.vid;
984 this.newchallenge.cadence = pchall.cadence;
985 this.newchallenge.randomness = pchall.randomness;
986 this.loadNewchallVariant(this.issueNewChallenge);
987 },
988 issueNewChallenge: async function() {
989 if (!!(this.newchallenge.cadence.match(/^[0-9]+$/)))
990 this.newchallenge.cadence += "+0"; //assume minutes, no increment
991 const ctype = this.classifyObject(this.newchallenge);
992 // TODO: cadence still unchecked so ctype could be wrong...
993 let error = "";
994 if (!this.newchallenge.vid)
995 error = this.st.tr["Please select a variant"];
996 else if (ctype == "corr" && this.st.user.id <= 0)
997 error = this.st.tr["Please log in to play correspondance games"];
998 else if (!!this.newchallenge.to) {
999 if (this.newchallenge.to == this.st.user.name)
1000 error = this.st.tr["Self-challenge is forbidden"];
1001 else if (
1002 ctype == "live" &&
1003 Object.values(this.people).every(p => p.name != this.newchallenge.to)
1004 ) {
1005 error = this.newchallenge.to + " " + this.st.tr["is not online"];
1006 }
1007 }
1008 if (error) {
1009 alert(error);
1010 return;
1011 }
1012 window.V = this.newchallenge.V;
1013 error = checkChallenge(this.newchallenge);
1014 if (error) {
1015 alert(error);
1016 return;
1017 }
1018 // NOTE: "from" information is not required here
1019 let chall = Object.assign({}, this.newchallenge);
1020 // Add only if not already issued (not counting target or FEN):
1021 if (this.challenges.some(c =>
1022 (
1023 c.from.sid == this.st.user.sid ||
1024 (c.from.id > 0 && c.from.id == this.st.user.id)
1025 )
1026 &&
1027 c.vid == chall.vid &&
1028 c.cadence == chall.cadence &&
1029 c.randomness == chall.randomness
1030 )) {
1031 alert(this.st.tr["Challenge already exists"]);
1032 return;
1033 }
1034 if (this.newchallenge.memorize) this.addPresetChall(this.newchallenge);
1035 delete chall["V"];
1036 delete chall["diag"];
1037 const finishAddChallenge = cid => {
1038 chall.id = cid || "c" + getRandString();
1039 const MAX_ALLOWED_CHALLS = 3;
1040 // Remove oldest challenge if 3 found: only 3 at a time of a given type
1041 let countMyChalls = 0;
1042 let challToDelIdx = 0;
1043 let oldestAdded = Number.MAX_SAFE_INTEGER;
1044 for (let i=0; i<this.challenges.length; i++) {
1045 const c = this.challenges[i];
1046 if (
1047 c.type == ctype &&
1048 (
1049 c.from.sid == this.st.user.sid ||
1050 (c.from.id > 0 && c.from.id == this.st.user.id)
1051 )
1052 ) {
1053 countMyChalls++;
1054 if (c.added < oldestAdded) {
1055 challToDelIdx = i;
1056 oldestAdded = c.added;
1057 }
1058 }
1059 }
1060 if (countMyChalls >= MAX_ALLOWED_CHALLS) {
1061 this.send(
1062 "deletechallenge_s",
1063 { data: { cid: this.challenges[challToDelIdx].id } }
1064 );
1065 if (ctype == "corr") {
1066 ajax(
1067 "/challenges",
1068 "DELETE",
1069 { data: { id: this.challenges[challToDelIdx].id } }
1070 );
1071 }
1072 this.challenges.splice(challToDelIdx, 1);
1073 }
1074 this.send("newchallenge", {
1075 data: Object.assign({ from: this.st.user.sid }, chall)
1076 });
1077 // Add new challenge:
1078 chall.from = {
1079 sid: this.st.user.sid,
1080 id: this.st.user.id,
1081 name: this.st.user.name
1082 };
1083 chall.added = Date.now();
1084 // NOTE: vname and type are redundant (deduced from cadence + vid)
1085 chall.type = ctype;
1086 chall.vname = this.newchallenge.vname;
1087 this.challenges.push(chall);
1088 // Remember cadence + vid for quicker further challenges:
1089 localStorage.setItem("cadence", chall.cadence);
1090 localStorage.setItem("vid", chall.vid);
1091 localStorage.setItem("challRandomness", chall.randomness);
1092 document.getElementById("modalNewgame").checked = false;
1093 // Show the challenge if not on current display
1094 if (
1095 (ctype == "live" && this.cdisplay == "corr") ||
1096 (ctype == "corr" && this.cdisplay == "live")
1097 ) {
1098 this.setDisplay('c', ctype);
1099 }
1100 };
1101 if (ctype == "live") {
1102 // Live challenges have a random ID
1103 finishAddChallenge(null);
1104 } else {
1105 // Correspondance game: send challenge to server
1106 ajax(
1107 "/challenges",
1108 "POST",
1109 {
1110 data: { chall: chall },
1111 success: (response) => {
1112 finishAddChallenge(response.id);
1113 }
1114 }
1115 );
1116 }
1117 },
1118 // Callback function after a diagram was showed to accept
1119 // or refuse targetted challenge:
1120 decisionChallenge: function(accepted) {
1121 this.curChallToAccept.accepted = accepted;
1122 this.finishProcessingChallenge(this.curChallToAccept);
1123 document.getElementById("modalAccept").checked = false;
1124 },
1125 finishProcessingChallenge: function(c) {
1126 if (c.accepted) {
1127 c.seat = {
1128 sid: this.st.user.sid,
1129 id: this.st.user.id,
1130 name: this.st.user.name
1131 };
1132 this.launchGame(c);
1133 if (c.type == "live") {
1134 // Remove all live challenges of both players
1135 this.send(
1136 "deletechallenge_s",
1137 { data: { sids: [c.from.sid, c.seat.sid] } }
1138 );
1139 }
1140 else
1141 // Corr challenge: just remove the challenge
1142 this.send("deletechallenge_s", { data: { cid: c.id } });
1143 } else {
1144 const oppsid = this.getOppsid(c);
1145 if (!!oppsid)
1146 this.send("refusechallenge", { data: c.id, target: oppsid });
1147 if (c.type == "corr") {
1148 ajax(
1149 "/challenges",
1150 "DELETE",
1151 { data: { id: c.id } }
1152 );
1153 }
1154 this.send("deletechallenge_s", { data: { cid: c.id } });
1155 }
1156 },
1157 // TODO: if several players click same challenge at the same time: problem
1158 clickChallenge: async function(c) {
1159 const myChallenge =
1160 c.from.sid == this.st.user.sid || //live
1161 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
1162 if (!myChallenge) {
1163 if (c.type == "corr" && this.st.user.id <= 0) {
1164 alert(this.st.tr["Please log in to accept corr challenges"]);
1165 return;
1166 }
1167 c.accepted = true;
1168 await import("@/variants/" + c.vname + ".js")
1169 .then((vModule) => {
1170 window.V = vModule[c.vname + "Rules"];
1171 if (!!c.to) {
1172 // c.to == this.st.user.name (connected)
1173 if (!!c.fen) {
1174 const parsedFen = V.ParseFen(c.fen);
1175 c.mycolor = V.GetOppCol(parsedFen.turn);
1176 this.tchallDiag = getDiagram({
1177 position: parsedFen.position,
1178 orientation: c.mycolor
1179 });
1180 }
1181 this.curChallToAccept = c;
1182 document.getElementById("modalAccept").checked = true;
1183 }
1184 else this.finishProcessingChallenge(c);
1185 });
1186 }
1187 else {
1188 // My challenge
1189 if (c.type == "corr") {
1190 ajax(
1191 "/challenges",
1192 "DELETE",
1193 { data: { id: c.id } }
1194 );
1195 }
1196 this.send("deletechallenge_s", { data: { cid: c.id } });
1197 }
1198 // In all cases, the challenge is consumed:
1199 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
1200 },
1201 // NOTE: when launching game, the challenge is already being deleted
1202 launchGame: function(c) {
1203 // White player index 0, black player index 1:
1204 let players =
1205 !!c.mycolor
1206 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
1207 : shuffle([c.from, c.seat]);
1208 players.forEach(p => {
1209 if (!!p["tmpIds"]) delete p["tmpIds"];
1210 });
1211 // These game informations will be shared
1212 let gameInfo = {
1213 id: getRandString(),
1214 fen: c.fen || V.GenRandInitFen(c.randomness),
1215 randomness: c.randomness, //for rematch
1216 players: players,
1217 vid: c.vid,
1218 cadence: c.cadence
1219 };
1220 const notifyNewgame = () => {
1221 const oppsid = this.getOppsid(c);
1222 if (!!oppsid)
1223 // Opponent is online
1224 this.send("startgame", { data: gameInfo, target: oppsid });
1225 // If new corr game, notify Hall (except opponent and me)
1226 if (c.type == "corr") {
1227 this.send(
1228 "newgame",
1229 {
1230 data: gameInfo,
1231 excluded: [this.st.user.sid, oppsid]
1232 }
1233 );
1234 }
1235 // Notify MyGames page:
1236 this.send(
1237 "notifynewgame",
1238 {
1239 data: gameInfo,
1240 targets: gameInfo.players
1241 }
1242 );
1243 // NOTE: no need to send the game to the room, since I'll connect
1244 // on game just after, the main Hall will be notified.
1245 };
1246 if (c.type == "live") {
1247 notifyNewgame();
1248 this.startNewGame(gameInfo);
1249 } else {
1250 // corr: game only on server
1251 ajax(
1252 "/games",
1253 "POST",
1254 {
1255 // cid is useful to delete the challenge:
1256 data: {
1257 gameInfo: gameInfo,
1258 cid: c.id
1259 },
1260 success: (response) => {
1261 gameInfo.id = response.id;
1262 notifyNewgame();
1263 this.$router.push("/game/" + response.id);
1264 }
1265 }
1266 );
1267 }
1268 },
1269 // NOTE: for live games only (corr games start on the server)
1270 startNewGame: function(gameInfo) {
1271 const game = Object.assign(
1272 {},
1273 gameInfo,
1274 {
1275 // (other) Game infos: constant
1276 fenStart: gameInfo.fen,
1277 vname: this.getVname(gameInfo.vid),
1278 created: Date.now(),
1279 // Game state (including FEN): will be updated
1280 moves: [],
1281 clocks: [-1, -1], //-1 = unstarted
1282 chats: [],
1283 score: "*"
1284 }
1285 );
1286 setTimeout(
1287 () => {
1288 const myIdx = (game.players[0].sid == this.st.user.sid ? 0 : 1);
1289 GameStorage.add(game, (err) => {
1290 // If an error occurred, game is not added: a tab already
1291 // added the game. Maybe a focused one, maybe not.
1292 // We know for sure that it emitted the gong start sound.
1293 // ==> Do not play it again.
1294 if (!err && this.st.settings.sound)
1295 new Audio("/sounds/newgame.flac").play().catch(() => {});
1296 if (!this.focus) {
1297 notify(
1298 "New live game",
1299 { body: "vs " + game.players[1-myIdx].name || "@nonymous" }
1300 );
1301 }
1302 this.$router.push("/game/" + gameInfo.id);
1303 });
1304 },
1305 this.focus ? 500 + 1000 * Math.random() : 0
1306 );
1307 }
1308 }
1309 };
1310 </script>
1311
1312 <style lang="sass" scoped>
1313 .active
1314 color: #42a983
1315
1316 #infoDiv > .card
1317 padding: 15px 0
1318 max-width: 430px
1319
1320 #newgameDiv > .card, #acceptDiv > .card
1321 max-width: 767px
1322 max-height: 100%
1323
1324 div#peopleWrap > .card
1325 max-height: 100%
1326
1327 @media screen and (min-width: 1281px)
1328 div#peopleWrap > .card
1329 max-width: 66.67%
1330
1331 @media screen and (max-width: 1280px)
1332 div#peopleWrap > .card
1333 max-width: 83.33%
1334
1335 @media screen and (max-width: 767px)
1336 div#peopleWrap > .card
1337 max-width: 100%
1338
1339 #players
1340 width: 50%
1341 position: relative
1342 float: left
1343
1344 #chat
1345 width: 50%
1346 float: left
1347 position: relative
1348
1349 @media screen and (max-width: 767px)
1350 #players, #chats
1351 width: 100%
1352
1353 #chat > .card
1354 max-width: 100%
1355 margin: 0;
1356 border: none;
1357
1358 #players > p
1359 margin-left: 5px
1360
1361 .anonymous
1362 font-style: italic
1363
1364 button.player-action
1365 margin-left: 32px
1366
1367 .somethingnew
1368 background-color: #c5fefe !important
1369
1370 .tabbtn
1371 background-color: #f9faee
1372
1373 button.acceptBtn
1374 background-color: lightgreen
1375 button.refuseBtn
1376 background-color: red
1377
1378 #buttonsTchall
1379 // margin-top set dynamically (depends if diagram showed or not)
1380 & > button > span
1381 width: 100%
1382 text-align: center
1383
1384 .variantName
1385 font-weight: bold
1386
1387 .diagram
1388 margin: 0 auto
1389 max-width: 400px
1390 // width: 100% required for Firefox
1391 width: 100%
1392
1393 #inputFen
1394 width: 100%
1395
1396 #div2, #div3
1397 margin-top: 15px
1398 @media screen and (max-width: 767px)
1399 #div2, #div3
1400 margin-top: 0
1401
1402 tr > td
1403 &.random-0
1404 background-color: #FF5733
1405 &.random-1
1406 background-color: #2B63B4
1407 &.random-2
1408 background-color: #33B42B
1409
1410 @media screen and (max-width: 767px)
1411 h4
1412 margin: 5px 0
1413
1414 button#loadMoreBtn
1415 display: block
1416 margin: 0 auto
1417
1418 td.remove-preset
1419 background-color: lightgrey
1420 text-align: center
1421 & > img
1422 height: 1em
1423 </style>