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