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