Implemented multi-move possibility in a moves list => better support for multi-moves...
[vchess.git] / client / src / views / Problems.vue
1 <template lang="pug">
2 main
3 input#modalNewprob.modal(
4 type="checkbox"
5 @change="infoMsg=''"
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"] }}
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("/problems", "GET", res => {
149 // Show newest problem first:
150 this.problems = res.problems.sort((p1, p2) => p2.added - p1.added);
151 if (this.st.variants.length > 0)
152 this.problems.forEach(p => this.setVname(p));
153 // Retrieve all problems' authors' names
154 let names = {};
155 this.problems.forEach(p => {
156 if (p.uid != this.st.user.id) names[p.uid] = "";
157 else p.uname = this.st.user.name;
158 });
159 const showOneIfPid = () => {
160 const pid = this.$route.query["id"];
161 if (pid) this.showProblem(this.problems.find(p => p.id == pid));
162 };
163 if (Object.keys(names).length > 0) {
164 ajax("/users", "GET", { ids: Object.keys(names).join(",") }, res2 => {
165 res2.users.forEach(u => {
166 names[u.id] = u.name;
167 });
168 this.problems.forEach(p => {
169 if (!p.uname)
170 p.uname = names[p.uid];
171 });
172 showOneIfPid();
173 });
174 } else showOneIfPid();
175 });
176 },
177 mounted: function() {
178 document
179 .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 setVname: function(prob) {
197 prob.vname = this.st.variants.find(v => v.id == prob.vid).name;
198 },
199 firstChars: function(text) {
200 let preparedText = text
201 // Replace line jumps and <br> by spaces
202 .replace(/\n/g, " ")
203 .replace(/<br\/?>/g, " ")
204 .replace(/<[^>]+>/g, "") //remove remaining HTML tags
205 .replace(/[ ]+/g, " ") //remove series of spaces by only one
206 .trim();
207 const maxLength = 32; //arbitrary...
208 if (preparedText.length > maxLength)
209 return preparedText.substr(0, 32) + "...";
210 return preparedText;
211 },
212 copyProblem: function(p1, p2) {
213 for (let key in p1) p2[key] = p1[key];
214 },
215 setHrefPid: function(p) {
216 // Change href => $route changes, watcher notices, call showProblem
217 const curHref = document.location.href;
218 document.location.href = curHref.split("?")[0] + "?id=" + p.id;
219 },
220 backToList: function() {
221 // Change href => $route change, watcher notices, reset showOne to false
222 document.location.href = document.location.href.split("?")[0];
223 },
224 resetCurProb: function() {
225 this.curproblem.id = 0;
226 this.curproblem.uid = 0;
227 this.curproblem.vid = "";
228 this.curproblem.vname = "";
229 this.curproblem.fen = "";
230 this.curproblem.diag = "";
231 this.curproblem.instruction = "";
232 this.curproblem.solution = "";
233 this.curproblem.showSolution = false;
234 },
235 parseHtml: function(txt) {
236 return !txt.match(/<[/a-zA-Z]+>/)
237 ? txt.replace(/\n/g, "<br/>") //no HTML tag
238 : txt;
239 },
240 changeVariant: function(prob) {
241 this.setVname(prob);
242 this.loadVariant(prob.vid, () => {
243 // Set FEN if possible (might not be correct yet)
244 if (V.IsGoodFen(prob.fen)) this.setDiagram(prob);
245 });
246 },
247 loadVariant: async function(vid, cb) {
248 // Condition: vid is a valid variant ID
249 this.loadedVar = 0;
250 const variant = this.st.variants.find(v => v.id == vid);
251 const vModule = await import("@/variants/" + variant.name + ".js");
252 window.V = vModule.VariantRules;
253 this.loadedVar = vid;
254 cb();
255 },
256 trySetDiagram: function(prob) {
257 // Problem edit: FEN could be wrong or incomplete,
258 // variant could not be ready, or not defined
259 if (prob.vid > 0 && this.loadedVar == prob.vid && V.IsGoodFen(prob.fen))
260 this.setDiagram(prob);
261 },
262 setDiagram: function(prob) {
263 // Condition: prob.fen is correct and global V is ready
264 const parsedFen = V.ParseFen(prob.fen);
265 const args = {
266 position: parsedFen.position,
267 orientation: parsedFen.turn
268 };
269 prob.diag = getDiagram(args);
270 },
271 displayProblem: function(p) {
272 return (
273 (!this.selectedVar || p.vid == this.selectedVar) &&
274 ((this.onlyMines && p.uid == this.st.user.id) ||
275 (!this.onlyMines && p.uid != this.st.user.id))
276 );
277 },
278 showProblem: function(p) {
279 this.loadVariant(p.vid, () => {
280 // The FEN is already checked at this stage:
281 this.game.vname = p.vname;
282 this.game.mycolor = V.ParseFen(p.fen).turn; //diagram orientation
283 this.game.fen = p.fen;
284 this.$set(this.game, "fenStart", p.fen);
285 this.copyProblem(p, this.curproblem);
286 this.showOne = true;
287 });
288 },
289 gotoPrevNext: function(e, prob, dir) {
290 const startIdx = this.problems.findIndex(p => p.id == prob.id);
291 let nextIdx = startIdx + dir;
292 while (
293 nextIdx >= 0 &&
294 nextIdx < this.problems.length &&
295 ((this.onlyMines && this.problems[nextIdx].uid != this.st.user.id) ||
296 (!this.onlyMines && this.problems[nextIdx].uid == this.st.user.id))
297 )
298 nextIdx += dir;
299 if (nextIdx >= 0 && nextIdx < this.problems.length)
300 this.setHrefPid(this.problems[nextIdx]);
301 else
302 alert(this.st.tr["No more problems"]);
303 },
304 prepareNewProblem: function() {
305 this.resetCurProb();
306 window.doClick("modalNewprob");
307 },
308 sendProblem: function() {
309 const error = checkProblem(this.curproblem);
310 if (error) {
311 alert(this.st.tr[error]);
312 return;
313 }
314 const edit = this.curproblem.id > 0;
315 this.infoMsg = "Processing... Please wait";
316 ajax(
317 "/problems",
318 edit ? "PUT" : "POST",
319 { prob: this.curproblem },
320 ret => {
321 if (edit) {
322 let editedP = this.problems.find(p => p.id == this.curproblem.id);
323 this.copyProblem(this.curproblem, editedP);
324 this.showProblem(editedP);
325 }
326 else {
327 let newProblem = Object.assign({}, this.curproblem);
328 newProblem.id = ret.id;
329 newProblem.uid = this.st.user.id;
330 newProblem.uname = this.st.user.name;
331 this.problems = [newProblem].concat(this.problems);
332 }
333 document.getElementById("modalNewprob").checked = false;
334 this.infoMsg = "";
335 }
336 );
337 },
338 editProblem: function(prob) {
339 // prob.diag might correspond to some other problem or be empty:
340 this.setDiagram(prob); //V is loaded at this stage
341 this.copyProblem(prob, this.curproblem);
342 window.doClick("modalNewprob");
343 },
344 deleteProblem: function(prob) {
345 if (confirm(this.st.tr["Are you sure?"])) {
346 ajax("/problems", "DELETE", { id: prob.id }, () => {
347 ArrayFun.remove(this.problems, p => p.id == prob.id);
348 this.backToList();
349 });
350 }
351 }
352 }
353 };
354 </script>
355
356 <style lang="sass" scoped>
357 [type="checkbox"].modal+div .card
358 max-width: 767px
359 max-height: 100%
360
361 #inputFen
362 width: 100%
363
364 textarea
365 width: 100%
366
367 #diagram
368 margin: 0 auto
369 max-width: 400px
370
371 table#tProblems
372 max-height: 100%
373
374 #controls
375 margin: 0
376 width: 100%
377 text-align: center
378 & > *
379 margin: 0
380
381 p.oneInstructions
382 margin: 0
383 padding: 2px 5px
384 background-color: lightgreen
385
386 #topPage
387 span.vname
388 font-weight: bold
389 padding-left: var(--universal-margin)
390 span.uname
391 padding-left: var(--universal-margin)
392 margin: 0 auto
393 & > .nomargin
394 margin: 0
395 & > .marginleft
396 margin: 0 0 0 15px
397
398 @media screen and (max-width: 767px)
399 #topPage
400 text-align: center
401 </style>