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