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