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