Factor some lines (raw loading pug files)
[vchess.git] / client / src / views / Problems.vue
CommitLineData
89021f18
BA
1<template lang="pug">
2main
956407c4
BA
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")
910d631b
BA
13 input#modalNewprob.modal(
14 type="checkbox"
09d37571 15 @change="fenFocusIfOpened($event)"
910d631b
BA
16 )
17 div#newprobDiv(
18 role="dialog"
19 data-checkbox="modalNewprob"
20 )
866842c3 21 .card
89021f18 22 label#closeNewprob.modal-close(for="modalNewprob")
604b951e
BA
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)"
e75718fc 31 v-if="!v.noProblems"
604b951e
BA
32 :value="v.id"
33 :selected="curproblem.vid==v.id"
34 )
35 | {{ v.name }}
36 fieldset
604b951e
BA
37 input#inputFen(
38 type="text"
bd76b456 39 placeholder="FEN"
604b951e
BA
40 v-model="curproblem.fen"
41 @input="trySetDiagram(curproblem)"
42 )
bd76b456 43 #diagram(v-html="curproblem.diag")
604b951e 44 fieldset
3c24a27d 45 textarea.instructions-edit(
604b951e 46 :placeholder="st.tr['Instructions']"
ad16f839 47 @input="adjustHeight('instructions')"
604b951e
BA
48 v-model="curproblem.instruction"
49 )
ad65975c 50 .instructions(v-html="parseHtml(curproblem.instruction)")
604b951e 51 fieldset
3c24a27d 52 textarea.solution-edit(
604b951e 53 :placeholder="st.tr['Solution']"
ad16f839 54 @input="adjustHeight('solution')"
604b951e
BA
55 v-model="curproblem.solution"
56 )
ad65975c 57 .solution(v-html="parseHtml(curproblem.solution)")
604b951e 58 button(@click="sendProblem()") {{ st.tr["Send"] }}
89021f18 59 #dialog.text-center {{ st.tr[infoMsg] }}
604b951e 60 .row(v-if="showOne")
866842c3 61 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
bd76b456 62 #topPage
2c5d7b20 63 .button-group(v-if="canIedit(curproblem.uid)")
d7c00f6a
BA
64 button(@click="editProblem(curproblem)") {{ st.tr["Edit"] }}
65 button(@click="deleteProblem(curproblem)") {{ st.tr["Delete"] }}
2f258c37 66 span.vname {{ curproblem.vname }}
98fb976e 67 span.uname ({{ curproblem.uname }})
bd76b456 68 button.marginleft(@click="backToList()") {{ st.tr["Back to list"] }}
01fba77c 69 button.nomargin(@click="gotoPrevNext(curproblem,1)")
d85f259c 70 | {{ st.tr["Previous_p"] }}
01fba77c 71 button.nomargin(@click="gotoPrevNext(curproblem,-1)")
feaf1bf7 72 | {{ st.tr["Next_p"] }}
ad65975c 73 .instructions.oneInstructions.clickable(
2f258c37 74 v-html="parseHtml(curproblem.instruction)"
bd76b456
BA
75 @click="curproblem.showSolution=!curproblem.showSolution"
76 )
604b951e 77 | {{ st.tr["Show solution"] }}
ad65975c 78 .solution(
604b951e
BA
79 v-show="curproblem.showSolution"
80 v-html="parseHtml(curproblem.solution)"
81 )
82 .row(v-else)
89021f18 83 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
bd76b456 84 #controls
f37790f7 85 button#newProblem(@click="prepareNewProblem()")
bd76b456 86 | {{ st.tr["New problem"] }}
84fc0f02
BA
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 )
bd76b456
BA
93 label(for="selectVariant") {{ st.tr["Variant"] }}
94 select#selectVariant(v-model="selectedVar")
95 option(
96 v-for="v in [emptyVar].concat(st.variants)"
2c5d7b20 97 v-if="!v.noProblems"
bd76b456
BA
98 :value="v.id"
99 )
100 | {{ v.name }}
9b35f4a9 101 table#tProblems
bd76b456
BA
102 tr
103 th {{ st.tr["Variant"] }}
104 th {{ st.tr["Instructions"] }}
2f258c37 105 th {{ st.tr["Number"] }}
bd76b456 106 tr(
84fc0f02
BA
107 v-for="p in problems[onlyMine ? 'mine' : 'others']"
108 v-show="onlyMine || !selectedVar || p.vid == selectedVar"
bd76b456
BA
109 @click="setHrefPid(p)"
110 )
111 td {{ p.vname }}
2f258c37
BA
112 td {{ firstChars(p.instruction) }}
113 td {{ p.id }}
68e19a44 114 button#loadMoreBtn(
84fc0f02
BA
115 v-if="hasMore[onlyMine ? 'mine' : 'others']"
116 @click="loadMore(onlyMine ? 'mine' : 'others')"
68e19a44
BA
117 )
118 | {{ st.tr["Load more"] }}
910d631b 119 BaseGame(
b1e46b33 120 ref="basegame"
910d631b
BA
121 v-if="showOne"
122 :game="game"
910d631b 123 )
89021f18
BA
124</template>
125
126<script>
127import { store } from "@/store";
128import { ajax } from "@/utils/ajax";
129import { checkProblem } from "@/data/problemCheck";
a9e79351 130import params from "@/parameters";
956407c4 131import { getDiagram, replaceByDiag } from "@/utils/printDiagram";
bd76b456
BA
132import { processModalClick } from "@/utils/modalClick";
133import { ArrayFun } from "@/utils/array";
70c9745d 134import afterRawLoad from "@/utils/afterRawLoad";
604b951e 135import BaseGame from "@/components/BaseGame.vue";
89021f18
BA
136export default {
137 name: "my-problems",
604b951e 138 components: {
6808d7a1 139 BaseGame
604b951e 140 },
89021f18
BA
141 data: function() {
142 return {
604b951e 143 st: store.state,
89021f18
BA
144 emptyVar: {
145 vid: 0,
6808d7a1 146 vname: ""
89021f18 147 },
604b951e
BA
148 // Problem currently showed, or edited:
149 curproblem: {
150 id: 0, //used in case of edit
89021f18
BA
151 vid: 0,
152 fen: "",
604b951e 153 diag: "",
89021f18
BA
154 instruction: "",
155 solution: "",
6808d7a1 156 showSolution: false
89021f18 157 },
604b951e
BA
158 loadedVar: 0, //corresponding to loaded V
159 selectedVar: 0, //to filter problems based on variant
84fc0f02 160 problems: { "mine": [], "others": [] },
68e19a44 161 // timestamp of oldest showed problem:
84fc0f02 162 cursor: {
934f7f70
BA
163 mine: Number.MAX_SAFE_INTEGER,
164 others: Number.MAX_SAFE_INTEGER
84fc0f02 165 },
68e19a44 166 // hasMore == TRUE: a priori there could be more problems to load
934f7f70 167 hasMore: { mine: true, others: true },
84fc0f02 168 onlyMine: false,
604b951e 169 showOne: false,
89021f18 170 infoMsg: "",
956407c4 171 rulesContent: "",
604b951e 172 game: {
6808d7a1
BA
173 players: [{ name: "Problem" }, { name: "Problem" }],
174 mode: "analyze"
175 }
89021f18
BA
176 };
177 },
178 created: function() {
84fc0f02
BA
179 const pid = this.$route.query["id"];
180 if (!!pid) this.showProblem(pid);
181 else this.loadMore("others", () => { this.loadMore("mine"); });
89021f18 182 },
bd76b456 183 mounted: function() {
956407c4
BA
184 ["rulesDiv","newprobDiv"].forEach(eltName => {
185 document.getElementById(eltName)
186 .addEventListener("click", processModalClick)
187 });
bd76b456 188 },
604b951e
BA
189 watch: {
190 // st.variants changes only once, at loading from [] to [...]
6808d7a1 191 "st.variants": function() {
604b951e 192 // Set problems vname (either all are set or none)
84fc0f02
BA
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));
604b951e 196 },
6808d7a1 197 $route: function(to) {
bd76b456 198 const pid = to.query["id"];
84fc0f02
BA
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 }
6808d7a1 207 }
98fb976e 208 },
89021f18 209 methods: {
09d37571
BA
210 fenFocusIfOpened: function(event) {
211 if (event.target.checked) {
212 this.infoMsg = "";
213 document.getElementById("inputFen").focus();
214 }
215 },
ad16f839 216 adjustHeight: function(elt) {
3c24a27d 217 // https://stackoverflow.com/a/48460773
ad16f839 218 let t = document.querySelector("." + elt + "-edit");
3c24a27d 219 t.style.height = "";
ad16f839 220 t.style.height = (t.scrollHeight + 3) + "px";
3c24a27d 221 },
604b951e
BA
222 setVname: function(prob) {
223 prob.vname = this.st.variants.find(v => v.id == prob.vid).name;
224 },
68e19a44
BA
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 },
2f258c37
BA
255 firstChars: function(text) {
256 let preparedText = text
257 // Replace line jumps and <br> by spaces
6808d7a1
BA
258 .replace(/\n/g, " ")
259 .replace(/<br\/?>/g, " ")
2f258c37
BA
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)
6808d7a1 265 return preparedText.substr(0, 32) + "...";
2f258c37
BA
266 return preparedText;
267 },
604b951e 268 copyProblem: function(p1, p2) {
6808d7a1 269 for (let key in p1) p2[key] = p1[key];
604b951e 270 },
bd76b456
BA
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 },
604b951e
BA
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;
89021f18 290 },
604b951e
BA
291 parseHtml: function(txt) {
292 return !txt.match(/<[/a-zA-Z]+>/)
ad16f839
BA
293 ?
294 // No HTML tag
295 txt.replace(/\n\n/g, "<br/><div class='br'></div>")
296 .replace(/\n/g, "<br/>")
604b951e
BA
297 : txt;
298 },
299 changeVariant: function(prob) {
300 this.setVname(prob);
6808d7a1
BA
301 this.loadVariant(prob.vid, () => {
302 // Set FEN if possible (might not be correct yet)
303 if (V.IsGoodFen(prob.fen)) this.setDiagram(prob);
6f2f9437 304 else prob.diag = "";
6808d7a1 305 });
604b951e
BA
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);
32f6285e
BA
311 await import("@/variants/" + variant.name + ".js")
312 .then((vModule) => {
313 window.V = vModule[variant.name + "Rules"];
314 this.loadedVar = vid;
315 cb();
316 });
956407c4 317 this.rulesContent =
70c9745d
BA
318 afterRawLoad(
319 require(
320 "raw-loader!@/translations/rules/" + variant.name + "/" +
321 this.st.lang + ".pug"
322 ).default
323 ).replace(/(fen:)([^:]*):/g, replaceByDiag);
604b951e
BA
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);
6f2f9437 330 else prob.diag = "";
89021f18 331 },
604b951e
BA
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,
6808d7a1 337 orientation: parsedFen.turn
604b951e
BA
338 };
339 prob.diag = getDiagram(args);
89021f18 340 },
84fc0f02
BA
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); });
1d0bb60f 354 this.curproblem.showSolution = false; //in case of
84fc0f02
BA
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();
604b951e 382 },
01fba77c 383 gotoPrevNext: function(prob, dir) {
84fc0f02
BA
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]);
01fba77c
BA
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 }
84fc0f02 399 else alert(this.st.tr["No more problems"]);
d7c00f6a 400 },
f37790f7
BA
401 prepareNewProblem: function() {
402 this.resetCurProb();
ad16f839
BA
403 this.adjustHeight("instructions");
404 this.adjustHeight("solution");
f37790f7
BA
405 window.doClick("modalNewprob");
406 },
604b951e
BA
407 sendProblem: function() {
408 const error = checkProblem(this.curproblem);
6808d7a1 409 if (error) {
866842c3 410 alert(this.st.tr[error]);
6808d7a1
BA
411 return;
412 }
604b951e
BA
413 const edit = this.curproblem.id > 0;
414 this.infoMsg = "Processing... Please wait";
415 ajax(
416 "/problems",
417 edit ? "PUT" : "POST",
e57c4de4
BA
418 {
419 data: { prob: this.curproblem },
420 success: (ret) => {
421 if (edit) {
2c5d7b20
BA
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);
e57c4de4
BA
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;
2c5d7b20
BA
436 this.problems["mine"] =
437 [newProblem].concat(this.problems["mine"]);
e57c4de4
BA
438 }
439 document.getElementById("modalNewprob").checked = false;
440 this.infoMsg = "";
0cd02605 441 }
604b951e
BA
442 }
443 );
444 },
2c5d7b20 445 canIedit: function(puid) {
a9e79351 446 return params.devs.concat([puid]).includes(this.st.user.id);
2c5d7b20 447 },
604b951e 448 editProblem: function(prob) {
bec548e7
BA
449 // prob.diag might correspond to some other problem or be empty:
450 this.setDiagram(prob); //V is loaded at this stage
604b951e 451 this.copyProblem(prob, this.curproblem);
ad16f839
BA
452 this.adjustHeight("instructions");
453 this.adjustHeight("solution");
6808d7a1 454 window.doClick("modalNewprob");
604b951e
BA
455 },
456 deleteProblem: function(prob) {
6808d7a1 457 if (confirm(this.st.tr["Are you sure?"])) {
e57c4de4
BA
458 ajax(
459 "/problems",
460 "DELETE",
461 {
462 data: { id: prob.id },
463 success: () => {
84fc0f02
BA
464 const mode = prob.uid == (this.st.user.id ? "mine" : "others");
465 ArrayFun.remove(this.problems[mode], p => p.id == prob.id);
e57c4de4
BA
466 this.backToList();
467 }
468 }
469 );
bd76b456 470 }
68e19a44 471 },
84fc0f02 472 loadMore: function(mode, cb) {
68e19a44
BA
473 ajax(
474 "/problems",
475 "GET",
476 {
84fc0f02
BA
477 data: {
478 uid: this.st.user.id,
479 mode: mode,
480 cursor: this.cursor[mode]
481 },
68e19a44
BA
482 success: (res) => {
483 const L = res.problems.length;
484 if (L > 0) {
84fc0f02
BA
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");
68e19a44 489 this.decorate(res.problems);
01fba77c
BA
490 this.problems[mode] =
491 this.problems[mode].concat(res.problems)
3c24a27d 492 // TODO: problems are already sorted, would just need to insert
01fba77c
BA
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);
84fc0f02 498 } else this.hasMore[mode] = false;
01fba77c 499 if (!!cb) cb(L);
68e19a44
BA
500 }
501 }
502 );
6808d7a1
BA
503 }
504 }
89021f18
BA
505};
506</script>
507
b406466b
BA
508<style lang="sass">
509@import "@/styles/_board_squares_img.sass"
956407c4 510@import "@/styles/_rules.sass"
ad65975c
BA
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
b406466b
BA
518</style>
519
89021f18 520<style lang="sass" scoped>
bd76b456
BA
521[type="checkbox"].modal+div .card
522 max-width: 767px
523 max-height: 100%
910d631b 524
29d33c8a
BA
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
bd76b456
BA
536#inputFen
537 width: 100%
910d631b 538
bd76b456
BA
539textarea
540 width: 100%
3c24a27d
BA
541 &.instructions-edit
542 min-height: 70px
543 &.solution-edit
544 min-height: 100px
910d631b 545
bd76b456
BA
546#diagram
547 margin: 0 auto
548 max-width: 400px
910d631b 549
9b35f4a9
BA
550table#tProblems
551 max-height: 100%
552
68e19a44
BA
553button#loadMoreBtn
554 display: block
555 margin: 0 auto
556
bd76b456
BA
557#controls
558 margin: 0
559 width: 100%
560 text-align: center
561 & > *
562 margin: 0
2f258c37 563
ad65975c 564.oneInstructions
866842c3
BA
565 margin: 0
566 padding: 2px 5px
567 background-color: lightgreen
568
84fc0f02
BA
569#myProblems
570 display: inline-block
571
bd76b456 572#topPage
2f258c37 573 span.vname
bd76b456 574 font-weight: bold
feae89d3 575 padding-left: var(--universal-margin)
2f258c37
BA
576 span.uname
577 padding-left: var(--universal-margin)
bd76b456
BA
578 margin: 0 auto
579 & > .nomargin
580 margin: 0
581 & > .marginleft
582 margin: 0 0 0 15px
583
2f258c37
BA
584@media screen and (max-width: 767px)
585 #topPage
586 text-align: center
956407c4
BA
587
588a#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))
89021f18 595</style>