Attempt to clarify installation instructions a little
[vchess.git] / client / src / views / Problems.vue
... / ...
CommitLineData
1<template lang="pug">
2main
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 | {{ curproblem.vdisp }}
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('instructions')"
48 v-model="curproblem.instruction"
49 )
50 .instructions(v-html="parseHtml(curproblem.instruction)")
51 fieldset
52 textarea.solution-edit(
53 :placeholder="st.tr['Solution']"
54 @input="adjustHeight('solution')"
55 v-model="curproblem.solution"
56 )
57 .solution(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.vdisp }}
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 .instructions.oneInstructions.clickable(
74 v-html="parseHtml(curproblem.instruction)"
75 @click="curproblem.showSolution=!curproblem.showSolution"
76 )
77 | {{ st.tr["Show solution"] }}
78 .solution(
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.vdisp }}
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>
127import { store } from "@/store";
128import { ajax } from "@/utils/ajax";
129import { checkProblem } from "@/data/problemCheck";
130import params from "@/parameters";
131import { getDiagram, replaceByDiag } from "@/utils/printDiagram";
132import { processModalClick } from "@/utils/modalClick";
133import { ArrayFun } from "@/utils/array";
134import afterRawLoad from "@/utils/afterRawLoad";
135import BaseGame from "@/components/BaseGame.vue";
136export default {
137 name: "my-problems",
138 components: {
139 BaseGame
140 },
141 data: function() {
142 return {
143 st: store.state,
144 emptyVar: { vid: 0 },
145 // Problem currently showed, or edited:
146 curproblem: {
147 id: 0, //used in case of edit
148 vid: 0,
149 fen: "",
150 diag: "",
151 instruction: "",
152 solution: "",
153 showSolution: false
154 },
155 loadedVar: 0, //corresponding to loaded V
156 selectedVar: 0, //to filter problems based on variant
157 problems: { "mine": [], "others": [] },
158 // timestamp of oldest showed problem:
159 cursor: {
160 mine: Number.MAX_SAFE_INTEGER,
161 others: Number.MAX_SAFE_INTEGER
162 },
163 // hasMore == TRUE: a priori there could be more problems to load
164 hasMore: { mine: true, others: true },
165 onlyMine: false,
166 showOne: false,
167 infoMsg: "",
168 rulesContent: "",
169 game: {
170 players: [{ name: "Problem" }, { name: "Problem" }],
171 mode: "analyze"
172 }
173 };
174 },
175 created: function() {
176 const pid = this.$route.query["id"];
177 if (!!pid) this.showProblem(pid);
178 else this.loadMore("others", () => { this.loadMore("mine"); });
179 },
180 mounted: function() {
181 ["rulesDiv","newprobDiv"].forEach(eltName => {
182 document.getElementById(eltName)
183 .addEventListener("click", processModalClick)
184 });
185 },
186 watch: {
187 // st.variants changes only once, at loading from [] to [...]
188 "st.variants": function() {
189 // Set problems vname (either all are set or none)
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));
193 },
194 $route: function(to) {
195 const pid = to.query["id"];
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 }
204 }
205 },
206 methods: {
207 fenFocusIfOpened: function(event) {
208 if (event.target.checked) {
209 this.infoMsg = "";
210 document.getElementById("inputFen").focus();
211 }
212 },
213 adjustHeight: function(elt) {
214 // https://stackoverflow.com/a/48460773
215 let t = document.querySelector("." + elt + "-edit");
216 t.style.height = "";
217 t.style.height = (t.scrollHeight + 3) + "px";
218 },
219 setVname: function(prob) {
220 const variant = this.st.variants.find(v => v.id == prob.vid);
221 prob.vname = variant.name;
222 prob.vdisp = variant.display;
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 }
253 else if (!!callback) callback();
254 },
255 firstChars: function(text) {
256 let preparedText = text
257 // Replace line jumps and <br> by spaces
258 .replace(/\n/g, " ")
259 .replace(/<br\/?>/g, " ")
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)
265 return preparedText.substr(0, 32) + "...";
266 return preparedText;
267 },
268 copyProblem: function(p1, p2) {
269 for (let key in p1) p2[key] = p1[key];
270 },
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 },
280 resetCurProb: function() {
281 this.curproblem.id = 0;
282 this.curproblem.uid = 0;
283 this.curproblem.vid = "";
284 this.curproblem.vname = "";
285 this.curproblem.vdisp = "";
286 this.curproblem.fen = "";
287 this.curproblem.diag = "";
288 this.curproblem.instruction = "";
289 this.curproblem.solution = "";
290 this.curproblem.showSolution = false;
291 },
292 parseHtml: function(txt) {
293 return !txt.match(/<[/a-zA-Z]+>/)
294 ?
295 // No HTML tag
296 txt.replace(/\n\n/g, "<br/><div class='br'></div>")
297 .replace(/\n/g, "<br/>")
298 : txt;
299 },
300 changeVariant: function(prob) {
301 this.setVname(prob);
302 this.loadVariant(prob.vid, () => {
303 // Set FEN if possible (might not be correct yet)
304 if (V.IsGoodFen(prob.fen)) this.setDiagram(prob);
305 else prob.diag = "";
306 });
307 },
308 loadVariant: async function(vid, cb) {
309 // Condition: vid is a valid variant ID
310 this.loadedVar = 0;
311 const variant = this.st.variants.find(v => v.id == vid);
312 await import("@/variants/" + variant.name + ".js")
313 .then((vModule) => {
314 window.V = vModule[variant.name + "Rules"];
315 this.loadedVar = vid;
316 cb();
317 });
318 this.rulesContent =
319 afterRawLoad(
320 require(
321 "raw-loader!@/translations/rules/" + variant.name + "/" +
322 this.st.lang + ".pug"
323 ).default
324 ).replace(/(fen:)([^:]*):/g, replaceByDiag);
325 },
326 trySetDiagram: function(prob) {
327 // Problem edit: FEN could be wrong or incomplete,
328 // variant could not be ready, or not defined
329 if (prob.vid > 0 && this.loadedVar == prob.vid && V.IsGoodFen(prob.fen))
330 this.setDiagram(prob);
331 else prob.diag = "";
332 },
333 setDiagram: function(prob) {
334 // Condition: prob.fen is correct and global V is ready
335 const parsedFen = V.ParseFen(prob.fen);
336 const args = {
337 position: parsedFen.position,
338 orientation: parsedFen.turn
339 };
340 prob.diag = getDiagram(args);
341 },
342 showProblem: function(p_id) {
343 const processWhenWeHaveProb = () => {
344 this.loadVariant(p.vid, () => {
345 this.onlyMine = (p.uid == this.st.user.id);
346 // The FEN is already checked at this stage:
347 this.game.vname = p.vname;
348 this.game.mycolor = V.ParseFen(p.fen).turn; //diagram orientation
349 this.game.fenStart = p.fen;
350 this.game.fen = p.fen;
351 this.showOne = true;
352 // $nextTick to be sure $refs["basegame"] exists
353 this.$nextTick(() => {
354 this.$refs["basegame"].re_setVariables(this.game); });
355 this.curproblem.showSolution = false; //in case of
356 this.copyProblem(p, this.curproblem);
357 });
358 };
359 let p = undefined;
360 if (typeof p_id == "object") p = p_id;
361 else {
362 const problems = this.problems["others"].concat(this.problems["mine"]);
363 p = problems.find(prob => prob.id == p_id);
364 }
365 if (!p) {
366 // Bad luck: problem not in list. Get from server
367 ajax(
368 "/problems",
369 "GET",
370 {
371 data: { id: p_id },
372 success: (res) => {
373 this.decorate([res.problem], () => {
374 p = res.problem;
375 const mode = (p.uid == this.st.user.id ? "mine" : "others");
376 this.problems[mode].push(p);
377 processWhenWeHaveProb();
378 });
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 this.adjustHeight("instructions");
406 this.adjustHeight("solution");
407 window.doClick("modalNewprob");
408 },
409 sendProblem: function() {
410 const error = checkProblem(this.curproblem);
411 if (error) {
412 alert(this.st.tr[error]);
413 return;
414 }
415 const edit = this.curproblem.id > 0;
416 this.infoMsg = "Processing... Please wait";
417 ajax(
418 "/problems",
419 edit ? "PUT" : "POST",
420 {
421 data: { prob: this.curproblem },
422 success: (ret) => {
423 if (edit) {
424 let editedP = this.problems["mine"]
425 .find(p => p.id == this.curproblem.id);
426 if (!editedP)
427 // I'm an admin and edit another user' problem
428 editedP = this.problems["others"]
429 .find(p => p.id == this.curproblem.id);
430 this.copyProblem(this.curproblem, editedP);
431 this.showProblem(editedP);
432 }
433 else {
434 let newProblem = Object.assign({}, this.curproblem);
435 newProblem.id = ret.id;
436 newProblem.uid = this.st.user.id;
437 newProblem.uname = this.st.user.name;
438 this.problems["mine"] =
439 [newProblem].concat(this.problems["mine"]);
440 }
441 document.getElementById("modalNewprob").checked = false;
442 this.infoMsg = "";
443 }
444 }
445 );
446 },
447 canIedit: function(puid) {
448 return params.devs.concat([puid]).includes(this.st.user.id);
449 },
450 editProblem: function(prob) {
451 // prob.diag might correspond to some other problem or be empty:
452 this.setDiagram(prob); //V is loaded at this stage
453 this.copyProblem(prob, this.curproblem);
454 this.adjustHeight("instructions");
455 this.adjustHeight("solution");
456 window.doClick("modalNewprob");
457 },
458 deleteProblem: function(prob) {
459 if (confirm(this.st.tr["Are you sure?"])) {
460 ajax(
461 "/problems",
462 "DELETE",
463 {
464 data: { id: prob.id },
465 success: () => {
466 const mode = prob.uid == (this.st.user.id ? "mine" : "others");
467 ArrayFun.remove(this.problems[mode], p => p.id == prob.id);
468 this.backToList();
469 }
470 }
471 );
472 }
473 },
474 loadMore: function(mode, cb) {
475 ajax(
476 "/problems",
477 "GET",
478 {
479 data: {
480 uid: this.st.user.id,
481 mode: mode,
482 cursor: this.cursor[mode]
483 },
484 success: (res) => {
485 const L = res.problems.length;
486 if (L > 0) {
487 this.cursor[mode] = res.problems[L - 1].added;
488 // Remove potential duplicates:
489 const pids = this.problems[mode].map(p => p.id);
490 ArrayFun.remove(res.problems, p => pids.includes(p.id), "all");
491 this.decorate(res.problems);
492 this.problems[mode] =
493 this.problems[mode].concat(res.problems)
494 // TODO: problems are already sorted, would just need to insert
495 // the current individual problem in list; more generally
496 // there is probably only one misclassified problem.
497 // (Unless the user navigated several times by URL to show a
498 // single problem...)
499 .sort((p1, p2) => p2.added - p1.added);
500 }
501 else this.hasMore[mode] = false;
502 if (!!cb) cb(L);
503 }
504 }
505 );
506 }
507 }
508};
509</script>
510
511<style lang="sass">
512@import "@/styles/_board_squares_img.sass"
513@import "@/styles/_rules.sass"
514.instructions, .solution
515 margin: 0 var(--universal-margin)
516 p, ul, ol, pre, table, h3, h4, h5, h6, blockquote
517 margin: var(--universal-margin) 0
518 .br
519 display: block
520 margin: 10px 0
521</style>
522
523<style lang="sass" scoped>
524[type="checkbox"].modal+div .card
525 max-width: 767px
526 max-height: 100%
527
528#rulesDiv > .card
529 padding: 5px 0
530 max-width: 50%
531 max-height: 100%
532 @media screen and (max-width: 1500px)
533 max-width: 67%
534 @media screen and (max-width: 1024px)
535 max-width: 85%
536 @media screen and (max-width: 767px)
537 max-width: 100%
538
539#inputFen
540 width: 100%
541
542textarea
543 width: 100%
544 &.instructions-edit
545 min-height: 70px
546 &.solution-edit
547 min-height: 100px
548
549#diagram
550 margin: 0 auto
551 max-width: 400px
552
553table#tProblems
554 max-height: 100%
555
556button#loadMoreBtn
557 display: block
558 margin: 0 auto
559
560#controls
561 margin: 0
562 width: 100%
563 text-align: center
564 & > *
565 margin: 0
566
567.oneInstructions
568 margin: 0
569 padding: 2px 5px
570 background-color: lightgreen
571
572#myProblems
573 display: inline-block
574
575#topPage
576 span.vdisp
577 font-weight: bold
578 padding-left: var(--universal-margin)
579 span.uname
580 padding-left: var(--universal-margin)
581 margin: 0 auto
582 & > .nomargin
583 margin: 0
584 & > .marginleft
585 margin: 0 0 0 15px
586
587@media screen and (max-width: 767px)
588 #topPage
589 text-align: center
590
591a#variantNameInProblems
592 color: var(--card-fore-color)
593 text-align: center
594 font-weight: bold
595 font-size: calc(1rem * var(--heading-ratio))
596 line-height: 1.2
597 margin: calc(1.5 * var(--universal-margin))
598</style>