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