better diagrams in rules pages + some improvements to pieces images
[vchess.git] / client / src / views / Problems.vue
1 <template lang="pug">
2 main
3 input#modalRules.modal(type="checkbox")
4 div#rulesDiv(
5 role="dialog"
6 data-checkbox="modalRules"
7 )
8 .card
9 label.modal-close(for="modalRules")
10 a#variantNameInProblems(:href="'/#/variants/'+game.vname")
11 | {{ game.vname }}
12 div(v-html="rulesContent")
13 input#modalNewprob.modal(
14 type="checkbox"
15 @change="fenFocusIfOpened($event)"
16 )
17 div#newprobDiv(
18 role="dialog"
19 data-checkbox="modalNewprob"
20 )
21 .card
22 label#closeNewprob.modal-close(for="modalNewprob")
23 fieldset
24 label(for="selectVariant") {{ st.tr["Variant"] }}
25 select#selectVariant(
26 v-model="curproblem.vid"
27 @change="changeVariant(curproblem)"
28 )
29 option(
30 v-for="v in [emptyVar].concat(st.variants)"
31 v-if="!v.noProblems"
32 :value="v.id"
33 :selected="curproblem.vid==v.id"
34 )
35 | {{ v.name }}
36 fieldset
37 input#inputFen(
38 type="text"
39 placeholder="FEN"
40 v-model="curproblem.fen"
41 @input="trySetDiagram(curproblem)"
42 )
43 #diagram(v-html="curproblem.diag")
44 fieldset
45 textarea(
46 :placeholder="st.tr['Instructions']"
47 v-model="curproblem.instruction"
48 )
49 p(v-html="parseHtml(curproblem.instruction)")
50 fieldset
51 textarea(
52 :placeholder="st.tr['Solution']"
53 v-model="curproblem.solution"
54 )
55 p(v-html="parseHtml(curproblem.solution)")
56 button(@click="sendProblem()") {{ st.tr["Send"] }}
57 #dialog.text-center {{ st.tr[infoMsg] }}
58 .row(v-if="showOne")
59 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
60 #topPage
61 .button-group(v-if="canIedit(curproblem.uid)")
62 button(@click="editProblem(curproblem)") {{ st.tr["Edit"] }}
63 button(@click="deleteProblem(curproblem)") {{ st.tr["Delete"] }}
64 span.vname {{ curproblem.vname }}
65 span.uname ({{ curproblem.uname }})
66 button.marginleft(@click="backToList()") {{ st.tr["Back to list"] }}
67 button.nomargin(@click="gotoPrevNext(curproblem,1)")
68 | {{ st.tr["Previous_p"] }}
69 button.nomargin(@click="gotoPrevNext(curproblem,-1)")
70 | {{ st.tr["Next_p"] }}
71 p.oneInstructions.clickable(
72 v-html="parseHtml(curproblem.instruction)"
73 @click="curproblem.showSolution=!curproblem.showSolution"
74 )
75 | {{ st.tr["Show solution"] }}
76 p(
77 v-show="curproblem.showSolution"
78 v-html="parseHtml(curproblem.solution)"
79 )
80 .row(v-else)
81 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
82 #controls
83 button#newProblem(@click="prepareNewProblem()")
84 | {{ st.tr["New problem"] }}
85 div#myProblems(v-if="st.user.id > 0")
86 label(for="checkboxMine") {{ st.tr["My problems"] }}
87 input#checkboxMine(
88 type="checkbox"
89 v-model="onlyMine"
90 )
91 label(for="selectVariant") {{ st.tr["Variant"] }}
92 select#selectVariant(v-model="selectedVar")
93 option(
94 v-for="v in [emptyVar].concat(st.variants)"
95 v-if="!v.noProblems"
96 :value="v.id"
97 )
98 | {{ v.name }}
99 table#tProblems
100 tr
101 th {{ st.tr["Variant"] }}
102 th {{ st.tr["Instructions"] }}
103 th {{ st.tr["Number"] }}
104 tr(
105 v-for="p in problems[onlyMine ? 'mine' : 'others']"
106 v-show="onlyMine || !selectedVar || p.vid == selectedVar"
107 @click="setHrefPid(p)"
108 )
109 td {{ p.vname }}
110 td {{ firstChars(p.instruction) }}
111 td {{ p.id }}
112 button#loadMoreBtn(
113 v-if="hasMore[onlyMine ? 'mine' : 'others']"
114 @click="loadMore(onlyMine ? 'mine' : 'others')"
115 )
116 | {{ st.tr["Load more"] }}
117 BaseGame(
118 ref="basegame"
119 v-if="showOne"
120 :game="game"
121 )
122 </template>
123
124 <script>
125 import { store } from "@/store";
126 import { ajax } from "@/utils/ajax";
127 import { checkProblem } from "@/data/problemCheck";
128 import params from "@/parameters";
129 import { getDiagram, replaceByDiag } from "@/utils/printDiagram";
130 import { processModalClick } from "@/utils/modalClick";
131 import { ArrayFun } from "@/utils/array";
132 import BaseGame from "@/components/BaseGame.vue";
133 export default {
134 name: "my-problems",
135 components: {
136 BaseGame
137 },
138 data: function() {
139 return {
140 st: store.state,
141 emptyVar: {
142 vid: 0,
143 vname: ""
144 },
145 // Problem currently showed, or edited:
146 curproblem: {
147 id: 0, //used in case of edit
148 vid: 0,
149 fen: "",
150 diag: "",
151 instruction: "",
152 solution: "",
153 showSolution: false
154 },
155 loadedVar: 0, //corresponding to loaded V
156 selectedVar: 0, //to filter problems based on variant
157 problems: { "mine": [], "others": [] },
158 // timestamp of oldest showed problem:
159 cursor: {
160 mine: Number.MAX_SAFE_INTEGER,
161 others: Number.MAX_SAFE_INTEGER
162 },
163 // hasMore == TRUE: a priori there could be more problems to load
164 hasMore: { mine: true, others: true },
165 onlyMine: false,
166 showOne: false,
167 infoMsg: "",
168 rulesContent: "",
169 game: {
170 players: [{ name: "Problem" }, { name: "Problem" }],
171 mode: "analyze"
172 }
173 };
174 },
175 created: function() {
176 const pid = this.$route.query["id"];
177 if (!!pid) this.showProblem(pid);
178 else this.loadMore("others", () => { this.loadMore("mine"); });
179 },
180 mounted: function() {
181 ["rulesDiv","newprobDiv"].forEach(eltName => {
182 document.getElementById(eltName)
183 .addEventListener("click", processModalClick)
184 });
185 },
186 watch: {
187 // st.variants changes only once, at loading from [] to [...]
188 "st.variants": function() {
189 // Set problems vname (either all are set or none)
190 let problems = this.problems["others"].concat(this.problems["mine"]);
191 if (problems.length > 0 && problems[0].vname == "")
192 problems.forEach(p => this.setVname(p));
193 },
194 $route: function(to) {
195 const pid = to.query["id"];
196 if (!!pid) this.showProblem(pid);
197 else {
198 if (this.cursor["others"] == Number.MAX_SAFE_INTEGER)
199 // Back from a single problem view at initial loading:
200 // problems lists are empty!
201 this.loadMore("others", () => { this.loadMore("mine"); });
202 this.showOne = false;
203 }
204 }
205 },
206 methods: {
207 fenFocusIfOpened: function(event) {
208 if (event.target.checked) {
209 this.infoMsg = "";
210 document.getElementById("inputFen").focus();
211 }
212 },
213 setVname: function(prob) {
214 prob.vname = this.st.variants.find(v => v.id == prob.vid).name;
215 },
216 // Add vname and user names:
217 decorate: function(problems, callback) {
218 if (this.st.variants.length > 0)
219 problems.forEach(p => this.setVname(p));
220 // Retrieve all problems' authors' names
221 let names = {};
222 problems.forEach(p => {
223 if (p.uid != this.st.user.id) names[p.uid] = "";
224 else p.uname = this.st.user.name;
225 });
226 if (Object.keys(names).length > 0) {
227 ajax(
228 "/users",
229 "GET",
230 {
231 data: { ids: Object.keys(names).join(",") },
232 success: (res2) => {
233 res2.users.forEach(u => {
234 names[u.id] = u.name;
235 });
236 problems.forEach(p => {
237 if (!p.uname)
238 p.uname = names[p.uid];
239 });
240 if (!!callback) callback();
241 }
242 }
243 );
244 } else if (!!callback) callback();
245 },
246 firstChars: function(text) {
247 let preparedText = text
248 // Replace line jumps and <br> by spaces
249 .replace(/\n/g, " ")
250 .replace(/<br\/?>/g, " ")
251 .replace(/<[^>]+>/g, "") //remove remaining HTML tags
252 .replace(/[ ]+/g, " ") //remove series of spaces by only one
253 .trim();
254 const maxLength = 32; //arbitrary...
255 if (preparedText.length > maxLength)
256 return preparedText.substr(0, 32) + "...";
257 return preparedText;
258 },
259 copyProblem: function(p1, p2) {
260 for (let key in p1) p2[key] = p1[key];
261 },
262 setHrefPid: function(p) {
263 // Change href => $route changes, watcher notices, call showProblem
264 const curHref = document.location.href;
265 document.location.href = curHref.split("?")[0] + "?id=" + p.id;
266 },
267 backToList: function() {
268 // Change href => $route change, watcher notices, reset showOne to false
269 document.location.href = document.location.href.split("?")[0];
270 },
271 resetCurProb: function() {
272 this.curproblem.id = 0;
273 this.curproblem.uid = 0;
274 this.curproblem.vid = "";
275 this.curproblem.vname = "";
276 this.curproblem.fen = "";
277 this.curproblem.diag = "";
278 this.curproblem.instruction = "";
279 this.curproblem.solution = "";
280 this.curproblem.showSolution = false;
281 },
282 parseHtml: function(txt) {
283 return !txt.match(/<[/a-zA-Z]+>/)
284 ? txt.replace(/\n/g, "<br/>") //no HTML tag
285 : txt;
286 },
287 changeVariant: function(prob) {
288 this.setVname(prob);
289 this.loadVariant(prob.vid, () => {
290 // Set FEN if possible (might not be correct yet)
291 if (V.IsGoodFen(prob.fen)) this.setDiagram(prob);
292 else prob.diag = "";
293 });
294 },
295 loadVariant: async function(vid, cb) {
296 // Condition: vid is a valid variant ID
297 this.loadedVar = 0;
298 const variant = this.st.variants.find(v => v.id == vid);
299 await import("@/variants/" + variant.name + ".js")
300 .then((vModule) => {
301 window.V = vModule[variant.name + "Rules"];
302 this.loadedVar = vid;
303 cb();
304 });
305 // (AJAX) Request to get rules content (plain text, HTML)
306 this.rulesContent =
307 require(
308 "raw-loader!@/translations/rules/" +
309 variant.name + "/" +
310 this.st.lang + ".pug"
311 )
312 // Next two lines fix a weird issue after last update (2019-11)
313 .replace(/\\n/g, " ")
314 .replace(/\\"/g, '"')
315 .replace('module.exports = "', "")
316 .replace(/"$/, "")
317 .replace(/(fen:)([^:]*):/g, replaceByDiag);
318 },
319 trySetDiagram: function(prob) {
320 // Problem edit: FEN could be wrong or incomplete,
321 // variant could not be ready, or not defined
322 if (prob.vid > 0 && this.loadedVar == prob.vid && V.IsGoodFen(prob.fen))
323 this.setDiagram(prob);
324 else prob.diag = "";
325 },
326 setDiagram: function(prob) {
327 // Condition: prob.fen is correct and global V is ready
328 const parsedFen = V.ParseFen(prob.fen);
329 const args = {
330 position: parsedFen.position,
331 orientation: parsedFen.turn
332 };
333 prob.diag = getDiagram(args);
334 },
335 showProblem: function(p_id) {
336 const processWhenWeHaveProb = () => {
337 this.loadVariant(p.vid, () => {
338 this.onlyMine = (p.uid == this.st.user.id);
339 // The FEN is already checked at this stage:
340 this.game.vname = p.vname;
341 this.game.mycolor = V.ParseFen(p.fen).turn; //diagram orientation
342 this.game.fenStart = p.fen;
343 this.game.fen = p.fen;
344 this.showOne = true;
345 // $nextTick to be sure $refs["basegame"] exists
346 this.$nextTick(() => {
347 this.$refs["basegame"].re_setVariables(this.game); });
348 this.curproblem.showSolution = false; //in case of
349 this.copyProblem(p, this.curproblem);
350 });
351 };
352 let p = undefined;
353 if (typeof p_id == "object") p = p_id;
354 else {
355 const problems = this.problems["others"].concat(this.problems["mine"]);
356 p = problems.find(prob => prob.id == p_id);
357 }
358 if (!p) {
359 // Bad luck: problem not in list. Get from server
360 ajax(
361 "/problems",
362 "GET",
363 {
364 data: { id: p_id },
365 success: (res) => {
366 this.decorate([res.problem], () => {
367 p = res.problem;
368 const mode = (p.uid == this.st.user.id ? "mine" : "others");
369 this.problems[mode].push(p);
370 processWhenWeHaveProb();
371 });
372 }
373 }
374 );
375 } else processWhenWeHaveProb();
376 },
377 gotoPrevNext: function(prob, dir) {
378 const mode = (this.onlyMine ? "mine" : "others");
379 const problems = this.problems[mode];
380 const startIdx = problems.findIndex(p => p.id == prob.id);
381 const nextIdx = startIdx + dir;
382 if (nextIdx >= 0 && nextIdx < problems.length)
383 this.setHrefPid(problems[nextIdx]);
384 else if (this.hasMore[mode]) {
385 this.loadMore(
386 mode,
387 (nbProbs) => {
388 if (nbProbs > 0) this.gotoPrevNext(prob, dir);
389 else alert(this.st.tr["No more problems"]);
390 }
391 );
392 }
393 else alert(this.st.tr["No more problems"]);
394 },
395 prepareNewProblem: function() {
396 this.resetCurProb();
397 window.doClick("modalNewprob");
398 },
399 sendProblem: function() {
400 const error = checkProblem(this.curproblem);
401 if (error) {
402 alert(this.st.tr[error]);
403 return;
404 }
405 const edit = this.curproblem.id > 0;
406 this.infoMsg = "Processing... Please wait";
407 ajax(
408 "/problems",
409 edit ? "PUT" : "POST",
410 {
411 data: { prob: this.curproblem },
412 success: (ret) => {
413 if (edit) {
414 let editedP = this.problems["mine"]
415 .find(p => p.id == this.curproblem.id);
416 if (!editedP)
417 // I'm an admin and edit another user' problem
418 editedP = this.problems["others"]
419 .find(p => p.id == this.curproblem.id);
420 this.copyProblem(this.curproblem, editedP);
421 this.showProblem(editedP);
422 }
423 else {
424 let newProblem = Object.assign({}, this.curproblem);
425 newProblem.id = ret.id;
426 newProblem.uid = this.st.user.id;
427 newProblem.uname = this.st.user.name;
428 this.problems["mine"] =
429 [newProblem].concat(this.problems["mine"]);
430 }
431 document.getElementById("modalNewprob").checked = false;
432 this.infoMsg = "";
433 }
434 }
435 );
436 },
437 canIedit: function(puid) {
438 return params.devs.concat([puid]).includes(this.st.user.id);
439 },
440 editProblem: function(prob) {
441 // prob.diag might correspond to some other problem or be empty:
442 this.setDiagram(prob); //V is loaded at this stage
443 this.copyProblem(prob, this.curproblem);
444 window.doClick("modalNewprob");
445 },
446 deleteProblem: function(prob) {
447 if (confirm(this.st.tr["Are you sure?"])) {
448 ajax(
449 "/problems",
450 "DELETE",
451 {
452 data: { id: prob.id },
453 success: () => {
454 const mode = prob.uid == (this.st.user.id ? "mine" : "others");
455 ArrayFun.remove(this.problems[mode], p => p.id == prob.id);
456 this.backToList();
457 }
458 }
459 );
460 }
461 },
462 loadMore: function(mode, cb) {
463 ajax(
464 "/problems",
465 "GET",
466 {
467 data: {
468 uid: this.st.user.id,
469 mode: mode,
470 cursor: this.cursor[mode]
471 },
472 success: (res) => {
473 const L = res.problems.length;
474 if (L > 0) {
475 this.cursor[mode] = res.problems[L - 1].added;
476 // Remove potential duplicates:
477 const pids = this.problems[mode].map(p => p.id);
478 ArrayFun.remove(res.problems, p => pids.includes(p.id), "all");
479 this.decorate(res.problems);
480 this.problems[mode] =
481 this.problems[mode].concat(res.problems)
482 // TODO: problems are alrady sorted, would just need to insert
483 // the current individual problem in list; more generally
484 // there is probably only one misclassified problem.
485 // (Unless the user navigated several times by URL to show a
486 // single problem...)
487 .sort((p1, p2) => p2.added - p1.added);
488 } else this.hasMore[mode] = false;
489 if (!!cb) cb(L);
490 }
491 }
492 );
493 }
494 }
495 };
496 </script>
497
498 <style lang="sass">
499 @import "@/styles/_board_squares_img.sass"
500 @import "@/styles/_rules.sass"
501 </style>
502
503 <style lang="sass" scoped>
504 [type="checkbox"].modal+div .card
505 max-width: 767px
506 max-height: 100%
507
508 #rulesDiv > .card
509 padding: 5px 0
510 max-width: 50%
511 max-height: 100%
512 @media screen and (max-width: 1500px)
513 max-width: 67%
514 @media screen and (max-width: 1024px)
515 max-width: 85%
516 @media screen and (max-width: 767px)
517 max-width: 100%
518
519 #inputFen
520 width: 100%
521
522 textarea
523 width: 100%
524
525 #diagram
526 margin: 0 auto
527 max-width: 400px
528
529 table#tProblems
530 max-height: 100%
531
532 button#loadMoreBtn
533 display: block
534 margin: 0 auto
535
536 #controls
537 margin: 0
538 width: 100%
539 text-align: center
540 & > *
541 margin: 0
542
543 p.oneInstructions
544 margin: 0
545 padding: 2px 5px
546 background-color: lightgreen
547
548 #myProblems
549 display: inline-block
550
551 #topPage
552 span.vname
553 font-weight: bold
554 padding-left: var(--universal-margin)
555 span.uname
556 padding-left: var(--universal-margin)
557 margin: 0 auto
558 & > .nomargin
559 margin: 0
560 & > .marginleft
561 margin: 0 0 0 15px
562
563 @media screen and (max-width: 767px)
564 #topPage
565 text-align: center
566
567 a#variantNameInProblems
568 color: var(--card-fore-color)
569 text-align: center
570 font-weight: bold
571 font-size: calc(1rem * var(--heading-ratio))
572 line-height: 1.2
573 margin: calc(1.5 * var(--universal-margin))
574 </style>