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