<commit_before>'use strict';

const path = require('path');
const helpers = require('yeoman-test');
const assert = require('yeoman-assert');

module.exports = () => {

  describe('when using CSS', () => {

    before(done => {
      this.generator = helpers
        .run(path.join(__dirname, '../../generators/app'))
        .withPrompts({
          cssPreprocessor: 'css'
        })
        .toPromise()
        .then(() => done());
    });

    it('should add a main.css file', () => {
      assert.file('src/styles/main.css');
    });

    it('should use CSSLint rules', () => {
      assert.file('src/.csslintrc');
      assert.fileContent('package.json', 'csslint src/styles/');
      assert.fileContent('package.json', '"csslint"');
    });

  });

  describe('when using Sass', () => {

    before(done => {
      this.generator = helpers
        .run(path.join(__dirname, '../../generators/app'))
        .withPrompts({
          cssPreprocessor: 'sass'
        })
        .toPromise()
        .then(() => done());
    });

    it('should add a main.scss file', () => {
      assert.file('src/styles/main.scss');
    });

    it('should create a 7-1 pattern', () => {
      assert.file('src/styles/README.md');
      assert.file('src/styles/abstracts/README.md');
      assert.file('src/styles/base/README.md');
      assert.file('src/styles/components/README.md');
      assert.file('src/styles/layout/README.md');
      assert.file('src/styles/pages/README.md');
      assert.file('src/styles/themes/README.md');
      assert.file('src/styles/vendors/README.md');
    });

    it('should use SASSLint rules', () => {
      assert.file('src/.sass-lint.yml');
      assert.fileContent('package.json', 'sass-lint -v -q');
      assert.fileContent('package.json', '"sasslintConfig": "src/.sass-lint.yml",');
    });

  });

  describe('when using Less', () => {

    before(done => {
      this.generator = helpers
        .run(path.join(__dirname, '../../generators/app'))
        .withPrompts({
          cssPreprocessor: 'less'
        })
        .toPromise()
        .then(() => done());
    });

    it('should add a main.less file', () => {
      assert.file('src/styles/main.less');
    });

    it('should create a 7-1 pattern', () => {
      assert.file('src/styles/README.md');
      assert.file('src/styles/abstracts/README.md');
      assert.file('src/styles/base/README.md');
      assert.file('src/styles/components/README.md');
      assert.file('src/styles/layout/README.md');
      assert.file('src/styles/pages/README.md');
      assert.file('src/styles/themes/README.md');
      assert.file('src/styles/vendors/README.md');
    });

  });

};
<commit_msg>test(css-preprocessors): sass-lint command shouldn't use the `-q` argument<commit_after>'use strict';

const path = require('path');
const helpers = require('yeoman-test');
const assert = require('yeoman-assert');

module.exports = () => {

  describe('when using CSS', () => {

    before(done => {
      this.generator = helpers
        .run(path.join(__dirname, '../../generators/app'))
        .withPrompts({
          cssPreprocessor: 'css'
        })
        .toPromise()
        .then(() => done());
    });

    it('should add a main.css file', () => {
      assert.file('src/styles/main.css');
    });

    it('should use CSSLint rules', () => {
      assert.file('src/.csslintrc');
      assert.fileContent('package.json', 'csslint src/styles/');
      assert.fileContent('package.json', '"csslint"');
    });

  });

  describe('when using Sass', () => {

    before(done => {
      this.generator = helpers
        .run(path.join(__dirname, '../../generators/app'))
        .withPrompts({
          cssPreprocessor: 'sass'
        })
        .toPromise()
        .then(() => done());
    });

    it('should add a main.scss file', () => {
      assert.file('src/styles/main.scss');
    });

    it('should create a 7-1 pattern', () => {
      assert.file('src/styles/README.md');
      assert.file('src/styles/abstracts/README.md');
      assert.file('src/styles/base/README.md');
      assert.file('src/styles/components/README.md');
      assert.file('src/styles/layout/README.md');
      assert.file('src/styles/pages/README.md');
      assert.file('src/styles/themes/README.md');
      assert.file('src/styles/vendors/README.md');
    });

    it('should use SASSLint rules', () => {
      assert.file('src/.sass-lint.yml');
      assert.fileContent('package.json', 'sass-lint -v');
      assert.fileContent('package.json', '"sasslintConfig": "src/.sass-lint.yml",');
    });

  });

  describe('when using Less', () => {

    before(done => {
      this.generator = helpers
        .run(path.join(__dirname, '../../generators/app'))
        .withPrompts({
          cssPreprocessor: 'less'
        })
        .toPromise()
        .then(() => done());
    });

    it('should add a main.less file', () => {
      assert.file('src/styles/main.less');
    });

    it('should create a 7-1 pattern', () => {
      assert.file('src/styles/README.md');
      assert.file('src/styles/abstracts/README.md');
      assert.file('src/styles/base/README.md');
      assert.file('src/styles/components/README.md');
      assert.file('src/styles/layout/README.md');
      assert.file('src/styles/pages/README.md');
      assert.file('src/styles/themes/README.md');
      assert.file('src/styles/vendors/README.md');
    });

  });

};
<|endoftext|>


<commit_before>"use strict"

class TPromise {

  constructor(executor) {
    this.status = "pending"
    this.callbackQueue = []

    typeof executor === "function" && executor(
      this.resolve.bind(this),
      this.reject.bind(this)
    )
  }

  then(onResolve, onReject) {
    onResolve && this.callbackQueue.push({
      cb: onResolve,
      type: "resolved"
    })

    onReject && this.callbackQueue.push({
      cb: onReject,
      type: "rejected"
    })

    this.status !== "pending" && this.fulfil()

    return this
  }

  catch(onReject) {
    this.callbackQueue.push({
      cb: onReject,
      type: "rejected"
    })

    this.status !== "pending" && this.fulfil()

    return this
  }

  resolve(...args) {
    this.status = "resolved"
    this.args = args

    return this.fulfil()
  }

  reject(...args) {
    this.status = "rejected"
    this.args = args

    return this.fulfil()
  }

  fulfil() {
    var item, ret

    if (this.status === "pending") {
      return this
    }

    while (item = this.callbackQueue.shift()) {
      if (item.type === this.status) {
        ret = item.cb(...this.args)

        if (ret instanceof TPromise) {
          ret.callbackQueue = ret.callbackQueue.concat(this.callbackQueue)
          this.callbackQueue = []

          ret.fulfil()

          break
        }
      }
    }

    return this
  }

  static resolve() {
    return TPromise.create().resolve()
  }

  static reject() {
    return TPromise.create().reject()
  }

  static create(executor) {
    return new TPromise(executor)
  }

}

if (module && module.exports) {
  module.exports = TPromise
}<commit_msg>module is undefined error fix<commit_after>"use strict"

class TPromise {

  constructor(executor) {
    this.status = "pending"
    this.callbackQueue = []

    typeof executor === "function" && executor(
      this.resolve.bind(this),
      this.reject.bind(this)
    )
  }

  then(onResolve, onReject) {
    onResolve && this.callbackQueue.push({
      cb: onResolve,
      type: "resolved"
    })

    onReject && this.callbackQueue.push({
      cb: onReject,
      type: "rejected"
    })

    this.status !== "pending" && this.fulfil()

    return this
  }

  catch(onReject) {
    this.callbackQueue.push({
      cb: onReject,
      type: "rejected"
    })

    this.status !== "pending" && this.fulfil()

    return this
  }

  resolve(...args) {
    this.status = "resolved"
    this.args = args

    return this.fulfil()
  }

  reject(...args) {
    this.status = "rejected"
    this.args = args

    return this.fulfil()
  }

  fulfil() {
    var item, ret

    if (this.status === "pending") {
      return this
    }

    while (item = this.callbackQueue.shift()) {
      if (item.type === this.status) {
        ret = item.cb(...this.args)

        if (ret instanceof TPromise) {
          ret.callbackQueue = ret.callbackQueue.concat(this.callbackQueue)
          this.callbackQueue = []

          ret.fulfil()

          break
        }
      }
    }

    return this
  }

  static resolve() {
    return TPromise.create().resolve()
  }

  static reject() {
    return TPromise.create().reject()
  }

  static create(executor) {
    return new TPromise(executor)
  }

}

if (typeof module !== "undefined" && module.exports) {
  module.exports = TPromise
}<|endoftext|>


