Experimental fix attempt in Board.vue (bad behavior on smartphones)
[vchess.git] / client / src / components / Board.vue
CommitLineData
24340cae 1<script>
e2732923
BA
2import { getSquareId, getSquareFromId } from "@/utils/squareId";
3import { ArrayFun } from "@/utils/array";
dfeb96ea 4import { store } from "@/store";
cf2343ce
BA
5export default {
6 name: 'my-board',
7 // Last move cannot be guessed from here, and is required to highlight squares
8 // vr: object to check moves, print board...
93d1d7a7 9 // userColor is left undefined for an external observer
f51c37cf 10 props: ["vr","lastMove","analyze","incheck","orientation","userColor","vname"],
cf2343ce
BA
11 data: function () {
12 return {
cf2343ce
BA
13 possibleMoves: [], //filled after each valid click/dragstart
14 choices: [], //promotion pieces, or checkered captures... (as moves)
15 selectedPiece: null, //moving piece (or clicked piece)
cf2343ce 16 start: {}, //pixels coordinates + id of starting square (click or drag)
dfeb96ea 17 settings: store.state.settings,
cf2343ce
BA
18 };
19 },
20 render(h) {
21 if (!this.vr)
7b3cf1b7
BA
22 {
23 // Return empty div of class 'game' to avoid error when setting size
24 return h("div",
25 {
26 "class": {
27 "game": true,
28 },
29 });
30 }
cf2343ce
BA
31 const [sizeX,sizeY] = [V.size.x,V.size.y];
32 // Precompute hints squares to facilitate rendering
e2732923 33 let hintSquares = ArrayFun.init(sizeX, sizeY, false);
cf2343ce
BA
34 this.possibleMoves.forEach(m => { hintSquares[m.end.x][m.end.y] = true; });
35 // Also precompute in-check squares
e2732923 36 let incheckSq = ArrayFun.init(sizeX, sizeY, false);
cf2343ce 37 this.incheck.forEach(sq => { incheckSq[sq[0]][sq[1]] = true; });
06e79b07 38
7b3cf1b7
BA
39 let boardElt = document.querySelector(".game");
40 const squareWidth = (!!boardElt
41 ? boardElt.offsetWidth / sizeY
06e79b07 42 : 40); //arbitrary value (not relevant)
168a5e4c
BA
43 const offset = (!!boardElt
44 ? [boardElt.offsetTop, boardElt.offsetLeft]
45 : [0, 0]);
cf2343ce
BA
46 const choices = h(
47 'div',
48 {
49 attrs: { "id": "choices" },
50 'class': { 'row': true },
51 style: {
93d1d7a7 52 "display": (this.choices.length > 0 ? "block" : "none"),
168a5e4c
BA
53 "top": (offset[0] + (sizeY/2)*squareWidth-squareWidth/2) + "px",
54 "left": (offset[1] + squareWidth*(sizeY - this.choices.length)/2) + "px",
cf2343ce
BA
55 "width": (this.choices.length * squareWidth) + "px",
56 "height": squareWidth + "px",
57 },
58 },
59 this.choices.map(m => { //a "choice" is a move
60 return h('div',
61 {
62 'class': {
63 'board': true,
64 ['board'+sizeY]: true,
65 },
66 style: {
67 'width': (100/this.choices.length) + "%",
68 'padding-bottom': (100/this.choices.length) + "%",
69 },
70 },
71 [h('img',
72 {
73 attrs: { "src": '/images/pieces/' +
74 V.getPpath(m.appear[0].c+m.appear[0].p) + '.svg' },
75 'class': { 'choice-piece': true },
76 on: {
77 "click": e => { this.play(m); this.choices=[]; },
cf2343ce
BA
78 },
79 })
80 ]
81 );
82 })
83 );
84 // Create board element (+ reserves if needed by variant or mode)
85 const lm = this.lastMove;
dfeb96ea 86 const showLight = this.settings.highlight && this.vname != "Dark";
cf2343ce
BA
87 const gameDiv = h(
88 'div',
89 {
90 'class': {
91 'game': true,
92 'clearer': true,
93 },
94 },
95 [...Array(sizeX).keys()].map(i => {
96 let ci = (this.orientation=='w' ? i : sizeX-i-1);
97 return h(
98 'div',
99 {
100 'class': {
101 'row': true,
102 },
103 style: { 'opacity': this.choices.length>0?"0.5":"1" },
104 },
105 [...Array(sizeY).keys()].map(j => {
106 let cj = (this.orientation=='w' ? j : sizeY-j-1);
107 let elems = [];
e2732923 108 if (this.vr.board[ci][cj] != V.EMPTY && (this.vname!="Dark"
93d1d7a7
BA
109 || this.analyze || (!!this.userColor
110 && this.vr.enlightened[this.userColor][ci][cj])))
cf2343ce
BA
111 {
112 elems.push(
113 h(
114 'img',
115 {
116 'class': {
117 'piece': true,
118 'ghost': !!this.selectedPiece
119 && this.selectedPiece.parentNode.id == "sq-"+ci+"-"+cj,
120 },
121 attrs: {
50aed5a1
BA
122 src: "/images/pieces/" +
123 V.getPpath(this.vr.board[ci][cj]) + ".svg",
cf2343ce
BA
124 },
125 }
126 )
127 );
128 }
dfeb96ea 129 if (this.settings.hints && hintSquares[ci][cj])
cf2343ce
BA
130 {
131 elems.push(
132 h(
133 'img',
134 {
135 'class': {
136 'mark-square': true,
137 },
138 attrs: {
139 src: "/images/mark.svg",
140 },
141 }
142 )
143 );
144 }
145 return h(
146 'div',
147 {
148 'class': {
149 'board': true,
150 ['board'+sizeY]: true,
151 'light-square': (i+j)%2==0,
152 'dark-square': (i+j)%2==1,
dfeb96ea 153 [this.settings.bcolor]: true,
93d1d7a7
BA
154 'in-shadow': this.vname=="Dark" && !this.analyze
155 && (!this.userColor
156 || !this.vr.enlightened[this.userColor][ci][cj]),
cf2343ce
BA
157 'highlight': showLight && !!lm && lm.end.x == ci && lm.end.y == cj,
158 'incheck': showLight && incheckSq[ci][cj],
159 },
160 attrs: {
161 id: getSquareId({x:ci,y:cj}),
162 },
163 },
164 elems
165 );
166 })
167 );
24340cae 168 })
cf2343ce 169 );
d4036efe 170 const playingColor = this.userColor || "w"; //default for an observer
cf2343ce
BA
171 let elementArray = [choices, gameDiv];
172 if (!!this.vr.reserve)
173 {
93d1d7a7 174 const shiftIdx = (playingColor=="w" ? 0 : 1);
cf2343ce
BA
175 let myReservePiecesArray = [];
176 for (let i=0; i<V.RESERVE_PIECES.length; i++)
177 {
178 myReservePiecesArray.push(h('div',
179 {
180 'class': {'board':true, ['board'+sizeY]:true},
181 attrs: { id: getSquareId({x:sizeX+shiftIdx,y:i}) }
182 },
183 [
184 h('img',
185 {
186 'class': {"piece":true, "reserve":true},
187 attrs: {
188 "src": "/images/pieces/" +
93d1d7a7 189 this.vr.getReservePpath(playingColor,i) + ".svg",
cf2343ce
BA
190 }
191 }),
192 h('sup',
193 {"class": { "reserve-count": true } },
93d1d7a7 194 [ this.vr.reserve[playingColor][V.RESERVE_PIECES[i]] ]
cf2343ce
BA
195 )
196 ]));
197 }
198 let oppReservePiecesArray = [];
93d1d7a7 199 const oppCol = V.GetOppCol(playingColor);
cf2343ce
BA
200 for (let i=0; i<V.RESERVE_PIECES.length; i++)
201 {
202 oppReservePiecesArray.push(h('div',
203 {
204 'class': {'board':true, ['board'+sizeY]:true},
205 attrs: { id: getSquareId({x:sizeX+(1-shiftIdx),y:i}) }
206 },
207 [
208 h('img',
209 {
210 'class': {"piece":true, "reserve":true},
211 attrs: {
212 "src": "/images/pieces/" +
213 this.vr.getReservePpath(oppCol,i) + ".svg",
214 }
215 }),
216 h('sup',
217 {"class": { "reserve-count": true } },
218 [ this.vr.reserve[oppCol][V.RESERVE_PIECES[i]] ]
219 )
220 ]));
221 }
222 let reserves = h('div',
223 {
224 'class':{
225 'game': true,
226 "reserve-div": true,
227 },
228 },
229 [
230 h('div',
231 {
232 'class': {
233 'row': true,
234 "reserve-row-1": true,
235 },
236 },
237 myReservePiecesArray
238 ),
239 h('div',
240 { 'class': { 'row': true }},
241 oppReservePiecesArray
242 )
243 ]
244 );
245 elementArray.push(reserves);
246 }
247 return h(
248 'div',
249 {
cf2343ce
BA
250 // NOTE: click = mousedown + mouseup
251 on: {
65495c17
BA
252 mousedown: this.mousedown,
253 mousemove: this.mousemove,
254 mouseup: this.mouseup,
255// touchstart: this.mousedown,
8e44d3a3 256 touchmove: this.mousemove,
65495c17 257// touchend: this.mouseup,
cf2343ce
BA
258 },
259 },
260 elementArray
261 );
262 },
263 methods: {
264 mousedown: function(e) {
265 e = e || window.event;
266 let ingame = false;
267 let elem = e.target;
268 while (!ingame && elem !== null)
269 {
270 if (elem.classList.contains("game"))
271 {
272 ingame = true;
273 break;
274 }
275 elem = elem.parentElement;
276 }
277 if (!ingame) //let default behavior (click on button...)
278 return;
279 e.preventDefault(); //disable native drag & drop
280 if (!this.selectedPiece && e.target.classList.contains("piece"))
281 {
83c6c2c9 282 let parent = e.target.parentNode;
cf2343ce 283 // Next few lines to center the piece on mouse cursor
83c6c2c9 284 let rect = parent.getBoundingClientRect();
cf2343ce
BA
285 this.start = {
286 x: rect.x + rect.width/2,
287 y: rect.y + rect.width/2,
83c6c2c9 288 id: parent.id
cf2343ce
BA
289 };
290 this.selectedPiece = e.target.cloneNode();
bd76b456
BA
291 let spStyle = this.selectedPiece.style
292 spStyle.position = "absolute";
293 spStyle.top = 0;
294 spStyle.display = "inline-block";
295 spStyle.zIndex = 3000;
83c6c2c9 296 const startSquare = getSquareFromId(parent.id);
cf2343ce 297 this.possibleMoves = [];
93d1d7a7 298 const color = (this.analyze ? this.vr.turn : this.userColor);
cf2343ce
BA
299 if (this.vr.canIplay(color,startSquare))
300 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
301 // Next line add moving piece just after current image
302 // (required for Crazyhouse reserve)
83c6c2c9 303 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
cf2343ce
BA
304 }
305 },
306 mousemove: function(e) {
307 if (!this.selectedPiece)
308 return;
309 e = e || window.event;
310 // If there is an active element, move it around
311 if (!!this.selectedPiece)
312 {
313 const [offsetX,offsetY] = !!e.clientX
314 ? [e.clientX,e.clientY] //desktop browser
315 : [e.changedTouches[0].pageX, e.changedTouches[0].pageY]; //smartphone
316 this.selectedPiece.style.left = (offsetX-this.start.x) + "px";
317 this.selectedPiece.style.top = (offsetY-this.start.y) + "px";
318 }
319 },
320 mouseup: function(e) {
321 if (!this.selectedPiece)
322 return;
323 e = e || window.event;
cf2343ce
BA
324 this.selectedPiece.style.zIndex = -3000; //HACK to find square from final coords
325 const [offsetX,offsetY] = !!e.clientX
326 ? [e.clientX,e.clientY]
327 : [e.changedTouches[0].pageX, e.changedTouches[0].pageY];
328 let landing = document.elementFromPoint(offsetX, offsetY);
329 this.selectedPiece.style.zIndex = 3000;
330 // Next condition: classList.contains(piece) fails because of marks
331 while (landing.tagName == "IMG")
332 landing = landing.parentNode;
333 if (this.start.id == landing.id)
334 {
335 // A click: selectedPiece and possibleMoves are already filled
336 return;
337 }
bd76b456 338 // OK: process move attempt, landing is a square node
cf2343ce
BA
339 let endSquare = getSquareFromId(landing.id);
340 let moves = this.findMatchingMoves(endSquare);
341 this.possibleMoves = [];
342 if (moves.length > 1)
343 this.choices = moves;
344 else if (moves.length==1)
345 this.play(moves[0]);
346 // Else: impossible move
347 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
348 delete this.selectedPiece;
349 this.selectedPiece = null;
350 },
351 findMatchingMoves: function(endSquare) {
352 // Run through moves list and return the matching set (if promotions...)
353 let moves = [];
354 this.possibleMoves.forEach(function(m) {
355 if (endSquare[0] == m.end.x && endSquare[1] == m.end.y)
356 moves.push(m);
357 });
358 return moves;
359 },
360 play: function(move) {
361 this.$emit('play-move', move);
362 },
363 },
364};
365</script>
4473050c 366
41c80bb6 367<style lang="sass" scoped>
50aed5a1
BA
368.game.reserve-div
369 margin-bottom: 18px
370
371.reserve-count
372 padding-left: 40%
373
374.reserve-row-1
375 margin-bottom: 15px
376
41cb9b94
BA
377// NOTE: no variants with reserve of size != 8
378
50aed5a1 379.game
cf94b843
BA
380 width: 100%
381 margin: 0
50aed5a1
BA
382 .board
383 cursor: pointer
50aed5a1
BA
384
385#choices
168a5e4c
BA
386 margin: 0
387 position: absolute
50aed5a1
BA
388 z-index: 300
389 overflow-y: inherit
390 background-color: rgba(0,0,0,0)
391 img
392 cursor: pointer
393 background-color: #e6ee9c
394 &:hover
395 background-color: skyblue
396 &.choice-piece
397 width: 100%
398 height: auto
399 display: block
400
50aed5a1
BA
401img.ghost
402 position: absolute
403 opacity: 0.4
404 top: 0
405
406.highlight
407 background-color: #00cc66 !important
408
50aed5a1
BA
409.incheck
410 background-color: #cc3300 !important
411
412.light-square.lichess
413 background-color: #f0d9b5;
414.dark-square.lichess
415 background-color: #b58863;
416
417.light-square.chesscom
418 background-color: #e5e5ca;
419.dark-square.chesscom
420 background-color: #6f8f57;
421
422.light-square.chesstempo
423 background-color: #fdfdfd;
424.dark-square.chesstempo
425 background-color: #88a0a8;
4473050c 426</style>