<commit_before>
var request = require('request');
var rp = require('request-promise');
var server = 'http://127.0.0.1:8000';
var chai = require('chai');
var expect = chai.expect;

var examplePosting1 = {
  "date": "1000",
  "country": "A",
  "state": "Maryland",
  "hub": "la",
  "source": "career_builder",
  "url": "www.fff.com",
  "text": "some posting text"
  };

var examplePosting2 = {
  "date": "1000",
  "country": "B",
  "state": "Maryland",
  "hub": "la",
  "source": "career_builder",
  "url": "www.fff.com",
  "text": "some posting text"
  };

var examplePosting3 = {
  "date": "1000",
  "country": "C",
  "state": "Maryland",
  "hub": "la",
  "source": "career_builder",
  "url": "www.fff.com",
  "text": "some posting text"
  };

beforeEach(function(done){
  rp.delete(server+'/raw-postings/:0').then(res=>{
    done();
  });
})

describe ('service of static assets',function(){
  it('serves index',function(done){
    request(server+'/').on('response',function(res){
      expect(res.statusCode).to.equal(200);
      done();
   });
  });
});

describe ('raw-postings api',function(){
  it('shows nothing after deletion',function(done){
    //rp.post(server+'/raw-postings',{json: examplePosting1})
    Promise.all([ rp.delete(server+'/raw-postings/:0'),
                  rp.get(server+'/raw-postings'),
                  ])
      .then(responses=>{
        console.log('r1',responses);
        expect(JSON.parse(responses[1]).length).to.equal(0);
        done();
    });
  });

  it('posts',function(done){
    Promise.all([rp.post(server+'/raw-postings',{json: examplePosting1}),
                 rp.post(server+'/raw-postings',{json: examplePosting2}),
                 rp.post(server+'/raw-postings',{json: examplePosting3}),])
      .then(responses=>{
        expect(JSON.parse(responses[1]).country).to.equal('A');
        done();
      });
  });

  it('returns the posted object from a post request',function(done){
    rp.post(server+'/raw-postings',{json: examplePosting1})
      .then(response=>{
        console.log('post response',response);
        done();
      });
  });

  it('gets the results of posts',function(done){
    Promise.all([rp.post(server+'/raw-postings',{json: examplePosting1}),
                 rp.post(server+'/raw-postings',{json: examplePosting2}),
                 rp.post(server+'/raw-postings',{json: examplePosting3}),])
      .then(rp.get(server+'/raw-postings?date=0'))
      .then(res=>{
        console.log('results of get', res);
      });
  })

  it('shows nothing after deletion',function(done){
    //rp.post(server+'/raw-postings',{json: examplePosting1})
    Promise.all([ rp.delete(server+'/raw-postings/:0'),
                  rp.get(server+'/raw-postings'),
                  ])
      .then(responses=>{
        console.log('r1',responses);
        expect(JSON.parse(responses[1]).length).to.equal(0);
        done();
    });
  });
});

// describe ('App (using local db)', function() {

//   describe('Posting creation: ', function(done) {

    // it('deletes postings', function(done) {
    //   request(app)
    //     .delete('/raw-postings/:0')
    //     .then(function(response){
    //       //console.log(response.status);
    //       expect(response.status).to.equal(204);
    //       done();
    //     })
    // });

    // it('posts postings', function(done) {
    //   var posts = [request(app).post('/raw-postings').send(examplePosting1),
    //               request(app).post('/raw-postings').send(examplePosting2),
    //               request(app).post('/raw-postings').send(examplePosting3)];

    //   Promise.all(posts).then(function(...results){
    //     console.log(results);
    //     done();
    //   });
    // });

    //  it('gets postings', function(done) {
    //    request(app)
    //      .get('/raw-postings?date=0')
    //      .then(function(response){
    //      expect(response.status).to.equal(202);
    //       done();
    //      });
    //  });

    //  it('posts', function(done) {
    //   request(app)
    //     .post('/raw-postings')
    //     .send(examplePosting2)
    //     .then(function(response){
    //       expect(response.status).to.equal(202);
    //       expect(response.length).to.equal(1);
    //       done();
    //     });
    //  });

  //});

  // it('deletes postings', function(done) {
  //     request(app)
  //       .delete('/raw-postings/:0')
  //       .then(function(response){
  //         console.log(response.status);
  //         expect(response.status).to.equal(204);
  //         done();
  //       })
//    });

// });
<commit_msg>server tests for existing endpoints<commit_after>
var request = require('request');
var rp = require('request-promise');
var server = 'http://127.0.0.1:8000';
var chai = require('chai');
var expect = chai.expect;
var promise = require('bluebird');
var bodyparser = require('body-parser');

var examplePosting1 = {
  "date": "1000",
  "country": "A",
  "state": "Maryland",
  "hub": "la",
  "source": "career_builder",
  "url": "www.fff.com",
  "text": "some posting text"
  };

var examplePosting2 = {
  "date": "1000",
  "country": "B",
  "state": "Maryland",
  "hub": "la",
  "source": "career_builder",
  "url": "www.fff.com",
  "text": "some posting text"
  };

var examplePosting3 = {
  "date": "1000",
  "country": "C",
  "state": "Maryland",
  "hub": "la",
  "source": "career_builder",
  "url": "www.fff.com",
  "text": "some posting text"
  };

var examplePosting4 = {
  "date": "1001",
  "country": "D",
  "state": "Maryland",
  "hub": "la",
  "source": "career_builder",
  "url": "www.fff.com",
  "text": "some posting text"
  };

var postone = function(){
  return rp.post(server+'/raw-postings',{json: examplePosting1});
}

var posttwo= function(){
  return rp.post(server+'/raw-postings',{json: examplePosting2});
}

var postfour = function(){
  return rp.post(server+'/raw-postings',{json: examplePosting4});
}

var postthree =  function(){
    return promise.all([rp.post(server+'/raw-postings',{json: examplePosting1}),
                        rp.post(server+'/raw-postings',{json: examplePosting2}),
                        rp.post(server+'/raw-postings',{json: examplePosting3}),]);
  };

var deleteall = function(){return rp.delete(server+'/raw-postings/:0');};
var deleteone = function(){return rp.delete(server+'/raw-postings/:1001');};

var getall = function(){return rp.get(server+'/raw-postings?date=0');};
var getone = function(){return rp.get(server+'/raw-postings?date=1001');};

beforeEach(function(done){
  deleteall().then(res=>{
    done();
  });
})

describe ('service of static assets',function(){
  it('serves index',function(done){
    request(server+'/').on('response',function(res){
      expect(res.statusCode).to.equal(200);
      done();
    })
  });
});

describe('raw-postings post request',function(){
  it('posts with statusCode of 202',function(done){
      postone()
        .on('response',response=>{
          expect(response.statusCode).to.equal(202);
          done();
        });
    });

  it('returns the posted object from a post request',function(done){
      postone()
        .then(response=>{
          expect(response.country).to.equal('A');
        })
        .catch()
        .then(done);
    });

});

describe('raw-postings get request',function(){

  it('gets postings with statusCode of 202',function(done){
    getall()
      .on('response',response=>{
        expect(response.statusCode).to.equal(202);
        done();
      });
  });

  it('getall returns an array of collections',function(done){
    postone()
      .then(getall)
      .then(response=>{
        var res = JSON.parse(response);
        expect(Array.isArray(res)).to.equal(true);
      })
      .then(done)
      .catch(done)
  });

  it('getone returns an array of one collection',function(done){
    postfour()
      .then(getone)
      .then(response=>{
        var res = JSON.parse(response);
        expect(Array.isArray(res)).to.equal(true);
      })
      .then(done)
      .catch(done)
  });

  it('gets one collection by date',function(done){
    postone()
      .then(posttwo)
      .then(postfour)
      .then(getone)
      .then((response)=>{
        var res = JSON.parse(response);
        expect(res.length).to.equal(1);
        expect(res[0].postings.length).to.equal(1);
      })
      .finally(done);
  })

  it('returns all collections on a getall request',function(done){
    postone()
      .then(getall)
      .then(response=>{
        var res = JSON.parse(response);
        expect(res[0].postings[0].country).to.equal('A');

      })
      .then(done)
      .catch(done)
  });

});

describe('raw-postings delete request',function(){

  it('deletes postings with statusCode of 204',function(done){
    deleteall()
      .on('response',response=>{
        expect(response.statusCode).to.equal(204);
        done();
      });
  });

  it('deletes one datelist by date',function(done){
    postone()
      .then(posttwo)
      .then(postfour)
      .then(deleteone)
      .then(getall)
      .then((response)=>{
        var res = JSON.parse(response);
        expect(res.length).to.equal(1);
        expect(res[0].postings[0].country).to.equal('A');
      })
      .finally(done);
  });

  it('deletes all posts',function(done){
    postone()
      .then(posttwo)
      .then(deleteall)
      .then(getall)
      .then((response)=>{
        expect(JSON.parse(response).length).to.equal(0);
      })
      .finally(done);
  });

});

describe('raw-postings database behavior',function(){

  it('adds multiple posts of the same date to the same list of postings',function(done){
    postone()
      .then(posttwo)
      .then(getall)
      .then((response)=>{
        expect(JSON.parse(response).length).to.equal(1);
        var res = JSON.parse(response);
        expect(res[0].postings.length).to.equal(2);
      })
      .finally(done);
  });

  it('adds multiple posts of a different date to different lists of postings',function(done){
    postone()
      .then(posttwo)
      .then(postfour)
      .then(getall)
      .then((response)=>{
        var res = JSON.parse(response);
        expect(res.length).to.equal(2);
        expect(res[0].postings.length).to.equal(2);
        expect(res[1].postings.length).to.equal(1);
      })
      .finally(done);
  });

});

<|endoftext|>


