/*! $.noUiSlider - WTFPL - refreshless.com/nouislider/ */ /*jslint browser: true */ /*jslint devel: true */ /*jslint continue: true */ /*jslint plusplus: true */ /*jslint sub: true */ /*jslint white: true */ // ==ClosureCompiler== // @externs_url http://refreshless.com/externs/jquery-1.8.js // @compilation_level ADVANCED_OPTIMIZATIONS // @warning_level VERBOSE // ==/ClosureCompiler== define(['jquery'], function( $ ){ 'use strict'; var // Cache the document selector; /** @const */ doc = $(document), // Namespace for binding and unbinding slider events; /** @const */ namespace = '.nui', // Copy of the current value function; /** @const */ $val = $.fn.val, // Determine the events to bind. IE11 implements pointerEvents without // a prefix, which breaks compatibility with the IE10 implementation. /** @const */ actions = window.navigator.pointerEnabled ? { start: 'pointerdown', move: 'pointermove', end: 'pointerup' } : window.navigator.msPointerEnabled ? { start: 'MSPointerDown', move: 'MSPointerMove', end: 'MSPointerUp' } : { start: 'mousedown touchstart', move: 'mousemove touchmove', end: 'mouseup touchend' }, // Re-usable list of classes; /** @const */ Classes = [ /* 0 */ 'noUi-target' /* 1 */ ,'noUi-base' /* 2 */ ,'noUi-origin' /* 3 */ ,'noUi-handle' /* 4 */ ,'noUi-horizontal' /* 5 */ ,'noUi-vertical' /* 6 */ ,'noUi-background' /* 7 */ ,'noUi-connect' /* 8 */ ,'noUi-ltr' /* 9 */ ,'noUi-rtl' /* 10 */ ,'noUi-dragable' /* 11 */ ,'' /* 12 */ ,'noUi-state-drag' /* 13 */ ,'' /* 14 */ ,'noUi-state-tap' /* 15 */ ,'noUi-active' /* 16 */ ,'noUi-extended' /* 17 */ ,'noUi-stacking' ], /** @const */ Formatting = [ /* 0 */ 'decimals' /* 1 */ ,'mark' /* 2 */ ,'thousand' /* 3 */ ,'prefix' /* 4 */ ,'postfix' /* 5 */ ,'encoder' /* 6 */ ,'decoder' /* 7 */ ,'negative' /* 8 */ ,'negativeBefore' ], /** @const */ FormatDefaults = [ /* 0 */ 2 /* 1 */ ,'.' /* 2 */ ,'' /* 3 */ ,'' /* 4 */ ,'' /* 5 */ ,function(a){ return a; } /* 6 */ ,function(a){ return a; } /* 7 */ ,'-' /* 8 */ ,'' ]; // Error handling function throwError( message ){ throw new RangeError('noUiSlider: ' + message); } // Throw an error if formatting options are incompatible. function throwEqualError( F, a, b ) { if ( (F[a] || F[b]) && (F[a] === F[b]) ) { throwError("(Link) '"+a+"' can't match '"+b+"'.'"); } } // General helpers // Limits a value to 0 - 100 function limit ( a ) { return Math.max(Math.min(a, 100), 0); } // Round a value to the closest 'to'. function closest ( value, to ) { return Math.round(value / to) * to; } // Determine the size of a sub-range in relation to a full range. function subRangeRatio ( pa, pb ) { return (100 / (pb - pa)); } // Type validation function typeMatch ( a, b ) { return (typeof a) === (typeof b); } // Test in an object is an instance of jQuery or Zepto. function isInstance ( a ) { return a instanceof $ || ( $['zepto'] && $['zepto']['isZ'](a) ); } // Checks whether a value is numerical. function isNumeric ( a ) { return typeof a === 'number' && !isNaN( a ) && isFinite( a ); } // Wraps a variable as an array, if it isn't one yet. function asArray ( a ) { return $.isArray(a) ? a : [a]; } // Class handling // Sets a class and removes it after [duration] ms. function addClassFor ( element, className, duration ) { element.addClass(className); setTimeout(function(){ element.removeClass(className); }, duration); } // Tests if element has a class, adds it if not. Returns original state. function getsClass ( element, className ) { var has = element.hasClass(className); if ( !has ) { element.addClass( className ); } return has; } // Value calculation // (percentage) How many percent is this value of this range? function fromPercentage ( range, value ) { return (value * 100) / ( range[1] - range[0] ); } // (percentage) Where is this value on this range? function toPercentage ( range, value ) { return fromPercentage( range, range[0] < 0 ? value + Math.abs(range[0]) : value - range[0] ); } // (value) How much is this percentage on this range? function isPercentage ( range, value ) { return ((value * ( range[1] - range[0] )) / 100) + range[0]; } // (percentage) function toStepping ( options, value ) { if ( value >= options.xVal.slice(-1)[0] ){ return 100; } var j = 1, va, vb, pa, pb; while ( value >= options.xVal[j] ){ j++; } va = options.xVal[j-1]; vb = options.xVal[j]; pa = options.xPct[j-1]; pb = options.xPct[j]; return pa + (toPercentage([va, vb], value) / subRangeRatio (pa, pb)); } // (value) function fromStepping ( options, value ) { // There is no range group that fits 100 if ( value >= 100 ){ return options.xVal.slice(-1)[0]; } var j = 1, va, vb, pa, pb; while ( value >= options.xPct[j] ){ j++; } va = options.xVal[j-1]; vb = options.xVal[j]; pa = options.xPct[j-1]; pb = options.xPct[j]; return isPercentage([va, vb], (value - pa) * subRangeRatio (pa, pb)); } // (percentage) Get the step that applies at a certain value. function getStep ( options, value ){ var j = 1, a, b; while ( value >= options.xPct[j] ){ j++; } if ( options.snap ) { a = options.xPct[j-1]; b = options.xPct[j]; if ((value - a) > ((b-a)/2)){ return b; } return a; } if ( !options.xSteps[j-1] ){ return value; } return options.xPct[j-1] + closest( value - options.xPct[j-1], options.xSteps[j-1] ); } // Event handling // Provide a clean event with standardized offset values. function fixEvent ( e ) { // Prevent scrolling and panning on touch events, while // attempting to slide. The tap event also depends on this. e.preventDefault(); // Filter the event to register the type, which can be // touch, mouse or pointer. Offset changes need to be // made on an event specific basis. var touch = e.type.indexOf('touch') === 0 ,mouse = e.type.indexOf('mouse') === 0 ,pointer = e.type.indexOf('pointer') === 0 ,x,y, event = e; // IE10 implemented pointer events with a prefix; if ( e.type.indexOf('MSPointer') === 0 ) { pointer = true; } // Get the originalEvent, if the event has been wrapped // by jQuery. Zepto doesn't wrap the event. if ( e.originalEvent ) { e = e.originalEvent; } if ( touch ) { // noUiSlider supports one movement at a time, // so we can select the first 'changedTouch'. x = e.changedTouches[0].pageX; y = e.changedTouches[0].pageY; } if ( mouse || pointer ) { // Polyfill the pageXOffset and pageYOffset // variables for IE7 and IE8; if( !pointer && window.pageXOffset === undefined ){ window.pageXOffset = document.documentElement.scrollLeft; window.pageYOffset = document.documentElement.scrollTop; } x = e.clientX + window.pageXOffset; y = e.clientY + window.pageYOffset; } event.points = [x, y]; event.cursor = mouse; return event; } // Organize formatting in an object. /** @constructor */ function Format( options ){ // If no settings where provided, the defaults will be loaded. if ( options === undefined ){ options = {}; } if ( typeof options !== 'object' ){ throwError("(Format) 'format' option must be an object."); } var settings = {}; // Copy all values into a new object. $(Formatting).each(function(i, val){ if ( options[val] === undefined ){ settings[val] = FormatDefaults[i]; // When we aren't loading defaults, validate the entry. } else if ( typeMatch(options[val], FormatDefaults[i]) ) { // Support for up to 7 decimals. // More can't be guaranteed due to floating point issues. if ( val === 'decimals' ){ if ( options[val] < 0 || options[val] > 7 ){ throwError("(Format) 'format.decimals' option must be between 0 and 7."); } } settings[val] = options[val]; // If the value isn't valid, emit an error. } else { throwError("(Format) 'format."+val+"' must be a " + typeof FormatDefaults[i] + "."); } }); // Some values can't be extracted from a // string if certain combinations are present. throwEqualError(settings, 'mark', 'thousand'); throwEqualError(settings, 'prefix', 'negative'); throwEqualError(settings, 'prefix', 'negativeBefore'); this.settings = settings; } // Shorthand for internal value get Format.prototype.v = function ( a ) { return this.settings[a]; }; Format.prototype.to = function ( number ) { function reverse ( a ) { return a.split('').reverse().join(''); } number = this.v('encoder')( number ); var negative = '', preNegative = '', base = '', mark = ''; if ( number < 0 ) { negative = this.v('negative'); preNegative = this.v('negativeBefore'); } // Round to proper decimal count number = Math.abs(number).toFixed( this.v('decimals') ).toString(); number = number.split('.'); // Rounding away decimals might cause a value of -0 // when using very small ranges. Remove those cases. if ( parseFloat(number) === 0 ) { number[0] = '0'; } // Group numbers in sets of three. if ( this.v('thousand') ) { base = reverse(number[0]).match(/.{1,3}/g); base = reverse(base.join(reverse( this.v('thousand') ))); } else { base = number[0]; } // Ignore the decimal separator if decimals are set to 0. if ( this.v('mark') && number.length > 1 ) { mark = this.v('mark') + number[1]; } // Return the finalized formatted number. return preNegative + this.v('prefix') + negative + base + mark + this.v('postfix'); }; Format.prototype.from = function ( input ) { function esc(s){ return s.replace(/[\-\/\\\^$*+?.()|\[\]{}]/g, '\\$&'); } var isNeg; // The set request might want to ignore this handle. // Test for 'undefined' too, as a two-handle slider // can still be set with an integer. if( input === null || input === undefined ) { return false; } // Remove formatting and set period for float parsing. input = input.toString(); // Replace the preNegative indicator. isNeg = input.replace(new RegExp('^' + esc( this.v('negativeBefore') )), ''); // Check if the value changed by removing the negativeBefore symbol. if( input !== isNeg ) { input = isNeg; isNeg = '-'; } else { isNeg = ''; } // If prefix is set and the number is actually prefixed. input = input.replace(new RegExp('^'+esc( this.v('prefix') )), ''); // Only replace if a negative sign is set. if ( this.v['negative'] ) { // Reset isNeg to prevent double '-' insertion. isNeg = ''; // Reset the negative sign to '-' input = input.replace(new RegExp('^'+esc( this.v('negative') )), '-'); } // Clean the input string input = input // If postfix is set and the number is postfixed. .replace( new RegExp(esc( this.v('postfix') ) + '$'), '') // Remove the separator every three digits. .replace( new RegExp(esc( this.v('thousand') ), 'g'), '') // Set the decimal separator back to period. .replace( this.v('mark'), '.'); // Run the user defined decoder. Returns input by default. input = this.v('decoder')( parseFloat( isNeg + input ) ); // Ignore invalid input if (isNaN( input )) { return false; } return input; }; // Serialization target /** @constructor */ function Link( entry, update ){ // Make sure Link isn't called as a function, in which case // the 'this' scope would be the window. if ( !(this instanceof Link) ) { throw new Error( "Link: " + "Don't use Link as a function. " + "Use the 'new' keyword."); } if ( !entry ) { throw new RangeError("Link: missing parameters."); } // Write all formatting to this object. // No validation needed, as we'll merge these with the parent // format options first. this.formatting = entry['format'] || {}; // Store the update option. this.update = !update; // In IE < 9, .bind() isn't available, need this link in .change(). var that = this, // Get values from the input. target = entry['target'] || function(){}, method = entry['method'], // Find the type of this link. isTooltip = ( typeof target === 'string' && target.indexOf('-tooltip-') === 0 ), isHidden = ( typeof target === 'string' && target.indexOf('-') !== 0 ), isMethod = ( typeof target === 'function' ), is$ = ( isInstance(target) ), isInput = ( is$ && target.is('input, select, textarea') ), methodIsFunction = ( is$ && typeof method === 'function' ), methodIsName = ( is$ && typeof method === 'string' && target[method] ); // If target is a string, a new hidden input will be created. if ( isTooltip ) { // By default, use the 'html' method. this.method = method || 'html'; // Use jQuery to create the element this.el = $( target.replace('-tooltip-', '') || '
' )[0]; return; } // If the string doesn't begin with '-', which is reserved, add a new hidden input. if ( isHidden ) { this.method = 'val'; this.el = document.createElement('input'); this.el.name = target; this.el.type = 'hidden'; return; } // The target can also be a function, which will be called. if ( isMethod ) { this.target = false; this.method = target; return; } // If the target is and $ element. if ( is$ ) { // The method must exist on the element. if ( method && ( methodIsFunction || methodIsName ) ) { this.target = target; this.method = method; return; } // If a jQuery/Zepto input element is provided, but no method is set, // the element can assume it needs to respond to 'change'... if ( !method && isInput ) { // Default to .val if this is an input element. this.method = 'val'; this.target = target; // Set the slider to a new value on change. this.target.on('change', function( e ){ // Returns null array. function at(a,b,c){ return [c?a:b, c?b:a]; } var output = at(null, $(e.target).val(), that.N); that.obj.val(output, { 'link': that }); }); return; } // ... or not. if ( !method && !isInput ) { // Default arbitrarily to 'html'. this.method = 'html'; this.target = target; return; } } throw new RangeError("Link: Invalid Link."); } // Provides external items with the slider value. Link.prototype.write = function ( options, value, handle, slider, update ) { // Don't synchronize this Link. if ( this.update && update === false ) { return; } // Convert the value to the slider stepping/range. value = fromStepping( options, value ); // Format values for display. value = this.format( value ); // Store the numerical value. this.saved = value; // Branch between serialization to a function or an object. if ( typeof this.method === 'function' ) { // When target is undefined, the target was a function. // In that case, provided the slider as the calling scope. // Use [0] to get the DOM element, not the $ instance. this.method.call( this.target[0] || slider[0], value, handle, slider ); } else { this.target[ this.method ]( value, handle, slider ); } }; // Parses slider value to user defined display. Link.prototype.format = function ( a ) { return this.formatting.to(a); }; // Converts a formatted value back to a real number. Link.prototype.valueOf = function ( a ) { return this.formatting.from(a); }; // Input validation function testStep ( parsed, entry ) { if ( !isNumeric( entry ) ) { throwError("'step' is not numeric."); } // The step option can still be used to set stepping // for linear sliders. Overwritten if set in 'range'. parsed.xSteps[0] = entry; } function testRange ( parsed, entry ) { // Filter incorrect input. if ( typeof entry !== 'object' || $.isArray(entry) ) { throwError("'range' is not an object."); } // Loop all entries. $.each( entry, function ( index, value ) { var percentage; // Wrap numerical input in an array. if ( typeof value === "number" ) { value = [value]; } // Reject any invalid input. if ( !$.isArray( value ) ){ throwError("'range' contains invalid value."); } // Covert min/max syntax to 0 and 100. if ( index === 'min' ) { percentage = 0; } else if ( index === 'max' ) { percentage = 100; } else { percentage = parseFloat( index ); } // Check for correct input. if ( !isNumeric( percentage ) || !isNumeric( value[0] ) ) { throwError("'range' value isn't numeric."); } // Store values. parsed.xPct.push( percentage ); parsed.xVal.push( value[0] ); // NaN will evaluate to false too, but to keep // logging clear, set step explicitly. Make sure // not to override the 'step' setting with false. if ( !percentage ) { if ( !isNaN( value[1] ) ) { parsed.xSteps[0] = value[1]; } } else { parsed.xSteps.push( isNaN(value[1]) ? false : value[1] ); } }); $.each(parsed.xSteps, function(i,n){ // Ignore 'false' stepping. if ( !n ) { return true; } // Check if step fits. Not required, but this might serve some goal. // !((parsed.xVal[i+1] - parsed.xVal[i]) % n); // Factor to range ratio parsed.xSteps[i] = fromPercentage([ parsed.xVal[i] ,parsed.xVal[i+1] ], n) / subRangeRatio ( parsed.xPct[i], parsed.xPct[i+1] ); }); } function testStart ( parsed, entry ) { if ( typeof entry === "number" ) { entry = [entry]; } // Validate input. Values aren't tested, the internal Link will do // that and provide a valid location. if ( !$.isArray( entry ) || !entry.length || entry.length > 2 ) { throwError("'start' option is incorrect."); } // Store the number of handles. parsed.handles = entry.length; // When the slider is initialized, the .val method will // be called with the start options. parsed.start = entry; } function testSnap ( parsed, entry ) { // Enforce 100% stepping within subranges. parsed.snap = entry; if ( typeof entry !== 'boolean' ){ throwError("'snap' option must be a boolean."); } } function testConnect ( parsed, entry ) { if ( entry === 'lower' && parsed.handles === 1 ) { parsed.connect = 1; } else if ( entry === 'upper' && parsed.handles === 1 ) { parsed.connect = 2; } else if ( entry === true && parsed.handles === 2 ) { parsed.connect = 3; } else if ( entry === false ) { parsed.connect = 0; } else { throwError("'connect' option was doesn't match handle count."); } } function testOrientation ( parsed, entry ) { // Set orientation to an a numerical value for easy // array selection. switch ( entry ){ case 'horizontal': parsed.ort = 0; break; case 'vertical': parsed.ort = 1; break; default: throwError("'orientation' option is invalid."); } } function testMargin ( parsed, entry ) { if ( parsed.xPct.length > 2 ) { throwError("'margin' option is only supported on linear sliders."); } // Parse value to range and store. As xVal is checked // to be no bigger than 2, use it as range. parsed.margin = fromPercentage(parsed.xVal, entry); if ( !isNumeric(entry) ){ throwError("'margin' option must be numeric."); } } function testDirection ( parsed, entry ) { // Set direction as a numerical value for easy parsing. // Invert connection for RTL sliders, so that the proper // handles get the connect/background classes. switch ( entry ) { case 'ltr': parsed.dir = 0; break; case 'rtl': parsed.dir = 1; parsed.connect = [0,2,1,3][parsed.connect]; break; default: throwError("'direction' option was not recognized."); } } function testBehaviour ( parsed, entry ) { // Make sure the input is a string. if ( typeof entry !== 'string' ) { throwError("'behaviour' must be a string containing options."); } // Check if the string contains any keywords. // None are required. var tap = entry.indexOf('tap') >= 0, extend = entry.indexOf('extend') >= 0, drag = entry.indexOf('drag') >= 0, fixed = entry.indexOf('fixed') >= 0, snap = entry.indexOf('snap') >= 0; parsed.events = { tap: tap || snap, extend: extend, drag: drag, fixed: fixed, snap: snap }; } function testSerialization ( parsed, entry, sliders ) { parsed.ser = [ entry['lower'], entry['upper'] ]; parsed.formatting = new Format( entry['format'] ); $.each( parsed.ser, function( i, a ){ // Check if the provided option is an array. if ( !$.isArray(a) ) { throwError("'serialization."+(!i?'lower':'upper')+"' must be an array."); } $.each(a, function(){ // Check if entry is a Link. if ( !(this instanceof Link) ) { throwError("'serialization."+(!i?'lower':'upper')+"' can only contain Link instances."); } // Assign other properties. this.N = i; this.obj = sliders; this.scope = this.scope || sliders; // Run internal validator. this.formatting = new Format($.extend({} ,entry['format'] ,this.formatting )); }); }); // If the slider has two handles and is RTL, // reverse the serialization input. For one handle, // lower is still lower. if ( parsed.dir && parsed.handles > 1 ) { parsed.ser.reverse(); } } // Test all developer settings and parse to assumption-safe values. function test ( options, sliders ){ /* Every input option is tested and parsed. This'll prevent endless validation in internal methods. These tests are structured with an item for every option available. An option can be marked as required by setting the 'r' flag. The testing function is provided with three arguments: - The provided value for the option; - A reference to the options object; - The name for the option; The testing function returns false when an error is detected, or true when everything is OK. It can also modify the option object, to make sure all values can be correctly looped elsewhere. */ var parsed = { xPct: [] ,xVal: [] ,xSteps: [ false ] ,margin: 0 }, tests; tests = { 'step': { r: false, t: testStep }, 'range': { r: true, t: testRange }, 'start': { r: true, t: testStart }, 'snap': { r: false, t: testSnap }, 'connect': { r: true, t: testConnect }, 'orientation': { r: false, t: testOrientation }, 'margin': { r: false, t: testMargin }, 'direction': { r: true, t: testDirection }, 'behaviour': { r: true, t: testBehaviour }, 'serialization': { r: true, t: testSerialization } }; // Set defaults where applicable. options = $.extend({ 'connect': false ,'direction': 'ltr' ,'behaviour': 'tap' ,'orientation': 'horizontal' }, options); // Make sure the test for serialization runs. options['serialization'] = $.extend({ 'lower': [] ,'upper': [] ,'format': {} }, options['serialization']); // Run all options through a testing mechanism to ensure correct // input. It should be noted that options might get modified to // be handled properly. E.g. wrapping integers in arrays. $.each( tests, function( name, test ){ if ( options[name] === undefined ) { if ( test.r ) { throwError("'" + name + "' is required."); } else { return true; } } test.t( parsed, options[name], sliders ); }); // Pre-define the styles. parsed.style = parsed.ort ? 'top' : 'left'; return parsed; } // DOM additions // Append a handle to the base. function addHandle ( options, index ) { var handle = $('