<commit_before>/**
	_moon.Drawers_ is a container kind for a set of moon.Drawers and
	client content. It accepts an array of a href="#moon.Drawer">moon.Drawers and will
	position the drawer's moon.DrawerHandles
	at the top center of the view in a small drawer (aka the dresser). When they are selected they
	will open their corresponding moon.Drawer's main drawer or control
	drawer depending on it's configuration.

	The control's child components may be of any kind.

	{kind:"moon.Drawers", drawers:[
		{name:"musicDrawer", kind: "moon.Drawer",
			handle: {kind:"moon.DrawerHandle", content:"Handle"},
			components: [
				{content:"Drawer Content"}
			],
			controlDrawerComponents: [
				{content:"Controls"}
			]}
		]},
		components: [
			{content: "Content Area"}
		]
	}
*/
enyo.kind({
	name: "moon.Drawers",
	kind: "enyo.Control",
	classes: "moon-drawers",
	published: {
		//* Set with an array of moon.Drawer components
		drawers: null
	},
	handlers: {
		//* Handlers to udpate the activator when the state of contained drawers changes
		onActivate: "drawerActivated",
		onDeactivate: "drawerDeactivated",
		onSpotlightDown:"spotDown",
		onSpotlightUp:"spotUp"
	},
	components: [
		{name:"handleContainer", kind:"enyo.Drawer", spotlight:'container', open:false, onpostresize:"resizeHandleContainer", components:[
			{name:"handles", classes:"moon-drawers-handles"}
		]},
		{name:"activator", classes:"moon-drawers-activator", spotlight:true, ontap:"activatorHandler", components:[
			{classes:"moon-drawers-activator-nub", components:[
				{name:"nubArrow", classes:"down"}
			]}
		]},
		{name: "drawers", classes:"moon-drawers-drawer-container"},
		{name: "client", classes:"moon-drawers-client", spotlight:'container', ontap:"clientTapped"}
	],
	create: function() {
		this.inherited(arguments);
		this.$.drawers.createComponents(this.drawers, {kind: "moon.Drawer", owner:this.owner});
		this.setupHandles();
	},
	rendered: function() {
	    this.inherited(arguments);
		this.resizeDresser();
	    var dh = document.body.getBoundingClientRect().height;
	    var ah = this.$.activator.hasNode().getBoundingClientRect().height;
	    this.waterfall("onDrawersRendered", {drawersHeight: dh, activatorHeight: ah});
	},
	resizeDresser: function() {
		var client = this.hasNode().getBoundingClientRect();

		this.$.activator.applyStyle('left', -client.left+'px');
		this.$.activator.applyStyle('top',-client.top+'px');
		this.$.activator.applyStyle('width',document.body.getBoundingClientRect().width + "px");

		this.$.handleContainer.applyStyle('left', -client.left+'px');
		this.$.handleContainer.applyStyle('top',(-client.top-5)+'px');
		this.$.handleContainer.applyStyle('width',document.body.getBoundingClientRect().width + "px");

		this.$.drawers.applyStyle('left', -client.left+'px');
		this.$.drawers.applyStyle('top', (-client.top-10)+'px');
		this.$.drawers.applyStyle('width',document.body.getBoundingClientRect().width + "px");
	},
	setupHandles: function() {
		var handles = [];
		for (var index in this.drawers){
			handles.push(this.drawers[index].handle);
		}
		this.$.handles.createComponents(handles, {kind: "moon.DrawerHandle", owner:this});
		for (index in handles) {
			this.$.handles.getControls()[index].addClass('moon-drawers-handle');
			this.$.handles.getControls()[index].tap = this.bindSafely(this.handleTapped);
		}
	},
	activatorHandler: function(){
		if (this.drawerOpen()) {
			this.closeDrawers();
		} else {
			if (this.$.handles.getControls().length == 1) {
				this.openDrawer(this.$.handles.getControls()[0]);
			} else {
				this.$.handleContainer.setOpen(!this.$.handleContainer.getOpen());
			}
			this.updateActivator(false);
		}
	},
	handleTapped: function(inSender, inEvent) {
		this.openDrawer(inEvent.originator)
		return true;
	},
	openDrawer: function(drawer) {
		var handles = this.$.handles.getControls();
		for (var index in handles)
		{
			if (handles[index] == drawer || enyo.Spotlight.Util.isChild(handles[index],drawer)) {
				var drawer = this.$.drawers.getControls()[index];
				drawer.toggleDrawer();
				this.$.handleContainer.setOpen(false);
				return;
			}
		}
	},
	drawerOpen: function() {
		var drawers = this.$.drawers.getControls();
		for (var index in drawers){
			if (drawers[index].getOpen() || drawers[index].getControlsOpen()) {
				return true;
			}
		}
		return false;
	},
	closeDrawers: function(inSender, inEvent) {
		var drawers = this.$.drawers.getControls();
		for (var index in drawers){
			if (drawers[index].getOpen()) {
				drawers[index].setOpen(false);
				if (drawers[index].controlDrawerComponents !== null && drawers[index].getControlsOpen()) {
					enyo.Spotlight.spot(drawers[index].$.controlDrawer);
				} else {
					enyo.Spotlight.spot(this.$.activator);
				}
			} else if (drawers[index].getControlsOpen()) {
				drawers[index].setControlsOpen(false);
			}
		}
	},
	clientTapped: function(inSender, inEvent) {
		for (var index in this.drawers)
		{
			var drawer = this.$.drawers.getControls()[index];
			drawer.setControlsOpen(false);
		}
	},
	drawerActivated: function(inSender, inEvent) {
		var drawers = this.$.drawers.getControls();
		for (var index in drawers)
		{
			if (drawers[index] == inEvent.originator) {
				this.updateActivator(true);
				return true;
			}
		}
	},
	drawerDeactivated: function(inSender, inEvent) {
		enyo.Spotlight.spot(this.$.activator);
		if (!inEvent.originator.getOpen() && !inEvent.originator.getControlsOpen()) {
			this.updateActivator(false);
		}
	},
	updateActivator: function(up) {
		this.$.nubArrow.addRemoveClass("up",up);
		this.$.nubArrow.addRemoveClass("down",!up);
		if (!up) {
			this.$.activator.addRemoveClass("drawer-open", false);
		}
	},
	resizeHandler: function() {
		this.inherited(arguments);
		if (this.$.handleContainer.$.animator.isAnimating()){
			return true;
		}
		this.resizeDresser();
	    var dh = document.body.getBoundingClientRect().height;
	    var ah = this.$.activator.hasNode().getBoundingClientRect().height;
	    this.waterfall("onDrawersResized", {drawersHeight: dh, activatorHeight: ah});
		this.updateActivator(false);
	},
	//Updates the activator's style only when it is not animating so that there are no visual artifacts
	resizeHandleContainer: function(inSender, inEvent) {
		enyo.asyncMethod(inEvent.delegate.bindSafely(function(){
			if (!this.$.animator.isAnimating()) {
				this.parent.$.activator.addRemoveClass("drawer-open", this.parent.drawerOpen() ? true : false);
			}
		}));
	},
	spotUp: function(inSender, inEvent) {
		if (inEvent.originator == this.$.activator && !this.$.handleContainer.getOpen()) {
			return true;
		}

		//this specifically handles an up event from moon.Panels, but it is potentially too strict
		if (inEvent.originator.kind == "moon.Panels" && enyo.Spotlight.Util.isChild(this.$.client,inEvent.originator)) {
			enyo.Spotlight.spot(this.$.activator);
			return true;
		}

		//if at the top of a drawer then move focus to the activator
		var drawers = this.$.drawers.getControls();
		for (var index in drawers) {
			if (drawers[index].getOpen()) {
				if (drawers[index].$.client == inEvent.originator) {
					enyo.Spotlight.spot(this.$.activator);
					return true;
				}
			} else if (drawers[index].$.controlDrawer == inEvent.originator) {
				enyo.Spotlight.spot(this.$.activator);
				return true;
			}
		}
	},
	spotDown: function(inSender, inEvent) {
		var drawers = this.$.drawers.getControls();
		var index;

		//if they hit down while on the activator & there's an open drawer, move focus to it
		if (inEvent.originator == this.$.activator) {
			for (index in drawers) {
				if (drawers[index].getOpen()) {
					enyo.Spotlight.spot(drawers[index].$.client);
					return true;
				} else if (drawers[index].getControlsOpen()) {
					enyo.Spotlight.spot(drawers[index].$.controlDrawer);
					return true;
				}
			}
			//spot the client area if no drawers are open
			enyo.Spotlight.spot(enyo.Spotlight.getFirstChild(this.$.client));
			return true;
		}

		//if at the bottom a drawer then stop them from going further
		for (index in drawers) {
			//when the main drawer is open
			if (drawers[index].getOpen()) {
				if (drawers[index].$.client == inEvent.originator) {
					//go to the controls drawer if there is one, otherwise stop at the last control
					if (drawers[index].controlDrawerComponents !== null && drawers[index].getControlsOpen()) {
						enyo.Spotlight.spot(drawers[index].$.controlDrawer);
					} else {
						var kids = enyo.Spotlight.getChildren(drawers[index].$.client);
						enyo.Spotlight.spot(kids[kids.length-1]);
					}
					return true;
				//if from the control drawer & it was the last spottable item, respot it
				} else if (drawers[index].$.controlDrawer == inEvent.originator) {
					var kids = enyo.Spotlight.getChildren(drawers[index].$.controlDrawer);
					enyo.Spotlight.spot(kids[kids.length-1]);
					return true;
				}
			//when only the control drawer is open then spotlight our main client area
			} else if (drawers[index].$.controlDrawer == inEvent.originator && drawers[index].getControlsOpen()) {
				enyo.Spotlight.spot(this.$.client);
				return true;
			}
		}
	}
});<commit_msg>Adding handle getter function Enyo-DCO-1.1-Signed-off-by: Steven Feaster <steven.feaster@lge.com><commit_after>/**
	_moon.Drawers_ is a container kind for a set of moon.Drawers and
	client content. It accepts an array of a href="#moon.Drawer">moon.Drawers and will
	position the drawer's moon.DrawerHandles
	at the top center of the view in a small drawer (aka the dresser). When they are selected they
	will open their corresponding moon.Drawer's main drawer or control
	drawer depending on it's configuration.

	The control's child components may be of any kind.

	{kind:"moon.Drawers", drawers:[
		{name:"musicDrawer", kind: "moon.Drawer",
			handle: {kind:"moon.DrawerHandle", content:"Handle"},
			components: [
				{content:"Drawer Content"}
			],
			controlDrawerComponents: [
				{content:"Controls"}
			]}
		]},
		components: [
			{content: "Content Area"}
		]
	}
*/
enyo.kind({
	name: "moon.Drawers",
	kind: "enyo.Control",
	classes: "moon-drawers",
	published: {
		//* Set with an array of moon.Drawer components
		drawers: null
	},
	handlers: {
		//* Handlers to udpate the activator when the state of contained drawers changes
		onActivate: "drawerActivated",
		onDeactivate: "drawerDeactivated",
		onSpotlightDown:"spotDown",
		onSpotlightUp:"spotUp"
	},
	components: [
		{name:"handleContainer", kind:"enyo.Drawer", spotlight:'container', open:false, onpostresize:"resizeHandleContainer", components:[
			{name:"handles", classes:"moon-drawers-handles"}
		]},
		{name:"activator", classes:"moon-drawers-activator", spotlight:true, ontap:"activatorHandler", components:[
			{classes:"moon-drawers-activator-nub", components:[
				{name:"nubArrow", classes:"down"}
			]}
		]},
		{name: "drawers", classes:"moon-drawers-drawer-container"},
		{name: "client", classes:"moon-drawers-client", spotlight:'container', ontap:"clientTapped"}
	],
	create: function() {
		this.inherited(arguments);
		this.$.drawers.createComponents(this.drawers, {kind: "moon.Drawer", owner:this.owner});
		this.setupHandles();
	},
	rendered: function() {
	    this.inherited(arguments);
		this.resizeDresser();
	    var dh = document.body.getBoundingClientRect().height;
	    var ah = this.$.activator.hasNode().getBoundingClientRect().height;
	    this.waterfall("onDrawersRendered", {drawersHeight: dh, activatorHeight: ah});
	},
	resizeDresser: function() {
		var client = this.hasNode().getBoundingClientRect();

		this.$.activator.applyStyle('left', -client.left+'px');
		this.$.activator.applyStyle('top',-client.top+'px');
		this.$.activator.applyStyle('width',document.body.getBoundingClientRect().width + "px");

		this.$.handleContainer.applyStyle('left', -client.left+'px');
		this.$.handleContainer.applyStyle('top',(-client.top-5)+'px');
		this.$.handleContainer.applyStyle('width',document.body.getBoundingClientRect().width + "px");

		this.$.drawers.applyStyle('left', -client.left+'px');
		this.$.drawers.applyStyle('top', (-client.top-10)+'px');
		this.$.drawers.applyStyle('width',document.body.getBoundingClientRect().width + "px");
	},
	setupHandles: function() {
		var handles = [];
		for (var index in this.drawers){
			handles.push(this.drawers[index].handle);
		}
		this.$.handles.createComponents(handles, {kind: "moon.DrawerHandle", owner:this});
		for (index in handles) {
			this.$.handles.getControls()[index].addClass('moon-drawers-handle');
			this.$.handles.getControls()[index].tap = this.bindSafely(this.handleTapped);
		}
	},
	activatorHandler: function(){
		if (this.drawerOpen()) {
			this.closeDrawers();
		} else {
			if (this.$.handles.getControls().length == 1) {
				this.openDrawer(this.$.handles.getControls()[0]);
			} else {
				this.$.handleContainer.setOpen(!this.$.handleContainer.getOpen());
			}
			this.updateActivator(false);
		}
	},
	handleTapped: function(inSender, inEvent) {
		this.openDrawer(inEvent.originator)
		return true;
	},
	openDrawer: function(drawer) {
		var handles = this.$.handles.getControls();
		for (var index in handles)
		{
			if (handles[index] == drawer || enyo.Spotlight.Util.isChild(handles[index],drawer)) {
				var drawer = this.$.drawers.getControls()[index];
				drawer.toggleDrawer();
				this.$.handleContainer.setOpen(false);
				return;
			}
		}
	},
	drawerOpen: function() {
		var drawers = this.$.drawers.getControls();
		for (var index in drawers){
			if (drawers[index].getOpen() || drawers[index].getControlsOpen()) {
				return true;
			}
		}
		return false;
	},
	closeDrawers: function(inSender, inEvent) {
		var drawers = this.$.drawers.getControls();
		for (var index in drawers){
			if (drawers[index].getOpen()) {
				drawers[index].setOpen(false);
				if (drawers[index].controlDrawerComponents !== null && drawers[index].getControlsOpen()) {
					enyo.Spotlight.spot(drawers[index].$.controlDrawer);
				} else {
					enyo.Spotlight.spot(this.$.activator);
				}
			} else if (drawers[index].getControlsOpen()) {
				drawers[index].setControlsOpen(false);
			}
		}
	},
	clientTapped: function(inSender, inEvent) {
		for (var index in this.drawers)
		{
			var drawer = this.$.drawers.getControls()[index];
			drawer.setControlsOpen(false);
		}
	},
	drawerActivated: function(inSender, inEvent) {
		var drawers = this.$.drawers.getControls();
		for (var index in drawers)
		{
			if (drawers[index] == inEvent.originator) {
				this.updateActivator(true);
				return true;
			}
		}
	},
	drawerDeactivated: function(inSender, inEvent) {
		enyo.Spotlight.spot(this.$.activator);
		if (!inEvent.originator.getOpen() && !inEvent.originator.getControlsOpen()) {
			this.updateActivator(false);
		}
	},
	updateActivator: function(up) {
		this.$.nubArrow.addRemoveClass("up",up);
		this.$.nubArrow.addRemoveClass("down",!up);
		if (!up) {
			this.$.activator.addRemoveClass("drawer-open", false);
		}
	},
	resizeHandler: function() {
		this.inherited(arguments);
		if (this.$.handleContainer.$.animator.isAnimating()){
			return true;
		}
		this.resizeDresser();
	    var dh = document.body.getBoundingClientRect().height;
	    var ah = this.$.activator.hasNode().getBoundingClientRect().height;
	    this.waterfall("onDrawersResized", {drawersHeight: dh, activatorHeight: ah});
		this.updateActivator(false);
	},
	//Updates the activator's style only when it is not animating so that there are no visual artifacts
	resizeHandleContainer: function(inSender, inEvent) {
		enyo.asyncMethod(inEvent.delegate.bindSafely(function(){
			if (!this.$.animator.isAnimating()) {
				this.parent.$.activator.addRemoveClass("drawer-open", this.parent.drawerOpen() ? true : false);
			}
		}));
	},
	handleAtIndex: function(inIndex) {
		return this.$.handles.getControls()[inIndex];
	},
	spotUp: function(inSender, inEvent) {
		if (inEvent.originator == this.$.activator && !this.$.handleContainer.getOpen()) {
			return true;
		}

		//this specifically handles an up event from moon.Panels, but it is potentially too strict
		if (inEvent.originator.kind == "moon.Panels" && enyo.Spotlight.Util.isChild(this.$.client,inEvent.originator)) {
			enyo.Spotlight.spot(this.$.activator);
			return true;
		}

		//if at the top of a drawer then move focus to the activator
		var drawers = this.$.drawers.getControls();
		for (var index in drawers) {
			if (drawers[index].getOpen()) {
				if (drawers[index].$.client == inEvent.originator) {
					enyo.Spotlight.spot(this.$.activator);
					return true;
				}
			} else if (drawers[index].$.controlDrawer == inEvent.originator) {
				enyo.Spotlight.spot(this.$.activator);
				return true;
			}
		}
	},
	spotDown: function(inSender, inEvent) {
		var drawers = this.$.drawers.getControls();
		var index;

		//if they hit down while on the activator & there's an open drawer, move focus to it
		if (inEvent.originator == this.$.activator) {
			for (index in drawers) {
				if (drawers[index].getOpen()) {
					enyo.Spotlight.spot(drawers[index].$.client);
					return true;
				} else if (drawers[index].getControlsOpen()) {
					enyo.Spotlight.spot(drawers[index].$.controlDrawer);
					return true;
				}
			}
			//spot the client area if no drawers are open
			enyo.Spotlight.spot(enyo.Spotlight.getFirstChild(this.$.client));
			return true;
		}

		//if at the bottom a drawer then stop them from going further
		for (index in drawers) {
			//when the main drawer is open
			if (drawers[index].getOpen()) {
				if (drawers[index].$.client == inEvent.originator) {
					//go to the controls drawer if there is one, otherwise stop at the last control
					if (drawers[index].controlDrawerComponents !== null && drawers[index].getControlsOpen()) {
						enyo.Spotlight.spot(drawers[index].$.controlDrawer);
					} else {
						var kids = enyo.Spotlight.getChildren(drawers[index].$.client);
						enyo.Spotlight.spot(kids[kids.length-1]);
					}
					return true;
				//if from the control drawer & it was the last spottable item, respot it
				} else if (drawers[index].$.controlDrawer == inEvent.originator) {
					var kids = enyo.Spotlight.getChildren(drawers[index].$.controlDrawer);
					enyo.Spotlight.spot(kids[kids.length-1]);
					return true;
				}
			//when only the control drawer is open then spotlight our main client area
			} else if (drawers[index].$.controlDrawer == inEvent.originator && drawers[index].getControlsOpen()) {
				enyo.Spotlight.spot(this.$.client);
				return true;
			}
		}
	}
});<|endoftext|>