<commit_before>(function() {
	"use strict";

	angular.module('skyVisible').provider('skyVisible', skyVisibleProvider);

	skyVisibleProvider.$inject = [];

	function skyVisibleProvider() {
		var _this = this;

		_this.defaults = {
			// Take the offset above fold into account
			foldOffset: true,
			// Makes sure progress reaches 1 when
			// bottom of page is reached
			bottomOffset: true
		};

		_this.getDefaults = function() {
			return _this.defaults;
		};

		_this.$get = skyVisible;

		skyVisible.$inject = ['skyVisibleViews', '$window'];

		function skyVisible(skyVisibleViews, $window) {

			// window variables
			var scrollPosition = {
				x:$window.pageYOffset,
				y:$window.pageXOffset
			};

			var windowHeight = $window.innerHeight;

			// Get the document height - assume it's the highest number
			var documentHeight = Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight);

			// List of all elements and their preferences
			var items = [];

			// Different calculations
			var views = skyVisibleViews;

			// Default view preferences
			var defaults = _this.getDefaults();

			/**
			 * Runs on resize debounce.
			 * Iterates through onResizeMethods
			 *
			 * Makes sure the resize methods are run after the window and
			 * document height is calculated
			 */
			function recalculateItems(element) {
				element = element ? getElement(element) : false;

				// Get the window height
				windowHeight = $window.innerHeight;
				documentHeight = Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight);

				if(element) {
					recalculateItem(getItem(element));
					return;
				}

				for (var i = 0; i < items.length; i++) {
					recalculateItem(items[i]);
				}

				function recalculateItem(item) {
					if(!item) {
						return;
					}
					// If theres a shouldRecalculate method, make sure it returns true
					if((angular.isFunction(item.shouldRecalculate) && item.shouldRecalculate()) || item.shouldRecalculate === undefined || item.shouldRecalculate ) {
						item.recalculate();
					}
				}
			}

			/**
			 * Runs through all methods in onScrollMethods
			 *
			 * Makes sure the methods are only run after the scroll
			 * position and window position is calculated
			 *
			 * @param {node} element [optional]
			 * @param {boolean} checkCache [optional]
			 */
			function checkItemsViews(element, checkCache) {
				element = element ? getElement(element) : false;

				// Get scroll position
				var position = {
					y: $window.pageYOffset,
					x: $window.pageXOffset
				};

				// Prevent running methods if position not changed
				if(angular.equals(position, scrollPosition) && checkCache) {
					return;
				} else {
					angular.extend(scrollPosition, position);
				}

				if(element) {
					checkItemViews(getItem(element));
					return;
				}

				for (var i = 0; i < items.length; i++) {
					checkItemViews(items[i]);
				}

				function checkItemViews(item) {
					// If theres a shouldUpdate method, make sure it returns true
					if((angular.isFunction(item.shouldUpdate) && item.shouldUpdate()) || item.shouldUpdate === undefined || item.shouldUpdate) {
						item.checkViews();
					}
				}
			}

			/**
			 * Public method that adds methods to a view, for
			 * a given element
			 *
			 * @param {array} elements
			 * @param {string} view
			 * @param {object} preferences [optional]
			 * @param {function} method
			 */
			function addMethods(elements, view, preferences, method) {
				elements = elements.length !== undefined ? elements : [elements];

				// View is left out
				if(angular.isObject(view)) {
					method = preferences;
					preferences = view;
					view = '';

				// view and preferences are left out
				} else if(angular.isFunction(view)) {
					method = view;
					preferences = {};
					view = '';

				// Preferences is left out
				} else if(angular.isFunction(preferences)) {
					method = preferences;
					preferences = {};
				}

				for (var i = 0; i < elements.length; i++) {
					var element = getElement(elements[i]);

					var item = addMethod(element, view, preferences, method, name);

					// If first - init item
					if(item.methods.length === 1 && angular.equals(item.methods[0].method, method)) {
						itemSetup(element);
					}
				}
			}

			/**
			 * Public method that removes a method from a
			 * bunch of element
			 * @param {array} elements
			 * @param {string} view
			 * @param {function} method
			 */
			function removeMethods(elements, view, method) {
				elements = elements.length !== undefined ? elements : [elements];

				// View is left out
				if(angular.isFunction(view)) {
					method = view;
					view = '';
				}

				// If no method or view, remove entire item
				if(!method && !view) {
					removeItems(elements);
					return;
				}

				for (var i = 0; i < elements.length; i++) {
					var element = getElement(elements[i]);
					var item = getItem(element);

					item.methods = item.methods.filter(filterMethods);
				}

				// Filter out methods based on view & method
				function filterMethods(item) {
					if(!method && view) {
						return item.view !== view;
					} else if(method && !view) {
						return item.method !== method;
					}

					return !(item.method === method && item.view === view);
				}
			}

			/**
			 * Get an item based on element
			 *
			 * @param {node} element
			 * @return {object}
			 */
			function getItem(element) {
				// If angular element or normal element
				element = element.tagName ? element : element[0];
				var index = getItemIndex(element);
				return items[index];
			}

			/**
			 * Create an item with a givin element,
			 * if non found, and returns the item
			 *
			 * @param {node} element
			 * @return {object}
			 */
			function addItem(element) {
				element = getElement(element);

				var index = getItemIndex(element);

				// Add to items and store item
				if(index === -1) {
					index = -1 + items.push({
						node: element,
						methods: []
					});
				}

				return items[index];
			}

			/**
			 * Removes items, based on their element
			 *
			 * @param {array} elements
			 */
			function removeItems(elements) {
				elements = elements.length !== undefined ? elements : [elements];

				for (var i = 0; i < elements.length; i++) {
					var index = getItemIndex(elements[i]);
					if(index !== -1) {
						items.splice(index, 1);
					}
				}
			}

			/**
			 * This methods does all the calculations and exposes
			 * methods for recalculation and checking views
			 *
			 * @param {node} element
			 */
			function itemSetup(element) {
				element = element instanceof Element ? element : angular.element(element);

				// Element properties
				var boundingRect = element.getBoundingClientRect();

				var dimentions = {
					height: element.offsetHeight,
					width: element.offsetWidth,
					top: boundingRect.top + scrollPosition.y - document.documentElement.clientTop,
					left: boundingRect.left + scrollPosition.x - document.documentElement.clientLeft,
					boundingClientRect: boundingRect
				};

				var elementHeight = element.offsetHeight;
				var elementBoundingRect = element.getBoundingClientRect();
				var elementOffsetTop = elementBoundingRect.top + scrollPosition.y - document.documentElement.clientTop;

				var viewVariables = {};

				var item = getItem(element);

				item.recalculate = recalculate;
				item.checkViews = checkViews;
				item.dimentions = dimentions;

				angular.element(element).on('$destroy skyVisible:unbind', destroy);

				// Assume other elements affected
				checkItemsViews();

				/**
				 * Recalculates variables
				 * Function added to onResize
				 */
				function recalculate() {
					boundingRect = element.getBoundingClientRect();

					dimentions.height = element.offsetHeight;
					dimentions.width = element.offsetWidth;
					dimentions.top = boundingRect.top + scrollPosition.y - document.documentElement.clientTop;
					dimentions.left = boundingRect.left + scrollPosition.x - document.documentElement.clientLeft;
					dimentions.boundingClientRect = boundingRect;

					checkViews();
				}

				/**
				 * Checks rather the element is visible in the defined
				 * views. It will then loop over them and dispatch an event
				 * with the given values
				 */
				function checkViews()  {
					var element = item.node;
					var methods = item.methods;

					for(var j = 0; j < methods.length; j++) {
						var method = methods[j];
						var callback = method.method;
						var view = method.view;
						var preferences = method.preferences;
						var value;

						if(views[view] && angular.isFunction(callback)) {
							// Continue if shouldUpdate function returns fales
							if(angular.isFunction(preferences.shouldUpdate) && !preferences.shouldUpdate()) {
								continue;
							}

							// Continue if shouldUpdate is falsy, without being undefined
							if(preferences.shouldUpdate !== undefined && !preferences.shouldUpdate) {
								continue;
							}

							// Get value
							value = views[view].call(undefined, element, dimentions, scrollPosition, windowHeight, documentHeight, preferences);

							// Continue if nothing changed
							if(angular.equals(value, method.value)) {
								continue;
							}

							callback.call(element, value, dimentions);
							method.value = value;
						}
					}
				}

				/**
				 * Unbind and remove resize/scroll methods
				 */
				function destroy() {
					removeItems(element);
					angular.element(element).off('$destroy skyVisible:unbind', destroy);
				}
			}

			/**
			 * Get the index of an item, that
			 * has a giving element
			 *
			 * @param {node} element
			 * @return {number}
			 */
			function getItemIndex(element) {
				var index = -1;
				for (var i = 0; i < items.length; i++) {
					var item = items[i];

					if(element instanceof Element && item.node === element) {
						index = i;
						break;
					}

					if(angular.isString(element) && element === item.name) {
						index = i;
						break;
					}
				}

				return index;
			}

			/**
			 * Get an element from the items list
			 *
			 * @param {node} element
			 * @return {node}
			 */
			function getElement(element) {
				// String -> getItem -> node
				// Element -> element
				// defined -> element[0]
				// element
				return angular.isString(element) ? getItem(element).node : element instanceof Element ? element : element !== undefined ? element[0] : element;
			}

			/**
			 * Adds a method to an item. The element is used to finde
			 * the specific item - if non found it will create one
			 *
			 * The used item will be returned
			 *
			 * @param {node} element
			 * @param {string} view [outer]
			 * @param {object} preferences
			 * @param {function} method
			 * @return {object}
			 */
			function addMethod(element, view, preferences, method) {
				view = view || 'outer';

				preferences =  angular.extend({}, defaults, (preferences || {}));

				// If element already added
				var index = getItemIndex(element);

				var exists = index !== -1;

				// The element item
				var item = addItem(element);

				// Add a view if givin
				// Adds to array of views
				if(item.methods.length) {
					item.methods.push({
						view:view,
						method:method,
						preferences:preferences
					});
					// Creates an array of views
				} else {
					item.methods = [{
						view:view,
						method:method,
						preferences:preferences
					}];
				}

				return item;
			}

			/**
			 * Give an item a reference name. The element
			 * is used to find an item
			 *
			 * @param {node} element
			 * @param {string} name
			 * @return {object}
			 */
			function setReference(element, name) {
				var item = addItem(element);
				item.name = name;
				return item;
			}

			/**
			 * Look up an item by reference name
			 *
			 * @param {string} name
			 * @return {object|boolean}
			 */
			function getReference(name) {
				var item = getItem(name) || {};
				return item.node || false;
			}

			window.skyVisible = {
				setReference:setReference,
				getReference:getItem,
				bind:addMethods,
				unbind:removeMethods,
				recalculate:recalculateItems,
				checkViews:checkItemsViews
			};

			// Exposes public methods
			return {
				setReference:setReference,
				getReference:getItem,

				bind:addMethods,
				unbind:removeMethods,

				recalculate:recalculateItems,
				checkViews:checkItemsViews
			};
		}
	}
})();
<commit_msg>enable value caching<commit_after>(function() {
	"use strict";

	angular.module('skyVisible').provider('skyVisible', skyVisibleProvider);

	skyVisibleProvider.$inject = [];

	function skyVisibleProvider() {
		var _this = this;

		_this.defaults = {
			// Take the offset above fold into account
			foldOffset: true,
			// Makes sure progress reaches 1 when
			// bottom of page is reached
			bottomOffset: true,
			// Caches the value - prevents executing callback
			// if value is the same
			cache:true
		};

		_this.getDefaults = function() {
			return _this.defaults;
		};

		_this.$get = skyVisible;

		skyVisible.$inject = ['skyVisibleViews', '$window'];

		function skyVisible(skyVisibleViews, $window) {

			// window variables
			var scrollPosition = {
				x:$window.pageYOffset,
				y:$window.pageXOffset
			};

			var windowHeight = $window.innerHeight;

			// Get the document height - assume it's the highest number
			var documentHeight = Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight);

			// List of all elements and their preferences
			var items = [];

			// Different calculations
			var views = skyVisibleViews;

			// Default view preferences
			var defaults = _this.getDefaults();

			/**
			 * Runs on resize debounce.
			 * Iterates through onResizeMethods
			 *
			 * Makes sure the resize methods are run after the window and
			 * document height is calculated
			 */
			function recalculateItems(element) {
				element = element ? getElement(element) : false;

				// Get the window height
				windowHeight = $window.innerHeight;
				documentHeight = Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight);

				if(element) {
					recalculateItem(getItem(element));
					return;
				}

				for (var i = 0; i < items.length; i++) {
					recalculateItem(items[i]);
				}

				function recalculateItem(item) {
					if(!item) {
						return;
					}
					// If theres a shouldRecalculate method, make sure it returns true
					if((angular.isFunction(item.shouldRecalculate) && item.shouldRecalculate()) || item.shouldRecalculate === undefined || item.shouldRecalculate ) {
						item.recalculate();
					}
				}
			}

			/**
			 * Runs through all methods in onScrollMethods
			 *
			 * Makes sure the methods are only run after the scroll
			 * position and window position is calculated
			 *
			 * @param {node} element [optional]
			 * @param {boolean} checkCache [optional]
			 */
			function checkItemsViews(element, checkCache) {
				element = element ? getElement(element) : false;

				// Get scroll position
				var position = {
					y: $window.pageYOffset,
					x: $window.pageXOffset
				};

				// Prevent running methods if position not changed
				if(angular.equals(position, scrollPosition) && checkCache) {
					return;
				} else {
					angular.extend(scrollPosition, position);
				}

				if(element) {
					checkItemViews(getItem(element));
					return;
				}

				for (var i = 0; i < items.length; i++) {
					checkItemViews(items[i]);
				}

				function checkItemViews(item) {
					// If theres a shouldUpdate method, make sure it returns true
					if((angular.isFunction(item.shouldUpdate) && item.shouldUpdate()) || item.shouldUpdate === undefined || item.shouldUpdate) {
						item.checkViews();
					}
				}
			}

			/**
			 * Public method that adds methods to a view, for
			 * a given element
			 *
			 * @param {array} elements
			 * @param {string} view
			 * @param {object} preferences [optional]
			 * @param {function} method
			 */
			function addMethods(elements, view, preferences, method) {
				elements = elements.length !== undefined ? elements : [elements];

				// View is left out
				if(angular.isObject(view)) {
					method = preferences;
					preferences = view;
					view = '';

				// view and preferences are left out
				} else if(angular.isFunction(view)) {
					method = view;
					preferences = {};
					view = '';

				// Preferences is left out
				} else if(angular.isFunction(preferences)) {
					method = preferences;
					preferences = {};
				}

				for (var i = 0; i < elements.length; i++) {
					var element = getElement(elements[i]);

					var item = addMethod(element, view, preferences, method, name);

					// If first - init item
					if(item.methods.length === 1 && angular.equals(item.methods[0].method, method)) {
						itemSetup(element);
					}
				}
			}

			/**
			 * Public method that removes a method from a
			 * bunch of element
			 * @param {array} elements
			 * @param {string} view
			 * @param {function} method
			 */
			function removeMethods(elements, view, method) {
				elements = elements.length !== undefined ? elements : [elements];

				// View is left out
				if(angular.isFunction(view)) {
					method = view;
					view = '';
				}

				// If no method or view, remove entire item
				if(!method && !view) {
					removeItems(elements);
					return;
				}

				for (var i = 0; i < elements.length; i++) {
					var element = getElement(elements[i]);
					var item = getItem(element);

					item.methods = item.methods.filter(filterMethods);
				}

				// Filter out methods based on view & method
				function filterMethods(item) {
					if(!method && view) {
						return item.view !== view;
					} else if(method && !view) {
						return item.method !== method;
					}

					return !(item.method === method && item.view === view);
				}
			}

			/**
			 * Get an item based on element
			 *
			 * @param {node} element
			 * @return {object}
			 */
			function getItem(element) {
				// If angular element or normal element
				element = element.tagName ? element : element[0];
				var index = getItemIndex(element);
				return items[index];
			}

			/**
			 * Create an item with a givin element,
			 * if non found, and returns the item
			 *
			 * @param {node} element
			 * @return {object}
			 */
			function addItem(element) {
				element = getElement(element);

				var index = getItemIndex(element);

				// Add to items and store item
				if(index === -1) {
					index = -1 + items.push({
						node: element,
						methods: []
					});
				}

				return items[index];
			}

			/**
			 * Removes items, based on their element
			 *
			 * @param {array} elements
			 */
			function removeItems(elements) {
				elements = elements.length !== undefined ? elements : [elements];

				for (var i = 0; i < elements.length; i++) {
					var index = getItemIndex(elements[i]);
					if(index !== -1) {
						items.splice(index, 1);
					}
				}
			}

			/**
			 * This methods does all the calculations and exposes
			 * methods for recalculation and checking views
			 *
			 * @param {node} element
			 */
			function itemSetup(element) {
				element = element instanceof Element ? element : angular.element(element);

				// Element properties
				var boundingRect = element.getBoundingClientRect();

				var dimentions = {
					height: element.offsetHeight,
					width: element.offsetWidth,
					top: boundingRect.top + scrollPosition.y - document.documentElement.clientTop,
					left: boundingRect.left + scrollPosition.x - document.documentElement.clientLeft,
					boundingClientRect: boundingRect
				};

				var elementHeight = element.offsetHeight;
				var elementBoundingRect = element.getBoundingClientRect();
				var elementOffsetTop = elementBoundingRect.top + scrollPosition.y - document.documentElement.clientTop;

				var viewVariables = {};

				var item = getItem(element);

				item.recalculate = recalculate;
				item.checkViews = checkViews;
				item.dimentions = dimentions;

				angular.element(element).on('$destroy skyVisible:unbind', destroy);

				// Assume other elements affected
				checkItemsViews();

				/**
				 * Recalculates variables
				 * Function added to onResize
				 */
				function recalculate() {
					boundingRect = element.getBoundingClientRect();

					dimentions.height = element.offsetHeight;
					dimentions.width = element.offsetWidth;
					dimentions.top = boundingRect.top + scrollPosition.y - document.documentElement.clientTop;
					dimentions.left = boundingRect.left + scrollPosition.x - document.documentElement.clientLeft;
					dimentions.boundingClientRect = boundingRect;

					checkViews();
				}

				/**
				 * Checks rather the element is visible in the defined
				 * views. It will then loop over them and dispatch an event
				 * with the given values
				 */
				function checkViews()  {
					var element = item.node;
					var methods = item.methods;

					for(var j = 0; j < methods.length; j++) {
						var method = methods[j];
						var callback = method.method;
						var view = method.view;
						var preferences = method.preferences;
						var value;

						if(views[view] && angular.isFunction(callback)) {
							// Continue if shouldUpdate function returns fales
							if(angular.isFunction(preferences.shouldUpdate) && !preferences.shouldUpdate()) {
								continue;
							}

							// Continue if shouldUpdate is falsy, without being undefined
							if(preferences.shouldUpdate !== undefined && !preferences.shouldUpdate) {
								continue;
							}

							// Get value
							value = views[view].call(undefined, element, dimentions, scrollPosition, windowHeight, documentHeight, preferences);

							// Continue if nothing changed
							if(angular.equals(value, method.value) && preferences.cache) {
								continue;
							}

							callback.call(element, value, dimentions);
							method.value = value;
						}
					}
				}

				/**
				 * Unbind and remove resize/scroll methods
				 */
				function destroy() {
					removeItems(element);
					angular.element(element).off('$destroy skyVisible:unbind', destroy);
				}
			}

			/**
			 * Get the index of an item, that
			 * has a giving element
			 *
			 * @param {node} element
			 * @return {number}
			 */
			function getItemIndex(element) {
				var index = -1;
				for (var i = 0; i < items.length; i++) {
					var item = items[i];

					if(element instanceof Element && item.node === element) {
						index = i;
						break;
					}

					if(angular.isString(element) && element === item.name) {
						index = i;
						break;
					}
				}

				return index;
			}

			/**
			 * Get an element from the items list
			 *
			 * @param {node} element
			 * @return {node}
			 */
			function getElement(element) {
				// String -> getItem -> node
				// Element -> element
				// defined -> element[0]
				// element
				return angular.isString(element) ? getItem(element).node : element instanceof Element ? element : element !== undefined ? element[0] : element;
			}

			/**
			 * Adds a method to an item. The element is used to finde
			 * the specific item - if non found it will create one
			 *
			 * The used item will be returned
			 *
			 * @param {node} element
			 * @param {string} view [outer]
			 * @param {object} preferences
			 * @param {function} method
			 * @return {object}
			 */
			function addMethod(element, view, preferences, method) {
				view = view || 'outer';

				preferences =  angular.extend({}, defaults, (preferences || {}));

				// If element already added
				var index = getItemIndex(element);

				var exists = index !== -1;

				// The element item
				var item = addItem(element);

				// Add a view if givin
				// Adds to array of views
				if(item.methods.length) {
					item.methods.push({
						view:view,
						method:method,
						preferences:preferences
					});
					// Creates an array of views
				} else {
					item.methods = [{
						view:view,
						method:method,
						preferences:preferences
					}];
				}

				return item;
			}

			/**
			 * Give an item a reference name. The element
			 * is used to find an item
			 *
			 * @param {node} element
			 * @param {string} name
			 * @return {object}
			 */
			function setReference(element, name) {
				var item = addItem(element);
				item.name = name;
				return item;
			}

			/**
			 * Look up an item by reference name
			 *
			 * @param {string} name
			 * @return {object|boolean}
			 */
			function getReference(name) {
				var item = getItem(name) || {};
				return item.node || false;
			}

			window.skyVisible = {
				setReference:setReference,
				getReference:getItem,
				bind:addMethods,
				unbind:removeMethods,
				recalculate:recalculateItems,
				checkViews:checkItemsViews
			};

			// Exposes public methods
			return {
				setReference:setReference,
				getReference:getItem,

				bind:addMethods,
				unbind:removeMethods,

				recalculate:recalculateItems,
				checkViews:checkItemsViews
			};
		}
	}
})();
<|endoftext|>


