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