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