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