<commit_before>/*
 * grunt-git
 * https://github.com/rubenv/grunt-git
 *
 * Copyright (c) 2013 Ruben Vermeersch
 * Licensed under the MIT license.
 */

'use strict';

var commands = require('../lib/commands');

module.exports = function (grunt) {
    function exec(command) {
        var args = Array.prototype.slice.call(arguments);
        var callback = args.pop();

        grunt.util.spawn({
            cmd: 'git',
            args: args,
            opts: this.data.options && this.data.options.stdio ? {stdio: 'inherit'} : {}
        }, function () {
            callback.apply(this, arguments);
        });
    }

    function wrapCommand(fn) {
        return function () {
            var done = this.async();
            fn(this, exec.bind(this), done);
        };
    }

    for (var command in commands) {
        var fn = commands[command];
        grunt.registerMultiTask("git" + command, fn.description || "", wrapCommand(fn));
    }
};
<commit_msg>add stdio option<commit_after>/*
 * grunt-git
 * https://github.com/rubenv/grunt-git
 *
 * Copyright (c) 2013 Ruben Vermeersch
 * Licensed under the MIT license.
 */

'use strict';

var commands = require('../lib/commands');

module.exports = function (grunt) {
    function exec(command) {
        var args = Array.prototype.slice.call(arguments);
        var callback = args.pop();

        grunt.util.spawn({
            cmd: 'git',
            args: args,
            opts: command.data.options && command.data.options.stdio ? {stdio: 'inherit'} : {}
        }, function () {
            callback.apply(this, arguments);
        });
    }

    function wrapCommand(fn) {
        return function () {
            var done = this.async();
            fn(this, function () { exec(this); }, done);
        };
    }

    for (var command in commands) {
        var fn = commands[command];
        grunt.registerMultiTask("git" + command, fn.description || "", wrapCommand(fn));
    }
};
<|endoftext|>


<commit_before>/*
 * grunt-kss
 * https://github.com/t32k/grunt-kss
 *
 * Copyright (c) 2013 Koji Ishimoto
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

    grunt.registerMultiTask('kss', 'Generate styleguide by KSS.', function() {

        var fs = require('fs'),
            path = require('path'),
            exec = require('child_process').exec,
            done = this.async();

        var kssCmd = ['node'],
            realPath = path.dirname(__filename).replace(/tasks$/g, ''),
            sass = require(realPath + '/lib/sass'),
            dest = process.cwd();

        var opts = this.options({
            template: null,
            includeType: null,
            includePath: null,
            mask: null,
            scssRoot: [],
            outputStyle: 'compressed'
        });

        kssCmd.push(realPath + 'node_modules/kss/bin/kss-node');

        this.files.forEach(function(file) {
            kssCmd.push(file.src[0]);
            kssCmd.push(file.dest);
            dest = file.dest;
        });

        if (opts.template !== null) {
            kssCmd.push('--template', opts.template);
        }

        if (opts.mask !== null) {
            kssCmd.push('--mask', opts.mask);
        }

        if (opts.includeType !== null && opts.includePath !== null) {
            kssCmd.push('--' + opts.includeType, opts.includePath);
        }

        var putInfo = function(error, result, code) {
            if (error !== null) {
                grunt.log.error(error);
                grunt.log.error('Code: ' + code);
            } else {
                grunt.log.write(result);
            }

            // Compile scss file if include type is "scss".
            if (opts.includeType === 'scss' && path.extname(opts.includePath) === '.scss') {
                opts.scssRoot = opts.scssRoot.map(function(root) {
                    return path.resolve(process.cwd() + '/' + root);
                });

                grunt.log.writeln('Scss includes compilation.');
                grunt.log.writeln(opts.includePath + ' -> ' + dest.replace(/\/$/, '') + '/public/style.css');

                grunt.file.write(
                    dest.replace(/\/$/, '') + '/public/style.css',
                    sass.compile(opts.includePath, opts.scssRoot, opts.outputStyle),
                    {encoding: 'utf8'}
                );
            }
            done();
        };

        // Execute!!
        exec(kssCmd.join(' '), putInfo);
        grunt.verbose.ok('`[KSS] ' + kssCmd.join(' ') + '` was initiated.');

    });
};
<commit_msg>Allows sub tasks to override includePath<commit_after>/*
 * grunt-kss
 * https://github.com/t32k/grunt-kss
 *
 * Copyright (c) 2013 Koji Ishimoto
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

    grunt.registerMultiTask('kss', 'Generate styleguide by KSS.', function() {

        var fs = require('fs'),
            path = require('path'),
            exec = require('child_process').exec,
            done = this.async();

        var kssCmd = ['node'],
            realPath = path.dirname(__filename).replace(/tasks$/g, ''),
            sass = require(realPath + '/lib/sass'),
            dest = process.cwd();

        var opts = this.options({
            template: null,
            includeType: null,
            includePath: null,
            mask: null,
            scssRoot: [],
            outputStyle: 'compressed'
        });

        // Allow sub tasks to override includePath
        if (this.data.includePath) {
            opts.includePath = this.data.includePath;
        }

        kssCmd.push(realPath + 'node_modules/kss/bin/kss-node');

        this.files.forEach(function(file) {
            kssCmd.push(file.src[0]);
            kssCmd.push(file.dest);
            dest = file.dest;
        });

        if (opts.template !== null) {
            kssCmd.push('--template', opts.template);
        }

        if (opts.mask !== null) {
            kssCmd.push('--mask', opts.mask);
        }

        if (opts.includeType !== null && opts.includePath !== null) {
            kssCmd.push('--' + opts.includeType, opts.includePath);
        }

        var putInfo = function(error, result, code) {
            if (error !== null) {
                grunt.log.error(error);
                grunt.log.error('Code: ' + code);
            } else {
                grunt.log.write(result);
            }

            // Compile scss file if include type is "scss".
            if (opts.includeType === 'scss' && path.extname(opts.includePath) === '.scss') {
                opts.scssRoot = opts.scssRoot.map(function(root) {
                    return path.resolve(process.cwd() + '/' + root);
                });

                grunt.log.writeln('Scss includes compilation.');
                grunt.log.writeln(opts.includePath + ' -> ' + dest.replace(/\/$/, '') + '/public/style.css');

                grunt.file.write(
                    dest.replace(/\/$/, '') + '/public/style.css',
                    sass.compile(opts.includePath, opts.scssRoot, opts.outputStyle),
                    {encoding: 'utf8'}
                );
            }
            done();
        };

        // Execute!!
        exec(kssCmd.join(' '), putInfo);
        grunt.verbose.ok('`[KSS] ' + kssCmd.join(' ') + '` was initiated.');

    });
};
<|endoftext|>


<commit_before>var babel = require('gulp-babel');
var del = require('del');

module.exports = function(gulp, config) {

	gulp.task('clean:lib', function(done) {
		del([config.component.lib], done);
	});

	gulp.task('build:lib', function() {
		return gulp.src([
				config.component.src + '/**/*.js',
				'!**/__tests__/**/*'
			])
			.pipe(babel({
				plugins: [require('babel-plugin-object-assign')]
			}))
			.pipe(gulp.dest(config.component.lib));
	});

}
<commit_msg>Adding watch:lib task<commit_after>var babel = require('gulp-babel');
var del = require('del');

