Generalize pawn movements: cleaner and smaller code
[vchess.git] / client / src / views / Problems.vue
CommitLineData
89021f18
BA
1<template lang="pug">
2main
910d631b
BA
3 input#modalNewprob.modal(
4 type="checkbox"
09d37571 5 @change="fenFocusIfOpened($event)"
910d631b
BA
6 )
7 div#newprobDiv(
8 role="dialog"
9 data-checkbox="modalNewprob"
10 )
866842c3 11 .card
89021f18 12 label#closeNewprob.modal-close(for="modalNewprob")
604b951e
BA
13 fieldset
14 label(for="selectVariant") {{ st.tr["Variant"] }}
15 select#selectVariant(
16 v-model="curproblem.vid"
17 @change="changeVariant(curproblem)"
18 )
19 option(
20 v-for="v in [emptyVar].concat(st.variants)"
21 :value="v.id"
22 :selected="curproblem.vid==v.id"
23 )
24 | {{ v.name }}
25 fieldset
604b951e
BA
26 input#inputFen(
27 type="text"
bd76b456 28 placeholder="FEN"
604b951e
BA
29 v-model="curproblem.fen"
30 @input="trySetDiagram(curproblem)"
31 )
bd76b456 32 #diagram(v-html="curproblem.diag")
604b951e 33 fieldset
bd76b456 34 textarea(
604b951e
BA
35 :placeholder="st.tr['Instructions']"
36 v-model="curproblem.instruction"
37 )
38 p(v-html="parseHtml(curproblem.instruction)")
39 fieldset
bd76b456 40 textarea(
604b951e
BA
41 :placeholder="st.tr['Solution']"
42 v-model="curproblem.solution"
43 )
44 p(v-html="parseHtml(curproblem.solution)")
45 button(@click="sendProblem()") {{ st.tr["Send"] }}
89021f18 46 #dialog.text-center {{ st.tr[infoMsg] }}
604b951e 47 .row(v-if="showOne")
866842c3 48 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
bd76b456 49 #topPage
d7c00f6a
BA
50 .button-group(v-if="st.user.id == curproblem.uid")
51 button(@click="editProblem(curproblem)") {{ st.tr["Edit"] }}
52 button(@click="deleteProblem(curproblem)") {{ st.tr["Delete"] }}
2f258c37 53 span.vname {{ curproblem.vname }}
98fb976e 54 span.uname ({{ curproblem.uname }})
bd76b456 55 button.marginleft(@click="backToList()") {{ st.tr["Back to list"] }}
d7c00f6a
BA
56 button.nomargin(@click="gotoPrevNext($event,curproblem,1)")
57 | {{ st.tr["Previous"] }}
58 button.nomargin(@click="gotoPrevNext($event,curproblem,-1)")
feaf1bf7 59 | {{ st.tr["Next_p"] }}
866842c3 60 p.oneInstructions.clickable(
2f258c37 61 v-html="parseHtml(curproblem.instruction)"
bd76b456
BA
62 @click="curproblem.showSolution=!curproblem.showSolution"
63 )
604b951e
BA
64 | {{ st.tr["Show solution"] }}
65 p(
66 v-show="curproblem.showSolution"
67 v-html="parseHtml(curproblem.solution)"
68 )
69 .row(v-else)
89021f18 70 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
bd76b456 71 #controls
f37790f7 72 button#newProblem(@click="prepareNewProblem()")
bd76b456
BA
73 | {{ st.tr["New problem"] }}
74 label(for="checkboxMine") {{ st.tr["My problems"] }}
75 input#checkboxMine(
76 type="checkbox"
77 v-model="onlyMines"
604b951e 78 )
bd76b456
BA
79 label(for="selectVariant") {{ st.tr["Variant"] }}
80 select#selectVariant(v-model="selectedVar")
81 option(
82 v-for="v in [emptyVar].concat(st.variants)"
83 :value="v.id"
84 )
85 | {{ v.name }}
9b35f4a9 86 table#tProblems
bd76b456
BA
87 tr
88 th {{ st.tr["Variant"] }}
89 th {{ st.tr["Instructions"] }}
2f258c37 90 th {{ st.tr["Number"] }}
bd76b456 91 tr(
6808d7a1 92 v-for="p in problems"
bd76b456
BA
93 v-show="displayProblem(p)"
94 @click="setHrefPid(p)"
95 )
96 td {{ p.vname }}
2f258c37
BA
97 td {{ firstChars(p.instruction) }}
98 td {{ p.id }}
68e19a44
BA
99 button#loadMoreBtn(
100 v-if="hasMore"
101 @click="loadMore()"
102 )
103 | {{ st.tr["Load more"] }}
910d631b 104 BaseGame(
b1e46b33 105 ref="basegame"
910d631b
BA
106 v-if="showOne"
107 :game="game"
910d631b 108 )
89021f18
BA
109</template>
110
111<script>
112import { store } from "@/store";
113import { ajax } from "@/utils/ajax";
114import { checkProblem } from "@/data/problemCheck";
115import { getDiagram } from "@/utils/printDiagram";
bd76b456
BA
116import { processModalClick } from "@/utils/modalClick";
117import { ArrayFun } from "@/utils/array";
604b951e 118import BaseGame from "@/components/BaseGame.vue";
89021f18
BA
119export default {
120 name: "my-problems",
604b951e 121 components: {
6808d7a1 122 BaseGame
604b951e 123 },
89021f18
BA
124 data: function() {
125 return {
604b951e 126 st: store.state,
89021f18
BA
127 emptyVar: {
128 vid: 0,
6808d7a1 129 vname: ""
89021f18 130 },
604b951e
BA
131 // Problem currently showed, or edited:
132 curproblem: {
133 id: 0, //used in case of edit
89021f18
BA
134 vid: 0,
135 fen: "",
604b951e 136 diag: "",
89021f18
BA
137 instruction: "",
138 solution: "",
6808d7a1 139 showSolution: false
89021f18 140 },
604b951e
BA
141 loadedVar: 0, //corresponding to loaded V
142 selectedVar: 0, //to filter problems based on variant
89021f18 143 problems: [],
68e19a44
BA
144 // timestamp of oldest showed problem:
145 cursor: Number.MAX_SAFE_INTEGER,
146 // hasMore == TRUE: a priori there could be more problems to load
147 hasMore: true,
604b951e
BA
148 onlyMines: false,
149 showOne: false,
89021f18 150 infoMsg: "",
604b951e 151 game: {
6808d7a1
BA
152 players: [{ name: "Problem" }, { name: "Problem" }],
153 mode: "analyze"
154 }
89021f18
BA
155 };
156 },
157 created: function() {
e57c4de4
BA
158 ajax(
159 "/problems",
160 "GET",
161 {
68e19a44 162 data: { cursor: this.cursor },
e57c4de4 163 success: (res) => {
68e19a44
BA
164 // The returned list is sorted from most recent to oldest
165 this.problems = res.problems;
166 const L = res.problems.length;
167 if (L > 0) this.cursor = res.problems[L - 1].added;
168 else this.hasMore = false;
e57c4de4
BA
169 const showOneIfPid = () => {
170 const pid = this.$route.query["id"];
b1e46b33 171 if (!!pid) this.showProblem(this.problems.find(p => p.id == pid));
e57c4de4 172 };
68e19a44 173 this.decorate(this.problems, showOneIfPid);
e57c4de4
BA
174 }
175 }
176 );
89021f18 177 },
bd76b456 178 mounted: function() {
42a92848 179 document.getElementById("newprobDiv")
6808d7a1 180 .addEventListener("click", processModalClick);
bd76b456 181 },
604b951e
BA
182 watch: {
183 // st.variants changes only once, at loading from [] to [...]
6808d7a1 184 "st.variants": function() {
604b951e
BA
185 // Set problems vname (either all are set or none)
186 if (this.problems.length > 0 && this.problems[0].vname == "")
187 this.problems.forEach(p => this.setVname(p));
188 },
6808d7a1 189 $route: function(to) {
bd76b456 190 const pid = to.query["id"];
b1e46b33 191 if (!!pid) this.showProblem(this.problems.find(p => p.id == pid));
6808d7a1
BA
192 else this.showOne = false;
193 }
98fb976e 194 },
89021f18 195 methods: {
09d37571
BA
196 fenFocusIfOpened: function(event) {
197 if (event.target.checked) {
198 this.infoMsg = "";
199 document.getElementById("inputFen").focus();
200 }
201 },
604b951e
BA
202 setVname: function(prob) {
203 prob.vname = this.st.variants.find(v => v.id == prob.vid).name;
204 },
68e19a44
BA
205 // Add vname and user names:
206 decorate: function(problems, callback) {
207 if (this.st.variants.length > 0)
208 problems.forEach(p => this.setVname(p));
209 // Retrieve all problems' authors' names
210 let names = {};
211 problems.forEach(p => {
212 if (p.uid != this.st.user.id) names[p.uid] = "";
213 else p.uname = this.st.user.name;
214 });
215 if (Object.keys(names).length > 0) {
216 ajax(
217 "/users",
218 "GET",
219 {
220 data: { ids: Object.keys(names).join(",") },
221 success: (res2) => {
222 res2.users.forEach(u => {
223 names[u.id] = u.name;
224 });
225 problems.forEach(p => {
226 if (!p.uname)
227 p.uname = names[p.uid];
228 });
229 if (!!callback) callback();
230 }
231 }
232 );
233 } else if (!!callback) callback();
234 },
2f258c37
BA
235 firstChars: function(text) {
236 let preparedText = text
237 // Replace line jumps and <br> by spaces
6808d7a1
BA
238 .replace(/\n/g, " ")
239 .replace(/<br\/?>/g, " ")
2f258c37
BA
240 .replace(/<[^>]+>/g, "") //remove remaining HTML tags
241 .replace(/[ ]+/g, " ") //remove series of spaces by only one
242 .trim();
243 const maxLength = 32; //arbitrary...
244 if (preparedText.length > maxLength)
6808d7a1 245 return preparedText.substr(0, 32) + "...";
2f258c37
BA
246 return preparedText;
247 },
604b951e 248 copyProblem: function(p1, p2) {
6808d7a1 249 for (let key in p1) p2[key] = p1[key];
604b951e 250 },
bd76b456
BA
251 setHrefPid: function(p) {
252 // Change href => $route changes, watcher notices, call showProblem
253 const curHref = document.location.href;
254 document.location.href = curHref.split("?")[0] + "?id=" + p.id;
255 },
256 backToList: function() {
257 // Change href => $route change, watcher notices, reset showOne to false
258 document.location.href = document.location.href.split("?")[0];
259 },
604b951e
BA
260 resetCurProb: function() {
261 this.curproblem.id = 0;
262 this.curproblem.uid = 0;
263 this.curproblem.vid = "";
264 this.curproblem.vname = "";
265 this.curproblem.fen = "";
266 this.curproblem.diag = "";
267 this.curproblem.instruction = "";
268 this.curproblem.solution = "";
269 this.curproblem.showSolution = false;
89021f18 270 },
604b951e
BA
271 parseHtml: function(txt) {
272 return !txt.match(/<[/a-zA-Z]+>/)
273 ? txt.replace(/\n/g, "<br/>") //no HTML tag
274 : txt;
275 },
276 changeVariant: function(prob) {
277 this.setVname(prob);
6808d7a1
BA
278 this.loadVariant(prob.vid, () => {
279 // Set FEN if possible (might not be correct yet)
280 if (V.IsGoodFen(prob.fen)) this.setDiagram(prob);
281 });
604b951e
BA
282 },
283 loadVariant: async function(vid, cb) {
284 // Condition: vid is a valid variant ID
285 this.loadedVar = 0;
286 const variant = this.st.variants.find(v => v.id == vid);
32f6285e
BA
287 await import("@/variants/" + variant.name + ".js")
288 .then((vModule) => {
289 window.V = vModule[variant.name + "Rules"];
290 this.loadedVar = vid;
291 cb();
292 });
604b951e
BA
293 },
294 trySetDiagram: function(prob) {
295 // Problem edit: FEN could be wrong or incomplete,
296 // variant could not be ready, or not defined
297 if (prob.vid > 0 && this.loadedVar == prob.vid && V.IsGoodFen(prob.fen))
298 this.setDiagram(prob);
89021f18 299 },
604b951e
BA
300 setDiagram: function(prob) {
301 // Condition: prob.fen is correct and global V is ready
302 const parsedFen = V.ParseFen(prob.fen);
303 const args = {
304 position: parsedFen.position,
6808d7a1 305 orientation: parsedFen.turn
604b951e
BA
306 };
307 prob.diag = getDiagram(args);
89021f18 308 },
604b951e 309 displayProblem: function(p) {
6808d7a1 310 return (
866842c3 311 (!this.selectedVar || p.vid == this.selectedVar) &&
6808d7a1
BA
312 ((this.onlyMines && p.uid == this.st.user.id) ||
313 (!this.onlyMines && p.uid != this.st.user.id))
314 );
604b951e
BA
315 },
316 showProblem: function(p) {
6808d7a1
BA
317 this.loadVariant(p.vid, () => {
318 // The FEN is already checked at this stage:
6808d7a1 319 this.game.vname = p.vname;
e71161fb 320 this.game.mycolor = V.ParseFen(p.fen).turn; //diagram orientation
b1e46b33 321 this.game.fenStart = p.fen;
6808d7a1 322 this.game.fen = p.fen;
6808d7a1 323 this.showOne = true;
b1e46b33
BA
324 // $nextTick to be sure $refs["basegame"] exists
325 this.$nextTick(() => {
326 this.$refs["basegame"].re_setVariables(this.game); });
327 this.copyProblem(p, this.curproblem);
6808d7a1 328 });
604b951e 329 },
d7c00f6a
BA
330 gotoPrevNext: function(e, prob, dir) {
331 const startIdx = this.problems.findIndex(p => p.id == prob.id);
332 let nextIdx = startIdx + dir;
333 while (
334 nextIdx >= 0 &&
335 nextIdx < this.problems.length &&
336 ((this.onlyMines && this.problems[nextIdx].uid != this.st.user.id) ||
337 (!this.onlyMines && this.problems[nextIdx].uid == this.st.user.id))
338 )
339 nextIdx += dir;
340 if (nextIdx >= 0 && nextIdx < this.problems.length)
341 this.setHrefPid(this.problems[nextIdx]);
342 else
343 alert(this.st.tr["No more problems"]);
344 },
f37790f7
BA
345 prepareNewProblem: function() {
346 this.resetCurProb();
347 window.doClick("modalNewprob");
348 },
604b951e
BA
349 sendProblem: function() {
350 const error = checkProblem(this.curproblem);
6808d7a1 351 if (error) {
866842c3 352 alert(this.st.tr[error]);
6808d7a1
BA
353 return;
354 }
604b951e
BA
355 const edit = this.curproblem.id > 0;
356 this.infoMsg = "Processing... Please wait";
357 ajax(
358 "/problems",
359 edit ? "PUT" : "POST",
e57c4de4
BA
360 {
361 data: { prob: this.curproblem },
362 success: (ret) => {
363 if (edit) {
364 let editedP = this.problems.find(p => p.id == this.curproblem.id);
365 this.copyProblem(this.curproblem, editedP);
366 this.showProblem(editedP);
367 }
368 else {
369 let newProblem = Object.assign({}, this.curproblem);
370 newProblem.id = ret.id;
371 newProblem.uid = this.st.user.id;
372 newProblem.uname = this.st.user.name;
373 this.problems = [newProblem].concat(this.problems);
374 }
375 document.getElementById("modalNewprob").checked = false;
376 this.infoMsg = "";
0cd02605 377 }
604b951e
BA
378 }
379 );
380 },
381 editProblem: function(prob) {
bec548e7
BA
382 // prob.diag might correspond to some other problem or be empty:
383 this.setDiagram(prob); //V is loaded at this stage
604b951e 384 this.copyProblem(prob, this.curproblem);
6808d7a1 385 window.doClick("modalNewprob");
604b951e
BA
386 },
387 deleteProblem: function(prob) {
6808d7a1 388 if (confirm(this.st.tr["Are you sure?"])) {
e57c4de4
BA
389 ajax(
390 "/problems",
391 "DELETE",
392 {
393 data: { id: prob.id },
394 success: () => {
395 ArrayFun.remove(this.problems, p => p.id == prob.id);
396 this.backToList();
397 }
398 }
399 );
bd76b456 400 }
68e19a44
BA
401 },
402 loadMore: function() {
403 ajax(
404 "/problems",
405 "GET",
406 {
407 data: { cursor: this.cursor },
408 success: (res) => {
409 const L = res.problems.length;
410 if (L > 0) {
411 this.decorate(res.problems);
412 this.problems = this.problems.concat(res.problems);
413 this.cursor = res.problems[L - 1].added;
414 } else this.hasMore = false;
415 }
416 }
417 );
6808d7a1
BA
418 }
419 }
89021f18
BA
420};
421</script>
422
423<style lang="sass" scoped>
bd76b456
BA
424[type="checkbox"].modal+div .card
425 max-width: 767px
426 max-height: 100%
910d631b 427
bd76b456
BA
428#inputFen
429 width: 100%
910d631b 430
bd76b456
BA
431textarea
432 width: 100%
910d631b 433
bd76b456
BA
434#diagram
435 margin: 0 auto
436 max-width: 400px
910d631b 437
9b35f4a9
BA
438table#tProblems
439 max-height: 100%
440
68e19a44
BA
441button#loadMoreBtn
442 display: block
443 margin: 0 auto
444
bd76b456
BA
445#controls
446 margin: 0
447 width: 100%
448 text-align: center
449 & > *
450 margin: 0
2f258c37 451
866842c3
BA
452p.oneInstructions
453 margin: 0
454 padding: 2px 5px
455 background-color: lightgreen
456
bd76b456 457#topPage
2f258c37 458 span.vname
bd76b456 459 font-weight: bold
feae89d3 460 padding-left: var(--universal-margin)
2f258c37
BA
461 span.uname
462 padding-left: var(--universal-margin)
bd76b456
BA
463 margin: 0 auto
464 & > .nomargin
465 margin: 0
466 & > .marginleft
467 margin: 0 0 0 15px
468
2f258c37
BA
469@media screen and (max-width: 767px)
470 #topPage
471 text-align: center
89021f18 472</style>