Sort problems by datetime
[vchess.git] / client / src / views / Problems.vue
1 <template lang="pug">
2 main
3 input#modalNewprob.modal(type="checkbox" @change="infoMsg=''")
4 div#newprobDiv(role="dialog" data-checkbox="modalNewprob")
5 .card(@keyup.enter="sendProblem()")
6 label#closeNewprob.modal-close(for="modalNewprob")
7 fieldset
8 label(for="selectVariant") {{ st.tr["Variant"] }}
9 select#selectVariant(
10 v-model="curproblem.vid"
11 @change="changeVariant(curproblem)"
12 )
13 option(
14 v-for="v in [emptyVar].concat(st.variants)"
15 :value="v.id"
16 :selected="curproblem.vid==v.id"
17 )
18 | {{ v.name }}
19 fieldset
20 input#inputFen(
21 type="text"
22 placeholder="FEN"
23 v-model="curproblem.fen"
24 @input="trySetDiagram(curproblem)"
25 )
26 #diagram(v-html="curproblem.diag")
27 fieldset
28 textarea(
29 :placeholder="st.tr['Instructions']"
30 v-model="curproblem.instruction"
31 )
32 p(v-html="parseHtml(curproblem.instruction)")
33 fieldset
34 textarea(
35 :placeholder="st.tr['Solution']"
36 v-model="curproblem.solution"
37 )
38 p(v-html="parseHtml(curproblem.solution)")
39 button(@click="sendProblem()") {{ st.tr["Send"] }}
40 #dialog.text-center {{ st.tr[infoMsg] }}
41 .row(v-if="showOne")
42 .col-sm-12.col-md-10.col-md-offset-2
43 #topPage
44 span.vname {{ curproblem.vname }}
45 span.uname ({{ curproblem.uname }})
46 button.marginleft(@click="backToList()") {{ st.tr["Back to list"] }}
47 button.nomargin(
48 v-if="st.user.id == curproblem.uid"
49 @click="editProblem(curproblem)"
50 )
51 | {{ st.tr["Edit"] }}
52 button.nomargin(
53 v-if="st.user.id == curproblem.uid"
54 @click="deleteProblem(curproblem)"
55 )
56 | {{ st.tr["Delete"] }}
57 p.clickable(
58 v-html="parseHtml(curproblem.instruction)"
59 @click="curproblem.showSolution=!curproblem.showSolution"
60 )
61 | {{ st.tr["Show solution"] }}
62 p(
63 v-show="curproblem.showSolution"
64 v-html="parseHtml(curproblem.solution)"
65 )
66 .row(v-else)
67 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
68 #controls
69 button#newProblem(onClick="doClick('modalNewprob')")
70 | {{ st.tr["New problem"] }}
71 label(for="checkboxMine") {{ st.tr["My problems"] }}
72 input#checkboxMine(
73 type="checkbox"
74 v-model="onlyMines"
75 )
76 label(for="selectVariant") {{ st.tr["Variant"] }}
77 select#selectVariant(v-model="selectedVar")
78 option(
79 v-for="v in [emptyVar].concat(st.variants)"
80 :value="v.id"
81 )
82 | {{ v.name }}
83 table
84 tr
85 th {{ st.tr["Variant"] }}
86 th {{ st.tr["Instructions"] }}
87 th {{ st.tr["Number"] }}
88 tr(
89 v-for="p in sortedProblems"
90 v-show="displayProblem(p)"
91 @click="setHrefPid(p)"
92 )
93 td {{ p.vname }}
94 td {{ firstChars(p.instruction) }}
95 td {{ p.id }}
96 BaseGame(v-if="showOne" :game="game" :vr="vr")
97 </template>
98
99 <script>
100 import { store } from "@/store";
101 import { ajax } from "@/utils/ajax";
102 import { checkProblem } from "@/data/problemCheck";
103 import { getDiagram } from "@/utils/printDiagram";
104 import { processModalClick } from "@/utils/modalClick";
105 import { ArrayFun } from "@/utils/array";
106 import BaseGame from "@/components/BaseGame.vue";
107 export default {
108 name: "my-problems",
109 components: {
110 BaseGame,
111 },
112 data: function() {
113 return {
114 st: store.state,
115 emptyVar: {
116 vid: 0,
117 vname: "",
118 },
119 // Problem currently showed, or edited:
120 curproblem: {
121 id: 0, //used in case of edit
122 vid: 0,
123 fen: "",
124 diag: "",
125 instruction: "",
126 solution: "",
127 showSolution: false,
128 },
129 loadedVar: 0, //corresponding to loaded V
130 selectedVar: 0, //to filter problems based on variant
131 problems: [],
132 onlyMines: false,
133 showOne: false,
134 infoMsg: "",
135 vr: null, //"variant rules" object initialized from FEN
136 game: {
137 players:[{name:"Problem"},{name:"Problem"}],
138 mode: "analyze",
139 },
140 };
141 },
142 created: function() {
143 ajax("/problems", "GET", (res) => {
144 this.problems = res.problems;
145 if (this.st.variants.length > 0)
146 this.problems.forEach(p => this.setVname(p));
147 // Retrieve all problems' authors' names
148 let names = {};
149 this.problems.forEach(p => {
150 if (p.uid != this.st.user.id)
151 names[p.uid] = ""; //unknwon for now
152 else
153 p.uname = this.st.user.name;
154 });
155 const showOneIfPid = () => {
156 const pid = this.$route.query["id"];
157 if (!!pid)
158 this.showProblem(this.problems.find(p => p.id == pid));
159 };
160 if (Object.keys(names).length > 0)
161 {
162 ajax("/users",
163 "GET",
164 { ids: Object.keys(names).join(",") },
165 res2 => {
166 res2.users.forEach(u => {names[u.id] = u.name});
167 this.problems.forEach(p => p.uname = names[p.uid]);
168 showOneIfPid();
169 }
170 );
171 }
172 else
173 showOneIfPid();
174 });
175 },
176 mounted: function() {
177 document.getElementById("newprobDiv").addEventListener("click", processModalClick);
178 },
179 watch: {
180 // st.variants changes only once, at loading from [] to [...]
181 "st.variants": function(variantArray) {
182 // Set problems vname (either all are set or none)
183 if (this.problems.length > 0 && this.problems[0].vname == "")
184 this.problems.forEach(p => this.setVname(p));
185 },
186 "$route": function(to, from) {
187 const pid = to.query["id"];
188 if (!!pid)
189 this.showProblem(this.problems.find(p => p.id == pid));
190 else
191 this.showOne = false
192 },
193 },
194 computed: {
195 sortedProblems: function() {
196 // Newest first:
197 return this.problems.sort( (p1,p2) => p2.added - p1.added);
198 },
199 },
200 methods: {
201 setVname: function(prob) {
202 prob.vname = this.st.variants.find(v => v.id == prob.vid).name;
203 },
204 firstChars: function(text) {
205 let preparedText = text
206 // Replace line jumps and <br> by spaces
207 .replace(/\n/g, " " )
208 .replace(/<br\/?>/g, " " )
209 .replace(/<[^>]+>/g, "") //remove remaining HTML tags
210 .replace(/[ ]+/g, " ") //remove series of spaces by only one
211 .trim();
212 const maxLength = 32; //arbitrary...
213 if (preparedText.length > maxLength)
214 return preparedText.substr(0,32) + "...";
215 return preparedText;
216 },
217 copyProblem: function(p1, p2) {
218 for (let key in p1)
219 p2[key] = p1[key];
220 },
221 setHrefPid: function(p) {
222 // Change href => $route changes, watcher notices, call showProblem
223 const curHref = document.location.href;
224 document.location.href = curHref.split("?")[0] + "?id=" + p.id;
225 },
226 backToList: function() {
227 // Change href => $route change, watcher notices, reset showOne to false
228 document.location.href = document.location.href.split("?")[0];
229 },
230 resetCurProb: function() {
231 this.curproblem.id = 0;
232 this.curproblem.uid = 0;
233 this.curproblem.vid = "";
234 this.curproblem.vname = "";
235 this.curproblem.fen = "";
236 this.curproblem.diag = "";
237 this.curproblem.instruction = "";
238 this.curproblem.solution = "";
239 this.curproblem.showSolution = false;
240 },
241 parseHtml: function(txt) {
242 return !txt.match(/<[/a-zA-Z]+>/)
243 ? txt.replace(/\n/g, "<br/>") //no HTML tag
244 : txt;
245 },
246 changeVariant: function(prob) {
247 this.setVname(prob);
248 this.loadVariant(
249 prob.vid,
250 () => {
251 // Set FEN if possible (might not be correct yet)
252 if (V.IsGoodFen(prob.fen))
253 this.setDiagram(prob);
254 }
255 );
256 },
257 loadVariant: async function(vid, cb) {
258 // Condition: vid is a valid variant ID
259 this.loadedVar = 0;
260 const variant = this.st.variants.find(v => v.id == vid);
261 const vModule = await import("@/variants/" + variant.name + ".js");
262 window.V = vModule.VariantRules;
263 this.loadedVar = vid;
264 cb();
265 },
266 trySetDiagram: function(prob) {
267 // Problem edit: FEN could be wrong or incomplete,
268 // variant could not be ready, or not defined
269 if (prob.vid > 0 && this.loadedVar == prob.vid && V.IsGoodFen(prob.fen))
270 this.setDiagram(prob);
271 },
272 setDiagram: function(prob) {
273 // Condition: prob.fen is correct and global V is ready
274 const parsedFen = V.ParseFen(prob.fen);
275 const args = {
276 position: parsedFen.position,
277 orientation: parsedFen.turn,
278 };
279 prob.diag = getDiagram(args);
280 },
281 displayProblem: function(p) {
282 return ((this.selectedVar == 0 || p.vid == this.selectedVar) &&
283 ((this.onlyMines && p.uid == this.st.user.id)
284 || (!this.onlyMines && p.uid != this.st.user.id)));
285 },
286 showProblem: function(p) {
287 this.loadVariant(
288 p.vid,
289 () => {
290 // The FEN is already checked at this stage:
291 this.vr = new V(p.fen);
292 this.game.vname = p.vname;
293 this.game.mycolor = this.vr.turn; //diagram orientation
294 this.game.fen = p.fen;
295 this.$set(this.game, "fenStart", p.fen);
296 this.copyProblem(p, this.curproblem);
297 this.showOne = true;
298 }
299 );
300 },
301 sendProblem: function() {
302 const error = checkProblem(this.curproblem);
303 if (!!error)
304 return alert(error);
305 const edit = this.curproblem.id > 0;
306 this.infoMsg = "Processing... Please wait";
307 ajax(
308 "/problems",
309 edit ? "PUT" : "POST",
310 {prob: this.curproblem},
311 (ret) => {
312 if (edit)
313 {
314 let editedP = this.problems.find(p => p.id == this.curproblem.id);
315 this.copyProblem(this.curproblem, editedP);
316 }
317 else //new problem
318 {
319 let newProblem = Object.assign({}, this.curproblem);
320 newProblem.id = ret.id;
321 newProblem.uid = this.st.user.id;
322 newProblem.uname = this.st.user.name;
323 this.problems = this.problems.concat(newProblem);
324 }
325 this.resetCurProb();
326 this.infoMsg = "";
327 }
328 );
329 },
330 editProblem: function(prob) {
331 if (!prob.diag)
332 this.setDiagram(prob); //possible because V is loaded at this stage
333 this.copyProblem(prob, this.curproblem);
334 doClick('modalNewprob');
335 },
336 deleteProblem: function(prob) {
337 if (confirm(this.st.tr["Are you sure?"]))
338 {
339 ajax("/problems", "DELETE", {id:prob.id}, () => {
340 ArrayFun.remove(this.problems, p => p.id == prob.id);
341 this.backToList();
342 });
343 }
344 },
345 },
346 };
347 </script>
348
349 <style lang="sass" scoped>
350 [type="checkbox"].modal+div .card
351 max-width: 767px
352 max-height: 100%
353 #inputFen
354 width: 100%
355 textarea
356 width: 100%
357 #diagram
358 margin: 0 auto
359 max-width: 400px
360 #controls
361 margin: 0
362 width: 100%
363 text-align: center
364 & > *
365 margin: 0
366
367 #topPage
368 span.vname
369 font-weight: bold
370 padding-left: var(--universal-margin)
371 span.uname
372 padding-left: var(--universal-margin)
373 margin: 0 auto
374 & > .nomargin
375 margin: 0
376 & > .marginleft
377 margin: 0 0 0 15px
378
379 @media screen and (max-width: 767px)
380 #topPage
381 text-align: center
382
383 </style>