<commit_before>/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 * Thanks to: Seamus Leahy for adding deltaX and deltaY
 *
 * Version: 3.0.3
 *
 * Requires: 1.2.2+
 */

(function($) {

var types = ['DOMMouseScroll', 'mousewheel'];

$.event.special.mousewheel = {
    setup: function() {
        if ( this.addEventListener ) {
            for ( var i=types.length; i; ) {
                this.addEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = handler;
        }
    },

    teardown: function() {
        if ( this.removeEventListener ) {
            for ( var i=types.length; i; ) {
                this.removeEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = null;
        }
    }
};

$.fn.extend({
    mousewheel: function(fn) {
        return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
    },

    unmousewheel: function(fn) {
        return this.unbind("mousewheel", fn);
    }
});

function handler(event) {
    var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;

    event = $.event.fix(event || window.event);
    event.type = "mousewheel";

    // Old school scrollwheel delta
    if ( event.wheelDelta ) { delta = event.wheelDelta/120; }
    if ( event.detail     ) { delta = -event.detail/3; }

    // New school multidimensional scroll (touchpads) deltas
    deltaY = delta;

    // Gecko
    if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
        deltaY = 0;
        deltaX = -1*delta;
    }

    // Webkit
    if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
    if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }

    // Add event and delta to the front of the arguments
    args.unshift(event, delta, deltaX, deltaY);

    return $.event.handle.apply(this, args);
}

})(jQuery);<commit_msg>Updated to 3.0.4 of the mousewheel plugin - official release which fixes the IE issue...<commit_after>/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 * Thanks to: Seamus Leahy for adding deltaX and deltaY
 *
 * Version: 3.0.4
 *
 * Requires: 1.2.2+
 */

