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