Do not show no-problems variants in problems select box
[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 v-if="!v.noProblems"
22 :value="v.id"
23 :selected="curproblem.vid==v.id"
24 )
25 | {{ v.name }}
26 fieldset
27 input#inputFen(
28 type="text"
29 placeholder="FEN"
30 v-model="curproblem.fen"
31 @input="trySetDiagram(curproblem)"
32 )
33 #diagram(v-html="curproblem.diag")
34 fieldset
35 textarea(
36 :placeholder="st.tr['Instructions']"
37 v-model="curproblem.instruction"
38 )
39 p(v-html="parseHtml(curproblem.instruction)")
40 fieldset
41 textarea(
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"] }}
47 #dialog.text-center {{ st.tr[infoMsg] }}
48 .row(v-if="showOne")
49 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
50 #topPage
51 .button-group(v-if="canIedit(curproblem.uid)")
52 button(@click="editProblem(curproblem)") {{ st.tr["Edit"] }}
53 button(@click="deleteProblem(curproblem)") {{ st.tr["Delete"] }}
54 span.vname {{ curproblem.vname }}
55 span.uname ({{ curproblem.uname }})
56 button.marginleft(@click="backToList()") {{ st.tr["Back to list"] }}
57 button.nomargin(@click="gotoPrevNext($event,curproblem,1)")
58 | {{ st.tr["Previous_p"] }}
59 button.nomargin(@click="gotoPrevNext($event,curproblem,-1)")
60 | {{ st.tr["Next_p"] }}
61 p.oneInstructions.clickable(
62 v-html="parseHtml(curproblem.instruction)"
63 @click="curproblem.showSolution=!curproblem.showSolution"
64 )
65 | {{ st.tr["Show solution"] }}
66 p(
67 v-show="curproblem.showSolution"
68 v-html="parseHtml(curproblem.solution)"
69 )
70 .row(v-else)
71 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
72 #controls
73 button#newProblem(@click="prepareNewProblem()")
74 | {{ st.tr["New problem"] }}
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 )
81 label(for="selectVariant") {{ st.tr["Variant"] }}
82 select#selectVariant(v-model="selectedVar")
83 option(
84 v-for="v in [emptyVar].concat(st.variants)"
85 v-if="!v.noProblems"
86 :value="v.id"
87 )
88 | {{ v.name }}
89 table#tProblems
90 tr
91 th {{ st.tr["Variant"] }}
92 th {{ st.tr["Instructions"] }}
93 th {{ st.tr["Number"] }}
94 tr(
95 v-for="p in problems[onlyMine ? 'mine' : 'others']"
96 v-show="onlyMine || !selectedVar || p.vid == selectedVar"
97 @click="setHrefPid(p)"
98 )
99 td {{ p.vname }}
100 td {{ firstChars(p.instruction) }}
101 td {{ p.id }}
102 button#loadMoreBtn(
103 v-if="hasMore[onlyMine ? 'mine' : 'others']"
104 @click="loadMore(onlyMine ? 'mine' : 'others')"
105 )
106 | {{ st.tr["Load more"] }}
107 BaseGame(
108 ref="basegame"
109 v-if="showOne"
110 :game="game"
111 )
112 </template>
113
114 <script>
115 import { store } from "@/store";
116 import { ajax } from "@/utils/ajax";
117 import { checkProblem } from "@/data/problemCheck";
118 import { getDiagram } from "@/utils/printDiagram";
119 import { processModalClick } from "@/utils/modalClick";
120 import { ArrayFun } from "@/utils/array";
121 import BaseGame from "@/components/BaseGame.vue";
122 export default {
123 name: "my-problems",
124 components: {
125 BaseGame
126 },
127 data: function() {
128 return {
129 st: store.state,
130 emptyVar: {
131 vid: 0,
132 vname: ""
133 },
134 // Problem currently showed, or edited:
135 curproblem: {
136 id: 0, //used in case of edit
137 vid: 0,
138 fen: "",
139 diag: "",
140 instruction: "",
141 solution: "",
142 showSolution: false
143 },
144 loadedVar: 0, //corresponding to loaded V
145 selectedVar: 0, //to filter problems based on variant
146 problems: { "mine": [], "others": [] },
147 // timestamp of oldest showed problem:
148 cursor: {
149 mine: Number.MAX_SAFE_INTEGER,
150 others: Number.MAX_SAFE_INTEGER
151 },
152 // hasMore == TRUE: a priori there could be more problems to load
153 hasMore: { mine: true, others: true },
154 onlyMine: false,
155 showOne: false,
156 infoMsg: "",
157 admins: [1], //hard-coded for now. TODO
158 game: {
159 players: [{ name: "Problem" }, { name: "Problem" }],
160 mode: "analyze"
161 }
162 };
163 },
164 created: function() {
165 const pid = this.$route.query["id"];
166 if (!!pid) this.showProblem(pid);
167 else this.loadMore("others", () => { this.loadMore("mine"); });
168 },
169 mounted: function() {
170 document.getElementById("newprobDiv")
171 .addEventListener("click", processModalClick);
172 },
173 watch: {
174 // st.variants changes only once, at loading from [] to [...]
175 "st.variants": function() {
176 // Set problems vname (either all are set or none)
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));
180 },
181 $route: function(to) {
182 const pid = to.query["id"];
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 }
191 }
192 },
193 methods: {
194 fenFocusIfOpened: function(event) {
195 if (event.target.checked) {
196 this.infoMsg = "";
197 document.getElementById("inputFen").focus();
198 }
199 },
200 setVname: function(prob) {
201 prob.vname = this.st.variants.find(v => v.id == prob.vid).name;
202 },
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 },
233 firstChars: function(text) {
234 let preparedText = text
235 // Replace line jumps and <br> by spaces
236 .replace(/\n/g, " ")
237 .replace(/<br\/?>/g, " ")
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)
243 return preparedText.substr(0, 32) + "...";
244 return preparedText;
245 },
246 copyProblem: function(p1, p2) {
247 for (let key in p1) p2[key] = p1[key];
248 },
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 },
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;
268 },
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);
276 this.loadVariant(prob.vid, () => {
277 // Set FEN if possible (might not be correct yet)
278 if (V.IsGoodFen(prob.fen)) this.setDiagram(prob);
279 else prob.diag = "";
280 });
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);
286 await import("@/variants/" + variant.name + ".js")
287 .then((vModule) => {
288 window.V = vModule[variant.name + "Rules"];
289 this.loadedVar = vid;
290 cb();
291 });
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);
298 else prob.diag = "";
299 },
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,
305 orientation: parsedFen.turn
306 };
307 prob.diag = getDiagram(args);
308 },
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); });
322 this.copyProblem(p, this.curproblem);
323 });
324 };
325 let p = undefined;
326 if (typeof p_id == "object") p = p_id;
327 else {
328 const problems = this.problems["others"].concat(this.problems["mine"]);
329 p = problems.find(prob => prob.id == p_id);
330 }
331 if (!p) {
332 // Bad luck: problem not in list. Get from server
333 ajax(
334 "/problems",
335 "GET",
336 {
337 data: { id: p_id },
338 success: (res) => {
339 this.decorate([res.problem], () => {
340 p = res.problem;
341 const mode = (p.uid == this.st.user.id ? "mine" : "others");
342 this.problems[mode].push(p);
343 processWhenWeHaveProb();
344 });
345 }
346 }
347 );
348 } else processWhenWeHaveProb();
349 },
350 gotoPrevNext: function(e, prob, dir) {
351 const mode = (this.onlyMine ? "mine" : "others");
352 const problems = this.problems[mode];
353 const startIdx = problems.findIndex(p => p.id == prob.id);
354 const nextIdx = startIdx + dir;
355 if (nextIdx >= 0 && nextIdx < problems.length)
356 this.setHrefPid(problems[nextIdx]);
357 else if (this.hasMore[mode]) this.loadMore(mode);
358 else alert(this.st.tr["No more problems"]);
359 },
360 prepareNewProblem: function() {
361 this.resetCurProb();
362 window.doClick("modalNewprob");
363 },
364 sendProblem: function() {
365 const error = checkProblem(this.curproblem);
366 if (error) {
367 alert(this.st.tr[error]);
368 return;
369 }
370 const edit = this.curproblem.id > 0;
371 this.infoMsg = "Processing... Please wait";
372 ajax(
373 "/problems",
374 edit ? "PUT" : "POST",
375 {
376 data: { prob: this.curproblem },
377 success: (ret) => {
378 if (edit) {
379 let editedP = this.problems["mine"]
380 .find(p => p.id == this.curproblem.id);
381 if (!editedP)
382 // I'm an admin and edit another user' problem
383 editedP = this.problems["others"]
384 .find(p => p.id == this.curproblem.id);
385 this.copyProblem(this.curproblem, editedP);
386 this.showProblem(editedP);
387 }
388 else {
389 let newProblem = Object.assign({}, this.curproblem);
390 newProblem.id = ret.id;
391 newProblem.uid = this.st.user.id;
392 newProblem.uname = this.st.user.name;
393 this.problems["mine"] =
394 [newProblem].concat(this.problems["mine"]);
395 }
396 document.getElementById("modalNewprob").checked = false;
397 this.infoMsg = "";
398 }
399 }
400 );
401 },
402 canIedit: function(puid) {
403 return this.admins.concat([puid]).includes(this.st.user.id);
404 },
405 editProblem: function(prob) {
406 // prob.diag might correspond to some other problem or be empty:
407 this.setDiagram(prob); //V is loaded at this stage
408 this.copyProblem(prob, this.curproblem);
409 window.doClick("modalNewprob");
410 },
411 deleteProblem: function(prob) {
412 if (confirm(this.st.tr["Are you sure?"])) {
413 ajax(
414 "/problems",
415 "DELETE",
416 {
417 data: { id: prob.id },
418 success: () => {
419 const mode = prob.uid == (this.st.user.id ? "mine" : "others");
420 ArrayFun.remove(this.problems[mode], p => p.id == prob.id);
421 this.backToList();
422 }
423 }
424 );
425 }
426 },
427 loadMore: function(mode, cb) {
428 ajax(
429 "/problems",
430 "GET",
431 {
432 data: {
433 uid: this.st.user.id,
434 mode: mode,
435 cursor: this.cursor[mode]
436 },
437 success: (res) => {
438 const L = res.problems.length;
439 if (L > 0) {
440 this.cursor[mode] = res.problems[L - 1].added;
441 // Remove potential duplicates:
442 const pids = this.problems[mode].map(p => p.id);
443 ArrayFun.remove(res.problems, p => pids.includes(p.id), "all");
444 this.decorate(res.problems);
445 this.problems[mode] = this.problems[mode].concat(res.problems);
446 } else this.hasMore[mode] = false;
447 if (!!cb) cb();
448 }
449 }
450 );
451 }
452 }
453 };
454 </script>
455
456 <style lang="sass" scoped>
457 [type="checkbox"].modal+div .card
458 max-width: 767px
459 max-height: 100%
460
461 #inputFen
462 width: 100%
463
464 textarea
465 width: 100%
466
467 #diagram
468 margin: 0 auto
469 max-width: 400px
470
471 table#tProblems
472 max-height: 100%
473
474 button#loadMoreBtn
475 display: block
476 margin: 0 auto
477
478 #controls
479 margin: 0
480 width: 100%
481 text-align: center
482 & > *
483 margin: 0
484
485 p.oneInstructions
486 margin: 0
487 padding: 2px 5px
488 background-color: lightgreen
489
490 #myProblems
491 display: inline-block
492
493 #topPage
494 span.vname
495 font-weight: bold
496 padding-left: var(--universal-margin)
497 span.uname
498 padding-left: var(--universal-margin)
499 margin: 0 auto
500 & > .nomargin
501 margin: 0
502 & > .marginleft
503 margin: 0 0 0 15px
504
505 @media screen and (max-width: 767px)
506 #topPage
507 text-align: center
508 </style>