(function($) {

var types = ['DOMMouseScroll', 'mousewheel'];

$.event.special.mousewheel = {
    setup: function() {
        if ( this.addEventListener ) {
            for ( var i=types.length; i; ) {
                this.addEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = handler;
        }
    },

    teardown: function() {
        if ( this.removeEventListener ) {
            for ( var i=types.length; i; ) {
                this.removeEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = null;
        }
    }
};

$.fn.extend({
    mousewheel: function(fn) {
        return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
    },

    unmousewheel: function(fn) {
        return this.unbind("mousewheel", fn);
    }
});

function handler(event) {
    var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
    event = $.event.fix(orgEvent);
    event.type = "mousewheel";

    // Old school scrollwheel delta
    if ( event.wheelDelta ) { delta = event.wheelDelta/120; }
    if ( event.detail     ) { delta = -event.detail/3; }

    // New school multidimensional scroll (touchpads) deltas
    deltaY = delta;

    // Gecko
    if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
        deltaY = 0;
        deltaX = -1*delta;
    }

    // Webkit
    if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
    if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }

    // Add event and delta to the front of the arguments
    args.unshift(event, delta, deltaX, deltaY);

    return $.event.handle.apply(this, args);
}

})(jQuery);<|endoftext|>


<commit_before>require.config({
    paths: {
        jquery: '/lib/jqueryui/external/jquery/jquery',
        spectrum: '/lib/jquerycolorpicker/spectrum',
        jqui: '/lib/jqueryui/jquery-ui',
        btncom:'/js/module/btncom/btncom',
        btncom_content:'/js/module/btncom/btncom_content',
        btncom_style:'/js/module/btncom/btncom_style',
        imgcom:'/js/module/imgcom/imgcom',
        imgcom_content:'/js/module/imgcom/imgcom_content',
        imgcom_style:'/js/module/imgcom/imgcom_style',
        pagecom:'/js/module/page/pagecom',
        imgs: '/js/module/imgs/imgs',
        pagecom_content:'/js/module/page/pagecom_content'
    },
    shim: {
        'jqui': {
            deps: ['jquery']
        },
        'spectrum': {
            deps: ['jquery']
        }
    }
});

require(['zepto','jquery','spectrum','btncom', 'imgcom',
    'btncom_content','btncom_style','imgcom_content',
    'imgcom_style','jqui','pagecom','imgs'], function (zepto,$,bigcolorpicker,Btncom,Imgcom,btncom_content,btncom_style,imgcom_content,imgcom_style,jqui,Pagecom,Imgs) {

    var Btncom = Btncom.Btncom;
    var Imgcom = Imgcom.Imgcom;
    var procon = $('#prototype-content');
    procon.tabs();
    var pagecom = new Pagecom();
    pagecom.initPage({Btncom: Btncom});
    var selectImgDialog = $('#selectImgDialog');
    selectImgDialog.tabs();

    var addtext = $('#addtext');
    var addimage = $('#addimage');
    var addbutton = $('#addbutton');
    var addpages = $('.add-page-list');

    addpages.on('click', function () {
        pagecom.addPage();
    });
    addimage.on('click', function () {

        Imgs.onImgSelect=function(imgSrc){
            var imgcom = new Imgcom({
                imgSrc:imgSrc
            });
            imgcom.render({
                container: zepto('#showbox')
            });
        };
        Imgs.show();

    });

    addbutton.on('click', function () {
        var pageId = pagecom.getSelectPage();
        var btncom = new Btncom({
            pageId: pageId
        });
        btncom.render({
            container: zepto('#showbox')
        });
    });

    $('#showbox').on('click','.W_iteam',function (e) {
        var $that = $(this);
        $('#J_pageContent').hide();
        var siblings = $that.siblings();
        $that.addClass('select');
        $that.draggable({
            cursor: 'move',
            containment: 'parent',
            cancel: false
        });
        $that.resizable({
            handles: ' n, e, s, w, ne, se, sw, nw',
            minWidth: 50,
            maxHeight: 200,
            minHeight: 20
        });
        $that.disableSelection();
        siblings.removeClass('select');
        siblings.each(function (i, o) {
            if ($(o).resizable('instance')) {
                $(o).resizable('destroy');
            }
            if ($(o).draggable('instance')) {
                $(o).draggable('destroy');
            }

        });
    });
    $('#showbox').on('click',function (e) {
        var issWich = true;
        var $Witem = $(e.target).children();
        $.each($Witem,function(index,item){
            if($(item).hasClass('select')){
                $(item).removeClass('select').resizable('destroy');
            }
          });
        if(issWich){
            var $li = procon.children('ul').children('li');
            var $jp = procon.find('#J_pageContent');
            var $jb = procon.find('#J_btncomContent');
            var $jm = procon.find('#J_imgcomContent');
            if (e.target.className == 'showbox') {
                $li.first().show().siblings('li').addClass('item-visible');
                $jp.show();
                $jb.hide();
                $jm.hide();
            } else {
                $li.siblings('li').removeClass('item-visible');
                $jp.hide();
                var type = $(e.target).data('type');
                if (type == 'btncom') {
                    $jb.show();
                } else if (type == 'imgcom') {
                    $jm.show();
                }
            }
         }
        e.stopPropagation();
    });

});<commit_msg> merger editorjs<commit_after>require.config({
    paths: {
        jquery: '/lib/jqueryui/external/jquery/jquery',
        spectrum: '/lib/jquerycolorpicker/spectrum',
        jqui: '/lib/jqueryui/jquery-ui',
        btncom:'/js/module/btncom/btncom',
        btncom_content:'/js/module/btncom/btncom_content',
        btncom_style:'/js/module/btncom/btncom_style',
        imgcom:'/js/module/imgcom/imgcom',
        imgcom_content:'/js/module/imgcom/imgcom_content',
        imgcom_style:'/js/module/imgcom/imgcom_style',
        pagecom:'/js/module/page/pagecom',
        imgs: '/js/module/imgs/imgs',
        pagecom_content:'/js/module/page/pagecom_content'
    },
    shim: {
        'jqui': {
            deps: ['jquery']
        },
        'spectrum': {
            deps: ['jquery']
        }
    }
});

require(['zepto','jquery','spectrum','btncom', 'imgcom',
    'btncom_content','btncom_style','imgcom_content',
    'imgcom_style','jqui','pagecom','imgs'], function (zepto,$,bigcolorpicker,Btncom,Imgcom,btncom_content,btncom_style,imgcom_content,imgcom_style,jqui,Pagecom,Imgs) {

    var Btncom = Btncom.Btncom;
    var Imgcom = Imgcom.Imgcom;
    var procon = $('#prototype-content');
    procon.tabs();
    var pagecom = new Pagecom();
    pagecom.initPage({Btncom: Btncom});
    var selectImgDialog = $('#selectImgDialog');
    selectImgDialog.tabs();

    var addtext = $('#addtext');
    var addimage = $('#addimage');
    var addbutton = $('#addbutton');
    var addpages = $('.add-page-list');

    addpages.on('click', function () {
        pagecom.addPage();
    });
    addimage.on('click', function () {

        Imgs.onImgSelect=function(imgSrc){
            var imgcom = new Imgcom({
                imgSrc:imgSrc
            });
            imgcom.render({
                container: zepto('#showbox')
            });
        };
        Imgs.show();

    });

    addbutton.on('click', function () {
        var pageId = pagecom.getSelectPage();
        var btncom = new Btncom({
            pageId: pageId
        });
        btncom.render({
            container: zepto('#showbox')
        });
    });

    $('#showbox').on('click','.W_iteam',function (e) {
        var $that = $(this);
        $('#J_pageContent').hide();
        var siblings = $that.siblings();
        $that.addClass('select');
        $that.draggable({
            cursor: 'move',
            containment: 'parent',
            cancel: false
        });
        $that.resizable({
            handles: ' n, e, s, w, ne, se, sw, nw',
            maxWidth: 300,
            minWidth: 50,
            maxHeight: 200,
            minHeight: 20
        });
        $that.disableSelection();
        siblings.removeClass('select');
        siblings.each(function (i, o) {
            if ($(o).resizable('instance')) {
                $(o).resizable('destroy');
            }
            if ($(o).draggable('instance')) {
                $(o).draggable('destroy');
            }

        });
    });
    $('#showbox').on('click',function (e) {
        var issWich = true;
        var $Witem = $(e.target).children();
        $.each($Witem,function(index,item){
            if($(item).hasClass('select')){
                $(item).removeClass('select').resizable('destroy');
            }
          });
        if(issWich){
            var $li = procon.children('ul').children('li');
            var $jp = procon.find('#J_pageContent');
            var $jb = procon.find('#J_btncomContent');
            var $jm = procon.find('#J_imgcomContent');
            if (e.target.className == 'showbox') {
                $li.first().show().siblings('li').addClass('item-visible');
                $jp.show();
                $jb.hide();
                $jm.hide();
            } else {
                $li.siblings('li').removeClass('item-visible');
                $jp.hide();
                var type = $(e.target).data('type');
                if (type == 'btncom') {
                    $jb.show();
                } else if (type == 'imgcom') {
                    $jm.show();
                }
            }
         }
        e.stopPropagation();
    });

});<|endoftext|>


