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