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