<commit_before>"use strict";

const
    fs = require("fs"),
    tools = require("../res/tools.js"),
    osPathSeparator = require("path").sep,
    isWindows = tools.isWindows,
    toArray = arrayLike => [].slice.call(arrayLike),
    sep = path => osPathSeparator === "/" ? path : path.replace(/\//g, osPathSeparator),

    // Node supports / on any host
    platoCmd = "node node_modules/plato/bin/plato -l .jshintrc -t GPF-JS -d tmp/plato",
    jsdocCmd = "node node_modules/jsdoc/jsdoc -d tmp/jsdoc --verbose -a all -c doc/private.json",
    checkdocCmd = `node doc/validate http://localhost:${configuration.serve.httpPort}/tmp/doc/public/index.html`,

    config = (cmd, ...options) => {
        if ("string" === typeof cmd || "function" === typeof cmd) {
            cmd = {
                cmd: cmd
            };
        }
        return Object.assign.apply(Object, [cmd].concat(options));
    },

    silent = {
        stdout: false,
        stderr: false
    },
    showErrors = {
        stdout: false,
        stderr: true
    },
    verbose = {
        stdout: true,
        stderr: true
    },
    failIfNot0 = {
        exitCode: 0
    },

    testConfig = (name, command, parameters) => {
        if (isWindows && command.indexOf(" ") !== -1) {
            command = `"${command}"`;
        }
        command += ` ${parameters}`;
        const cmd = suffix => function () {
            let parameter;
            if (arguments.length) {
                parameter = toArray(arguments).join(" ") + " ";
            } else {
                parameter = "";
            }
            return command + " " + parameter + suffix;
        };
        module.exports[`test${name}`] = config(cmd(""), silent, failIfNot0);
        module.exports[`test${name}Verbose`] = config(cmd("-debugger"), verbose, failIfNot0);
        module.exports[`test${name}Coverage`] = config(cmd("-coverage"), silent, failIfNot0);
        module.exports[`test${name}Debug`] = config(cmd("-debug"), silent, failIfNot0);
        module.exports[`test${name}Release`] = config(cmd("-release"), silent, failIfNot0);
        module.exports[`test${name}Legacy`] = config(version => `${command} legacy/${version}`, silent, failIfNot0);
        module.exports[`test${name}Flavor`] = config(flavor => `${command} flavor:${flavor}`, silent, failIfNot0);
    };

let phantomJsBin = "/usr/local/phantomjs/bin/phantomjs"; // If already installed
if (!fs.existsSync(phantomJsBin)) {
    // Assume it is installed with the phantomjs-prebuilt package
    phantomJsBin = sep("node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs");
}

// Custom command lines
module.exports = {
    buildDebug: config({cmd: "node make.js debug", cwd: "make"}, silent, failIfNot0),
    buildRelease: config({cmd: "node make.js release", cwd: "make"}, silent, failIfNot0),
    plato: config(() => `${platoCmd} ${configuration.files.src.join(" ")}`, verbose),
    metrics: config((...args) => `node make/metrics.js ${args.join(" ")}`, showErrors, failIfNot0),
    globals: config("node make/globals.js", showErrors, failIfNot0),
    version: config("node make/version.js", silent, failIfNot0),
    detectSelenium: config("node test/host/selenium/detect.js", verbose, failIfNot0),
    jsdoc: config((...args) => `${jsdocCmd} ${args.join(" ")}`, verbose, failIfNot0),
    fixUglify: config(name => `node make/fix_uglify.js ${name}`, verbose, failIfNot0),
    checkDoc: config(checkdocCmd, verbose, failIfNot0)
};

// Flavor builds
Object.keys(configuration.files.flavors).forEach(flavor => {
    module.exports[`build${tools.capitalize(flavor)}`] = config({
        cmd: `node make.js flavor/${flavor}`,
        cwd: "make"
    }, silent, failIfNot0);
});

// Test configurations
testConfig("Node", "node", "test/host/nodejs.js");
testConfig("Phantom", phantomJsBin, sep("--web-security=false test/host/phantomjs.js"));
testConfig("Wscript", "cscript.exe", `/D /E:JScript ${sep("test/host/cscript.js")}`);
testConfig("Nodewscript", "node", "test/host/node_cscript.js");
testConfig("Rhino", "java", sep("-jar node_modules/rhino-1_7r5-bin/rhino1_7R5/js.jar test/host/java.js"));
testConfig("Nashorn", configuration.host.nashorn, sep("test/host/java.js  --"));

Object.keys(configuration.browsers).forEach(browserName =>{
    const
        browserConfig = configuration.browsers[browserName],
        capitalizedBrowserName = tools.capitalize(browserName);
    if ("selenium" === browserConfig.type) {
        testConfig(capitalizedBrowserName, "node", `test/host/selenium.js ${browserName}`);
    } else if ("spawn" === browserConfig.type) {
        testConfig(capitalizedBrowserName, "node", `test/host/browser.js ${browserName}`);
    }
});
<commit_msg>Generate zillions of traces (damn!)<commit_after>"use strict";

const
    fs = require("fs"),
    tools = require("../res/tools.js"),
    osPathSeparator = require("path").sep,
    isWindows = tools.isWindows,
    toArray = arrayLike => [].slice.call(arrayLike),
    sep = path => osPathSeparator === "/" ? path : path.replace(/\//g, osPathSeparator),

    // Node supports / on any host
    platoCmd = "node node_modules/plato/bin/plato -l .jshintrc -t GPF-JS -d tmp/plato",
    jsdocCmd = "node node_modules/jsdoc/jsdoc -d tmp/jsdoc --verbose -a all -c doc/private.json",
    checkdocCmd = `node doc/validate http://localhost:${configuration.serve.httpPort}/tmp/doc/public/index.html`,

    config = (cmd, ...options) => {
        if ("string" === typeof cmd || "function" === typeof cmd) {
            cmd = {
                cmd: cmd
            };
        }
        return Object.assign.apply(Object, [cmd].concat(options));
    },

    silent = {
        stdout: false,
        stderr: false
    },
    showErrors = {
        stdout: false,
        stderr: true
    },
    verbose = {
        stdout: true,
        stderr: true
    },
    failIfNot0 = {
        exitCode: 0
    },

    testConfig = (name, command, parameters) => {
        if (isWindows && command.indexOf(" ") !== -1) {
            command = `"${command}"`;
        }
        command += ` ${parameters}`;
        const cmd = suffix => function () {
            let parameter;
            if (arguments.length) {
                parameter = toArray(arguments).join(" ") + " ";
            } else {
                parameter = "";
            }
            return command + " " + parameter + suffix;
        };
        module.exports[`test${name}`] = config(cmd(""), silent, failIfNot0);
        module.exports[`test${name}Verbose`] = config(cmd("-debugger"), verbose, failIfNot0);
        module.exports[`test${name}Coverage`] = config(cmd("-coverage"), verbose, failIfNot0);
        module.exports[`test${name}Debug`] = config(cmd("-debug"), silent, failIfNot0);
        module.exports[`test${name}Release`] = config(cmd("-release"), silent, failIfNot0);
        module.exports[`test${name}Legacy`] = config(version => `${command} legacy/${version}`, silent, failIfNot0);
        module.exports[`test${name}Flavor`] = config(flavor => `${command} flavor:${flavor}`, silent, failIfNot0);
    };

let phantomJsBin = "/usr/local/phantomjs/bin/phantomjs"; // If already installed
if (!fs.existsSync(phantomJsBin)) {
    // Assume it is installed with the phantomjs-prebuilt package
    phantomJsBin = sep("node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs");
}

// Custom command lines
module.exports = {
    buildDebug: config({cmd: "node make.js debug", cwd: "make"}, silent, failIfNot0),
    buildRelease: config({cmd: "node make.js release", cwd: "make"}, silent, failIfNot0),
    plato: config(() => `${platoCmd} ${configuration.files.src.join(" ")}`, verbose),
    metrics: config((...args) => `node make/metrics.js ${args.join(" ")}`, showErrors, failIfNot0),
    globals: config("node make/globals.js", showErrors, failIfNot0),
    version: config("node make/version.js", silent, failIfNot0),
    detectSelenium: config("node test/host/selenium/detect.js", verbose, failIfNot0),
    jsdoc: config((...args) => `${jsdocCmd} ${args.join(" ")}`, verbose, failIfNot0),
    fixUglify: config(name => `node make/fix_uglify.js ${name}`, verbose, failIfNot0),
    checkDoc: config(checkdocCmd, verbose, failIfNot0)
};

// Flavor builds
Object.keys(configuration.files.flavors).forEach(flavor => {
    module.exports[`build${tools.capitalize(flavor)}`] = config({
        cmd: `node make.js flavor/${flavor}`,
        cwd: "make"
    }, silent, failIfNot0);
});

// Test configurations
testConfig("Node", "node", "test/host/nodejs.js");
testConfig("Phantom", phantomJsBin, sep("--web-security=false test/host/phantomjs.js"));
testConfig("Wscript", "cscript.exe", `/D /E:JScript ${sep("test/host/cscript.js")}`);
testConfig("Nodewscript", "node", "test/host/node_cscript.js");
testConfig("Rhino", "java", sep("-jar node_modules/rhino-1_7r5-bin/rhino1_7R5/js.jar test/host/java.js"));
testConfig("Nashorn", configuration.host.nashorn, sep("test/host/java.js  --"));

Object.keys(configuration.browsers).forEach(browserName =>{
    const
        browserConfig = configuration.browsers[browserName],
        capitalizedBrowserName = tools.capitalize(browserName);
    if ("selenium" === browserConfig.type) {
        testConfig(capitalizedBrowserName, "node", `test/host/selenium.js ${browserName}`);
    } else if ("spawn" === browserConfig.type) {
        testConfig(capitalizedBrowserName, "node", `test/host/browser.js ${browserName}`);
    }
});
<|endoftext|>


<commit_before>/**
 * Wrapper around the metrics package.  Contains convenience functions for
 * updating metrics in a global instance.  Serves a metrics status page via
 * HTTP.
 */

var debug = require('debug')('vox:eyes');
var http = require('http');
var metrics = require('metrics');

/**
 * Initializes the metrics server.
 */
exports.Init = function(serverPort) {
  if (exports.isInitialized) {
    throw new Error('Eyes metrics server is already initialized!');
  }
  return new MetricsCollector(serverPort);
}

exports._globalCollector = null;
exports.isInitialized = false;
exports.inc = function() {};
exports.dec = function() {};
exports.mark = function() {};
exports.observe = function() {};
exports.start = function() { return function() {} };
exports.close = function() {};

function MetricsCollector(serverPort) {
  exports._globalCollector = this;

  this.metricsServer = new MetricsServer(serverPort);
  this.metrics = {};
  exports.inc = this.inc.bind(this);
  exports.dec = this.dec.bind(this);
  exports.mark = this.mark.bind(this);
  exports.observe = this.observe.bind(this);
  exports.start = this.start.bind(this);
  exports.close = this.close.bind(this);
  exports.isInitialized = true;
}

/**
 * Increments a counter.  If you never need to decrement the counter, then you
 * probably want `mark()` instead.
 */
MetricsCollector.prototype.inc = function(name) {
  var metric = this.metrics[name];
  if (!metric) {
    metric = new metrics.Counter();
    this.metrics[name] = metric;
    this.metricsServer.addMetric(name, metric);
  }
  metric.inc();
  this.mark(name + '.inc_rate');
}

/**
 * Decrements a counter.
 */
MetricsCollector.prototype.dec = function(name) {
  var metric = this.metrics[name];
  if (!metric) {
    metric = new metrics.Counter();
    this.metrics[name] = metric;
    this.metricsServer.addMetric(name, metric);
  }
  metric.dec();
  this.mark(name + '.dec_rate');
}

/**
 * Marks an event.
 */
MetricsCollector.prototype.mark = function(name) {
  var metric = this.metrics[name];
  if (!metric) {
    metric = new metrics.Meter();
    this.metrics[name] = metric;
    this.metricsServer.addMetric(name, metric);
  }
  metric.mark();
}

/**
 * Observes a value and stuffs it into a histogram.
 */
MetricsCollector.prototype.observe = function(name, val, opt_unit) {
  var metric = this.metrics[name];
  if (!metric) {
    metric = new metrics.Histogram.createUniformHistogram();
    this.metrics[name] = metric;
    this.metricsServer.addMetric(name, metric, opt_unit || '');
  }
  metric.update(val);
}

/**
 * Starts a timer.
 *
 * @return {function(opt_itemCount)} A function that stops the timer and reports
 *     the delta. May be called multiple times.  If `opt_itemCount` is given,
 *     then an additional metric ".avg_per_item" is added, with the total time
 *     divided by the item count.
 */
MetricsCollector.prototype.start = function(name) {
  var metric = this.metrics[name];
  if (!metric) {
    metric = new metrics.Timer();
    this.metrics[name] = metric;
    this.metricsServer.addMetric(name, metric);
  }
  var start = process.hrtime();
  var self = this;
  return function(opt_itemCount) {
    var delta = process.hrtime(start);
    var ns = delta[0] * 1e9 + delta[1];
    var ms = ns / 1e6;
    metric.update(ms);
    if (opt_itemCount) {
      var perItemMs = ms / opt_itemCount;
      var perItemName = name + '.avg_per_item';
      var itemMetric = self.metrics[perItemName];
      if (!itemMetric) {
        itemMetric = new metrics.Timer();
        self.metrics[perItemName] = itemMetric;
        self.metricsServer.addMetric(perItemName, itemMetric);
      }
      itemMetric.update(perItemMs);
    }
  }
}

MetricsCollector.prototype.close = function() {
  this.metricsServer.server.close();
  exports._globalCollector = null;
  exports.isInitialized = false;
}

/**
 * A simple server for metrics.  Serves a metrics report in a text format on the
 * path "/eyes".
 */
function MetricsServer(port) {
  this.servedMetrics = [];
  this.sorted = true;
  this.startTime = new Date();
  this.server = http.createServer(this._handleRequest.bind(this));
  this.server.listen(port);
  debug('Serving metrics on localhost:%d/eyes', port);
}

var TIMER_PERCENTILES = [0.5, 0.9, 0.99];
var OBSERVER_PERCENTILES = [0.1, 0.25, 0.5, 0.75, 0.9, 0.99];

MetricsServer.prototype.addMetric = function(name, metric, opt_unit) {
  this.servedMetrics.push([name, metric, opt_unit]);
  this.sorted = false;
}

MetricsServer.prototype._handleRequest = function(req, res) {
  if (req.url != '/eyes' || req.method != 'GET') {
    res.statusCode = 404;
    res.write('ok');
    res.end();
    return;
  }
  res.writeHead(200, {
      'Content-Type': 'text/plain'
  });
  res.write('Started ' + this.startTime);
  res.write('\nUptime ' + process.uptime() + ' seconds');
  res.write('\nNow ' + (Date.now()));
  var memoryUsage = process.memoryUsage();
  res.write('\nRSS ' + memoryUsage.rss / 1e3);
  res.write('K\nheapUsed ' + memoryUsage.heapUsed / 1e3);
  res.write('K\nheapTotal ' + memoryUsage.heapTotal / 1e3);
  res.write('K\n=================\n');

  if (!this.sorted) {
    this.servedMetrics.sort(function(a, b) { return a[0].localeCompare(b[0]) });
    this.sorted = true;
  }

  for (var i = 0; i < this.servedMetrics.length; i++) {
    var tuple = this.servedMetrics[i];
    res.write(tuple[0] + ':');
    var metric = tuple[1];
    if (metric instanceof metrics.Counter) {
      res.write('\n    count ' + metric.count);
    } else if (metric instanceof metrics.Meter) {
      writeMeter(res, metric);
    } else if (metric instanceof metrics.Timer) {
      writeMeter(res, metric.meter);
      writeHistogram(res, metric.histogram, TIMER_PERCENTILES, ' ms');
    } else if (metric instanceof metrics.Histogram) {
      writeHistogram(res, metric, OBSERVER_PERCENTILES, ' ' + tuple[2]);
    }
    res.write('\n');
  }
  res.end();
}

function writeMeter(res, meter) {
  res.write('\n    count ' + meter.count);
  res.write('\n    1m_rate ' + meter.m1Rate.rate().toFixed(3));
  res.write('/s\n    5m_rate ' + meter.m5Rate.rate().toFixed(3));
  res.write('/s\n    15m_rate ' + meter.m15Rate.rate().toFixed(3));
  res.write('/s');
}

function writeHistogram(res, histogram, percentiles, suffix) {
  if (!histogram.count) {
    return;
  }
  res.write('\n    var ' + histogram.variance().toFixed(3));
  res.write(suffix);
  res.write('\n    mean ' + histogram.mean().toFixed(3));
  res.write(suffix);
  var scores = histogram.percentiles(percentiles);
  for (var i = 0; i < percentiles.length; i++) {
    var p = percentiles[i];
    res.write('\n    ');
    res.write((p * 100).toFixed(0) + '% ' + scores[p].toFixed(3));
    res.write(suffix);
  }
}
<commit_msg>Add os info to /eyes<commit_after>/**
 * Wrapper around the metrics package.  Contains convenience functions for
 * updating metrics in a global instance.  Serves a metrics status page via
 * HTTP.
 */

var debug = require('debug')('vox:eyes');
var http = require('http');
var metrics = require('metrics');
var os = require('os');

/**
 * Initializes the metrics server.
 */
exports.Init = function(serverPort) {
  if (exports.isInitialized) {
    throw new Error('Eyes metrics server is already initialized!');
  }
  return new MetricsCollector(serverPort);
}

exports._globalCollector = null;
exports.isInitialized = false;
exports.inc = function() {};
exports.dec = function() {};
exports.mark = function() {};
exports.observe = function() {};
exports.start = function() { return function() {} };
exports.close = function() {};

function MetricsCollector(serverPort) {
  exports._globalCollector = this;

  this.metricsServer = new MetricsServer(serverPort);
  this.metrics = {};
  exports.inc = this.inc.bind(this);
  exports.dec = this.dec.bind(this);
  exports.mark = this.mark.bind(this);
  exports.observe = this.observe.bind(this);
  exports.start = this.start.bind(this);
  exports.close = this.close.bind(this);
  exports.isInitialized = true;
}

/**
 * Increments a counter.  If you never need to decrement the counter, then you
 * probably want `mark()` instead.
 */
MetricsCollector.prototype.inc = function(name) {
  var metric = this.metrics[name];
  if (!metric) {
    metric = new metrics.Counter();
    this.metrics[name] = metric;
    this.metricsServer.addMetric(name, metric);
  }
  metric.inc();
  this.mark(name + '.inc_rate');
}

/**
 * Decrements a counter.
 */
MetricsCollector.prototype.dec = function(name) {
  var metric = this.metrics[name];
  if (!metric) {
    metric = new metrics.Counter();
    this.metrics[name] = metric;
    this.metricsServer.addMetric(name, metric);
  }
  metric.dec();
  this.mark(name + '.dec_rate');
}

/**
 * Marks an event.
 */
MetricsCollector.prototype.mark = function(name) {
  var metric = this.metrics[name];
  if (!metric) {
    metric = new metrics.Meter();
    this.metrics[name] = metric;
    this.metricsServer.addMetric(name, metric);
  }
  metric.mark();
}

/**
 * Observes a value and stuffs it into a histogram.
 */
MetricsCollector.prototype.observe = function(name, val, opt_unit) {
  var metric = this.metrics[name];
  if (!metric) {
    metric = new metrics.Histogram.createUniformHistogram();
    this.metrics[name] = metric;
    this.metricsServer.addMetric(name, metric, opt_unit || '');
  }
  metric.update(val);
}

/**
 * Starts a timer.
 *
 * @return {function(opt_itemCount)} A function that stops the timer and reports
 *     the delta. May be called multiple times.  If `opt_itemCount` is given,
 *     then an additional metric ".avg_per_item" is added, with the total time
 *     divided by the item count.
 */
MetricsCollector.prototype.start = function(name) {
  var metric = this.metrics[name];
  if (!metric) {
    metric = new metrics.Timer();
    this.metrics[name] = metric;
    this.metricsServer.addMetric(name, metric);
  }
  var start = process.hrtime();
  var self = this;
  return function(opt_itemCount) {
    var delta = process.hrtime(start);
    var ns = delta[0] * 1e9 + delta[1];
    var ms = ns / 1e6;
    metric.update(ms);
    if (opt_itemCount) {
      var perItemMs = ms / opt_itemCount;
      var perItemName = name + '.avg_per_item';
      var itemMetric = self.metrics[perItemName];
      if (!itemMetric) {
        itemMetric = new metrics.Timer();
        self.metrics[perItemName] = itemMetric;
        self.metricsServer.addMetric(perItemName, itemMetric);
      }
      itemMetric.update(perItemMs);
    }
  }
}

MetricsCollector.prototype.close = function() {
  this.metricsServer.server.close();
  exports._globalCollector = null;
  exports.isInitialized = false;
}

/**
 * A simple server for metrics.  Serves a metrics report in a text format on the
 * path "/eyes".
 */
function MetricsServer(port) {
  this.servedMetrics = [];
  this.sorted = true;
  this.startTime = new Date();
  this.server = http.createServer(this._handleRequest.bind(this));
  this.server.listen(port);
  debug('Serving metrics on localhost:%d/eyes', port);
}

var TIMER_PERCENTILES = [0.5, 0.9, 0.99];
var OBSERVER_PERCENTILES = [0.1, 0.25, 0.5, 0.75, 0.9, 0.99];

MetricsServer.prototype.addMetric = function(name, metric, opt_unit) {
  this.servedMetrics.push([name, metric, opt_unit]);
  this.sorted = false;
}

MetricsServer.prototype._handleRequest = function(req, res) {
  if (req.url != '/eyes' || req.method != 'GET') {
    res.statusCode = 404;
    res.write('ok');
    res.end();
    return;
  }
  res.writeHead(200, {
      'Content-Type': 'text/plain'
  });
  res.write('Started ' + this.startTime);
  res.write('\nUptime ' + process.uptime() + ' seconds');
  res.write('\nNow ' + (Date.now()));
  var memoryUsage = process.memoryUsage();
  res.write('\nRSS ' + memoryUsage.rss / 1e3);
  res.write('K\nheapUsed ' + memoryUsage.heapUsed / 1e3);
  res.write('K\nheapTotal ' + memoryUsage.heapTotal / 1e3);
  res.write('K\nos.totalmem ' + os.totalmem() / 1e3);
  res.write('K\nos.freemem ' + os.freemem() / 1e3);
  res.write('K\nos.loadavg ' + os.loadavg());
  if (!this.cpuCount) {
    this.cpuCount = os.cpus().length;
  }
  res.write('\nos.cpu_count ' + this.cpuCount);
  res.write('\n=================\n');

  if (!this.sorted) {
    this.servedMetrics.sort(function(a, b) { return a[0].localeCompare(b[0]) });
    this.sorted = true;
  }

  for (var i = 0; i < this.servedMetrics.length; i++) {
    var tuple = this.servedMetrics[i];
    res.write(tuple[0] + ':');
    var metric = tuple[1];
    if (metric instanceof metrics.Counter) {
      res.write('\n    count ' + metric.count);
    } else if (metric instanceof metrics.Meter) {
      writeMeter(res, metric);
    } else if (metric instanceof metrics.Timer) {
      writeMeter(res, metric.meter);
      writeHistogram(res, metric.histogram, TIMER_PERCENTILES, ' ms');
    } else if (metric instanceof metrics.Histogram) {
      writeHistogram(res, metric, OBSERVER_PERCENTILES, ' ' + tuple[2]);
    }
    res.write('\n');
  }
  res.end();
}

function writeMeter(res, meter) {
  res.write('\n    count ' + meter.count);
  res.write('\n    1m_rate ' + meter.m1Rate.rate().toFixed(3));
  res.write('/s\n    5m_rate ' + meter.m5Rate.rate().toFixed(3));
  res.write('/s\n    15m_rate ' + meter.m15Rate.rate().toFixed(3));
  res.write('/s');
}

function writeHistogram(res, histogram, percentiles, suffix) {
  if (!histogram.count) {
    return;
  }
  res.write('\n    var ' + histogram.variance().toFixed(3));
  res.write(suffix);
  res.write('\n    mean ' + histogram.mean().toFixed(3));
  res.write(suffix);
  var scores = histogram.percentiles(percentiles);
  for (var i = 0; i < percentiles.length; i++) {
    var p = percentiles[i];
    res.write('\n    ');
    res.write((p * 100).toFixed(0) + '% ' + scores[p].toFixed(3));
    res.write(suffix);
  }
}
<|endoftext|>


<commit_before>// Load data tiles using the JQuery ajax function
L.TileLayer.Ajax = L.TileLayer.extend({
    options: {
        // use L.tileCacheNone to turn caching off
        tileCacheFactory: L.tileCache
    },

    _tileCache: null,

    initialize: function (url, options) {
        L.TileLayer.prototype.initialize.call(this, url, options);

        this._tileCache = this.options.tileCacheFactory();
    },

    onAdd: function (map) {
        L.TileLayer.prototype.onAdd.call(this, map);
        this.on('tileunload', this._unloadTile);
    },
    onRemove: function (map) {
        L.TileLayer.prototype.onRemove.call(this, map);
        this.off('tileunload', this._unloadTile);
    },
    _addTile: function(tilePoint, container) {
        var cached = null;
        var key = tilePoint.x + ':' + tilePoint.y;
        var urlZoom = this._getZoomForUrl();
        var tile = cached = this._tileCache.get(key, urlZoom);
        if (!tile) {
            tile = { key: key, urlZoom: urlZoom, datum: null, loading: true };
        } else {
            tile.loading = true;
        }

        this._tiles[key] = tile;
        this.fire('tileloadstart', {tile: tile});

        if (cached) {
            this._addTileData(tile);
        } else {
            this._loadTile(tile, tilePoint);
        }
    },
    _addTileData: function(tile) {
        // override in subclass
    },
    // XMLHttpRequest handler; closure over the XHR object, the layer, and the tile
    _xhrHandler: function (req, layer, tile) {
        return function() {
            if (req.readyState != 4) {
                return;
            }
            var s = req.status;
            if ((s >= 200 && s < 300) || s == 304) {
                // check if request is about to be aborted, avoid rare error when aborted while parsing
                if (tile._request) {
                    tile._request = null;
                    layer.fire('tileresponse', {tile: tile, request: req});
                    tile.datum = req.responseText;
                    layer._addTileData(tile);
                }
            } else {
                tile.loading = false;
                tile._request = null;
                layer.fire('tileerror', {tile: tile, request: req});
                layer._tileLoaded();
            }
        }
    },
    // Load the requested tile via AJAX
    _loadTile: function (tile, tilePoint) {
        this._adjustTilePoint(tilePoint);
        var layer = this;
        var req = new XMLHttpRequest();
        tile._request = req;
        req.onreadystatechange = this._xhrHandler(req, layer, tile);
        this.fire('tilerequest', {tile: tile, request: req});
        req.open('GET', this.getTileUrl(tilePoint), true);
        req.send();
    },
    _unloadTile: function(evt) {
        var tile = evt.tile,
            req = tile._request;
        if (req) {
            tile._request = null;
            req.abort();
            this.fire('tilerequestabort', {tile: tile, request: req});
        }
    }
});

L.TileLayer.Vector = L.TileLayer.Ajax.extend({
    options: {
        // factory function to create the vector tile layers (defaults to L.GeoJSON)
        layerFactory: L.geoJson,
        // factory function to create a web worker for parsing/preparing tile data
        //workerFactory: L.communistWorker
        workerFactory: L.noWorker
    },
    initialize: function (url, options, vectorOptions) {
        L.TileLayer.Ajax.prototype.initialize.call(this, url, options);
        this.vectorOptions = vectorOptions || {};
        this._worker = this.options.workerFactory(L.TileLayer.Vector.parseData);
        this._addQueue = new L.TileQueue(L.bind(this._addTileDataInternal, this));
    },
    onAdd: function (map) {
        this._map = map;

        L.TileLayer.Ajax.prototype.onAdd.call(this, map);

        // root vector layer, contains tile vector layers as children
        this.vectorLayer = this._createVectorLayer();
        map.addLayer(this.vectorLayer);

        this._worker.onAdd(map);
        this._tileCache.onAdd(map);
    },
    onRemove: function (map) {
        // unload tiles (L.TileLayer only calls _reset in onAdd)
        this._reset();
        map.removeLayer(this.vectorLayer);

        L.TileLayer.Ajax.prototype.onRemove.call(this, map);

        this._worker.onRemove(map);
        this._tileCache.onRemove(map);

        this.vectorLayer = null;
        this._map = null;
    },
    _createVectorLayer: function() {
        return this.options.layerFactory(null, this.vectorOptions);
    },
    _createTileLayer: function() {
        return this._createVectorLayer();
    },
    _addTileData: function(tile) {
        if (!tile.parsed) {
            this._worker.process(tile, L.bind(function(tile) {
                this._addQueue.add(tile);
            },this));
        } else {
            // from cache
            this._addQueue.add(tile);
        }
    },
    _addTileDataInternal: function(tile) {
        var tileLayer = this._createTileLayer();
        if (!tile.parsed) {
            // when no worker for parsing
            tile.parsed = L.TileLayer.Vector.parseData(tile.datum);
            tile.datum = null;
        }
        tileLayer.addData(tile.parsed);
        tile.layer = tileLayer;
        this.vectorLayer.addLayer(tileLayer);

        tile.loading = false;
        this.fire('tileload', {tile: tile});
        this._tileLoaded();
    },
    _unloadTile: function(evt) {
        L.TileLayer.Ajax.prototype._unloadTile.apply(this, arguments);

        var tile = evt.tile,
            tileLayer = tile.layer;
        if (tile.loading) {
            this._addQueue.remove(tile);
            // not from cache or not loaded and parsed yet
            if (!tile.parsed) {
                this._worker.abort(tile);
            }
            this.fire('tileabort', {tile: tile});
            this._tileLoaded();
        }
        if (tileLayer && this.vectorLayer.hasLayer(tileLayer)) {
            this.vectorLayer.removeLayer(tileLayer);
        }

        if (tile.parsed) {
            this._tileCache.put(tile);
        }
    },
    _reset: function() {
        L.TileLayer.Ajax.prototype._reset.apply(this, arguments);
        this._addQueue.clear();
        this._worker.clear();
    }
});

L.extend(L.TileLayer.Vector, {
    parseData: function(data) {
        return JSON.parse(data);
    }
});
<commit_msg>start updating to Leaflet master (0.8-dev): fix errors<commit_after>// Load data tiles using the JQuery ajax function
L.TileLayer.Ajax = L.TileLayer.extend({
    options: {
        // use L.tileCacheNone to turn caching off
        tileCacheFactory: L.tileCache
    },

    _tileCache: null,

    initialize: function (url, options) {
        L.TileLayer.prototype.initialize.call(this, url, options);

        this._tileCache = this.options.tileCacheFactory();
    },

    onAdd: function (map) {
        L.TileLayer.prototype.onAdd.call(this, map);
        this.on('tileunload', this._unloadTile);
    },
    onRemove: function (map) {
        L.TileLayer.prototype.onRemove.call(this, map);
        this.off('tileunload', this._unloadTile);
    },
    _addTile: function(coords, container) {
        var cached = null;
        var key = this._tileCoordsToKey(coords);
        var urlZoom = this._getZoomForUrl();
        var tile = cached = this._tileCache.get(key, urlZoom);
        if (!tile) {
            tile = { key: key, urlZoom: urlZoom, datum: null, loading: true };
        } else {
            tile.loading = true;
        }

        this._tiles[key] = tile;
        this.fire('tileloadstart', {tile: tile});

        if (cached) {
            this._addTileData(tile);
        } else {
            this._loadTile(tile, coords);
        }
    },
    _addTileData: function(tile) {
        // override in subclass
    },
    // XMLHttpRequest handler; closure over the XHR object, the layer, and the tile
    _xhrHandler: function (req, layer, tile) {
        return function() {
            if (req.readyState != 4) {
                return;
            }
            var s = req.status;
            if ((s >= 200 && s < 300) || s == 304) {
                // check if request is about to be aborted, avoid rare error when aborted while parsing
                if (tile._request) {
                    tile._request = null;
                    layer.fire('tileresponse', {tile: tile, request: req});
                    tile.datum = req.responseText;
                    layer._addTileData(tile);
                }
            } else {
                tile.loading = false;
                tile._request = null;
                layer.fire('tileerror', {tile: tile, request: req});
                layer._tileLoaded();
            }
        }
    },
    // Load the requested tile via AJAX
    _loadTile: function (tile, coords) {
        var layer = this;
        var req = new XMLHttpRequest();
        tile._request = req;
        req.onreadystatechange = this._xhrHandler(req, layer, tile);
        this.fire('tilerequest', {tile: tile, request: req});
        req.open('GET', this.getTileUrl(coords), true);
        req.send();
    },
    _unloadTile: function(evt) {
        var tile = evt.tile,
            req = tile._request;
        if (req) {
            tile._request = null;
            req.abort();
            this.fire('tilerequestabort', {tile: tile, request: req});
        }
    },
    // TODO _tileLoaded replaced by _tileReady + _visibleTilesReady,
    // but cannot use because tile assumed to be component (L.DomUtil.addClass)?
    _tileLoaded: function () {
        this._tilesToLoad--;

        if (this._tilesToLoad === 0) {
            this.fire('load');
        }
    }
});

L.TileLayer.Vector = L.TileLayer.Ajax.extend({
    options: {
        // factory function to create the vector tile layers (defaults to L.GeoJSON)
        layerFactory: L.geoJson,
        // factory function to create a web worker for parsing/preparing tile data
        //workerFactory: L.communistWorker
        workerFactory: L.noWorker
    },
    initialize: function (url, options, vectorOptions) {
        L.TileLayer.Ajax.prototype.initialize.call(this, url, options);
        this.vectorOptions = vectorOptions || {};
        this._worker = this.options.workerFactory(L.TileLayer.Vector.parseData);
        this._addQueue = new L.TileQueue(L.bind(this._addTileDataInternal, this));
    },
    onAdd: function (map) {
        this._map = map;

        L.TileLayer.Ajax.prototype.onAdd.call(this, map);

        // root vector layer, contains tile vector layers as children
        this.vectorLayer = this._createVectorLayer();
        map.addLayer(this.vectorLayer);

        this._worker.onAdd(map);
        this._tileCache.onAdd(map);
    },
    onRemove: function (map) {
        // unload tiles (L.TileLayer only calls _reset in onAdd)
        this._reset();
        map.removeLayer(this.vectorLayer);

        L.TileLayer.Ajax.prototype.onRemove.call(this, map);

        this._worker.onRemove(map);
        this._tileCache.onRemove(map);

        this.vectorLayer = null;
        this._map = null;
    },
    _createVectorLayer: function() {
        return this.options.layerFactory(null, this.vectorOptions);
    },
    _createTileLayer: function() {
        return this._createVectorLayer();
    },
    _addTileData: function(tile) {
        if (!tile.parsed) {
            this._worker.process(tile, L.bind(function(tile) {
                this._addQueue.add(tile);
            },this));
        } else {
            // from cache
            this._addQueue.add(tile);
        }
    },
    _addTileDataInternal: function(tile) {
        var tileLayer = this._createTileLayer();
        if (!tile.parsed) {
            // when no worker for parsing
            tile.parsed = L.TileLayer.Vector.parseData(tile.datum);
            tile.datum = null;
        }
        tileLayer.addData(tile.parsed);
        tile.layer = tileLayer;
        this.vectorLayer.addLayer(tileLayer);

        tile.loading = false;
        this.fire('tileload', {tile: tile});
        this._tileLoaded();
    },
    _unloadTile: function(evt) {
        L.TileLayer.Ajax.prototype._unloadTile.apply(this, arguments);

        var tile = evt.tile,
            tileLayer = tile.layer;
        if (tile.loading) {
            this._addQueue.remove(tile);
            // not from cache or not loaded and parsed yet
            if (!tile.parsed) {
                this._worker.abort(tile);
            }
            this.fire('tileabort', {tile: tile});
            this._tileLoaded();
        }
        if (tileLayer && this.vectorLayer.hasLayer(tileLayer)) {
            this.vectorLayer.removeLayer(tileLayer);
        }

        if (tile.parsed) {
            this._tileCache.put(tile);
        }
    },
    _reset: function() {
        L.TileLayer.Ajax.prototype._reset.apply(this, arguments);
        this._addQueue.clear();
        this._worker.clear();
    }
});

L.extend(L.TileLayer.Vector, {
    parseData: function(data) {
        return JSON.parse(data);
    }
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

var path = require('path');
var fs = require('fs');

var mainBowerFiles = require('main-bower-files');

module.exports = {
  src: src
};

function src(gulp, options) {

  options = options || {};

  // Grab globs from main-bower-files module.
  // This sorts out the dependencies.

  var globs = mainBowerFiles(options);

  for(var i = 0; i < globs.length; i++) {

    var glob = globs[i];

    var ext = path.extname(glob);

    if((ext === '.js' || ext === '.css' ) && glob.indexOf('.min') == -1) {
      var dirname = path.dirname(glob);
      var basename = path.basename(glob);

      var minified = basename.split('.');
      minified.splice(1, 0, 'min');
      minified = minified.join('.');
      minified = path.join(dirname, minified);

      i += 1;
      globs.splice(i, 0, minified);

    }
  }

//  console.log(globs);
  // If the current build target is production we'll try to grab minified files where possible.

//  if(options.env === 'production') {
//    globs = globs.map(function(glob) {
//
//      var ext = path.extname(glob);
//
//      if(ext === '.js' || ext === '.css') {
//        return getMinifiedFilename(glob, { exists: true });
//      } else {
//        return glob;
//      }
//
//    });
//  }

  return gulp.src(globs, options);
}

function getMinifiedFilename(filename, opts) {

  opts = opts || {};

  var dirname = path.dirname(filename);
  var basename = path.basename(filename);

  var minified = basename.split('.');
  minified.splice(1, 0, 'min');
  minified = minified.join('.');
  minified = path.join(dirname, minified);

  if(opts.exists && !fs.existsSync(minified)) {
    return filename;
  }

  return minified;
}
<commit_msg>bower cp include source map files<commit_after>#!/usr/bin/env node

var path = require('path');
var fs = require('fs');

var mainBowerFiles = require('main-bower-files');

module.exports = {
  src: src
};

function src(gulp, options) {

  options = options || {};

  // Grab globs from main-bower-files module.
  // This sorts out the dependencies.

  var globs = mainBowerFiles(options);

  for(var i = 0; i < globs.length; i++) {

    var glob = globs[i];

    var ext = path.extname(glob);

    // Check if the extension is JS or css
    if(ext === '.js' || ext === '.css') {

      if(glob.indexOf('.min') == -1) {
        // Add the minified version file name to the list
        var dirname = path.dirname(glob);
        var basename = path.basename(glob);

        var minified = basename.split('.');
        minified.splice(1, 0, 'min');
        minified = minified.join('.');
        minified = path.join(dirname, minified);

        i += 1;
        globs.splice(i, 0, minified);
      }

      // Add the source map file name

      i += 1;
      globs.splice(i, 0, glob + '.map');

    }
  }

//  console.log(globs);
  // If the current build target is production we'll try to grab minified files where possible.

//  if(options.env === 'production') {
//    globs = globs.map(function(glob) {
//
//      var ext = path.extname(glob);
//
//      if(ext === '.js' || ext === '.css') {
//        return getMinifiedFilename(glob, { exists: true });
//      } else {
//        return glob;
//      }
//
//    });
//  }

  return gulp.src(globs, options);
}

function getMinifiedFilename(filename, opts) {

  opts = opts || {};

  var dirname = path.dirname(filename);
  var basename = path.basename(filename);

  var minified = basename.split('.');
  minified.splice(1, 0, 'min');
  minified = minified.join('.');
  minified = path.join(dirname, minified);

  if(opts.exists && !fs.existsSync(minified)) {
    return filename;
  }

  return minified;
}
<|endoftext|>