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