]> git.ipfire.org Git - thirdparty/foundation/foundation-sites.git/commitdiff
Convert slider to ES6 class
authorColin Marshall <colin.michael.marshall@gmail.com>
Thu, 4 Feb 2016 05:33:15 +0000 (22:33 -0700)
committerColin Marshall <colin.michael.marshall@gmail.com>
Thu, 4 Feb 2016 05:33:15 +0000 (22:33 -0700)
js/foundation.slider.js

index 868befd14d1bcd666c063a5408bf837b5c811497..e5babd2e00932b50bd9eb323c4cc3a8c13afaad3 100644 (file)
@@ -1,3 +1,5 @@
+'use strict';
+
 /**
  * Slider module.
  * @module foundation.slider
@@ -6,16 +8,15 @@
  * @requires foundation.util.keyboard
  * @requires foundation.util.touch
  */
-!function($, Foundation){
-  'use strict';
 
+export default class Slider {  
   /**
    * Creates a new instance of a drilldown menu.
    * @class
    * @param {jQuery} element - jQuery object to make into an accordion menu.
    * @param {Object} options - Overrides to the default plugin settings.
    */
-  function Slider(element, options){
+  constructor(element, options) {
     this.$element = element;
     this.options = $.extend({}, Slider.defaults, this.$element.data(), options);
 
     });
   }
 
-  Slider.defaults = {
-    /**
-     * Minimum value for the slider scale.
-     * @option
-     * @example 0
-     */
-    start: 0,
-    /**
-     * Maximum value for the slider scale.
-     * @option
-     * @example 100
-     */
-    end: 100,
-    /**
-     * Minimum value change per change event. Not Currently Implemented!
-
-     */
-    step: 1,
-    /**
-     * Value at which the handle/input *(left handle/first input)* should be set to on initialization.
-     * @option
-     * @example 0
-     */
-    initialStart: 0,
-    /**
-     * Value at which the right handle/second input should be set to on initialization.
-     * @option
-     * @example 100
-     */
-    initialEnd: 100,
-    /**
-     * Allows the input to be located outside the container and visible. Set to by the JS
-     * @option
-     * @example false
-     */
-    binding: false,
-    /**
-     * Allows the user to click/tap on the slider bar to select a value.
-     * @option
-     * @example true
-     */
-    clickSelect: true,
-    /**
-     * Set to true and use the `vertical` class to change alignment to vertical.
-     * @option
-     * @example false
-     */
-    vertical: false,
-    /**
-     * Allows the user to drag the slider handle(s) to select a value.
-     * @option
-     * @example true
-     */
-    draggable: true,
-    /**
-     * Disables the slider and prevents event listeners from being applied. Double checked by JS with `disabledClass`.
-     * @option
-     * @example false
-     */
-    disabled: false,
-    /**
-     * Allows the use of two handles. Double checked by the JS. Changes some logic handling.
-     * @option
-     * @example false
-     */
-    doubleSided: false,
-    /**
-     * Potential future feature.
-     */
-    // steps: 100,
-    /**
-     * Number of decimal places the plugin should go to for floating point precision.
-     * @option
-     * @example 2
-     */
-    decimal: 2,
-    /**
-     * Time delay for dragged elements.
-     */
-    // dragDelay: 0,
-    /**
-     * Time, in ms, to animate the movement of a slider handle if user clicks/taps on the bar. Needs to be manually set if updating the transition time in the Sass settings.
-     * @option
-     * @example 200
-     */
-    moveTime: 200,//update this if changing the transition time in the sass
-    /**
-     * Class applied to disabled sliders.
-     * @option
-     * @example 'disabled'
-     */
-    disabledClass: 'disabled',
-    invertVertical: false
-  };
   /**
    * Initilizes the plugin by reading/setting attributes, creating collections and setting the initial position of the handle(s).
    * @function
    * @private
    */
-  Slider.prototype._init = function(){
+  _init() {
     this.inputs = this.$element.find('input');
     this.handles = this.$element.find('[data-slider-handle]');
 
 
     var isDbl = false,
         _this = this;
-    if(this.options.disabled || this.$element.hasClass(this.options.disabledClass)){
+    if (this.options.disabled || this.$element.hasClass(this.options.disabledClass)) {
       this.options.disabled = true;
       this.$element.addClass(this.options.disabledClass);
     }
-    if(!this.inputs.length){
+    if (!this.inputs.length) {
       this.inputs = $().add(this.$input);
       this.options.binding = true;
     }
     this._setInitAttr(0);
     this._events(this.$handle);
 
-    if(this.handles[1]){
+    if (this.handles[1]) {
       this.options.doubleSided = true;
       this.$handle2 = this.handles.eq(1);
       this.$input2 = this.inputs.length > 1 ? this.inputs.eq(1) : $(`#${this.$handle2.attr('aria-controls')}`);
 
-      if(!this.inputs[1]){
+      if (!this.inputs[1]) {
         this.inputs = this.inputs.add(this.$input2);
       }
       isDbl = true;
 
-      this._setHandlePos(this.$handle, this.options.initialStart, true, function(){
+      this._setHandlePos(this.$handle, this.options.initialStart, true, function() {
 
         _this._setHandlePos(_this.$handle2, _this.options.initialEnd, true);
       });
       this._events(this.$handle2);
     }
 
-    if(!isDbl){
+    if (!isDbl) {
       this._setHandlePos(this.$handle, this.options.initialStart, true);
     }
-  };
+  }
+
   /**
    * Sets the position of the selected handle and fill bar.
    * @function
    * @param {Function} cb - callback function to fire on completion.
    * @fires Slider#moved
    */
-  Slider.prototype._setHandlePos = function($hndl, location, noInvert, cb){
+  _setHandlePos($hndl, location, noInvert, cb) {
   //might need to alter that slightly for bars that will have odd number selections.
     location = parseFloat(location);//on input change events, convert string to number...grumble.
 
     // prevent slider from running out of bounds, if value exceeds the limits set through options, override the value to min/max
-    if(location < this.options.start){ location = this.options.start; }
-    else if(location > this.options.end){ location = this.options.end; }
+    if (location < this.options.start) { location = this.options.start; }
+    else if (location > this.options.end) { location = this.options.end; }
 
     var isDbl = this.options.doubleSided;
 
-    if(isDbl){ //this block is to prevent 2 handles from crossing eachother. Could/should be improved.
-      if(this.handles.index($hndl) === 0){
+    if (isDbl) { //this block is to prevent 2 handles from crossing eachother. Could/should be improved.
+      if (this.handles.index($hndl) === 0) {
         var h2Val = parseFloat(this.$handle2.attr('aria-valuenow'));
         location = location >= h2Val ? h2Val - this.options.step : location;
-      }else{
+      } else {
         var h1Val = parseFloat(this.$handle.attr('aria-valuenow'));
         location = location <= h1Val ? h1Val + this.options.step : location;
       }
 
     //this is for single-handled vertical sliders, it adjusts the value to account for the slider being "upside-down"
     //for click and drag events, it's weird due to the scale(-1, 1) css property
-    if(this.options.vertical && !noInvert){
+    if (this.options.vertical && !noInvert) {
       location = this.options.end - location;
     }
 
     this._setValues($hndl, location);
 
     // TODO update to calculate based on values set to respective inputs??
-    if(isDbl){
+    if (isDbl) {
       var isLeftHndl = this.handles.index($hndl) === 0,
           //empty variable, will be used for min-height/width for fill bar
           dim,
           //percentage w/h of the handle compared to the slider bar
           handlePct =  ~~(percent(handleDim, elemDim) * 100);
       //if left handle, the math is slightly different than if it's the right handle, and the left/top property needs to be changed for the fill bar
-      if(isLeftHndl){
+      if (isLeftHndl) {
         //left or top percentage value to apply to the fill bar.
         css[lOrT] = `${movement}%`;
         //calculate the new min-height/width for the fill bar.
         dim = parseFloat(this.$handle2[0].style[lOrT]) - movement + handlePct;
         //this callback is necessary to prevent errors and allow the proper placement and initialization of a 2-handled slider
         //plus, it means we don't care if 'dim' isNaN on init, it won't be in the future.
-        if(cb && typeof cb === 'function'){ cb(); }//this is only needed for the initialization of 2 handled sliders
-      }else{
+        if (cb && typeof cb === 'function') { cb(); }//this is only needed for the initialization of 2 handled sliders
+      } else {
         //just caching the value of the left/bottom handle's left/top property
         var handlePos = parseFloat(this.$handle[0].style[lOrT]);
         //calculate the new min-height/width for the fill bar. Use isNaN to prevent false positives for numbers <= 0
       css[`min-${hOrW}`] = `${dim}%`;
     }
 
-    this.$element.one('finished.zf.animate', function(){
+    this.$element.one('finished.zf.animate', function() {
                     /**
                      * Fires when the handle is done moving.
                      * @event Slider#moved
     //because we don't know exactly how the handle will be moved, check the amount of time it should take to move.
     var moveTime = this.$element.data('dragging') ? 1000/60 : this.options.moveTime;
 
-    Foundation.Move(moveTime, $hndl, function(){
+    Foundation.Move(moveTime, $hndl, function() {
       //adjusting the left/top property of the handle, based on the percentage calculated above
       $hndl.css(lOrT, `${movement}%`);
 
-      if(!_this.options.doubleSided){
+      if (!_this.options.doubleSided) {
         //if single-handled, a simple method to expand the fill bar
         _this.$fill.css(hOrW, `${pctOfBar * 100}%`);
-      }else{
+      } else {
         //otherwise, use the css object we created above
         _this.$fill.css(css);
       }
     });
+  }
 
-  };
   /**
    * Sets the initial attribute for the slider element.
    * @function
    * @private
    * @param {Number} idx - index of the current handle/input to use.
    */
-  Slider.prototype._setInitAttr = function(idx){
+  _setInitAttr(idx) {
     var id = this.inputs.eq(idx).attr('id') || Foundation.GetYoDigits(6, 'slider');
     this.inputs.eq(idx).attr({
       'id': id,
       'aria-orientation': this.options.vertical ? 'vertical' : 'horizontal',
       'tabindex': 0
     });
-  };
+  }
+
   /**
    * Sets the input and `aria-valuenow` values for the slider element.
    * @function
    * @param {jQuery} $handle - the currently selected handle.
    * @param {Number} val - floating point of the new value.
    */
-  Slider.prototype._setValues = function($handle, val){
+  _setValues($handle, val) {
     var idx = this.options.doubleSided ? this.handles.index($handle) : 0;
     this.inputs.eq(idx).val(val);
     $handle.attr('aria-valuenow', val);
-  };
+  }
+
   /**
    * Handles events on the slider element.
    * Calculates the new location of the current handle.
    * @param {Number} val - floating point number for the new value of the slider.
    * TODO clean this up, there's a lot of repeated code between this and the _setHandlePos fn.
    */
-  Slider.prototype._handleEvent = function(e, $handle, val){
+  _handleEvent(e, $handle, val) {
     var value, hasVal;
-    if(!val){//click or drag events
+    if (!val) {//click or drag events
       e.preventDefault();
       var _this = this,
           vertical = this.options.vertical,
 // >>>>>>> develop
       hasVal = false;
 
-      if(!$handle){//figure out which handle it is, pass it to the next function.
+      if (!$handle) {//figure out which handle it is, pass it to the next function.
         var firstHndlPos = absPosition(this.$handle, direction, barXY, param),
             secndHndlPos = absPosition(this.$handle2, direction, barXY, param);
             $handle = firstHndlPos <= secndHndlPos ? this.$handle : this.$handle2;
       }
 
-    }else{//change event on input
+    } else {//change event on input
       value = this._adjustValue($handle);
       hasVal = true;
     }
 
     this._setHandlePos($handle, value, hasVal);
-  };
+  }
 
   /**
    * Adjustes value for handle in regard to step value. returns adjusted value
    * @param {jQuery} $handle - the selected handle.
    * @param {Number} value - value to adjust. used if $handle is falsy
    */
-  Slider.prototype._adjustValue = function($handle, value) {
+  _adjustValue($handle, value) {
     var val,
       step = this.options.step,
       div = parseFloat(step/2),
       left, prev_val, next_val;
-    if(!!$handle) {
+    if (!!$handle) {
       val = parseFloat($handle.attr('aria-valuenow'));
     }
     else {
     }
     val = val >= prev_val + div ? next_val : prev_val;
     return val;
-  };
+  }
 
   /**
    * Adds event listeners to the slider elements.
    * @private
    * @param {jQuery} $handle - the current handle to apply listeners to.
    */
-  Slider.prototype._events = function($handle){
-    if(this.options.disabled){ return false; }
+  _events($handle) {
+    if (this.options.disabled) { return false; }
 
     var _this = this,
         curHandle,
         timer;
 
-      this.inputs.off('change.zf.slider').on('change.zf.slider', function(e){
+      this.inputs.off('change.zf.slider').on('change.zf.slider', function(e) {
         var idx = _this.inputs.index($(this));
         _this._handleEvent(e, _this.handles.eq(idx), $(this).val());
       });
 
-    if(this.options.clickSelect){
-      this.$element.off('click.zf.slider').on('click.zf.slider', function(e){
-        if(_this.$element.data('dragging')){ return false; }
+    if (this.options.clickSelect) {
+      this.$element.off('click.zf.slider').on('click.zf.slider', function(e) {
+        if (_this.$element.data('dragging')) { return false; }
 // <<<<<<< HEAD
         _this.animComplete = false;
 
-        if(!$(e.target).is('[data-slider-handle]')) {
+        if (!$(e.target).is('[data-slider-handle]')) {
           if (_this.options.doubleSided) {
             _this._handleEvent(e);
           } else {
           }
 // =======
 
-        if(_this.options.doubleSided){
+        if (_this.options.doubleSided) {
           _this._handleEvent(e);
-        }else{
+        } else {
           _this._handleEvent(e, _this.$handle);
 // >>>>>>> develop
         }
       }});
     }
 
-    if(this.options.draggable){
+    if (this.options.draggable) {
       this.handles.addTouch();
 
       var $body = $('body');
       $handle
         .off('mousedown.zf.slider')
-        .on('mousedown.zf.slider', function(e){
+        .on('mousedown.zf.slider', function(e) {
           $handle.addClass('is-dragging');
           _this.$fill.addClass('is-dragging');//
           _this.$element.data('dragging', true);
 
           curHandle = $(e.currentTarget);
 
-          $body.on('mousemove.zf.slider', function(e){
+          $body.on('mousemove.zf.slider', function(e) {
             e.preventDefault();
 
             _this._handleEvent(e, curHandle);
 
-          }).on('mouseup.zf.slider', function(e){
+          }).on('mouseup.zf.slider', function(e) {
             _this._handleEvent(e, curHandle);
 
             $handle.removeClass('is-dragging');
           });
       });
     }
-    $handle.off('keydown.zf.slider').on('keydown.zf.slider', function(e){
+    
+    $handle.off('keydown.zf.slider').on('keydown.zf.slider', function(e) {
       var _$handle = $(this),
           idx = _this.options.doubleSided ? _this.handles.index(_$handle) : 0,
           oldValue = parseFloat(_this.inputs.eq(idx).val()),
           newValue;
 
-
       // handle keyboard event with keyboard util
       Foundation.Keyboard.handleKey(e, 'Slider', {
         decrease: function() {
         _this._setHandlePos(_$handle, newValue);
       }*/
     });
-  };
+  }
+
   /**
    * Destroys the slider plugin.
    */
-   Slider.prototype.destroy = function(){
-     this.handles.off('.zf.slider');
-     this.inputs.off('.zf.slider');
-     this.$element.off('.zf.slider');
+  destroy() {
+    this.handles.off('.zf.slider');
+    this.inputs.off('.zf.slider');
+    this.$element.off('.zf.slider');
 
-     Foundation.unregisterPlugin(this);
-   };
+    Foundation.unregisterPlugin(this);
+  }
+}
 
-  Foundation.plugin(Slider, 'Slider');
+Slider.defaults = {
+  /**
+   * Minimum value for the slider scale.
+   * @option
+   * @example 0
+   */
+  start: 0,
+  /**
+   * Maximum value for the slider scale.
+   * @option
+   * @example 100
+   */
+  end: 100,
+  /**
+   * Minimum value change per change event. Not Currently Implemented!
 
-  function percent(frac, num){
-    return (frac / num);
-  }
-  function absPosition($handle, dir, clickPos, param){
-    return Math.abs(($handle.position()[dir] + ($handle[param]() / 2)) - clickPos);
-  }
-}(jQuery, window.Foundation);
+   */
+  step: 1,
+  /**
+   * Value at which the handle/input *(left handle/first input)* should be set to on initialization.
+   * @option
+   * @example 0
+   */
+  initialStart: 0,
+  /**
+   * Value at which the right handle/second input should be set to on initialization.
+   * @option
+   * @example 100
+   */
+  initialEnd: 100,
+  /**
+   * Allows the input to be located outside the container and visible. Set to by the JS
+   * @option
+   * @example false
+   */
+  binding: false,
+  /**
+   * Allows the user to click/tap on the slider bar to select a value.
+   * @option
+   * @example true
+   */
+  clickSelect: true,
+  /**
+   * Set to true and use the `vertical` class to change alignment to vertical.
+   * @option
+   * @example false
+   */
+  vertical: false,
+  /**
+   * Allows the user to drag the slider handle(s) to select a value.
+   * @option
+   * @example true
+   */
+  draggable: true,
+  /**
+   * Disables the slider and prevents event listeners from being applied. Double checked by JS with `disabledClass`.
+   * @option
+   * @example false
+   */
+  disabled: false,
+  /**
+   * Allows the use of two handles. Double checked by the JS. Changes some logic handling.
+   * @option
+   * @example false
+   */
+  doubleSided: false,
+  /**
+   * Potential future feature.
+   */
+  // steps: 100,
+  /**
+   * Number of decimal places the plugin should go to for floating point precision.
+   * @option
+   * @example 2
+   */
+  decimal: 2,
+  /**
+   * Time delay for dragged elements.
+   */
+  // dragDelay: 0,
+  /**
+   * Time, in ms, to animate the movement of a slider handle if user clicks/taps on the bar. Needs to be manually set if updating the transition time in the Sass settings.
+   * @option
+   * @example 200
+   */
+  moveTime: 200,//update this if changing the transition time in the sass
+  /**
+   * Class applied to disabled sliders.
+   * @option
+   * @example 'disabled'
+   */
+  disabledClass: 'disabled',
+  invertVertical: false
+};
+
+function percent(frac, num) {
+  return (frac / num);
+}
+function absPosition($handle, dir, clickPos, param) {
+  return Math.abs(($handle.position()[dir] + ($handle[param]() / 2)) - clickPos);
+}
+
+// Window exports
+if (window.Foundation) {
+  window.Foundation.plugin(Slider, 'Slider');
+}
 
 //*********this is in case we go to static, absolute positions instead of dynamic positioning********
-// this.setSteps(function(){
+// this.setSteps(function() {
 //   _this._events();
 //   var initStart = _this.options.positions[_this.options.initialStart - 1] || null;
 //   var initEnd = _this.options.initialEnd ? _this.options.position[_this.options.initialEnd - 1] : null;
-//   if(initStart || initEnd){
+//   if (initStart || initEnd) {
 //     _this._handleEvent(initStart, initEnd);
 //   }
 // });
 
 //***********the other part of absolute positions*************
-// Slider.prototype.setSteps = function(cb){
+// Slider.prototype.setSteps = function(cb) {
 //   var posChange = this.$element.outerWidth() / this.options.steps;
 //   var counter = 0
-//   while(counter < this.options.steps){
-//     if(counter){
+//   while(counter < this.options.steps) {
+//     if (counter) {
 //       this.options.positions.push(this.options.positions[counter - 1] + posChange);
-//     }else{
+//     } else {
 //       this.options.positions.push(posChange);
 //     }
 //     counter++;