More balanced Shinobi according to Couch Tomato + Fables tests
[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 p.text-center(v-if="!!curChallToAccept.color")
19 | {{ st.tr["Your color:"] + " " + invColor(curChallToAccept.color) }}
20 .diagram(
21 v-if="!!curChallToAccept.fen"
22 v-html="tchallDiag"
23 )
24 .button-group#buttonsTchall(:style="tchallButtonsMargin()")
25 button.acceptBtn(@click="decisionChallenge(true)")
26 span {{ st.tr["Accept challenge?"] }}
27 button.refuseBtn(@click="decisionChallenge(false)")
28 span {{ st.tr["Refuse"] }}
29 input#modalNewgame.modal(
30 type="checkbox"
31 @change="cadenceFocusIfOpened($event)"
32 )
33 div#newgameDiv(
34 role="dialog"
35 data-checkbox="modalNewgame"
36 )
37 .card
38 label#closeNewgame.modal-close(for="modalNewgame")
39 div(@keyup.enter="issueNewChallenge()")
40 fieldset
41 label(for="selectVariant") {{ st.tr["Variant"] }} *
42 select#selectVariant(
43 @change="loadNewchallVariant(trySetNewchallDiag)"
44 v-model="newchallenge.vid"
45 )
46 option(
47 v-for="v in st.variants"
48 :value="v.id"
49 :selected="newchallenge.vid==v.id"
50 )
51 | {{ v.name }}
52 fieldset
53 label(for="cadence") {{ st.tr["Cadence"] }} *
54 div#predefinedCadences
55 button(type="button") 15+5
56 button(type="button") 45+30
57 button(type="button") 3d
58 button(type="button") 7d
59 input#cadence(
60 type="text"
61 v-model="newchallenge.cadence"
62 placeholder="5+0, 1h+30s, 5d ..."
63 )
64 fieldset
65 label(for="selectRandomLevel") {{ st.tr["Randomness"] }} *
66 select#selectRandomLevel(v-model="newchallenge.randomness")
67 option(value="0") {{ st.tr["Deterministic"] }}
68 option(value="1") {{ st.tr["Symmetric random"] }}
69 option(value="2") {{ st.tr["Asymmetric random"] }}
70 fieldset
71 label(for="memorizeChall") {{ st.tr["Memorize"] }}
72 input#memorizeChall(
73 type="checkbox"
74 v-model="newchallenge.memorize"
75 )
76 fieldset(v-if="st.user.id > 0")
77 label(for="selectPlayers") {{ st.tr["Play with"] }}
78 select#selectPlayersInList(
79 v-model="newchallenge.to"
80 @change="changeChallTarget()"
81 )
82 option(value="")
83 option(
84 v-for="p in Object.values(people)"
85 v-if="!!p.name"
86 :value="p.name"
87 )
88 | {{ p.name }}
89 input#selectPlayers(
90 type="text"
91 v-model="newchallenge.to"
92 )
93 fieldset(v-show="st.user.id > 0 && newchallenge.to.length > 0")
94 label(for="selectColor") {{ st.tr["Color"] }}
95 select#selectColor(v-model="newchallenge.color")
96 option(value='')
97 option(value='w') {{ st.tr["White"] }}
98 option(value='b') {{ st.tr["Black"] }}
99 br
100 input#inputFen(
101 placeholder="FEN"
102 @input="trySetNewchallDiag()"
103 type="text"
104 v-model="newchallenge.fen"
105 )
106 .diagram(v-html="newchallenge.diag")
107 button(@click="issueNewChallenge()") {{ st.tr["Send challenge"] }}
108 input#modalPeople.modal(
109 type="checkbox"
110 @click="toggleSocialColor()"
111 )
112 div#peopleWrap(
113 role="dialog"
114 data-checkbox="modalPeople"
115 )
116 .card
117 label.modal-close(for="modalPeople")
118 #people
119 #players
120 p(
121 v-for="sid in Object.keys(people)"
122 v-if="!!people[sid].name"
123 )
124 UserBio.user-bio(:uid="people[sid].id" :uname="people[sid].name")
125 button.player-action(
126 v-if="isGamer(sid)"
127 @click="watchGame(sid)"
128 )
129 | {{ st.tr["Observe"] }}
130 button.player-action(
131 v-else-if="st.user.sid != sid"
132 :class="{focused: isFocusedOnHall(sid)}"
133 @click="challenge(sid)"
134 )
135 | {{ st.tr["Challenge"] }}
136 p.anonymous @nonymous ({{ anonymousCount() }})
137 #chat
138 Chat(
139 ref="chatcomp"
140 @mychat="processChat"
141 :pastChats="[]"
142 )
143 .clearer
144 .row
145 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
146 .button-group
147 button#peopleBtn(onClick="window.doClick('modalPeople')")
148 | {{ st.tr["Who's there?"] }}
149 button(@click="showNewchallengeForm()")
150 | {{ st.tr["New game"] }}
151 .row(v-if="presetChalls.length > 0")
152 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
153 h4.text-center {{ st.tr["Preset challenges"] }}
154 table
155 thead
156 tr
157 th {{ st.tr["Variant"] }}
158 th {{ st.tr["Cadence"] }}
159 th {{ st.tr["Random?"] }}
160 th
161 tbody
162 tr(
163 v-for="pc in presetChalls"
164 @click="newChallFromPreset(pc)"
165 )
166 td {{ pc.vname }}
167 td {{ pc.cadence }}
168 td(:class="getRandomnessClass(pc)")
169 td.remove-preset(@click="removePresetChall($event, pc)")
170 img(src="/images/icons/delete.svg")
171 .row
172 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
173 div#div2
174 .button-group
175 button.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
176 | {{ st.tr["Live challenges"] }}
177 button.tabbtn#btnCcorr(@click="setDisplay('c','corr',$event)")
178 | {{ st.tr["Correspondence challenges"] }}
179 ChallengeList(
180 v-show="cdisplay=='live'"
181 :challenges="filterChallenges('live')"
182 @click-challenge="clickChallenge"
183 )
184 ChallengeList(
185 v-show="cdisplay=='corr'"
186 :challenges="filterChallenges('corr')"
187 @click-challenge="clickChallenge"
188 )
189 div#div3
190 .button-group
191 button.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
192 | {{ st.tr["Live games"] }}
193 button.tabbtn#btnGcorr(@click="setDisplay('g','corr',$event)")
194 | {{ st.tr["Correspondence games"] }}
195 GameList(
196 v-show="gdisplay=='live'"
197 :games="filterGames('live')"
198 :show-both="true"
199 @show-game="showGame"
200 )
201 div(v-show="gdisplay=='corr'")
202 GameList(
203 :games="filterGames('corr')"
204 :show-both="true"
205 @show-game="showGame"
206 )
207 button#loadMoreBtn(
208 v-if="hasMore"
209 @click="loadMoreCorr()"
210 )
211 | {{ st.tr["Load more"] }}
212 </template>
213
214 <script>
215 import { store } from "@/store";
216 import { checkChallenge } from "@/data/challengeCheck";
217 import { notify } from "@/utils/notifications";
218 import { ArrayFun } from "@/utils/array";
219 import { ajax } from "@/utils/ajax";
220 import params from "@/parameters";
221 import { getRandString, shuffle, randInt } from "@/utils/alea";
222 import { getDiagram } from "@/utils/printDiagram";
223 import Chat from "@/components/Chat.vue";
224 import UserBio from "@/components/UserBio.vue";
225 import GameList from "@/components/GameList.vue";
226 import ChallengeList from "@/components/ChallengeList.vue";
227 import { GameStorage } from "@/utils/gameStorage";
228 import { processModalClick } from "@/utils/modalClick";
229 export default {
230 name: "my-hall",
231 components: {
232 Chat,
233 UserBio,
234 GameList,
235 ChallengeList
236 },
237 data: function() {
238 return {
239 st: store.state,
240 cdisplay: "live", //or corr
241 gdisplay: "live",
242 // timestamp of last showed (oldest) corr game:
243 cursor: Number.MAX_SAFE_INTEGER,
244 // hasMore == TRUE: a priori there could be more games to load
245 hasMore: true,
246 games: [],
247 challenges: [],
248 people: {},
249 infoMessage: "",
250 newchallenge: {
251 fen: "",
252 vid: parseInt(localStorage.getItem("vid"), 10) || 0,
253 to: "", //name of challenged player (if any)
254 color: '',
255 cadence: localStorage.getItem("cadence") || "",
256 randomness:
257 // Warning: randomness can be 0, then !!randomness is false
258 (parseInt(localStorage.getItem("challRandomness"),10)+1 || 3) - 1,
259 // VariantRules object, stored to not interfere with
260 // diagrams of targetted challenges:
261 V: null,
262 vname: "",
263 diag: "", //visualizing FEN
264 memorize: false //put settings in localStorage
265 },
266 focus: true,
267 tchallDiag: "",
268 curChallToAccept: { from: {} },
269 presetChalls: JSON.parse(localStorage.getItem("presetChalls") || "[]"),
270 conn: null,
271 connexionString: "",
272 socketCloseListener: 0,
273 // Related to (killing of) self multi-connects:
274 newConnect: {}
275 };
276 },
277 watch: {
278 // st.variants changes only once, at loading from [] to [...]
279 "st.variants": function() {
280 // Set potential challenges and games variant names:
281 this.challenges.concat(this.games).forEach(o => {
282 if (!o.vname) o.vname = this.getVname(o.vid);
283 });
284 if (!this.newchallenge.V && this.newchallenge.vid > 0)
285 this.loadNewchallVariant();
286 },
287 $route: function(to, from) {
288 if (to.path != "/") this.cleanBeforeDestroy();
289 }
290 },
291 created: function() {
292 document.addEventListener('visibilitychange', this.visibilityChange);
293 window.addEventListener('focus', this.onFocus);
294 window.addEventListener('blur', this.onBlur);
295 window.addEventListener("beforeunload", this.cleanBeforeDestroy);
296 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
297 this.loadNewchallVariant();
298 const my = this.st.user;
299 const tmpId = getRandString();
300 this.$set(
301 this.people,
302 my.sid,
303 {
304 id: my.id,
305 name: my.name,
306 tmpIds: {
307 tmpId: { page: "/", focus: true }
308 }
309 }
310 );
311 const connectAndPoll = () => {
312 this.send("connect");
313 this.send("pollclientsandgamers");
314 if (!!this.$route.query["challenge"]) {
315 // Automatic challenge sending, for tournaments
316 this.loadNewchallVariant(
317 () => {
318 this.newchallenge = Object.assign(
319 this.newchallenge,
320 {
321 fen: "",
322 vid:
323 this.st.variants
324 .find(v => v.name == this.$route.query["variant"])
325 .id,
326 to: this.$route.query["challenge"],
327 color: this.$route.query["color"] || '',
328 cadence: this.$route.query["cadence"],
329 // Tournament: no randomness (TODO: for now at least)
330 randomness: 0,
331 memorize: false
332 }
333 );
334 window.doClick("modalNewgame");
335 //this.issueNewChallenge(); //NOTE: doesn't work yet.
336 },
337 this.$route.query["variant"]
338 );
339 }
340 };
341 // Initialize connection
342 this.connexionString =
343 params.socketUrl +
344 "/?sid=" + this.st.user.sid +
345 "&id=" + this.st.user.id +
346 "&tmpId=" + tmpId +
347 "&page=" +
348 // Hall: path is "/" (TODO: could be hard-coded as well)
349 encodeURIComponent(this.$route.path);
350 this.conn = new WebSocket(this.connexionString);
351 this.conn.onopen = connectAndPoll;
352 this.conn.addEventListener("message", this.socketMessageListener);
353 this.socketCloseListener = setInterval(
354 () => {
355 if (this.conn.readyState == 3) {
356 this.conn.removeEventListener("message", this.socketMessageListener);
357 this.conn = new WebSocket(this.connexionString);
358 this.conn.addEventListener("message", this.socketMessageListener);
359 }
360 },
361 1000
362 );
363 },
364 mounted: function() {
365 document.getElementById("peopleWrap")
366 .addEventListener("click", (e) => {
367 processModalClick(e, () => {
368 this.toggleSocialColor("close")
369 });
370 });
371 ["infoDiv", "newgameDiv"].forEach(eltName => {
372 document.getElementById(eltName)
373 .addEventListener("click", processModalClick);
374 });
375 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
376 b.addEventListener("click", () => {
377 this.newchallenge.cadence = b.innerHTML;
378 });
379 });
380 const dispCorr = this.$route.query["disp"];
381 const showCtype =
382 dispCorr || localStorage.getItem("type-challenges") || "live";
383 const showGtype =
384 dispCorr || localStorage.getItem("type-games") || "live";
385 this.setDisplay('c', showCtype);
386 this.setDisplay('g', showGtype);
387 // Ask server for current corr games (all but mines)
388 this.loadMoreCorr();
389 // Also ask for corr challenges (open + sent by/to me)
390 // List them all, because they are not supposed to be that many (TODO?)
391 ajax(
392 "/challenges",
393 "GET",
394 {
395 data: { uid: this.st.user.id },
396 success: (response) => {
397 if (
398 response.challenges.length > 0 &&
399 this.challenges.length == 0 &&
400 this.cdisplay == "live"
401 ) {
402 document
403 .getElementById("btnCcorr")
404 .classList.add("somethingnew");
405 }
406 // Gather all senders names, and then retrieve full identity:
407 // (TODO [perf]: some might be online...)
408 let names = {};
409 response.challenges.forEach(c => {
410 if (c.uid != this.st.user.id) names[c.uid] = "";
411 else if (!!c.target && c.target != this.st.user.id)
412 names[c.target] = "";
413 });
414 const addChallenges = () => {
415 names[this.st.user.id] = this.st.user.name; //in case of
416 this.challenges = this.challenges.concat(
417 response.challenges.map(c => {
418 const from = { name: names[c.uid], id: c.uid }; //or just name
419 const type = this.classifyObject(c);
420 const vname = this.getVname(c.vid);
421 return Object.assign(
422 {},
423 {
424 type: type,
425 vname: vname,
426 from: from,
427 to: c.target ? names[c.target] : ""
428 },
429 c
430 );
431 })
432 );
433 };
434 if (Object.keys(names).length > 0) {
435 ajax(
436 "/users",
437 "GET",
438 {
439 data: { ids: Object.keys(names).join(",") },
440 success: (response2) => {
441 response2.users.forEach(u => {
442 names[u.id] = u.name;
443 });
444 addChallenges();
445 }
446 }
447 );
448 }
449 else addChallenges();
450 }
451 }
452 );
453 },
454 beforeDestroy: function() {
455 this.cleanBeforeDestroy();
456 },
457 methods: {
458 cleanBeforeDestroy: function() {
459 clearInterval(this.socketCloseListener);
460 document.removeEventListener('visibilitychange', this.visibilityChange);
461 window.removeEventListener('focus', this.onFocus);
462 window.removeEventListener('blur', this.onBlur);
463 window.removeEventListener("beforeunload", this.cleanBeforeDestroy);
464 this.conn.removeEventListener("message", this.socketMessageListener);
465 this.send("disconnect");
466 this.conn = null;
467 },
468 getRandomnessClass: function(pc) {
469 return {
470 ["random-" + pc.randomness]: true
471 };
472 },
473 anonymousCount: function() {
474 let count = 0;
475 Object.values(this.people).forEach(p => {
476 // Do not cound people who did not send their identity yet:
477 count += (!p.name && p.id === 0) ? 1 : 0;
478 });
479 return count;
480 },
481 visibilityChange: function() {
482 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
483 this.focus = (document.visibilityState == "visible");
484 this.send(this.focus ? "getfocus" : "losefocus");
485 },
486 onFocus: function() {
487 this.focus = true;
488 this.send("getfocus");
489 },
490 onBlur: function() {
491 this.focus = false;
492 this.send("losefocus");
493 },
494 invColor: function(c) {
495 if (c == 'w') return this.st.tr["Black"];
496 return this.tr.tr["White"];
497 },
498 partialResetNewchallenge: function() {
499 // Reset potential target and custom FEN:
500 this.newchallenge.to = "";
501 this.newchallenge.color = '';
502 this.newchallenge.fen = "";
503 this.newchallenge.diag = "";
504 this.newchallenge.memorize = false;
505 },
506 showNewchallengeForm: function() {
507 this.partialResetNewchallenge();
508 window.doClick("modalNewgame");
509 },
510 addPresetChall: function(chall) {
511 // Add only if not already existing:
512 if (this.presetChalls.some(c =>
513 c.vid == chall.vid &&
514 c.cadence == chall.cadence &&
515 c.randomness == chall.randomness
516 )) {
517 return;
518 }
519 const L = this.presetChalls.length;
520 this.presetChalls.push({
521 index: L,
522 vid: chall.vid,
523 vname: chall.vname, //redundant, but easier
524 cadence: chall.cadence,
525 randomness: chall.randomness
526 });
527 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
528 },
529 removePresetChall: function(e, pchall) {
530 e.stopPropagation();
531 const pchallIdx =
532 this.presetChalls.findIndex(pc => pc.index == pchall.index);
533 this.presetChalls.splice(pchallIdx, 1);
534 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
535 },
536 tchallButtonsMargin: function() {
537 if (!!this.curChallToAccept.fen) return { "margin-top": "10px" };
538 return {};
539 },
540 changeChallTarget: function() {
541 if (!this.newchallenge.to) {
542 // Reset potential FEN + diagram
543 this.newchallenge.fen = "";
544 this.newchallenge.color = '';
545 this.newchallenge.diag = "";
546 }
547 },
548 cadenceFocusIfOpened: function() {
549 if (event.target.checked)
550 document.getElementById("cadence").focus();
551 },
552 send: function(code, obj) {
553 if (!!this.conn && this.conn.readyState == 1) {
554 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
555 }
556 },
557 getVname: function(vid) {
558 const variant = this.st.variants.find(v => v.id == vid);
559 // this.st.variants might be uninitialized (variant == null)
560 return variant ? variant.name : "";
561 },
562 filterChallenges: function(type) {
563 return this.challenges.filter(c => c.type == type);
564 },
565 filterGames: function(type) {
566 return this.games.filter(g => g.type == type);
567 },
568 // o: challenge or game
569 classifyObject: function(o) {
570 // No imported games here
571 return (o.cadence.indexOf("d") >= 0 ? "corr" : "live");
572 },
573 setDisplay: function(letter, type, e) {
574 this[letter + "display"] = type;
575 localStorage.setItem(
576 "type-" + (letter == "c" ? "challenges" : "games"),
577 type
578 );
579 let elt = e
580 ? e.target
581 : document.getElementById("btn" + letter.toUpperCase() + type);
582 elt.classList.add("active");
583 elt.classList.remove("somethingnew"); //in case of
584 if (!!elt.previousElementSibling)
585 elt.previousElementSibling.classList.remove("active");
586 else elt.nextElementSibling.classList.remove("active");
587 },
588 isGamer: function(sid) {
589 return Object.values(this.people[sid].tmpIds)
590 .some(v => v.focus && v.page.indexOf("/game/") >= 0);
591 },
592 isFocusedOnHall: function(sid) {
593 return (
594 // This is meant to challenge people, thus the next 2 conditions:
595 this.st.user.id > 0 &&
596 sid != this.st.user.sid &&
597 Object.values(this.people[sid].tmpIds)
598 .some(v => v.focus && v.page == "/")
599 );
600 },
601 challenge: function(sid) {
602 this.partialResetNewchallenge();
603 // Available, in Hall
604 this.newchallenge.to = this.people[sid].name;
605 // TODO: also store target sid to not re-search for it
606 document.getElementById("modalPeople").checked = false;
607 window.doClick("modalNewgame");
608 },
609 watchGame: function(sid) {
610 // In some game, maybe playing maybe not: show a random one
611 let gids = [];
612 Object.values(this.people[sid].tmpIds).forEach(v => {
613 if (v.focus) {
614 const matchGid = v.page.match(/[a-zA-Z0-9]+$/);
615 if (!!matchGid) gids.push(matchGid[0]);
616 }
617 });
618 const gid = gids[Math.floor(Math.random() * gids.length)];
619 window.open("/#/game/" + gid, "_blank");
620 },
621 showGame: function(g) {
622 // NOTE: we are an observer, since only games I don't play are shown here
623 // ==> Moves sent by connected remote player(s) if live game
624 window.open("/#/game/" + g.id, "_blank");
625 },
626 toggleSocialColor: function(action) {
627 if (!action && document.getElementById("modalPeople").checked)
628 document.getElementById("inputChat").focus();
629 else
630 document.getElementById("peopleBtn").classList.remove("somethingnew");
631 },
632 processChat: function(chat) {
633 this.send("newchat", { data: chat });
634 },
635 getOppsid: function(c) {
636 let oppsid = c.from.sid; //may not be defined if corr + offline opp
637 if (!oppsid) {
638 oppsid = Object.keys(this.people).find(
639 sid => this.people[sid].id == c.from.id
640 );
641 }
642 return oppsid;
643 },
644 // Messaging center:
645 socketMessageListener: function(msg) {
646 if (!this.conn) return;
647 const data = JSON.parse(msg.data);
648 switch (data.code) {
649 case "pollclientsandgamers": {
650 // TODO: shuffling and random filtering on server,
651 // if the room is really crowded.
652 Object.keys(data.sockIds).forEach(sid => {
653 if (sid != this.st.user.sid) {
654 // Pick a target tmpId (+page) at random:
655 const pt = Object.values(data.sockIds[sid]);
656 const randPage = pt[randInt(pt.length)].page;
657 this.send(
658 "askidentity",
659 {
660 target: sid,
661 page: randPage
662 }
663 );
664 }
665 if (!this.people[sid])
666 // Do not set name or id: identity unknown yet
667 this.people[sid] = { tmpIds: data.sockIds[sid] };
668 else
669 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
670 if (Object.values(data.sockIds[sid]).some(v => v.page == "/"))
671 // Peer is in Hall
672 this.send("askchallenges", { target: sid });
673 Object.values(data.sockIds[sid]).forEach(v => {
674 if (
675 v.page.indexOf("/game/") >= 0 &&
676 !v.page.match(/\/[0-9]+$/)
677 ) {
678 // Peer is in Game: ask only if live game
679 this.send("askgame", { target: sid, page: v.page });
680 }
681 });
682 });
683 break;
684 }
685 case "connect":
686 case "gconnect": {
687 const page = data.page || "/";
688 if (data.code == "connect") {
689 // Ask challenges only on first connexion:
690 if (!this.people[data.from[0]])
691 this.send("askchallenges", { target: data.from[0] });
692 }
693 // Ask game only if live:
694 else if (!page.match(/\/[0-9]+$/))
695 this.send("askgame", { target: data.from[0], page: page });
696 if (!this.people[data.from[0]]) {
697 this.$set(
698 this.people,
699 data.from[0],
700 {
701 tmpIds: {
702 [data.from[1]]: { page: page, focus: true }
703 }
704 }
705 );
706 // For self multi-connects tests:
707 this.newConnect[data.from[0]] = true;
708 this.send("askidentity", { target: data.from[0], page: page });
709 }
710 else {
711 this.people[data.from[0]].tmpIds[data.from[1]] =
712 { page: page, focus: true };
713 this.$forceUpdate(); //TODO: shouldn't be required
714 }
715 break;
716 }
717 case "disconnect":
718 case "gdisconnect": {
719 // If the user reloads the page twice very quickly
720 // (experienced with Firefox), the first reload won't have time to
721 // connect but will trigger a "close" event anyway.
722 // ==> Next check is required.
723 if (!this.people[data.from[0]]) return;
724 delete this.people[data.from[0]].tmpIds[data.from[1]];
725 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
726 this.$delete(this.people, data.from[0]);
727 else this.$forceUpdate(); //TODO: shouldn't be required
728 if (data.code == "disconnect") {
729 // Remove the live challenges sent by this player, if
730 // he isn't connected on another tab:
731 if (
732 !this.people[data.from[0]] ||
733 Object.values(this.people[data.from[0]].tmpIds)
734 .every(v => v.page != "/")
735 ) {
736 ArrayFun.remove(
737 this.challenges,
738 c => c.type == "live" && c.from.sid == data.from[0],
739 "all"
740 );
741 }
742 }
743 else {
744 // Remove the matching live game if now unreachable
745 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
746 // Corr games are always reachable:
747 if (!gid.match(/^[0-9]+$/)) {
748 // Live games are reachable if someone is on the game page
749 if (Object.values(this.people).every(p =>
750 Object.values(p.tmpIds).every(v => v.page != data.page))
751 ) {
752 ArrayFun.remove(this.games, g => g.id == gid);
753 }
754 }
755 }
756 break;
757 }
758 case "getfocus": {
759 let player = this.people[data.from[0]];
760 // If user reload a page, focus may arrive earlier than connect
761 if (!!player) {
762 player.tmpIds[data.from[1]].focus = true;
763 this.$forceUpdate(); //TODO: shouldn't be required
764 }
765 break;
766 }
767 case "losefocus": {
768 let player = this.people[data.from[0]];
769 if (!!player) {
770 player.tmpIds[data.from[1]].focus = false;
771 this.$forceUpdate(); //TODO: shouldn't be required
772 }
773 break;
774 }
775 case "askidentity": {
776 // Request for identification
777 const me = {
778 // Decompose to avoid revealing email
779 name: this.st.user.name,
780 sid: this.st.user.sid,
781 id: this.st.user.id
782 };
783 this.send("identity", { data: me, target: data.from });
784 break;
785 }
786 case "identity": {
787 const user = data.data;
788 let player = this.people[user.sid];
789 // player.tmpIds is already set
790 player.id = user.id;
791 player.name = user.name;
792 // TODO: this.$set(people, ...) fails. So forceUpdate.
793 // But this shouldn't be like that!
794 this.$forceUpdate();
795 // If I multi-connect, kill current connexion if no mark (I'm older)
796 if (this.newConnect[user.sid]) {
797 delete this.newConnect[user.sid];
798 if (
799 user.id > 0 &&
800 user.id == this.st.user.id &&
801 user.sid != this.st.user.sid
802 ) {
803 // I logged in elsewhere:
804 this.cleanBeforeDestroy();
805 alert(this.st.tr["New connexion detected: tab now offline"]);
806 }
807 }
808 break;
809 }
810 case "askchallenges": {
811 // Send my current live challenges (if any)
812 const myChallenges = this.challenges
813 .filter(c =>
814 c.from.sid == this.st.user.sid && c.type == "live"
815 )
816 .map(c => {
817 // NOTE: in principle, should only send targeted challenge to the
818 // target. But we may not know yet the identity of the target
819 // (just name), so can't decide if data.from is the target.
820 return {
821 id: c.id,
822 from: this.st.user.sid,
823 to: c.to,
824 randomness: c.randomness,
825 fen: c.fen,
826 vid: c.vid,
827 cadence: c.cadence,
828 added: c.added
829 };
830 });
831 if (myChallenges.length > 0)
832 this.send("challenges", { data: myChallenges, target: data.from });
833 break;
834 }
835 case "challenges": //after "askchallenges"
836 data.data.forEach(this.addChallenge);
837 break;
838 case "newchallenge":
839 this.addChallenge(data.data);
840 break;
841 case "refusechallenge": {
842 const cid = data.data;
843 ArrayFun.remove(this.challenges, c => c.id == cid);
844 alert(this.st.tr["Challenge declined"]);
845 break;
846 }
847 case "deletechallenge_s": {
848 // NOTE: the challenge(s) may be already removed
849 const cref = data.data;
850 if (!!cref.cid)
851 ArrayFun.remove(this.challenges, c => c.id == cref.cid);
852 else if (!!cref.sids) {
853 cref.sids.forEach(s => {
854 ArrayFun.remove(
855 this.challenges,
856 c => c.type == "live" && c.from.sid == s,
857 "all"
858 );
859 });
860 }
861 break;
862 }
863 case "game": // Individual request
864 case "newgame": {
865 const game = data.data;
866 // Ignore games where I play (will go in MyGames page),
867 // and also games that I already received.
868 if (
869 this.games.findIndex(g => g.id == game.id) == -1 &&
870 game.players.every(p => {
871 return (
872 p.sid != this.st.user.sid &&
873 (p.id == 0 || p.id != this.st.user.id)
874 );
875 })
876 ) {
877 let newGame = game;
878 newGame.type = this.classifyObject(game);
879 newGame.vname = this.getVname(game.vid);
880 if (!game.score)
881 // New game from Hall
882 newGame.score = "*";
883 this.games.push(newGame);
884 if (
885 newGame.score == '*' &&
886 (newGame.type == "live" && this.gdisplay == "corr") ||
887 (newGame.type == "corr" && this.gdisplay == "live")
888 ) {
889 document
890 .getElementById("btnG" + newGame.type)
891 .classList.add("somethingnew");
892 }
893 }
894 break;
895 }
896 case "result": {
897 let g = this.games.find(g => g.id == data.gid);
898 if (!!g) g.score = data.score;
899 break;
900 }
901 case "startgame": {
902 // New game just started, I'm involved
903 const gameInfo = data.data;
904 if (this.classifyObject(gameInfo) == "live")
905 this.startNewGame(gameInfo);
906 else {
907 this.infoMessage =
908 this.st.tr["New correspondence game:"] + " " +
909 "<a href='#/game/" + gameInfo.id + "'>" +
910 "#/game/" + gameInfo.id + "</a>";
911 document.getElementById("modalInfo").checked = true;
912 }
913 break;
914 }
915 case "newchat":
916 this.$refs["chatcomp"].newChat(data.data);
917 if (!document.getElementById("modalPeople").checked)
918 document.getElementById("peopleBtn").classList.add("somethingnew");
919 break;
920 }
921 },
922 loadMoreCorr: function() {
923 ajax(
924 "/observedgames",
925 "GET",
926 {
927 data: {
928 uid: this.st.user.id,
929 cursor: this.cursor
930 },
931 success: (res) => {
932 const L = res.games.length;
933 if (L > 0) {
934 if (
935 this.cursor == Number.MAX_SAFE_INTEGER &&
936 this.games.length == 0 &&
937 this.gdisplay == "live" &&
938 res.games.some(g => g.score == '*')
939 ) {
940 // First loading: show indicators
941 document
942 .getElementById("btnGcorr")
943 .classList.add("somethingnew");
944 }
945 this.cursor = res.games[L - 1].created;
946 let moreGames = res.games.map(g => {
947 const vname = this.getVname(g.vid);
948 return Object.assign(
949 {},
950 g,
951 {
952 type: "corr",
953 vname: vname
954 }
955 );
956 });
957 this.games = this.games.concat(moreGames);
958 }
959 else this.hasMore = false;
960 }
961 }
962 );
963 },
964 // Challenge lifecycle:
965 addChallenge: function(chall) {
966 // NOTE about next condition: see "askchallenges" case.
967 if (
968 !chall.to ||
969 (this.people[chall.from].id > 0 &&
970 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
971 ) {
972 let newChall = Object.assign({}, chall);
973 newChall.type = this.classifyObject(chall);
974 newChall.randomness = chall.randomness;
975 newChall.added = Date.now();
976 let fromValues = Object.assign({}, this.people[chall.from]);
977 delete fromValues["pages"]; //irrelevant in this context
978 newChall.from = Object.assign({ sid: chall.from }, fromValues);
979 newChall.vname = this.getVname(newChall.vid);
980 this.challenges.push(newChall);
981 if (
982 (newChall.type == "live" && this.cdisplay == "corr") ||
983 (newChall.type == "corr" && this.cdisplay == "live")
984 ) {
985 document
986 .getElementById("btnC" + newChall.type)
987 .classList.add("somethingnew");
988 }
989 if (!!chall.to && chall.to == this.st.user.name) {
990 notify(
991 "New challenge",
992 // fromValues.name should exist since the player is online, but
993 // let's consider there is some chance that the challenge arrives
994 // right after we connected and before receiving the poll result:
995 { body: "from " + (fromValues.name || "@nonymous") }
996 );
997 }
998 }
999 },
1000 loadNewchallVariant: async function(cb, vname) {
1001 vname = vname || this.getVname(this.newchallenge.vid);
1002 await import("@/variants/" + vname + ".js")
1003 .then((vModule) => {
1004 window.V = vModule[vname + "Rules"];
1005 this.newchallenge.V = window.V;
1006 this.newchallenge.vname = vname;
1007 if (!!cb) cb();
1008 });
1009 },
1010 trySetNewchallDiag: function() {
1011 if (!this.newchallenge.fen) {
1012 this.newchallenge.diag = "";
1013 return;
1014 }
1015 // If vid > 0 then the variant is loaded (function above):
1016 window.V = this.newchallenge.V;
1017 if (
1018 this.newchallenge.vid > 0 &&
1019 !!this.newchallenge.fen &&
1020 V.IsGoodFen(this.newchallenge.fen)
1021 ) {
1022 const parsedFen = V.ParseFen(this.newchallenge.fen);
1023 this.newchallenge.diag = getDiagram({
1024 position: parsedFen.position
1025 //,orientation: parsedFen.turn
1026 });
1027 }
1028 else this.newchallenge.diag = "";
1029 },
1030 newChallFromPreset(pchall) {
1031 this.partialResetNewchallenge();
1032 this.newchallenge.vid = pchall.vid;
1033 this.newchallenge.cadence = pchall.cadence;
1034 this.newchallenge.randomness = pchall.randomness;
1035 this.loadNewchallVariant(this.issueNewChallenge);
1036 },
1037 issueNewChallenge: async function() {
1038 if (!!(this.newchallenge.cadence.match(/^[0-9]+$/)))
1039 this.newchallenge.cadence += "+0"; //assume minutes, no increment
1040 const ctype = this.classifyObject(this.newchallenge);
1041 // TODO: cadence still unchecked so ctype could be wrong...
1042 let error = "";
1043 if (!this.newchallenge.vid)
1044 error = this.st.tr["Please select a variant"];
1045 else if (ctype == "corr" && this.st.user.id <= 0)
1046 error = this.st.tr["Please log in to play correspondence games"];
1047 else if (!this.newchallenge.to && !!this.newchallenge.color)
1048 error = this.st.tr["Color option only for targeted challenge"];
1049 else if (!!this.newchallenge.to) {
1050 if (this.newchallenge.to == this.st.user.name)
1051 error = this.st.tr["Self-challenge is forbidden"];
1052 else if (
1053 ctype == "live" &&
1054 Object.values(this.people).every(p => p.name != this.newchallenge.to)
1055 ) {
1056 error = this.newchallenge.to + " " + this.st.tr["is not online"];
1057 }
1058 if (
1059 !!this.newchallenge.color &&
1060 !['w', 'b'].includes(this.newchallenge.color)
1061 ) {
1062 error = this.st.tr["Wrong color"];
1063 }
1064 }
1065 if (!!error) {
1066 alert(error);
1067 return;
1068 }
1069 window.V = this.newchallenge.V;
1070 error = checkChallenge(this.newchallenge);
1071 if (error) {
1072 alert(error);
1073 return;
1074 }
1075 // NOTE: "from" information is not required here
1076 let chall = Object.assign({}, this.newchallenge);
1077 // Add only if not already issued (not counting FEN):
1078 if (this.challenges.some(c =>
1079 (
1080 c.from.sid == this.st.user.sid ||
1081 (c.from.id > 0 && c.from.id == this.st.user.id)
1082 )
1083 &&
1084 (
1085 (!c.to && !chall.to) ||
1086 c.to == chall.to
1087 )
1088 &&
1089 c.vid == chall.vid &&
1090 c.cadence == chall.cadence &&
1091 c.randomness == chall.randomness
1092 )) {
1093 alert(this.st.tr["Challenge already exists"]);
1094 return;
1095 }
1096 if (this.newchallenge.memorize) this.addPresetChall(this.newchallenge);
1097 delete chall["V"];
1098 delete chall["diag"];
1099 const finishAddChallenge = cid => {
1100 chall.id = cid || "c" + getRandString();
1101 const MAX_ALLOWED_CHALLS = 3;
1102 // Remove oldest challenge if 3 found: only 3 at a time of a given type
1103 let countMyChalls = 0;
1104 let challToDelIdx = 0;
1105 let oldestAdded = Number.MAX_SAFE_INTEGER;
1106 for (let i=0; i<this.challenges.length; i++) {
1107 const c = this.challenges[i];
1108 if (
1109 c.type == ctype &&
1110 (
1111 c.from.sid == this.st.user.sid ||
1112 (c.from.id > 0 && c.from.id == this.st.user.id)
1113 )
1114 ) {
1115 countMyChalls++;
1116 if (c.added < oldestAdded) {
1117 challToDelIdx = i;
1118 oldestAdded = c.added;
1119 }
1120 }
1121 }
1122 if (countMyChalls >= MAX_ALLOWED_CHALLS) {
1123 this.send(
1124 "deletechallenge_s",
1125 { data: { cid: this.challenges[challToDelIdx].id } }
1126 );
1127 if (ctype == "corr") {
1128 ajax(
1129 "/challenges",
1130 "DELETE",
1131 { data: { id: this.challenges[challToDelIdx].id } }
1132 );
1133 }
1134 this.challenges.splice(challToDelIdx, 1);
1135 }
1136 this.send("newchallenge", {
1137 data: Object.assign(
1138 // Temporarily add sender infos to display challenge on Discord.
1139 { from: this.st.user.sid, sender: this.st.user.name }, chall)
1140 });
1141 // Add new challenge:
1142 chall.from = {
1143 sid: this.st.user.sid,
1144 id: this.st.user.id,
1145 name: this.st.user.name
1146 };
1147 chall.added = Date.now();
1148 // NOTE: vname and type are redundant (deduced from cadence + vid)
1149 chall.type = ctype;
1150 chall.vname = this.newchallenge.vname;
1151 this.challenges.push(chall);
1152 // Remember cadence + vid for quicker further challenges:
1153 localStorage.setItem("cadence", chall.cadence);
1154 localStorage.setItem("vid", chall.vid);
1155 localStorage.setItem("challRandomness", chall.randomness);
1156 document.getElementById("modalNewgame").checked = false;
1157 // Show the challenge if not on current display
1158 if (
1159 (ctype == "live" && this.cdisplay == "corr") ||
1160 (ctype == "corr" && this.cdisplay == "live")
1161 ) {
1162 this.setDisplay('c', ctype);
1163 }
1164 };
1165 if (ctype == "live") {
1166 // Live challenges have a random ID
1167 finishAddChallenge(null);
1168 }
1169 else {
1170 // Correspondence game: send challenge to server
1171 ajax(
1172 "/challenges",
1173 "POST",
1174 {
1175 data: { chall: chall },
1176 success: (response) => {
1177 finishAddChallenge(response.id);
1178 }
1179 }
1180 );
1181 }
1182 },
1183 // Callback function after a diagram was showed to accept
1184 // or refuse targetted challenge:
1185 decisionChallenge: function(accepted) {
1186 this.curChallToAccept.accepted = accepted;
1187 this.finishProcessingChallenge(this.curChallToAccept);
1188 document.getElementById("modalAccept").checked = false;
1189 },
1190 finishProcessingChallenge: function(c) {
1191 if (c.accepted) {
1192 c.seat = {
1193 sid: this.st.user.sid,
1194 id: this.st.user.id,
1195 name: this.st.user.name
1196 };
1197 this.launchGame(c);
1198 if (c.type == "live") {
1199 // Remove all live challenges of both players
1200 this.send(
1201 "deletechallenge_s",
1202 { data: { sids: [c.from.sid, c.seat.sid] } }
1203 );
1204 }
1205 else
1206 // Corr challenge: just remove the challenge
1207 this.send("deletechallenge_s", { data: { cid: c.id } });
1208 }
1209 else {
1210 const oppsid = this.getOppsid(c);
1211 if (!!oppsid)
1212 this.send("refusechallenge", { data: c.id, target: oppsid });
1213 if (c.type == "corr") {
1214 ajax(
1215 "/challenges",
1216 "DELETE",
1217 { data: { id: c.id } }
1218 );
1219 }
1220 this.send("deletechallenge_s", { data: { cid: c.id } });
1221 }
1222 },
1223 // TODO: if several players click same challenge at the same time: problem
1224 clickChallenge: async function(c) {
1225 const myChallenge =
1226 c.from.sid == this.st.user.sid || //live
1227 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
1228 if (!myChallenge) {
1229 if (c.type == "corr" && this.st.user.id <= 0) {
1230 alert(this.st.tr["Please log in to accept corr challenges"]);
1231 return;
1232 }
1233 else {
1234 c.accepted = true;
1235 await import("@/variants/" + c.vname + ".js")
1236 .then((vModule) => {
1237 window.V = vModule[c.vname + "Rules"];
1238 if (!!c.to) {
1239 // c.to == this.st.user.name (connected)
1240 if (!!c.fen) {
1241 const parsedFen = V.ParseFen(c.fen);
1242 this.tchallDiag = getDiagram({
1243 position: parsedFen.position,
1244 orientation: parsedFen.turn
1245 });
1246 }
1247 this.curChallToAccept = c;
1248 document.getElementById("modalAccept").checked = true;
1249 }
1250 else this.finishProcessingChallenge(c);
1251 });
1252 }
1253 }
1254 else {
1255 // My challenge
1256 if (c.type == "corr") {
1257 ajax(
1258 "/challenges",
1259 "DELETE",
1260 { data: { id: c.id } }
1261 );
1262 }
1263 this.send("deletechallenge_s", { data: { cid: c.id } });
1264 }
1265 // In all cases, the challenge is consumed:
1266 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
1267 },
1268 // NOTE: when launching game, the challenge is already being deleted
1269 launchGame: function(c) {
1270 // White player index 0, black player index 1:
1271 let players =
1272 !!c.color
1273 ? (c.color == "w" ? [c.from, c.seat] : [c.seat, c.from])
1274 : shuffle([c.from, c.seat]);
1275 players.forEach(p => {
1276 if (!!p["tmpIds"]) delete p["tmpIds"];
1277 });
1278 // These game informations will be shared
1279 let gameInfo = {
1280 id: getRandString(),
1281 fen: c.fen || V.GenRandInitFen(c.randomness),
1282 randomness: c.randomness, //for rematch
1283 players: players,
1284 vid: c.vid,
1285 cadence: c.cadence
1286 };
1287 const notifyNewgame = () => {
1288 const oppsid = this.getOppsid(c);
1289 if (!!oppsid)
1290 // Opponent is online
1291 this.send("startgame", { data: gameInfo, target: oppsid });
1292 // If new corr game, notify Hall (except opponent and me)
1293 if (c.type == "corr") {
1294 this.send(
1295 "newgame",
1296 {
1297 data: gameInfo,
1298 excluded: [this.st.user.sid, oppsid]
1299 }
1300 );
1301 }
1302 // Notify MyGames page:
1303 this.send(
1304 "notifynewgame",
1305 {
1306 data: gameInfo,
1307 targets: gameInfo.players
1308 }
1309 );
1310 // NOTE: no need to send the game to the room, since I'll connect
1311 // on game just after, the main Hall will be notified.
1312 };
1313 if (c.type == "live") {
1314 // TODO: ask my IP + opp IP, to add to game infos? (potential bans)
1315 notifyNewgame();
1316 this.startNewGame(gameInfo);
1317 // Increment game stats counter in DB
1318 ajax(
1319 "/gamestat",
1320 "POST",
1321 { data: { vid: gameInfo.vid } }
1322 );
1323 }
1324 else {
1325 // corr: game only on server
1326 ajax(
1327 "/games",
1328 "POST",
1329 {
1330 // cid is useful to delete the challenge:
1331 data: {
1332 gameInfo: gameInfo,
1333 cid: c.id
1334 },
1335 success: (response) => {
1336 gameInfo.id = response.id;
1337 notifyNewgame();
1338 this.$router.push("/game/" + response.id);
1339 }
1340 }
1341 );
1342 }
1343 },
1344 // NOTE: for live games only (corr games start on the server)
1345 startNewGame: function(gameInfo) {
1346 const game = Object.assign(
1347 {},
1348 gameInfo,
1349 {
1350 // (other) Game infos: constant
1351 fenStart: gameInfo.fen,
1352 vname: this.getVname(gameInfo.vid),
1353 created: Date.now(),
1354 // Game state (including FEN): will be updated
1355 moves: [],
1356 clocks: [-1, -1], //-1 = unstarted
1357 chats: [],
1358 score: "*"
1359 }
1360 );
1361 setTimeout(
1362 () => {
1363 const myIdx = (game.players[0].sid == this.st.user.sid ? 0 : 1);
1364 GameStorage.add(game, (err) => {
1365 // If an error occurred, game is not added: the focused tab
1366 // already added the game.
1367 if (!this.focus) {
1368 if (this.st.settings.sound)
1369 // This will be played several times if several hidden tabs
1370 // on Hall... TODO: fix that (how ?!)
1371 new Audio("/sounds/newgame.flac").play().catch(() => {});
1372 notify(
1373 "New live game",
1374 { body: "vs " + (game.players[1-myIdx].name || "@nonymous") }
1375 );
1376 }
1377 this.$router.push("/game/" + gameInfo.id);
1378 });
1379 },
1380 this.focus ? 0 : 500 + 1000 * Math.random()
1381 );
1382 }
1383 }
1384 };
1385 </script>
1386
1387 <style lang="sass" scoped>
1388 .active
1389 color: #388e3c
1390
1391 #infoDiv > .card
1392 padding: 15px 0
1393 max-width: 430px
1394
1395 #newgameDiv > .card, #acceptDiv > .card
1396 max-width: 767px
1397 max-height: 100%
1398
1399 div#peopleWrap > .card
1400 max-height: 100%
1401
1402 @media screen and (min-width: 1281px)
1403 div#peopleWrap > .card
1404 max-width: 66.67%
1405
1406 @media screen and (max-width: 1280px)
1407 div#peopleWrap > .card
1408 max-width: 83.33%
1409
1410 @media screen and (max-width: 767px)
1411 div#peopleWrap > .card
1412 max-width: 100%
1413
1414 #players
1415 width: 50%
1416 position: relative
1417 float: left
1418
1419 #chat
1420 width: 50%
1421 float: left
1422 position: relative
1423
1424 @media screen and (max-width: 767px)
1425 #players, #chats
1426 width: 100%
1427
1428 #chat > .card
1429 max-width: 100%
1430 margin: 0;
1431 border: none;
1432
1433 #players > p
1434 margin-left: 5px
1435
1436 .anonymous
1437 font-style: italic
1438
1439 button.player-action
1440 margin-left: 32px
1441 &.focused
1442 background-color: #E6D271
1443
1444 .somethingnew
1445 background-color: #90C4EC !important
1446
1447 .tabbtn
1448 background-color: #f9faee
1449
1450 button.acceptBtn
1451 background-color: lightgreen
1452 button.refuseBtn
1453 background-color: red
1454
1455 #buttonsTchall
1456 // margin-top set dynamically (depends if diagram showed or not)
1457 & > button > span
1458 width: 100%
1459 text-align: center
1460
1461 .variantName
1462 font-weight: bold
1463
1464 .diagram
1465 margin: 0 auto
1466 max-width: 400px
1467 // width: 100% required for Firefox
1468 width: 100%
1469
1470 #inputFen
1471 width: 100%
1472
1473 #div2, #div3
1474 margin-top: 15px
1475 @media screen and (max-width: 767px)
1476 #div2, #div3
1477 margin-top: 0
1478
1479 .user-bio
1480 display: inline
1481
1482 tr > td
1483 &.random-0
1484 background-color: #FF5733
1485 &.random-1
1486 background-color: #2B63B4
1487 &.random-2
1488 background-color: #33B42B
1489
1490 @media screen and (max-width: 767px)
1491 h4
1492 margin: 5px 0
1493
1494 button#loadMoreBtn
1495 display: block
1496 margin: 0 auto
1497
1498 td.remove-preset
1499 background-color: lightgrey
1500 text-align: center
1501 & > img
1502 height: 1em
1503 </style>