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