Fix autoplay mode
[vchess.git] / client / src / views / Problems.vue
CommitLineData
89021f18
BA
1<template lang="pug">
2main
910d631b
BA
3 input#modalNewprob.modal(
4 type="checkbox"
09d37571 5 @change="fenFocusIfOpened($event)"
910d631b
BA
6 )
7 div#newprobDiv(
8 role="dialog"
9 data-checkbox="modalNewprob"
10 )
866842c3 11 .card
89021f18 12 label#closeNewprob.modal-close(for="modalNewprob")
604b951e
BA
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
604b951e
BA
26 input#inputFen(
27 type="text"
bd76b456 28 placeholder="FEN"
604b951e
BA
29 v-model="curproblem.fen"
30 @input="trySetDiagram(curproblem)"
31 )
bd76b456 32 #diagram(v-html="curproblem.diag")
604b951e 33 fieldset
bd76b456 34 textarea(
604b951e
BA
35 :placeholder="st.tr['Instructions']"
36 v-model="curproblem.instruction"
37 )
38 p(v-html="parseHtml(curproblem.instruction)")
39 fieldset
bd76b456 40 textarea(
604b951e
BA
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"] }}
89021f18 46 #dialog.text-center {{ st.tr[infoMsg] }}
604b951e 47 .row(v-if="showOne")
866842c3 48 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
bd76b456 49 #topPage
d7c00f6a
BA
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"] }}
2f258c37 53 span.vname {{ curproblem.vname }}
98fb976e 54 span.uname ({{ curproblem.uname }})
bd76b456 55 button.marginleft(@click="backToList()") {{ st.tr["Back to list"] }}
d7c00f6a
BA
56 button.nomargin(@click="gotoPrevNext($event,curproblem,1)")
57 | {{ st.tr["Previous"] }}
58 button.nomargin(@click="gotoPrevNext($event,curproblem,-1)")
feaf1bf7 59 | {{ st.tr["Next_p"] }}
866842c3 60 p.oneInstructions.clickable(
2f258c37 61 v-html="parseHtml(curproblem.instruction)"
bd76b456
BA
62 @click="curproblem.showSolution=!curproblem.showSolution"
63 )
604b951e
BA
64 | {{ st.tr["Show solution"] }}
65 p(
66 v-show="curproblem.showSolution"
67 v-html="parseHtml(curproblem.solution)"
68 )
69 .row(v-else)
89021f18 70 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
bd76b456 71 #controls
f37790f7 72 button#newProblem(@click="prepareNewProblem()")
bd76b456 73 | {{ st.tr["New problem"] }}
84fc0f02
BA
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 )
bd76b456
BA
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 }}
9b35f4a9 87 table#tProblems
bd76b456
BA
88 tr
89 th {{ st.tr["Variant"] }}
90 th {{ st.tr["Instructions"] }}
2f258c37 91 th {{ st.tr["Number"] }}
bd76b456 92 tr(
84fc0f02
BA
93 v-for="p in problems[onlyMine ? 'mine' : 'others']"
94 v-show="onlyMine || !selectedVar || p.vid == selectedVar"
bd76b456
BA
95 @click="setHrefPid(p)"
96 )
97 td {{ p.vname }}
2f258c37
BA
98 td {{ firstChars(p.instruction) }}
99 td {{ p.id }}
68e19a44 100 button#loadMoreBtn(
84fc0f02
BA
101 v-if="hasMore[onlyMine ? 'mine' : 'others']"
102 @click="loadMore(onlyMine ? 'mine' : 'others')"
68e19a44
BA
103 )
104 | {{ st.tr["Load more"] }}
910d631b 105 BaseGame(
b1e46b33 106 ref="basegame"
910d631b
BA
107 v-if="showOne"
108 :game="game"
910d631b 109 )
89021f18
BA
110</template>
111
112<script>
113import { store } from "@/store";
114import { ajax } from "@/utils/ajax";
115import { checkProblem } from "@/data/problemCheck";
116import { getDiagram } from "@/utils/printDiagram";
bd76b456
BA
117import { processModalClick } from "@/utils/modalClick";
118import { ArrayFun } from "@/utils/array";
604b951e 119import BaseGame from "@/components/BaseGame.vue";
89021f18
BA
120export default {
121 name: "my-problems",
604b951e 122 components: {
6808d7a1 123 BaseGame
604b951e 124 },
89021f18
BA
125 data: function() {
126 return {
604b951e 127 st: store.state,
89021f18
BA
128 emptyVar: {
129 vid: 0,
6808d7a1 130 vname: ""
89021f18 131 },
604b951e
BA
132 // Problem currently showed, or edited:
133 curproblem: {
134 id: 0, //used in case of edit
89021f18
BA
135 vid: 0,
136 fen: "",
604b951e 137 diag: "",
89021f18
BA
138 instruction: "",
139 solution: "",
6808d7a1 140 showSolution: false
89021f18 141 },
604b951e
BA
142 loadedVar: 0, //corresponding to loaded V
143 selectedVar: 0, //to filter problems based on variant
84fc0f02 144 problems: { "mine": [], "others": [] },
68e19a44 145 // timestamp of oldest showed problem:
84fc0f02 146 cursor: {
934f7f70
BA
147 mine: Number.MAX_SAFE_INTEGER,
148 others: Number.MAX_SAFE_INTEGER
84fc0f02 149 },
68e19a44 150 // hasMore == TRUE: a priori there could be more problems to load
934f7f70 151 hasMore: { mine: true, others: true },
84fc0f02 152 onlyMine: false,
604b951e 153 showOne: false,
89021f18 154 infoMsg: "",
604b951e 155 game: {
6808d7a1
BA
156 players: [{ name: "Problem" }, { name: "Problem" }],
157 mode: "analyze"
158 }
89021f18
BA
159 };
160 },
161 created: function() {
84fc0f02
BA
162 const pid = this.$route.query["id"];
163 if (!!pid) this.showProblem(pid);
164 else this.loadMore("others", () => { this.loadMore("mine"); });
89021f18 165 },
bd76b456 166 mounted: function() {
42a92848 167 document.getElementById("newprobDiv")
6808d7a1 168 .addEventListener("click", processModalClick);
bd76b456 169 },
604b951e
BA
170 watch: {
171 // st.variants changes only once, at loading from [] to [...]
6808d7a1 172 "st.variants": function() {
604b951e 173 // Set problems vname (either all are set or none)
84fc0f02
BA
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));
604b951e 177 },
6808d7a1 178 $route: function(to) {
bd76b456 179 const pid = to.query["id"];
84fc0f02
BA
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 }
6808d7a1 188 }
98fb976e 189 },
89021f18 190 methods: {
09d37571
BA
191 fenFocusIfOpened: function(event) {
192 if (event.target.checked) {
193 this.infoMsg = "";
194 document.getElementById("inputFen").focus();
195 }
196 },
604b951e
BA
197 setVname: function(prob) {
198 prob.vname = this.st.variants.find(v => v.id == prob.vid).name;
199 },
68e19a44
BA
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 },
2f258c37
BA
230 firstChars: function(text) {
231 let preparedText = text
232 // Replace line jumps and <br> by spaces
6808d7a1
BA
233 .replace(/\n/g, " ")
234 .replace(/<br\/?>/g, " ")
2f258c37
BA
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)
6808d7a1 240 return preparedText.substr(0, 32) + "...";
2f258c37
BA
241 return preparedText;
242 },
604b951e 243 copyProblem: function(p1, p2) {
6808d7a1 244 for (let key in p1) p2[key] = p1[key];
604b951e 245 },
bd76b456
BA
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 },
604b951e
BA
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;
89021f18 265 },
604b951e
BA
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);
6808d7a1
BA
273 this.loadVariant(prob.vid, () => {
274 // Set FEN if possible (might not be correct yet)
275 if (V.IsGoodFen(prob.fen)) this.setDiagram(prob);
6f2f9437 276 else prob.diag = "";
6808d7a1 277 });
604b951e
BA
278 },
279 loadVariant: async function(vid, cb) {
280 // Condition: vid is a valid variant ID
281 this.loadedVar = 0;
282 const variant = this.st.variants.find(v => v.id == vid);
32f6285e
BA
283 await import("@/variants/" + variant.name + ".js")
284 .then((vModule) => {
285 window.V = vModule[variant.name + "Rules"];
286 this.loadedVar = vid;
287 cb();
288 });
604b951e
BA
289 },
290 trySetDiagram: function(prob) {
291 // Problem edit: FEN could be wrong or incomplete,
292 // variant could not be ready, or not defined
293 if (prob.vid > 0 && this.loadedVar == prob.vid && V.IsGoodFen(prob.fen))
294 this.setDiagram(prob);
6f2f9437 295 else prob.diag = "";
89021f18 296 },
604b951e
BA
297 setDiagram: function(prob) {
298 // Condition: prob.fen is correct and global V is ready
299 const parsedFen = V.ParseFen(prob.fen);
300 const args = {
301 position: parsedFen.position,
6808d7a1 302 orientation: parsedFen.turn
604b951e
BA
303 };
304 prob.diag = getDiagram(args);
89021f18 305 },
84fc0f02
BA
306 showProblem: function(p_id) {
307 const processWhenWeHaveProb = () => {
308 this.loadVariant(p.vid, () => {
309 this.onlyMine = (p.uid == this.st.user.id);
310 // The FEN is already checked at this stage:
311 this.game.vname = p.vname;
312 this.game.mycolor = V.ParseFen(p.fen).turn; //diagram orientation
313 this.game.fenStart = p.fen;
314 this.game.fen = p.fen;
315 this.showOne = true;
316 // $nextTick to be sure $refs["basegame"] exists
317 this.$nextTick(() => {
318 this.$refs["basegame"].re_setVariables(this.game); });
319 this.copyProblem(p, this.curproblem);
320 });
321 };
322 let p = undefined;
323 if (typeof p_id == "object") p = p_id;
324 else {
325 const problems = this.problems["others"].concat(this.problems["mine"]);
326 p = problems.find(prob => prob.id == p_id);
327 }
328 if (!p) {
329 // Bad luck: problem not in list. Get from server
330 ajax(
331 "/problems",
332 "GET",
333 {
334 data: { id: p_id },
335 success: (res) => {
336 this.decorate([res.problem], () => {
337 p = res.problem;
338 const mode = (p.uid == this.st.user.id ? "mine" : "others");
339 this.problems[mode].push(p);
340 processWhenWeHaveProb();
341 });
342 }
343 }
344 );
345 } else processWhenWeHaveProb();
604b951e 346 },
d7c00f6a 347 gotoPrevNext: function(e, prob, dir) {
84fc0f02
BA
348 const mode = (this.onlyMine ? "mine" : "others");
349 const problems = this.problems[mode];
350 const startIdx = problems.findIndex(p => p.id == prob.id);
351 const nextIdx = startIdx + dir;
352 if (nextIdx >= 0 && nextIdx < problems.length)
353 this.setHrefPid(problems[nextIdx]);
354 else if (this.hasMore[mode]) this.loadMore(mode);
355 else alert(this.st.tr["No more problems"]);
d7c00f6a 356 },
f37790f7
BA
357 prepareNewProblem: function() {
358 this.resetCurProb();
359 window.doClick("modalNewprob");
360 },
604b951e
BA
361 sendProblem: function() {
362 const error = checkProblem(this.curproblem);
6808d7a1 363 if (error) {
866842c3 364 alert(this.st.tr[error]);
6808d7a1
BA
365 return;
366 }
604b951e
BA
367 const edit = this.curproblem.id > 0;
368 this.infoMsg = "Processing... Please wait";
369 ajax(
370 "/problems",
371 edit ? "PUT" : "POST",
e57c4de4
BA
372 {
373 data: { prob: this.curproblem },
374 success: (ret) => {
375 if (edit) {
970b6e20 376 let editedP = this.problems["mine"].find(p => p.id == this.curproblem.id);
e57c4de4
BA
377 this.copyProblem(this.curproblem, editedP);
378 this.showProblem(editedP);
379 }
380 else {
381 let newProblem = Object.assign({}, this.curproblem);
382 newProblem.id = ret.id;
383 newProblem.uid = this.st.user.id;
384 newProblem.uname = this.st.user.name;
84fc0f02 385 this.problems["mine"] = [newProblem].concat(this.problems["mine"]);
e57c4de4
BA
386 }
387 document.getElementById("modalNewprob").checked = false;
388 this.infoMsg = "";
0cd02605 389 }
604b951e
BA
390 }
391 );
392 },
393 editProblem: function(prob) {
bec548e7
BA
394 // prob.diag might correspond to some other problem or be empty:
395 this.setDiagram(prob); //V is loaded at this stage
604b951e 396 this.copyProblem(prob, this.curproblem);
6808d7a1 397 window.doClick("modalNewprob");
604b951e
BA
398 },
399 deleteProblem: function(prob) {
6808d7a1 400 if (confirm(this.st.tr["Are you sure?"])) {
e57c4de4
BA
401 ajax(
402 "/problems",
403 "DELETE",
404 {
405 data: { id: prob.id },
406 success: () => {
84fc0f02
BA
407 const mode = prob.uid == (this.st.user.id ? "mine" : "others");
408 ArrayFun.remove(this.problems[mode], p => p.id == prob.id);
e57c4de4
BA
409 this.backToList();
410 }
411 }
412 );
bd76b456 413 }
68e19a44 414 },
84fc0f02 415 loadMore: function(mode, cb) {
68e19a44
BA
416 ajax(
417 "/problems",
418 "GET",
419 {
84fc0f02
BA
420 data: {
421 uid: this.st.user.id,
422 mode: mode,
423 cursor: this.cursor[mode]
424 },
68e19a44
BA
425 success: (res) => {
426 const L = res.problems.length;
427 if (L > 0) {
84fc0f02
BA
428 this.cursor[mode] = res.problems[L - 1].added;
429 // Remove potential duplicates:
430 const pids = this.problems[mode].map(p => p.id);
431 ArrayFun.remove(res.problems, p => pids.includes(p.id), "all");
68e19a44 432 this.decorate(res.problems);
84fc0f02
BA
433 this.problems[mode] = this.problems[mode].concat(res.problems);
434 } else this.hasMore[mode] = false;
435 if (!!cb) cb();
68e19a44
BA
436 }
437 }
438 );
6808d7a1
BA
439 }
440 }
89021f18
BA
441};
442</script>
443
444<style lang="sass" scoped>
bd76b456
BA
445[type="checkbox"].modal+div .card
446 max-width: 767px
447 max-height: 100%
910d631b 448
bd76b456
BA
449#inputFen
450 width: 100%
910d631b 451
bd76b456
BA
452textarea
453 width: 100%
910d631b 454
bd76b456
BA
455#diagram
456 margin: 0 auto
457 max-width: 400px
910d631b 458
9b35f4a9
BA
459table#tProblems
460 max-height: 100%
461
68e19a44
BA
462button#loadMoreBtn
463 display: block
464 margin: 0 auto
465
bd76b456
BA
466#controls
467 margin: 0
468 width: 100%
469 text-align: center
470 & > *
471 margin: 0
2f258c37 472
866842c3
BA
473p.oneInstructions
474 margin: 0
475 padding: 2px 5px
476 background-color: lightgreen
477
84fc0f02
BA
478#myProblems
479 display: inline-block
480
bd76b456 481#topPage
2f258c37 482 span.vname
bd76b456 483 font-weight: bold
feae89d3 484 padding-left: var(--universal-margin)
2f258c37
BA
485 span.uname
486 padding-left: var(--universal-margin)
bd76b456
BA
487 margin: 0 auto
488 & > .nomargin
489 margin: 0
490 & > .marginleft
491 margin: 0 0 0 15px
492
2f258c37
BA
493@media screen and (max-width: 767px)
494 #topPage
495 text-align: center
89021f18 496</style>