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