module.exports = function(gulp, config) {

	gulp.task('clean:lib', function(done) {
		del([config.component.lib], done);
	});

	gulp.task('build:lib', function() {
		return gulp.src([
				config.component.src + '/**/*.js',
				'!**/__tests__/**/*'
			])
			.pipe(babel({
				plugins: [require('babel-plugin-object-assign')]
			}))
			.pipe(gulp.dest(config.component.lib));
	});

	gulp.task('watch:lib', ['build:lib'], function() {
		return gulp.watch([
				config.component.src + '/**/*.js',
				'!**/__tests__/**/*'
			], ['build:lib']);
	});

}
<|endoftext|>


<commit_before>'use strict'

const _ = require('lodash')
const fs = require('fs-extra')
const os = require('os')
const path = require('path')
const temp = require('temp')

const installer = require('../..')

module.exports = function describeInstaller (description, installerOptions, itDescription, itFunc) {
  describe(description, test => {
    const outputDir = module.exports.tempOutputDir(installerOptions.dest)

    before(done => {
      const options = module.exports.testInstallerOptions(outputDir, installerOptions)

      installer(options, done)
    })

    it(itDescription, done => {
      itFunc(outputDir, done)
    })

    module.exports.cleanupOutputDir(outputDir)
  })
}

module.exports.cleanupOutputDir = function cleanupOutputDir (outputDir) {
  after(done => {
    fs.remove(outputDir, done)
  })
}

module.exports.tempOutputDir = function tempOutputDir (customDir) {
  return customDir ? path.join(os.tmpdir(), customDir) : temp.path({prefix: 'electron-installer-debian-'})
}

module.exports.testInstallerOptions = function testInstallerOptions (outputDir, installerOptions) {
  return _.merge({
    dest: outputDir,
    rename: debFile => {
      return path.join(debFile, '<%= name %>_<%= arch %>.deb')
    },
    options: {
      arch: 'amd64'
    }
  }, installerOptions)
}
<commit_msg>outputDir must always be dest for testInstallerOptions<commit_after>'use strict'

const _ = require('lodash')
const fs = require('fs-extra')
const os = require('os')
const path = require('path')
const temp = require('temp')

const installer = require('../..')

module.exports = function describeInstaller (description, installerOptions, itDescription, itFunc) {
  describe(description, test => {
    const outputDir = module.exports.tempOutputDir(installerOptions.dest)

    before(done => {
      const options = module.exports.testInstallerOptions(outputDir, installerOptions)

      installer(options, done)
    })

    it(itDescription, done => {
      itFunc(outputDir, done)
    })

    module.exports.cleanupOutputDir(outputDir)
  })
}

module.exports.cleanupOutputDir = function cleanupOutputDir (outputDir) {
  after(done => {
    fs.remove(outputDir, done)
  })
}

module.exports.tempOutputDir = function tempOutputDir (customDir) {
  return customDir ? path.join(os.tmpdir(), customDir) : temp.path({prefix: 'electron-installer-debian-'})
}

module.exports.testInstallerOptions = function testInstallerOptions (outputDir, installerOptions) {
  return _.merge({
    rename: debFile => {
      return path.join(debFile, '<%= name %>_<%= arch %>.deb')
    },
    options: {
      arch: 'amd64'
    }
  }, installerOptions, {dest: outputDir})
}
<|endoftext|>


<commit_before>var argon2 = process.env.ARGON2_COVERAGE
  ? require('./index-cov')
  : require('./index');

module.exports = {
  test_hash: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.equal(hash, "$argon2i$m=4096,t=3,p=1$c29tZXNhbHQAAAAAAAAAAA$FHF/OZ0GJpMRAlBmPTqXxw36Ftp87JllALZPcP9w9gs",
        "Hash should be equal to expected.");
      assert.equal(undefined, err, "Error should not be defined.");
      assert.done();
    });
  },

  test_hash_argon2d: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      argon2d: true
    }, function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.ok(/\$argon2d\$/.test(hash), "Hash should use argon2d signature.");
      assert.equal(undefined, err, "Error should not be defined.");
      assert.done();
    });
  },

  test_hash_long_salt: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesaltwaytoobig", function (err, hash) {
      assert.ok(err, "Error should be defined.");
      assert.equal(err.message, "Salt too long, maximum 16 characters.", "Error message should be equal to expected.");
      assert.equal(undefined, hash, "Hash should not be defined.");
      assert.done();
    });
  },

  test_hash_time_cost: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      timeCost: 4
    }, function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.ok(/m=4096,t=4,p=1/.test(hash), "Hash should have correct time cost.");
      assert.equal(undefined, err, "Error should not be defined.");
      assert.done();
    });
  },

  test_hash_invalid_time_cost: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      timeCost: "foo"
    }, function (err, hash) {
      assert.ok(err, "Error should be defined.");
      assert.equal(err.message, "Invalid time cost, must be a number.", "Error message should be equal to expected.");
      assert.equal(undefined, hash, "Hash should not be defined.");
      assert.done();
    });
  },

  test_hash_memory_cost: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      memoryCost: 13
    }, function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.ok(/m=8192,t=3,p=1/.test(hash), "Hash should have correct memory cost.");
      assert.equal(undefined, err, "Error should not be defined.");
      assert.done();
    });
  },

  test_hash_invalid_memory_cost: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      memoryCost: "foo"
    }, function (err, hash) {
      assert.ok(err, "Error should be defined.");
      assert.equal(err.message, "Invalid memory cost, must be a number.", "Error message should be equal to expected.");
      assert.equal(undefined, hash, "Hash should not be defined.");
      assert.done();
    });
  },

  test_hash_high_memory_cost: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      memoryCost: 32
    }, function (err, hash) {
      assert.ok(err, "Error should be defined.");
      assert.equal(err.message, "Memory cost too high, maximum of 32.", "Error message should be equal to expected.");
      assert.equal(undefined, hash, "Hash should not be defined.");
      assert.done();
    });
  },

  test_hash_parallelism: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      parallelism: 2
    }, function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.ok(/m=4096,t=3,p=2/.test(hash), "Hash should have correct parallelism.");
      assert.equal(undefined, err, "Error should not be defined.");
      assert.done();
    });
  },

  test_hash_invalid_parallelism: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      parallelism: "foo"
    }, function (err, hash) {
      assert.ok(err, "Error should be defined.");
      assert.equal(err.message, "Invalid parallelism, must be a number.", "Error message should be equal to expected.");
      assert.equal(undefined, hash, "Hash should not be defined.");
      assert.done();
    });
  },

  test_hash_all_options: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      timeCost: 4,
      memoryCost: 13,
      parallelism: 2
    }, function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.ok(/m=8192,t=4,p=2/.test(hash), "Hash should have correct options.");
      assert.equal(undefined, err, "Error should not be defined.");
      assert.done();
    });
  },

  test_hash_sync: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt");
    assert.equal(hash, "$argon2i$m=4096,t=3,p=1$c29tZXNhbHQAAAAAAAAAAA$FHF/OZ0GJpMRAlBmPTqXxw36Ftp87JllALZPcP9w9gs",
      "Hash should be equal to expected.");
    assert.done();
  },

  test_hash_argon2d_sync: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt", {
      argon2d: true
    });
    assert.ok(/\$argon2d\$/.test(hash), "Hash should use argon2d signature.");
    assert.done();
  },

  test_hash_sync_time_cost: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt", {
      timeCost: 4
    });
    assert.ok(/m=4096,t=4,p=1/.test(hash), "Hash should have correct time cost.");
    assert.done();
  },

  test_hash_sync_invalid_time_cost: function (assert) {
    "use strict";

    assert.expect(1);

    assert.throws(function () {
      var hash = argon2.encryptSync("password", "somesalt", {
        timeCost: "foo"
      });
    }, Error, "Error should be thrown.");
    assert.done();
  },

  test_hash_sync_memory_cost: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt", {
      memoryCost: 13
    });
    assert.ok(/m=8192,t=3,p=1/.test(hash), "Hash should have correct memory cost.");
    assert.done();
  },

  test_hash_sync_invalid_memory_cost: function (assert) {
    "use strict";

    assert.expect(1);

    assert.throws(function () {
      var hash = argon2.encryptSync("password", "somesalt", {
        memoryCost: "foo"
      });
    }, Error, "Error should be thrown.");
    assert.done();
  },

  test_hash_sync_high_memory_cost: function (assert) {
    "use strict";

    assert.expect(1);

    assert.throws(function () {
      argon2.encryptSync("password", "somesalt", {
        memoryCost: 32
      });
    }, Error, "Error should be thrown.");
    assert.done();
  },

  test_hash_sync_parallelism: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt", {
      parallelism: 2
    });
    assert.ok(/m=4096,t=3,p=2/.test(hash), "Hash should have correct parallelism.");
    assert.done();
  },

  test_hash_sync_invalid_parallelism: function (assert) {
    "use strict";

    assert.expect(1);

    assert.throws(function () {
      var hash = argon2.encryptSync("password", "somesalt", {
        parallelism: "foo"
      });
    }, Error, "Error should be thrown.");
    assert.done();
  },

  test_hash_sync_all_options: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt", {
      timeCost: 4,
      memoryCost: 13,
      parallelism: 2
    });
    assert.ok(/m=8192,t=4,p=2/.test(hash), "Hash should have correct options.");
    assert.done();
  },

  test_hash_sync_long_salt: function (assert) {
    "use strict";

    assert.expect(1);

    assert.throws(function () {
      argon2.encryptSync("password", "somesaltwaytoobig");
    }, Error, "Error should be thrown.");
    assert.done();
  },

  test_generate_salt: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.generateSalt(function (err, salt) {
      assert.ok(salt.length <= 16, "Generated salt length should be less than 16.");
      assert.done();
    });
  },

  test_generate_salt_sync: function (assert) {
    "use strict";

    assert.expect(1);

    assert.ok(argon2.generateSaltSync().length <= 16, "Generated salt length should be less than 16.");
    assert.done();
  },

  test_verify_ok: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.verify(
      "$argon2i$m=4096,t=3,p=1$c29tZXNhbHQAAAAAAAAAAA$FHF/OZ0GJpMRAlBmPTqXxw36Ftp87JllALZPcP9w9gs",
      "password", function (err) {
        assert.equal(undefined, err, "Error should be undefined.");
        assert.done();
      });
  },

  test_verify_fail: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.verify(
      "$argon2i$m=4096,t=3,p=1$c29tZXNhbHQAAAAAAAAAAA$FHF/OZ0GJpMRAlBmPTqXxw36Ftp87JllALZPcP9w9gs",
      "passwolrd", function (err) {
        assert.ok(err, "Error should be defined.");
        assert.done();
      });
  },

  test_verify_argon2d_ok: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.encrypt("password", "somesalt", {
      argon2d: true
    }, function (err, hash) {
      argon2.verify(hash, "password", function (err) {
        assert.equal(undefined, err, "Error should be undefined.");
        assert.done();
      });
    });
  },

  test_verify_argon2d_fail: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.encrypt("password", "somesalt", {
      argon2d: true
    }, function (err, hash) {
      argon2.verify(hash, "passwolrd", function (err) {
        assert.ok(err, "Error should be defined.");
        assert.done();
      });
    });
  },

  test_verify_sync_ok: function (assert) {
    "use strict";

    assert.expect(1);

    assert.equal(true, argon2.verifySync(
      "$argon2i$m=4096,t=3,p=1$c29tZXNhbHQAAAAAAAAAAA$FHF/OZ0GJpMRAlBmPTqXxw36Ftp87JllALZPcP9w9gs",
      "password"));
    assert.done();
  },

  test_verify_sync_fail: function (assert) {
    "use strict";

    assert.expect(1);

    assert.equal(false, argon2.verifySync(
      "$argon2i$m=4096,t=3,p=1$c29tZXNhbHQAAAAAAAAAAA$FHF/OZ0GJpMRAlBmPTqXxw36Ftp87JllALZPcP9w9gs",
      "passwolrd"));
    assert.done();
  },

  test_verify_argon2d_sync_ok: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.encrypt("password", "somesalt", {
      argon2d: true
    }, function (err, hash) {
      assert.equal(true, argon2.verifySync(hash, "password"));
      assert.done();
    });
  },

  test_verify_argon2d_sync_fail: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.encrypt("password", "somesalt", {
      argon2d: true
    }, function (err, hash) {
      assert.equal(false, argon2.verifySync(hash, "passwolrd"));
      assert.done();
    });
  }
};
<commit_msg>Remove redundant failure messages, rewrite others<commit_after>var argon2 = process.env.ARGON2_COVERAGE
  ? require('./index-cov')
  : require('./index');

