Computer mode in rules section almost OK
[vchess.git] / public / javascripts / components / problems.js
1 Vue.component('my-problems', {
2 props: ["queryHash","settings"],
3 data: function () {
4 return {
5 userId: user.id,
6 problems: [], //oldest first
7 myProblems: [], //same, but only mine
8 singletons: [], //requested problems (using #num)
9 display: "others", //or "mine"
10 curProb: null, //(reference to) current displayed problem (if any)
11 showSolution: false,
12 pbNum: 0, //to navigate directly to some problem
13 // New problem (to upload), or existing problem to edit:
14 modalProb: {
15 id: 0, //defined if it's an edit
16 fen: "",
17 instructions: "",
18 solution: "",
19 preview: false,
20 },
21 };
22 },
23 template: `
24 <div class="col-sm-12 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2">
25 <div id="problemControls" class="button-group">
26 <button :aria-label='translate("Previous problem(s)")' class="tooltip" @click="showNext('backward')">
27 <i class="material-icons">skip_previous</i>
28 </button>
29 <button :aria-label='translate("Add a problem")' class="tooltip" onClick="doClick('modal-newproblem')">
30 {{ translate("New") }}
31 </button>
32 <button :aria-label='translate("Next problem(s)")' class="tooltip" @click="showNext('forward')">
33 <i class="material-icons">skip_next</i>
34 </button>
35 </div>
36 <div id="mainBoard" v-show="!!curProb">
37 <div id="instructions-div" class="section-content">
38 <p id="problem-instructions">
39 {{ curProb.instructions }}
40 </p>
41 </div>
42 <my-game :fen="curProb.fen" :mode="analyze" :allowMovelist="true" :settings="settings">
43 </my-board>
44 <div id="solution-div" class="section-content">
45 <h3 class="clickable" @click="showSolution = !showSolution">
46 {{ translations["Show solution"] }}
47 </h3>
48 <p id="problem-solution" v-show="showSolution">
49 {{ curProb.solution }}
50 </p>
51 </div>
52 <button @click="displayList()">
53 <span>Back to list display</span>
54 </button>
55 </div>
56 <div>
57 <input type="text" placeholder="Type problem number" v-model="pbNum"/>
58 <button @click="showProblem()">
59 <span>Show problem</span>
60 </button>
61 </div>
62 <button v-if="!!userId" @click="toggleListDisplay()">
63 <span>My problems (only)</span>
64 </button>
65 <my-problem-summary v-show="!curProb"
66 v-on:edit-problem="editProblem(p)" v-on:delete-problem="deleteProblem(p.id)"
67 v-for="p in curProblems" @click="curProb=p"
68 v-bind:prob="p" v-bind:userid="userId" v-bind:key="p.id">
69 </my-problem-summary>
70 <input type="checkbox" id="modal-newproblem" class="modal"/>
71 <div role="dialog" aria-labelledby="modalProblemTxt">
72 <div v-show="!modalProb.preview" class="card newproblem-form">
73 <label for="modal-newproblem" class="modal-close">
74 </label>
75 <h3 id="modalProblemTxt">
76 {{ translate("Add a problem") }}
77 </h3>
78 <form @submit.prevent="previewProblem()">
79 <fieldset>
80 <label for="newpbFen">FEN</label>
81 <input id="newpbFen" type="text" v-model="modalProb.fen"
82 :placeholder='translate("Full FEN description")'/>
83 </fieldset>
84 <fieldset>
85 <p class="emphasis">
86 {{ translate("Safe HTML tags allowed") }}
87 </p>
88 <label for="newpbInstructions">
89 {{ translate("Instructions") }}
90 </label>
91 <textarea id="newpbInstructions" v-model="modalProb.instructions"
92 :placeholder='translate("Describe the problem goal")'>
93 </textarea>
94 <label for="newpbSolution">
95 {{ translate("Solution") }}
96 </label>
97 <textarea id="newpbSolution" v-model="modalProb.solution"
98 :placeholder='translate("How to solve the problem?")'>
99 </textarea>
100 <button class="center-btn">
101 {{ translate("Preview") }}
102 </button>
103 </fieldset>
104 </form>
105 </div>
106 <div v-show="modalProb.preview" class="card newproblem-preview">
107 <label for="modal-newproblem" class="modal-close">
108 </label>
109 <my-problem-summary v-bind:prob="modalProb" v-bind:userid="userId">
110 </my-problem-summary>
111 <div class="button-group">
112 <button @click="modalProb.preview=false">
113 {{ translate("Cancel") }}
114 </button>
115 <button @click="sendProblem()">
116 {{ translate("Send") }}
117 </button>
118 </div>
119 </div>
120 </div>
121 <input id="modalNomore" type="checkbox" class="modal"/>
122 <div role="dialog" aria-labelledby="nomoreMessage">
123 <div class="card smallpad small-modal text-center">
124 <label for="modalNomore" class="modal-close"></label>
125 <h3 id="nomoreMessage" class="section">
126 {{ nomoreMessage }}
127 </h3>
128 </div>
129 </div>
130 </div>
131 `,
132 watch: {
133 queryHash: function(newQhash) {
134 if (!!newQhash)
135 {
136 // New query hash = "id=42"; get 42 as problem ID
137 const pid = parseInt(newQhash.substr(2));
138 this.showProblem(pid);
139 }
140 else
141 this.curProb = null; //(back to) list display
142 },
143 },
144 created: function() {
145 if (!!this.queryHash)
146 {
147 const pid = parseInt(this.queryHash.substr(2));
148 this.showProblem(pid);
149 }
150 else
151 this.firstFetch();
152 },
153 methods: {
154 firstFetch: function() {
155 // Fetch most recent problems from server, for both lists
156 this.fetchProblems("others", "bacwkard");
157 this.fetchProblems("mine", "bacwkard");
158 this.listsInitialized = true;
159 },
160 showProblem: function(num) {
161 const pid = num || this.pbNum;
162 location.hash = "#" + pid;
163 const pIdx = this.singletons.findIndex(p => p.id == pid);
164 if (pIdx >= 0)
165 curProb = this.singletons[pIdx];
166 else
167 {
168 // Cannot find problem in current set; get from server, and add to singletons.
169 ajax(
170 "/problems/" + variant.name + "/" + pid, //TODO: use variant._id ?
171 "GET",
172 response => {
173 if (!!response.problem)
174 {
175 this.singletons.push(response.problem);
176 this.curProb = response.problem;
177 }
178 else
179 this.noMoreProblems("Sorry, problem " + pid + " does not exist");
180 }
181 );
182 }
183 },
184 translate: function(text) {
185 return translations[text];
186 },
187 curProblems: function() {
188 switch (this.display)
189 {
190 case "others":
191 return this.problems;
192 case "mine":
193 return this.myProblems;
194 }
195 },
196 // TODO?: get 50 from server but only show 10 at a time (for example)
197 showNext: function(direction) {
198 if (!this.curProb)
199 return this.fetchProblems(this.display, direction);
200 // Show next problem (older or newer):
201 let curProbs = this.curProblems();
202 // Try to find a neighbour problem in the direction, among current set
203 const neighbor = this.findClosestNeighbor(this.curProb, curProbs, direction);
204 if (!!neighbor)
205 {
206 this.curProb = neighbor;
207 return;
208 }
209 // Boundary case: nothing in current set, need to fetch from server
210 const curSize = curProbs.length;
211 this.fetchProblems(this.display, direction);
212 const newSize = curProbs.length;
213 if (curSize == newSize) //no problems found
214 return this.noMoreProblems("No more problems in this direction");
215 // Ok, found something:
216 this.curProb = this.findClosestNeighbor(this.curProb, curProbs, direction);
217 },
218 findClosestNeighbor: function(problem, probList, direction) {
219 let neighbor = undefined;
220 let smallestDistance = Number.MAX_SAFE_INTEGER;
221 for (let prob of probList)
222 {
223 const delta = Math.abs(prob.id - problem.id);
224 if (delta < smallestDistance &&
225 ((direction == "backward" && prob.id < problem.id)
226 || (direction == "forward" && prob.id > problem.id)))
227 {
228 neighbor = prob;
229 smallestDistance = delta;
230 }
231 }
232 return neighbor;
233 },
234 noMoreProblems: function(message) {
235 this.nomoreMessage = message;
236 let modalNomore = document.getElementById("modalNomore");
237 modalNomore.checked = true;
238 setTimeout(() => modalNomore.checked = false, 2000);
239 },
240 displayList: function() {
241 this.curProb = null;
242 location.hash = "";
243 // Fetch problems if first call (if #num, and then lists)
244 if (!this.listsInitialized)
245 this.firstFetch();
246 },
247 toggleListDisplay: function() {
248 this.display = (this.display == "others" ? "mine" : "others");
249 },
250 fetchProblems: function(type, direction) {
251 let problems = (type == "others" ? this.problems : this.myProblems);
252 let last_dt = (direction=="forward" ? 0 : Number.MAX_SAFE_INTEGER);
253 if (this.problems.length > 0)
254 {
255 // Search for newest date (or oldest)
256 last_dt = problems[0].added;
257 for (let i=1; i<problems.length; i++)
258 {
259 if ((direction == "forward" && this.problems[i].added > last_dt) ||
260 (direction == "backward" && this.problems[i].added < last_dt))
261 {
262 last_dt = this.problems[i].added;
263 }
264 }
265 }
266 ajax(
267 "/problems/" + variant.id,
268 "GET",
269 {
270 type: type,
271 direction: direction,
272 last_dt: last_dt,
273 },
274 response => {
275 if (response.problems.length > 0)
276 {
277 Array.prototype.push.apply(problems,
278 response.problems.sort((p1,p2) => { return p1.added - p2.added; }));
279 // If one list is empty but not the other, show the non-empty
280 const otherArray = (type == "mine" ? this.problems : this.myProblems);
281 if (problems.length > 0 && otherArray.length == 0)
282 this.display = type;
283 }
284 }
285 );
286 },
287 previewProblem: function() {
288 if (!V.IsGoodFen(this.newProblem.fen))
289 return alert(translations["Bad FEN description"]);
290 if (this.newProblem.instructions.trim().length == 0)
291 return alert(translations["Empty instructions"]);
292 if (this.newProblem.solution.trim().length == 0)
293 return alert(translations["Empty solution"]);
294 this.modalProb.preview = true;
295 },
296 editProblem: function(prob) {
297 this.modalProb = prob;
298 document.getElementById("modal-newproblem").checked = true;
299 },
300 deleteProblem: function(pid) {
301 ajax(
302 "/problems/" + variant.id + "/" + pid,
303 "DELETE",
304 response => {
305 // Delete problem from the list on client side
306 let problems = this.curProblems();
307 const pIdx = problems.findIndex(p => p.id == pid);
308 problems.splice(pIdx, 1);
309 }
310 );
311 },
312 sendProblem: function() {
313 // Send it to the server and close modal
314 ajax(
315 "/problems/" + variant.id,
316 (this.modalProb.id > 0 ? "PUT" : "POST"),
317 this.modalProb,
318 response => {
319 document.getElementById("modal-newproblem").checked = false;
320 if (this.modalProb.id == 0)
321 {
322 this.modalProb.added = Date.now();
323 this.modalProb.preview = false;
324 this.myProblems.push(JSON.parse(JSON.stringify(this.modalProb)));
325 }
326 else
327 this.modalProb.id = 0;
328 }
329 );
330 },
331 },
332 })