Fix user bio modal. Should work now
[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($event)"
48 v-model="curproblem.instruction"
49 )
50 p(v-html="parseHtml(curproblem.instruction)")
51 fieldset
52 textarea.solution-edit(
53 :placeholder="st.tr['Solution']"
54 @input="adjustHeight($event)"
55 v-model="curproblem.solution"
56 )
57 p(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 p.oneInstructions.clickable(
74 v-html="parseHtml(curproblem.instruction)"
75 @click="curproblem.showSolution=!curproblem.showSolution"
76 )
77 | {{ st.tr["Show solution"] }}
78 p(
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 BaseGame from "@/components/BaseGame.vue";
135 export default {
136 name: "my-problems",
137 components: {
138 BaseGame
139 },
140 data: function() {
141 return {
142 st: store.state,
143 emptyVar: {
144 vid: 0,
145 vname: ""
146 },
147 // Problem currently showed, or edited:
148 curproblem: {
149 id: 0, //used in case of edit
150 vid: 0,
151 fen: "",
152 diag: "",
153 instruction: "",
154 solution: "",
155 showSolution: false
156 },
157 loadedVar: 0, //corresponding to loaded V
158 selectedVar: 0, //to filter problems based on variant
159 problems: { "mine": [], "others": [] },
160 // timestamp of oldest showed problem:
161 cursor: {
162 mine: Number.MAX_SAFE_INTEGER,
163 others: Number.MAX_SAFE_INTEGER
164 },
165 // hasMore == TRUE: a priori there could be more problems to load
166 hasMore: { mine: true, others: true },
167 onlyMine: false,
168 showOne: false,
169 infoMsg: "",
170 rulesContent: "",
171 game: {
172 players: [{ name: "Problem" }, { name: "Problem" }],
173 mode: "analyze"
174 }
175 };
176 },
177 created: function() {
178 const pid = this.$route.query["id"];
179 if (!!pid) this.showProblem(pid);
180 else this.loadMore("others", () => { this.loadMore("mine"); });
181 },
182 mounted: function() {
183 ["rulesDiv","newprobDiv"].forEach(eltName => {
184 document.getElementById(eltName)
185 .addEventListener("click", processModalClick)
186 });
187 },
188 watch: {
189 // st.variants changes only once, at loading from [] to [...]
190 "st.variants": function() {
191 // Set problems vname (either all are set or none)
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));
195 },
196 $route: function(to) {
197 const pid = to.query["id"];
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 }
206 }
207 },
208 methods: {
209 fenFocusIfOpened: function(event) {
210 if (event.target.checked) {
211 this.infoMsg = "";
212 document.getElementById("inputFen").focus();
213 }
214 },
215 adjustHeight: function(e) {
216 // https://stackoverflow.com/a/48460773
217 let t = e.target;
218 t.style.height = "";
219 t.style.height = t.scrollHeight + "px";
220 },
221 setVname: function(prob) {
222 prob.vname = this.st.variants.find(v => v.id == prob.vid).name;
223 },
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 },
254 firstChars: function(text) {
255 let preparedText = text
256 // Replace line jumps and <br> by spaces
257 .replace(/\n/g, " ")
258 .replace(/<br\/?>/g, " ")
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)
264 return preparedText.substr(0, 32) + "...";
265 return preparedText;
266 },
267 copyProblem: function(p1, p2) {
268 for (let key in p1) p2[key] = p1[key];
269 },
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 },
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;
289 },
290 parseHtml: function(txt) {
291 return !txt.match(/<[/a-zA-Z]+>/)
292 ? txt.replace(/\n/g, "<br/>") //no HTML tag
293 : txt;
294 },
295 changeVariant: function(prob) {
296 this.setVname(prob);
297 this.loadVariant(prob.vid, () => {
298 // Set FEN if possible (might not be correct yet)
299 if (V.IsGoodFen(prob.fen)) this.setDiagram(prob);
300 else prob.diag = "";
301 });
302 },
303 loadVariant: async function(vid, cb) {
304 // Condition: vid is a valid variant ID
305 this.loadedVar = 0;
306 const variant = this.st.variants.find(v => v.id == vid);
307 await import("@/variants/" + variant.name + ".js")
308 .then((vModule) => {
309 window.V = vModule[variant.name + "Rules"];
310 this.loadedVar = vid;
311 cb();
312 });
313 // (AJAX) Request to get rules content (plain text, HTML)
314 this.rulesContent =
315 require(
316 "raw-loader!@/translations/rules/" +
317 variant.name + "/" +
318 this.st.lang + ".pug"
319 )
320 // Next two lines fix a weird issue after last update (2019-11)
321 .replace(/\\n/g, " ")
322 .replace(/\\"/g, '"')
323 .replace('module.exports = "', "")
324 .replace(/"$/, "")
325 .replace(/(fen:)([^:]*):/g, replaceByDiag);
326 },
327 trySetDiagram: function(prob) {
328 // Problem edit: FEN could be wrong or incomplete,
329 // variant could not be ready, or not defined
330 if (prob.vid > 0 && this.loadedVar == prob.vid && V.IsGoodFen(prob.fen))
331 this.setDiagram(prob);
332 else prob.diag = "";
333 },
334 setDiagram: function(prob) {
335 // Condition: prob.fen is correct and global V is ready
336 const parsedFen = V.ParseFen(prob.fen);
337 const args = {
338 position: parsedFen.position,
339 orientation: parsedFen.turn
340 };
341 prob.diag = getDiagram(args);
342 },
343 showProblem: function(p_id) {
344 const processWhenWeHaveProb = () => {
345 this.loadVariant(p.vid, () => {
346 this.onlyMine = (p.uid == this.st.user.id);
347 // The FEN is already checked at this stage:
348 this.game.vname = p.vname;
349 this.game.mycolor = V.ParseFen(p.fen).turn; //diagram orientation
350 this.game.fenStart = p.fen;
351 this.game.fen = p.fen;
352 this.showOne = true;
353 // $nextTick to be sure $refs["basegame"] exists
354 this.$nextTick(() => {
355 this.$refs["basegame"].re_setVariables(this.game); });
356 this.curproblem.showSolution = false; //in case of
357 this.copyProblem(p, this.curproblem);
358 });
359 };
360 let p = undefined;
361 if (typeof p_id == "object") p = p_id;
362 else {
363 const problems = this.problems["others"].concat(this.problems["mine"]);
364 p = problems.find(prob => prob.id == p_id);
365 }
366 if (!p) {
367 // Bad luck: problem not in list. Get from server
368 ajax(
369 "/problems",
370 "GET",
371 {
372 data: { id: p_id },
373 success: (res) => {
374 this.decorate([res.problem], () => {
375 p = res.problem;
376 const mode = (p.uid == this.st.user.id ? "mine" : "others");
377 this.problems[mode].push(p);
378 processWhenWeHaveProb();
379 });
380 }
381 }
382 );
383 } else processWhenWeHaveProb();
384 },
385 gotoPrevNext: function(prob, dir) {
386 const mode = (this.onlyMine ? "mine" : "others");
387 const problems = this.problems[mode];
388 const startIdx = problems.findIndex(p => p.id == prob.id);
389 const nextIdx = startIdx + dir;
390 if (nextIdx >= 0 && nextIdx < problems.length)
391 this.setHrefPid(problems[nextIdx]);
392 else if (this.hasMore[mode]) {
393 this.loadMore(
394 mode,
395 (nbProbs) => {
396 if (nbProbs > 0) this.gotoPrevNext(prob, dir);
397 else alert(this.st.tr["No more problems"]);
398 }
399 );
400 }
401 else alert(this.st.tr["No more problems"]);
402 },
403 prepareNewProblem: function() {
404 this.resetCurProb();
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 window.doClick("modalNewprob");
453 },
454 deleteProblem: function(prob) {
455 if (confirm(this.st.tr["Are you sure?"])) {
456 ajax(
457 "/problems",
458 "DELETE",
459 {
460 data: { id: prob.id },
461 success: () => {
462 const mode = prob.uid == (this.st.user.id ? "mine" : "others");
463 ArrayFun.remove(this.problems[mode], p => p.id == prob.id);
464 this.backToList();
465 }
466 }
467 );
468 }
469 },
470 loadMore: function(mode, cb) {
471 ajax(
472 "/problems",
473 "GET",
474 {
475 data: {
476 uid: this.st.user.id,
477 mode: mode,
478 cursor: this.cursor[mode]
479 },
480 success: (res) => {
481 const L = res.problems.length;
482 if (L > 0) {
483 this.cursor[mode] = res.problems[L - 1].added;
484 // Remove potential duplicates:
485 const pids = this.problems[mode].map(p => p.id);
486 ArrayFun.remove(res.problems, p => pids.includes(p.id), "all");
487 this.decorate(res.problems);
488 this.problems[mode] =
489 this.problems[mode].concat(res.problems)
490 // TODO: problems are already sorted, would just need to insert
491 // the current individual problem in list; more generally
492 // there is probably only one misclassified problem.
493 // (Unless the user navigated several times by URL to show a
494 // single problem...)
495 .sort((p1, p2) => p2.added - p1.added);
496 } else this.hasMore[mode] = false;
497 if (!!cb) cb(L);
498 }
499 }
500 );
501 }
502 }
503 };
504 </script>
505
506 <style lang="sass">
507 @import "@/styles/_board_squares_img.sass"
508 @import "@/styles/_rules.sass"
509 </style>
510
511 <style lang="sass" scoped>
512 [type="checkbox"].modal+div .card
513 max-width: 767px
514 max-height: 100%
515
516 #rulesDiv > .card
517 padding: 5px 0
518 max-width: 50%
519 max-height: 100%
520 @media screen and (max-width: 1500px)
521 max-width: 67%
522 @media screen and (max-width: 1024px)
523 max-width: 85%
524 @media screen and (max-width: 767px)
525 max-width: 100%
526
527 #inputFen
528 width: 100%
529
530 textarea
531 width: 100%
532 &.instructions-edit
533 min-height: 70px
534 &.solution-edit
535 min-height: 100px
536
537 #diagram
538 margin: 0 auto
539 max-width: 400px
540
541 table#tProblems
542 max-height: 100%
543
544 button#loadMoreBtn
545 display: block
546 margin: 0 auto
547
548 #controls
549 margin: 0
550 width: 100%
551 text-align: center
552 & > *
553 margin: 0
554
555 p.oneInstructions
556 margin: 0
557 padding: 2px 5px
558 background-color: lightgreen
559
560 #myProblems
561 display: inline-block
562
563 #topPage
564 span.vname
565 font-weight: bold
566 padding-left: var(--universal-margin)
567 span.uname
568 padding-left: var(--universal-margin)
569 margin: 0 auto
570 & > .nomargin
571 margin: 0
572 & > .marginleft
573 margin: 0 0 0 15px
574
575 @media screen and (max-width: 767px)
576 #topPage
577 text-align: center
578
579 a#variantNameInProblems
580 color: var(--card-fore-color)
581 text-align: center
582 font-weight: bold
583 font-size: calc(1rem * var(--heading-ratio))
584 line-height: 1.2
585 margin: calc(1.5 * var(--universal-margin))
586 </style>