module.exports = {
  test_hash: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.equal(hash, "$argon2i$m=4096,t=3,p=1$c29tZXNhbHQAAAAAAAAAAA$FHF/OZ0GJpMRAlBmPTqXxw36Ftp87JllALZPcP9w9gs");
      assert.equal(undefined, err);
      assert.done();
    });
  },

  test_hash_argon2d: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      argon2d: true
    }, function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.ok(/\$argon2d\$/.test(hash), "Should have argon2d signature.");
      assert.equal(undefined, err);
      assert.done();
    });
  },

  test_hash_long_salt: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesaltwaytoobig", function (err, hash) {
      assert.ok(err, "Error should be defined.");
      assert.equal(err.message, "Salt too long, maximum 16 characters.");
      assert.equal(undefined, hash);
      assert.done();
    });
  },

  test_hash_time_cost: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      timeCost: 4
    }, function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.ok(/m=4096,t=4,p=1/.test(hash), "Should have correct time cost.");
      assert.equal(undefined, err);
      assert.done();
    });
  },

  test_hash_invalid_time_cost: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      timeCost: "foo"
    }, function (err, hash) {
      assert.ok(err, "Error should be defined.");
      assert.equal(err.message, "Invalid time cost, must be a number.");
      assert.equal(undefined, hash);
      assert.done();
    });
  },

  test_hash_memory_cost: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      memoryCost: 13
    }, function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.ok(/m=8192,t=3,p=1/.test(hash), "Should have correct memory cost.");
      assert.equal(undefined, err);
      assert.done();
    });
  },

  test_hash_invalid_memory_cost: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      memoryCost: "foo"
    }, function (err, hash) {
      assert.ok(err, "Error should be defined.");
      assert.equal(err.message, "Invalid memory cost, must be a number.");
      assert.equal(undefined, hash);
      assert.done();
    });
  },

  test_hash_high_memory_cost: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      memoryCost: 32
    }, function (err, hash) {
      assert.ok(err, "Error should be defined.");
      assert.equal(err.message, "Memory cost too high, maximum of 32.");
      assert.equal(undefined, hash);
      assert.done();
    });
  },

  test_hash_parallelism: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      parallelism: 2
    }, function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.ok(/m=4096,t=3,p=2/.test(hash), "Should have correct parallelism.");
      assert.equal(undefined, err);
      assert.done();
    });
  },

  test_hash_invalid_parallelism: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      parallelism: "foo"
    }, function (err, hash) {
      assert.ok(err, "Error should be defined.");
      assert.equal(err.message, "Invalid parallelism, must be a number.");
      assert.equal(undefined, hash);
      assert.done();
    });
  },

  test_hash_all_options: function (assert) {
    "use strict";

    assert.expect(3);

    argon2.encrypt("password", "somesalt", {
      timeCost: 4,
      memoryCost: 13,
      parallelism: 2
    }, function (err, hash) {
      assert.ok(hash, "Hash should be defined.");
      assert.ok(/m=8192,t=4,p=2/.test(hash), "Should have correct options.");
      assert.equal(undefined, err);
      assert.done();
    });
  },

  test_hash_sync: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt");
    assert.equal(hash, "$argon2i$m=4096,t=3,p=1$c29tZXNhbHQAAAAAAAAAAA$FHF/OZ0GJpMRAlBmPTqXxw36Ftp87JllALZPcP9w9gs");
    assert.done();
  },

  test_hash_argon2d_sync: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt", {
      argon2d: true
    });
    assert.ok(/\$argon2d\$/.test(hash), "Should use argon2d signature.");
    assert.done();
  },

  test_hash_sync_time_cost: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt", {
      timeCost: 4
    });
    assert.ok(/m=4096,t=4,p=1/.test(hash), "Should have correct time cost.");
    assert.done();
  },

  test_hash_sync_invalid_time_cost: function (assert) {
    "use strict";

    assert.expect(1);

    assert.throws(function () {
      var hash = argon2.encryptSync("password", "somesalt", {
        timeCost: "foo"
      });
    });
    assert.done();
  },

  test_hash_sync_memory_cost: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt", {
      memoryCost: 13
    });
    assert.ok(/m=8192,t=3,p=1/.test(hash), "Should have correct memory cost.");
    assert.done();
  },

  test_hash_sync_invalid_memory_cost: function (assert) {
    "use strict";

    assert.expect(1);

    assert.throws(function () {
      var hash = argon2.encryptSync("password", "somesalt", {
        memoryCost: "foo"
      });
    });
    assert.done();
  },

  test_hash_sync_high_memory_cost: function (assert) {
    "use strict";

    assert.expect(1);

    assert.throws(function () {
      argon2.encryptSync("password", "somesalt", {
        memoryCost: 32
      });
    });
    assert.done();
  },

  test_hash_sync_parallelism: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt", {
      parallelism: 2
    });
    assert.ok(/m=4096,t=3,p=2/.test(hash), "Should have correct parallelism.");
    assert.done();
  },

  test_hash_sync_invalid_parallelism: function (assert) {
    "use strict";

    assert.expect(1);

    assert.throws(function () {
      var hash = argon2.encryptSync("password", "somesalt", {
        parallelism: "foo"
      });
    });
    assert.done();
  },

  test_hash_sync_all_options: function (assert) {
    "use strict";

    assert.expect(1);

    var hash = argon2.encryptSync("password", "somesalt", {
      timeCost: 4,
      memoryCost: 13,
      parallelism: 2
    });
    assert.ok(/m=8192,t=4,p=2/.test(hash), "Should have correct options.");
    assert.done();
  },

  test_hash_sync_long_salt: function (assert) {
    "use strict";

    assert.expect(1);

    assert.throws(function () {
      argon2.encryptSync("password", "somesaltwaytoobig");
    });
    assert.done();
  },

  test_generate_salt: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.generateSalt(function (err, salt) {
      assert.ok(salt.length <= 16);
      assert.done();
    });
  },

  test_generate_salt_sync: function (assert) {
    "use strict";

    assert.expect(1);

    assert.ok(argon2.generateSaltSync().length <= 16);
    assert.done();
  },

  test_verify_ok: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.verify(
      "$argon2i$m=4096,t=3,p=1$c29tZXNhbHQAAAAAAAAAAA$FHF/OZ0GJpMRAlBmPTqXxw36Ftp87JllALZPcP9w9gs",
      "password", function (err) {
        assert.equal(undefined, err);
        assert.done();
      });
  },

  test_verify_fail: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.verify(
      "$argon2i$m=4096,t=3,p=1$c29tZXNhbHQAAAAAAAAAAA$FHF/OZ0GJpMRAlBmPTqXxw36Ftp87JllALZPcP9w9gs",
      "passwolrd", function (err) {
        assert.ok(err, "Error should be defined.");
        assert.done();
      });
  },

  test_verify_argon2d_ok: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.encrypt("password", "somesalt", {
      argon2d: true
    }, function (err, hash) {
      argon2.verify(hash, "password", function (err) {
        assert.equal(undefined, err);
        assert.done();
      });
    });
  },

  test_verify_argon2d_fail: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.encrypt("password", "somesalt", {
      argon2d: true
    }, function (err, hash) {
      argon2.verify(hash, "passwolrd", function (err) {
        assert.ok(err, "Error should be defined.");
        assert.done();
      });
    });
  },

  test_verify_sync_ok: function (assert) {
    "use strict";

    assert.expect(1);

    assert.equal(true, argon2.verifySync(
      "$argon2i$m=4096,t=3,p=1$c29tZXNhbHQAAAAAAAAAAA$FHF/OZ0GJpMRAlBmPTqXxw36Ftp87JllALZPcP9w9gs",
      "password"));
    assert.done();
  },

  test_verify_sync_fail: function (assert) {
    "use strict";

    assert.expect(1);

    assert.equal(false, argon2.verifySync(
      "$argon2i$m=4096,t=3,p=1$c29tZXNhbHQAAAAAAAAAAA$FHF/OZ0GJpMRAlBmPTqXxw36Ftp87JllALZPcP9w9gs",
      "passwolrd"));
    assert.done();
  },

  test_verify_argon2d_sync_ok: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.encrypt("password", "somesalt", {
      argon2d: true
    }, function (err, hash) {
      assert.equal(true, argon2.verifySync(hash, "password"));
      assert.done();
    });
  },

  test_verify_argon2d_sync_fail: function (assert) {
    "use strict";

    assert.expect(1);

    argon2.encrypt("password", "somesalt", {
      argon2d: true
    }, function (err, hash) {
      assert.equal(false, argon2.verifySync(hash, "passwolrd"));
      assert.done();
    });
  }
};
<|endoftext|>


