<commit_before>const React = require('react')
const MediaQuery = require('index').default
const mm = { default: require('matchmediaquery') }
const assert = require('chai').assert
const sinon = require('sinon')
const ReactDOM = require('react-dom')
const TestUtils = require('react-dom/test-utils')

describe('MediaQuery', function () {
  describe('when query matches', function () {
    before(function () {
      this.mmStub = sinon.stub(mm, 'default').returns({
        matches: true,
        addListener: function () {},
        removeListener: function () {}
      })
    })
    after(function () {
      this.mmStub.restore()
    })
    it('renders with output of callback', function () {
      const mq = (
        <MediaQuery query="all">
          {matches =>
}
        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.isNotFalse(TestUtils.findRenderedDOMComponentWithClass(e, 'matched'))
    })
    it('renders children', function () {
      const mq = (
        <MediaQuery query="all">

        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.isNotFalse(TestUtils.findRenderedDOMComponentWithClass(e, 'childComponent'))
    })
    it('renders text node', function () {
      const mq = (
        <MediaQuery query="all">
          1231
        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.isNotFalse(TestUtils.findAllInRenderedTree(e, function () {return true}))
    })
    it('does not wrap text node', function () {
      const mq = (
        <MediaQuery query="all">
          1231
        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.throws(() => (TestUtils.findRenderedDOMComponentWithTag(e, 'div')), /Did not find exactly one match/)
    })
    it('renders the wrapper', function () {
      const mq = (
        <MediaQuery query="all" component="section">

        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.isNotFalse(TestUtils.findRenderedDOMComponentWithTag(e, 'section'))
    })
    it('does not render a div when there are multiple children', function () {
      const mq = (
        <MediaQuery query="all">

        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.throws(() => (TestUtils.findRenderedDOMComponentWithTag(e, 'div')), /Did not find exactly one match/)
    })
    it('render a div when there are extra props and multiple children', function () {
      const mq = (
        <MediaQuery query="all" className="wrapper">

        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.isNotFalse(TestUtils.findRenderedDOMComponentWithTag(e, 'div'))
    })
    it('renders the first child when children is a single-element array', function () {
      const mq = (
        <MediaQuery query="all">
          {[ 'single element' ].map((content, index) => {content})}
        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.isNotFalse(TestUtils.findRenderedDOMComponentWithTag(e, 'span'))
      assert.throws(() => (TestUtils.findRenderedDOMComponentWithTag(e, 'div')), /Did not find exactly one match/)
    })
    it('passes extra props', function () {
      const mq = (
        <MediaQuery query="all" className="passedProp">

        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.isNotFalse(TestUtils.findRenderedDOMComponentWithClass(e, 'passedProp'))
    })
    it('uses query prop if it has one', function () {
      const mq = (
        <MediaQuery query="all" className="passedProp">

        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.equal(e.query, 'all')
    })
    it('builds query from props', function () {
      const mq = (
        <MediaQuery all className="passedProp">

        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.equal(e.query, 'all')
    })
    it('builds query from values', function () {
      const mq = (
        <MediaQuery orientation="portrait" className="passedProp">

        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.equal(e.query, '(orientation: portrait)')
    })
    it('throws if theres no query', function () {
      const mq = (
        <MediaQuery>

        </MediaQuery>
      )
      assert.throws(() => (TestUtils.renderIntoDocument(mq)), 'Invalid or missing MediaQuery!')
    })
    it('throws if theres a bad query', function () {
      const mq = (
        <MediaQuery doesntExist="test">

        </MediaQuery>
      )
      assert.throws(() => (TestUtils.renderIntoDocument(mq)), 'Invalid or missing MediaQuery!')
    })
    it('renders nothing when children is an empty array', function () {
      const mq = (
        <MediaQuery query="all">
          {[].map((content, index) => {
            return
{content}

          })}
        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.equal(e.render(), null)
    })
    it.skip('forces static check if values are specified', function () {
      const values = { width: 150 }
      const query = '(max-width: 300px)'
      const mq = (
        <MediaQuery values={values} query={query}>

        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      // TODO: looks like this.mmStub is never called?
      assert.isNotFalse(this.mmStub.calledWithMatch(e.query, values, true))
    })
  })
  it('renders nothing when no matches', function () {
    const mq = (
      <MediaQuery maxWidth={300}>

      </MediaQuery>
    )
    const e = TestUtils.renderIntoDocument(mq)
    assert.throws(() => (TestUtils.findRenderedDOMComponentWithClass(e, 'childComponent')), /Did not find exactly one match/)
  })
  it('renders taking values with precedence', function () {
    const mq = (
      <MediaQuery values={{ width: 150 }} maxWidth={300}>

      </MediaQuery>
    )
    const e = TestUtils.renderIntoDocument(mq)
    assert.isNotFalse(TestUtils.findRenderedDOMComponentWithClass(e, 'childComponent'))
  })
  it('doesnt render taking values with precedence', function () {
    const mq = (
      <MediaQuery values={{ width: 350 }} maxWidth={300}>

      </MediaQuery>
    )
    const e = TestUtils.renderIntoDocument(mq)
    assert.throws(() => (TestUtils.findRenderedDOMComponentWithClass(e, 'childComponent')), /Did not find exactly one match/)
  })
  it('doesnt throw error when unspecificed component with empty children', function () {
    const mq = (
      <MediaQuery all className="parentBox" />
    )
    const e = TestUtils.renderIntoDocument(mq)
    assert.isNotFalse(TestUtils.findRenderedDOMComponentWithClass(e, 'parentBox'))
  })
  it('doesnt throw error when component with null children', function () {
    const mq = (
      <MediaQuery all className="parentBox">{null}</MediaQuery>
    )
    const e = TestUtils.renderIntoDocument(mq)
    assert.isNotFalse(TestUtils.findRenderedDOMComponentWithClass(e, 'parentBox'))
  })

  it('renders with output of callback', function () {
    const mq = (
      <MediaQuery maxWidth={300}>
        {matches =>
}
      </MediaQuery>
    )
    const e = TestUtils.renderIntoDocument(mq)
    assert.isNotFalse(TestUtils.findRenderedDOMComponentWithClass(e, 'no-match'))
  })
  it('calls onChange callback if provided', function () {
    const callback = sinon.spy()
    const mq = (
      <MediaQuery onChange={callback} query="all">

      </MediaQuery>
    )
    const e = TestUtils.renderIntoDocument(mq)
    e.setState({ matches: false })
    assert.isNotFalse(callback.calledOnce)
  })
  it('calls onBeforeChange callback if provided', function () {
    const callback = sinon.spy()
    const mq = (
      <MediaQuery onBeforeChange={callback} query="all">

      </MediaQuery>
    )
    const e = TestUtils.renderIntoDocument(mq)
    e.setState({ matches: false })
    assert.isNotFalse(callback.calledOnce)
  })
  it('calls onChange callback after onBeforeChange if booth are provided', function () {
    const onChangeCallback = sinon.spy()
    const onBeforeChangeCallback = sinon.spy()

    const mq = (
      <MediaQuery
        onChange={onChangeCallback}
        onBeforeChange={onBeforeChangeCallback}
        query="all"
      >

      </MediaQuery>
    )
    const e = TestUtils.renderIntoDocument(mq)
    e.setState({ matches: false })
    assert.isNotFalse(onBeforeChangeCallback.calledBefore(onChangeCallback))
  })
  it('handles unmount', function () {
    const container = document.createElement('div')
    const mq = (
      <MediaQuery query="all">

      </MediaQuery>
    )
    ReactDOM.render(mq, container)
    assert.doesNotThrow(() => ReactDOM.unmountComponentAtNode(container))
  })
})
<commit_msg>Remove skipped test<commit_after>const React = require('react')
const MediaQuery = require('index').default
const mm = { default: require('matchmediaquery') }
const assert = require('chai').assert
const sinon = require('sinon')
const ReactDOM = require('react-dom')
const TestUtils = require('react-dom/test-utils')

describe('MediaQuery', function () {
  describe('when query matches', function () {
    before(function () {
      this.mmStub = sinon.stub(mm, 'default').returns({
        matches: true,
        addListener: function () {},
        removeListener: function () {}
      })
    })
    after(function () {
      this.mmStub.restore()
    })
    it('renders with output of callback', function () {
      const mq = (
        <MediaQuery query="all">
          {matches =>
}
        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.isNotFalse(TestUtils.findRenderedDOMComponentWithClass(e, 'matched'))
    })
    it('renders children', function () {
      const mq = (
        <MediaQuery query="all">

        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.isNotFalse(TestUtils.findRenderedDOMComponentWithClass(e, 'childComponent'))
    })
    it('renders text node', function () {
      const mq = (
        <MediaQuery query="all">
          1231
        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.isNotFalse(TestUtils.findAllInRenderedTree(e, function () {return true}))
    })
    it('does not wrap text node', function () {
      const mq = (
        <MediaQuery query="all">
          1231
        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.throws(() => (TestUtils.findRenderedDOMComponentWithTag(e, 'div')), /Did not find exactly one match/)
    })
    it('renders the wrapper', function () {
      const mq = (
        <MediaQuery query="all" component="section">

        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.isNotFalse(TestUtils.findRenderedDOMComponentWithTag(e, 'section'))
    })
    it('does not render a div when there are multiple children', function () {
      const mq = (
        <MediaQuery query="all">

        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.throws(() => (TestUtils.findRenderedDOMComponentWithTag(e, 'div')), /Did not find exactly one match/)
    })
    it('render a div when there are extra props and multiple children', function () {
      const mq = (
        <MediaQuery query="all" className="wrapper">

        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.isNotFalse(TestUtils.findRenderedDOMComponentWithTag(e, 'div'))
    })
    it('renders the first child when children is a single-element array', function () {
      const mq = (
        <MediaQuery query="all">
          {[ 'single element' ].map((content, index) => {content})}
        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.isNotFalse(TestUtils.findRenderedDOMComponentWithTag(e, 'span'))
      assert.throws(() => (TestUtils.findRenderedDOMComponentWithTag(e, 'div')), /Did not find exactly one match/)
    })
    it('passes extra props', function () {
      const mq = (
        <MediaQuery query="all" className="passedProp">

        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.isNotFalse(TestUtils.findRenderedDOMComponentWithClass(e, 'passedProp'))
    })
    it('uses query prop if it has one', function () {
      const mq = (
        <MediaQuery query="all" className="passedProp">

        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.equal(e.query, 'all')
    })
    it('builds query from props', function () {
      const mq = (
        <MediaQuery all className="passedProp">

        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.equal(e.query, 'all')
    })
    it('builds query from values', function () {
      const mq = (
        <MediaQuery orientation="portrait" className="passedProp">

        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.equal(e.query, '(orientation: portrait)')
    })
    it('throws if theres no query', function () {
      const mq = (
        <MediaQuery>

        </MediaQuery>
      )
      assert.throws(() => (TestUtils.renderIntoDocument(mq)), 'Invalid or missing MediaQuery!')
    })
    it('throws if theres a bad query', function () {
      const mq = (
        <MediaQuery doesntExist="test">

        </MediaQuery>
      )
      assert.throws(() => (TestUtils.renderIntoDocument(mq)), 'Invalid or missing MediaQuery!')
    })
    it('renders nothing when children is an empty array', function () {
      const mq = (
        <MediaQuery query="all">
          {[].map((content, index) => {
            return
{content}

          })}
        </MediaQuery>
      )
      const e = TestUtils.renderIntoDocument(mq)
      assert.equal(e.render(), null)
    })
  })
  it('renders nothing when no matches', function () {
    const mq = (
      <MediaQuery maxWidth={300}>

      </MediaQuery>
    )
    const e = TestUtils.renderIntoDocument(mq)
    assert.throws(() => (TestUtils.findRenderedDOMComponentWithClass(e, 'childComponent')), /Did not find exactly one match/)
  })
  it('renders taking values with precedence', function () {
    const mq = (
      <MediaQuery values={{ width: 150 }} maxWidth={300}>

      </MediaQuery>
    )
    const e = TestUtils.renderIntoDocument(mq)
    assert.isNotFalse(TestUtils.findRenderedDOMComponentWithClass(e, 'childComponent'))
  })
  it('doesnt render taking values with precedence', function () {
    const mq = (
      <MediaQuery values={{ width: 350 }} maxWidth={300}>

      </MediaQuery>
    )
    const e = TestUtils.renderIntoDocument(mq)
    assert.throws(() => (TestUtils.findRenderedDOMComponentWithClass(e, 'childComponent')), /Did not find exactly one match/)
  })
  it('doesnt throw error when unspecificed component with empty children', function () {
    const mq = (
      <MediaQuery all className="parentBox" />
    )
    const e = TestUtils.renderIntoDocument(mq)
    assert.isNotFalse(TestUtils.findRenderedDOMComponentWithClass(e, 'parentBox'))
  })
  it('doesnt throw error when component with null children', function () {
    const mq = (
      <MediaQuery all className="parentBox">{null}</MediaQuery>
    )
    const e = TestUtils.renderIntoDocument(mq)
    assert.isNotFalse(TestUtils.findRenderedDOMComponentWithClass(e, 'parentBox'))
  })

  it('renders with output of callback', function () {
    const mq = (
      <MediaQuery maxWidth={300}>
        {matches =>
}
      </MediaQuery>
    )
    const e = TestUtils.renderIntoDocument(mq)
    assert.isNotFalse(TestUtils.findRenderedDOMComponentWithClass(e, 'no-match'))
  })
  it('calls onChange callback if provided', function () {
    const callback = sinon.spy()
    const mq = (
      <MediaQuery onChange={callback} query="all">

      </MediaQuery>
    )
    const e = TestUtils.renderIntoDocument(mq)
    e.setState({ matches: false })
    assert.isNotFalse(callback.calledOnce)
  })
  it('calls onBeforeChange callback if provided', function () {
    const callback = sinon.spy()
    const mq = (
      <MediaQuery onBeforeChange={callback} query="all">

      </MediaQuery>
    )
    const e = TestUtils.renderIntoDocument(mq)
    e.setState({ matches: false })
    assert.isNotFalse(callback.calledOnce)
  })
  it('calls onChange callback after onBeforeChange if booth are provided', function () {
    const onChangeCallback = sinon.spy()
    const onBeforeChangeCallback = sinon.spy()

    const mq = (
      <MediaQuery
        onChange={onChangeCallback}
        onBeforeChange={onBeforeChangeCallback}
        query="all"
      >

      </MediaQuery>
    )
    const e = TestUtils.renderIntoDocument(mq)
    e.setState({ matches: false })
    assert.isNotFalse(onBeforeChangeCallback.calledBefore(onChangeCallback))
  })
  it('handles unmount', function () {
    const container = document.createElement('div')
    const mq = (
      <MediaQuery query="all">

      </MediaQuery>
    )
    ReactDOM.render(mq, container)
    assert.doesNotThrow(() => ReactDOM.unmountComponentAtNode(container))
  })
})
<|endoftext|>


<commit_before>module.exports = function(apiKey, apiSecret, to, per){
	var limiter = require("simple-rate-limiter"),
		request = require("request"),
		apiUrl = 'https://ssapi.shipstation.com',
		baseRequest = limiter(request.defaults({
			headers: {
				'Accept': 'application/json',
				'Content-Type': 'application/json'
			},
			json:true,
			auth: {
				user: apiKey,
				pass: apiSecret
			}
		})).to(36).per(60);
	if (to) baseRequest.to(to);
	if (per)baseRequest.per(per);
	var deepValue = function (obj, path) {
			for (var i = 0, path = path.split('.'), len = path.length; i < len; i++) {
				obj = obj[path[i]];
			};
			return obj;
		},
		parsingRegex = /{\s*([\w\.]+)\s*}/g,
		apiRequest = function(parameterizedUrl, fn){
			return function(){
				//Handle optional params
				var id = null,
					options = null,
					callback = null,
					args = [].slice.call(arguments);
				args.forEach(function(arg){
					if(typeof arg == 'string' || typeof arg == 'number') id = arg;
					if(typeof arg == 'object') options = arg;
					if(typeof arg == 'function') callback = arg;
				})
				if(id != null){
					if(options != null) options.id = id;
					else options = {id: id};
				}

				//Populate URL
				var url = parameterizedUrl.replace(parsingRegex, function(match, path){
					return deepValue(options, path);
				});

				//Remove ID from options
				if(options != null) delete options.id;

				//Rest of the request
				fn(url, options, callback);
			}
		},
		getMethod = function(parameterizedUrl){
			return new apiRequest(parameterizedUrl, function(url, options, callback){
				api.get(url, options, callback);
			})
		},
		postMethod = function(parameterizedUrl){
			return new apiRequest(parameterizedUrl, function(url, data, callback){
				api.post(url, data, callback);
			})
		},
		putMethod = function(parameterizedUrl){
			return new apiRequest(parameterizedUrl, function(url, data, callback){
				api.put(url, data, callback);
			})
		},
		deleteMethod = function(parameterizedUrl){
			return new apiRequest(parameterizedUrl, function(url, options, callback){
				api.del(url, options, callback);
			})
		},
		merge = function(target, source) {
		    if ( typeof target !== 'object' ) target = {};
		    for (var property in source) {
		        if ( source.hasOwnProperty(property) ) {
		            var sourceProperty = source[ property ];
		            if ( typeof sourceProperty === 'object' ) {
		                target[ property ] = merge( target[ property ], sourceProperty );
		                continue;
		            }
		            target[ property ] = sourceProperty;
		        }
		    }

		    for (var a = 2, l = arguments.length; a < l; a++) merge(target, arguments[a]);

		    return target;
		};

	var api = {
		get: function(link, options, callback){
			baseRequest({
				method: "GET",
				url: apiUrl + link,
				qs: options
			}, callback);
		},
		post: function(link, data, callback){
			baseRequest({
				method: "POST",
				url: apiUrl + link,
				json: data
			}, callback);
		},
		put: function(link, data, callback){
			baseRequest({
				method: "PUT"
				url: apiUrl + link,
				json: data
			}, callback);
		},
		del: function(link, options, callback){
			baseRequest({
				method: "DELETE",
				url: apiUrl + link,
				qs: options
			}, callback);
		},
		addAccount: '/accounts/registeraccount', // http://www.shipstation.com/developer-api/#/reference/accounts/register-account/register-account
		getTags: '/accounts/listtags',
		getCarriers: '/carriers',
		getCarrier: '/carriers/getcarrier?carrierCode={id}',
		addFunds: '/carriers/addfunds', //{carrierCode, amount}
		getPackages: '/carriers/listpackages?carrierCode={id}',
		getServices: '/carriers/listservices?carrierCode={id}',
		carrier: function(id){
			var carrier = {
				addFunds: function(amount, callback){
					api.addFunds({carrierCode: id, amount: amount}, callback);
					return carrier;
				},
				packages: function(callback){
					api.getPackages({id:id},callback);
				},
				services: function(callback){
					api.getServices({id:id},callback);
				}
			}
			return carrier;
		},

		getCustomers: '/customers',
		getCustomer: '/customers/{id}',

		getOrders: '/orders', // options http://www.shipstation.com/developer-api/#/reference/orders/orders/post
		getOrdersByTag: '/orders/listbytag', // requires {orderStatus, tagId}
		getOrder: '/orders/{id}',
		addOrder: '/orders/createorder', // http://www.shipstation.com/developer-api/#/reference/orders/orderscreateorder/get-order
		updateOrder: function(id, changes, callback){ // A combination of get and create...
			api.getOrder(id, function(err, res, body){
				if(err) throw err;
				merge(body, changes);
				api.addOrder(body, callback);
			});
		},
		deleteOrder: '/orders/{id}',
		setOrderHold: '/orders/holduntil', //{orderId, holdUntilDate}
		setLabelForOrder: '/orders/createlabelfororder', // http://www.shipstation.com/developer-api/#/reference/orders/orderscreatelabelfororder/post
		setOrderShipped: '/orders/markasshipped', // {orderId*, carrierCode*, shipDate, trackingNumber, notifyCustomer, notifySalesChannel}
		addTagToOrder: '/orders/addtag', //{orderId, tagId}
		removeTagFromOrder: new postMethod('/orders/removetag'), //{orderId, tagId}
		order: function(id){
			var order = {
				get: function(callback){
					api.getOrder(id, callback);
					return order;
				},
				delete: function(callback){
					api.deleteOrder(id, callback);
					return order;
				},
				update: function(changes, callback){
					api.updateOrder(id, changes, callback);
					return order;
				},
				hold: function(date, callback){
					if(typeof date == 'object') date = date.ToISOString();
					api.setOrderHold({orderId: id, holdUntilDate: date}, callback);
					return order;
				},
				addTag: function(tagId, callback){
					api.addTagToOrder({orderId: id, tagId: tagId}, callback);
					return order;
				},
				removeTag: function(tagId, callback){
					api.removeTagFromOrder({orderId: id, tagId: tagId}, callback);
					return order;
				},
				shipped: function(data, callback){
					data.orderId = id;
					api.setOrderShipped(data, callback);
					return order;
				},
				label: function(data, callback){
					data.orderId = id;
					api.setLabelForOrder(data, callback);
					return order;
				}
			}

			return order;
		},

		getProducts: '/products',
		getProduct: '/products/{id}/',

		getShipments: '/shipments',
		addShippingLabel: '/shipments/createlabel', // http://www.shipstation.com/developer-api/#/reference/shipments/shipmentscreatelabel/post
		getShippingRates: new postMethod('/shipments/getrates'), // http://www.shipstation.com/developer-api/#/reference/shipments/shipmentsgetrates/post
		voidShippingLabel: function(id, callback){
			api.post('/shipments/voidlabel', {shipmentId: id}, callback);
		},

		getStores: '/stores',
		getStore: '/stores/{id}',
		updateStore: '/stores/{id}', // http://www.shipstation.com/developer-api/#/reference/stores/store/update-store
		getStoreRefreshStatus: '/stores/getrefreshstatus?storeId={id}',
		refreshStore: function(id, callback){
			if(typeof id == 'function'){
				callback = id;
				id = null;
			}
			api.get('/stores/refreshstore', id != null? {storeId: id} : {}, callback);
		},
		deactivateStore: function(id, callback){
			api.post('/stores/deactivate', {storeId: id}, callback);
		},
		reactivateStore: function(id, callback){
			api.post('/stores/reactivate', {storeId: id}, callback);
		},
		getMarketplaces: '/stores/marketplaces',
		store: function(id){
			var store = {
				update: function(data, callback){
					data.id = id;
					api.updateStore(data, callback);
					return store;
				},
				status: function(callback){
					api.getStoreRefreshStatus(id, callback);
					return store;
				},
				refresh: function(callback){
					api.refreshStore(id, callback);
					return store;
				},
				deactivate: function(callback){
					api.deactivateStore(id, callback);
					return store;
				},
				reactivate: function(callback){
					api.reactivateStore(id, callback);
					return store;
				},
			}
			return store;
		},

		getWarehouses: '/warehouses',
		getWarehouse: '/warehouses/{id}',
		updateWarehouse: '/warehouses/{id}', // http://www.shipstation.com/developer-api/#/reference/warehouses/warehouse/update-warehouse
		addWarehouse: '/warehouses/createwarehouse', // http://www.shipstation.com/developer-api/#/reference/warehouses/warehousescreatewarehouse
	};

	//Build default methods
	for(method in api){
		if(typeof api[method] == 'function') continue;

		var url = api[method];
		if(method.indexOf('get') == 0) api[method] = new getMethod(url);
		if(method.indexOf('add') == 0 || method.indexOf('set') == 0) api[method] = new postMethod(url);
		if(method.indexOf('update') == 0) api[method] = new putMethod(url);
		if(method.indexOf('delete') == 0) api[method] = new deleteMethod(url);
	}

	return api;
}
<commit_msg>Darn comma<commit_after>module.exports = function(apiKey, apiSecret, to, per){
	var limiter = require("simple-rate-limiter"),
		request = require("request"),
		apiUrl = 'https://ssapi.shipstation.com',
		baseRequest = limiter(request.defaults({
			headers: {
				'Accept': 'application/json',
				'Content-Type': 'application/json'
			},
			json:true,
			auth: {
				user: apiKey,
				pass: apiSecret
			}
		})).to(36).per(60);
	if (to) baseRequest.to(to);
	if (per)baseRequest.per(per);
	var deepValue = function (obj, path) {
			for (var i = 0, path = path.split('.'), len = path.length; i < len; i++) {
				obj = obj[path[i]];
			};
			return obj;
		},
		parsingRegex = /{\s*([\w\.]+)\s*}/g,
		apiRequest = function(parameterizedUrl, fn){
			return function(){
				//Handle optional params
				var id = null,
					options = null,
					callback = null,
					args = [].slice.call(arguments);
				args.forEach(function(arg){
					if(typeof arg == 'string' || typeof arg == 'number') id = arg;
					if(typeof arg == 'object') options = arg;
					if(typeof arg == 'function') callback = arg;
				})
				if(id != null){
					if(options != null) options.id = id;
					else options = {id: id};
				}

				//Populate URL
				var url = parameterizedUrl.replace(parsingRegex, function(match, path){
					return deepValue(options, path);
				});

				//Remove ID from options
				if(options != null) delete options.id;

				//Rest of the request
				fn(url, options, callback);
			}
		},
		getMethod = function(parameterizedUrl){
			return new apiRequest(parameterizedUrl, function(url, options, callback){
				api.get(url, options, callback);
			})
		},
		postMethod = function(parameterizedUrl){
			return new apiRequest(parameterizedUrl, function(url, data, callback){
				api.post(url, data, callback);
			})
		},
		putMethod = function(parameterizedUrl){
			return new apiRequest(parameterizedUrl, function(url, data, callback){
				api.put(url, data, callback);
			})
		},
		deleteMethod = function(parameterizedUrl){
			return new apiRequest(parameterizedUrl, function(url, options, callback){
				api.del(url, options, callback);
			})
		},
		merge = function(target, source) {
		    if ( typeof target !== 'object' ) target = {};
		    for (var property in source) {
		        if ( source.hasOwnProperty(property) ) {
		            var sourceProperty = source[ property ];
		            if ( typeof sourceProperty === 'object' ) {
		                target[ property ] = merge( target[ property ], sourceProperty );
		                continue;
		            }
		            target[ property ] = sourceProperty;
		        }
		    }

		    for (var a = 2, l = arguments.length; a < l; a++) merge(target, arguments[a]);

		    return target;
		};

	var api = {
		get: function(link, options, callback){
			baseRequest({
				method: "GET",
				url: apiUrl + link,
				qs: options
			}, callback);
		},
		post: function(link, data, callback){
			baseRequest({
				method: "POST",
				url: apiUrl + link,
				json: data
			}, callback);
		},
		put: function(link, data, callback){
			baseRequest({
				method: "PUT",
				url: apiUrl + link,
				json: data
			}, callback);
		},
		del: function(link, options, callback){
			baseRequest({
				method: "DELETE",
				url: apiUrl + link,
				qs: options
			}, callback);
		},
		addAccount: '/accounts/registeraccount', // http://www.shipstation.com/developer-api/#/reference/accounts/register-account/register-account
		getTags: '/accounts/listtags',
		getCarriers: '/carriers',
		getCarrier: '/carriers/getcarrier?carrierCode={id}',
		addFunds: '/carriers/addfunds', //{carrierCode, amount}
		getPackages: '/carriers/listpackages?carrierCode={id}',
		getServices: '/carriers/listservices?carrierCode={id}',
		carrier: function(id){
			var carrier = {
				addFunds: function(amount, callback){
					api.addFunds({carrierCode: id, amount: amount}, callback);
					return carrier;
				},
				packages: function(callback){
					api.getPackages({id:id},callback);
				},
				services: function(callback){
					api.getServices({id:id},callback);
				}
			}
			return carrier;
		},

		getCustomers: '/customers',
		getCustomer: '/customers/{id}',

		getOrders: '/orders', // options http://www.shipstation.com/developer-api/#/reference/orders/orders/post
		getOrdersByTag: '/orders/listbytag', // requires {orderStatus, tagId}
		getOrder: '/orders/{id}',
		addOrder: '/orders/createorder', // http://www.shipstation.com/developer-api/#/reference/orders/orderscreateorder/get-order
		updateOrder: function(id, changes, callback){ // A combination of get and create...
			api.getOrder(id, function(err, res, body){
				if(err) throw err;
				merge(body, changes);
				api.addOrder(body, callback);
			});
		},
		deleteOrder: '/orders/{id}',
		setOrderHold: '/orders/holduntil', //{orderId, holdUntilDate}
		setLabelForOrder: '/orders/createlabelfororder', // http://www.shipstation.com/developer-api/#/reference/orders/orderscreatelabelfororder/post
		setOrderShipped: '/orders/markasshipped', // {orderId*, carrierCode*, shipDate, trackingNumber, notifyCustomer, notifySalesChannel}
		addTagToOrder: '/orders/addtag', //{orderId, tagId}
		removeTagFromOrder: new postMethod('/orders/removetag'), //{orderId, tagId}
		order: function(id){
			var order = {
				get: function(callback){
					api.getOrder(id, callback);
					return order;
				},
				delete: function(callback){
					api.deleteOrder(id, callback);
					return order;
				},
				update: function(changes, callback){
					api.updateOrder(id, changes, callback);
					return order;
				},
				hold: function(date, callback){
					if(typeof date == 'object') date = date.ToISOString();
					api.setOrderHold({orderId: id, holdUntilDate: date}, callback);
					return order;
				},
				addTag: function(tagId, callback){
					api.addTagToOrder({orderId: id, tagId: tagId}, callback);
					return order;
				},
				removeTag: function(tagId, callback){
					api.removeTagFromOrder({orderId: id, tagId: tagId}, callback);
					return order;
				},
				shipped: function(data, callback){
					data.orderId = id;
					api.setOrderShipped(data, callback);
					return order;
				},
				label: function(data, callback){
					data.orderId = id;
					api.setLabelForOrder(data, callback);
					return order;
				}
			}

			return order;
		},

		getProducts: '/products',
		getProduct: '/products/{id}/',

		getShipments: '/shipments',
		addShippingLabel: '/shipments/createlabel', // http://www.shipstation.com/developer-api/#/reference/shipments/shipmentscreatelabel/post
		getShippingRates: new postMethod('/shipments/getrates'), // http://www.shipstation.com/developer-api/#/reference/shipments/shipmentsgetrates/post
		voidShippingLabel: function(id, callback){
			api.post('/shipments/voidlabel', {shipmentId: id}, callback);
		},

		getStores: '/stores',
		getStore: '/stores/{id}',
		updateStore: '/stores/{id}', // http://www.shipstation.com/developer-api/#/reference/stores/store/update-store
		getStoreRefreshStatus: '/stores/getrefreshstatus?storeId={id}',
		refreshStore: function(id, callback){
			if(typeof id == 'function'){
				callback = id;
				id = null;
			}
			api.get('/stores/refreshstore', id != null? {storeId: id} : {}, callback);
		},
		deactivateStore: function(id, callback){
			api.post('/stores/deactivate', {storeId: id}, callback);
		},
		reactivateStore: function(id, callback){
			api.post('/stores/reactivate', {storeId: id}, callback);
		},
		getMarketplaces: '/stores/marketplaces',
		store: function(id){
			var store = {
				update: function(data, callback){
					data.id = id;
					api.updateStore(data, callback);
					return store;
				},
				status: function(callback){
					api.getStoreRefreshStatus(id, callback);
					return store;
				},
				refresh: function(callback){
					api.refreshStore(id, callback);
					return store;
				},
				deactivate: function(callback){
					api.deactivateStore(id, callback);
					return store;
				},
				reactivate: function(callback){
					api.reactivateStore(id, callback);
					return store;
				},
			}
			return store;
		},

		getWarehouses: '/warehouses',
		getWarehouse: '/warehouses/{id}',
		updateWarehouse: '/warehouses/{id}', // http://www.shipstation.com/developer-api/#/reference/warehouses/warehouse/update-warehouse
		addWarehouse: '/warehouses/createwarehouse', // http://www.shipstation.com/developer-api/#/reference/warehouses/warehousescreatewarehouse
	};

	//Build default methods
	for(method in api){
		if(typeof api[method] == 'function') continue;

		var url = api[method];
		if(method.indexOf('get') == 0) api[method] = new getMethod(url);
		if(method.indexOf('add') == 0 || method.indexOf('set') == 0) api[method] = new postMethod(url);
		if(method.indexOf('update') == 0) api[method] = new putMethod(url);
		if(method.indexOf('delete') == 0) api[method] = new deleteMethod(url);
	}

	return api;
}
<|endoftext|>


<commit_before>(function(){

	var button = document.getElementById('cn-button'),
    wrapper = document.getElementById('cn-wrapper'),
    overlay = document.getElementById('cn-overlay');

	//open and close menu when the button is clicked
	var open = false;
	button.addEventListener('click', handler, false);
	wrapper.addEventListener('click', cnhandle, false);

	function cnhandle(e){
		e.stopPropagation();
	}

	function handler(e){
		if (!e) var e = window.event;
	 	e.stopPropagation();//so that it doesn't trigger click event on document

	  	if(!open){
	    	openNav();
	  	}
	 	else{
	    	closeNav();
	  	}
	}
	function openNav(){
		open = true;
	    button.innerHTML = "";
	    classie.add(overlay, 'on-overlay');
	    classie.add(wrapper, 'opened-nav');
	}
	function closeNav(){
		open = false;
		button.innerHTML = "";
		classie.remove(overlay, 'on-overlay');
		classie.remove(wrapper, 'opened-nav');
	}
	document.addEventListener('click', closeNav);

})();

<commit_msg>Update demo1.js<commit_after>(function(){

	var button = document.getElementById('cn-button'),
    wrapper = document.getElementById('cn-wrapper'),
    overlay = document.getElementById('cn-overlay');

	//open and close menu when the button is clicked
	var open = false;
	button.addEventListener('click', handler, false);
	wrapper.addEventListener('click', cnhandle, false);

	function cnhandle(e){
		e.stopPropagation();
	}

	function handler(e){
		if (!e) var e = window.event;
	 	e.stopPropagation();//so that it doesn't trigger click event on document

	  	if(!open){
	    	openNav();
	  	}
	 	else{
	    	closeNav();
	  	}
	}
	function openNav(){
		open = true;
	    button.innerHTML = "";
	    classie.add(overlay, 'on-overlay');
	    classie.add(wrapper, 'opened-nav');
	}
	function closeNav(){
		open = false;
		button.innerHTML = "";
		classie.remove(overlay, 'on-overlay');
		classie.remove(wrapper, 'opened-nav');
	}
	document.addEventListener('click', closeNav);

})();

<|endoftext|>


<commit_before>import update from 'immutability-helper'

// TODO: port user-specific code from the otp reducer.
function createUserReducer () {
  const initialState = {}

  return (state = initialState, action) => {
    switch (action.type) {
      case 'SET_CURRENT_USER': {
        return update(state, {
          accessToken: { $set: action.payload.accessToken },
          loggedInUser: { $set: action.payload.user }
        })
      }

      case 'SET_CURRENT_USER_MONITORED_TRIPS': {
        return update(state, {
          loggedInUserMonitoredTrips: { $set: action.payload }
        })
      }

      case 'SET_PATH_BEFORE_SIGNIN': {
        return update(state, {
          pathBeforeSignIn: { $set: action.payload }
        })
      }

      default:
        return state
    }
  }
}

export default createUserReducer
<commit_msg>refactor(createUserReducer): Add initial user redux state.<commit_after>import update from 'immutability-helper'

// TODO: port user-specific code from the otp reducer.
function createUserReducer () {
  const initialState = {
    accessToken: null,
    loggedInUser: null,
    loggedInUserMonitoredTrips: null,
    pathBeforeSignIn: null
  }

  return (state = initialState, action) => {
    switch (action.type) {
      case 'SET_CURRENT_USER': {
        return update(state, {
          accessToken: { $set: action.payload.accessToken },
          loggedInUser: { $set: action.payload.user }
        })
      }

      case 'SET_CURRENT_USER_MONITORED_TRIPS': {
        return update(state, {
          loggedInUserMonitoredTrips: { $set: action.payload }
        })
      }

      case 'SET_PATH_BEFORE_SIGNIN': {
        return update(state, {
          pathBeforeSignIn: { $set: action.payload }
        })
      }

      default:
        return state
    }
  }
}

export default createUserReducer
<|endoftext|>


<commit_before>/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2018 New Vector Ltd

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.
*/
import React from 'react';
import PropTypes from 'prop-types';
import MatrixClientPeg from '../../../MatrixClientPeg';
import dis from '../../../dispatcher';
import { _t } from '../../../languageHandler';

module.exports = React.createClass({
    displayName: 'IncomingCallBox',

    propTypes: {
        incomingCall: PropTypes.object,
    },

    onAnswerClick: function(e) {
        e.stopPropagation();
        dis.dispatch({
            action: 'answer',
            room_id: this.props.incomingCall.roomId,
        });
    },

    onRejectClick: function(e) {
        e.stopPropagation();
        dis.dispatch({
            action: 'hangup',
            room_id: this.props.incomingCall.roomId,
        });
    },

    render: function() {
        let room = null;
        if (this.props.incomingCall) {
            room = MatrixClientPeg.get().getRoom(this.props.incomingCall.roomId);
        }

        const caller = room ? room.name : _t("unknown caller");

        let incomingCallText = null;
        if (this.props.incomingCall) {
            if (this.props.incomingCall.type === "voice") {
                incomingCallText = _t("Incoming voice call from %(name)s", {name: caller});
            } else if (this.props.incomingCall.type === "video") {
                incomingCallText = _t("Incoming video call from %(name)s", {name: caller});
            } else {
                incomingCallText = _t("Incoming call from %(name)s", {name: caller});
            }
        }

        const AccessibleButton = sdk.getComponent('elements.AccessibleButton');
        return (

                    { incomingCallText }

                        <AccessibleButton className="mx_IncomingCallBox_buttons_decline" onClick={this.onRejectClick}>
                            { _t("Decline") }
                        </AccessibleButton>

                        <AccessibleButton className="mx_IncomingCallBox_buttons_accept" onClick={this.onAnswerClick}>
                            { _t("Accept") }
                        </AccessibleButton>

        );
    },
});

<commit_msg>import sdk<commit_after>/*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2018 New Vector Ltd

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.
*/
import React from 'react';
import PropTypes from 'prop-types';
import MatrixClientPeg from '../../../MatrixClientPeg';
import dis from '../../../dispatcher';
import { _t } from '../../../languageHandler';
import sdk from '../../../index'

module.exports = React.createClass({
    displayName: 'IncomingCallBox',

    propTypes: {
        incomingCall: PropTypes.object,
    },

    onAnswerClick: function(e) {
        e.stopPropagation();
        dis.dispatch({
            action: 'answer',
            room_id: this.props.incomingCall.roomId,
        });
    },

    onRejectClick: function(e) {
        e.stopPropagation();
        dis.dispatch({
            action: 'hangup',
            room_id: this.props.incomingCall.roomId,
        });
    },

    render: function() {
        let room = null;
        if (this.props.incomingCall) {
            room = MatrixClientPeg.get().getRoom(this.props.incomingCall.roomId);
        }

        const caller = room ? room.name : _t("unknown caller");

        let incomingCallText = null;
        if (this.props.incomingCall) {
            if (this.props.incomingCall.type === "voice") {
                incomingCallText = _t("Incoming voice call from %(name)s", {name: caller});
            } else if (this.props.incomingCall.type === "video") {
                incomingCallText = _t("Incoming video call from %(name)s", {name: caller});
            } else {
                incomingCallText = _t("Incoming call from %(name)s", {name: caller});
            }
        }

        const AccessibleButton = sdk.getComponent('elements.AccessibleButton');
        return (

                    { incomingCallText }

                        <AccessibleButton className="mx_IncomingCallBox_buttons_decline" onClick={this.onRejectClick}>
                            { _t("Decline") }
                        </AccessibleButton>

                        <AccessibleButton className="mx_IncomingCallBox_buttons_accept" onClick={this.onAnswerClick}>
                            { _t("Accept") }
                        </AccessibleButton>

        );
    },
});

<|endoftext|>


<commit_before>/**
 * Eve.js <evejs.com> - Version: 0.6 (September 16, 2012)
 *
 *	   A JavaScript meta-framework for scoped event delegation.
 *
 * Copyright (c) 2012 Michelle Steigerwalt, http://evejs.com/
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
(function() {

var _registry = {}, _scopes = {}, _attachments = {}, _extensions = {},
    _debugging = [], _debugAll = false;

function dbug(name, message) {
		if (!window.console) { return; }
		var debug = _debugAll;
		if (!_debugAll) {
			debug = false;
			for (var i = 0; i<_debugging.length; i++) {
				if (_debugging[i]==name) debug = true;
			}
		}
		if (!debug) { return; }
		while (name.length<10) { name=name+' '; }
		name = name.substring(0, 10)+" - ";
		console.info(name, message);
};

function bindToScope(fun, obj, reg, name) {

	for (var k in Scope) obj[k] = Scope[k];
	for (var k in _extensions) obj[k] = _extensions[k];

	if (window.YUI) {
		YUI().use('node', function(Y) {
			Eve.dom  = Y.one;
			reg[name] = fun.apply(obj);
		});
	} else if (window.dojo) {
		require(["dojo/NodeList-dom", "dojo/NodeList-traverse"], function(dom){
			Eve.dom  = dom;
			reg[name] = fun.apply(obj);
		});
	} else {
		reg[name] = fun.apply(obj);
	}

};

//The primary Eve API.
window.Eve = {

	debug: function(moduleName) {
		if (moduleName) {
			_debugging.push(moduleName);
		} else {
			_debugAll = true;
		}
	},

	register: function(name, obj) {
		dbug(name, "registered");
		if (_registry[name]) {
			throw new Error("Module already exists: "+name);
		}
		_registry[name] = obj;
		return this;
	},

	extend: function(key, fun) {
		_extensions[key] = fun;
	},

	scope: function(ns, fun) {
		if (_scopes[ns]) {
			console.warn("Duplicate namespace: "+ns);
		}
		bindToScope(fun, {
			name: ns,
			namespace: ns
		}, _scopes, ns);
	},

	attach: function(moduleName, namespace) {
		dbug(moduleName, "attached to "+namespace);
		//We're delegating off the window, so there's no need to reattach for
		//multiple instances of a single given module.
		if (_attachments[moduleName+namespace]) {
			return false;
		}
		if (!_registry[moduleName]) {
			console.warn("Module not found: "+moduleName);
			return false;
		}
		var mod = bindToScope(_registry[moduleName], {
			namespace:namespace,
			name:moduleName
		}, _attachments, moduleName+namespace);
		return true;
	}

};

var Scope = {

	listen: function(selector, event, handler) {

		//There's a special hell for putting optional parameters at the
		//beginning.  A special and awesome hell.
		if (!handler) {
			handler = event;
			event = selector;
			selector = '';
		}
		selector = selector || '';

		//If listen is happening in the context of a triggered event handler,
		//we only want to delegate to the current event namespace.
		var scope = (this.event) ? this.find() : document.body;

		var name = this.name,
			sel	 = (this.namespace+' '+selector).trim(),
			obj  = { };
			for (k in this) if (this.hasOwnProperty(k))	obj[k] = this[k];
			function fun(e,t) {
				dbug(name, sel+':'+event);
				obj.event = e;
				if (window.MooTools) { e.target = t; }
				if (window.jQuery)   { e.target = e.currentTarget; }
				handler.apply(obj, arguments);
			};

		//JavaScript framework development is so much easier when you let some
		//other framework do most of the work.
		if (window.jQuery) {
			$(scope).delegate(sel, event, fun);
		} else if (window.MooTools) {
			//I really hate the MooTools event delegation syntax.
			$(scope).addEvent(event+':relay('+sel+')', fun);
		} else if (window.YUI) {
			Eve.dom(scope).delegate(event, fun, sel);
		} else if (window.Prototype) {
			$(scope).on(event, sel, fun);
		} else if (window.dojo) {
			require(["dojo/on"], function(on){
				on(scope, sel+':'+event, fun);
			});
		} else {
			console.error("Eve doesn't support your JavaScript framework.");
		}

	},

	//Yo dawg...
	scope: function(ns, fun) {
		Eve.scope(this.namespace+' '+ns, fun);
	},

	//This method is bound to the namespaced closure.
	attach: function(moduleName, ns) {
		Eve.attach(moduleName, this.namespace+' '+(ns||''));
	},

	find: function(sel) {
		var scope;
		if (!sel || typeof(sel)=='string') { sel = (sel || '').trim(); }
		//Scope to the particular instance of the DOM module active in this
		//event.
		if (this.event) {
			var t = (window.$) ? $(this.event.target) : this.event.target;
			var map = {
				jQuery: ['is', 'parents', 'find'],
				MooTools: ['match', 'getParent', 'getElements'],
				Prototype: ['match', 'up', 'select'],
				YUI: ['test', 'ancestor', 'all']
			};
			for (var fw in map) {
				if (!window[fw]) continue;
				var m = map[fw], match = m[0], up = m[1], all = m[2];
				if (t[match](this.namespace)) return t;
				scope = t[up](this.namespace);
				return (sel) ? scope[all](sel) : scope;
			}
			if (window.dojo) {
				//Dojo returns the current node if it matches the selector.
				scope = Eve.dom(t).closest(this.namespace);
				return (sel) ? scope.query(sel) : scope;
			}
		//Scope to the DOM namespace across all instances.
		} else {
			sel = this.namespace+' '+sel;
			if (window.jQuery||window.Prototype) {
				return $(sel);
			} else if (window.MooTools) {
				return $$(sel);
			}
		}
	}

};

})();<commit_msg>Eve.setFramework method to allow the user to specify which framework to use in the event of multiple frameworks attached to the window element.  Eve.js will also be consistent in which framework it decides to use by caching the framework result on detection.<commit_after>/**
 * Eve.js <evejs.com> - Version: 0.6 (September 16, 2012)
 *
 *	   A JavaScript meta-framework for scoped event delegation.
 *
 * Copyright (c) 2012 Michelle Steigerwalt, http://evejs.com/
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
(function() {

var _registry = {}, _scopes = {}, _attachments = {}, _extensions = {},
    _debugging = [], _debugAll = false, _framework;

//Detects the current JavaScript framework.
function detectFramework() {

	if (_framework) return _framework;

	var fws = ['jQuery', 'MooTools', 'YUI', 'Prototype', 'dojo'];
	for (var i = 0; i<= fws.length; i++) {
		if (window[fws[i]]) {
			Eve.setFramework(fws[i]);
			return fws[i];
		}
	} console.error("Eve doesn't support your JavaScript framework.");

};

//Either matches the chosen JS framework to the passed guess, or returns the
//current framework.
function using(guess) {
	var fw = _framework || detectFramework();
	return (guess) ? (_framework == guess.toLowerCase()) : _framework;
};

function dbug(name, message) {
		if (!window.console) { return; }
		var debug = _debugAll;
		if (!_debugAll) {
			debug = false;
			for (var i = 0; i<_debugging.length; i++) {
				if (_debugging[i]==name) debug = true;
			}
		}
		if (!debug) { return; }
		while (name.length<10) { name=name+' '; }
		name = name.substring(0, 10)+" - ";
		console.info(name, message);
};

function bindToScope(fun, obj, reg, name) {

	for (var k in Scope) obj[k] = Scope[k];
	for (var k in _extensions) obj[k] = _extensions[k];

	if (using("YUI")) {
		YUI().use('node', function(Y) {
			Eve.dom  = Y.one;
			reg[name] = fun.apply(obj);
		});
	} else if (using("dojo")) {
		require(["dojo/NodeList-dom", "dojo/NodeList-traverse"], function(dom){
			Eve.dom  = dom;
			reg[name] = fun.apply(obj);
		});
	} else {
		reg[name] = fun.apply(obj);
	}

};

//The primary Eve API.
window.Eve = {

	setFramework: function(fw) {
		_framework = (fw+"").toLowerCase();
		if (_framework=='jquery') $ = jQuery; //No-conflict compat.
	},

	debug: function(moduleName) {
		if (moduleName) {
			_debugging.push(moduleName);
		} else {
			_debugAll = true;
		}
	},

	register: function(name, obj) {
		dbug(name, "registered");
		if (_registry[name]) {
			throw new Error("Module already exists: "+name);
		}
		_registry[name] = obj;
		return this;
	},

	extend: function(key, fun) {
		_extensions[key] = fun;
	},

	scope: function(ns, fun) {
		if (_scopes[ns]) {
			console.warn("Duplicate namespace: "+ns);
		}
		bindToScope(fun, {
			name: ns,
			namespace: ns
		}, _scopes, ns);
	},

	attach: function(moduleName, namespace) {
		dbug(moduleName, "attached to "+namespace);
		//We're delegating off the window, so there's no need to reattach for
		//multiple instances of a single given module.
		if (_attachments[moduleName+namespace]) {
			return false;
		}
		if (!_registry[moduleName]) {
			console.warn("Module not found: "+moduleName);
			return false;
		}
		var mod = bindToScope(_registry[moduleName], {
			namespace:namespace,
			name:moduleName
		}, _attachments, moduleName+namespace);
		return true;
	}

};

var Scope = {

	listen: function(selector, event, handler) {

		//There's a special hell for putting optional parameters at the
		//beginning.  A special and awesome hell.
		if (!handler) {
			handler = event;
			event = selector;
			selector = '';
		}
		selector = selector || '';

		//If listen is happening in the context of a triggered event handler,
		//we only want to delegate to the current event namespace.
		var scope = (this.event) ? this.find() : document.body;

		var name = this.name,
			sel	 = (this.namespace+' '+selector).trim(),
			obj  = { };
			for (k in this) if (this.hasOwnProperty(k))	obj[k] = this[k];
			function fun(e,t) {
				dbug(name, sel+':'+event);
				obj.event = e;
				if (using("MooTools")) { e.target = t; }
				if (using("jQuery"))   { e.target = e.currentTarget; }
				if (using("dojo"))     { e.target = e.explicitOriginalTarget; }
				handler.apply(obj, arguments);
			};

		//JavaScript framework development is so much easier when you let some
		//other framework do most of the work.
		if (using("jQuery")) {
			$(scope).delegate(sel, event, fun);
		} else if (using('MooTools')) {
			//I really hate the MooTools event delegation syntax.
			$(scope).addEvent(event+':relay('+sel+')', fun);
		} else if (using("YUI")) {
			Eve.dom(scope).delegate(event, fun, sel);
		} else if (using("Prototype")) {
			$(scope).on(event, sel, fun);
		} else if (using("dojo")) {
			require(["dojo/on"], function(on){
				on(scope, sel+':'+event, fun);
			});
		}

	},

	//Yo dawg...
	scope: function(ns, fun) {
		Eve.scope(this.namespace+' '+ns, fun);
	},

	//This method is bound to the namespaced closure.
	attach: function(moduleName, ns) {
		Eve.attach(moduleName, this.namespace+' '+(ns||''));
	},

	find: function(sel) {
		var scope;
		if (!sel || typeof(sel)=='string') { sel = (sel || '').trim(); }
		//Scope to the particular instance of the DOM module active in this
		//event.
		if (this.event) {
			var t = this.event.target;
			if (using('jQuery')) t = jQuery(t);
			var map = {
				jQuery: ['is', 'parents', 'find'],
				MooTools: ['match', 'getParent', 'getElements'],
				Prototype: ['match', 'up', 'select'],
				YUI: ['test', 'ancestor', 'all']
			};
			for (var fw in map) {
				if (!using(fw)) continue;
				var m = map[fw], match = m[0], up = m[1], all = m[2];
				if (t[match](this.namespace)) return t;
				scope = t[up](this.namespace);
				return (sel) ? scope[all](sel) : scope;
			}
			if (using('dojo')) {
				//Dojo returns the current node if it matches the selector.
				scope = Eve.dom(t).closest(this.namespace);
				return (sel) ? scope.query(sel) : scope;
			}
		//Scope to the DOM namespace across all instances.
		} else {
			sel = this.namespace+' '+sel;
			if (using('jQuery')||using('Prototype')) {
				return $(sel);
			} else if (using('MooTools')) {
				return $$(sel);
			}
		}
	}

};

})();<|endoftext|>


<commit_before>module.exports = function(config){
  var configuration = {

    basePath : '../',

    files : [
      'bower_components/angular/angular.js',
      'bower_components/angular-route/angular-route.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'bower_components/angular-smart-table/dist/smart-table.min.js',
      'app/js/**/*.js',
      'test/unit/**/*.js',

      // fixtures
      {pattern: 'test/fixtures/**/*.json', watched: true, served: true, included: false}
    ],

    autoWatch : true,

    frameworks: ['jasmine'],

    plugins : [
            'karma-chrome-launcher',
            'karma-jasmine'
            ],

    junitReporter : {
      outputFile: 'test_out/unit.xml',
      suite: 'unit'
    }
    // start these browsers
    browsers: ['Chrome', 'ChromeCanary'],

    customLaunchers: {
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },

  };

  if(process.env.TRAVIS){
    configuration.browsers = ['Chrome_travis_ci'];
  }

  config.set(configuration);
};<commit_msg>Syntax error in Karma conf<commit_after>module.exports = function(config){
  var configuration = {

    basePath : '../',

    files : [
      'bower_components/angular/angular.js',
      'bower_components/angular-route/angular-route.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'bower_components/angular-smart-table/dist/smart-table.min.js',
      'app/js/**/*.js',
      'test/unit/**/*.js',

      // fixtures
      {pattern: 'test/fixtures/**/*.json', watched: true, served: true, included: false}
    ],

    autoWatch : true,

    frameworks: ['jasmine'],

    plugins : [
            'karma-chrome-launcher',
            'karma-jasmine'
            ],

    junitReporter : {
      outputFile: 'test_out/unit.xml',
      suite: 'unit'
    },

    // start these browsers
    browsers: ['Chrome', 'ChromeCanary'],

    customLaunchers: {
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    }

  };

  if(process.env.TRAVIS){
    configuration.browsers = ['Chrome_travis_ci'];
  }

  config.set(configuration);
};<|endoftext|>


<commit_before>import {
  hiddenFromAT
, listensTo
, devices
} from '../util'

export default ctx => function (tagName, props, children) {
  const hidden   = hiddenFromAT(props)
  const disabled = props.ariaDisabled === true
  const readOnly = props.ariaReadonly === true
  const onChange = listensTo(props, 'onChange')

  if ( !(hidden || disabled || readOnly)&& onChange ) {
    ctx.report({
      msg: '`onBlur` should be preferred over `onChange`, unless absolutely necessary '
         + 'and it has no negative consequences for keyboard only or screen-reader users.'
    , url: 'http://webaim.org/techniques/javascript/eventhandlers#onchange'
    , affects: [
        devices.keyboardOnly
      , devices.screenReaders
      ]
    })
  }
}
<commit_msg>use trueish<commit_after>import {
  hiddenFromAT
, listensTo
, devices
, trueish
} from '../util'

export default ctx => function (tagName, props, children) {
  const hidden   = hiddenFromAT(props)
  const disabled = trueish(props, 'ariaDisabled')
  const readOnly = trueish(props, 'ariaReadonly')
  const onChange = listensTo(props, 'onChange')

  if ( !(hidden || disabled || readOnly)&& onChange ) {
    ctx.report({
      msg: '`onBlur` should be preferred over `onChange`, unless absolutely necessary '
         + 'and it has no negative consequences for keyboard only or screen-reader users.'
    , url: 'http://webaim.org/techniques/javascript/eventhandlers#onchange'
    , affects: [
        devices.keyboardOnly
      , devices.screenReaders
      ]
    })
  }
}
<|endoftext|>


<commit_before>/**
 * 2k v 1.1 2011-09-03
 * http://aino.com
 *
 * Copyright (c) 2011, Aino
 * Licensed under the MIT license.
 *
 * --
 *
 * Usage:
 * E.bind( HTMLElement, type, callback[, capture] );
 * E.one( HTMLElement, type, callback[, capture] );
 * E.unbind( [HTMLElement][, type][, callback][, capture] );
 * E.trigger( HTMLElement, type );
 * E.hover( HTMLElement, onMouseOver, onMouseOut );
 *
 * Shorthands:
 * E.click( HTMLElement, callback ); // same as E.bind( HTMLElement, 'click', callback );
 * E.resize( window, callback );
 * E.click( HTMLElement ); // triggers a click event on HTMLElement
*/

/*global E:true */

E = (function( window ) {

    var document = window.document,

        undef,

        types = ('blur focus focusin focusout load ' +
                 'resize scroll unload click dblclick ' +
                 'mousedown mouseup mousemove mouseover mouseout ' +
                 'mouseenter mouseleave change select submit ' +
                 'keydown keypress keyup error wheel ' +
                 'abort').split(' '),

        // match types
        _reg = function( arr ) {
            var t = [],
                i = 0,
                len = arr.length;
            while( i < len ) {
                t.push( types[ arr[ i++ ]-1 ] );
            }
            return new RegExp('^(' + t.join('|') + ')$');
        },

        // collection of types that cancels/bubbles
        cancelable = _reg( [9,11,12,13,14,15,21,22,23] ),
        dontbubble = _reg( [5,8,24,26,6,2,1,16,17] ),

        // mouseenter / leave
        mouseenter = _reg( [15,17] ),
        mouseleave = _reg( [14,16] ),

        // cache ie detection
        ie = ('attachEvent' in document),

        // the events holder
        events = [],

        // holder for callbacks in IE
        bounds = [],

        // method for retrieveing or iterating through matching event objects
        _get = function(filter, each) {

            filter = filter || {};

            var evt, i, j, ret = [];

            main: for ( i=0; events[i]; i++ ) {
                evt = events[i];

                for ( j in filter ) {
                    if ( evt[ j ] !== filter[ j ] ) {
                        continue main;
                    }
                }
                if ( each ) {
                    each( i, evt );
                }
                ret.push( evt );
            }
            return ret;
        },

        // method for finding if an element contains another element
        _contains = function( outer, inner ) {
            if ( inner && outer && inner !== outer ) {
                while( inner && inner !== document.body && inner !== outer ) {
                    inner = inner.parentNode;
                }
                if ( inner === outer ) {
                    return true;
                }
            }
            return false;
        },

        // a really basic extend method
        _extend = function( obj, extend ) {
            for ( var i in extend ) {
                obj[ i ] = extend[ i ];
            }
            return obj;
        },

        _page = function( e, xy, sc ) {
            var c = 'client'+xy;
            return typeof e[c] == 'number' ? e[c] + document.body['scroll' + sc] : undef;
        },

        _normalize = function( ev ) {

            // save some native methods first
            var pd = function() {
                    ev.preventDefault.call(ev);
                };

            // now we flatclone the event into a normal object
            // to allow overwrite of read-only attributes
            // we pass some normalized props and let the native ones override if they exist
            var e = _extend({

                CAPTURING_PHASE: 1,
                AT_TARGET: 2,
                BUBBLING_PHASE: 3,

                cancelable: cancelable.test( ev.type ),

                bubbles: !(dontbubble.test( ev.type )),

                defaultPrevented: false,

                isTrusted: true,

                timeStamp: new Date().getTime(),

                target: ( ev.target || ev.srcElement || window ),

                currentTarget: this,

                relatedTarget: (function() {

                    if ( mouseenter.test( ev.type ) ) {
                        return ev.toElement;
                    } else if ( mouseleave.test( ev.type ) ) {
                        return ev.fromElement;
                    }

                    return null;

                }()),

                cancelBubble: false,

                pageX: _page(ev, 'X', 'Left'),
                pageY: _page(ev, 'Y', 'Top')
            }, ev );

            // the methods will not be native, except preventDefault that we previously saved
            // we need full control of the propagations since we do our own bubbling/capturing
            return _extend(e, {

                preventDefault: function() {
                    if ( !e.cancelable ) {
                        return;
                    }
                    e.returnValue = false;
                    e.defaultPrevented = true;
                    pd();
                },
                stopPropagation: function() {
                    e.cancelBubble = true;
                },
                stopImmediatePropagation: function() {
                    e.cancelBubble = true;
                    e._stop = true;
                }
            });

        },

        // shortcut for making an event object out of arguments
        _makeObject = function( args ) {
            var o = {},
                props = 'elem type callback capture'.split(' '),
                i;
            for( i=0; i < args.length; i++ ) {
                o[ props[i] ] = args[i];
            }
            return o;
        },

        // the generic event handler
        _handler = function( e ) {

            e = _normalize.call( this, e );

            var capture = [],
                elem = e.currentTarget,
                bubble = [],
                multi = [],
                target = e.target,
                ev, obj, i, phase,
                filter = function() {
                    _get({
                        elem: target,
                        type: e.type
                    }, function( i, evt ) {
                        if ( target === elem ) {
                            multi.push( evt );
                        }
                        if( evt.capture ) {
                            capture.push( evt );
                        } else if ( target === elem || e.bubbles ) {
                            bubble.push( evt );
                        }
                    });
                };

            // loop through events and call callbacks
            // use our own bubble/capture process for consistency
            // we need to manually move up the tree and collect events
            while ( target ) {
                filter();
                target = target.parentNode;
            }

            bubble = capture.reverse().concat( bubble );

            if ( bubble.length ) {

                // do the manual capture/bubble

                for ( i=0; bubble[i]; i++ ) {

                    obj = bubble[i];

                    phase = obj.elem === elem ? 2 :
                        ( obj.capture ? 1 : 3 );

                    // manually create a normalized event object and trigger the bubble
                    ev = _extend(e, {
                        currentTarget: obj.elem,
                        eventPhase: phase
                    });

                    (obj.callback = obj.callback).call( obj.elem, ev );

                    // detect propagation
                    if( ( ev._stop && !obj.capture ) || ( ev.cancelBubble && !multi.length ) ) {
                        break;
                    }

                    // shift raises no error on empty arrays
                    multi.shift();
                }
            }
        },

        // what to do when someone binds to a certian type if it's not supported
        _special = (function(){

            var check = function( e, type, handler ) {
                var elem = e.currentTarget,
                    related = e.relatedTarget;
                if( related !== elem && !_contains( elem, related ) ) {
                    e.type = type;
                    handler.call( elem, _normalize(e) );
                }
            };

            return {
                mouseenter: function(elem, handler) {
                    E.bind( elem, types[13], function(e) {
                        check( e, types[15], handler );
                    });
                },
                mouseleave: function(elem, handler) {
                    E.bind( elem, types[14], function(e) {
                        check( e, types[16], handler );
                    });
                }
            };
        }()),

        _toArray = function(a) {
            return [].slice.call(a);
        },

        _loopTypes = function( types, args, fn ) {
            for ( var i=0; types[ i ]; i++ ) {
                args[ 1 ] = types[ i ];
                E[ fn ].apply( window, args );
            }
        };

        // The main class

        E = {

            // make the get method public, mostly for testing
            get: _get,

            // bind an event
            bind: function() {

                var type, exists,
                    args = _toArray(arguments),
                    obj = _makeObject( args ),
                    elem = args[0],
                    types = args[1].split(' '),
                    handler = ie ? function(e) { _handler.call( elem, e ); } : _handler;

                if ( types.length > 1 ) {
                    _loopTypes( types, args, 'bind' );
                    return E;
                }

                type = obj.type = types[0];

                // special events, no bubbling or native handling
                if ( !( type in document ) && type in _special ) {
                    _special[ type ]( elem, obj.callback );
                    return E;
                }

                exists = _get({
                    elem: elem,
                    type: type
                }, false).length;

                // force a boolean cast of capture
                obj.capture = !!obj.capture;

                // if duplicated event, return
                if ( _get( obj, false ).length ) {
                    return E;
                }

                // add the event to the events holder
                events.push( obj );

                // no need to bind one type twice, the handler will take care of multiple events
                if ( exists ) {
                    return E;
                }

                if ( ie ) {
                    // save the anonymous handler
                    bounds.push([ elem, type, handler ]);
                    elem.attachEvent('on'+ type, handler);
                } else {
                    elem.addEventListener( type, handler );
                }

                return E;
            },

            // unbind event(s). Takes 0-4 arguments.
            unbind: function() {

                var args = _toArray( arguments ),
                    evt, b, j, elem, type,
                    types = args[1] ? args[1].split(' ') : [];

                if ( types.length > 1 ) {
                    _loopTypes( types, args, 'unbind' );
                    return E;
                }

                _get( _makeObject( args ), function(i, evt) {

                        // removeEListeners on elements that don't have listeners do not raise errors!

                        elem = evt.elem;
                        type = evt.type;

                        if ( !elem || !type ) {
                            return;
                        }

                        if ( ie ) {
                            for( j=0; bounds[j]; j++ ) {
                                b = bounds[j];
                                if ( b[0] === elem && b[1] == type ) {
                                    elem.detachEvent( 'on'+type, b[2] );
                                    bounds.splice( j, 1 );
                                    break;
                                }
                            }
                        } else {
                            elem.removeEventListener( type, _handler );
                        }

                        // remove the event
                        events[ i ] = {};
                    });

                return E;
            },

            // helper method for mouseover without child elements triggering mouseout
            hover: function( elem, over, out ) {
                E.bind(elem, types[15], over );
                if ( out ) {
                    E.bind(elem, types[16], out );
                }
                return E;
            },

            // helper method for binding and unbinding an event
            one: function( elem, type, callback, capture ) {

                var unbind = this.unbind;

                return E.bind( elem, type, function(e) {
                    unbind( elem, type, arguments.callee );
                    callback.call( elem, e );
                }, capture);

            },

            // trigger all events bound to a certian type
            trigger: function( elem, type, e ) {

                var evt, i,
                    fn = function(){};

                _get({
                    elem: elem,
                    type: type
                }, function() {
                    _handler.call(elem, _extend({
                        target: elem,
                        type: type,
                        isTrusted: false
                    }, e));
                });
                return E;
            }
        };

    // some shortcuts jQuery style
    (function() {

        var args, i,
            define = function(type) {
                return function() {
                    args = _toArray( arguments );
                    args.splice(1, 0, type);
                    return E[ typeof args[2] == 'function' ? 'bind' : 'trigger' ].apply( window, args );
                };
            };

        for ( i=0; types[ i ]; i++ ) {
            E[ types[ i ] ] = define( types[ i ] );
        }

    }());

    // return the singleton class
    return E;

}( this ));<commit_msg>hover, mouseenter, mouseleave<commit_after>/**
 * 2k v 1.1 2011-09-03
 * http://aino.com
 *
 * Copyright (c) 2011, Aino
 * Licensed under the MIT license.
 *
 * --
 *
 * Usage:
 * E.bind( HTMLElement, type, callback[, capture] );
 * E.one( HTMLElement, type, callback[, capture] );
 * E.unbind( [HTMLElement][, type][, callback][, capture] );
 * E.trigger( HTMLElement, type );
 * E.hover( HTMLElement, onMouseOver, onMouseOut );
 *
 * Shorthands:
 * E.click( HTMLElement, callback ); // same as E.bind( HTMLElement, 'click', callback );
 * E.resize( window, callback );
 * E.click( HTMLElement ); // triggers a click event on HTMLElement
*/

/*global E:true */

E = (function( window ) {

    var document = window.document,

        undef,

        types = ('blur focus focusin focusout load ' +
                 'resize scroll unload click dblclick ' +
                 'mousedown mouseup mousemove mouseover mouseout ' +
                 'mouseenter mouseleave change select submit ' +
                 'keydown keypress keyup error wheel ' +
                 'abort').split(' '),

        // match types
        _reg = function( arr ) {
            var t = [],
                i = 0,
                len = arr.length;
            while( i < len ) {
                t.push( types[ arr[ i++ ]-1 ] );
            }
            return new RegExp('^(' + t.join('|') + ')$');
        },

        // collection of types that cancels/bubbles
        cancelable = _reg( [9,11,12,13,14,15,21,22,23] ),
        dontbubble = _reg( [5,8,24,26,6,2,1,16,17] ),

        // mouseenter / leave
        mouseenter = _reg( [15,17] ),
        mouseleave = _reg( [14,16] ),

        // cache ie detection
        ie = ('attachEvent' in document),

        // the events holder
        events = [],

        // holder for callbacks in IE
        bounds = [],

        // method for retrieveing or iterating through matching event objects
        _get = function(filter, each) {

            filter = filter || {};

            var evt, i, j, ret = [];

            main: for ( i=0; events[i]; i++ ) {
                evt = events[i];

                for ( j in filter ) {
                    if ( evt[ j ] !== filter[ j ] ) {
                        continue main;
                    }
                }
                if ( each ) {
                    each( i, evt );
                }
                ret.push( evt );
            }
            return ret;
        },

        // method for finding if an element contains another element
        _contains = function( outer, inner ) {
            if ( inner && outer && inner !== outer ) {
                while( inner && inner !== document.body && inner !== outer ) {
                    inner = inner.parentNode;
                }
                if ( inner === outer ) {
                    return true;
                }
            }
            return false;
        },

        // a really basic extend method
        _extend = function( obj, extend ) {
            for ( var i in extend ) {
                obj[ i ] = extend[ i ];
            }
            return obj;
        },

        _page = function( e, xy, sc ) {
            var c = 'client'+xy;
            return typeof e[c] == 'number' ? e[c] + document.body['scroll' + sc] : undef;
        },

        _normalize = function( ev ) {

            // save some native methods first
            var pd = function() {
                    ev.preventDefault.call(ev);
                };

            // now we flatclone the event into a normal object
            // to allow overwrite of read-only attributes
            // we pass some normalized props and let the native ones override if they exist
            var e = _extend({

                CAPTURING_PHASE: 1,
                AT_TARGET: 2,
                BUBBLING_PHASE: 3,

                cancelable: cancelable.test( ev.type ),

                bubbles: !(dontbubble.test( ev.type )),

                defaultPrevented: false,

                isTrusted: true,

                timeStamp: new Date().getTime(),

                target: ( ev.target || ev.srcElement || window ),

                currentTarget: this,

                relatedTarget: (function() {

                    if ( mouseenter.test( ev.type ) ) {
                        return ev.toElement;
                    } else if ( mouseleave.test( ev.type ) ) {
                        return ev.fromElement;
                    }

                    return null;

                }()),

                cancelBubble: false,

                pageX: _page(ev, 'X', 'Left'),
                pageY: _page(ev, 'Y', 'Top')
            }, ev );

            // the methods will not be native, except preventDefault that we previously saved
            // we need full control of the propagations since we do our own bubbling/capturing
            return _extend(e, {

                preventDefault: function() {
                    if ( !e.cancelable ) {
                        return;
                    }
                    e.returnValue = false;
                    e.defaultPrevented = true;
                    pd();
                },
                stopPropagation: function() {
                    e.cancelBubble = true;
                },
                stopImmediatePropagation: function() {
                    e.cancelBubble = true;
                    e._stop = true;
                }
            });

        },

        // shortcut for making an event object out of arguments
        _makeObject = function( args ) {
            var o = {},
                props = 'elem type callback capture'.split(' '),
                i;
            for( i=0; i < args.length; i++ ) {
                o[ props[i] ] = args[i];
            }
            return o;
        },

        // the generic event handler
        _handler = function( e ) {

            e = _normalize.call( this, e );

            var capture = [],
                elem = e.currentTarget,
                bubble = [],
                multi = [],
                target = e.target,
                ev, obj, i, phase,
                filter = function() {
                    _get({
                        elem: target,
                        type: e.type
                    }, function( i, evt ) {
                        if ( target === elem ) {
                            multi.push( evt );
                        }
                        if( evt.capture ) {
                            capture.push( evt );
                        } else if ( target === elem || e.bubbles ) {
                            bubble.push( evt );
                        }
                    });
                };

            // loop through events and call callbacks
            // use our own bubble/capture process for consistency
            // we need to manually move up the tree and collect events
            while ( target ) {
                filter();
                target = target.parentNode;
            }

            bubble = capture.reverse().concat( bubble );

            if ( bubble.length ) {

                // do the manual capture/bubble

                for ( i=0; bubble[i]; i++ ) {

                    obj = bubble[i];

                    phase = obj.elem === elem ? 2 :
                        ( obj.capture ? 1 : 3 );

                    // manually create a normalized event object and trigger the bubble
                    ev = _extend(e, {
                        currentTarget: obj.elem,
                        eventPhase: phase
                    });

                    (obj.callback = obj.callback).call( obj.elem, ev );

                    // detect propagation
                    if( ( ev._stop && !obj.capture ) || ( ev.cancelBubble && !multi.length ) ) {
                        break;
                    }

                    // shift raises no error on empty arrays
                    multi.shift();
                }
            }
        },

        // what to do when someone binds to a certian type if it's not supported
        _special = (function(){

            var check = function( e, type, handler ) {
                var elem = e.currentTarget,
                    related = e.relatedTarget;
                if( related !== elem && !_contains( elem, related ) ) {
                    e.type = type;
                    // no bubbling here!
                    handler.call( elem, _normalize(e) );
                }
            };

            return {
                mouseenter: function( obj ) {
                    E.bind( obj.elem, types[13], function(e) {
                        check( e, types[15], obj.callback );
                    });
                },
                mouseleave: function( obj ) {
                    E.bind( obj.elem, types[14], function(e) {
                        check( e, types[16], obj.callback );
                    });
                }
            };
        }()),

        _toArray = function(a) {
            return [].slice.call(a);
        },

        _loopTypes = function( types, args, fn ) {
            for ( var i=0; types[ i ]; i++ ) {
                args[ 1 ] = types[ i ];
                E[ fn ].apply( window, args );
            }
        };

        // The main class

        E = {

            // make the get method public, mostly for testing
            get: _get,

            // bind an event
            bind: function() {

                var type, exists,
                    args = _toArray(arguments),
                    obj = _makeObject( args ),
                    elem = args[0],
                    types = args[1].split(' '),
                    handler = ie ? function(e) { _handler.call( elem, e ); } : _handler;

                if ( types.length > 1 ) {
                    _loopTypes( types, args, 'bind' );
                    return E;
                }

                type = obj.type = types[0];

                // force a boolean cast of capture
                obj.capture = !!obj.capture;

                // if duplicated event, return
                if ( _get( obj, false ).length ) {
                    return E;
                }

                // special events, no bubbling or native handling
                if ( !( type in document ) && type in _special ) {
                    _special[ type ]( obj );
                    return E;
                }

                exists = _get({
                    elem: elem,
                    type: type
                }, false).length;

                // add the event to the events holder
                events.push( obj );

                // no need to bind one type twice, the handler will take care of multiple events
                if ( exists ) {
                    return E;
                }

                if ( ie ) {
                    // save the anonymous handler
                    bounds.push([ elem, type, handler ]);
                    elem.attachEvent('on'+ type, handler);
                } else {
                    elem.addEventListener( type, handler );
                }

                return E;
            },

            // unbind event(s). Takes 0-4 arguments.
            unbind: function() {

                var args = _toArray( arguments ),
                    evt, b, j, elem, type,
                    types = args[1] ? args[1].split(' ') : [];

                if ( types.length > 1 ) {
                    _loopTypes( types, args, 'unbind' );
                    return E;
                }

                _get( _makeObject( args ), function(i, evt) {

                        // removeEListeners on elements that don't have listeners do not raise errors!

                        elem = evt.elem;
                        type = evt.type;

                        if ( !elem || !type ) {
                            return;
                        }

                        if ( ie ) {
                            for( j=0; bounds[j]; j++ ) {
                                b = bounds[j];
                                if ( b[0] === elem && b[1] == type ) {
                                    elem.detachEvent( 'on'+type, b[2] );
                                    bounds.splice( j, 1 );
                                    break;
                                }
                            }
                        } else {
                            elem.removeEventListener( type, _handler );
                        }

                        // remove the event
                        events[ i ] = {};
                    });

                return E;
            },

            // helper method for mouseover without child elements triggering mouseout
            hover: function( elem, over, out ) {
                E.bind(elem, types[15], over );
                if ( out ) {
                    E.bind(elem, types[16], out );
                }
                return E;
            },

            // helper method for binding and unbinding an event
            one: function( elem, type, callback, capture ) {

                var unbind = this.unbind;

                return E.bind( elem, type, function(e) {
                    unbind( elem, type, arguments.callee );
                    callback.call( elem, e );
                }, capture);

            },

            // trigger all events bound to a certian type
            trigger: function( elem, type, e ) {

                var evt, i,
                    fn = function(){};

                _get({
                    elem: elem,
                    type: type
                }, function() {
                    _handler.call(elem, _extend({
                        target: elem,
                        type: type,
                        isTrusted: false
                    }, e));
                });
                return E;
            }
        };

    // some shortcuts jQuery style
    (function() {

        var args, i,
            define = function(type) {
                return function() {
                    args = _toArray( arguments );
                    args.splice(1, 0, type);
                    return E[ typeof args[2] == 'function' ? 'bind' : 'trigger' ].apply( window, args );
                };
            };

        for ( i=0; types[ i ]; i++ ) {
            E[ types[ i ] ] = define( types[ i ] );
        }

    }());

    // return the singleton class
    return E;

}( this ));<|endoftext|>


<commit_before>/**
 * CG Space Invaders
 * CG45179 16'17
 *
 * @author: Rui Ventura ( ist181045 )
 * @author: Diogo Freitas ( ist181586 )
 * @author: Sara Azinhal ( ist181700 )
 */

class Field {

	constructor( x, y, z ) {
		var field = new THREE.Object3D();

		this.addBottom( field, 0, -75, 0 );
		this.addVerticalBarriers( field, -975, 0, 0 );
		this.addVerticalBarriers( field, 975, 0, 0 );
		this.addHorizontalBarriers( field, 0, 0, -725 );
		this.addHorizontalBarriers( field, 0, 0, 725 );

		scene.add( field );
		field.position.x = x;
		field.position.y = y;
		field.position.z = z;
	}

	addBottom( obj, x, y, z ) {
		var geometry = new THREE.CubeGeometry( 2000, 1, 1500 );
		var mesh = new THREE.Mesh( geometry, material4 );
		mesh.position.set( x, y, z );

		obj.add( mesh );
	}

	addVerticalBarriers( obj, x, y, z ) {
		var geometry = new THREE.CubeGeometry( 50, 150, 1500 );
		var mesh = new THREE.Mesh( geometry, material5 );
		mesh.position.set( x, y, z );

		obj.add( mesh );
	}

	addHorizontalBarriers( obj, x, y, z ) {
		var geometry = new THREE.CubeGeometry( 2000, 150, 50 );
		var mesh = new THREE.Mesh( geometry, material5 );
		mesh.position.set( x, y, z );

		obj.add( mesh );
	}
}<commit_msg>Redo Field class (resize inbound)<commit_after>/*global THREE*/

/**
 * CG Space Invaders
 * Game field - CG45179 16'17
 *
 * @author: Rui Ventura ( ist181045 )
 * @author: Diogo Freitas ( ist181586 )
 * @author: Sara Azinhal ( ist181700 )
 */

class Field extends THREE.Object3D {

	constructor( x, y, z, w = 250, l = 250 ) {

		super();

		this.type = 'Field';

		this._width  = w;
		this._length = l;

		this._buildField( 0, 0, 0 );

		this.position.set( x, y, z );

	}

	get width () {

		return this._width;

	}

	get length () {

		return this._length;

	}

	_buildField ( x, y, z ) {

		let w = this._width;
		let l = this._length;

		console.log( `${w} : ${l}` );

		let barriers = new THREE.Group();

		let barrierMaterial = new THREE.MeshBasicMaterial( {
			color: new THREE.Color( 0xFFFFFF )
		} );

		let floorMaterial = new THREE.MeshBasicMaterial( {
			color: new THREE.Color( 0x1A1A1A ),
			side: THREE.DoubleSide
		} );

		this.children.splice( 0, this.children.length );

		this._addFloor( this, x, y, z, floorMaterial );
		this._addVerticalBarrier( barriers, x + w / -2, y, z, barrierMaterial );
		this._addVerticalBarrier( barriers, x + w /  2, y, z, barrierMaterial );
		this._addHorizontalBarrier( barriers, x, y, z + l / -2, barrierMaterial );
		this._addHorizontalBarrier( barriers, x, y, z + l /  2, barrierMaterial );

		this.add( barriers );

	}

	_addFloor ( obj, x, y, z, material ) {

		let geometry = new THREE.PlaneGeometry( this._width, this._length );
		let mesh = new THREE.Mesh( geometry, material );

		mesh.position.set( x, y, z );
		mesh.rotateX( Math.PI / -2 );

		obj.add( mesh );

	}

	_addVerticalBarrier ( obj, x, y, z, material ) {

		let geometry = new THREE.CubeGeometry( 4, 2, this._length );
		let mesh = new THREE.Mesh( geometry, material );

		mesh.position.set( x > 0 ? x - 2 : x + 2, y, z );

		obj.add( mesh );

	}

	_addHorizontalBarrier ( obj, x, y, z, material ) {

		let geometry = new THREE.CubeGeometry( this._width, 2, 4 );
		let mesh = new THREE.Mesh( geometry, material );

		mesh.position.set( x, y, z > 0 ? z - 2 : z + 2 );

		obj.add( mesh );

	}

}
<|endoftext|>