Better challenge link in emails, better text on 'social' button
[vchess.git] / client / src / components / BaseGame.vue
CommitLineData
a6088c90 1<template lang="pug">
6808d7a1
BA
2div#baseGame(
3 tabindex=-1
4 @click="focusBg()"
5 @keydown="handleKeys($event)"
6 @wheel="handleScroll($event)"
7)
7e355d68 8 input#modalEog.modal(type="checkbox")
6808d7a1
BA
9 div#eogDiv(
10 role="dialog"
11 data-checkbox="modalEog"
12 )
9a3049f3 13 .card.text-center
7e355d68 14 label.modal-close(for="modalEog")
9a3049f3 15 h3.section {{ endgameMessage }}
602d6bef 16 input#modalAdjust.modal(type="checkbox")
6808d7a1
BA
17 div#adjuster(
18 role="dialog"
19 data-checkbox="modalAdjust"
20 )
9a3049f3 21 .card.text-center
602d6bef 22 label.modal-close(for="modalAdjust")
9a3049f3 23 label(for="boardSize") {{ st.tr["Board size"] }}
6808d7a1
BA
24 input#boardSize.slider(
25 type="range"
26 min="0"
27 max="100"
28 value="50"
29 @input="adjustBoard()"
30 )
cf94b843
BA
31 #gameContainer
32 #boardContainer
6808d7a1
BA
33 Board(
34 :vr="vr"
35 :last-move="lastMove"
36 :analyze="analyze"
37 :user-color="game.mycolor"
38 :orientation="orientation"
39 :vname="game.vname"
40 :incheck="incheck"
41 @play-move="play"
42 )
3b8b49ce 43 #turnIndicator(v-if="game.vname=='Dark' && game.score=='*'") {{ turn }}
cf94b843 44 #controls
9ddaf8da
BA
45 button(@click="gotoBegin()") <<
46 button(@click="undo()") <
47 button(@click="flip()") &#8645;
48 button(@click="play()") >
49 button(@click="gotoEnd()") >>
bd76b456 50 #belowControls
ed06d9e9 51 #downloadDiv(v-if="game.vname!='Dark' || game.score!='*'")
4f518610 52 a#download(href="#")
9ddaf8da 53 button(@click="download()") {{ st.tr["Download"] }} PGN
910d631b 54 button(onClick="window.doClick('modalAdjust')") &#10530;
6808d7a1
BA
55 button(
56 v-if="game.vname!='Dark' && game.mode!='analyze'"
57 @click="analyzePosition()"
58 )
677fe285 59 | {{ st.tr["Analyse"] }}
4f518610 60 // NOTE: rather ugly hack to avoid showing twice "rules" link...
6808d7a1
BA
61 button(
62 v-if="!$route.path.match('/variants/')"
63 @click="showRules()"
64 )
4f518610 65 | {{ st.tr["Rules"] }}
cf94b843 66 #movesList
6808d7a1
BA
67 MoveList(
68 v-if="showMoves"
69 :score="game.score"
70 :message="game.scoreMsg"
71 :firstNum="firstMoveNumber"
72 :moves="moves"
73 :cursor="cursor"
74 @goto-move="gotoMove"
75 )
41c80bb6 76 .clearer
a6088c90
BA
77</template>
78
79<script>
80import Board from "@/components/Board.vue";
f21cd6d9 81import MoveList from "@/components/MoveList.vue";
a6088c90
BA
82import { store } from "@/store";
83import { getSquareId } from "@/utils/squareId";
d4036efe 84import { getDate } from "@/utils/datetime";
602d6bef 85import { processModalClick } from "@/utils/modalClick";
77c50966 86import { getScoreMessage } from "@/utils/scoring";
a6088c90 87export default {
6808d7a1 88 name: "my-base-game",
a6088c90
BA
89 components: {
90 Board,
6808d7a1 91 MoveList
a6088c90 92 },
bc8734ba 93 // "vr": VariantRules object, describing the game state + rules
6808d7a1 94 props: ["vr", "game"],
a6088c90
BA
95 data: function() {
96 return {
97 st: store.state,
b7c32f1a 98 // NOTE: all following variables must be reset at the beginning of a game
a6088c90
BA
99 endgameMessage: "",
100 orientation: "w",
101 score: "*", //'*' means 'unfinished'
b7c32f1a 102 moves: [],
a6088c90
BA
103 cursor: -1, //index of the move just played
104 lastMove: null,
5157ce0b 105 firstMoveNumber: 0, //for printing
6808d7a1 106 incheck: [] //for Board
a6088c90
BA
107 };
108 },
37cdcbf3 109 watch: {
834c202a
BA
110 // game initial FEN changes when a new game starts
111 "game.fenStart": function() {
4b0384fa 112 this.re_setVariables();
37cdcbf3 113 },
7e355d68 114 // Received a new move to play:
6808d7a1
BA
115 "game.moveToPlay": function(move) {
116 if (move) this.play(move, "receive");
7e355d68 117 },
89021f18
BA
118 // ...Or to undo (corr game, move not validated)
119 "game.moveToUndo": function(move) {
6808d7a1
BA
120 if (move) this.undo(move);
121 }
37cdcbf3 122 },
a6088c90
BA
123 computed: {
124 showMoves: function() {
4f518610 125 return this.game.vname != "Dark" || this.game.score != "*";
a6088c90 126 },
58ae6be5
BA
127 turn: function() {
128 return this.st.tr[(this.vr.turn == 'w' ? "White" : "Black") + " to move"];
129 },
4f518610 130 analyze: function() {
6808d7a1
BA
131 return (
132 this.game.mode == "analyze" ||
4f518610 133 // From Board viewpoint, a finished Dark game == analyze (TODO: unclear)
6808d7a1
BA
134 (this.game.vname == "Dark" && this.game.score != "*")
135 );
136 }
a6088c90 137 },
4b0384fa 138 created: function() {
6808d7a1 139 if (this.game.fenStart) this.re_setVariables();
4b0384fa 140 },
cf94b843 141 mounted: function() {
6808d7a1
BA
142 [
143 document.getElementById("eogDiv"),
144 document.getElementById("adjuster")
145 ].forEach(elt => elt.addEventListener("click", processModalClick));
96e9585a
BA
146 // Take full width on small screens:
147 let boardSize = parseInt(localStorage.getItem("boardSize"));
6808d7a1
BA
148 if (!boardSize) {
149 boardSize =
150 window.innerWidth >= 768
151 ? 0.75 * Math.min(window.innerWidth, window.innerHeight)
152 : window.innerWidth;
96e9585a 153 }
6808d7a1 154 const movesWidth = window.innerWidth >= 768 ? 280 : 0;
96e9585a
BA
155 document.getElementById("boardContainer").style.width = boardSize + "px";
156 let gameContainer = document.getElementById("gameContainer");
6808d7a1
BA
157 gameContainer.style.width = boardSize + movesWidth + "px";
158 document.getElementById("boardSize").value =
159 (boardSize * 100) / (window.innerWidth - movesWidth);
602d6bef
BA
160 // timeout to avoid calling too many time the adjust method
161 let timeoutLaunched = false;
6808d7a1
BA
162 window.addEventListener("resize", () => {
163 if (!timeoutLaunched) {
602d6bef 164 timeoutLaunched = true;
6808d7a1 165 setTimeout(() => {
602d6bef
BA
166 this.adjustBoard();
167 timeoutLaunched = false;
168 }, 500);
169 }
170 });
cf94b843 171 },
a6088c90 172 methods: {
9ca1e26b 173 focusBg: function() {
9ca1e26b
BA
174 document.getElementById("baseGame").focus();
175 },
602d6bef
BA
176 adjustBoard: function() {
177 const boardContainer = document.getElementById("boardContainer");
6808d7a1 178 if (!boardContainer) return; //no board on page
602d6bef 179 const k = document.getElementById("boardSize").value;
6808d7a1 180 const movesWidth = window.innerWidth >= 768 ? 280 : 0;
602d6bef
BA
181 const minBoardWidth = 240; //TODO: these 240 and 280 are arbitrary...
182 // Value of 0 is board min size; 100 is window.width [- movesWidth]
6808d7a1
BA
183 const boardSize =
184 minBoardWidth +
185 (k * (window.innerWidth - (movesWidth + minBoardWidth))) / 100;
602d6bef
BA
186 localStorage.setItem("boardSize", boardSize);
187 boardContainer.style.width = boardSize + "px";
188 document.getElementById("gameContainer").style.width =
6808d7a1 189 boardSize + movesWidth + "px";
602d6bef 190 },
9ca1e26b 191 handleKeys: function(e) {
6808d7a1
BA
192 if ([32, 37, 38, 39, 40].includes(e.keyCode)) e.preventDefault();
193 switch (e.keyCode) {
9ca1e26b
BA
194 case 37:
195 this.undo();
196 break;
197 case 39:
198 this.play();
199 break;
5701c228 200 case 38:
9ca1e26b
BA
201 this.gotoBegin();
202 break;
203 case 40:
204 this.gotoEnd();
205 break;
206 case 32:
9ca1e26b
BA
207 this.flip();
208 break;
209 }
210 },
dcd68c41 211 handleScroll: function(e) {
4f518610 212 // NOTE: since game.mode=="analyze" => no score, next condition is enough
6808d7a1 213 if (this.game.score != "*") {
41c80bb6 214 e.preventDefault();
6808d7a1
BA
215 if (e.deltaY < 0) this.undo();
216 else if (e.deltaY > 0) this.play();
41c80bb6 217 }
dcd68c41 218 },
0e16cb26
BA
219 showRules: function() {
220 //this.$router.push("/variants/" + this.game.vname);
221 window.open("#/variants/" + this.game.vname, "_blank"); //better
222 },
4b0384fa
BA
223 re_setVariables: function() {
224 this.endgameMessage = "";
225 this.orientation = this.game.mycolor || "w"; //default orientation for observed games
4b0384fa 226 this.moves = JSON.parse(JSON.stringify(this.game.moves || []));
d4036efe
BA
227 // Post-processing: decorate each move with color + current FEN:
228 // (to be able to jump to any position quickly)
27d18a24 229 let vr_tmp = new V(this.game.fenStart); //vr is already at end of game
6808d7a1
BA
230 this.firstMoveNumber = Math.floor(
231 V.ParseFen(this.game.fenStart).movesCount / 2
232 );
d4036efe
BA
233 this.moves.forEach(move => {
234 // NOTE: this is doing manually what play() function below achieve,
235 // but in a lighter "fast-forward" way
27d18a24
BA
236 move.color = vr_tmp.turn;
237 move.notation = vr_tmp.getNotation(move);
238 vr_tmp.play(move);
239 move.fen = vr_tmp.getFen();
d4036efe 240 });
6808d7a1
BA
241 if (
242 (this.moves.length > 0 && this.moves[0].color == "b") ||
243 (this.moves.length == 0 && vr_tmp.turn == "b")
244 ) {
697ee580 245 // 'end' is required for Board component to check lastMove for e.p.
6808d7a1
BA
246 this.moves.unshift({
247 color: "w",
248 notation: "...",
249 end: { x: -1, y: -1 }
250 });
697ee580 251 }
4b0384fa 252 const L = this.moves.length;
6808d7a1
BA
253 this.cursor = L - 1;
254 this.lastMove = L > 0 ? this.moves[L - 1] : null;
9ef63965 255 this.incheck = this.vr.getCheckSquares(this.vr.turn);
4b0384fa 256 },
63ca2b89 257 analyzePosition: function() {
6808d7a1
BA
258 const newUrl =
259 "/analyse/" +
260 this.game.vname +
261 "/?fen=" +
262 this.vr.getFen().replace(/ /g, "_");
910d631b 263 // Open in same tab in live games (against cheating)
6808d7a1 264 if (this.game.type == "live") this.$router.push(newUrl);
910d631b 265 else window.open("#" + newUrl);
603b8a8b 266 },
a6088c90
BA
267 download: function() {
268 const content = this.getPgn();
269 // Prepare and trigger download link
270 let downloadAnchor = document.getElementById("download");
271 downloadAnchor.setAttribute("download", "game.pgn");
6808d7a1
BA
272 downloadAnchor.href =
273 "data:text/plain;charset=utf-8," + encodeURIComponent(content);
a6088c90
BA
274 downloadAnchor.click();
275 },
276 getPgn: function() {
277 let pgn = "";
278 pgn += '[Site "vchess.club"]\n';
834c202a 279 pgn += '[Variant "' + this.game.vname + '"]\n';
a6088c90 280 pgn += '[Date "' + getDate(new Date()) + '"]\n';
d4036efe
BA
281 pgn += '[White "' + this.game.players[0].name + '"]\n';
282 pgn += '[Black "' + this.game.players[1].name + '"]\n';
834c202a 283 pgn += '[Fen "' + this.game.fenStart + '"]\n';
430a2038 284 pgn += '[Result "' + this.game.score + '"]\n\n';
a6088c90
BA
285 let counter = 1;
286 let i = 0;
6808d7a1
BA
287 while (i < this.moves.length) {
288 pgn += counter++ + ".";
289 for (let color of ["w", "b"]) {
a6088c90
BA
290 let move = "";
291 while (i < this.moves.length && this.moves[i].color == color)
d4036efe 292 move += this.moves[i++].notation + ",";
6808d7a1 293 move = move.slice(0, -1); //remove last comma
d4036efe 294 pgn += move + (i < this.moves.length ? " " : "");
a6088c90
BA
295 }
296 }
297 return pgn + "\n";
298 },
b988c726
BA
299 showEndgameMsg: function(message) {
300 this.endgameMessage = message;
4494c17c 301 let modalBox = document.getElementById("modalEog");
a6088c90 302 modalBox.checked = true;
6808d7a1
BA
303 setTimeout(() => {
304 modalBox.checked = false;
305 }, 2000);
a6088c90 306 },
63ca2b89 307 animateMove: function(move, callback) {
a6088c90
BA
308 let startSquare = document.getElementById(getSquareId(move.start));
309 let endSquare = document.getElementById(getSquareId(move.end));
310 let rectStart = startSquare.getBoundingClientRect();
311 let rectEnd = endSquare.getBoundingClientRect();
6808d7a1
BA
312 let translation = {
313 x: rectEnd.x - rectStart.x,
314 y: rectEnd.y - rectStart.y
315 };
316 let movingPiece = document.querySelector(
317 "#" + getSquareId(move.start) + " > img.piece"
318 );
a6088c90
BA
319 // HACK for animation (with positive translate, image slides "under background")
320 // Possible improvement: just alter squares on the piece's way...
321 const squares = document.getElementsByClassName("board");
6808d7a1 322 for (let i = 0; i < squares.length; i++) {
a6088c90 323 let square = squares.item(i);
6808d7a1 324 if (square.id != getSquareId(move.start)) square.style.zIndex = "-1";
a6088c90 325 }
6808d7a1
BA
326 movingPiece.style.transform =
327 "translate(" + translation.x + "px," + translation.y + "px)";
910d631b 328 movingPiece.style.transitionDuration = "0.25s";
a6088c90 329 movingPiece.style.zIndex = "3000";
6808d7a1
BA
330 setTimeout(() => {
331 for (let i = 0; i < squares.length; i++)
a6088c90
BA
332 squares.item(i).style.zIndex = "auto";
333 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
63ca2b89 334 callback();
a6088c90
BA
335 }, 250);
336 },
63ca2b89
BA
337 play: function(move, receive) {
338 // NOTE: navigate and receive are mutually exclusive
9d54ab89 339 const navigate = !move;
63ca2b89
BA
340 // Forbid playing outside analyze mode, except if move is received.
341 // Sufficient condition because Board already knows which turn it is.
6808d7a1
BA
342 if (
343 !navigate &&
344 this.game.mode != "analyze" &&
345 !receive &&
346 (this.game.score != "*" || this.cursor < this.moves.length - 1)
347 ) {
a6088c90
BA
348 return;
349 }
63ca2b89 350 const doPlayMove = () => {
910d631b
BA
351 // To play a move, cursor must be at the end of the game:
352 if (!!receive && this.cursor < this.moves.length - 1) this.gotoEnd();
6808d7a1
BA
353 if (navigate) {
354 if (this.cursor == this.moves.length - 1) return; //no more moves
355 move = this.moves[this.cursor + 1];
356 } else {
63ca2b89
BA
357 move.color = this.vr.turn;
358 move.notation = this.vr.getNotation(move);
359 }
360 this.vr.play(move);
361 this.cursor++;
362 this.lastMove = move;
363 if (this.st.settings.sound == 2)
6808d7a1
BA
364 new Audio("/sounds/move.mp3").play().catch(() => {});
365 if (!navigate) {
63ca2b89 366 move.fen = this.vr.getFen();
9d54ab89 367 // Stack move on movesList at current cursor
6808d7a1
BA
368 if (this.cursor == this.moves.length) this.moves.push(move);
369 else this.moves = this.moves.slice(0, this.cursor).concat([move]);
9d54ab89 370 }
63ca2b89
BA
371 // Is opponent in check?
372 this.incheck = this.vr.getCheckSquares(this.vr.turn);
373 const score = this.vr.getCurrentScore();
6808d7a1 374 if (score != "*") {
77c50966 375 const message = getScoreMessage(score);
63ca2b89
BA
376 if (this.game.mode != "analyze")
377 this.$emit("gameover", score, message);
6808d7a1
BA
378 //just show score on screen (allow undo)
379 else this.showEndgameMsg(score + " . " + message);
63ca2b89 380 }
6808d7a1 381 if (!navigate && this.game.mode != "analyze")
4f518610 382 this.$emit("newmove", move); //post-processing (e.g. computer play)
63ca2b89
BA
383 };
384 if (!!receive && this.game.vname != "Dark")
385 this.animateMove(move, doPlayMove);
6808d7a1 386 else doPlayMove();
a6088c90
BA
387 },
388 undo: function(move) {
9d54ab89 389 const navigate = !move;
6808d7a1
BA
390 if (navigate) {
391 if (this.cursor < 0) return; //no more moves
a6088c90
BA
392 move = this.moves[this.cursor];
393 }
394 this.vr.undo(move);
395 this.cursor--;
6808d7a1 396 this.lastMove = this.cursor >= 0 ? this.moves[this.cursor] : undefined;
a6088c90 397 if (this.st.settings.sound == 2)
6808d7a1 398 new Audio("/sounds/undo.mp3").play().catch(() => {});
a6088c90 399 this.incheck = this.vr.getCheckSquares(this.vr.turn);
6808d7a1 400 if (!navigate) this.moves.pop();
a6088c90
BA
401 },
402 gotoMove: function(index) {
37cdcbf3 403 this.vr.re_init(this.moves[index].fen);
a6088c90
BA
404 this.cursor = index;
405 this.lastMove = this.moves[index];
406 },
407 gotoBegin: function() {
6808d7a1 408 if (this.cursor == -1) return;
834c202a 409 this.vr.re_init(this.game.fenStart);
6808d7a1 410 if (this.moves.length > 0 && this.moves[0].notation == "...") {
5701c228
BA
411 this.cursor = 0;
412 this.lastMove = this.moves[0];
6808d7a1 413 } else {
5701c228
BA
414 this.cursor = -1;
415 this.lastMove = null;
416 }
a6088c90
BA
417 },
418 gotoEnd: function() {
6808d7a1
BA
419 if (this.cursor == this.moves.length - 1) return;
420 this.gotoMove(this.moves.length - 1);
a6088c90
BA
421 },
422 flip: function() {
0e16cb26 423 this.orientation = V.GetOppCol(this.orientation);
6808d7a1
BA
424 }
425 }
a6088c90
BA
426};
427</script>
72ccbd67 428
41c80bb6 429<style lang="sass" scoped>
9a3049f3
BA
430[type="checkbox"]#modalEog+div .card
431 min-height: 45px
910d631b 432
9a3049f3
BA
433[type="checkbox"]#modalAdjust+div .card
434 padding: 5px
435
cf94b843
BA
436#baseGame
437 width: 100%
4f518610
BA
438 &:focus
439 outline: none
cf94b843
BA
440
441#gameContainer
72ccbd67
BA
442 margin-left: auto
443 margin-right: auto
cf94b843 444
ed06d9e9
BA
445#downloadDiv
446 display: inline-block
447
72ccbd67 448#controls
bd76b456 449 margin: 0 auto
72ccbd67
BA
450 button
451 display: inline-block
452 width: 20%
453 margin: 0
910d631b 454
0e16cb26
BA
455#turnIndicator
456 text-align: center
29bc61be 457 font-weight: bold
910d631b 458
bd76b456
BA
459#belowControls
460 border-top: 1px solid #2f4f4f
cf94b843 461 text-align: center
bd76b456
BA
462 margin: 0 auto
463 & > #downloadDiv
464 margin: 0
465 & > button
466 margin: 0
467 & > button
468 border-left: 1px solid #2f4f4f
469 margin: 0
910d631b 470
72ccbd67 471#boardContainer
cf94b843 472 float: left
41c80bb6
BA
473// TODO: later, maybe, allow movesList of variable width
474// or e.g. between 250 and 350px (but more complicated)
910d631b 475
cf94b843
BA
476#movesList
477 width: 280px
478 float: left
910d631b 479
96e9585a
BA
480@media screen and (max-width: 767px)
481 #movesList
482 width: 100%
483 float: none
484 clear: both
72ccbd67 485</style>