On the way to multi-tabs support
[vchess.git] / client / src / views / Hall.vue
CommitLineData
ccd4a2b7 1<template lang="pug">
9d58ef95 2main
dce792f6 3 input#modalInfo.modal(type="checkbox")
602d6bef 4 div#infoDiv(role="dialog" data-checkbox="modalInfo" aria-labelledby="infoMessage")
dce792f6
BA
5 .card.smallpad.small-modal.text-center
6 label.modal-close(for="modalInfo")
7 h3#infoMessage.section
3d55deea 8 p(v-html="infoMessage")
5b020e73 9 input#modalNewgame.modal(type="checkbox")
602d6bef 10 div#newgameDiv(role="dialog" data-checkbox="modalNewgame"
dcd68c41 11 aria-labelledby="titleFenedit")
c97830ea 12 .card.smallpad(@keyup.enter="newChallenge")
5b020e73
BA
13 label#closeNewgame.modal-close(for="modalNewgame")
14 fieldset
602d6bef 15 label(for="selectVariant") {{ st.tr["Variant"] }} *
9d58ef95 16 select#selectVariant(v-model="newchallenge.vid")
25d18342
BA
17 option(v-for="v in st.variants" :value="v.id"
18 :selected="newchallenge.vid==v.id")
19 | {{ v.name }}
5b020e73 20 fieldset
f44fd3bf 21 label(for="timeControl") {{ st.tr["Cadence"] }} *
25d18342
BA
22 div#predefinedTimeControls
23 button 3+2
24 button 5+3
25 button 15+5
9d58ef95 26 input#timeControl(type="text" v-model="newchallenge.timeControl"
25d18342 27 placeholder="5+0, 1h+30s, 7d+1d ...")
b4d619d1 28 fieldset(v-if="st.user.id > 0")
602d6bef 29 label(for="selectPlayers") {{ st.tr["Play with?"] }}
6fba6e0c 30 input#selectPlayers(type="text" v-model="newchallenge.to")
25d18342 31 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
ac8f441c 32 label(for="inputFen") FEN
9d58ef95 33 input#inputFen(type="text" v-model="newchallenge.fen")
b4d619d1 34 button(@click="newChallenge") {{ st.tr["Send challenge"] }}
9d58ef95 35 .row
9ca1e26b 36 .col-sm-12
602d6bef 37 button#newGame(onClick="doClick('modalNewgame')") {{ st.tr["New game"] }}
9d58ef95 38 .row
9ca1e26b 39 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
ed06d9e9
BA
40 div
41 .button-group
42 button(@click="(e) => setDisplay('c','live',e)" class="active")
602d6bef 43 | {{ st.tr["Live challenges"] }}
ed06d9e9 44 button(@click="(e) => setDisplay('c','corr',e)")
602d6bef 45 | {{ st.tr["Correspondance challenges"] }}
ed06d9e9
BA
46 ChallengeList(v-show="cdisplay=='live'"
47 :challenges="filterChallenges('live')" @click-challenge="clickChallenge")
48 ChallengeList(v-show="cdisplay=='corr'"
49 :challenges="filterChallenges('corr')" @click-challenge="clickChallenge")
50 #people
602d6bef 51 h3.text-center {{ st.tr["Who's there?"] }}
ed06d9e9 52 #players
9335d45b
BA
53 p(v-for="sid in Object.keys(people)" v-if="!!people[sid].name")
54 span {{ people[sid].name }}
ed06d9e9 55 button.player-action(
9335d45b
BA
56 v-if="people[sid].name != st.user.name"
57 @click="challOrWatch(sid, $event)"
ed06d9e9 58 )
9335d45b 59 | {{ st.tr[!!people[sid].gamer ? 'Playing' : 'Available'] }}
ed06d9e9
BA
60 p.anonymous @nonymous ({{ anonymousCount }})
61 #chat
ac8f441c 62 Chat(:newChat="newChat" @mychat="processChat")
ed06d9e9
BA
63 .clearer
64 div
65 .button-group
66 button(@click="(e) => setDisplay('g','live',e)" class="active")
602d6bef 67 | {{ st.tr["Live games"] }}
ed06d9e9 68 button(@click="(e) => setDisplay('g','corr',e)")
602d6bef 69 | {{ st.tr["Correspondance games"] }}
ed06d9e9
BA
70 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
71 @show-game="showGame")
72 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
73 @show-game="showGame")
625022fd
BA
74</template>
75
76<script>
5b020e73 77import { store } from "@/store";
9d58ef95
BA
78import { checkChallenge } from "@/data/challengeCheck";
79import { ArrayFun } from "@/utils/array";
03608482 80import { ajax } from "@/utils/ajax";
8418f0d7 81import params from "@/parameters";
4b0384fa 82import { getRandString, shuffle } from "@/utils/alea";
603b8a8b 83import Chat from "@/components/Chat.vue";
5b020e73
BA
84import GameList from "@/components/GameList.vue";
85import ChallengeList from "@/components/ChallengeList.vue";
967a2686 86import { GameStorage } from "@/utils/gameStorage";
602d6bef
BA
87import { processModalClick } from "@/utils/modalClick";
88
625022fd 89export default {
cf2343ce 90 name: "my-hall",
5b020e73 91 components: {
603b8a8b 92 Chat,
5b020e73
BA
93 GameList,
94 ChallengeList,
95 },
fb54f098
BA
96 data: function () {
97 return {
5b020e73 98 st: store.state,
6855163c
BA
99 cdisplay: "live", //or corr
100 pdisplay: "players", //or chat
fb54f098 101 gdisplay: "live",
6855163c 102 games: [],
b4d619d1 103 challenges: [],
dcd68c41 104 people: {}, //people in main hall
3d55deea 105 infoMessage: "",
9d58ef95 106 newchallenge: {
fb54f098 107 fen: "",
25d18342 108 vid: localStorage.getItem("vid") || "",
6fba6e0c 109 to: "", //name of challenged player (if any)
25d18342 110 timeControl: localStorage.getItem("timeControl") || "",
fb54f098 111 },
ac8f441c 112 newChat: "",
8418f0d7
BA
113 conn: null,
114 page: "",
115 tempId: "", //to distinguish several tabs
fb54f098
BA
116 };
117 },
fd7aea36
BA
118 watch: {
119 // st.variants changes only once, at loading from [] to [...]
120 "st.variants": function(variantArray) {
121 // Set potential challenges and games variant names:
122 this.challenges.forEach(c => {
123 if (c.vname == "")
124 c.vname = this.getVname(c.vid);
125 });
126 this.games.forEach(g => {
127 if (g.vname == "")
f41ce580 128 g.vname = this.getVname(g.vid);
fd7aea36
BA
129 });
130 },
131 },
b4d619d1 132 computed: {
ed06d9e9
BA
133 anonymousCount: function() {
134 let count = 0;
135 Object.values(this.people).forEach(p => { count += (!p.name ? 1 : 0); });
136 return count;
b4d619d1
BA
137 },
138 },
9d58ef95 139 created: function() {
4d64881e 140 // Always add myself to players' list
66d03f23 141 const my = this.st.user;
8418f0d7
BA
142 this.tempId = getRandString();
143 this.$set(this.people, my.sid, {id:my.id, name:my.name, tmpId: [this.tempId]});
3d55deea
BA
144 // Ask server for current corr games (all but mines)
145 ajax(
146 "/games",
147 "GET",
148 {uid: this.st.user.id, excluded: true},
149 response => {
150 this.games = this.games.concat(response.games.map(g => {
151 const type = this.classifyObject(g);
152 const vname = this.getVname(g.vid);
153 return Object.assign({}, g, {type: type, vname: vname});
154 }));
155 }
156 );
fe4c7e67 157 // Also ask for corr challenges (open + sent by/to me)
3d55deea
BA
158 ajax(
159 "/challenges",
160 "GET",
161 {uid: this.st.user.id},
162 response => {
163 // Gather all senders names, and then retrieve full identity:
164 // (TODO [perf]: some might be online...)
fe4c7e67
BA
165 let names = {};
166 response.challenges.forEach(c => {
167 if (c.uid != this.st.user.id)
168 names[c.uid] = ""; //unknwon for now
169 else if (!!c.target && c.target != this.st.user.id)
170 names[c.target] = "";
171 });
172 const addChallenges = (newChalls) => {
173 names[this.st.user.id] = this.st.user.name; //in case of
174 this.challenges = this.challenges.concat(
175 response.challenges.map(c => {
176 const from = {name: names[c.uid], id: c.uid}; //or just name
177 const type = this.classifyObject(c);
178 const vname = this.getVname(c.vid);
179 return Object.assign({},
180 {
181 type: type,
182 vname: vname,
183 from: from,
184 to: (!!c.target ? names[c.target] : ""),
185 },
186 c);
187 })
188 );
189 };
190 if (names !== {})
191 {
192 ajax("/users",
193 "GET",
194 { ids: Object.keys(names).join(",") },
195 response2 => {
196 response2.users.forEach(u => {names[u.id] = u.name});
197 addChallenges();
198 }
199 );
200 }
201 else
202 addChallenges();
3d55deea
BA
203 }
204 );
2ada153c 205 // 0.1] Ask server for room composition:
7b01e447 206 const funcPollClients = () => {
8418f0d7
BA
207 this.conn.send(JSON.stringify({code:"connect"}));
208 this.conn.send(JSON.stringify({code:"pollclients"}));
209 this.conn.send(JSON.stringify({code:"pollgamers"}));
4d64881e 210 };
8418f0d7
BA
211 // Initialize connection
212 this.page = this.$route.path;
213 const connexionString = params.socketUrl +
214 "/?sid=" + this.st.user.sid +
215 "&tmpId=" + this.tempId +
216 "&page=" + encodeURIComponent(this.page);
217 this.conn = new WebSocket(connexionString);
218 this.conn.onopen = funcPollClients;
219 this.conn.onmessage = this.socketMessageListener;
4d64881e 220 const socketCloseListener = () => {
8418f0d7
BA
221 this.conn = new WebSocket(connexionString);
222 this.conn.addEventListener('message', this.socketMessageListener);
223 this.conn.addEventListener('close', socketCloseListener);
4d64881e 224 };
8418f0d7 225 this.conn.onclose = socketCloseListener;
9d58ef95 226 },
25d18342 227 mounted: function() {
602d6bef
BA
228 [document.getElementById("infoDiv"),document.getElementById("newgameDiv")]
229 .forEach(elt => elt.addEventListener("click", processModalClick));
25d18342
BA
230 document.querySelectorAll("#predefinedTimeControls > button").forEach(
231 (b) => { b.addEventListener("click",
232 () => { this.newchallenge.timeControl = b.innerHTML; }
233 )}
234 );
235 },
8418f0d7
BA
236 beforeDestroy: function() {
237 this.conn.send(JSON.stringify({code:"disconnect",page:this.page}));
238 },
fb54f098 239 methods: {
a6bddfc6 240 // Helpers:
6855163c
BA
241 filterChallenges: function(type) {
242 return this.challenges.filter(c => c.type == type);
243 },
244 filterGames: function(type) {
a9b131f1 245 return this.games.filter(g => g.type == type);
6855163c 246 },
2ada153c 247 classifyObject: function(o) { //challenge or game
2ada153c 248 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
6855163c 249 },
2ada153c 250 showGame: function(g) {
5bd05dba 251 // NOTE: we are an observer, since only games I don't play are shown here
2ada153c 252 // ==> Moves sent by connected remote player(s) if live game
d9b86b16 253 let url = "/game/" + g.id;
2ada153c 254 if (g.type == "live")
dc284d90 255 url += "?rid=" + g.rid;
2ada153c 256 this.$router.push(url);
a6bddfc6 257 },
5bcc9b31
BA
258 setDisplay: function(letter, type, e) {
259 this[letter + "display"] = type;
260 e.target.classList.add("active");
261 if (!!e.target.previousElementSibling)
262 e.target.previousElementSibling.classList.remove("active");
263 else
264 e.target.nextElementSibling.classList.remove("active");
265 },
a6bddfc6 266 getVname: function(vid) {
f41ce580
BA
267 const variant = this.st.variants.find(v => v.id == vid);
268 // this.st.variants might be uninitialized (variant == null)
269 return (!!variant ? variant.name : "");
a6bddfc6 270 },
ac8f441c
BA
271 processChat: function(chat) {
272 // When received on server, this will trigger a "notifyRoom"
8418f0d7 273 this.conn.send(JSON.stringify({code:"newchat", chat: chat}));
ac8f441c 274 },
a6bddfc6
BA
275 sendSomethingTo: function(to, code, obj, warnDisconnected) {
276 const doSend = (code, obj, sid) => {
8418f0d7 277 this.conn.send(JSON.stringify(Object.assign(
a6bddfc6
BA
278 {code: code},
279 obj,
280 {target: sid}
281 )));
282 };
9335d45b 283 if (!to || (!to.sid && !to.name))
a6bddfc6 284 {
5ea8d113 285 // Open challenge: send to all connected players (me excepted)
dcd68c41
BA
286 Object.keys(this.people).forEach(sid => {
287 if (sid != this.st.user.sid)
288 doSend(code, obj, sid);
a6bddfc6
BA
289 });
290 }
9335d45b
BA
291 else
292 {
293 let targetSid = "";
294 if (!!to.sid)
295 targetSid = to.sid;
296 else
297 {
298 if (to.name == this.st.user.name)
299 return alert(this.st.tr["Cannot challenge self"]);
300 // Challenge with targeted players
301 targetSid =
302 Object.keys(this.people).find(sid => this.people[sid].name == to.name);
303 if (!targetSid)
304 {
305 if (!!warnDisconnected)
bc093771 306 alert(this.st.tr["Target is not connected"]);
9335d45b
BA
307 return false;
308 }
309 }
310 doSend(code, obj, targetSid);
311 }
5ea8d113 312 return true;
a6bddfc6
BA
313 },
314 // Messaging center:
9d58ef95
BA
315 socketMessageListener: function(msg) {
316 const data = JSON.parse(msg.data);
317 switch (data.code)
318 {
6d9f4315 319 case "duplicate":
8418f0d7
BA
320 this.conn.send(JSON.stringify({code:"duplicate", page:"/"}));
321 this.conn.send = () => {};
bc093771 322 alert(this.st.tr["This tab is now offline"]);
6d9f4315 323 break;
f4f4c03c 324 // 0.2] Receive clients list (just socket IDs)
81d9ce72 325 case "pollclients":
5a3da968 326 data.sockIds.forEach(sid => {
dcd68c41 327 this.$set(this.people, sid, {id:0, name:""});
ac8f441c 328 // Ask identity and challenges
8418f0d7
BA
329 this.conn.send(JSON.stringify({code:"askidentity", target:sid}));
330 this.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
5a3da968 331 });
ac8f441c
BA
332 break;
333 case "pollgamers":
334 // NOTE: we could make a difference between people in hall
335 // and gamers, but is it necessary?
336 data.sockIds.forEach(sid => {
9335d45b 337 this.$set(this.people, sid, {id:0, name:"", gamer:true});
8418f0d7 338 this.conn.send(JSON.stringify({code:"askidentity", target:sid}));
ac8f441c 339 });
cd0d7743 340 // Also ask current games to all playing peers (TODO: some design issue)
8418f0d7 341 this.conn.send(JSON.stringify({code:"askgames"}));
5a3da968 342 break;
81d9ce72 343 case "askidentity":
6855163c
BA
344 // Request for identification: reply if I'm not anonymous
345 if (this.st.user.id > 0)
346 {
8418f0d7 347 this.conn.send(JSON.stringify({code:"identity",
dcd68c41
BA
348 user: {
349 // NOTE: decompose to avoid revealing email
350 name: this.st.user.name,
351 sid: this.st.user.sid,
352 id: this.st.user.id,
353 },
354 target:data.from}));
6855163c 355 }
5a3da968 356 break;
dcd68c41 357 case "identity":
dcd68c41 358 this.$set(this.people, data.user.sid,
9335d45b
BA
359 {
360 id: data.user.id,
361 name: data.user.name,
362 gamer: this.people[data.user.sid].gamer,
363 });
dcd68c41 364 break;
dd75774d 365 case "askchallenge":
1efe1d79 366 {
6855163c 367 // Send my current live challenge (if any)
5ea8d113
BA
368 const cIdx = this.challenges.findIndex(c =>
369 c.from.sid == this.st.user.sid && c.type == "live");
dd75774d
BA
370 if (cIdx >= 0)
371 {
372 const c = this.challenges[cIdx];
a64d9122
BA
373 // TODO: code below requires "c.to" to have given his identity,
374 // but it can happen that the identity arrives later, which
375 // prevent him from receiving the challenge.
376 // ==> Filter later (when receiving challenge)
377// if (!!c.to)
378// {
379// // Only share targeted challenges to the targets:
380// const toSid = Object.keys(this.people).find(k =>
381// this.people[k].name == c.to);
382// if (toSid != data.from)
383// return;
384// }
dd75774d
BA
385 const myChallenge =
386 {
81d9ce72 387 // Minimal challenge informations: (from not required)
2ada153c 388 id: c.id,
81d9ce72
BA
389 to: c.to,
390 fen: c.fen,
391 vid: c.vid,
5ea8d113 392 timeControl: c.timeControl,
a64d9122 393 added: c.added,
dd75774d 394 };
8418f0d7 395 this.conn.send(JSON.stringify({code:"challenge",
42c15a75 396 chall:myChallenge, target:data.from}));
81d9ce72
BA
397 }
398 break;
1efe1d79 399 }
dd75774d
BA
400 case "challenge":
401 // Receive challenge from some player (+sid)
a64d9122
BA
402 // NOTE about next condition: see "askchallenge" case.
403 if (!data.chall.to || data.chall.to == this.st.user.name)
404 {
405 let newChall = data.chall;
406 newChall.type = this.classifyObject(data.chall);
407 newChall.from =
408 Object.assign({sid:data.from}, this.people[data.from]);
409 newChall.vname = this.getVname(newChall.vid);
410 this.challenges.push(newChall);
411 }
81d9ce72 412 break;
dd75774d 413 case "game":
1efe1d79 414 {
6855163c 415 // Receive game from some player (+sid)
6855163c 416 // NOTE: it may be correspondance (if newgame while we are connected)
b1ea2149
BA
417 // If duplicate found: select rid (remote ID) at random
418 let game = this.games.find(g => g.id == data.game.id);
a64d9122
BA
419 if (!!game)
420 {
421 if (Math.random() < 0.5)
422 game.rid = data.from;
423 }
b1ea2149 424 else
d9b86b16
BA
425 {
426 let newGame = data.game;
427 newGame.type = this.classifyObject(data.game);
a9b131f1 428 newGame.vname = this.getVname(data.game.vid);
d9b86b16 429 newGame.rid = data.from;
a64d9122
BA
430 if (!data.game.score)
431 newGame.score = "*";
d9b86b16
BA
432 this.games.push(newGame);
433 }
81d9ce72 434 break;
1efe1d79 435 }
9d58ef95 436 case "newgame":
5d04793e 437 // New game just started: data contain all information
66d03f23 438 if (this.classifyObject(data.gameInfo) == "live")
5d04793e 439 this.startNewGame(data.gameInfo);
5d04793e
BA
440 else
441 {
3d55deea 442 this.infoMessage = "New game started: " +
11667c79
BA
443 "<a href='#/game/" + data.gameInfo.id + "'>" +
444 "#/game/" + data.gameInfo.id + "</a>";
dce792f6
BA
445 let modalBox = document.getElementById("modalInfo");
446 modalBox.checked = true;
3d55deea 447 setTimeout(() => { modalBox.checked = false; }, 3000);
5d04793e 448 }
9d58ef95 449 break;
ac8f441c
BA
450 case "newchat":
451 this.newChat = data.chat;
452 break;
bb7dd7db 453 case "refusechallenge":
5bd05dba 454 ArrayFun.remove(this.challenges, c => c.id == data.cid);
602d6bef 455 alert(this.st.tr["Challenge declined"]);
bb7dd7db 456 break;
1efe1d79 457 case "deletechallenge":
1ba761c8 458 // NOTE: the challenge may be already removed
9d58ef95
BA
459 ArrayFun.remove(this.challenges, c => c.id == data.cid);
460 break;
b4d619d1 461 case "connect":
ac8f441c 462 case "gconnect":
9335d45b 463 this.$set(this.people, data.from, {name:"", id:0, gamer:data.code[0]=='g'});
8418f0d7 464 this.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
ac8f441c 465 if (data.code == "connect")
8418f0d7 466 this.conn.send(JSON.stringify({code:"askchallenge", target:data.from}));
ac8f441c 467 else
8418f0d7 468 this.conn.send(JSON.stringify({code:"askgame", target:data.from}));
9d58ef95 469 break;
b4d619d1 470 case "disconnect":
26f3a887 471 case "gdisconnect":
dcd68c41 472 this.$delete(this.people, data.from);
ac8f441c
BA
473 if (data.code == "disconnect")
474 {
475 // Also remove all challenges sent by this player:
476 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
477 }
478 else
479 {
480 // And all live games where he plays and no other opponent is online
481 ArrayFun.remove(this.games, g =>
482 g.type == "live" && (g.players.every(p => p.sid == data.from
483 || !this.people[p.sid])), "all");
484 }
9d58ef95
BA
485 break;
486 }
487 },
a6bddfc6 488 // Challenge lifecycle:
9335d45b
BA
489 tryChallenge: function(sid) {
490 if (this.people[sid].id == 0)
b4d619d1 491 return; //anonymous players cannot be challenged
9335d45b
BA
492 // TODO: SID is available, so we could use it instead of searching from name
493 this.newchallenge.to = this.people[sid].name;
b4d619d1 494 doClick("modalNewgame");
fb54f098 495 },
29ced362
BA
496 challOrWatch: function(sid) {
497 if (!this.people[sid].gamer)
dcd68c41 498 {
29ced362
BA
499 // Available, in Hall
500 this.tryChallenge(sid);
501 }
502 else
503 {
504 // Playing, in Game
505 this.showGame(this.games.find(
506 g => g.players.some(pl => pl.sid == sid || pl.uid == this.people[sid].id)));
507 }
dcd68c41 508 },
9d58ef95 509 newChallenge: async function() {
25d18342 510 if (this.newchallenge.vid == "")
602d6bef 511 return alert(this.st.tr["Please select a variant"]);
a64d9122
BA
512 if (!!this.newchallenge.to && this.newchallenge.to == this.st.user.name)
513 return alert(this.st.tr["Self-challenge is forbidden"]);
bb7dd7db 514 const vname = this.getVname(this.newchallenge.vid);
1efe1d79
BA
515 const vModule = await import("@/variants/" + vname + ".js");
516 window.V = vModule.VariantRules;
dcd68c41
BA
517 if (!!this.newchallenge.timeControl.match(/^[0-9]+$/))
518 this.newchallenge.timeControl += "+0"; //assume minutes, no increment
9d58ef95
BA
519 const error = checkChallenge(this.newchallenge);
520 if (!!error)
521 return alert(error);
2ada153c 522 const ctype = this.classifyObject(this.newchallenge);
098cd7f1 523 if (ctype == "corr" && this.st.user.id <= 0)
602d6bef 524 return alert(this.st.tr["Please log in to play correspondance games"]);
bb7dd7db 525 // NOTE: "from" information is not required here
a7808884 526 let chall = Object.assign({}, this.newchallenge);
2ada153c 527 const finishAddChallenge = (cid,warnDisconnected) => {
1efe1d79 528 chall.id = cid || "c" + getRandString();
2ada153c 529 // Send challenge to peers (if connected)
9335d45b 530 const isSent = this.sendSomethingTo({name:chall.to}, "challenge",
5ea8d113
BA
531 {chall:chall}, !!warnDisconnected);
532 if (!isSent)
533 return;
fe4c7e67 534 // Remove old challenge if any (only one at a time of a given type):
5ea8d113 535 const cIdx = this.challenges.findIndex(c =>
fe4c7e67 536 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) && c.type == ctype);
5ea8d113
BA
537 if (cIdx >= 0)
538 {
539 // Delete current challenge (will be replaced now)
9335d45b 540 this.sendSomethingTo({name:this.challenges[cIdx].to},
5ea8d113
BA
541 "deletechallenge", {cid:this.challenges[cIdx].id});
542 if (ctype == "corr")
543 {
544 ajax(
545 "/challenges",
546 "DELETE",
547 {id: this.challenges[cIdx].id}
548 );
549 }
550 this.challenges.splice(cIdx, 1);
551 }
552 // Add new challenge:
1efe1d79 553 chall.added = Date.now();
a9b131f1 554 // NOTE: vname and type are redundant (can be deduced from timeControl + vid)
bb7dd7db
BA
555 chall.type = ctype;
556 chall.vname = vname;
dcd68c41
BA
557 chall.from = { //decompose to avoid revealing email
558 sid: this.st.user.sid,
559 id: this.st.user.id,
560 name: this.st.user.name,
561 };
1efe1d79 562 this.challenges.push(chall);
a3ac374b 563 // Remember timeControl + vid for quicker further challenges:
25d18342
BA
564 localStorage.setItem("timeControl", chall.timeControl);
565 localStorage.setItem("vid", chall.vid);
b4d619d1
BA
566 document.getElementById("modalNewgame").checked = false;
567 };
1efe1d79
BA
568 if (ctype == "live")
569 {
570 // Live challenges have a random ID
2ada153c 571 finishAddChallenge(null, "warnDisconnected");
03608482 572 }
b4d619d1 573 else
03608482 574 {
b4d619d1 575 // Correspondance game: send challenge to server
03608482 576 ajax(
1efe1d79 577 "/challenges",
03608482 578 "POST",
bebcc8d4 579 { chall: chall },
1efe1d79 580 response => { finishAddChallenge(response.cid); }
03608482 581 );
9d58ef95 582 }
fb54f098 583 },
a6bddfc6 584 clickChallenge: function(c) {
485fccd5
BA
585 const myChallenge = (c.from.sid == this.st.user.sid //live
586 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
587 if (!myChallenge)
a6bddfc6 588 {
3d55deea 589 if (c.type == "corr" && this.st.user.id <= 0)
602d6bef 590 return alert(this.st.tr["Please log in to accept corr challenges"]);
a6bddfc6 591 c.accepted = true;
485fccd5 592 if (!!c.to) //c.to == this.st.user.name (connected)
a6bddfc6
BA
593 {
594 // TODO: if special FEN, show diagram after loading variant
595 c.accepted = confirm("Accept challenge?");
596 }
485fccd5 597 if (c.accepted)
36093eba 598 {
dcd68c41
BA
599 c.seat = { //again, avoid c.seat = st.user to not reveal email
600 sid: this.st.user.sid,
601 id: this.st.user.id,
602 name: this.st.user.name,
603 };
485fccd5
BA
604 this.launchGame(c);
605 }
606 else
607 {
8418f0d7 608 this.conn.send(JSON.stringify({
485fccd5
BA
609 code: "refusechallenge",
610 cid: c.id, target: c.from.sid}));
36093eba 611 }
9335d45b 612 this.sendSomethingTo(!!c.to ? {sid:c.from.sid} : null, "deletechallenge", {cid:c.id});
a6bddfc6 613 }
2be5d614 614 else //my challenge
485fccd5 615 {
2be5d614
BA
616 if (c.type == "corr")
617 {
618 ajax(
619 "/challenges",
620 "DELETE",
621 {id: c.id}
622 );
623 }
9335d45b 624 this.sendSomethingTo({name:c.to}, "deletechallenge", {cid:c.id});
485fccd5 625 }
5ea8d113 626 // In all cases, the challenge is consumed:
3d55deea 627 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
a6bddfc6 628 },
a64d9122 629 // NOTE: when launching game, the challenge is already being deleted
36093eba 630 launchGame: async function(c) {
a9b131f1 631 const vModule = await import("@/variants/" + c.vname + ".js");
a6bddfc6 632 window.V = vModule.VariantRules;
4b0384fa
BA
633 // These game informations will be sent to other players
634 const gameInfo =
a6bddfc6 635 {
11667c79 636 id: getRandString(),
a6bddfc6 637 fen: c.fen || V.GenRandInitFen(),
5d04793e 638 players: shuffle([c.from, c.seat]), //white then black
a6bddfc6 639 vid: c.vid,
f41ce580 640 vname: c.vname, //theoretically vid is enough, but much easier with vname
a9b131f1 641 timeControl: c.timeControl,
a6bddfc6 642 };
5ea8d113
BA
643 let oppsid = c.from.sid; //may not be defined if corr + offline opp
644 if (!oppsid)
8c564f46 645 {
5ea8d113 646 oppsid = Object.keys(this.people).find(sid =>
dcd68c41 647 this.people[sid].id == c.from.id);
8c564f46 648 }
411d23cd 649 const tryNotifyOpponent = () => {
5ea8d113 650 if (!!oppsid) //opponent is online
411d23cd 651 {
8418f0d7 652 this.conn.send(JSON.stringify({code:"newgame",
5ea8d113 653 gameInfo:gameInfo, target:oppsid, cid:c.id}));
411d23cd
BA
654 }
655 };
485fccd5 656 if (c.type == "live")
411d23cd 657 {
b1ea2149 658 // NOTE: in this case we are sure opponent is online
411d23cd 659 tryNotifyOpponent();
485fccd5 660 this.startNewGame(gameInfo);
411d23cd 661 }
485fccd5
BA
662 else //corr: game only on server
663 {
664 ajax(
665 "/games",
666 "POST",
2be5d614 667 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
411d23cd 668 response => {
11667c79 669 gameInfo.id = response.gameId;
411d23cd
BA
670 tryNotifyOpponent();
671 this.$router.push("/game/" + response.gameId);
672 }
485fccd5
BA
673 );
674 }
c6788ecf 675 // Send game info to everyone except opponent (and me)
5ea8d113 676 Object.keys(this.people).forEach(sid => {
b1ea2149 677 if (![this.st.user.sid,oppsid].includes(sid))
5ea8d113 678 {
8418f0d7 679 this.conn.send(JSON.stringify({code:"game",
5ea8d113
BA
680 game: { //minimal game info:
681 id: gameInfo.id,
b1ea2149 682 players: gameInfo.players,
5ea8d113
BA
683 vid: gameInfo.vid,
684 timeControl: gameInfo.timeControl,
685 },
686 target: sid}));
687 }
688 });
fb54f098 689 },
a9b131f1 690 // NOTE: for live games only (corr games start on the server)
42c15a75 691 startNewGame: function(gameInfo) {
25996aed
BA
692 const game = Object.assign({}, gameInfo, {
693 // (other) Game infos: constant
6d01bb17 694 fenStart: gameInfo.fen,
92a523d1 695 added: Date.now(),
25996aed 696 // Game state (including FEN): will be updated
967a2686 697 moves: [],
a9b131f1 698 clocks: [-1, -1], //-1 = unstarted
66d03f23 699 initime: [0, 0], //initialized later
967a2686 700 score: "*",
a7808884 701 });
967a2686 702 GameStorage.add(game);
7b626bdd
BA
703 if (this.st.settings.sound >= 1)
704 new Audio("/sounds/newgame.mp3").play().catch(err => {});
11667c79 705 this.$router.push("/game/" + gameInfo.id);
1efe1d79 706 },
fb54f098 707 },
85e5b5c1 708};
ccd4a2b7 709</script>
85e5b5c1 710
41c80bb6 711<style lang="sass" scoped>
5bcc9b31
BA
712.active
713 color: #42a983
9ca1e26b
BA
714#newGame
715 display: block
72ccbd67 716 margin: 10px auto 5px auto
ed06d9e9
BA
717#people
718 width: 100%
719#players
720 width: 50%
721 position: relative
722 float: left
723#chat
724 width: 50%
725 float: left
726 position: relative
727@media screen and (max-width: 767px)
728 #players, #chats
729 width: 100%
72ccbd67
BA
730#chat > .card
731 max-width: 100%
732 margin: 0;
733 border: none;
41c80bb6 734#players > p
ed06d9e9 735 margin-left: 5px
dcd68c41
BA
736.anonymous
737 font-style: italic
738button.player-action
41c80bb6 739 margin-left: 32px
85e5b5c1 740</style>