Replaced AJAX by fetch: not everything tested yet, but seems fine
[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(v-html="tchallDiag")
19 .button-group#buttonsTchall
20 button.acceptBtn(@click="decisionChallenge(true)")
21 span {{ st.tr["Accept challenge?"] }}
22 button.refuseBtn(@click="decisionChallenge(false)")
23 span {{ st.tr["Refuse"] }}
24 input#modalNewgame.modal(
25 type="checkbox"
26 @change="cadenceFocusIfOpened($event)"
27 )
28 div#newgameDiv(
29 role="dialog"
30 data-checkbox="modalNewgame"
31 )
32 .card
33 label#closeNewgame.modal-close(for="modalNewgame")
34 div(@keyup.enter="newChallenge()")
35 fieldset
36 label(for="selectVariant") {{ st.tr["Variant"] }} *
37 select#selectVariant(
38 @change="loadNewchallVariant(trySetNewchallDiag)"
39 v-model="newchallenge.vid"
40 )
41 option(
42 v-for="v in st.variants"
43 :value="v.id"
44 :selected="newchallenge.vid==v.id"
45 )
46 | {{ v.name }}
47 fieldset
48 label(for="cadence") {{ st.tr["Cadence"] }} *
49 div#predefinedCadences
50 button(type="button") 15+5
51 button(type="button") 45+30
52 button(type="button") 3d
53 button(type="button") 7d
54 input#cadence(
55 type="text"
56 v-model="newchallenge.cadence"
57 placeholder="5+0, 1h+30s, 5d ..."
58 )
59 fieldset
60 label(for="selectRandomLevel") {{ st.tr["Randomness"] }} *
61 select#selectRandomLevel(v-model="newchallenge.randomness")
62 option(value="0") {{ st.tr["Deterministic"] }}
63 option(value="1") {{ st.tr["Symmetric random"] }}
64 option(value="2") {{ st.tr["Asymmetric random"] }}
65 fieldset(v-if="st.user.id > 0")
66 label(for="selectPlayers") {{ st.tr["Play with?"] }}
67 input#selectPlayers(
68 type="text"
69 v-model="newchallenge.to"
70 )
71 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
72 input#inputFen(
73 placeholder="FEN"
74 @input="trySetNewchallDiag()"
75 type="text"
76 v-model="newchallenge.fen"
77 )
78 .diagram(v-html="newchallenge.diag")
79 button(@click="newChallenge()") {{ st.tr["Send challenge"] }}
80 input#modalPeople.modal(
81 type="checkbox"
82 @click="resetSocialColor()"
83 )
84 div#peopleWrap(
85 role="dialog"
86 data-checkbox="modalPeople"
87 )
88 .card
89 label.modal-close(for="modalPeople")
90 #people
91 #players
92 p(
93 v-for="sid in Object.keys(people)"
94 v-if="!!people[sid].name"
95 )
96 span {{ people[sid].name }}
97 button.player-action(
98 v-if="isGamer(sid)"
99 @click="watchGame(sid)"
100 )
101 | {{ st.tr["Observe"] }}
102 button.player-action(
103 v-else-if="st.user.id > 0 && sid != st.user.sid"
104 @click="challenge(sid)"
105 )
106 | {{ st.tr["Challenge"] }}
107 p.anonymous @nonymous ({{ anonymousCount }})
108 #chat
109 Chat(
110 :newChat="newChat"
111 @mychat="processChat"
112 :pastChats="[]"
113 )
114 .clearer
115 .row
116 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
117 .button-group
118 button#peopleBtn(onClick="window.doClick('modalPeople')")
119 | {{ st.tr["Who's there?"] }}
120 button(onClick="window.doClick('modalNewgame')")
121 | {{ st.tr["New game"] }}
122 .row
123 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
124 div#div2
125 .button-group
126 button.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
127 | {{ st.tr["Live challenges"] }}
128 button.tabbtn#btnCcorr(@click="setDisplay('c','corr',$event)")
129 | {{ st.tr["Correspondance challenges"] }}
130 ChallengeList(
131 v-show="cdisplay=='live'"
132 :challenges="filterChallenges('live')"
133 @click-challenge="clickChallenge"
134 )
135 ChallengeList(
136 v-show="cdisplay=='corr'"
137 :challenges="filterChallenges('corr')"
138 @click-challenge="clickChallenge"
139 )
140 div#div3
141 .button-group
142 button.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
143 | {{ st.tr["Live games"] }}
144 button.tabbtn#btnGcorr(@click="setDisplay('g','corr',$event)")
145 | {{ st.tr["Correspondance games"] }}
146 GameList(
147 v-show="gdisplay=='live'"
148 :games="filterGames('live')"
149 :showBoth="true"
150 @show-game="showGame"
151 )
152 GameList(
153 v-show="gdisplay=='corr'"
154 :games="filterGames('corr')"
155 :showBoth="true"
156 @show-game="showGame"
157 )
158 </template>
159
160 <script>
161 import { store } from "@/store";
162 import { checkChallenge } from "@/data/challengeCheck";
163 import { ArrayFun } from "@/utils/array";
164 import { ajax } from "@/utils/ajax";
165 import params from "@/parameters";
166 import { getRandString, shuffle } from "@/utils/alea";
167 import { getDiagram } from "@/utils/printDiagram";
168 import Chat from "@/components/Chat.vue";
169 import GameList from "@/components/GameList.vue";
170 import ChallengeList from "@/components/ChallengeList.vue";
171 import { GameStorage } from "@/utils/gameStorage";
172 import { processModalClick } from "@/utils/modalClick";
173 export default {
174 name: "my-hall",
175 components: {
176 Chat,
177 GameList,
178 ChallengeList
179 },
180 data: function() {
181 return {
182 st: store.state,
183 cdisplay: "live", //or corr
184 gdisplay: "live",
185 games: [],
186 challenges: [],
187 people: {},
188 infoMessage: "",
189 newchallenge: {
190 fen: "",
191 vid: parseInt(localStorage.getItem("vid")) || 0,
192 to: "", //name of challenged player (if any)
193 cadence: localStorage.getItem("cadence") || "",
194 randomness: parseInt(localStorage.getItem("randomness")) || 2,
195 // VariantRules object, stored to not interfere with
196 // diagrams of targetted challenges:
197 V: null,
198 vname: "",
199 diag: "" //visualizing FEN
200 },
201 tchallDiag: "",
202 curChallToAccept: {from: {}},
203 newChat: "",
204 conn: null,
205 connexionString: "",
206 // Related to (killing of) self multi-connects:
207 newConnect: {},
208 killed: {}
209 };
210 },
211 watch: {
212 // st.variants changes only once, at loading from [] to [...]
213 "st.variants": function() {
214 // Set potential challenges and games variant names:
215 this.challenges.concat(this.games).forEach(o => {
216 if (!o.vname) o.vname = this.getVname(o.vid);
217 });
218 if (!this.newchallenge.V && this.newchallenge.vid > 0)
219 this.loadNewchallVariant();
220 }
221 },
222 computed: {
223 anonymousCount: function() {
224 let count = 0;
225 Object.values(this.people).forEach(p => {
226 // Do not cound people who did not send their identity yet:
227 count += (!p.name && p.id === 0) ? 1 : 0;
228 });
229 return count;
230 }
231 },
232 created: function() {
233 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
234 this.loadNewchallVariant();
235 const my = this.st.user;
236 this.$set(this.people, my.sid, { id: my.id, name: my.name, pages: ["/"] });
237 // Ask server for current corr games (all but mines)
238 ajax(
239 "/games",
240 "GET",
241 {
242 data: { uid: this.st.user.id, excluded: true },
243 success: (response) => {
244 this.games = this.games.concat(
245 response.games.map(g => {
246 const type = this.classifyObject(g);
247 const vname = this.getVname(g.vid);
248 return Object.assign({}, g, { type: type, vname: vname });
249 })
250 );
251 }
252 }
253 );
254 // Also ask for corr challenges (open + sent by/to me)
255 ajax(
256 "/challenges",
257 "GET",
258 {
259 data: { uid: this.st.user.id },
260 success: (response) => {
261 // Gather all senders names, and then retrieve full identity:
262 // (TODO [perf]: some might be online...)
263 let names = {};
264 response.challenges.forEach(c => {
265 if (c.uid != this.st.user.id) names[c.uid] = "";
266 else if (!!c.target && c.target != this.st.user.id)
267 names[c.target] = "";
268 });
269 const addChallenges = () => {
270 names[this.st.user.id] = this.st.user.name; //in case of
271 this.challenges = this.challenges.concat(
272 response.challenges.map(c => {
273 const from = { name: names[c.uid], id: c.uid }; //or just name
274 const type = this.classifyObject(c);
275 const vname = this.getVname(c.vid);
276 return Object.assign(
277 {},
278 {
279 type: type,
280 vname: vname,
281 from: from,
282 to: c.target ? names[c.target] : ""
283 },
284 c
285 );
286 })
287 );
288 };
289 if (Object.keys(names).length > 0) {
290 ajax(
291 "/users",
292 "GET",
293 {
294 data: { ids: Object.keys(names).join(",") },
295 success: (response2) => {
296 response2.users.forEach(u => {
297 names[u.id] = u.name;
298 });
299 addChallenges();
300 }
301 }
302 );
303 } else addChallenges();
304 }
305 }
306 );
307 const connectAndPoll = () => {
308 this.send("connect");
309 this.send("pollclientsandgamers");
310 };
311 // Initialize connection
312 this.connexionString =
313 params.socketUrl +
314 "/?sid=" +
315 this.st.user.sid +
316 "&tmpId=" +
317 getRandString() +
318 "&page=" +
319 // Hall: path is "/" (could be hard-coded as well)
320 encodeURIComponent(this.$route.path);
321 this.conn = new WebSocket(this.connexionString);
322 this.conn.onopen = connectAndPoll;
323 this.conn.onmessage = this.socketMessageListener;
324 this.conn.onclose = this.socketCloseListener;
325 },
326 mounted: function() {
327 ["peopleWrap", "infoDiv", "newgameDiv"].forEach(eltName => {
328 let elt = document.getElementById(eltName);
329 elt.addEventListener("click", processModalClick);
330 });
331 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
332 b.addEventListener("click", () => {
333 this.newchallenge.cadence = b.innerHTML;
334 });
335 });
336 const dispCorr = this.$route.query["disp"];
337 const showCtype =
338 dispCorr || localStorage.getItem("type-challenges") || "live";
339 const showGtype =
340 dispCorr || localStorage.getItem("type-games") || "live";
341 this.setDisplay("c", showCtype);
342 this.setDisplay("g", showGtype);
343 },
344 beforeDestroy: function() {
345 this.send("disconnect");
346 },
347 methods: {
348 // Helpers:
349 cadenceFocusIfOpened: function() {
350 if (event.target.checked)
351 document.getElementById("cadence").focus();
352 },
353 send: function(code, obj) {
354 if (!!this.conn) {
355 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
356 }
357 },
358 getVname: function(vid) {
359 const variant = this.st.variants.find(v => v.id == vid);
360 // this.st.variants might be uninitialized (variant == null)
361 return variant ? variant.name : "";
362 },
363 filterChallenges: function(type) {
364 return this.challenges.filter(c => c.type == type);
365 },
366 filterGames: function(type) {
367 return this.games.filter(g => g.type == type);
368 },
369 classifyObject: function(o) {
370 //challenge or game
371 return o.cadence.indexOf("d") === -1 ? "live" : "corr";
372 },
373 setDisplay: function(letter, type, e) {
374 this[letter + "display"] = type;
375 localStorage.setItem(
376 "type-" + (letter == "c" ? "challenges" : "games"),
377 type
378 );
379 let elt = e
380 ? e.target
381 : document.getElementById("btn" + letter.toUpperCase() + type);
382 elt.classList.add("active");
383 elt.classList.remove("somethingnew"); //in case of
384 if (!!elt.previousElementSibling)
385 elt.previousElementSibling.classList.remove("active");
386 else elt.nextElementSibling.classList.remove("active");
387 },
388 isGamer: function(sid) {
389 return this.people[sid].pages.some(p => p.indexOf("/game/") >= 0);
390 },
391 challenge: function(sid) {
392 // Available, in Hall (only)
393 this.newchallenge.to = this.people[sid].name;
394 document.getElementById("modalPeople").checked = false;
395 window.doClick("modalNewgame");
396 },
397 watchGame: function(sid) {
398 // In some game, maybe playing maybe not: show a random one
399 let gids = [];
400 this.people[sid].pages.forEach(p => {
401 const matchGid = p.match(/[a-zA-Z0-9]+$/);
402 if (!!matchGid) gids.push(matchGid[0]);
403 });
404 const gid = gids[Math.floor(Math.random() * gids.length)];
405 const game = this.games.find(g => g.id == gid);
406 if (!!game) this.showGame(game);
407 else this.$router.push("/game/" + gid); //game vs. me
408 },
409 showGame: function(g) {
410 // NOTE: we are an observer, since only games I don't play are shown here
411 // ==> Moves sent by connected remote player(s) if live game
412 let url = "/game/" + g.id;
413 if (g.type == "live")
414 url += "?rid=" + g.rids[Math.floor(Math.random() * g.rids.length)];
415 this.$router.push(url);
416 },
417 resetSocialColor: function() {
418 // TODO: this is called twice, once on opening an once on closing
419 document.getElementById("peopleBtn").classList.remove("somethingnew");
420 },
421 processChat: function(chat) {
422 this.send("newchat", { data: chat });
423 },
424 getOppsid: function(c) {
425 let oppsid = c.from.sid; //may not be defined if corr + offline opp
426 if (!oppsid) {
427 oppsid = Object.keys(this.people).find(
428 sid => this.people[sid].id == c.from.id
429 );
430 }
431 return oppsid;
432 },
433 // Messaging center:
434 socketMessageListener: function(msg) {
435 if (!this.conn) return;
436 const data = JSON.parse(msg.data);
437 switch (data.code) {
438 case "pollclientsandgamers": {
439 // Since people can be both in Hall and Game,
440 // need to track "askIdentity" requests:
441 let identityAsked = {};
442 data.sockIds.forEach(s => {
443 const page = s.page || "/";
444 if (s.sid != this.st.user.sid && !identityAsked[s.sid]) {
445 this.send("askidentity", { target: s.sid, page: page });
446 identityAsked[s.sid] = true;
447 }
448 if (!this.people[s.sid])
449 // Do not set name or id: identity unknown yet
450 this.$set(this.people, s.sid, { pages: [page] });
451 else if (this.people[s.sid].pages.indexOf(page) < 0)
452 this.people[s.sid].pages.push(page);
453 if (!s.page)
454 // Peer is in Hall
455 this.send("askchallenge", { target: s.sid });
456 // Peer is in Game
457 else this.send("askgame", { target: s.sid, page: page });
458 });
459 break;
460 }
461 case "connect":
462 case "gconnect": {
463 const page = data.page || "/";
464 // NOTE: player could have been polled earlier, but might have logged in then
465 // So it's a good idea to ask identity if he was anonymous.
466 // But only ask game / challenge if currently disconnected.
467 if (!this.people[data.from]) {
468 this.$set(this.people, data.from, { pages: [page] });
469 if (data.code == "connect")
470 this.send("askchallenge", { target: data.from });
471 else this.send("askgame", { target: data.from, page: page });
472 } else {
473 // Append page if not already in list
474 if (this.people[data.from].pages.indexOf(page) < 0)
475 this.people[data.from].pages.push(page);
476 }
477 if (!this.people[data.from].name && this.people[data.from].id !== 0) {
478 // Identity not known yet
479 this.newConnect[data.from] = true; //for self multi-connects tests
480 this.send("askidentity", { target: data.from, page: page });
481 }
482 break;
483 }
484 case "disconnect":
485 case "gdisconnect": {
486 // If the user reloads the page twice very quickly (experienced with Firefox),
487 // the first reload won't have time to connect but will trigger a "close" event anyway.
488 // ==> Next check is required.
489 if (!this.people[data.from]) return;
490 // Disconnect means no more tmpIds:
491 if (data.code == "disconnect") {
492 // Remove the live challenge sent by this player:
493 ArrayFun.remove(
494 this.challenges,
495 c => c.type == "live" && c.from.sid == data.from
496 );
497 } else {
498 // Remove the matching live game if now unreachable
499 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
500 const gidx = this.games.findIndex(g => g.id == gid);
501 if (gidx >= 0) {
502 const game = this.games[gidx];
503 if (
504 game.type == "live" &&
505 game.rids.length == 1 &&
506 game.rids[0] == data.from
507 ) {
508 this.games.splice(gidx, 1);
509 }
510 }
511 }
512 const page = data.page || "/";
513 ArrayFun.remove(this.people[data.from].pages, p => p == page);
514 if (this.people[data.from].pages.length == 0)
515 this.$delete(this.people, data.from);
516 break;
517 }
518 case "killed":
519 // I logged in elsewhere:
520 this.conn = null;
521 alert(this.st.tr["New connexion detected: tab now offline"]);
522 break;
523 case "askidentity": {
524 // Request for identification (TODO: anonymous shouldn't need to reply)
525 const me = {
526 // Decompose to avoid revealing email
527 name: this.st.user.name,
528 sid: this.st.user.sid,
529 id: this.st.user.id
530 };
531 this.send("identity", { data: me, target: data.from });
532 break;
533 }
534 case "identity": {
535 const user = data.data;
536 this.$set(this.people, user.sid, {
537 id: user.id,
538 name: user.name,
539 pages: this.people[user.sid].pages
540 });
541 // If I multi-connect, kill current connexion if no mark (I'm older)
542 if (this.newConnect[user.sid]) {
543 if (
544 user.id > 0 &&
545 user.id == this.st.user.id &&
546 user.sid != this.st.user.sid &&
547 !this.killed[this.st.user.sid]
548 ) {
549 this.send("killme", { sid: this.st.user.sid });
550 this.killed[this.st.user.sid] = true;
551 }
552 delete this.newConnect[user.sid];
553 }
554 break;
555 }
556 case "askchallenge": {
557 // Send my current live challenge (if any)
558 const cIdx = this.challenges.findIndex(
559 c => c.from.sid == this.st.user.sid && c.type == "live"
560 );
561 if (cIdx >= 0) {
562 const c = this.challenges[cIdx];
563 // NOTE: in principle, should only send targeted challenge to the target.
564 // But we may not know yet the identity of the target (just name),
565 // so cannot decide if data.from is the target or not.
566 const myChallenge = {
567 id: c.id,
568 from: this.st.user.sid,
569 to: c.to,
570 randomness: c.randomness,
571 fen: c.fen,
572 vid: c.vid,
573 cadence: c.cadence,
574 added: c.added
575 };
576 this.send("challenge", { data: myChallenge, target: data.from });
577 }
578 break;
579 }
580 case "challenge": //after "askchallenge"
581 case "newchallenge": {
582 // NOTE about next condition: see "askchallenge" case.
583 const chall = data.data;
584 if (
585 !chall.to ||
586 (this.people[chall.from].id > 0 &&
587 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
588 ) {
589 let newChall = Object.assign({}, chall);
590 newChall.type = this.classifyObject(chall);
591 newChall.randomness = chall.randomness;
592 newChall.added = Date.now();
593 let fromValues = Object.assign({}, this.people[chall.from]);
594 delete fromValues["pages"]; //irrelevant in this context
595 newChall.from = Object.assign({ sid: chall.from }, fromValues);
596 newChall.vname = this.getVname(newChall.vid);
597 this.challenges.push(newChall);
598 if (
599 (newChall.type == "live" && this.cdisplay == "corr") ||
600 (newChall.type == "corr" && this.cdisplay == "live")
601 ) {
602 document
603 .getElementById("btnC" + newChall.type)
604 .classList.add("somethingnew");
605 }
606 }
607 break;
608 }
609 case "refusechallenge": {
610 const cid = data.data;
611 ArrayFun.remove(this.challenges, c => c.id == cid);
612 alert(this.st.tr["Challenge declined"]);
613 break;
614 }
615 case "deletechallenge": {
616 // NOTE: the challenge may be already removed
617 const cid = data.data;
618 ArrayFun.remove(this.challenges, c => c.id == cid);
619 break;
620 }
621 case "game": //individual request
622 case "newgame": {
623 // NOTE: it may be live or correspondance
624 const game = data.data;
625 // Ignore games where I play (corr games)
626 if (game.players.every(p =>
627 p.sid != this.st.user.sid || p.id != this.st.user.id))
628 {
629 let locGame = this.games.find(g => g.id == game.id);
630 if (!locGame) {
631 let newGame = game;
632 newGame.type = this.classifyObject(game);
633 newGame.vname = this.getVname(game.vid);
634 if (!game.score)
635 //if new game from Hall
636 newGame.score = "*";
637 newGame.rids = [game.rid];
638 delete newGame["rid"];
639 this.games.push(newGame);
640 if (
641 (newGame.type == "live" && this.gdisplay == "corr") ||
642 (newGame.type == "corr" && this.gdisplay == "live")
643 ) {
644 document
645 .getElementById("btnG" + newGame.type)
646 .classList.add("somethingnew");
647 }
648 } else {
649 // Append rid (if not already in list)
650 if (!locGame.rids.includes(game.rid)) locGame.rids.push(game.rid);
651 }
652 }
653 break;
654 }
655 case "result": {
656 let g = this.games.find(g => g.id == data.gid);
657 if (!!g) g.score = data.score;
658 break;
659 }
660 case "startgame": {
661 // New game just started: data contain all information
662 const gameInfo = data.data;
663 if (this.classifyObject(gameInfo) == "live")
664 this.startNewGame(gameInfo);
665 else {
666 this.infoMessage =
667 this.st.tr["New correspondance game:"] +
668 " <a href='#/game/" +
669 gameInfo.id +
670 "'>" +
671 "#/game/" +
672 gameInfo.id +
673 "</a>";
674 let modalBox = document.getElementById("modalInfo");
675 modalBox.checked = true;
676 }
677 break;
678 }
679 case "newchat":
680 this.newChat = data.data;
681 if (!document.getElementById("modalPeople").checked)
682 document.getElementById("peopleBtn").classList.add("somethingnew");
683 break;
684 }
685 },
686 socketCloseListener: function() {
687 if (!this.conn) return;
688 this.conn = new WebSocket(this.connexionString);
689 this.conn.addEventListener("message", this.socketMessageListener);
690 this.conn.addEventListener("close", this.socketCloseListener);
691 },
692 // Challenge lifecycle:
693 loadNewchallVariant: async function(cb) {
694 const vname = this.getVname(this.newchallenge.vid);
695 const vModule = await import("@/variants/" + vname + ".js");
696 this.newchallenge.V = vModule.VariantRules;
697 this.newchallenge.vname = vname;
698 if (!!cb)
699 cb();
700 },
701 trySetNewchallDiag: function() {
702 if (!this.newchallenge.fen) {
703 this.newchallenge.diag = "";
704 return;
705 }
706 // If vid > 0 then the variant is loaded (function above):
707 window.V = this.newchallenge.V;
708 if (
709 this.newchallenge.vid > 0 &&
710 !!this.newchallenge.fen &&
711 V.IsGoodFen(this.newchallenge.fen)
712 ) {
713 const parsedFen = V.ParseFen(this.newchallenge.fen);
714 this.newchallenge.diag = getDiagram({
715 position: parsedFen.position,
716 orientation: parsedFen.turn
717 });
718 }
719 },
720 newChallenge: async function() {
721 if (!!(this.newchallenge.cadence.match(/^[0-9]+$/)))
722 this.newchallenge.cadence += "+0"; //assume minutes, no increment
723 const ctype = this.classifyObject(this.newchallenge);
724 // TODO: cadence still unchecked so ctype could be wrong...
725 let error = "";
726 if (!this.newchallenge.vid)
727 error = this.st.tr["Please select a variant"];
728 else if (ctype == "corr" && this.st.user.id <= 0)
729 error = this.st.tr["Please log in to play correspondance games"];
730 else if (!!this.newchallenge.to) {
731 if (this.newchallenge.to == this.st.user.name)
732 error = this.st.tr["Self-challenge is forbidden"];
733 else if (
734 ctype == "live" &&
735 Object.values(this.people).every(p => p.name != this.newchallenge.to)
736 )
737 error = this.newchallenge.to + " " + this.st.tr["is not online"];
738 }
739 if (error) {
740 alert(error);
741 return;
742 }
743 window.V = this.newchallenge.V;
744 error = checkChallenge(this.newchallenge);
745 if (error) {
746 alert(error);
747 return;
748 }
749 // NOTE: "from" information is not required here
750 let chall = Object.assign({}, this.newchallenge);
751 delete chall["V"];
752 delete chall["diag"];
753 const finishAddChallenge = cid => {
754 chall.id = cid || "c" + getRandString();
755 // Remove old challenge if any (only one at a time of a given type):
756 const cIdx = this.challenges.findIndex(
757 c =>
758 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) &&
759 c.type == ctype
760 );
761 if (cIdx >= 0) {
762 // Delete current challenge (will be replaced now)
763 this.send("deletechallenge", { data: this.challenges[cIdx].id });
764 if (ctype == "corr") {
765 ajax(
766 "/challenges",
767 "DELETE",
768 { data: { id: this.challenges[cIdx].id } }
769 );
770 }
771 this.challenges.splice(cIdx, 1);
772 }
773 this.send("newchallenge", {
774 data: Object.assign({ from: this.st.user.sid }, chall)
775 });
776 // Add new challenge:
777 chall.from = {
778 // Decompose to avoid revealing email
779 sid: this.st.user.sid,
780 id: this.st.user.id,
781 name: this.st.user.name
782 };
783 chall.added = Date.now();
784 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
785 chall.type = ctype;
786 chall.vname = this.newchallenge.vname;
787 this.challenges.push(chall);
788 // Remember cadence + vid for quicker further challenges:
789 localStorage.setItem("cadence", chall.cadence);
790 localStorage.setItem("vid", chall.vid);
791 localStorage.setItem("randomness", chall.randomness);
792 document.getElementById("modalNewgame").checked = false;
793 // Show the challenge if not on current display
794 if (
795 (ctype == "live" && this.cdisplay == "corr") ||
796 (ctype == "corr" && this.cdisplay == "live")
797 ) {
798 this.setDisplay('c', ctype);
799 }
800 };
801 if (ctype == "live") {
802 // Live challenges have a random ID
803 finishAddChallenge(null);
804 } else {
805 // Correspondance game: send challenge to server
806 ajax(
807 "/challenges",
808 "POST",
809 {
810 data: { chall: chall },
811 success: (response) => {
812 finishAddChallenge(response.cid);
813 }
814 }
815 );
816 }
817 },
818 // Callback function after a diagram was showed to accept
819 // or refuse targetted challenge:
820 decisionChallenge: function(accepted) {
821 this.curChallToAccept.accepted = accepted;
822 this.finishProcessingChallenge(this.curChallToAccept);
823 document.getElementById("modalAccept").checked = false;
824 },
825 finishProcessingChallenge: function(c) {
826 if (c.accepted) {
827 c.seat = {
828 // Again, avoid c.seat = st.user to not reveal email
829 sid: this.st.user.sid,
830 id: this.st.user.id,
831 name: this.st.user.name
832 };
833 this.launchGame(c);
834 } else {
835 const oppsid = this.getOppsid(c);
836 if (!!oppsid)
837 this.send("refusechallenge", { data: c.id, target: oppsid });
838 if (c.type == "corr") {
839 ajax(
840 "/challenges",
841 "DELETE",
842 { data: { id: c.id } }
843 );
844 }
845 }
846 this.send("deletechallenge", { data: c.id });
847 },
848 clickChallenge: async function(c) {
849 const myChallenge =
850 c.from.sid == this.st.user.sid || //live
851 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
852 if (!myChallenge) {
853 if (c.type == "corr" && this.st.user.id <= 0) {
854 alert(this.st.tr["Please log in to accept corr challenges"]);
855 return;
856 }
857 c.accepted = true;
858 const vModule = await import("@/variants/" + c.vname + ".js");
859 window.V = vModule.VariantRules;
860 if (!!c.to) {
861 // c.to == this.st.user.name (connected)
862 if (!!c.fen) {
863 const parsedFen = V.ParseFen(c.fen);
864 c.mycolor = V.GetOppCol(parsedFen.turn);
865 this.tchallDiag = getDiagram({
866 position: parsedFen.position,
867 orientation: c.mycolor
868 });
869 this.curChallToAccept = c;
870 document.getElementById("modalAccept").checked = true;
871 }
872 else {
873 if (!confirm(this.st.tr["Accept challenge?"]))
874 c.accepted = false;
875 this.finishProcessingChallenge(c);
876 }
877 }
878 else
879 this.finishProcessingChallenge(c);
880 }
881 else {
882 // My challenge
883 if (c.type == "corr") {
884 ajax(
885 "/challenges",
886 "DELETE",
887 { data: { id: c.id } }
888 );
889 }
890 this.send("deletechallenge", { data: c.id });
891 }
892 // In all cases, the challenge is consumed:
893 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
894 },
895 // NOTE: when launching game, the challenge is already being deleted
896 launchGame: function(c) {
897 // These game informations will be shared
898 let gameInfo = {
899 id: getRandString(),
900 fen: c.fen || V.GenRandInitFen(c.randomness),
901 // White player index 0, black player index 1:
902 players: c.mycolor
903 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
904 : shuffle([c.from, c.seat]),
905 vid: c.vid,
906 cadence: c.cadence
907 };
908 const notifyNewgame = () => {
909 const oppsid = this.getOppsid(c);
910 if (!!oppsid)
911 //opponent is online
912 this.send("startgame", { data: gameInfo, target: oppsid });
913 // Send game info (only if live) to everyone except me in this tab
914 this.send("newgame", { data: gameInfo });
915 };
916 if (c.type == "live") {
917 notifyNewgame();
918 this.startNewGame(gameInfo);
919 } //corr: game only on server
920 else {
921 ajax(
922 "/games",
923 "POST",
924 {
925 // cid is useful to delete the challenge:
926 data: { gameInfo: gameInfo, cid: c.id },
927 success: (response) => {
928 gameInfo.id = response.gameId;
929 notifyNewgame();
930 this.$router.push("/game/" + response.gameId);
931 }
932 }
933 );
934 }
935 },
936 // NOTE: for live games only (corr games start on the server)
937 startNewGame: function(gameInfo) {
938 const game = Object.assign({}, gameInfo, {
939 // (other) Game infos: constant
940 fenStart: gameInfo.fen,
941 vname: this.getVname(gameInfo.vid),
942 created: Date.now(),
943 // Game state (including FEN): will be updated
944 moves: [],
945 clocks: [-1, -1], //-1 = unstarted
946 initime: [0, 0], //initialized later
947 score: "*"
948 });
949 GameStorage.add(game, (err) => {
950 // If an error occurred, game is not added: abort
951 if (!err) {
952 if (this.st.settings.sound)
953 new Audio("/sounds/newgame.flac").play().catch(() => {});
954 this.$router.push("/game/" + gameInfo.id);
955 }
956 });
957 }
958 }
959 };
960 </script>
961
962 <style lang="sass" scoped>
963 .active
964 color: #42a983
965
966 #infoDiv > .card
967 padding: 15px 0
968 max-width: 430px
969
970 #newgameDiv > .card, #acceptDiv > .card
971 max-width: 767px
972 max-height: 100%
973
974 div#peopleWrap > .card
975 max-height: 100%
976
977 @media screen and (min-width: 1281px)
978 div#peopleWrap > .card
979 max-width: 66.67%
980
981 @media screen and (max-width: 1280px)
982 div#peopleWrap > .card
983 max-width: 83.33%
984
985 @media screen and (max-width: 767px)
986 div#peopleWrap > .card
987 max-width: 100%
988
989 #players
990 width: 50%
991 position: relative
992 float: left
993
994 #chat
995 width: 50%
996 float: left
997 position: relative
998
999 @media screen and (max-width: 767px)
1000 #players, #chats
1001 width: 100%
1002
1003 #chat > .card
1004 max-width: 100%
1005 margin: 0;
1006 border: none;
1007
1008 #players > p
1009 margin-left: 5px
1010
1011 .anonymous
1012 font-style: italic
1013
1014 button.player-action
1015 margin-left: 32px
1016
1017 .somethingnew
1018 background-color: #c5fefe !important
1019
1020 .tabbtn
1021 background-color: #f9faee
1022
1023 button.acceptBtn
1024 background-color: lightgreen
1025 button.refuseBtn
1026 background-color: red
1027
1028 #buttonsTchall
1029 margin-top: 10px
1030 & > button > span
1031 width: 100%
1032 text-align: center
1033
1034 .variantName
1035 font-weight: bold
1036
1037 .diagram
1038 margin: 0 auto
1039 max-width: 400px
1040 // width: 100% required for Firefox
1041 width: 100%
1042
1043 #inputFen
1044 width: 100%
1045
1046 #div2, #div3
1047 margin-top: 15px
1048 @media screen and (max-width: 767px)
1049 #div2, #div3
1050 margin-top: 0
1051 </style>