<commit_before>var should = require('chai').should();
require('fake-dom');
document.getElementsByTagName('body')[0].setAttribute('id','stats');
require('../scripts/game')
describe('game', function() {
  it('game should be an object', function() {
    game.should.be.a('object');
  });
  //functions
  describe('#tick()', function() {
    it('tick should be a function', function() {
      game.tick.should.be.a('function');
    });
  });
  describe('#resource()', function() {
    it('resource should be a function', function() {
      game.resource.should.be.a('function');
    });
  });
  describe('#modifier()', function() {
    it('modifier should be a function', function() {
      game.modifier.should.be.a('function');
    });
  });
  //data
  describe('#resources', function() {
    it('resources should be an object', function() {
      game.resources.should.be.a('object');
    });
  });
});
<commit_msg>Update game.js<commit_after>var should = require('chai').should();
require('fake-dom');
document.getElementsByTagName('body')[0].setAttribute('id','stats');
describe('game', function() {
  var game = require('../modules/game');
  var fakeBody = document.getElementsByTagName('body')[0];
  it('game should be an function', function() {
    game.should.be.a('function');
  });
  //functions
  describe('#tick()', function() {
    it('tick should be a function', function() {
      game(fakeBody).tick.should.be.a('function');
    });
  });
  //data
  describe('#resources', function() {
    it('resources should be an object', function() {
      game(fakeBody).resources.should.be.a('object');
    });
  });
});
<|endoftext|>


<commit_before>
describe('subscribe suite', function() {

	var bugle,

	type = function(val) {
		return Object.prototype.toString.call(val).slice(8, -1);
	},

	build = function(n, fn) {
		var arr = [];

		while(n) {
			arr.push(fn);
			n--;
		}

		return arr;
	},

	subAll = function(bugle, topic, arr) {

		while(arr.length) {
			bugle.sub(topic, arr.shift());
		}
	},

	topic = function(bugle, topic) {

		topic = bugle.topics[topic];

		return {

			'len': function() {
				return topic.length;
			},

			'take': function(n) {
				return topic.splice(0, Math.min(this.len(), n));
			}
		};
	};

	beforeEach(function() {

		bugle = Bugle.extend({

			'_constructor': function(a, b) {
				this.a = a;
				this.b = b;
			},

			'listen': function() {
				this.sub('values', this.update)
			},

			'update': function(a, b) {
				this.a = a;
				this.b = b;
			}
		})(1,2);
	});

	it("should start with an empty state", function() {

		expect(bugle.oId).toBe(0);
		expect(bugle.topics).toEqual([]);
	});

	it("can subscribe an anonymous function to a topic", function() {

		bugle.sub('values', function() { });

		var values = topic(bugle, 'values'),
		topicLen = values.len(),
		sample = values.take(1)[0];

		expect(topicLen).toBe(1);

		expect(sample.fn).toBeDefined();
		expect(type(sample.fn)).toBe('Function');
	});

	it("can subscribe an object method to a topic", function() {

		// subscribe bugle to 'values' topic
		bugle.listen();

		var values = topic(bugle, 'values'),
		topicLen = values.len(),
		sample = values.take(1)[0];

		expect(topicLen).toBe(1);

		expect(sample.fn).toBeDefined();
		expect(type(sample.fn)).toBe('Function');

	});

	it('can have multiple subscriptions to a topic', function() {

		var SAMPLE_LENGTH = 100,
		SUBSET_LENGTH = 50,

		functionsArr = build(SAMPLE_LENGTH, function() { });

		subAll(bugle, 'multiples', functionsArr);

		var multiples = topic(bugle, 'multiples'),
		len = multiples.len(),
		sample = multiples.take(SUBSET_LENGTH);

		expect(len).toBe(SAMPLE_LENGTH);

		for(var ith = 0; ith < SUBSET_LENGTH; ith++) {

			expect(sample[ith].fn).toBeDefined();
			expect(type(sample[ith].fn)).toBe('Function');
		}
	});

});<commit_msg>added more tests to jasmine subscribe spec<commit_after>
describe('subscribe suite', function() {

	var bugle,

	type = function(val) {
		return Object.prototype.toString.call(val).slice(8, -1);
	},

	build = function(n, fn) {
		var arr = [];

		while(n) {
			arr.push(fn);
			n--;
		}

		return arr;
	},

	subAll = function(topic, arr) {

		while(arr.length) {
			bugle.sub(topic, arr.shift());
		}
	},

	topic = function(topic) {

		topic = bugle.topics[topic];

		return {

			'len': function() {
				return topic.length;
			},

			'take': function(n) {
				return topic.splice(0, Math.min(this.len(), n));
			}
		};
	};

	beforeEach(function() {

		bugle = Bugle.extend({

			'_constructor': function(a, b) {
				this.a = a;
				this.b = b;
			},

			'listen': function() {
				this.sub('values', this.update)
			},

			'update': function(a, b) {
				this.a = a;
				this.b = b;
			}
		})(1,2);
	});

	it("should start with an empty state", function() {

		expect(bugle.oId).toBe(0);
		expect(bugle.topics).toEqual([]);
	});

	it("can subscribe an anonymous function to a topic", function() {

		bugle.sub('values', function() { });

		var values = topic('values'),
		topicLen = values.len(),
		sub = values.take(1)[0];

		expect(topicLen).toBe(1);
		expect(type(sub.fn)).toBe('Function');
	});

	it("can subscribe a named function to a topic", function() {

		function namedTest() { };

		bugle.sub('named', namedTest);

		var named = topic('named'),
		len = named.len(),
		sub = named.take(1)[0];

		expect(len).toBe(1);
		expect(type(sub.fn)).toBe('Function');
	});

	it("can subscribe an object method to a topic", function() {

		// subscribe bugle to 'values' topic
		bugle.listen();

		var values = topic('values'),
		topicLen = values.len(),
		sub = values.take(1)[0];

		expect(topicLen).toBe(1);
		expect(type(sub.fn)).toBe('Function');

	});

	it('can have multiple subscriptions to a topic', function() {

		var SAMPLE_LENGTH = 100,
		SUBSET_LENGTH = 50,

		functionsArr = build(SAMPLE_LENGTH, function() { });

		subAll('multiples', functionsArr);

		var multiples = topic('multiples'),
		len = multiples.len(),
		sample = multiples.take(SUBSET_LENGTH);

		expect(len).toBe(SAMPLE_LENGTH);

		for(var ith = 0; ith < SUBSET_LENGTH; ith++) {

			expect(type(sample[ith].fn)).toBe('Function');
		}
	});

	it('returns an object id (number) for each new subscription', function() {

		var oId = bugle.sub('oId', function() { });
		expect(type(oId)).toBe('Number');
	});

});<|endoftext|>


<commit_before>import assert from 'assert'
import join from '../lib/join'

