'use strict'; /*! ========================================================= * bootstrap-slider.js * * Maintainers: * Kyle Kemp * - Twitter: @seiyria * - Github: seiyria * Rohit Kalkur * - Twitter: @Rovolutionary * - Github: rovolution * * ========================================================= * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================= */ /** * Bridget makes jQuery widgets * v1.0.1 * MIT license */ (function(root, factory) { if(typeof define === "function" && define.amd) { define(["jquery"], factory); } else if(typeof module === "object" && module.exports) { var jQuery; try { jQuery = require("jquery"); } catch (err) { jQuery = null; } module.exports = factory(jQuery); } else { root.Slider = factory(root.jQuery); } }(this, function($) { // Reference to Slider constructor var Slider; (function( $ ) { 'use strict'; // -------------------------- utils -------------------------- // var slice = Array.prototype.slice; function noop() {} // -------------------------- definition -------------------------- // function defineBridget( $ ) { // bail if no jQuery if ( !$ ) { return; } // -------------------------- addOptionMethod -------------------------- // /** * adds option method -> $().plugin('option', {...}) * @param {Function} PluginClass - constructor class */ function addOptionMethod( PluginClass ) { // don't overwrite original option method if ( PluginClass.prototype.option ) { return; } // option setter PluginClass.prototype.option = function( opts ) { // bail out if not an object if ( !$.isPlainObject( opts ) ){ return; } this.options = $.extend( true, this.options, opts ); }; } // -------------------------- plugin bridge -------------------------- // // helper function for logging errors // $.error breaks jQuery chaining var logError = typeof console === 'undefined' ? noop : function( message ) { console.error( message ); }; /** * jQuery plugin bridge, access methods like $elem.plugin('method') * @param {String} namespace - plugin name * @param {Function} PluginClass - constructor class */ function bridge( namespace, PluginClass ) { // add to jQuery fn namespace $.fn[ namespace ] = function( options ) { if ( typeof options === 'string' ) { // call plugin method when first argument is a string // get arguments for method var args = slice.call( arguments, 1 ); for ( var i=0, len = this.length; i < len; i++ ) { var elem = this[i]; var instance = $.data( elem, namespace ); if ( !instance ) { logError( "cannot call methods on " + namespace + " prior to initialization; " + "attempted to call '" + options + "'" ); continue; } if ( !$.isFunction( instance[options] ) || options.charAt(0) === '_' ) { logError( "no such method '" + options + "' for " + namespace + " instance" ); continue; } // trigger method with arguments var returnValue = instance[ options ].apply( instance, args); // break look and return first value if provided if ( returnValue !== undefined && returnValue !== instance) { return returnValue; } } // return this if no return value return this; } else { var objects = this.map( function() { var instance = $.data( this, namespace ); if ( instance ) { // apply options & init instance.option( options ); instance._init(); } else { // initialize new instance instance = new PluginClass( this, options ); $.data( this, namespace, instance ); } return $(this); }); if(!objects || objects.length > 1) { return objects; } else { return objects[0]; } } }; } // -------------------------- bridget -------------------------- // /** * converts a Prototypical class into a proper jQuery plugin * the class must have a ._init method * @param {String} namespace - plugin name, used in $().pluginName * @param {Function} PluginClass - constructor class */ $.bridget = function( namespace, PluginClass ) { addOptionMethod( PluginClass ); bridge( namespace, PluginClass ); }; return $.bridget; } // get jquery from browser global defineBridget( $ ); })( $ ); /************************************************* BOOTSTRAP-SLIDER SOURCE CODE **************************************************/ (function($) { var ErrorMsgs = { formatInvalidInputErrorMsg : function(input) { return "Invalid input value '" + input + "' passed in"; }, callingContextNotSliderInstance : "Calling context element does not have instance of Slider bound to it. Check your code to make sure the JQuery object returned from the call to the slider() initializer is calling the method" }; var SliderScale = { linear: { toValue: function(percentage) { var rawValue = percentage/100 * (this.options.max - this.options.min); if (this.options.ticks_positions.length > 0) { var minv, maxv, minp, maxp = 0; for (var i = 0; i < this.options.ticks_positions.length; i++) { if (percentage <= this.options.ticks_positions[i]) { minv = (i > 0) ? this.options.ticks[i-1] : 0; minp = (i > 0) ? this.options.ticks_positions[i-1] : 0; maxv = this.options.ticks[i]; maxp = this.options.ticks_positions[i]; break; } } if (i > 0) { var partialPercentage = (percentage - minp) / (maxp - minp); rawValue = minv + partialPercentage * (maxv - minv); } } var value = this.options.min + Math.round(rawValue / this.options.step) * this.options.step; if (value < this.options.min) { return this.options.min; } else if (value > this.options.max) { return this.options.max; } else { return value; } }, toPercentage: function(value) { if (this.options.max === this.options.min) { return 0; } if (this.options.ticks_positions.length > 0) { var minv, maxv, minp, maxp = 0; for (var i = 0; i < this.options.ticks.length; i++) { if (value <= this.options.ticks[i]) { minv = (i > 0) ? this.options.ticks[i-1] : 0; minp = (i > 0) ? this.options.ticks_positions[i-1] : 0; maxv = this.options.ticks[i]; maxp = this.options.ticks_positions[i]; break; } } if (i > 0) { var partialPercentage = (value - minv) / (maxv - minv); return minp + partialPercentage * (maxp - minp); } } return 100 * (value - this.options.min) / (this.options.max - this.options.min); } }, logarithmic: { /* Based on http://stackoverflow.com/questions/846221/logarithmic-slider */ toValue: function(percentage) { var min = (this.options.min === 0) ? 0 : Math.log(this.options.min); var max = Math.log(this.options.max); var value = Math.exp(min + (max - min) * percentage / 100); value = this.options.min + Math.round((value - this.options.min) / this.options.step) * this.options.step; /* Rounding to the nearest step could exceed the min or * max, so clip to those values. */ if (value < this.options.min) { return this.options.min; } else if (value > this.options.max) { return this.options.max; } else { return value; } }, toPercentage: function(value) { if (this.options.max === this.options.min) { return 0; } else { var max = Math.log(this.options.max); var min = this.options.min === 0 ? 0 : Math.log(this.options.min); var v = value === 0 ? 0 : Math.log(value); return 100 * (v - min) / (max - min); } } } }; /************************************************* CONSTRUCTOR **************************************************/ Slider = function(element, options) { createNewSlider.call(this, element, options); return this; }; function createNewSlider(element, options) { /* The internal state object is used to store data about the current 'state' of slider. This includes values such as the `value`, `enabled`, etc... */ this._state = { value: null, enabled: null, offset: null, size: null, percentage: null, inDrag: false, over: false }; if(typeof element === "string") { this.element = document.querySelector(element); } else if(element instanceof HTMLElement) { this.element = element; } /************************************************* Process Options **************************************************/ options = options ? options : {}; var optionTypes = Object.keys(this.defaultOptions); for(var i = 0; i < optionTypes.length; i++) { var optName = optionTypes[i]; // First check if an option was passed in via the constructor var val = options[optName]; // If no data attrib, then check data atrributes val = (typeof val !== 'undefined') ? val : getDataAttrib(this.element, optName); // Finally, if nothing was specified, use the defaults val = (val !== null) ? val : this.defaultOptions[optName]; // Set all options on the instance of the Slider if(!this.options) { this.options = {}; } this.options[optName] = val; } /* Validate `tooltip_position` against 'orientation` - if `tooltip_position` is incompatible with orientation, swith it to a default compatible with specified `orientation` -- default for "vertical" -> "right" -- default for "horizontal" -> "left" */ if(this.options.orientation === "vertical" && (this.options.tooltip_position === "top" || this.options.tooltip_position === "bottom")) { this.options.tooltip_position = "right"; } else if(this.options.orientation === "horizontal" && (this.options.tooltip_position === "left" || this.options.tooltip_position === "right")) { this.options.tooltip_position = "top"; } function getDataAttrib(element, optName) { var dataName = "data-slider-" + optName.replace(/_/g, '-'); var dataValString = element.getAttribute(dataName); try { return JSON.parse(dataValString); } catch(err) { return dataValString; } } /************************************************* Create Markup **************************************************/ var origWidth = this.element.style.width; var updateSlider = false; var parent = this.element.parentNode; var sliderTrackSelection; var sliderTrackLow, sliderTrackHigh; var sliderMinHandle; var sliderMaxHandle; if (this.sliderElem) { updateSlider = true; } else { /* Create elements needed for slider */ this.sliderElem = document.createElement("div"); this.sliderElem.className = "slider"; /* Create slider track elements */ var sliderTrack = document.createElement("div"); sliderTrack.className = "slider-track"; sliderTrackLow = document.createElement("div"); sliderTrackLow.className = "slider-track-low"; sliderTrackSelection = document.createElement("div"); sliderTrackSelection.className = "slider-selection"; sliderTrackHigh = document.createElement("div"); sliderTrackHigh.className = "slider-track-high"; sliderMinHandle = document.createElement("div"); sliderMinHandle.className = "slider-handle min-slider-handle"; sliderMaxHandle = document.createElement("div"); sliderMaxHandle.className = "slider-handle max-slider-handle"; sliderTrack.appendChild(sliderTrackLow); sliderTrack.appendChild(sliderTrackSelection); sliderTrack.appendChild(sliderTrackHigh); /* Create ticks */ this.ticks = []; if (Array.isArray(this.options.ticks) && this.options.ticks.length > 0) { for (i = 0; i < this.options.ticks.length; i++) { var tick = document.createElement('div'); tick.className = 'slider-tick'; this.ticks.push(tick); sliderTrack.appendChild(tick); } sliderTrackSelection.className += " tick-slider-selection"; } sliderTrack.appendChild(sliderMinHandle); sliderTrack.appendChild(sliderMaxHandle); this.tickLabels = []; if (Array.isArray(this.options.ticks_labels) && this.options.ticks_labels.length > 0) { this.tickLabelContainer = document.createElement('div'); this.tickLabelContainer.className = 'slider-tick-label-container'; for (i = 0; i < this.options.ticks_labels.length; i++) { var label = document.createElement('div'); var noTickPositionsSpecified = this.options.ticks_positions.length === 0; var tickLabelsIndex = (this.options.reversed && noTickPositionsSpecified) ? (this.options.ticks_labels.length - (i + 1)) : i; label.className = 'slider-tick-label'; label.innerHTML = this.options.ticks_labels[tickLabelsIndex]; this.tickLabels.push(label); this.tickLabelContainer.appendChild(label); } } var createAndAppendTooltipSubElements = function(tooltipElem) { var arrow = document.createElement("div"); arrow.className = "tooltip-arrow"; var inner = document.createElement("div"); inner.className = "tooltip-inner"; tooltipElem.appendChild(arrow); tooltipElem.appendChild(inner); }; /* Create tooltip elements */ var sliderTooltip = document.createElement("div"); sliderTooltip.className = "tooltip tooltip-main"; createAndAppendTooltipSubElements(sliderTooltip); var sliderTooltipMin = document.createElement("div"); sliderTooltipMin.className = "tooltip tooltip-min"; createAndAppendTooltipSubElements(sliderTooltipMin); var sliderTooltipMax = document.createElement("div"); sliderTooltipMax.className = "tooltip tooltip-max"; createAndAppendTooltipSubElements(sliderTooltipMax); /* Append components to sliderElem */ this.sliderElem.appendChild(sliderTrack); this.sliderElem.appendChild(sliderTooltip); this.sliderElem.appendChild(sliderTooltipMin); this.sliderElem.appendChild(sliderTooltipMax); if (this.tickLabelContainer) { this.sliderElem.appendChild(this.tickLabelContainer); } /* Append slider element to parent container, right before the original element */ parent.insertBefore(this.sliderElem, this.element); /* Hide original element */ this.element.style.display = "none"; } /* If JQuery exists, cache JQ references */ if($) { this.$element = $(this.element); this.$sliderElem = $(this.sliderElem); } /************************************************* Setup **************************************************/ this.eventToCallbackMap = {}; this.sliderElem.id = this.options.id; this.touchCapable = 'ontouchstart' in window || (window.DocumentTouch && document instanceof window.DocumentTouch); this.tooltip = this.sliderElem.querySelector('.tooltip-main'); this.tooltipInner = this.tooltip.querySelector('.tooltip-inner'); this.tooltip_min = this.sliderElem.querySelector('.tooltip-min'); this.tooltipInner_min = this.tooltip_min.querySelector('.tooltip-inner'); this.tooltip_max = this.sliderElem.querySelector('.tooltip-max'); this.tooltipInner_max= this.tooltip_max.querySelector('.tooltip-inner'); if (SliderScale[this.options.scale]) { this.options.scale = SliderScale[this.options.scale]; } if (updateSlider === true) { // Reset classes this._removeClass(this.sliderElem, 'slider-horizontal'); this._removeClass(this.sliderElem, 'slider-vertical'); this._removeClass(this.tooltip, 'hide'); this._removeClass(this.tooltip_min, 'hide'); this._removeClass(this.tooltip_max, 'hide'); // Undo existing inline styles for track ["left", "top", "width", "height"].forEach(function(prop) { this._removeProperty(this.trackLow, prop); this._removeProperty(this.trackSelection, prop); this._removeProperty(this.trackHigh, prop); }, this); // Undo inline styles on handles [this.handle1, this.handle2].forEach(function(handle) { this._removeProperty(handle, 'left'); this._removeProperty(handle, 'top'); }, this); // Undo inline styles and classes on tooltips [this.tooltip, this.tooltip_min, this.tooltip_max].forEach(function(tooltip) { this._removeProperty(tooltip, 'left'); this._removeProperty(tooltip, 'top'); this._removeProperty(tooltip, 'margin-left'); this._removeProperty(tooltip, 'margin-top'); this._removeClass(tooltip, 'right'); this._removeClass(tooltip, 'top'); }, this); } if(this.options.orientation === 'vertical') { this._addClass(this.sliderElem,'slider-vertical'); this.stylePos = 'top'; this.mousePos = 'pageY'; this.sizePos = 'offsetHeight'; } else { this._addClass(this.sliderElem, 'slider-horizontal'); this.sliderElem.style.width = origWidth; this.options.orientation = 'horizontal'; this.stylePos = 'left'; this.mousePos = 'pageX'; this.sizePos = 'offsetWidth'; } this._setTooltipPosition(); /* In case ticks are specified, overwrite the min and max bounds */ if (Array.isArray(this.options.ticks) && this.options.ticks.length > 0) { this.options.max = Math.max.apply(Math, this.options.ticks); this.options.min = Math.min.apply(Math, this.options.ticks); } if (Array.isArray(this.options.value)) { this.options.range = true; this._state.value = this.options.value; } else if (this.options.range) { // User wants a range, but value is not an array this._state.value = [this.options.value, this.options.max]; } else { this._state.value = this.options.value; } this.trackLow = sliderTrackLow || this.trackLow; this.trackSelection = sliderTrackSelection || this.trackSelection; this.trackHigh = sliderTrackHigh || this.trackHigh; if (this.options.selection === 'none') { this._addClass(this.trackLow, 'hide'); this._addClass(this.trackSelection, 'hide'); this._addClass(this.trackHigh, 'hide'); } this.handle1 = sliderMinHandle || this.handle1; this.handle2 = sliderMaxHandle || this.handle2; if (updateSlider === true) { // Reset classes this._removeClass(this.handle1, 'round triangle'); this._removeClass(this.handle2, 'round triangle hide'); for (i = 0; i < this.ticks.length; i++) { this._removeClass(this.ticks[i], 'round triangle hide'); } } var availableHandleModifiers = ['round', 'triangle', 'custom']; var isValidHandleType = availableHandleModifiers.indexOf(this.options.handle) !== -1; if (isValidHandleType) { this._addClass(this.handle1, this.options.handle); this._addClass(this.handle2, this.options.handle); for (i = 0; i < this.ticks.length; i++) { this._addClass(this.ticks[i], this.options.handle); } } this._state.offset = this._offset(this.sliderElem); this._state.size = this.sliderElem[this.sizePos]; this.setValue(this._state.value); /****************************************** Bind Event Listeners ******************************************/ // Bind keyboard handlers this.handle1Keydown = this._keydown.bind(this, 0); this.handle1.addEventListener("keydown", this.handle1Keydown, false); this.handle2Keydown = this._keydown.bind(this, 1); this.handle2.addEventListener("keydown", this.handle2Keydown, false); this.mousedown = this._mousedown.bind(this); if (this.touchCapable) { // Bind touch handlers this.sliderElem.addEventListener("touchstart", this.mousedown, false); } this.sliderElem.addEventListener("mousedown", this.mousedown, false); // Bind tooltip-related handlers if(this.options.tooltip === 'hide') { this._addClass(this.tooltip, 'hide'); this._addClass(this.tooltip_min, 'hide'); this._addClass(this.tooltip_max, 'hide'); } else if(this.options.tooltip === 'always') { this._showTooltip(); this._alwaysShowTooltip = true; } else { this.showTooltip = this._showTooltip.bind(this); this.hideTooltip = this._hideTooltip.bind(this); this.sliderElem.addEventListener("mouseenter", this.showTooltip, false); this.sliderElem.addEventListener("mouseleave", this.hideTooltip, false); this.handle1.addEventListener("focus", this.showTooltip, false); this.handle1.addEventListener("blur", this.hideTooltip, false); this.handle2.addEventListener("focus", this.showTooltip, false); this.handle2.addEventListener("blur", this.hideTooltip, false); } if(this.options.enabled) { this.enable(); } else { this.disable(); } } /************************************************* INSTANCE PROPERTIES/METHODS - Any methods bound to the prototype are considered part of the plugin's `public` interface **************************************************/ Slider.prototype = { _init: function() {}, // NOTE: Must exist to support bridget constructor: Slider, defaultOptions: { id: "", min: 0, max: 10, step: 1, precision: 0, orientation: 'horizontal', value: 5, range: false, selection: 'before', tooltip: 'show', tooltip_split: false, handle: 'round', reversed: false, enabled: true, formatter: function(val) { if (Array.isArray(val)) { return val[0] + " : " + val[1]; } else { return val; } }, natural_arrow_keys: false, ticks: [], ticks_positions: [], ticks_labels: [], ticks_snap_bounds: 0, scale: 'linear', focus: false, tooltip_position: null }, getElement: function() { return this.sliderElem; }, getValue: function() { if (this.options.range) { return this._state.value; } else { return this._state.value[0]; } }, setValue: function(val, triggerSlideEvent, triggerChangeEvent) { if (!val) { val = 0; } var oldValue = this.getValue(); this._state.value = this._validateInputValue(val); var applyPrecision = this._applyPrecision.bind(this); if (this.options.range) { this._state.value[0] = applyPrecision(this._state.value[0]); this._state.value[1] = applyPrecision(this._state.value[1]); this._state.value[0] = Math.max(this.options.min, Math.min(this.options.max, this._state.value[0])); this._state.value[1] = Math.max(this.options.min, Math.min(this.options.max, this._state.value[1])); } else { this._state.value = applyPrecision(this._state.value); this._state.value = [ Math.max(this.options.min, Math.min(this.options.max, this._state.value))]; this._addClass(this.handle2, 'hide'); if (this.options.selection === 'after') { this._state.value[1] = this.options.max; } else { this._state.value[1] = this.options.min; } } if (this.options.max > this.options.min) { this._state.percentage = [ this._toPercentage(this._state.value[0]), this._toPercentage(this._state.value[1]), this.options.step * 100 / (this.options.max - this.options.min) ]; } else { this._state.percentage = [0, 0, 100]; } this._layout(); var newValue = this.options.range ? this._state.value : this._state.value[0]; if(triggerSlideEvent === true) { this._trigger('slide', newValue); } if( (oldValue !== newValue) && (triggerChangeEvent === true) ) { this._trigger('change', { oldValue: oldValue, newValue: newValue }); } this._setDataVal(newValue); return this; }, destroy: function(){ // Remove event handlers on slider elements this._removeSliderEventHandlers(); // Remove the slider from the DOM this.sliderElem.parentNode.removeChild(this.sliderElem); /* Show original element */ this.element.style.display = ""; // Clear out custom event bindings this._cleanUpEventCallbacksMap(); // Remove data values this.element.removeAttribute("data"); // Remove JQuery handlers/data if($) { this._unbindJQueryEventHandlers(); this.$element.removeData('slider'); } }, disable: function() { this._state.enabled = false; this.handle1.removeAttribute("tabindex"); this.handle2.removeAttribute("tabindex"); this._addClass(this.sliderElem, 'slider-disabled'); this._trigger('slideDisabled'); return this; }, enable: function() { this._state.enabled = true; this.handle1.setAttribute("tabindex", 0); this.handle2.setAttribute("tabindex", 0); this._removeClass(this.sliderElem, 'slider-disabled'); this._trigger('slideEnabled'); return this; }, toggle: function() { if(this._state.enabled) { this.disable(); } else { this.enable(); } return this; }, isEnabled: function() { return this._state.enabled; }, on: function(evt, callback) { this._bindNonQueryEventHandler(evt, callback); return this; }, off: function(evt, callback) { if($) { this.$element.off(evt, callback); this.$sliderElem.off(evt, callback); } else { this._unbindNonQueryEventHandler(evt, callback); } }, getAttribute: function(attribute) { if(attribute) { return this.options[attribute]; } else { return this.options; } }, setAttribute: function(attribute, value) { this.options[attribute] = value; return this; }, refresh: function() { this._removeSliderEventHandlers(); createNewSlider.call(this, this.element, this.options); if($) { // Bind new instance of slider to the element $.data(this.element, 'slider', this); } return this; }, relayout: function() { this._layout(); return this; }, /******************************+ HELPERS - Any method that is not part of the public interface. - Place it underneath this comment block and write its signature like so: _fnName : function() {...} ********************************/ _removeSliderEventHandlers: function() { // Remove keydown event listeners this.handle1.removeEventListener("keydown", this.handle1Keydown, false); this.handle2.removeEventListener("keydown", this.handle2Keydown, false); if (this.showTooltip) { this.handle1.removeEventListener("focus", this.showTooltip, false); this.handle2.removeEventListener("focus", this.showTooltip, false); } if (this.hideTooltip) { this.handle1.removeEventListener("blur", this.hideTooltip, false); this.handle2.removeEventListener("blur", this.hideTooltip, false); } // Remove event listeners from sliderElem if (this.showTooltip) { this.sliderElem.removeEventListener("mouseenter", this.showTooltip, false); } if (this.hideTooltip) { this.sliderElem.removeEventListener("mouseleave", this.hideTooltip, false); } this.sliderElem.removeEventListener("touchstart", this.mousedown, false); this.sliderElem.removeEventListener("mousedown", this.mousedown, false); }, _bindNonQueryEventHandler: function(evt, callback) { if(this.eventToCallbackMap[evt] === undefined) { this.eventToCallbackMap[evt] = []; } this.eventToCallbackMap[evt].push(callback); }, _unbindNonQueryEventHandler: function(evt, callback) { var callbacks = this.eventToCallbackMap[evt]; if(callbacks !== undefined) { for (var i = 0; i < callbacks.length; i++) { if (callbacks[i] === callback) { callbacks.splice(i, 1); break; } } } }, _cleanUpEventCallbacksMap: function() { var eventNames = Object.keys(this.eventToCallbackMap); for(var i = 0; i < eventNames.length; i++) { var eventName = eventNames[i]; this.eventToCallbackMap[eventName] = null; } }, _showTooltip: function() { if (this.options.tooltip_split === false ){ this._addClass(this.tooltip, 'in'); this.tooltip_min.style.display = 'none'; this.tooltip_max.style.display = 'none'; } else { this._addClass(this.tooltip_min, 'in'); this._addClass(this.tooltip_max, 'in'); this.tooltip.style.display = 'none'; } this._state.over = true; }, _hideTooltip: function() { if (this._state.inDrag === false && this.alwaysShowTooltip !== true) { this._removeClass(this.tooltip, 'in'); this._removeClass(this.tooltip_min, 'in'); this._removeClass(this.tooltip_max, 'in'); } this._state.over = false; }, _layout: function() { var positionPercentages; if(this.options.reversed) { positionPercentages = [ 100 - this._state.percentage[0], this.options.range ? 100 - this._state.percentage[1] : this._state.percentage[1]]; } else { positionPercentages = [ this._state.percentage[0], this._state.percentage[1] ]; } this.handle1.style[this.stylePos] = positionPercentages[0]+'%'; this.handle2.style[this.stylePos] = positionPercentages[1]+'%'; /* Position ticks and labels */ if (Array.isArray(this.options.ticks) && this.options.ticks.length > 0) { var styleSize = this.options.orientation === 'vertical' ? 'height' : 'width'; var styleMargin = this.options.orientation === 'vertical' ? 'marginTop' : 'marginLeft'; var labelSize = this._state.size / (this.options.ticks.length - 1); if (this.tickLabelContainer) { var extraMargin = 0; if (this.options.ticks_positions.length === 0) { if (this.options.orientation !== 'vertical') { this.tickLabelContainer.style[styleMargin] = -labelSize/2 + 'px'; } extraMargin = this.tickLabelContainer.offsetHeight; } else { /* Chidren are position absolute, calculate height by finding the max offsetHeight of a child */ for (i = 0 ; i < this.tickLabelContainer.childNodes.length; i++) { if (this.tickLabelContainer.childNodes[i].offsetHeight > extraMargin) { extraMargin = this.tickLabelContainer.childNodes[i].offsetHeight; } } } if (this.options.orientation === 'horizontal') { this.sliderElem.style.marginBottom = extraMargin + 'px'; } } for (var i = 0; i < this.options.ticks.length; i++) { var percentage = this.options.ticks_positions[i] || this._toPercentage(this.options.ticks[i]); if (this.options.reversed) { percentage = 100 - percentage; } this.ticks[i].style[this.stylePos] = percentage + '%'; /* Set class labels to denote whether ticks are in the selection */ this._removeClass(this.ticks[i], 'in-selection'); if (!this.options.range) { if (this.options.selection === 'after' && percentage >= positionPercentages[0]){ this._addClass(this.ticks[i], 'in-selection'); } else if (this.options.selection === 'before' && percentage <= positionPercentages[0]) { this._addClass(this.ticks[i], 'in-selection'); } } else if (percentage >= positionPercentages[0] && percentage <= positionPercentages[1]) { this._addClass(this.ticks[i], 'in-selection'); } if (this.tickLabels[i]) { this.tickLabels[i].style[styleSize] = labelSize + 'px'; if (this.options.orientation !== 'vertical' && this.options.ticks_positions[i] !== undefined) { this.tickLabels[i].style.position = 'absolute'; this.tickLabels[i].style[this.stylePos] = percentage + '%'; this.tickLabels[i].style[styleMargin] = -labelSize/2 + 'px'; } else if (this.options.orientation === 'vertical') { this.tickLabels[i].style['marginLeft'] = this.sliderElem.offsetWidth + 'px'; this.tickLabelContainer.style['marginTop'] = this.sliderElem.offsetWidth / 2 * -1 + 'px'; } } } } var formattedTooltipVal; if (this.options.range) { formattedTooltipVal = this.options.formatter(this._state.value); this._setText(this.tooltipInner, formattedTooltipVal); this.tooltip.style[this.stylePos] = (positionPercentages[1] + positionPercentages[0])/2 + '%'; if (this.options.orientation === 'vertical') { this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px'); } else { this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px'); } if (this.options.orientation === 'vertical') { this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px'); } else { this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px'); } var innerTooltipMinText = this.options.formatter(this._state.value[0]); this._setText(this.tooltipInner_min, innerTooltipMinText); var innerTooltipMaxText = this.options.formatter(this._state.value[1]); this._setText(this.tooltipInner_max, innerTooltipMaxText); this.tooltip_min.style[this.stylePos] = positionPercentages[0] + '%'; if (this.options.orientation === 'vertical') { this._css(this.tooltip_min, 'margin-top', -this.tooltip_min.offsetHeight / 2 + 'px'); } else { this._css(this.tooltip_min, 'margin-left', -this.tooltip_min.offsetWidth / 2 + 'px'); } this.tooltip_max.style[this.stylePos] = positionPercentages[1] + '%'; if (this.options.orientation === 'vertical') { this._css(this.tooltip_max, 'margin-top', -this.tooltip_max.offsetHeight / 2 + 'px'); } else { this._css(this.tooltip_max, 'margin-left', -this.tooltip_max.offsetWidth / 2 + 'px'); } } else { formattedTooltipVal = this.options.formatter(this._state.value[0]); this._setText(this.tooltipInner, formattedTooltipVal); this.tooltip.style[this.stylePos] = positionPercentages[0] + '%'; if (this.options.orientation === 'vertical') { this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px'); } else { this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px'); } } if (this.options.orientation === 'vertical') { this.trackLow.style.top = '0'; this.trackLow.style.height = Math.min(positionPercentages[0], positionPercentages[1]) +'%'; this.trackSelection.style.top = Math.min(positionPercentages[0], positionPercentages[1]) +'%'; this.trackSelection.style.height = Math.abs(positionPercentages[0] - positionPercentages[1]) +'%'; this.trackHigh.style.bottom = '0'; this.trackHigh.style.height = (100 - Math.min(positionPercentages[0], positionPercentages[1]) - Math.abs(positionPercentages[0] - positionPercentages[1])) +'%'; } else { this.trackLow.style.left = '0'; this.trackLow.style.width = Math.min(positionPercentages[0], positionPercentages[1]) +'%'; this.trackSelection.style.left = Math.min(positionPercentages[0], positionPercentages[1]) +'%'; this.trackSelection.style.width = Math.abs(positionPercentages[0] - positionPercentages[1]) +'%'; this.trackHigh.style.right = '0'; this.trackHigh.style.width = (100 - Math.min(positionPercentages[0], positionPercentages[1]) - Math.abs(positionPercentages[0] - positionPercentages[1])) +'%'; var offset_min = this.tooltip_min.getBoundingClientRect(); var offset_max = this.tooltip_max.getBoundingClientRect(); if (offset_min.right > offset_max.left) { this._removeClass(this.tooltip_max, 'top'); this._addClass(this.tooltip_max, 'bottom'); this.tooltip_max.style.top = 18 + 'px'; } else { this._removeClass(this.tooltip_max, 'bottom'); this._addClass(this.tooltip_max, 'top'); this.tooltip_max.style.top = this.tooltip_min.style.top; } } }, _removeProperty: function(element, prop) { if (element.style.removeProperty) { element.style.removeProperty(prop); } else { element.style.removeAttribute(prop); } }, _mousedown: function(ev) { if(!this._state.enabled) { return false; } this._state.offset = this._offset(this.sliderElem); this._state.size = this.sliderElem[this.sizePos]; var percentage = this._getPercentage(ev); if (this.options.range) { var diff1 = Math.abs(this._state.percentage[0] - percentage); var diff2 = Math.abs(this._state.percentage[1] - percentage); this._state.dragged = (diff1 < diff2) ? 0 : 1; } else { this._state.dragged = 0; } this._state.percentage[this._state.dragged] = percentage; this._layout(); if (this.touchCapable) { document.removeEventListener("touchmove", this.mousemove, false); document.removeEventListener("touchend", this.mouseup, false); } if(this.mousemove){ document.removeEventListener("mousemove", this.mousemove, false); } if(this.mouseup){ document.removeEventListener("mouseup", this.mouseup, false); } this.mousemove = this._mousemove.bind(this); this.mouseup = this._mouseup.bind(this); if (this.touchCapable) { // Touch: Bind touch events: document.addEventListener("touchmove", this.mousemove, false); document.addEventListener("touchend", this.mouseup, false); } // Bind mouse events: document.addEventListener("mousemove", this.mousemove, false); document.addEventListener("mouseup", this.mouseup, false); this._state.inDrag = true; var newValue = this._calculateValue(); this._trigger('slideStart', newValue); this._setDataVal(newValue); this.setValue(newValue, false, true); this._pauseEvent(ev); if (this.options.focus) { this._triggerFocusOnHandle(this._state.dragged); } return true; }, _triggerFocusOnHandle: function(handleIdx) { if(handleIdx === 0) { this.handle1.focus(); } if(handleIdx === 1) { this.handle2.focus(); } }, _keydown: function(handleIdx, ev) { if(!this._state.enabled) { return false; } var dir; switch (ev.keyCode) { case 37: // left case 40: // down dir = -1; break; case 39: // right case 38: // up dir = 1; break; } if (!dir) { return; } // use natural arrow keys instead of from min to max if (this.options.natural_arrow_keys) { var ifVerticalAndNotReversed = (this.options.orientation === 'vertical' && !this.options.reversed); var ifHorizontalAndReversed = (this.options.orientation === 'horizontal' && this.options.reversed); if (ifVerticalAndNotReversed || ifHorizontalAndReversed) { dir = -dir; } } var val = this._state.value[handleIdx] + dir * this.options.step; if (this.options.range) { val = [ (!handleIdx) ? val : this._state.value[0], ( handleIdx) ? val : this._state.value[1]]; if (val[0] > val[1]) { var temp = val[0]; val[0] = val[1] val[1] = temp if (this.options.focus) { this._triggerFocusOnHandle(handleIdx ? 0 : 1); } } } this._trigger('slideStart', val); this._setDataVal(val); this.setValue(val, true, true); this._setDataVal(val); this._trigger('slideStop', val); this._layout(); this._pauseEvent(ev); return false; }, _pauseEvent: function(ev) { if(ev.stopPropagation) { ev.stopPropagation(); } if(ev.preventDefault) { ev.preventDefault(); } ev.cancelBubble=true; ev.returnValue=false; }, _mousemove: function(ev) { if(!this._state.enabled) { return false; } var percentage = this._getPercentage(ev); this._adjustPercentageForRangeSliders(percentage); this._state.percentage[this._state.dragged] = percentage; this._layout(); var val = this._calculateValue(true); this.setValue(val, true, true); return false; }, _adjustPercentageForRangeSliders: function(percentage) { if (this.options.range) { var precision = this._getNumDigitsAfterDecimalPlace(percentage); precision = precision ? precision - 1 : 0; var percentageWithAdjustedPrecision = this._applyToFixedAndParseFloat(percentage, precision); if (this._state.dragged === 0 && this._applyToFixedAndParseFloat(this._state.percentage[1], precision) < percentageWithAdjustedPrecision) { this._state.percentage[0] = this._state.percentage[1]; this._state.dragged = 1; if (this.options.focus) { this._triggerFocusOnHandle(1); } } else if (this._state.dragged === 1 && this._applyToFixedAndParseFloat(this._state.percentage[0], precision) > percentageWithAdjustedPrecision) { this._state.percentage[1] = this._state.percentage[0]; this._state.dragged = 0; if (this.options.focus) { this._triggerFocusOnHandle(0); } } } }, _mouseup: function() { if(!this._state.enabled) { return false; } if (this.touchCapable) { // Touch: Unbind touch event handlers: document.removeEventListener("touchmove", this.mousemove, false); document.removeEventListener("touchend", this.mouseup, false); } // Unbind mouse event handlers: document.removeEventListener("mousemove", this.mousemove, false); document.removeEventListener("mouseup", this.mouseup, false); this._state.inDrag = false; if (this._state.over === false) { this._hideTooltip(); } var val = this._calculateValue(true); this._layout(); this._setDataVal(val); this._trigger('slideStop', val); return false; }, _calculateValue: function(snapToClosestTick) { var val; if (this.options.range) { val = [this.options.min,this.options.max]; if (this._state.percentage[0] !== 0){ val[0] = this._toValue(this._state.percentage[0]); val[0] = this._applyPrecision(val[0]); } if (this._state.percentage[1] !== 100){ val[1] = this._toValue(this._state.percentage[1]); val[1] = this._applyPrecision(val[1]); } } else { val = this._toValue(this._state.percentage[0]); val = parseFloat(val); val = this._applyPrecision(val); } if (snapToClosestTick) { var min = [val, Infinity]; for (var i = 0; i < this.options.ticks.length; i++) { var diff = Math.abs(this.options.ticks[i] - val); if (diff <= min[1]) { min = [this.options.ticks[i], diff]; } } if (min[1] <= this.options.ticks_snap_bounds) { return min[0]; } } return val; }, _applyPrecision: function(val) { var precision = this.options.precision || this._getNumDigitsAfterDecimalPlace(this.options.step); return this._applyToFixedAndParseFloat(val, precision); }, _getNumDigitsAfterDecimalPlace: function(num) { var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/); if (!match) { return 0; } return Math.max(0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0)); }, _applyToFixedAndParseFloat: function(num, toFixedInput) { var truncatedNum = num.toFixed(toFixedInput); return parseFloat(truncatedNum); }, /* Credits to Mike Samuel for the following method! Source: http://stackoverflow.com/questions/10454518/javascript-how-to-retrieve-the-number-of-decimals-of-a-string-number */ _getPercentage: function(ev) { if (this.touchCapable && (ev.type === 'touchstart' || ev.type === 'touchmove')) { ev = ev.touches[0]; } var eventPosition = ev[this.mousePos]; var sliderOffset = this._state.offset[this.stylePos]; var distanceToSlide = eventPosition - sliderOffset; // Calculate what percent of the length the slider handle has slid var percentage = (distanceToSlide / this._state.size) * 100; percentage = Math.round(percentage / this._state.percentage[2]) * this._state.percentage[2]; if (this.options.reversed) { percentage = 100 - percentage; } // Make sure the percent is within the bounds of the slider. // 0% corresponds to the 'min' value of the slide // 100% corresponds to the 'max' value of the slide return Math.max(0, Math.min(100, percentage)); }, _validateInputValue: function(val) { if (typeof val === 'number') { return val; } else if (Array.isArray(val)) { this._validateArray(val); return val; } else { throw new Error( ErrorMsgs.formatInvalidInputErrorMsg(val) ); } }, _validateArray: function(val) { for(var i = 0; i < val.length; i++) { var input = val[i]; if (typeof input !== 'number') { throw new Error( ErrorMsgs.formatInvalidInputErrorMsg(input) ); } } }, _setDataVal: function(val) { this.element.setAttribute('data-value', val); this.element.setAttribute('value', val); this.element.value = val; }, _trigger: function(evt, val) { val = (val || val === 0) ? val : undefined; var callbackFnArray = this.eventToCallbackMap[evt]; if(callbackFnArray && callbackFnArray.length) { for(var i = 0; i < callbackFnArray.length; i++) { var callbackFn = callbackFnArray[i]; callbackFn(val); } } /* If JQuery exists, trigger JQuery events */ if($) { this._triggerJQueryEvent(evt, val); } }, _triggerJQueryEvent: function(evt, val) { var eventData = { type: evt, value: val }; this.$element.trigger(eventData); this.$sliderElem.trigger(eventData); }, _unbindJQueryEventHandlers: function() { this.$element.off(); this.$sliderElem.off(); }, _setText: function(element, text) { if(typeof element.innerText !== "undefined") { element.innerText = text; } else if(typeof element.textContent !== "undefined") { element.textContent = text; } }, _removeClass: function(element, classString) { var classes = classString.split(" "); var newClasses = element.className; for(var i = 0; i < classes.length; i++) { var classTag = classes[i]; var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)"); newClasses = newClasses.replace(regex, " "); } element.className = newClasses.trim(); }, _addClass: function(element, classString) { var classes = classString.split(" "); var newClasses = element.className; for(var i = 0; i < classes.length; i++) { var classTag = classes[i]; var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)"); var ifClassExists = regex.test(newClasses); if(!ifClassExists) { newClasses += " " + classTag; } } element.className = newClasses.trim(); }, _offsetLeft: function(obj){ return obj.getBoundingClientRect().left; }, _offsetTop: function(obj){ var offsetTop = obj.offsetTop; while((obj = obj.offsetParent) && !isNaN(obj.offsetTop)){ offsetTop += obj.offsetTop; } return offsetTop; }, _offset: function (obj) { return { left: this._offsetLeft(obj), top: this._offsetTop(obj) }; }, _css: function(elementRef, styleName, value) { if ($) { $.style(elementRef, styleName, value); } else { var style = styleName.replace(/^-ms-/, "ms-").replace(/-([\da-z])/gi, function (all, letter) { return letter.toUpperCase(); }); elementRef.style[style] = value; } }, _toValue: function(percentage) { return this.options.scale.toValue.apply(this, [percentage]); }, _toPercentage: function(value) { return this.options.scale.toPercentage.apply(this, [value]); }, _setTooltipPosition: function(){ var tooltips = [this.tooltip, this.tooltip_min, this.tooltip_max]; if (this.options.orientation === 'vertical'){ var tooltipPos = this.options.tooltip_position || 'right'; var oppositeSide = (tooltipPos === 'left') ? 'right' : 'left'; tooltips.forEach(function(tooltip){ this._addClass(tooltip, tooltipPos); tooltip.style[oppositeSide] = '100%'; }.bind(this)); } else if(this.options.tooltip_position === 'bottom') { tooltips.forEach(function(tooltip){ this._addClass(tooltip, 'bottom'); tooltip.style.top = 22 + 'px'; }.bind(this)); } else { tooltips.forEach(function(tooltip){ this._addClass(tooltip, 'top'); tooltip.style.top = -this.tooltip.outerHeight - 14 + 'px'; }.bind(this)); } } }; /********************************* Attach to global namespace *********************************/ if($) { var namespace = $.fn.slider ? 'bootstrapSlider' : 'slider'; $.bridget(namespace, Slider); } })( $ ); return Slider; }));angular.module('ui.bootstrap-slider', []) .directive('slider', ['$parse', '$timeout', '$rootScope', function ($parse, $timeout, $rootScope) { return { restrict: 'AE', replace: true, template: '
', require: 'ngModel', scope: { max: "=", min: "=", step: "=", value: "=", ngModel: '=', ngDisabled: '=', range: '=', sliderid: '=', ticks: '=', ticksLabels: '=', ticksSnapBounds: '=', ticksPositions: '=', scale: '=', focus: '=', formatter: '&', onStartSlide: '&', onStopSlide: '&', onSlide: '&' }, link: function ($scope, element, attrs, ngModelCtrl, $compile) { var ngModelDeregisterFn, ngDisabledDeregisterFn; var slider = initSlider(); function initSlider() { var options = {}; function setOption(key, value, defaultValue) { options[key] = value || defaultValue; } function setFloatOption(key, value, defaultValue) { options[key] = value || value === 0 ? parseFloat(value) : defaultValue; } function setBooleanOption(key, value, defaultValue) { options[key] = value ? value + '' === 'true' : defaultValue; } function getArrayOrValue(value) { return (angular.isString(value) && value.indexOf("[") === 0) ? angular.fromJson(value) : value; } setOption('id', $scope.sliderid); setOption('orientation', attrs.orientation, 'horizontal'); setOption('selection', attrs.selection, 'before'); setOption('handle', attrs.handle, 'round'); setOption('tooltip', attrs.sliderTooltip || attrs.tooltip, 'show'); setOption('tooltip_position', attrs.sliderTooltipPosition, 'top'); setOption('tooltipseparator', attrs.tooltipseparator, ':'); setOption('ticks', $scope.ticks); setOption('ticks_labels', $scope.ticksLabels); setOption('ticks_snap_bounds', $scope.ticksSnapBounds); setOption('ticks_positions', $scope.ticksPositions); setOption('scale', $scope.scale, 'linear'); setOption('focus', $scope.focus); setFloatOption('min', $scope.min, 0); setFloatOption('max', $scope.max, 10); setFloatOption('step', $scope.step, 1); var strNbr = options.step + ''; var dotPos = strNbr.search(/[^.,]*$/); var decimals = strNbr.substring(dotPos); setFloatOption('precision', attrs.precision, decimals.length); setBooleanOption('tooltip_split', attrs.tooltipsplit, false); setBooleanOption('enabled', attrs.enabled, true); setBooleanOption('naturalarrowkeys', attrs.naturalarrowkeys, false); setBooleanOption('reversed', attrs.reversed, false); setBooleanOption('range', $scope.range, false); if (options.range) { if (angular.isArray($scope.value)) { options.value = $scope.value; } else if (angular.isString($scope.value)) { options.value = getArrayOrValue($scope.value); if (!angular.isArray(options.value)) { var value = parseFloat($scope.value); if (isNaN(value)) value = 5; if (value < $scope.min) { value = $scope.min; options.value = [value, options.max]; } else if (value > $scope.max) { value = $scope.max; options.value = [options.min, value]; } else { options.value = [options.min, options.max]; } } } else { options.value = [options.min, options.max]; // This is needed, because of value defined at $.fn.slider.defaults - default value 5 prevents creating range slider } $scope.ngModel = options.value; // needed, otherwise turns value into [null, ##] } else { setFloatOption('value', $scope.value, 5); } if (attrs.formatter) { options.formatter = $scope.$eval($scope.formatter); } // check if slider jQuery plugin exists if ('$' in window && $.fn.slider) { // adding methods to jQuery slider plugin prototype $.fn.slider.constructor.prototype.disable = function () { this.picker.off(); }; $.fn.slider.constructor.prototype.enable = function () { this.picker.on(); }; } // destroy previous slider to reset all options if (element[0].__slider) element[0].__slider.destroy(); var slider = new Slider(element[0].getElementsByClassName('slider-input')[0], options); element[0].__slider = slider; // everything that needs slider element var updateEvent = getArrayOrValue(attrs.updateevent); if (angular.isString(updateEvent)) { // if only single event name in string updateEvent = [updateEvent]; } else { // default to slide event updateEvent = ['slide']; } angular.forEach(updateEvent, function (sliderEvent) { slider.on(sliderEvent, function (ev) { ngModelCtrl.$setViewValue(ev); }); }); slider.on('change', function (ev) { ngModelCtrl.$setViewValue(ev.newValue); }); // Event listeners var sliderEvents = { slideStart: 'onStartSlide', slide: 'onSlide', slideStop: 'onStopSlide' }; angular.forEach(sliderEvents, function (sliderEventAttr, sliderEvent) { var fn = $parse(attrs[sliderEventAttr]); slider.on(sliderEvent, function (ev) { if ($scope[sliderEventAttr]) { fn($scope.$parent, { $event: ev, value: ev }); } }); }); // deregister ngDisabled watcher to prevent memory leaks if (angular.isFunction(ngDisabledDeregisterFn)) { ngDisabledDeregisterFn(); ngDisabledDeregisterFn = null; } ngDisabledDeregisterFn = $scope.$watch('ngDisabled', function (value) { if (value) { slider.disable(); } else { slider.enable(); } }); // deregister ngModel watcher to prevent memory leaks if (angular.isFunction(ngModelDeregisterFn)) ngModelDeregisterFn(); ngModelDeregisterFn = $scope.$watch('ngModel', function (value) { if($scope.range){ slider.setValue(value); }else{ slider.setValue(parseFloat(value)); } slider.relayout(); }, true); return slider; } var watchers = ['min', 'max', 'step', 'range', 'scale']; angular.forEach(watchers, function (prop) { $scope.$watch(prop, function () { slider = initSlider(); }); }); $scope.$on('slider:relayout', function() { slider.relayout(); }); } }; }]) ; /* * Utility functions */ var simple_clone = function( source ) { var clone = {}; for ( var key in source ) { if ( Array.isArray( source[ key ] ) ) { clone[ key ] = source[ key ].slice(); } else { clone[ key ] = source[ key ]; } } return clone; }; /* * Angular app */ var app = angular.module( 'latticeApp', [ 'ngRoute', 'ui.bootstrap-slider', ] ); app.config( [ '$compileProvider', '$interpolateProvider', '$routeProvider', function( $compileProvider, $interpolateProvider, $routeProvider ) { $compileProvider.debugInfoEnabled( false ); $interpolateProvider.startSymbol( '{[' ); $interpolateProvider.endSymbol( ']}' ); $routeProvider. when( '/', { redirectTo: 'control', } ). when( '/flash', { templateUrl: 'flash', } ). when( '/control', { templateUrl: 'control', } ). when( '/settings', { templateUrl: 'settings', } ); } ] ); app.controller( 'latticeCtrl', [ '$filter', '$http', '$location', '$log', '$scope', '$timeout', function( $filter, $http, $location, $log, $scope, $timeout ) { var vm = this; /* * Exposed members */ vm.modals = [ 'modal_first_connecting', null, null, 'modal_disconnected_unable_to_connect', 'modal_disconnected_inactivity', 'modal_flashing', 'modal_flashing_successful', 'modal_flashing_failed', 'modal_error', ]; vm.firmware_list = ([{"description": "Use temperature to choose your color. The lights will approximate the color of a blackbody at that temperature.", "disable_lighting_control": false, "id": "kelvin", "keywords": ["science", "solid", "static"], "title": "Blackbody"}, {"description": "A simple blinking color.", "disable_lighting_control": false, "id": "blink", "keywords": ["dynamic", "hue", "solid"], "title": "Blink"}, {"description": "Turn on all the lights!", "disable_lighting_control": true, "id": "bright", "keywords": ["solid", "static", "white"], "title": "Bright"}, {"description": "Display the time using a colored light for each clock hand.", "disable_lighting_control": false, "id": "clock", "keywords": ["data", "dynamic", "time"], "title": "Clock"}, {"description": "Choose a sequence of colors to switch between.", "disable_lighting_control": false, "id": "simple_series", "keywords": ["dynamic", "hue", "series", "solid"], "title": "Color Sequence"}, {"description": "A scrolling wave of colored light.", "disable_lighting_control": false, "id": "hue_wave", "keywords": ["dynamic", "hue", "scrolling"], "title": "Color Wave"}, {"description": "By your command.", "disable_lighting_control": false, "id": "cylon", "keywords": ["dynamic", "hue", "rainbow", "sci fi"], "title": "Cylon Eye"}, {"description": "Select from eight colors, chosen to be the most distinct eight colors in the available range.", "disable_lighting_control": false, "id": "eight_colors", "keywords": ["color picker", "solid", "static"], "title": "Eight Colors"}, {"description": "Where no one has gone before.", "disable_lighting_control": false, "id": "startrek", "keywords": ["collection", "dynamic", "sci fi"], "title": "Enterprise"}, {"description": "Fill the room with explosions.", "disable_lighting_control": false, "id": "impacts", "keywords": ["dynamic", "hue"], "title": "Explosions"}, {"description": "Fade between the colors of the rainbow.", "disable_lighting_control": false, "id": "fade_rainbow", "keywords": ["dynamic", "rainbow", "solid"], "title": "Fade Through The Rainbow"}, {"description": "All the hastle of maintaining a fireplace fire. None of the warmth. Add some wood. Add some kindling. Then light a match and watch it burn. When it gets low, throw in a few more logs to keep it going.", "disable_lighting_control": false, "id": "fireplace", "keywords": ["dynamic", "fireplace", "interactive"], "title": "Fireplace Simulator"}, {"description": "Four mathematical models of a rainbow. The sawtooth model linearly interpolates between red, green, and blue. The modified sawtooth adjusts the interpolation to widen and brighten the yellow band, as well as increase the amount of green in the green-blue transition. The artisanal rainbow blends between eight colors, hand picked to please the eye. The sinusoidal model replaces linear blends with three offset sine waves.", "disable_lighting_control": false, "id": "three_rainbows", "keywords": ["dynamic", "math", "rainbow", "scrolling", "wave"], "title": "Four Rainbows"}, {"description": "A smooth gradient between two colors.", "disable_lighting_control": false, "id": "gradient", "keywords": ["dynamic", "hue", "scrolling"], "title": "Gradient"}, {"description": "A collection of spooky lighting configurations.", "disable_lighting_control": false, "id": "hallow", "keywords": ["collection", "dynamic", "halloween", "holiday", "seasonal"], "title": "Happy Halloween"}, {"description": "A soothing fireplace.", "disable_lighting_control": false, "id": "hearth", "keywords": ["dynamic", "fireplace"], "title": "Hearth"}, {"description": "Choose the color of the lights by hue.", "disable_lighting_control": false, "id": "hue", "keywords": ["hue", "solid", "static"], "title": "Hue"}, {"description": "Set the lights by choosing hue, saturation, and value.", "disable_lighting_control": false, "id": "hsv", "keywords": ["hue", "solid", "static"], "title": "Hue Saturation Value"}, {"description": "Count down to midnight with the lights! A minute before New Year\u0027s, the lights start flashing once per second. The flashes turn red ten seconds before midnight.", "disable_lighting_control": false, "id": "is_it_new_years", "keywords": ["dynamic", "holiday", "time"], "title": "Is It New Year\u0027s?"}, {"description": "Break the lights into sections of shifting color. Control the number of sections, the speed of the color change, and the rate of scrolling.", "disable_lighting_control": false, "id": "kaleidoscope", "keywords": ["dynamic", "rainbow", "scrolling"], "title": "Kaleidoscope"}, {"description": "Slowly scrolling sources of white light.", "disable_lighting_control": true, "id": "white_wave", "keywords": ["dynamic", "scrolling", "white"], "title": "Marching Sconces"}, {"description": "The rarest of mythical beasts.", "disable_lighting_control": false, "id": "lava_lamp", "keywords": ["dynamic", "wave"], "title": "Mermaid Unicorn"}, {"description": "A collection of lighting configurations for the Christmas season.", "disable_lighting_control": false, "id": "xmas", "keywords": ["christmas", "collection", "dynamic", "holiday", "seasonal"], "title": "Merry Christmas"}, {"description": "Display the lunar phase.", "disable_lighting_control": true, "id": "moon_phase", "keywords": ["astronomy", "data", "dynamic", "moon", "science", "white"], "title": "Moon Phase"}, {"description": "Display the the planets based on their location in the sky.", "disable_lighting_control": false, "id": "planets", "keywords": ["astronomy", "data", "dynamic", "science"], "title": "Planets"}, {"description": "Select a color from among the primary and secondary colors.", "disable_lighting_control": false, "id": "basic_colors", "keywords": ["color picker", "solid", "static"], "title": "Primary Colors"}, {"description": "A scrolling rainbow.", "disable_lighting_control": false, "id": "rainbow", "keywords": ["dynamic", "rainbow", "scrolling"], "title": "Rainbow"}, {"description": "Set the lights to a random color.", "disable_lighting_control": false, "id": "random_single_color", "keywords": ["random", "solid", "static"], "title": "Random Color"}, {"description": "Choose your color by setting the intensity of red, green, and blue.", "disable_lighting_control": false, "id": "rgb", "keywords": ["rgb", "solid", "static"], "title": "Red Green Blue"}, {"description": "Choose your light by setting the intensity of red, green, blue, and white.", "disable_lighting_control": true, "id": "rgbw", "keywords": ["rgb", "solid", "static"], "title": "Red Green Blue White"}, {"description": "Transition between random colors using any number of transition.", "disable_lighting_control": false, "id": "random_color", "keywords": ["dynamic", "random", "series", "solid"], "title": "Sequence of Random Colors"}, {"description": "Room-filling white light with a warm hue hand-picked by Angie. Deprecated by True White.", "disable_lighting_control": false, "id": "simple_white", "keywords": ["solid", "static", "white"], "title": "Simply White"}, {"description": "Display a section of the color spectrum.", "disable_lighting_control": false, "id": "hue_arc", "keywords": ["dynamic", "rainbow", "scrolling"], "title": "Slice of Spectrum"}, {"description": "Sing along to this classic Spruceway Christmas color pattern.", "disable_lighting_control": false, "id": "spruceway", "keywords": ["christmas", "dynamic", "holiday", "seasonal", "series", "solid"], "title": "A Spruceway Christmas"}, {"description": "Display the west-east position of the sun and moon in the sky of Woodland Hills. When below the horizon, their position in the sky on the opposite side of the earth is used.", "disable_lighting_control": true, "id": "sun_moon", "keywords": ["astronomy", "data", "dynamic", "moon", "science"], "title": "Sun and Moon"}, {"description": "Display the temperature in key cities.", "disable_lighting_control": false, "id": "web_data", "keywords": ["data", "dynamic", "science", "weather"], "title": "Temperature"}, {"description": "White with a hint of color. Deprecated because white light can be added to any color firmware in Settings.", "disable_lighting_control": true, "id": "tinted_white", "keywords": ["dynamic", "hue", "rainbow", "scrolling", "solid", "white"], "title": "Tinted White"}, {"description": "Room-filling light with the warm hue of natively white LEDs.", "disable_lighting_control": true, "id": "true_white", "keywords": ["solid", "static", "white"], "title": "True White"}, {"description": "Choose your color from the warm range of a tungsten filament.", "disable_lighting_control": false, "id": "filament", "keywords": ["science", "solid", "static"], "title": "Tungsten Filament"}, {"description": "Create your own wave patterns from scratch.", "disable_lighting_control": false, "id": "interference", "keywords": ["dynamic", "hue", "math", "scrolling", "wave"], "title": "Wave Crafting"}, {"description": "Select a color from a set of whites.", "disable_lighting_control": false, "id": "whites", "keywords": ["color picker", "solid", "static", "white"], "title": "Whites"}]); vm.firmware_mapping = ({"basic_colors": {"description": "Select a color from among the primary and secondary colors.", "disable_lighting_control": false, "id": "basic_colors", "keywords": ["color picker", "solid", "static"], "title": "Primary Colors"}, "blink": {"description": "A simple blinking color.", "disable_lighting_control": false, "id": "blink", "keywords": ["dynamic", "hue", "solid"], "title": "Blink"}, "bright": {"description": "Turn on all the lights!", "disable_lighting_control": true, "id": "bright", "keywords": ["solid", "static", "white"], "title": "Bright"}, "clock": {"description": "Display the time using a colored light for each clock hand.", "disable_lighting_control": false, "id": "clock", "keywords": ["data", "dynamic", "time"], "title": "Clock"}, "cylon": {"description": "By your command.", "disable_lighting_control": false, "id": "cylon", "keywords": ["dynamic", "hue", "rainbow", "sci fi"], "title": "Cylon Eye"}, "eight_colors": {"description": "Select from eight colors, chosen to be the most distinct eight colors in the available range.", "disable_lighting_control": false, "id": "eight_colors", "keywords": ["color picker", "solid", "static"], "title": "Eight Colors"}, "fade_rainbow": {"description": "Fade between the colors of the rainbow.", "disable_lighting_control": false, "id": "fade_rainbow", "keywords": ["dynamic", "rainbow", "solid"], "title": "Fade Through The Rainbow"}, "filament": {"description": "Choose your color from the warm range of a tungsten filament.", "disable_lighting_control": false, "id": "filament", "keywords": ["science", "solid", "static"], "title": "Tungsten Filament"}, "fireplace": {"description": "All the hastle of maintaining a fireplace fire. None of the warmth. Add some wood. Add some kindling. Then light a match and watch it burn. When it gets low, throw in a few more logs to keep it going.", "disable_lighting_control": false, "id": "fireplace", "keywords": ["dynamic", "fireplace", "interactive"], "title": "Fireplace Simulator"}, "gradient": {"description": "A smooth gradient between two colors.", "disable_lighting_control": false, "id": "gradient", "keywords": ["dynamic", "hue", "scrolling"], "title": "Gradient"}, "hallow": {"description": "A collection of spooky lighting configurations.", "disable_lighting_control": false, "id": "hallow", "keywords": ["collection", "dynamic", "halloween", "holiday", "seasonal"], "title": "Happy Halloween"}, "hearth": {"description": "A soothing fireplace.", "disable_lighting_control": false, "id": "hearth", "keywords": ["dynamic", "fireplace"], "title": "Hearth"}, "hsv": {"description": "Set the lights by choosing hue, saturation, and value.", "disable_lighting_control": false, "id": "hsv", "keywords": ["hue", "solid", "static"], "title": "Hue Saturation Value"}, "hue": {"description": "Choose the color of the lights by hue.", "disable_lighting_control": false, "id": "hue", "keywords": ["hue", "solid", "static"], "title": "Hue"}, "hue_arc": {"description": "Display a section of the color spectrum.", "disable_lighting_control": false, "id": "hue_arc", "keywords": ["dynamic", "rainbow", "scrolling"], "title": "Slice of Spectrum"}, "hue_wave": {"description": "A scrolling wave of colored light.", "disable_lighting_control": false, "id": "hue_wave", "keywords": ["dynamic", "hue", "scrolling"], "title": "Color Wave"}, "impacts": {"description": "Fill the room with explosions.", "disable_lighting_control": false, "id": "impacts", "keywords": ["dynamic", "hue"], "title": "Explosions"}, "interference": {"description": "Create your own wave patterns from scratch.", "disable_lighting_control": false, "id": "interference", "keywords": ["dynamic", "hue", "math", "scrolling", "wave"], "title": "Wave Crafting"}, "is_it_new_years": {"description": "Count down to midnight with the lights! A minute before New Year\u0027s, the lights start flashing once per second. The flashes turn red ten seconds before midnight.", "disable_lighting_control": false, "id": "is_it_new_years", "keywords": ["dynamic", "holiday", "time"], "title": "Is It New Year\u0027s?"}, "kaleidoscope": {"description": "Break the lights into sections of shifting color. Control the number of sections, the speed of the color change, and the rate of scrolling.", "disable_lighting_control": false, "id": "kaleidoscope", "keywords": ["dynamic", "rainbow", "scrolling"], "title": "Kaleidoscope"}, "kelvin": {"description": "Use temperature to choose your color. The lights will approximate the color of a blackbody at that temperature.", "disable_lighting_control": false, "id": "kelvin", "keywords": ["science", "solid", "static"], "title": "Blackbody"}, "lava_lamp": {"description": "The rarest of mythical beasts.", "disable_lighting_control": false, "id": "lava_lamp", "keywords": ["dynamic", "wave"], "title": "Mermaid Unicorn"}, "moon_phase": {"description": "Display the lunar phase.", "disable_lighting_control": true, "id": "moon_phase", "keywords": ["astronomy", "data", "dynamic", "moon", "science", "white"], "title": "Moon Phase"}, "planets": {"description": "Display the the planets based on their location in the sky.", "disable_lighting_control": false, "id": "planets", "keywords": ["astronomy", "data", "dynamic", "science"], "title": "Planets"}, "rainbow": {"description": "A scrolling rainbow.", "disable_lighting_control": false, "id": "rainbow", "keywords": ["dynamic", "rainbow", "scrolling"], "title": "Rainbow"}, "random_color": {"description": "Transition between random colors using any number of transition.", "disable_lighting_control": false, "id": "random_color", "keywords": ["dynamic", "random", "series", "solid"], "title": "Sequence of Random Colors"}, "random_single_color": {"description": "Set the lights to a random color.", "disable_lighting_control": false, "id": "random_single_color", "keywords": ["random", "solid", "static"], "title": "Random Color"}, "rgb": {"description": "Choose your color by setting the intensity of red, green, and blue.", "disable_lighting_control": false, "id": "rgb", "keywords": ["rgb", "solid", "static"], "title": "Red Green Blue"}, "rgbw": {"description": "Choose your light by setting the intensity of red, green, blue, and white.", "disable_lighting_control": true, "id": "rgbw", "keywords": ["rgb", "solid", "static"], "title": "Red Green Blue White"}, "simple_series": {"description": "Choose a sequence of colors to switch between.", "disable_lighting_control": false, "id": "simple_series", "keywords": ["dynamic", "hue", "series", "solid"], "title": "Color Sequence"}, "simple_white": {"description": "Room-filling white light with a warm hue hand-picked by Angie. Deprecated by True White.", "disable_lighting_control": false, "id": "simple_white", "keywords": ["solid", "static", "white"], "title": "Simply White"}, "spruceway": {"description": "Sing along to this classic Spruceway Christmas color pattern.", "disable_lighting_control": false, "id": "spruceway", "keywords": ["christmas", "dynamic", "holiday", "seasonal", "series", "solid"], "title": "A Spruceway Christmas"}, "startrek": {"description": "Where no one has gone before.", "disable_lighting_control": false, "id": "startrek", "keywords": ["collection", "dynamic", "sci fi"], "title": "Enterprise"}, "sun_moon": {"description": "Display the west-east position of the sun and moon in the sky of Woodland Hills. When below the horizon, their position in the sky on the opposite side of the earth is used.", "disable_lighting_control": true, "id": "sun_moon", "keywords": ["astronomy", "data", "dynamic", "moon", "science"], "title": "Sun and Moon"}, "three_rainbows": {"description": "Four mathematical models of a rainbow. The sawtooth model linearly interpolates between red, green, and blue. The modified sawtooth adjusts the interpolation to widen and brighten the yellow band, as well as increase the amount of green in the green-blue transition. The artisanal rainbow blends between eight colors, hand picked to please the eye. The sinusoidal model replaces linear blends with three offset sine waves.", "disable_lighting_control": false, "id": "three_rainbows", "keywords": ["dynamic", "math", "rainbow", "scrolling", "wave"], "title": "Four Rainbows"}, "tinted_white": {"description": "White with a hint of color. Deprecated because white light can be added to any color firmware in Settings.", "disable_lighting_control": true, "id": "tinted_white", "keywords": ["dynamic", "hue", "rainbow", "scrolling", "solid", "white"], "title": "Tinted White"}, "true_white": {"description": "Room-filling light with the warm hue of natively white LEDs.", "disable_lighting_control": true, "id": "true_white", "keywords": ["solid", "static", "white"], "title": "True White"}, "web_data": {"description": "Display the temperature in key cities.", "disable_lighting_control": false, "id": "web_data", "keywords": ["data", "dynamic", "science", "weather"], "title": "Temperature"}, "white_wave": {"description": "Slowly scrolling sources of white light.", "disable_lighting_control": true, "id": "white_wave", "keywords": ["dynamic", "scrolling", "white"], "title": "Marching Sconces"}, "whites": {"description": "Select a color from a set of whites.", "disable_lighting_control": false, "id": "whites", "keywords": ["color picker", "solid", "static", "white"], "title": "Whites"}, "xmas": {"description": "A collection of lighting configurations for the Christmas season.", "disable_lighting_control": false, "id": "xmas", "keywords": ["christmas", "collection", "dynamic", "holiday", "seasonal"], "title": "Merry Christmas"}}); vm.client = { fps: (false), device: (false), }; /* * Internal members */ var m_stop_watching_controls; var m_time_of_last_activity = Date.now(); /* * Accessors */ vm.navClass = function( route ) { return route === $location.path().substring( 1 ) ? 'active' : ''; }; /* * Formatters */ var determine_decimal_places_linear = function( value ) { }; var determine_decimal_places_log = function( value ) { if ( value >= 9.95 ) { return 0; } else if ( value >= 0.995 ) { return 1; } else if ( value >= 0.0995 ) { return 2; } else { return 3; } }; var format_frequency = function( value ) { var prefix; var suffix; if ( value > 60.0 ) { value /= 60.0; prefix = 'once every ' suffix = ' minutes'; } else if ( value > 0.5 ) { prefix = 'once every ' suffix = ' seconds'; } else { prefix = '' value = 1.0 / value; suffix = ' times a second'; } var decimal_places = determine_decimal_places_log( value ); return prefix + value.toFixed( decimal_places ) + suffix; }; var format_period = function( value ) { var prefix; var suffix; if ( value > 60.0 ) { value /= 60.0; suffix = ' minutes'; } else { suffix = ' seconds'; } var decimal_places = determine_decimal_places_log( value ); return value.toFixed( decimal_places ) + suffix; }; vm.formatter_number = function( control ) { var decimal_places = control.decimal_places; var suffix = control.suffix || ''; return function( value ) { value = value || control.min; return value.toFixed( decimal_places ) + suffix; } }; vm.formatter_linear = function( control ) { var suffix = control.suffix || ''; var decimal_places; var step = ( control.display_max - control.display_min ) / ( control.max - control.min ); if ( step >= 1.0 ) { decimal_places = 0; } else { decimal_places = Math.ceil( -Math.log10( step ) ); } return function( value ) { value = value || control.min; value = ( value - control.min ) / ( control.max - control.min ); value = control.display_min + value * ( control.display_max - control.display_min ); return value.toFixed( decimal_places ) + suffix; } }; vm.formatter_log = function( control ) { var base = Math.exp( Math.log( ( control.display_max ) / ( control.display_min ) ) / ( ( control.max ) - 1 ) ); var display_min = control.display_min; return function( value ) { if ( !value ) { return '0'; } value = display_min * Math.pow( base, value - 1 ); var decimal_places = determine_decimal_places_log( value ); return value.toFixed( decimal_places ); } }; vm.formatter_log_duration = function( control ) { var base = Math.exp( Math.log( ( control.display_max ) / ( control.display_min ) ) / ( ( control.max ) - 1 ) ); var display_min = control.display_min; return function( value ) { if ( !value ) { return 'stopped'; } value = display_min * Math.pow( base, value - 1 ); return format_frequency( value ); } }; vm.formatter_log_rate = function( control ) { var base = Math.exp( Math.log( ( control.display_max ) / ( control.display_min ) ) / ( ( control.max ) - 1 ) ); var display_min = control.display_min; return function( value ) { if ( !value ) { return 'stopped'; } value = display_min * Math.pow( base, value - 1 ); value = 1.0 / value; return format_frequency( value ); } }; vm.formatter_log_period = function( control ) { var base = Math.exp( Math.log( ( control.display_max ) / ( control.display_min ) ) / ( ( control.max ) - 1 ) ); var display_min = control.display_min; return function( value ) { if ( !value ) { return 'immediate'; } value = display_min * Math.pow( base, value - 1 ); return format_period( value ); } }; vm.formatter_log_inv_period = function( control ) { var base = Math.exp( Math.log( ( control.display_max ) / ( control.display_min ) ) / ( ( control.max ) - 1 ) ); var display_min = control.display_min; return function( value ) { if ( !value ) { return 'immediate'; } value = display_min * Math.pow( base, value - 1 ); value = 1.0 / value; return format_period( value ); } }; vm.formatter_bounds = function( decimal_places, suffix ) { return function( value ) { var value_0 = value[ 0 ] || 0; var value_1 = value[ 1 ] || 0; return value_0.toFixed( decimal_places ) + suffix + ' to ' + value_1.toFixed( decimal_places ) + suffix; } }; vm.format_integer = function( value, map ) { if ( map && value in map ) { return map[value]; } return value; } vm.format_time = function( seconds ) { var hours = Math.floor( seconds / 60 / 60 ); seconds -= hours * 60 * 60; var minutes = Math.floor( seconds / 60 ); seconds -= minutes * 60; return $filter( 'date' )( new Date( 0, 0, 0, hours, minutes, seconds, 0 ), 'mediumTime' ); }; vm.format_date = function( days ) { var years = Math.floor( days / 12 / 31 ); days -= years * 12 * 31; var months = Math.floor( days / 31 ); days -= months * 31; return $filter( 'date' )( new Date( years, months, days + 1, 0, 0, 0, 0 ), 'longDate' ); }; vm.format_status = function( status, data ) { if ( status === 0 ) { return data; } else if ( status === 1 || status === 2 ) { return 'pending'; } else if ( status === 3 ) { return 'no data'; } else { return 'error'; } }; vm.format_location = function( altitude, azimuth ) { var altitude_text; var azimuth_test; if ( altitude < 0 ) { altitude_text = '\u00B0 below the horizon'; altitude *= -1; } else { altitude_text = '\u00B0 above the horizon'; } if ( azimuth < 180 ) { azimuth_test = '\u00B0 around the horizon clockwise from north, '; } else { azimuth_test = '\u00B0 around the horizon counterclockwise from north, '; azimuth = 360 - azimuth; } return azimuth + azimuth_test + altitude + altitude_text; }; vm.format_fireplace = function( l, n, w ) { var strings = []; if ( l > 0 ) { strings.push( ( l / 100 ).toFixed( 2 ) + ' logs' ); } if ( n > 0 ) { strings.push( ( n / 100 ).toFixed( 2 ) + ' balls of newspaper' ); } if ( w > 0 ) { strings.push( ( w / 100 ).toFixed( 2 ) + ' oz of water' ); } if ( strings.length === 0 ) { return 'empty'; } else if ( strings.length === 1 ) { return strings[ 0 ]; } else if ( strings.length === 2 ) { return strings[ 0 ] + ' and ' + strings[ 1 ]; } else { return strings[ 0 ] + ', ' + strings[ 1 ] + ', and ' + strings[ 2 ]; } } vm.rgbw_color = function( r, g, b, w ) { var adjust = function( c, w ) { var white_factor = w / ( 255 + 32 ); return c + Math.floor( ( 1 - c / 255 ) * white_factor * 255 ); }; return adjust( r, w ) + ',' + adjust( g, w ) + ',' + adjust( b, w ); } /* * OnClicks */ vm.connect = function() { if ( vm.status.state === (3) || vm.status.state === (4) ) { mark_activity(); change_to_state( (0) ); } }; vm.incrementControl = function( control, max ) { var previous_value = vm.controls_ui[ control ]; if ( previous_value < max ) { vm.controls_ui[ control ] = previous_value + 1; } }; vm.decrementControl = function( control, min ) { var previous_value = vm.controls_ui[ control ]; if ( previous_value > min ) { vm.controls_ui[ control ] = previous_value - 1; } }; /* * Status State Machine */ vm.status = { state: (0), state_duration: 0, process_id: 0, firmware_id: '', client_id: Math.floor( Math.random() * 256 * 256 * 256 ) * 256, command_count: -1, timing: 1, controls: null, }; var poll_status = function() { var url = '/status/pion'; //$log.log( 'get - ' + url ); // random suffix to avoid cached results var random_suffix = '' + Math.floor( Math.random() * Math.floor( 10000000000000000 ) ); $http.get( url + '?' + random_suffix ).then( function( response ) { // $log.log( response ); var connected = response.data.status; var process_id = parseInt( response.data.process_id, 16 ); var firmware_id = response.data.firmware_name; var last_serviced_command_id = parseInt( response.data.last_serviced_command_id, 16 ); var timing = response.data.timing; var controls = response.data.controls; process_status_results( connected, process_id, firmware_id, last_serviced_command_id, timing, controls ); }, function( response ) { // $log.log( response ); var connected = 0; var process_id = 0; var firmware_id = ''; var last_serviced_command_id = 0; var timing = 0; var controls = null; process_status_results( connected, process_id, firmware_id, last_serviced_command_id, timing, controls ); } ); }; var process_status_results = function( connected, process_id, firmware_id, last_serviced_command_id, timing, controls ) { vm.status.state_duration++; var inactive = determine_inactivity(); var new_state = process_transitions( connected, inactive, process_id ) || (8); if ( process_id ) { if ( vm.controls_status.fetch_state !== (0) ) { var msec_since_last_control_send = Date.now() - vm.controls_status.time_of_last_control_send; if ( msec_since_last_control_send > (10) * 1000 ) { set_fetch_state( (0) ); } else if ( process_id !== vm.status.process_id ) { set_fetch_state( (0) ); } else if ( last_serviced_command_id === get_command_id() ) { set_fetch_state( (0) ); } } vm.status.process_id = process_id; vm.status.firmware_id = firmware_id; vm.status.timing = timing; vm.status.controls = controls; } if ( new_state !== (8) ) { change_to_state( new_state ); } switch ( vm.status.state ) { case (2): { if ( vm.controls_status.fetch_state === (0) ) { vm.controls_last_successfully_sent = simple_clone( vm.status.controls ); vm.controls_ui = simple_clone( vm.controls_last_successfully_sent ); } } break; } if ( vm.status.state !== (3) && vm.status.state !== (4) ) { $timeout( poll_status, (1000) ); } }; var process_transitions = function( connected, inactive, process_id ) { if ( inactive ) { return (4); } if ( connected ) { switch ( vm.status.state ) { case (0): case (1): case (3): case (4): { return (2); } case (2): { return; } case (5): case (6): case (7): { if ( process_id !== vm.status.process_id || vm.status.state_duration > (8) ) { return (2); } return; } } } else { switch ( vm.status.state ) { case (0): { if ( vm.status.state_duration >= (2) ) { return (3); } return; } case (1): { if ( vm.status.state_duration >= (8) ) { return (3); } return; } case (2): { return (1); } case (3): case (4): { return; } case (5): case (6): case (7): { if ( vm.status.state_duration > (8) ) { return (3); } return; } } } }; var change_to_state = function( new_state ) { exit_state( vm.status.state, new_state ); var old_state = vm.status.state; vm.status.state = new_state; vm.status.state_duration = 0; enter_state( vm.status.state, old_state ); }; var enter_state = function( state, old_state ) { if ( vm.modals[ old_state ] && !vm.modals[ state ] ) { vm.controls_last_successfully_sent = simple_clone( vm.status.controls ); vm.controls_ui = simple_clone( vm.controls_last_successfully_sent ); m_stop_watching_controls = $scope.$watchCollection( 'vm.controls_ui', function() { update_controls( true ); } ); } }; var exit_state = function( state, new_state ) { switch ( state ) { case (3): case (4): { $timeout( poll_status, 0 ); break; } case (6): { $location.path( '/control' ); break; } } if ( !vm.modals[ state ] && vm.modals[ new_state ] ) { m_stop_watching_controls(); } }; /* * Flash */ vm.flashing_firmware_title = ''; vm.flashFirmware = function( firmware ) { if ( vm.status.state !== (2) ) return; mark_activity(); change_to_state( (5) ); vm.flashing_firmware_title = firmware.title; var url = '/flash/pion/' + firmware.id; //$log.log( 'put - ' + url ); $http.put( url ).then( function( response ) { change_to_state( response.data.success ? (6) : (7) ); }, function( response ) { change_to_state( (7) ); } ); }; /* * Controls */ vm.controls_last_successfully_sent = null; vm.controls_ui = null; vm.controls_status = { dirty: false, put_active: false, fetch_state: (0), time_of_last_command_send: 0, }; var update_controls = function( set_dirty ) { mark_activity(); if ( set_dirty ) { vm.controls_status.dirty = true; vm.controls_status.time_of_last_control_send = Date.now(); set_fetch_state( (1) ); } if ( vm.controls_status.put_active ) { return; } if ( !vm.controls_status.dirty ) { set_fetch_state( (2) ); return; } vm.controls_status.put_active = true; vm.controls_status.dirty = false; if ( vm.status.state === (2) ) { if ( angular.equals( vm.controls_ui, vm.controls_last_successfully_sent ) ) { process_controls_response( true ); set_fetch_state( (0) ); } else { step_command_count(); var controls_being_sent = simple_clone( vm.controls_ui ); var data = { process_id: vm.status.process_id, firmware: vm.status.firmware_id, command_id: get_command_id(), controls: simple_clone( vm.controls_ui ), }; var url = '/set/pion' //$log.log( 'put - ' + url ); //$log.log( data ); $http.put( url, data ).then( function( response ) { if ( response.data.success ) { vm.controls_last_successfully_sent = controls_being_sent; } process_controls_response( response.data.success ); }, function( response ) { process_controls_response( false ); } ); } } else if ( vm.status.state === (1) ) { step_command_count(); $timeout( function() { process_controls_response( false ); }, (1000) ); } else { vm.controls_status.put_active = false; } }; var process_controls_response = function( success ) { vm.controls_status.put_active = false; update_controls( !success ); }; var set_fetch_state = function( state ) { vm.controls_status.fetch_state = state; } var get_command_id = function() { return vm.status.client_id + vm.status.command_count; } var step_command_count = function() { vm.status.command_count++; if ( vm.status.command_count >= 256 ) { vm.status.command_count = 0; } } /* * Inactivity */ var determine_inactivity = function() { var msec_since_last_activity = Date.now() - m_time_of_last_activity return msec_since_last_activity > (15) * 60 * 1000; } var mark_activity = function() { m_time_of_last_activity = Date.now(); } /* * Poll */ poll_status(); /* * Tooltip patch * * The slider tooltips render at the wrong location on first load. * https://github.com/seiyria/angular-bootstrap-slider/issues/123 * This papers over the problem for some cases. If this issue is ever * fixed, remove this patch. */ $scope.$on( '$includeContentLoaded', function() { $timeout( function() { $scope.$broadcast( 'slider:relayout' ); } ) } ); } ] );