1 /*
  2     Copyright 2008-2021
  3         Matthias Ehmann,
  4         Michael Gerhaeuser,
  5         Carsten Miller,
  6         Bianca Valentin,
  7         Alfred Wassermann,
  8         Peter Wilfahrt
  9 
 10     This file is part of JSXGraph.
 11 
 12     JSXGraph is free software dual licensed under the GNU LGPL or MIT License.
 13 
 14     You can redistribute it and/or modify it under the terms of the
 15 
 16       * GNU Lesser General Public License as published by
 17         the Free Software Foundation, either version 3 of the License, or
 18         (at your option) any later version
 19       OR
 20       * MIT License: https://github.com/jsxgraph/jsxgraph/blob/master/LICENSE.MIT
 21 
 22     JSXGraph is distributed in the hope that it will be useful,
 23     but WITHOUT ANY WARRANTY; without even the implied warranty of
 24     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 25     GNU Lesser General Public License for more details.
 26 
 27     You should have received a copy of the GNU Lesser General Public License and
 28     the MIT License along with JSXGraph. If not, see <http://www.gnu.org/licenses/>
 29     and <http://opensource.org/licenses/MIT/>.
 30  */
 31 
 32 
 33 /*global JXG: true, define: true*/
 34 /*jslint nomen: true, plusplus: true*/
 35 
 36 /* depends:
 37  jxg
 38  math/math
 39  base/constants
 40  base/point
 41  utils/type
 42   elements:
 43    point
 44    group
 45    segment
 46    ticks
 47    glider
 48    text
 49  */
 50 
 51 /**
 52  * @fileoverview The geometry object slider is defined in this file. Slider stores all
 53  * style and functional properties that are required to draw and use a slider on
 54  * a board.
 55  */
 56 
 57 define([
 58     'jxg', 'math/math', 'base/constants', 'base/coords', 'utils/type', 'base/point'
 59 ], function (JXG, Mat, Const, Coords, Type, Point) {
 60 
 61     "use strict";
 62 
 63     /**
 64      * @class A slider can be used to choose values from a given range of numbers.
 65      * @pseudo
 66      * @description
 67      * @name Slider
 68      * @augments Glider
 69      * @constructor
 70      * @type JXG.Point
 71      * @throws {Exception} If the element cannot be constructed with the given parent objects an exception is thrown.
 72      * @param {Array_Array_Array} start,end,data The first two arrays give the start and the end where the slider is drawn
 73      * on the board. The third array gives the start and the end of the range the slider operates as the first resp. the
 74      * third component of the array. The second component of the third array gives its start value.
 75      * @example
 76      * // Create a slider with values between 1 and 10, initial position is 5.
 77      * var s = board.create('slider', [[1, 2], [3, 2], [1, 5, 10]]);
 78      * </pre><div class="jxgbox" id="JXGcfb51cde-2603-4f18-9cc4-1afb452b374d" style="width: 200px; height: 200px;"></div>
 79      * <script type="text/javascript">
 80      *   (function () {
 81      *     var board = JXG.JSXGraph.initBoard('JXGcfb51cde-2603-4f18-9cc4-1afb452b374d', {boundingbox: [-1, 5, 5, -1], axis: true, showcopyright: false, shownavigation: false});
 82      *     var s = board.create('slider', [[1, 2], [3, 2], [1, 5, 10]]);
 83      *   })();
 84      * </script><pre>
 85      * @example
 86      * // Create a slider taking integer values between 1 and 50. Initial value is 50.
 87      * var s = board.create('slider', [[1, 3], [3, 1], [0, 10, 50]], {snapWidth: 1, ticks: { drawLabels: true }});
 88      * </pre><div class="jxgbox" id="JXGe17128e6-a25d-462a-9074-49460b0d66f4" style="width: 200px; height: 200px;"></div>
 89      * <script type="text/javascript">
 90      *   (function () {
 91      *     var board = JXG.JSXGraph.initBoard('JXGe17128e6-a25d-462a-9074-49460b0d66f4', {boundingbox: [-1, 5, 5, -1], axis: true, showcopyright: false, shownavigation: false});
 92      *     var s = board.create('slider', [[1, 3], [3, 1], [1, 10, 50]], {snapWidth: 1, ticks: { drawLabels: true }});
 93      *   })();
 94      * </script><pre>
 95      * @example
 96      *     // Draggable slider
 97      *     var s1 = board.create('slider', [[-3,1], [2,1],[-10,1,10]], {
 98      *         visible: true,
 99      *         snapWidth: 2,
100      *         point1: {fixed: false},
101      *         point2: {fixed: false},
102      *         baseline: {fixed: false, needsRegularUpdate: true}
103      *     });
104      *
105      * </pre><div id="JXGbfc67817-2827-44a1-bc22-40bf312e76f8" class="jxgbox" style="width: 300px; height: 300px;"></div>
106      * <script type="text/javascript">
107      *     (function() {
108      *         var board = JXG.JSXGraph.initBoard('JXGbfc67817-2827-44a1-bc22-40bf312e76f8',
109      *             {boundingbox: [-8, 8, 8,-8], axis: true, showcopyright: false, shownavigation: false});
110      *         var s1 = board.create('slider', [[-3,1], [2,1],[-10,1,10]], {
111      *             visible: true,
112      *             snapWidth: 2,
113      *             point1: {fixed: false},
114      *             point2: {fixed: false},
115      *             baseline: {fixed: false, needsRegularUpdate: true}
116      *         });
117      *
118      *     })();
119      *
120      * </script><pre>
121      *
122      * @example
123      *     // Set the slider by clicking on the base line: attribute 'moveOnUp'
124      *     var s1 = board.create('slider', [[-3,1], [2,1],[-10,1,10]], {
125      *         snapWidth: 2,
126      *         moveOnUp: true // default value
127      *     });
128      *
129      * </pre><div id="JXGc0477c8a-b1a7-4111-992e-4ceb366fbccc" class="jxgbox" style="width: 300px; height: 300px;"></div>
130      * <script type="text/javascript">
131      *     (function() {
132      *         var board = JXG.JSXGraph.initBoard('JXGc0477c8a-b1a7-4111-992e-4ceb366fbccc',
133      *             {boundingbox: [-8, 8, 8,-8], axis: true, showcopyright: false, shownavigation: false});
134      *         var s1 = board.create('slider', [[-3,1], [2,1],[-10,1,10]], {
135      *             snapWidth: 2,
136      *             moveOnUp: true // default value
137      *         });
138      *
139      *     })();
140      *
141      * </script><pre>
142      *
143      * @example
144      * // Set colors
145      * var sl = board.create('slider', [[-3, 1], [1, 1], [-10, 1, 10]], {
146      * 
147      *   baseline: { strokeColor: 'blue'},
148      *   highline: { strokeColor: 'red'},
149      *   fillColor: 'yellow',
150      *   label: {fontSize: 24, strokeColor: 'orange'},
151      *   name: 'xyz', // Not shown, if suffixLabel is set
152      *   suffixLabel: 'x = ',
153      *   postLabel: ' u'
154      * 
155      * });
156      * 
157      * </pre><div id="JXGd96c9e2c-2c25-4131-b6cf-9dbb80819401" class="jxgbox" style="width: 300px; height: 300px;"></div>
158      * <script type="text/javascript">
159      *     (function() {
160      *         var board = JXG.JSXGraph.initBoard('JXGd96c9e2c-2c25-4131-b6cf-9dbb80819401',
161      *             {boundingbox: [-8, 8, 8,-8], axis: true, showcopyright: false, shownavigation: false});
162      *     var sl = board.create('slider', [[-3, 1], [1, 1], [-10, 1, 10]], {
163      *     
164      *       baseline: { strokeColor: 'blue'},
165      *       highline: { strokeColor: 'red'},
166      *       fillColor: 'yellow',
167      *       label: {fontSize: 24, strokeColor: 'orange'},
168      *       name: 'xyz', // Not shown, if suffixLabel is set
169      *       suffixLabel: 'x = ',
170      *       postLabel: ' u'
171      *     
172      *     });
173      * 
174      *     })();
175      * 
176      * </script><pre>
177      * 
178  */
179     JXG.createSlider = function (board, parents, attributes) {
180         var pos0, pos1, smin, start, smax, sdiff,
181             p1, p2, l1, ticks, ti, startx, starty, p3, l2, t,
182             withText, withTicks, snapWidth, sw, s, attr, precision;
183 
184         attr = Type.copyAttributes(attributes, board.options, 'slider');
185         withTicks = attr.withticks;
186         withText = attr.withlabel;
187         snapWidth = attr.snapwidth;
188         precision = attr.precision;
189 
190         // start point
191         attr = Type.copyAttributes(attributes, board.options, 'slider', 'point1');
192         p1 = board.create('point', parents[0],  attr);
193 
194         // end point
195         attr = Type.copyAttributes(attributes, board.options, 'slider', 'point2');
196         p2 = board.create('point', parents[1],  attr);
197         //g = board.create('group', [p1, p2]);
198 
199         // Base line
200         attr = Type.copyAttributes(attributes, board.options, 'slider', 'baseline');
201         l1 = board.create('segment', [p1, p2], attr);
202 
203         // This is required for a correct projection of the glider onto the segment below
204         l1.updateStdform();
205 
206         pos0 = p1.coords.usrCoords.slice(1);
207         pos1 = p2.coords.usrCoords.slice(1);
208         smin = parents[2][0];
209         start = parents[2][1];
210         smax = parents[2][2];
211         sdiff = smax - smin;
212 
213         sw = Type.evaluate(snapWidth);
214         s = (sw === -1) ? start : Math.round(start / sw) * sw;
215         startx = pos0[0] + (pos1[0] - pos0[0]) * (s - smin) / (smax - smin);
216         starty = pos0[1] + (pos1[1] - pos0[1]) * (s - smin) / (smax - smin);
217 
218         // glider point
219         attr = Type.copyAttributes(attributes, board.options, 'slider');
220         // overwrite this in any case; the sliders label is a special text element, not the gliders label.
221         // this will be set back to true after the text was created (and only if withlabel was true initially).
222         attr.withLabel = false;
223         // gliders set snapwidth=-1 by default (i.e. deactivate them)
224         p3 = board.create('glider', [startx, starty, l1], attr);
225         p3.setAttribute({snapwidth: snapWidth});
226 
227         // Segment from start point to glider point: highline
228         attr = Type.copyAttributes(attributes, board.options, 'slider', 'highline');
229         l2 = board.create('segment', [p1, p3],  attr);
230 
231         /**
232          * Returns the current slider value.
233          * @memberOf Slider.prototype
234          * @name Value
235          * @function
236          * @returns {Number}
237          */
238         p3.Value = function () {
239             var sdiff = this._smax - this._smin,
240                 ev_sw = Type.evaluate(this.visProp.snapwidth);
241 
242             return ev_sw === -1 ?
243                         this.position * sdiff + this._smin :
244                         Math.round((this.position * sdiff + this._smin) / ev_sw) * ev_sw;
245         };
246 
247         p3.methodMap = Type.deepCopy(p3.methodMap, {
248             Value: 'Value',
249             setValue: 'setValue',
250             smax: '_smax',
251             smin: '_smin',
252             setMax: 'setMax',
253             setMin: 'setMin'
254         });
255 
256         /**
257          * End value of the slider range.
258          * @memberOf Slider.prototype
259          * @name _smax
260          * @type Number
261          */
262         p3._smax = smax;
263 
264         /**
265          * Start value of the slider range.
266          * @memberOf Slider.prototype
267          * @name _smin
268          * @type Number
269          */
270         p3._smin = smin;
271 
272         /**
273          * Sets the maximum value of the slider.
274          * @memberOf Slider.prototype
275          * @name setMax
276          * @param {Number} val New maximum value
277          * @returns {Object} this object
278          */
279         p3.setMax = function(val) {
280             this._smax = val;
281             return this;
282         };
283 
284         /**
285          * Sets the value of the slider. This call must be followed
286          * by a board update call.
287          * @memberOf Slider.prototype
288          * @name setValue
289          * @param {Number} val New value
290          * @returns {Object} this object
291          */
292         p3.setValue = function(val) {
293             var sdiff = this._smax - this._smin;
294 
295             if (Math.abs(sdiff) > Mat.eps) {
296                 this.position = (val - this._smin) / sdiff;
297             } else {
298                 this.position = 0.0; //this._smin;
299             }
300             this.position = Math.max(0.0, Math.min(1.0, this.position));
301             return this;
302         };
303 
304         /**
305          * Sets the minimum value of the slider.
306          * @memberOf Slider.prototype
307          * @name setMin
308          * @param {Number} val New minimum value
309          * @returns {Object} this object
310          */
311         p3.setMin = function(val) {
312             this._smin = val;
313             return this;
314         };
315 
316         if (withText) {
317             attr = Type.copyAttributes(attributes, board.options, 'slider', 'label');
318             t = board.create('text', [
319                 function () {
320                     return (p2.X() - p1.X()) * 0.05 + p2.X();
321                 },
322                 function () {
323                     return (p2.Y() - p1.Y()) * 0.05 + p2.Y();
324                 },
325                 function () {
326                     var n,
327                         sl = Type.evaluate(p3.visProp.suffixlabel),
328                         ul = Type.evaluate(p3.visProp.unitlabel),
329                         pl = Type.evaluate(p3.visProp.postlabel);
330 
331                     if (sl !== null) {
332                         n = sl;
333                     } else if (p3.name && p3.name !== '') {
334                         n = p3.name + ' = ';
335                     } else {
336                         n = '';
337                     }
338 
339                     n += Type.toFixed(p3.Value(), precision);
340 
341                     if (ul !== null) {
342                         n += ul;
343                     }
344                     if (pl !== null) {
345                         n += pl;
346                     }
347 
348                     return n;
349                 }
350             ], attr);
351 
352             /**
353              * The text element to the right of the slider, indicating its current value.
354              * @memberOf Slider.prototype
355              * @name label
356              * @type JXG.Text
357              */
358             p3.label = t;
359 
360             // reset the withlabel attribute
361             p3.visProp.withlabel = true;
362             p3.hasLabel = true;
363         }
364 
365         /**
366          * Start point of the base line.
367          * @memberOf Slider.prototype
368          * @name point1
369          * @type JXG.Point
370          */
371         p3.point1 = p1;
372 
373         /**
374          * End point of the base line.
375          * @memberOf Slider.prototype
376          * @name point2
377          * @type JXG.Point
378          */
379         p3.point2 = p2;
380 
381         /**
382          * The baseline the glider is bound to.
383          * @memberOf Slider.prototype
384          * @name baseline
385          * @type JXG.Line
386          */
387         p3.baseline = l1;
388 
389         /**
390          * A line on top of the baseline, indicating the slider's progress.
391          * @memberOf Slider.prototype
392          * @name highline
393          * @type JXG.Line
394          */
395         p3.highline = l2;
396 
397         if (withTicks) {
398             // Function to generate correct label texts
399 
400             attr = Type.copyAttributes(attributes, board.options, 'slider', 'ticks');
401             if (!Type.exists(attr.generatelabeltext)) {
402                 attr.generateLabelText = function(tick, zero, value) {
403                     var labelText,
404                         dFull = p3.point1.Dist(p3.point2),
405                         smin = p3._smin, smax = p3._smax,
406                         val = this.getDistanceFromZero(zero, tick) * (smax - smin) / dFull  + smin;
407 
408                         if (dFull < Mat.eps || Math.abs(val) < Mat.eps) { // Point is zero
409                             labelText = '0';
410                         } else {
411                             labelText = this.formatLabelText(val);
412                         }
413                         return labelText;
414                 };
415             }
416             ticks  = 2;
417             ti = board.create('ticks', [
418                 p3.baseline,
419                 p3.point1.Dist(p1) / ticks,
420 
421                 function (tick) {
422                     var dFull = p3.point1.Dist(p3.point2),
423                         d = p3.point1.coords.distance(Const.COORDS_BY_USER, tick);
424 
425                     if (dFull < Mat.eps) {
426                         return 0;
427                     }
428 
429                     return d / dFull * sdiff + smin;
430                 }
431             ], attr);
432 
433             /**
434              * Ticks give a rough indication about the slider's current value.
435              * @memberOf Slider.prototype
436              * @name ticks
437              * @type JXG.Ticks
438              */
439             p3.ticks = ti;
440         }
441 
442         // override the point's remove method to ensure the removal of all elements
443         p3.remove = function () {
444             if (withText) {
445                 board.removeObject(t);
446             }
447 
448             board.removeObject(l2);
449             board.removeObject(l1);
450             board.removeObject(p2);
451             board.removeObject(p1);
452 
453 
454             Point.Point.prototype.remove.call(p3);
455         };
456 
457         p1.dump = false;
458         p2.dump = false;
459         l1.dump = false;
460         l2.dump = false;
461 
462         p3.elType = 'slider';
463         p3.parents = parents;
464         p3.subs = {
465             point1: p1,
466             point2: p2,
467             baseLine: l1,
468             highLine: l2
469         };
470         p3.inherits.push(p1, p2, l1, l2);
471 
472         if (withTicks) {
473             ti.dump = false;
474             p3.subs.ticks = ti;
475             p3.inherits.push(ti);
476         }
477 
478         p3.baseline.on('up', function(evt) {
479             var pos, c;
480 
481             if (Type.evaluate(p3.visProp.moveonup) && !Type.evaluate(p3.visProp.fixed) ) {
482                 pos = l1.board.getMousePosition(evt, 0);
483                 c = new Coords(Const.COORDS_BY_SCREEN, pos, this.board);
484                 p3.moveTo([c.usrCoords[1], c.usrCoords[2]]);
485             }
486         });
487 
488         // Save the visibility attribute of the sub-elements
489         // for (el in p3.subs) {
490         //     p3.subs[el].status = {
491         //         visible: p3.subs[el].visProp.visible
492         //     };
493         // }
494 
495         // p3.hideElement = function () {
496         //     var el;
497         //     GeometryElement.prototype.hideElement.call(this);
498         //
499         //     for (el in this.subs) {
500         //         // this.subs[el].status.visible = this.subs[el].visProp.visible;
501         //         this.subs[el].hideElement();
502         //     }
503         // };
504 
505 //         p3.showElement = function () {
506 //             var el;
507 //             GeometryElement.prototype.showElement.call(this);
508 //
509 //             for (el in this.subs) {
510 // //                if (this.subs[el].status.visible) {
511 //                 this.subs[el].showElement();
512 // //                }
513 //             }
514 //         };
515 
516 
517 
518         // This is necessary to show baseline, highline and ticks
519         // when opening the board in case the visible attributes are set
520         // to 'inherit'.
521         p3.prepareUpdate().update();
522         if (!board.isSuspendedUpdate) {
523             p3.updateVisibility().updateRenderer();
524             p3.baseline.updateVisibility().updateRenderer();
525             p3.highline.updateVisibility().updateRenderer();
526             if (withTicks) {
527                 p3.ticks.updateVisibility().updateRenderer();
528             }
529         }
530 
531         return p3;
532     };
533 
534     JXG.registerElement('slider', JXG.createSlider);
535 
536     return {
537         createSlider: JXG.createSlider
538     };
539 });
540