describe.only('join', () => {
  it('joins base path and tokens', () => {
    assert.strictEqual(join('/foo', ['bar', 'foo']), '/foo/bar/foo');
    assert.strictEqual(join('/foo', ['bar']), '/foo/bar');
    assert.strictEqual(join(['foo'], ['bar']), '/foo/bar');
    assert.strictEqual(join(['foo'], 'bar'), '/foo/bar');
    assert.strictEqual(join('/foo', 'bar'), '/foo/bar');
    assert.strictEqual(join('/foo', ['bar']), '/foo/bar');
    assert.strictEqual(join('/foo', []), '/foo');
    assert.strictEqual(join('', ['foo']), '/foo');

    assert.strictEqual(join('', ['0']), '/0');
    assert.strictEqual(join('/0', ['foo']), '/0/foo');
  })
})
<commit_msg>remove test only (#8)<commit_after>import assert from 'assert'
import join from '../lib/join'

describe('join', () => {
  it('joins base path and tokens', () => {
    assert.strictEqual(join('/foo', ['bar', 'foo']), '/foo/bar/foo');
    assert.strictEqual(join('/foo', ['bar']), '/foo/bar');
    assert.strictEqual(join(['foo'], ['bar']), '/foo/bar');
    assert.strictEqual(join(['foo'], 'bar'), '/foo/bar');
    assert.strictEqual(join('/foo', 'bar'), '/foo/bar');
    assert.strictEqual(join('/foo', ['bar']), '/foo/bar');
    assert.strictEqual(join('/foo', []), '/foo');
    assert.strictEqual(join('', ['foo']), '/foo');

    assert.strictEqual(join('', ['0']), '/0');
    assert.strictEqual(join('/0', ['foo']), '/0/foo');
  })
})
<|endoftext|>


<commit_before>import HTML5Video from 'playbacks/html5_video'
import Events from 'base/events.js'

import $ from 'clappr-zepto'

describe('HTML5Video playback', function() {
  beforeEach(function() {
    this.options = {src: 'http://example.com/dash.ogg'}
  })

  it('checks if it can play a resource', function() {
    expect(HTML5Video.canPlay('')).to.be.false
    expect(HTML5Video.canPlay('resource_without_dots')).to.be.false
    expect(HTML5Video.canPlay('http://domain.com/video.ogv')).to.be.true
    expect(HTML5Video.canPlay('http://domain.com/video.ogv?query_string=here')).to.be.true
    expect(HTML5Video.canPlay('/relative/video.ogv')).to.be.true
  })

  it('checks if it can play a resource with mime-type', function() {
    expect(HTML5Video.canPlay('resource_without_dots', 'video/ogg; codecs="theora, vorbis"')).to.be.true
  })

  it('does set a valid src to video element', function() {
    const playback = new HTML5Video(this.options)
    expect(playback._src).to.be.equals('http://example.com/dash.ogg')
  })

  it('starts not ready', function() {
    const playback = new HTML5Video(this.options)

    expect(playback.isReady).to.be.undefined
  })

  it('can be ready', function() {
    const playback = new HTML5Video(this.options)
    playback._ready()

    expect(playback.isReady).to.be.true
  })

  it('triggers PLAYBACK_PLAY_INTENT on play request', function() {
    let thereWasPlayIntent = false
    const playback = new HTML5Video(this.options)

    playback.on(Events.PLAYBACK_PLAY_INTENT, function() {
      thereWasPlayIntent = true
    })

    playback.play()

    expect(thereWasPlayIntent).to.be.true
  })

  it('isPlaying() is true after constructor when autoPlay is true', function(done) {
    const playback = new HTML5Video({src: 'http://example.com/dash.ogg', autoPlay: true})
    process.nextTick(function(){
      expect(playback.isPlaying()).to.be.true
      done()
    })
  })

  it('setup crossorigin attribute', function() {
    const options = $.extend({playback: {crossOrigin: 'use-credentials'}}, this.options)
    const playback = new HTML5Video(options)

    expect(playback.el.crossOrigin).to.be.equal('use-credentials')
    expect(playback.el.getAttribute('crossorigin')).equal('use-credentials')
  })

  it('enables inline playback for webviews when playInline flag is set', function() {
    const options = $.extend({playback: {playInline: true}}, this.options)
    const playback = new HTML5Video(options)

    expect(playback.el['x-webkit-playsinline']).to.be.true
    expect(playback.el.getAttribute('playsinline')).equal('playsinline')
  })

  it('allows displaying default video tag controls', function() {
    const options = $.extend({playback: {controls: 'controls'}}, this.options)
    const playback = new HTML5Video(options)
    expect(playback.el.controls).to.be.true
  })

  it('mute or unmute video element when volume is changed', function() {
    const playback = new HTML5Video(this.options)

    expect(playback.el.getAttribute('muted')).to.be.null
    expect(playback.el.muted).to.be.false
    playback.volume(0)
    expect(playback.el.getAttribute('muted')).equal('true')
    expect(playback.el.muted).to.be.true
    playback.volume(0.5)
    expect(playback.el.getAttribute('muted')).to.be.null
    expect(playback.el.muted).to.be.false
  })

  describe('progress', function() {
    let start, end, currentTime
    const duration = 300
    beforeEach(function() {
      this.playback = new HTML5Video(this.options)
      currentTime = 0
      start = [0]
      end = [30]
      const fakeEl = {
        get currentTime() { return currentTime },
        get duration() { return duration },
        get buffered() { return {start: (i) => start[i], end: (i) => end[i], get length() { return start.length }} }
      }
      this.playback.setElement(fakeEl)
    })

    it('should trigger PLAYBACK_PROGRESS with current buffer position', function() {
      let progress
      this.playback.on(Events.PLAYBACK_PROGRESS, function(currentProgress) {
        progress = currentProgress
      })
      this.playback._onProgress() // cannot trigger event on fake element (improve later?)
      expect(progress.start).to.be.equal(start[0])
      expect(progress.current).to.be.equal(end[0])
      expect(progress.total).to.be.equal(duration)
    })

    it('should find current buffer position', function() {
      start = [0, 50, 180]
      end = [30, 90, 280]
      currentTime = 75 // this should be located at index 1
      let progress
      this.playback.on(Events.PLAYBACK_PROGRESS, function(currentProgress) {
        progress = currentProgress
      })
      this.playback._onProgress() // cannot trigger event on fake element (improve later?)
      expect(progress.start).to.be.equal(start[1])
      expect(progress.current).to.be.equal(end[1])
    })

    it('should return an array of buffer segments as {start, end} objects', function() {
      start = [0, 50, 180]
      end = [30, 90, 280]
      let buffered
      this.playback.on(Events.PLAYBACK_PROGRESS, function(currentProgress, bufferedSegments) {
        buffered = bufferedSegments
      })
      this.playback._onProgress() // cannot trigger event on fake element (improve later?)
      expect(buffered.length).to.be.equal(start.length)
      expect(buffered[0]).to.deep.equal({start: start[0], end: end[0]})
      expect(buffered[1]).to.deep.equal({start: start[1], end: end[1]})
      expect(buffered[2]).to.deep.equal({start: start[2], end: end[2]})
    })
  })

  it('should be able to identify it can play resources independently of the file extension case', function() {
    expect(HTML5Video.canPlay('/relative/video.ogg')).to.be.true
    expect(HTML5Video.canPlay('/relative/VIDEO.OGG')).to.be.true
  })

  describe('options', function() {
    it('should use the playback object within player options', function() {
      const options = {
        src: 'http://example.com/video.m3u8',
        nonPlaybackOption: false,
        playback: {
          somePlaybackOption: true
        }
      }
      const html5Video = new HTML5Video(options)
      expect(html5Video.options.playback.somePlaybackOption).to.be.true
      expect(html5Video.options.playback).not.to.include.keys('nonPlaybackOption')
    })

    it('should use hlsjsConfig from player options as fallback', function() {
      const options = {
        src: 'http://example.com/video.m3u8',
        nonPlaybackOption: false,
        somePlaybackOption: true
      }
      const html5Video = new HTML5Video(options)
      expect(html5Video.options.playback.somePlaybackOption).to.be.true
      expect(html5Video.options.playback.nonPlaybackOption).to.be.false
    })
  })

  describe('video element', function() {
    it('should set src url from options', function() {
      const options = {
        src: 'http://example.com/some_source?query_string=here',
        mimeType: 'application/x-mpegURL'
      }
      const html5Video = new HTML5Video(options)
      html5Video.render()
      expect(html5Video.el.getAttribute('src')).to.be.equal(options.src)
    })

    it('should have src attribute removed after stop, and then added after play', function() {
      const options = {
        src: 'http://example.com/video.mp4'
      }
      const html5Video = new HTML5Video(options)
      html5Video.render()
      html5Video.play()
      html5Video.stop()
      expect(html5Video.el.hasAttribute('src')).to.be.false
      html5Video.play()
      expect(html5Video.el.getAttribute('src')).to.be.equal(options.src)
    })
  })

  describe('audio resources', function() {
    it('should be able to play audio resources', function() {
      expect(HTML5Video.canPlay('http://domain.com/Audio.oga')).to.be.true
      expect(HTML5Video.canPlay('http://domain.com/Audio.oga?query_string=here')).to.be.true
      expect(HTML5Video.canPlay('/relative/Audio.oga')).to.be.true
      expect(HTML5Video.canPlay('/relative/Audio.wav')).to.be.true
    })

    it('should play audio resources on an audio tag', function() {
      const options = { src: 'http://example.com/dash.oga' }
      const playback = new HTML5Video(options)
      expect(playback.tagName).to.be.equal('audio')
    })

    it('should use an audio tag when the audioOnly option is set to true', function() {
      const options = {
        src: 'http://example.com/dash.m3u8',
        playback: { audioOnly: true }
      }
      const playback = new HTML5Video(options)
      expect(playback.tagName).to.be.equal('audio')
    })

    it('should not play video resources on an audio tag if audioOnly flag is not set and a video mime-type is set', function() {
      const options = { src: 'http://example.com/video.mp4', mimeType: 'video/mp4' }
      const playback = new HTML5Video(options)
      expect(playback.isAudioOnly).to.be.false
      expect(playback.tagName).to.be.equal('video')
    })

    it('should play on audio tag if audioOnly flag is not set and the mime-type specified is audio only', function() {
      let options = { src: 'http://example.com/audio?some_parameter=value', mimeType: 'audio/ogg' },
        playback = new HTML5Video(options)
      expect(playback.isAudioOnly).to.be.true
      expect(playback.tagName).to.be.equal('audio')

      options = { src: 'http://example.com/audio?some_parameter=value', mimeType: 'audio/wav' }
      playback = new HTML5Video(options)
      expect(playback.isAudioOnly).to.be.true
      expect(playback.tagName).to.be.equal('audio')
    })

    it('should not play video resources on an audio tag if audioOnly flag is not set', function() {
      const options = { src: 'http://example.com/dash.m3u8' }
      const playback = new HTML5Video(options)
      expect(playback.isAudioOnly).to.be.false
      expect(playback.tagName).to.be.equal('video')
    })
  })
})
<commit_msg>test(html5_video_spec): adds text tracks tests<commit_after>import HTML5Video from 'playbacks/html5_video'
import Events from 'base/events.js'

import $ from 'clappr-zepto'

describe('HTML5Video playback', function() {
  beforeEach(function() {
    this.options = {src: 'http://example.com/dash.ogg'}
  })

  it('checks if it can play a resource', function() {
    expect(HTML5Video.canPlay('')).to.be.false
    expect(HTML5Video.canPlay('resource_without_dots')).to.be.false
    expect(HTML5Video.canPlay('http://domain.com/video.ogv')).to.be.true
    expect(HTML5Video.canPlay('http://domain.com/video.ogv?query_string=here')).to.be.true
    expect(HTML5Video.canPlay('/relative/video.ogv')).to.be.true
  })

  it('checks if it can play a resource with mime-type', function() {
    expect(HTML5Video.canPlay('resource_without_dots', 'video/ogg; codecs="theora, vorbis"')).to.be.true
  })

  it('does set a valid src to video element', function() {
    const playback = new HTML5Video(this.options)
    expect(playback._src).to.be.equals('http://example.com/dash.ogg')
  })

  it('starts not ready', function() {
    const playback = new HTML5Video(this.options)

    expect(playback.isReady).to.be.undefined
  })

  it('can be ready', function() {
    const playback = new HTML5Video(this.options)
    playback._ready()

    expect(playback.isReady).to.be.true
  })

  it('triggers PLAYBACK_PLAY_INTENT on play request', function() {
    let thereWasPlayIntent = false
    const playback = new HTML5Video(this.options)

    playback.on(Events.PLAYBACK_PLAY_INTENT, function() {
      thereWasPlayIntent = true
    })

    playback.play()

    expect(thereWasPlayIntent).to.be.true
  })

  it('isPlaying() is true after constructor when autoPlay is true', function(done) {
    const playback = new HTML5Video({src: 'http://example.com/dash.ogg', autoPlay: true})
    process.nextTick(function(){
      expect(playback.isPlaying()).to.be.true
      done()
    })
  })

  it('setup crossorigin attribute', function() {
    const options = $.extend({playback: {crossOrigin: 'use-credentials'}}, this.options)
    const playback = new HTML5Video(options)

    expect(playback.el.crossOrigin).to.be.equal('use-credentials')
    expect(playback.el.getAttribute('crossorigin')).equal('use-credentials')
  })

  it('enables inline playback for webviews when playInline flag is set', function() {
    const options = $.extend({playback: {playInline: true}}, this.options)
    const playback = new HTML5Video(options)

    expect(playback.el['x-webkit-playsinline']).to.be.true
    expect(playback.el.getAttribute('playsinline')).equal('playsinline')
  })

  it('allows displaying default video tag controls', function() {
    const options = $.extend({playback: {controls: 'controls'}}, this.options)
    const playback = new HTML5Video(options)
    expect(playback.el.controls).to.be.true
  })

  it('mute or unmute video element when volume is changed', function() {
    const playback = new HTML5Video(this.options)

    expect(playback.el.getAttribute('muted')).to.be.null
    expect(playback.el.muted).to.be.false
    playback.volume(0)
    expect(playback.el.getAttribute('muted')).equal('true')
    expect(playback.el.muted).to.be.true
    playback.volume(0.5)
    expect(playback.el.getAttribute('muted')).to.be.null
    expect(playback.el.muted).to.be.false
  })

  it('setup external tracks', function() {
    let newTrackUrl = () => { URL.createObjectURL(new Blob([], {type: 'text/vtt'})) }
    const options = $.extend({playback: {
      externalTracks: [
        {lang: 'en', label: 'English', src: newTrackUrl(), kind: 'subtitles'},
        {lang: 'fr', label: 'French', src: newTrackUrl()}
      ]
    }}, this.options)
    const playback = new HTML5Video(options)
    playback.render()
    const $tracks = playback.$el.find('track[data-html5-video-track]')

    expect($tracks[0].getAttribute('data-html5-video-track')).to.be.equal('0')
    expect($tracks[0].getAttribute('kind')).to.be.equal('subtitles')
    expect($tracks[0].getAttribute('label')).to.be.equal('English')
    expect($tracks[0].getAttribute('srclang')).to.be.equal('en')

    expect($tracks[1].getAttribute('data-html5-video-track')).to.be.equal('1')
    expect($tracks[1].getAttribute('kind')).to.be.equal('subtitles')
    expect($tracks[1].getAttribute('label')).to.be.equal('French')
    expect($tracks[1].getAttribute('srclang')).to.be.equal('fr')
  })

  it('can switch text tracks', function() {
    let newTrackUrl = () => { URL.createObjectURL(new Blob([], {type: 'text/vtt'})) }
    const options = $.extend({playback: {
      externalTracks: [
        {lang: 'en', label: 'English', src: newTrackUrl(), kind: 'subtitles'},
        {lang: 'fr', label: 'French', src: newTrackUrl()}
      ]
    }}, this.options)
    const playback = new HTML5Video(options)
    playback.render()

    expect(playback.hasClosedCaptionsTracks).to.be.true
    expect(playback.closedCaptionsTracks.length).equal(2)
    expect(playback.closedCaptionsTrackId).equal(-1)
    expect(playback.closedCaptionsTracks[0].track.mode).to.not.equal('showing')
    expect(playback.closedCaptionsTracks[1].track.mode).to.not.equal('showing')

    playback.closedCaptionsTrackId = 0
    expect(playback.closedCaptionsTrackId).equal(0)
    expect(playback.closedCaptionsTracks[0].track.mode).equal('showing')
    expect(playback.closedCaptionsTracks[1].track.mode).to.not.equal('showing')

    playback.closedCaptionsTrackId = 1
    expect(playback.closedCaptionsTrackId).equal(1)
    expect(playback.closedCaptionsTracks[0].track.mode).to.not.equal('showing')
    expect(playback.closedCaptionsTracks[1].track.mode).equal('showing')

    playback.closedCaptionsTrackId = -1
    expect(playback.closedCaptionsTrackId).equal(-1)
    expect(playback.closedCaptionsTracks[0].track.mode).to.not.equal('showing')
    expect(playback.closedCaptionsTracks[1].track.mode).to.not.equal('showing')
  })

  describe('progress', function() {
    let start, end, currentTime
    const duration = 300
    beforeEach(function() {
      this.playback = new HTML5Video(this.options)
      currentTime = 0
      start = [0]
      end = [30]
      const fakeEl = {
        get currentTime() { return currentTime },
        get duration() { return duration },
        get buffered() { return {start: (i) => start[i], end: (i) => end[i], get length() { return start.length }} }
      }
      this.playback.setElement(fakeEl)
    })

    it('should trigger PLAYBACK_PROGRESS with current buffer position', function() {
      let progress
      this.playback.on(Events.PLAYBACK_PROGRESS, function(currentProgress) {
        progress = currentProgress
      })
      this.playback._onProgress() // cannot trigger event on fake element (improve later?)
      expect(progress.start).to.be.equal(start[0])
      expect(progress.current).to.be.equal(end[0])
      expect(progress.total).to.be.equal(duration)
    })

    it('should find current buffer position', function() {
      start = [0, 50, 180]
      end = [30, 90, 280]
      currentTime = 75 // this should be located at index 1
      let progress
      this.playback.on(Events.PLAYBACK_PROGRESS, function(currentProgress) {
        progress = currentProgress
      })
      this.playback._onProgress() // cannot trigger event on fake element (improve later?)
      expect(progress.start).to.be.equal(start[1])
      expect(progress.current).to.be.equal(end[1])
    })

    it('should return an array of buffer segments as {start, end} objects', function() {
      start = [0, 50, 180]
      end = [30, 90, 280]
      let buffered
      this.playback.on(Events.PLAYBACK_PROGRESS, function(currentProgress, bufferedSegments) {
        buffered = bufferedSegments
      })
      this.playback._onProgress() // cannot trigger event on fake element (improve later?)
      expect(buffered.length).to.be.equal(start.length)
      expect(buffered[0]).to.deep.equal({start: start[0], end: end[0]})
      expect(buffered[1]).to.deep.equal({start: start[1], end: end[1]})
      expect(buffered[2]).to.deep.equal({start: start[2], end: end[2]})
    })
  })

  it('should be able to identify it can play resources independently of the file extension case', function() {
    expect(HTML5Video.canPlay('/relative/video.ogg')).to.be.true
    expect(HTML5Video.canPlay('/relative/VIDEO.OGG')).to.be.true
  })

  describe('options', function() {
    it('should use the playback object within player options', function() {
      const options = {
        src: 'http://example.com/video.m3u8',
        nonPlaybackOption: false,
        playback: {
          somePlaybackOption: true
        }
      }
      const html5Video = new HTML5Video(options)
      expect(html5Video.options.playback.somePlaybackOption).to.be.true
      expect(html5Video.options.playback).not.to.include.keys('nonPlaybackOption')
    })

    it('should use hlsjsConfig from player options as fallback', function() {
      const options = {
        src: 'http://example.com/video.m3u8',
        nonPlaybackOption: false,
        somePlaybackOption: true
      }
      const html5Video = new HTML5Video(options)
      expect(html5Video.options.playback.somePlaybackOption).to.be.true
      expect(html5Video.options.playback.nonPlaybackOption).to.be.false
    })
  })

  describe('video element', function() {
    it('should set src url from options', function() {
      const options = {
        src: 'http://example.com/some_source?query_string=here',
        mimeType: 'application/x-mpegURL'
      }
      const html5Video = new HTML5Video(options)
      html5Video.render()
      expect(html5Video.el.getAttribute('src')).to.be.equal(options.src)
    })

    it('should have src attribute removed after stop, and then added after play', function() {
      const options = {
        src: 'http://example.com/video.mp4'
      }
      const html5Video = new HTML5Video(options)
      html5Video.render()
      html5Video.play()
      html5Video.stop()
      expect(html5Video.el.hasAttribute('src')).to.be.false
      html5Video.play()
      expect(html5Video.el.getAttribute('src')).to.be.equal(options.src)
    })
  })

  describe('audio resources', function() {
    it('should be able to play audio resources', function() {
      expect(HTML5Video.canPlay('http://domain.com/Audio.oga')).to.be.true
      expect(HTML5Video.canPlay('http://domain.com/Audio.oga?query_string=here')).to.be.true
      expect(HTML5Video.canPlay('/relative/Audio.oga')).to.be.true
      expect(HTML5Video.canPlay('/relative/Audio.wav')).to.be.true
    })

    it('should play audio resources on an audio tag', function() {
      const options = { src: 'http://example.com/dash.oga' }
      const playback = new HTML5Video(options)
      expect(playback.tagName).to.be.equal('audio')
    })

    it('should use an audio tag when the audioOnly option is set to true', function() {
      const options = {
        src: 'http://example.com/dash.m3u8',
        playback: { audioOnly: true }
      }
      const playback = new HTML5Video(options)
      expect(playback.tagName).to.be.equal('audio')
    })

    it('should not play video resources on an audio tag if audioOnly flag is not set and a video mime-type is set', function() {
      const options = { src: 'http://example.com/video.mp4', mimeType: 'video/mp4' }
      const playback = new HTML5Video(options)
      expect(playback.isAudioOnly).to.be.false
      expect(playback.tagName).to.be.equal('video')
    })

    it('should play on audio tag if audioOnly flag is not set and the mime-type specified is audio only', function() {
      let options = { src: 'http://example.com/audio?some_parameter=value', mimeType: 'audio/ogg' },
        playback = new HTML5Video(options)
      expect(playback.isAudioOnly).to.be.true
      expect(playback.tagName).to.be.equal('audio')

      options = { src: 'http://example.com/audio?some_parameter=value', mimeType: 'audio/wav' }
      playback = new HTML5Video(options)
      expect(playback.isAudioOnly).to.be.true
      expect(playback.tagName).to.be.equal('audio')
    })

    it('should not play video resources on an audio tag if audioOnly flag is not set', function() {
      const options = { src: 'http://example.com/dash.m3u8' }
      const playback = new HTML5Video(options)
      expect(playback.isAudioOnly).to.be.false
      expect(playback.tagName).to.be.equal('video')
    })
  })
})
<|endoftext|>


<commit_before>Crafty.init(800, 600, 'game');

Crafty.e('Floor, 2D, Canvas, Color')
  .attr({x: 0, y: 250, w: 250, h: 10})
    .color('green');

    Crafty.e('2D, Canvas, Color, Fourway, Gravity')
      .attr({x: 0, y: 0, w: 50, h: 50})
    .color('#F00')
      .fourway(4)
    .gravity('Floor');
<commit_msg>whitespace<commit_after>Crafty.init(800, 600, 'game');

Crafty.e('Floor, 2D, Canvas, Color')
  .attr({x: 0, y: 250, w: 250, h: 10})
  .color('green');

Crafty.e('2D, Canvas, Color, Fourway, Gravity')
  .attr({x: 0, y: 0, w: 50, h: 50})
  .color('#F00')
  .fourway(4)
  .gravity('Floor');
<|endoftext|>