Generalize pawn movements: cleaner and smaller code
[vchess.git] / client / src / views / Problems.vue
1 <template lang="pug">
2 main
3 input#modalNewprob.modal(
4 type="checkbox"
5 @change="fenFocusIfOpened($event)"
6 )
7 div#newprobDiv(
8 role="dialog"
9 data-checkbox="modalNewprob"
10 )
11 .card
12 label#closeNewprob.modal-close(for="modalNewprob")
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
26 input#inputFen(
27 type="text"
28 placeholder="FEN"
29 v-model="curproblem.fen"
30 @input="trySetDiagram(curproblem)"
31 )
32 #diagram(v-html="curproblem.diag")
33 fieldset
34 textarea(
35 :placeholder="st.tr['Instructions']"
36 v-model="curproblem.instruction"
37 )
38 p(v-html="parseHtml(curproblem.instruction)")
39 fieldset
40 textarea(
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"] }}
46 #dialog.text-center {{ st.tr[infoMsg] }}
47 .row(v-if="showOne")
48 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
49 #topPage
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"] }}
53 span.vname {{ curproblem.vname }}
54 span.uname ({{ curproblem.uname }})
55 button.marginleft(@click="backToList()") {{ st.tr["Back to list"] }}
56 button.nomargin(@click="gotoPrevNext($event,curproblem,1)")
57 | {{ st.tr["Previous"] }}
58 button.nomargin(@click="gotoPrevNext($event,curproblem,-1)")
59 | {{ st.tr["Next_p"] }}
60 p.oneInstructions.clickable(
61 v-html="parseHtml(curproblem.instruction)"
62 @click="curproblem.showSolution=!curproblem.showSolution"
63 )
64 | {{ st.tr["Show solution"] }}
65 p(
66 v-show="curproblem.showSolution"
67 v-html="parseHtml(curproblem.solution)"
68 )
69 .row(v-else)
70 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
71 #controls
72 button#newProblem(@click="prepareNewProblem()")
73 | {{ st.tr["New problem"] }}
74 label(for="checkboxMine") {{ st.tr["My problems"] }}
75 input#checkboxMine(
76 type="checkbox"
77 v-model="onlyMines"
78 )
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 }}
86 table#tProblems
87 tr
88 th {{ st.tr["Variant"] }}
89 th {{ st.tr["Instructions"] }}
90 th {{ st.tr["Number"] }}
91 tr(
92 v-for="p in problems"
93 v-show="displayProblem(p)"
94 @click="setHrefPid(p)"
95 )
96 td {{ p.vname }}
97 td {{ firstChars(p.instruction) }}
98 td {{ p.id }}
99 button#loadMoreBtn(
100 v-if="hasMore"
101 @click="loadMore()"
102 )
103 | {{ st.tr["Load more"] }}
104 BaseGame(
105 ref="basegame"
106 v-if="showOne"
107 :game="game"
108 )
109 </template>
110
111 <script>
112 import { store } from "@/store";
113 import { ajax } from "@/utils/ajax";
114 import { checkProblem } from "@/data/problemCheck";
115 import { getDiagram } from "@/utils/printDiagram";
116 import { processModalClick } from "@/utils/modalClick";
117 import { ArrayFun } from "@/utils/array";
118 import BaseGame from "@/components/BaseGame.vue";
119 export default {
120 name: "my-problems",
121 components: {
122 BaseGame
123 },
124 data: function() {
125 return {
126 st: store.state,
127 emptyVar: {
128 vid: 0,
129 vname: ""
130 },
131 // Problem currently showed, or edited:
132 curproblem: {
133 id: 0, //used in case of edit
134 vid: 0,
135 fen: "",
136 diag: "",
137 instruction: "",
138 solution: "",
139 showSolution: false
140 },
141 loadedVar: 0, //corresponding to loaded V
142 selectedVar: 0, //to filter problems based on variant
143 problems: [],
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,
148 onlyMines: false,
149 showOne: false,
150 infoMsg: "",
151 game: {
152 players: [{ name: "Problem" }, { name: "Problem" }],
153 mode: "analyze"
154 }
155 };
156 },
157 created: function() {
158 ajax(
159 "/problems",
160 "GET",
161 {
162 data: { cursor: this.cursor },
163 success: (res) => {
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;
169 const showOneIfPid = () => {
170 const pid = this.$route.query["id"];
171 if (!!pid) this.showProblem(this.problems.find(p => p.id == pid));
172 };
173 this.decorate(this.problems, showOneIfPid);
174 }
175 }
176 );
177 },
178 mounted: function() {
179 document.getElementById("newprobDiv")
180 .addEventListener("click", processModalClick);
181 },
182 watch: {
183 // st.variants changes only once, at loading from [] to [...]
184 "st.variants": function() {
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 },
189 $route: function(to) {
190 const pid = to.query["id"];
191 if (!!pid) this.showProblem(this.problems.find(p => p.id == pid));
192 else this.showOne = false;
193 }
194 },
195 methods: {
196 fenFocusIfOpened: function(event) {
197 if (event.target.checked) {
198 this.infoMsg = "";
199 document.getElementById("inputFen").focus();
200 }
201 },
202 setVname: function(prob) {
203 prob.vname = this.st.variants.find(v => v.id == prob.vid).name;
204 },
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 },
235 firstChars: function(text) {
236 let preparedText = text
237 // Replace line jumps and <br> by spaces
238 .replace(/\n/g, " ")
239 .replace(/<br\/?>/g, " ")
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)
245 return preparedText.substr(0, 32) + "...";
246 return preparedText;
247 },
248 copyProblem: function(p1, p2) {
249 for (let key in p1) p2[key] = p1[key];
250 },
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 },
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;
270 },
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);
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 });
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);
287 await import("@/variants/" + variant.name + ".js")
288 .then((vModule) => {
289 window.V = vModule[variant.name + "Rules"];
290 this.loadedVar = vid;
291 cb();
292 });
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);
299 },
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,
305 orientation: parsedFen.turn
306 };
307 prob.diag = getDiagram(args);
308 },
309 displayProblem: function(p) {
310 return (
311 (!this.selectedVar || p.vid == this.selectedVar) &&
312 ((this.onlyMines && p.uid == this.st.user.id) ||
313 (!this.onlyMines && p.uid != this.st.user.id))
314 );
315 },
316 showProblem: function(p) {
317 this.loadVariant(p.vid, () => {
318 // The FEN is already checked at this stage:
319 this.game.vname = p.vname;
320 this.game.mycolor = V.ParseFen(p.fen).turn; //diagram orientation
321 this.game.fenStart = p.fen;
322 this.game.fen = p.fen;
323 this.showOne = true;
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);
328 });
329 },
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 },
345 prepareNewProblem: function() {
346 this.resetCurProb();
347 window.doClick("modalNewprob");
348 },
349 sendProblem: function() {
350 const error = checkProblem(this.curproblem);
351 if (error) {
352 alert(this.st.tr[error]);
353 return;
354 }
355 const edit = this.curproblem.id > 0;
356 this.infoMsg = "Processing... Please wait";
357 ajax(
358 "/problems",
359 edit ? "PUT" : "POST",
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 = "";
377 }
378 }
379 );
380 },
381 editProblem: function(prob) {
382 // prob.diag might correspond to some other problem or be empty:
383 this.setDiagram(prob); //V is loaded at this stage
384 this.copyProblem(prob, this.curproblem);
385 window.doClick("modalNewprob");
386 },
387 deleteProblem: function(prob) {
388 if (confirm(this.st.tr["Are you sure?"])) {
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 );
400 }
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 );
418 }
419 }
420 };
421 </script>
422
423 <style lang="sass" scoped>
424 [type="checkbox"].modal+div .card
425 max-width: 767px
426 max-height: 100%
427
428 #inputFen
429 width: 100%
430
431 textarea
432 width: 100%
433
434 #diagram
435 margin: 0 auto
436 max-width: 400px
437
438 table#tProblems
439 max-height: 100%
440
441 button#loadMoreBtn
442 display: block
443 margin: 0 auto
444
445 #controls
446 margin: 0
447 width: 100%
448 text-align: center
449 & > *
450 margin: 0
451
452 p.oneInstructions
453 margin: 0
454 padding: 2px 5px
455 background-color: lightgreen
456
457 #topPage
458 span.vname
459 font-weight: bold
460 padding-left: var(--universal-margin)
461 span.uname
462 padding-left: var(--universal-margin)
463 margin: 0 auto
464 & > .nomargin
465 margin: 0
466 & > .marginleft
467 margin: 0 0 0 15px
468
469 @media screen and (max-width: 767px)
470 #topPage
471 text-align: center
472 </style>