Draft or user bio support (ready in Hall, TODO in Game)
[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
bd76b456 45 textarea(
604b951e
BA
46 :placeholder="st.tr['Instructions']"
47 v-model="curproblem.instruction"
48 )
49 p(v-html="parseHtml(curproblem.instruction)")
50 fieldset
bd76b456 51 textarea(
604b951e
BA
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"] }}
89021f18 57 #dialog.text-center {{ st.tr[infoMsg] }}
604b951e 58 .row(v-if="showOne")
866842c3 59 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
bd76b456 60 #topPage
2c5d7b20 61 .button-group(v-if="canIedit(curproblem.uid)")
d7c00f6a
BA
62 button(@click="editProblem(curproblem)") {{ st.tr["Edit"] }}
63 button(@click="deleteProblem(curproblem)") {{ st.tr["Delete"] }}
2f258c37 64 span.vname {{ curproblem.vname }}
98fb976e 65 span.uname ({{ curproblem.uname }})
bd76b456 66 button.marginleft(@click="backToList()") {{ st.tr["Back to list"] }}
01fba77c 67 button.nomargin(@click="gotoPrevNext(curproblem,1)")
d85f259c 68 | {{ st.tr["Previous_p"] }}
01fba77c 69 button.nomargin(@click="gotoPrevNext(curproblem,-1)")
feaf1bf7 70 | {{ st.tr["Next_p"] }}
866842c3 71 p.oneInstructions.clickable(
2f258c37 72 v-html="parseHtml(curproblem.instruction)"
bd76b456
BA
73 @click="curproblem.showSolution=!curproblem.showSolution"
74 )
604b951e
BA
75 | {{ st.tr["Show solution"] }}
76 p(
77 v-show="curproblem.showSolution"
78 v-html="parseHtml(curproblem.solution)"
79 )
80 .row(v-else)
89021f18 81 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
bd76b456 82 #controls
f37790f7 83 button#newProblem(@click="prepareNewProblem()")
bd76b456 84 | {{ st.tr["New problem"] }}
84fc0f02
BA
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 )
bd76b456
BA
91 label(for="selectVariant") {{ st.tr["Variant"] }}
92 select#selectVariant(v-model="selectedVar")
93 option(
94 v-for="v in [emptyVar].concat(st.variants)"
2c5d7b20 95 v-if="!v.noProblems"
bd76b456
BA
96 :value="v.id"
97 )
98 | {{ v.name }}
9b35f4a9 99 table#tProblems
bd76b456
BA
100 tr
101 th {{ st.tr["Variant"] }}
102 th {{ st.tr["Instructions"] }}
2f258c37 103 th {{ st.tr["Number"] }}
bd76b456 104 tr(
84fc0f02
BA
105 v-for="p in problems[onlyMine ? 'mine' : 'others']"
106 v-show="onlyMine || !selectedVar || p.vid == selectedVar"
bd76b456
BA
107 @click="setHrefPid(p)"
108 )
109 td {{ p.vname }}
2f258c37
BA
110 td {{ firstChars(p.instruction) }}
111 td {{ p.id }}
68e19a44 112 button#loadMoreBtn(
84fc0f02
BA
113 v-if="hasMore[onlyMine ? 'mine' : 'others']"
114 @click="loadMore(onlyMine ? 'mine' : 'others')"
68e19a44
BA
115 )
116 | {{ st.tr["Load more"] }}
910d631b 117 BaseGame(
b1e46b33 118 ref="basegame"
910d631b
BA
119 v-if="showOne"
120 :game="game"
910d631b 121 )
89021f18
BA
122</template>
123
124<script>
125import { store } from "@/store";
126import { ajax } from "@/utils/ajax";
127import { checkProblem } from "@/data/problemCheck";
a9e79351 128import params from "@/parameters";
956407c4 129import { getDiagram, replaceByDiag } from "@/utils/printDiagram";
bd76b456
BA
130import { processModalClick } from "@/utils/modalClick";
131import { ArrayFun } from "@/utils/array";
604b951e 132import BaseGame from "@/components/BaseGame.vue";
89021f18
BA
133export default {
134 name: "my-problems",
604b951e 135 components: {
6808d7a1 136 BaseGame
604b951e 137 },
89021f18
BA
138 data: function() {
139 return {
604b951e 140 st: store.state,
89021f18
BA
141 emptyVar: {
142 vid: 0,
6808d7a1 143 vname: ""
89021f18 144 },
604b951e
BA
145 // Problem currently showed, or edited:
146 curproblem: {
147 id: 0, //used in case of edit
89021f18
BA
148 vid: 0,
149 fen: "",
604b951e 150 diag: "",
89021f18
BA
151 instruction: "",
152 solution: "",
6808d7a1 153 showSolution: false
89021f18 154 },
604b951e
BA
155 loadedVar: 0, //corresponding to loaded V
156 selectedVar: 0, //to filter problems based on variant
84fc0f02 157 problems: { "mine": [], "others": [] },
68e19a44 158 // timestamp of oldest showed problem:
84fc0f02 159 cursor: {
934f7f70
BA
160 mine: Number.MAX_SAFE_INTEGER,
161 others: Number.MAX_SAFE_INTEGER
84fc0f02 162 },
68e19a44 163 // hasMore == TRUE: a priori there could be more problems to load
934f7f70 164 hasMore: { mine: true, others: true },
84fc0f02 165 onlyMine: false,
604b951e 166 showOne: false,
89021f18 167 infoMsg: "",
956407c4 168 rulesContent: "",
604b951e 169 game: {
6808d7a1
BA
170 players: [{ name: "Problem" }, { name: "Problem" }],
171 mode: "analyze"
172 }
89021f18
BA
173 };
174 },
175 created: function() {
84fc0f02
BA
176 const pid = this.$route.query["id"];
177 if (!!pid) this.showProblem(pid);
178 else this.loadMore("others", () => { this.loadMore("mine"); });
89021f18 179 },
bd76b456 180 mounted: function() {
956407c4
BA
181 ["rulesDiv","newprobDiv"].forEach(eltName => {
182 document.getElementById(eltName)
183 .addEventListener("click", processModalClick)
184 });
bd76b456 185 },
604b951e
BA
186 watch: {
187 // st.variants changes only once, at loading from [] to [...]
6808d7a1 188 "st.variants": function() {
604b951e 189 // Set problems vname (either all are set or none)
84fc0f02
BA
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));
604b951e 193 },
6808d7a1 194 $route: function(to) {
bd76b456 195 const pid = to.query["id"];
84fc0f02
BA
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 }
6808d7a1 204 }
98fb976e 205 },
89021f18 206 methods: {
09d37571
BA
207 fenFocusIfOpened: function(event) {
208 if (event.target.checked) {
209 this.infoMsg = "";
210 document.getElementById("inputFen").focus();
211 }
212 },
604b951e
BA
213 setVname: function(prob) {
214 prob.vname = this.st.variants.find(v => v.id == prob.vid).name;
215 },
68e19a44
BA
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 },
2f258c37
BA
246 firstChars: function(text) {
247 let preparedText = text
248 // Replace line jumps and <br> by spaces
6808d7a1
BA
249 .replace(/\n/g, " ")
250 .replace(/<br\/?>/g, " ")
2f258c37
BA
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)
6808d7a1 256 return preparedText.substr(0, 32) + "...";
2f258c37
BA
257 return preparedText;
258 },
604b951e 259 copyProblem: function(p1, p2) {
6808d7a1 260 for (let key in p1) p2[key] = p1[key];
604b951e 261 },
bd76b456
BA
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 },
604b951e
BA
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;
89021f18 281 },
604b951e
BA
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);
6808d7a1
BA
289 this.loadVariant(prob.vid, () => {
290 // Set FEN if possible (might not be correct yet)
291 if (V.IsGoodFen(prob.fen)) this.setDiagram(prob);
6f2f9437 292 else prob.diag = "";
6808d7a1 293 });
604b951e
BA
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);
32f6285e
BA
299 await import("@/variants/" + variant.name + ".js")
300 .then((vModule) => {
301 window.V = vModule[variant.name + "Rules"];
302 this.loadedVar = vid;
303 cb();
304 });
956407c4
BA
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);
604b951e
BA
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);
6f2f9437 324 else prob.diag = "";
89021f18 325 },
604b951e
BA
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,
6808d7a1 331 orientation: parsedFen.turn
604b951e
BA
332 };
333 prob.diag = getDiagram(args);
89021f18 334 },
84fc0f02
BA
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); });
1d0bb60f 348 this.curproblem.showSolution = false; //in case of
84fc0f02
BA
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();
604b951e 376 },
01fba77c 377 gotoPrevNext: function(prob, dir) {
84fc0f02
BA
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]);
01fba77c
BA
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 }
84fc0f02 393 else alert(this.st.tr["No more problems"]);
d7c00f6a 394 },
f37790f7
BA
395 prepareNewProblem: function() {
396 this.resetCurProb();
397 window.doClick("modalNewprob");
398 },
604b951e
BA
399 sendProblem: function() {
400 const error = checkProblem(this.curproblem);
6808d7a1 401 if (error) {
866842c3 402 alert(this.st.tr[error]);
6808d7a1
BA
403 return;
404 }
604b951e
BA
405 const edit = this.curproblem.id > 0;
406 this.infoMsg = "Processing... Please wait";
407 ajax(
408 "/problems",
409 edit ? "PUT" : "POST",
e57c4de4
BA
410 {
411 data: { prob: this.curproblem },
412 success: (ret) => {
413 if (edit) {
2c5d7b20
BA
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);
e57c4de4
BA
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;
2c5d7b20
BA
428 this.problems["mine"] =
429 [newProblem].concat(this.problems["mine"]);
e57c4de4
BA
430 }
431 document.getElementById("modalNewprob").checked = false;
432 this.infoMsg = "";
0cd02605 433 }
604b951e
BA
434 }
435 );
436 },
2c5d7b20 437 canIedit: function(puid) {
a9e79351 438 return params.devs.concat([puid]).includes(this.st.user.id);
2c5d7b20 439 },
604b951e 440 editProblem: function(prob) {
bec548e7
BA
441 // prob.diag might correspond to some other problem or be empty:
442 this.setDiagram(prob); //V is loaded at this stage
604b951e 443 this.copyProblem(prob, this.curproblem);
6808d7a1 444 window.doClick("modalNewprob");
604b951e
BA
445 },
446 deleteProblem: function(prob) {
6808d7a1 447 if (confirm(this.st.tr["Are you sure?"])) {
e57c4de4
BA
448 ajax(
449 "/problems",
450 "DELETE",
451 {
452 data: { id: prob.id },
453 success: () => {
84fc0f02
BA
454 const mode = prob.uid == (this.st.user.id ? "mine" : "others");
455 ArrayFun.remove(this.problems[mode], p => p.id == prob.id);
e57c4de4
BA
456 this.backToList();
457 }
458 }
459 );
bd76b456 460 }
68e19a44 461 },
84fc0f02 462 loadMore: function(mode, cb) {
68e19a44
BA
463 ajax(
464 "/problems",
465 "GET",
466 {
84fc0f02
BA
467 data: {
468 uid: this.st.user.id,
469 mode: mode,
470 cursor: this.cursor[mode]
471 },
68e19a44
BA
472 success: (res) => {
473 const L = res.problems.length;
474 if (L > 0) {
84fc0f02
BA
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");
68e19a44 479 this.decorate(res.problems);
01fba77c
BA
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);
84fc0f02 488 } else this.hasMore[mode] = false;
01fba77c 489 if (!!cb) cb(L);
68e19a44
BA
490 }
491 }
492 );
6808d7a1
BA
493 }
494 }
89021f18
BA
495};
496</script>
497
b406466b
BA
498<style lang="sass">
499@import "@/styles/_board_squares_img.sass"
956407c4 500@import "@/styles/_rules.sass"
b406466b
BA
501</style>
502
89021f18 503<style lang="sass" scoped>
bd76b456
BA
504[type="checkbox"].modal+div .card
505 max-width: 767px
506 max-height: 100%
910d631b 507
29d33c8a
BA
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
bd76b456
BA
519#inputFen
520 width: 100%
910d631b 521
bd76b456
BA
522textarea
523 width: 100%
910d631b 524
bd76b456
BA
525#diagram
526 margin: 0 auto
527 max-width: 400px
910d631b 528
9b35f4a9
BA
529table#tProblems
530 max-height: 100%
531
68e19a44
BA
532button#loadMoreBtn
533 display: block
534 margin: 0 auto
535
bd76b456
BA
536#controls
537 margin: 0
538 width: 100%
539 text-align: center
540 & > *
541 margin: 0
2f258c37 542
866842c3
BA
543p.oneInstructions
544 margin: 0
545 padding: 2px 5px
546 background-color: lightgreen
547
84fc0f02
BA
548#myProblems
549 display: inline-block
550
bd76b456 551#topPage
2f258c37 552 span.vname
bd76b456 553 font-weight: bold
feae89d3 554 padding-left: var(--universal-margin)
2f258c37
BA
555 span.uname
556 padding-left: var(--universal-margin)
bd76b456
BA
557 margin: 0 auto
558 & > .nomargin
559 margin: 0
560 & > .marginleft
561 margin: 0 0 0 15px
562
2f258c37
BA
563@media screen and (max-width: 767px)
564 #topPage
565 text-align: center
956407c4
BA
566
567a#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))
89021f18 574</style>