<commit_before>define([
	"engine/map/entity",
	"basic/mapbuilder",
	"physics/jello"
], function(
	Entity,
	MapBuilder,
	Jello
) {
	var Layer = mini.Class.subclass({
		initialize: function(name) {
			this.name = name || "";
			this.entities = [];
			this.enabled = true;

			this.zIndex = 0;
			this.scrollFactor = Jello.Vector2.One.copy();
			this.scale = Jello.Vector2.One.copy();
		},

		// Update all entities.
		update: function() {
			if(this.enabled) {
				env.camera.pushLayer(this);
				env.renderer.updateCanvasWorldAABB();
				if(typeof this.world !== "undefined")
					this.world.update(1/60); // env.time.timePassed

				// TODO: adjust to use dedicated getter and setter
				// update Floom fluid system
				if(typeof this.fluidSystem !== "undefined")
					this.fluidSystem.update(); // env.time.timePassed

				for(var index in this.entities) {
					if(!this.entities.hasOwnProperty(index)) continue;

					this.entities[index].update();
				}

				if(typeof this.interaction === "function")
					this.interaction.call(this);

				env.camera.popLayer();
			}
		},

		draw: function(renderer) {
			if(this.enabled) {
				env.camera.pushLayer(this);
				env.renderer.updateCanvasWorldAABB();
				env.renderer.pushLayer(this);

				// TODO: adjust to use dedicated getter and setter
				// draw Floom fluid system
				if(typeof this.fluidSystem !== "undefined")
					this.fluidSystem.draw(renderer);

				// draw Entities
				for(var index in this.entities) {
					if(!this.entities.hasOwnProperty(index)) continue;

					this.entities[index].draw(renderer);
				}

				env.renderer.popLayer();
				env.camera.popLayer();
			}
		},

		debugDraw: function(debugDraw) {
			if(this.enabled) {
				env.camera.pushLayer(this);
				env.renderer.updateCanvasWorldAABB();
				env.renderer.pushLayer(this);

				for(var index in this.entities) {
					if(!this.entities.hasOwnProperty(index)) continue;

					this.entities[index].debugDraw(debugDraw);
				}

				if(typeof this.world !== "undefined")
					this.world.debugDraw(debugDraw);

				env.renderer.popLayer();
				env.camera.popLayer();
			}
		},

		setWorld: function(world) {
			this.world = world;
			if(typeof Editor === "undefined")
				MapBuilder.setUpTestMap(this, this.world);

			return this;
		},

		getWorld: function() {
			return this.world;
		},

		/*
		 * Fluid System
		 */
		setFluidSystem: function(fluidSystem) {
			this.fluidSystem = fluidSystem;
		},

		getFluidSystem: function() {
			return this.fluidSystem;
		},

		/*
		 * Manage Entities
		 */
		addEntity: function(entity) {
			this.entities.push(entity);

			return this;
		},

		getEntities: function() {
			return this.entities;
		},

		getEntityWithName: function(name) {
			return this.getEntitiesWithName(name)[0];
		},

		getEntitiesWithName: function(name) {
			return _.filter(this.entities, function(entity) {
				return entity.name == name;
			}, this);
		},

		getEntityWithTag: function(tag) {
			return this.getEntitiesWithTag(tag)[0];
		},

		getEntitiesWithTag: function(tag) {
			return _.filter(this.entities, function(entity) {
				return entity.hasTag(tag);
			}, this);
		},

		/*
		 * Interactions
		 */
		setInteraction: function(callback) {
			this.interaction = callback;
		},

		/*
		 * Interaction and debug
		 */
		/*
		// TODO: redo or remove
		initMouseInteractionEditor: function(mouse, datGuiFolder) {
			if(typeof this.world === "undefined") return;
			var that = this;

			// interaction techniques
			var setSpawnPoint = new InteractionHandler();

			var createBody = new InteractionHandler()
				.name("CREATE BODY")
				.onPressed(function() {
					Jello.BodyFactory.createBluePrint()
						.world(that.world)
						.shape(new Jello.ClosedShape()
							.begin()
							.addVertex(new Jello.Vector2(-1, -1))
							.addVertex(new Jello.Vector2(-1,  1))
							.addVertex(new Jello.Vector2( 1,  1))
							.addVertex(new Jello.Vector2( 1, -1))
							.finish())
						.pointMasses(1)
						.translate(env.camera.screenToWorldCoordinates(env.input.mouse))
						.rotate(0)
						.scale(Jello.Vector2.One.copy())
						.isKinematic(false)
						.edgeSpringK(300.0)
						.edgeSpringDamp(5.0)
						.shapeSpringK(150.0)
						.shapeSpringDamp(5.0)
						.addInternalSpring(0, 2, 300, 10)
						.addInternalSpring(1, 3, 300, 10)
						.build();
				});

			var moveBody = new InteractionHandler()
				.name("MOVE BODY")
				.context({
					"world": this.world,
					"body": undefined,
					"screenStartCoordinates": Jello.Vector2.Zero.copy(),
					"screenCurrentCoordinates": Jello.Vector2.Zero.copy()
				})
				.onPressed(function() {
					// remenber body to move
					var answer = this.world.getClosestPointMass(env.camera.screenToWorldCoordinates(env.input.mouse));
					this.body = this.world.getBody(answer.bodyId);

					// remember start coordinate
					this.screenStartCoordinates.set(env.input.mouse);
					this.screenCurrentCoordinates = this.screenStartCoordinates.copy();
				})
				.onState(function() {
					if(typeof this.body !== "undefined") {
						// add the offset to the previous step of the cursor
						// to the body position (translated in world coordinates)
						var cursorOffsetInWorld = env.camera.screenToWorldCoordinates(env.input.mouse)
							.sub(env.camera.screenToWorldCoordinates(this.screenCurrentCoordinates));
						var pos = this.body.getDerivedPosition().copy().add(cursorOffsetInWorld);
						var angleInRadians = this.body.getDerivedAngle();
						var scale = this.body.getScale();

						// actual update of position (leave angle and scale unchanged)
						this.body.setPositionAngle(pos, angleInRadians, scale);

						// remember current coordinates
						this.screenCurrentCoordinates.set(env.input.mouse);

						// adjustments for rendering
						this.body.updateAABB(0, true);
					};
				});

			var deleteBody = new InteractionHandler()
				.name("DELETE BODY")
				.context({
					"world": this.world
				})
				.onPressed(function() {
					var answer = this.world.getClosestPointMass(env.camera.screenToWorldCoordinates(env.input.mouse));
					var body = this.world.getBody(answer.bodyId);
					this.world.removeBody(body);
				});

			var createPointMass = new InteractionHandler()
				.name("CREATE POINT MASS")
				.context({
					"world": this.world
				})
				.onPressed(function() {
					var answer = this.world.getClosestPointMass(env.camera.screenToWorldCoordinates(env.input.mouse));
					console.log(answer);
					var body = this.world.getBody(answer.bodyId);
					var baseShape = body.getBaseShape();
					body.setShape(baseShape.addVertex(new Jello.Vector2(0,0)));
				});

			var movePointMass = new InteractionHandler()
				.name("MOVE POINT MASS")
				.context({
					"world": this.world,
					"body": undefined,
					"pointMassId": 0,
					"screenCurrentCoordinates": Jello.Vector2.Zero.copy()
				})
				.onPressed(function() {
					var answer = this.world.getClosestPointMass(env.camera.screenToWorldCoordinates(env.input.mouse));
					this.body = this.world.getBody(answer.bodyId);
					this.pointMassId = answer.pointMassId;

					// remember current coordinates
					this.screenCurrentCoordinates.set(env.input.mouse);
				})
				.onState(function() {
					var angleInRadians = -this.body.getDerivedAngle();
					var cursorOffsetInWorld = env.camera.screenToWorldCoordinates(env.input.mouse)
						.sub(env.camera.screenToWorldCoordinates(this.screenCurrentCoordinates))
						.rotate(angleInRadians)
						.divVector(this.body.getScale());

					var baseShape = this.body.getBaseShape();
					baseShape.getVertices()[this.pointMassId].addSelf(cursorOffsetInWorld);
					this.body.setShape(baseShape, true);

					// remember current coordinates
					this.screenCurrentCoordinates.set(env.input.mouse);

					// adjustments for rendering
					this.body.updateAABB(0, true);
				});

			var deletePointMass = new InteractionHandler()
				.name("DELETE POINT MASS")
				.context({
					"world": this.world
				})
				.onPressed(function() {
					var answer = this.world.getClosestPointMass(env.camera.screenToWorldCoordinates(env.input.mouse));
					var body = this.world.getBody(answer.bodyId);
					var pointMassId = answer.pointMassId;
					var baseShape = body.getBaseShape();
					// do not delete the last point mass
					if(baseShape.getVertices().length > 1) {
						baseShape.mLocalVertices.splice( pointMassId, 1 );
						body.setShape(baseShape);
					};
				});

			var interactionTechniquesforDatGui = [
				setSpawnPoint,
				createBody,
				moveBody,
				deleteBody,
				createPointMass,
				movePointMass,
				deletePointMass,
				// TODO: create, delete Springs
			];

			mouse
				.onLeftClick(movePointMass)
				.onRightClick(moveBody)
				.initDatGui(datGuiFolder, interactionTechniquesforDatGui);

			return mouse;
		},
		*/

		initDatGui: function(mapFolder, index) {
			if(!Bloob.debug || !Bloob.debug.datGui) return;
			if(typeof this.world === "undefined") return;
			var layerFolder = mapFolder.addFolder('Layer' + index);
			layerFolder.open();
			layerFolder.add(Jello.Material.Default, 'friction').name('Friction').min(-2).max(2).listen().step(0.1);
			layerFolder.add(Jello.Material.Default, 'elasticity').name('Elasticity').min(-2).max(2).listen().step(0.1);
			layerFolder.add(this.world.gravitation, 'x').name('Gravitation_x').listen().min(-20).max(20).step(0.01);
			layerFolder.add(this.world.gravitation, 'y').name('Gravitation_y').listen().min(-20).max(20).step(0.01);
			layerFolder.add(this, 'zIndex').listen().min(0.01).max(20).step(0.01);
			layerFolder.add(this.scrollFactor, 'x').name('ScrollFactor_x').listen();
			layerFolder.add(this.scrollFactor, 'y').name('ScrollFactor_y').listen();
			layerFolder.add(this.scale, 'x').name('Scale_x').listen();
			layerFolder.add(this.scale, 'y').name('Scale_y').listen();
		}
	});

	Layer.prototype.toJson = function() {
		var json = {
			name: this.name,
			zIndex: this.zIndex,
			scrollFactor: this.scrollFactor.toJson(),
			scale: this.scale.toJson(),
			entities: []
		};

		// Serialize world if existing.
		if(typeof this.world !== "undefined")
			json.world = this.world.toJson();

		var entities = this.getEntities();
		for(var i = 0; i < entities.length; i++) {
			json.entities.push(entities[i].toJson());
		}
		return json;
	};

	Layer.fromJson = function(json) {
		var layer = new Layer(json.name);

		if(typeof json.world !== "undefined") {
			var world = Jello.World.fromJson(json.world);
			layer.setWorld(world);
		}
		if(typeof json.zIndex !== "undefined") {
			layer.zIndex = json.zIndex;
		}
		if(typeof json.scrollFactor !== "undefined") {
			layer.scrollFactor = Jello.Vector2.fromJson(json.scrollFactor);
		}
		if(typeof json.scale !== "undefined") {
			layer.scale = Jello.Vector2.fromJson(json.scale);
		}

		if(typeof json.entities !== "undefined") {
			for(var index in json.entities)
				Entity.fromJson(json.entities[index], layer.getWorld()).addToLayer(layer);
		}

		return layer;
	};

	Layer.WorldLayer = Layer;

	return Layer;
});
<commit_msg>removed unused methods in Layer<commit_after>define([
	"engine/map/entity",
	"basic/mapbuilder",
	"physics/jello"
], function(
	Entity,
	MapBuilder,
	Jello
) {
	var Layer = mini.Class.subclass({
		initialize: function(name) {
			this.name = name || "";
			this.entities = [];
			this.enabled = true;

			this.zIndex = 0;
			this.scrollFactor = Jello.Vector2.One.copy();
			this.scale = Jello.Vector2.One.copy();
		},

		// Update all entities.
		update: function() {
			if(this.enabled) {
				env.camera.pushLayer(this);
				env.renderer.updateCanvasWorldAABB();
				if(typeof this.world !== "undefined")
					this.world.update(1/60); // env.time.timePassed

				// TODO: adjust to use dedicated getter and setter
				// update Floom fluid system
				if(typeof this.fluidSystem !== "undefined")
					this.fluidSystem.update(); // env.time.timePassed

				for(var index in this.entities) {
					if(!this.entities.hasOwnProperty(index)) continue;

					this.entities[index].update();
				}

				if(typeof this.interaction === "function")
					this.interaction.call(this);

				env.camera.popLayer();
			}
		},

		draw: function(renderer) {
			if(this.enabled) {
				env.camera.pushLayer(this);
				env.renderer.updateCanvasWorldAABB();
				env.renderer.pushLayer(this);

				// TODO: adjust to use dedicated getter and setter
				// draw Floom fluid system
				if(typeof this.fluidSystem !== "undefined")
					this.fluidSystem.draw(renderer);

				// draw Entities
				for(var index in this.entities) {
					if(!this.entities.hasOwnProperty(index)) continue;

					this.entities[index].draw(renderer);
				}

				env.renderer.popLayer();
				env.camera.popLayer();
			}
		},

		debugDraw: function(debugDraw) {
			if(this.enabled) {
				env.camera.pushLayer(this);
				env.renderer.updateCanvasWorldAABB();
				env.renderer.pushLayer(this);

				for(var index in this.entities) {
					if(!this.entities.hasOwnProperty(index)) continue;

					this.entities[index].debugDraw(debugDraw);
				}

				if(typeof this.world !== "undefined")
					this.world.debugDraw(debugDraw);

				env.renderer.popLayer();
				env.camera.popLayer();
			}
		},

		setWorld: function(world) {
			this.world = world;
			if(typeof Editor === "undefined")
				MapBuilder.setUpTestMap(this, this.world);

			return this;
		},

		getWorld: function() {
			return this.world;
		},

		/*
		 * Fluid System
		 */
		setFluidSystem: function(fluidSystem) {
			this.fluidSystem = fluidSystem;
		},

		getFluidSystem: function() {
			return this.fluidSystem;
		},

		/*
		 * Manage Entities
		 */
		addEntity: function(entity) {
			this.entities.push(entity);

			return this;
		},

		getEntities: function() {
			return this.entities;
		},

		getEntityWithName: function(name) {
			return this.getEntitiesWithName(name)[0];
		},

		getEntitiesWithName: function(name) {
			return _.filter(this.entities, function(entity) {
				return entity.name == name;
			}, this);
		},

		getEntityWithTag: function(tag) {
			return this.getEntitiesWithTag(tag)[0];
		},

		getEntitiesWithTag: function(tag) {
			return _.filter(this.entities, function(entity) {
				return entity.hasTag(tag);
			}, this);
		},

		/*
		 * Interactions
		 */
		setInteraction: function(callback) {
			this.interaction = callback;
		},

		/*
		 * Interaction and debug
		 */
		initDatGui: function(mapFolder, index) {
			if(!Bloob.debug || !Bloob.debug.datGui) return;
			if(typeof this.world === "undefined") return;
			var layerFolder = mapFolder.addFolder('Layer' + index);
			layerFolder.open();
			layerFolder.add(Jello.Material.Default, 'friction').name('Friction').min(-2).max(2).listen().step(0.1);
			layerFolder.add(Jello.Material.Default, 'elasticity').name('Elasticity').min(-2).max(2).listen().step(0.1);
			layerFolder.add(this.world.gravitation, 'x').name('Gravitation_x').listen().min(-20).max(20).step(0.01);
			layerFolder.add(this.world.gravitation, 'y').name('Gravitation_y').listen().min(-20).max(20).step(0.01);
			layerFolder.add(this, 'zIndex').listen().min(0.01).max(20).step(0.01);
			layerFolder.add(this.scrollFactor, 'x').name('ScrollFactor_x').listen();
			layerFolder.add(this.scrollFactor, 'y').name('ScrollFactor_y').listen();
			layerFolder.add(this.scale, 'x').name('Scale_x').listen();
			layerFolder.add(this.scale, 'y').name('Scale_y').listen();
		}
	});

	Layer.prototype.toJson = function() {
		var json = {
			name: this.name,
			zIndex: this.zIndex,
			scrollFactor: this.scrollFactor.toJson(),
			scale: this.scale.toJson(),
			entities: []
		};

		// Serialize world if existing.
		if(typeof this.world !== "undefined")
			json.world = this.world.toJson();

		var entities = this.getEntities();
		for(var i = 0; i < entities.length; i++) {
			json.entities.push(entities[i].toJson());
		}
		return json;
	};

	Layer.fromJson = function(json) {
		var layer = new Layer(json.name);

		if(typeof json.world !== "undefined") {
			var world = Jello.World.fromJson(json.world);
			layer.setWorld(world);
		}
		if(typeof json.zIndex !== "undefined") {
			layer.zIndex = json.zIndex;
		}
		if(typeof json.scrollFactor !== "undefined") {
			layer.scrollFactor = Jello.Vector2.fromJson(json.scrollFactor);
		}
		if(typeof json.scale !== "undefined") {
			layer.scale = Jello.Vector2.fromJson(json.scale);
		}

		if(typeof json.entities !== "undefined") {
			for(var index in json.entities)
				Entity.fromJson(json.entities[index], layer.getWorld()).addToLayer(layer);
		}

		return layer;
	};

	Layer.WorldLayer = Layer;

	return Layer;
});
<|endoftext|>


<commit_before>'use strict';

const createError = require('http-errors');
const debug = require('debug')('wheatlessinv2:error-middleware');

module.exports = function(err, req, res, next) {
  debug('error middleware');

  console.error('msg:', err.message);
  console.error('name:', err.name);

  if (err.status) {
    res.status(err.status).send(err.name);
    next();
    return;
  }

  if (err.name === 'ValidationError') {
    err = createError(400, err.message);
    res.status(err.status).send(err.name);
    next();
    return;
  }

  err = createError(500, err.message);
  res.status(err.status).send(err.name);
  next();
};
<commit_msg>console.log -> debug<commit_after>'use strict';

const createError = require('http-errors');
const debug = require('debug')('wheatlessinv2:error-middleware');

module.exports = function(err, req, res, next) {
  debug('error middleware');

  debug('msg:', err.message);
  debug('name:', err.name);

  if (err.status) {
    res.status(err.status).send(err.name);
    next();
    return;
  }

  if (err.name === 'ValidationError') {
    err = createError(400, err.message);
    res.status(err.status).send(err.name);
    next();
    return;
  }

  err = createError(500, err.message);
  res.status(err.status).send(err.name);
  next();
};
<|endoftext|>


<commit_before>var Schema = require('../BaseSchema')
  , EqualitySchema = require('../patterns/equality')
  , anything = require('../patterns/anything').instance

var ArraySchema = module.exports = Schema.extensions.ArraySchema = Schema.extend({
  initialize : function(itemSchema, max, min) {
    this.itemSchema = itemSchema || anything
    this.min = min || 0
    this.max = max || Infinity
  },

  validate : function(instance) {
    // Instance must be an instance of Array
    if (!(instance instanceof Array)) return false

    // Checking length
    if (this.min === this.max) {
      if (instance.length !== this.min) return false

    } else {
      if (this.min > 0        && instance.length < this.min) return false
      if (this.max < Infinity && instance.length > this.max) return false
    }

    // Checking conformance to the given item schema
    for (var i = 0; i < instance.length; i++) {
      if (!this.itemSchema.validate(instance[i])) return false;
    }

    return true
  },

  toJSON : Schema.session(function() {
    var json = Schema.prototype.toJSON.call(this, true)

    if (json['$ref'] != null) return json

    json.type = 'array'

    if (this.min > 0) json.minItems = this.min
    if (this.max < Infinity) json.maxItems = this.max
    if (this.itemSchema !== anything) json.items = this.itemSchema.toJSON()

    return json
  })
})

Schema.fromJSON.def(function(sch) {
  if (!sch || sch.type !== 'array') return

  // Tuple typing is not yet supported
  if (sch.items instanceof Array) return

  return new ArraySchema(Schema.fromJSON(sch.items), sch.maxItems, sch.minItems)
})

Array.of = function() {
  // Possible signatures : (schema)
  //                       (length, schema)
  //                       (minLength, maxLength, schema)
  var args = Array.prototype.slice.call(arguments).reverse()
  if (args.length === 2) args[2] = args[1]
  return new ArraySchema(Schema.fromJS(args[0]), args[1], args[2]).wrap()
}

Array.like = function(other) {
  return new EqualitySchema(other).wrap()
}

Array.schema = new ArraySchema().wrap()
<commit_msg>feature errors : added errors to ArraySchema<commit_after>var Schema = require('../BaseSchema')
  , EqualitySchema = require('../patterns/equality')
  , anything = require('../patterns/anything').instance

var ArraySchema = module.exports = Schema.extensions.ArraySchema = Schema.extend({
  initialize : function(itemSchema, max, min) {
    this.itemSchema = itemSchema || anything
    this.min = min || 0
    this.max = max || Infinity
  },
  errors : function(instance) {
        console.log("ArraySchema.errors | instance = ",instance);
        var self  =this;
        var err = function(message, obj){
            value = obj || instance;
            return {
                schema:self.toJSON(),
                message:message,
                value:value
            }
        }
        // Instance must be an instance of Array
        if (!(instance instanceof Array))

        // Checking length
        if (this.min === this.max) {
          if (instance.length !== this.min) return err("Array length should "+this.min+" and is " + instance.length)

        } else {
          if (this.min > 0        && instance.length < this.min) return err("Array length should be less than "+this.min+" and is " + instance.length);
          if (this.max < Infinity && instance.length > this.max) return err("Array length should be more than "+this.max+" and is " + instance.length);
        }

        // Checking conformance to the given item schema
        var results = {};
        for (var i = 0; i < instance.length; i++) {
            var errs = this.itemSchema.errors(instance[i])
            if(errs){
                results[i] = errs
            }
        }
        var resultKeysArray = Object.keys(results)
        if(resultKeysArray.length > 0){
            return err(resultKeysArray.length +" of "+instance.length + " were invalid.", results);
        }

        return false
  },
  validate : function(instance) {
    // Instance must be an instance of Array
    if (!(instance instanceof Array)) return false

    // Checking length
    if (this.min === this.max) {
      if (instance.length !== this.min) return false

    } else {
      if (this.min > 0        && instance.length < this.min) return false
      if (this.max < Infinity && instance.length > this.max) return false
    }

    // Checking conformance to the given item schema
    for (var i = 0; i < instance.length; i++) {
      if (!this.itemSchema.validate(instance[i])) return false;
    }

    return true
  },

  toJSON : Schema.session(function() {
    var json = Schema.prototype.toJSON.call(this, true)

    if (json['$ref'] != null) return json

    json.type = 'array'

    if (this.min > 0) json.minItems = this.min
    if (this.max < Infinity) json.maxItems = this.max
    if (this.itemSchema !== anything) json.items = this.itemSchema.toJSON()

    return json
  })
})

Schema.fromJSON.def(function(sch) {
  if (!sch || sch.type !== 'array') return

  // Tuple typing is not yet supported
  if (sch.items instanceof Array) return

  return new ArraySchema(Schema.fromJSON(sch.items), sch.maxItems, sch.minItems)
})

Array.of = function() {
  // Possible signatures : (schema)
  //                       (length, schema)
  //                       (minLength, maxLength, schema)
  var args = Array.prototype.slice.call(arguments).reverse()
  if (args.length === 2) args[2] = args[1]
  return new ArraySchema(Schema.fromJS(args[0]), args[1], args[2]).wrap()
}

Array.like = function(other) {
  return new EqualitySchema(other).wrap()
}

Array.schema = new ArraySchema().wrap()
<|endoftext|>


<commit_before>import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from '../../tests/helpers/start-app';

let application;

module('Acceptance | drilling in', {
  beforeEach() {
    application = startApp();
  },

  afterEach() {
    Ember.run(application, 'destroy');
  }
});

test('Drilling in', function(assert) {
  visit('/company/1/buildings');

  andThen(function() {
    assert.equal(currentURL(), '/company/1/buildings');
  });

});
<commit_msg>Drill-in test<commit_after>import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from '../../tests/helpers/start-app';

let application;

module('Acceptance | drilling in', {
  beforeEach() {
    application = startApp();
    application.perfService = application.__container__.lookup('service:ember-perf');
  },

  afterEach() {
    Ember.run(application, 'destroy');
    application = null;
  }
});

test('Drilling in', function(assert) {
  let dataCount = 0;
  application.perfService.on('transitionComplete', () => {
    dataCount++;
  });

  visit('/company/1/buildings');

  andThen(function() {
    assert.equal(dataCount, 1, 'Only one event has been fired for the initial load');
    assert.equal(currentURL(), '/company/1/buildings');
  });

  click('ul.buildings-list li:first-child a');

  andThen(function() {
    assert.equal(dataCount, 2, 'Only one event has been fired for a drill-in');
  });

});
<|endoftext|>


<commit_before>/*!
 * Module dependencies.
 */

var util = require('util'),
	super_ = require('../field');

/**
 * Color FieldType Constructor
 * @extends Field
 * @api public
 */

function color(list, path, options) {

	this._nativeType = String;
	this._underscoreMethods = [];
	this._fixedSize = 'large';

	color.super_.call(this, list, path, options);

}

/*!
 * Inherit from Field
 */

util.inherits(color, super_);

/*!
 * Export class
 */

exports = module.exports = color;
<commit_msg>colour fields should be small<commit_after>/*!
 * Module dependencies.
 */

var util = require('util'),
	super_ = require('../field');

/**
 * Color FieldType Constructor
 * @extends Field
 * @api public
 */

function color(list, path, options) {

	this._nativeType = String;
	this._underscoreMethods = [];
	this._fixedSize = 'small';

	color.super_.call(this, list, path, options);

}

/*!
 * Inherit from Field
 */

util.inherits(color, super_);

/*!
 * Export class
 */

exports = module.exports = color;
<|endoftext|>


<commit_before>const Subiex = require('../bot.js')
const bot = Subiex.bot
const config = Subiex.config
const commands = Subiex.commands

bot.on('message', (message) => {
    let hasArgs
    let cmd
    let cmdType
    if (message.author.id === config.botID) {
        //  This is the bot speaking
    } else if (message.author.bot) {
        //  This is the bot speaking
    } else {
        //  set the message content to lower case here. No need to check anymore and can accept any case input. ;)
        message.content = message.content.toLowerCase()
        for (let loopCmdType in commands) {
            for (let loopCmd in commands[loopCmdType]) {
                if (message.content.lastIndexOf(config.prefix + loopCmd, 0) === 0 || message.content.lastIndexOf(loopCmd + config.suffix, 0) === 0) {
                    message.content = message.content.replace(config.prefix + loopCmd, '')
                    message.content = message.content.replace(loopCmd + config.suffix, '')
                    cmd = loopCmd
                    cmdType = loopCmdType
                    break
                } else {
                    let aliases = commands[loopCmdType][loopCmd].aliases
                    for (let i = 0; i < aliases.length; i++) {
                        let alias = aliases[i]
                        if (message.content.lastIndexOf(config.prefix + alias, 0) === 0 || message.content.lastIndexOf(alias + config.suffix, 0) === 0) {
                            message.content = message.content.replace(config.prefix + alias, '')
                            message.content = message.content.replace(alias + config.suffix, '')
                            cmd = loopCmd
                            cmdType = loopCmdType
                            break
                        }
                    }
                }
            }
        }
        if (message.content.indexOf(' ') === 0)
            hasArgs = true
        message.content = message.content.indexOf(' ') === 0 ? message.content.substring(1) : message.content
        if (cmd !== null) {
            if (cmdType === 'master') {
                if (!(config.masters).includes(message.author.id)) {
                    message.reply("You don't have enough permissions to execute this command.")
                    return
                }
            } else if (cmdType === 'moderator') {
                let accepted = ['Bot Commander', 'Moderator']
                let isMod
                let roles = message.guild.member(message.author.id).roles.array()
                for (let i = 0; i < roles.length; i++) {
                    if (accepted.includes(roles[i].name)) {
                        isMod = true
                        break
                    }
                }
                if (!isMod) {
                    message.reply("You don't have enough permissions to execute this command.")
                    return
                }
            } else if (cmdType === 'dm') {
                if (message.channel.type === 'dm') {
                    console.log(message.author.username + ' - ' + message.content)
                } else {
                    return
                }
            }
            try {
                if (hasArgs || !message.content.length > 0)
                    var result = commands[cmdType][cmd].process(message, bot)
            } catch (error) {
                console.log('An Error occured: ' + error.stack)
            }
            if (result) {
                if (cmdType === 'dm') {
                    message.author.send(result)
                } else {
                    message.reply(result)
                }
            }
        }
    }
})<commit_msg>:zap: Im the master now<commit_after>const Subiex = require('../bot.js')
const bot = Subiex.bot
const config = Subiex.config
const commands = Subiex.commands

bot.on('message', (message) => {
    let hasArgs
    let cmd
    let cmdType
    if (message.author.id === config.botID) {
        //  This is the bot speaking
    } else if (message.author.bot) {
        //  This is the bot speaking
    } else {
        //  set the message content to lower case here. No need to check anymore and can accept any case input. ;)
        message.content = message.content.toLowerCase()
        for (let loopCmdType in commands) {
            for (let loopCmd in commands[loopCmdType]) {
                if (message.content.lastIndexOf(config.prefix + loopCmd, 0) === 0 || message.content.lastIndexOf(loopCmd + config.suffix, 0) === 0) {
                    message.content = message.content.replace(config.prefix + loopCmd, '')
                    message.content = message.content.replace(loopCmd + config.suffix, '')
                    cmd = loopCmd
                    cmdType = loopCmdType
                    break
                } else {
                    let aliases = commands[loopCmdType][loopCmd].aliases
                    for (let i = 0; i < aliases.length; i++) {
                        let alias = aliases[i]
                        if (message.content.lastIndexOf(config.prefix + alias, 0) === 0 || message.content.lastIndexOf(alias + config.suffix, 0) === 0) {
                            message.content = message.content.replace(config.prefix + alias, '')
                            message.content = message.content.replace(alias + config.suffix, '')
                            cmd = loopCmd
                            cmdType = loopCmdType
                            break
                        }
                    }
                }
            }
        }
        if (message.content.indexOf(' ') === 0)
            hasArgs = true
        message.content = message.content.indexOf(' ') === 0 ? message.content.substring(1) : message.content
        if (cmd !== null) {
            if (cmdType === 'master') {
                if (!(config.master).includes(message.author.id)) {
                    message.reply("You don't have enough permissions to execute this command.")
                    return
                }
            } else if (cmdType === 'moderator') {
                let accepted = ['Bot Commander', 'Moderator']
                let isMod
                let roles = message.guild.member(message.author.id).roles.array()
                for (let i = 0; i < roles.length; i++) {
                    if (accepted.includes(roles[i].name)) {
                        isMod = true
                        break
                    }
                }
                if (!isMod) {
                    message.reply("You don't have enough permissions to execute this command.")
                    return
                }
            } else if (cmdType === 'dm') {
                if (message.channel.type === 'dm') {
                    console.log(message.author.username + ' - ' + message.content)
                } else {
                    return
                }
            }
            try {
                if (hasArgs || !message.content.length > 0)
                    var result = commands[cmdType][cmd].process(message, bot)
            } catch (error) {
                console.log('An Error occured: ' + error.stack)
            }
            if (result) {
                if (cmdType === 'dm') {
                    message.author.send(result)
                } else {
                    message.reply(result)
                }
            }
        }
    }
})<|endoftext|>


<commit_before>describe("Rivets.binders", function() {
  var context

  beforeEach(function() {
    context = {
      publish: function() {}
    }
  })

  describe("value", function() {
    var el

    beforeEach(function() {
      el = document.createElement('input')
    })

    it("unbinds the same bound function", function() {
      var boundFn

      sinon.stub(el, 'addEventListener', function(event, fn) {
        boundFn = fn
      })

      rivets.binders.value.bind.call(context, el)

      sinon.stub(el, 'removeEventListener', function(event, fn) {
        fn.should.equal(boundFn)
      })

      rivets.binders.value.unbind.call(context, el)
    })
  })

  describe("each-*", function() {
    var fragment;
    var el;
    var model;

    beforeEach(function() {
      fragment = document.createDocumentFragment();
      el = document.createElement("li");
      el.setAttribute("rv-each-item", "items");
      el.setAttribute("rv-text", "item.val");

      fragment.appendChild(el);

      model = { items: [{val: 0},{val: 1},{val: 2}] };
    });

    it("binds to the model creating a list item for each element in items", function() {
      var view = rivets.bind(fragment, model);

      // one child for each element in the model plus 1 for the comment placeholder
      Should(fragment.childNodes.length).be.exactly(model.items.length + 1);
    });

    it("reflects changes to the model into the DOM", function() {
      var view = rivets.bind(fragment, model);
      Should(fragment.childNodes[1].innerText).be.exactly("0");

      model.items[0].val = "howdy";
      Should(fragment.childNodes[1].innerText).be.exactly("howdy");
    });

    it("reflects changes to the model into the DOM after unbind/bind", function() {
      var view = rivets.bind(fragment, model);
      Should(fragment.childNodes[1].innerText).be.exactly("0");

      view.unbind();
      view.bind();
      model.items[0].val = "howdy";
      Should(fragment.childNodes[1].innerText).be.exactly("howdy");
    });

    it("lets you push an item", function() {
      var view = rivets.bind(fragment, model);
      var originalLength  = model.items.length;

      // one child for each element in the model plus 1 for the comment placeholder
      Should(fragment.childNodes.length).be.exactly(model.items.length + 1);

      model.items.push({val: 3});
      Should(model.items.length).be.exactly(originalLength + 1);
      Should(fragment.childNodes.length).be.exactly(model.items.length + 1);
    });

    it("lets you push an item after unbind/bind", function() {
      var view = rivets.bind(fragment, model);
      var originalLength  = model.items.length;

      // one child for each element in the model plus 1 for the comment placeholder
      Should(fragment.childNodes.length).be.exactly(model.items.length + 1);

      view.unbind();
      view.bind();

      model.items.push({val: 3});
      Should(model.items.length).be.exactly(originalLength + 1);
      Should(fragment.childNodes.length).be.exactly(model.items.length + 1);
    });
  });

  describe("nested-each-*", function() {
    var fragment;
    var el;
    var nestedEl;
    var model;

    beforeEach(function() {
      fragment = document.createDocumentFragment();
      el = document.createElement("span");
      el.setAttribute("rv-each-item", "items");
      nestedEl = document.createElement("span");
      nestedEl.setAttribute("rv-each-nested", "item.val");
      nestedEl.innerText = "{%item%}-{%nested%}";
      el.appendChild(nestedEl);
      fragment.appendChild(el);

      model = { items: [{val: [{val: 0},{val: 1}]},{val: [{val: 2},{val: 3}]},{val: [{val: 4},{val: 5}]}] };
    });

    it("lets you get all the indexes", function() {
      var view = rivets.bind(el, model);

      Should(fragment.childNodes[1].childNodes[1].innerText).be.exactly('0-0');
      Should(fragment.childNodes[1].childNodes[2].innerText).be.exactly('0-1');
      Should(fragment.childNodes[2].childNodes[2].innerText).be.exactly('1-1');
    });
  });

  describe("if", function() {
    var fragment;
    var el;
    var model;

    beforeEach(function() {
      fragment = document.createDocumentFragment();
      el = document.createElement("div");
      el.setAttribute("rv-if", "data.show");
      el.innerHTML = "{ data.count }";

      fragment.appendChild(el);

      model = { data: {
        show: true,
        count: 1
      } };
    });

    it("shows element with bound key inside if the value is true", function() {
      var view = rivets.bind(fragment, model);

      // one child for the original div plus 1 for the comment placeholder
      Should(fragment.childNodes.length).be.exactly(2);
      Should(fragment.childNodes[1].innerHTML).be.exactly("1");
    });

    it("hides if the value is false", function() {
      var view = rivets.bind(fragment, model);

      model.data.show = false;

      // 1 for the comment placeholder
      Should(fragment.childNodes.length).be.exactly(1);
    });

    it("keeps binding when element becomes visible again", function() {
      var view = rivets.bind(fragment, model);

      model.data.show = false;
      model.data.count = 2;
      model.data.show = true;

      // one child for the original div plus 1 for the comment placeholder
      Should(fragment.childNodes.length).be.exactly(2);
      Should(fragment.childNodes[1].innerHTML).be.exactly("2");
    });

    it("hides if the value is falsey - zero", function() {
      var view = rivets.bind(fragment, model);

      model.data.show = 0;
      // 1 for the comment placeholder
      Should(fragment.childNodes.length).be.exactly(1);
    });

    it("hides if the value is falsey - empty string", function() {
      var view = rivets.bind(fragment, model);

      model.data.show = "";
      // 1 for the comment placeholder
      Should(fragment.childNodes.length).be.exactly(1);
    });

    it("hides if the value is falsey - undefined", function() {
      var view = rivets.bind(fragment, model);

      model.data.show = undefined;
      // 1 for the comment placeholder
      Should(fragment.childNodes.length).be.exactly(1);
    });
  });

  describe("Custom binder with no attribute value", function() {
    rivets.binders["custom-binder"] = function(el, value) {
      el.innerHTML = "received " + value;
    };
    beforeEach(function() {
      fragment = document.createDocumentFragment();
      el = document.createElement("div");

      fragment.appendChild(el);

      model = {};
    });

    it("receives undefined when html attribute is not specified", function() {
      el.innerHTML = "

";
      var view = rivets.bind(fragment, model);
      Should(el.children[0].innerHTML).be.exactly('received undefined');
    });
    it("receives undefined when html attribute is not specified", function() {
      el.innerHTML = "

";
      var view = rivets.bind(fragment, model);
      Should(el.children[0].innerHTML).be.exactly('received undefined');
    });
  });
});
<commit_msg>Use textContent in tests<commit_after>describe("Rivets.binders", function() {
  var context

  beforeEach(function() {
    context = {
      publish: function() {}
    }
  })

  describe("value", function() {
    var el

    beforeEach(function() {
      el = document.createElement('input')
    })

    it("unbinds the same bound function", function() {
      var boundFn

      sinon.stub(el, 'addEventListener', function(event, fn) {
        boundFn = fn
      })

      rivets.binders.value.bind.call(context, el)

      sinon.stub(el, 'removeEventListener', function(event, fn) {
        fn.should.equal(boundFn)
      })

      rivets.binders.value.unbind.call(context, el)
    })
  })

  describe("each-*", function() {
    var fragment;
    var el;
    var model;

    beforeEach(function() {
      fragment = document.createDocumentFragment();
      el = document.createElement("li");
      el.setAttribute("rv-each-item", "items");
      el.setAttribute("rv-text", "item.val");

      fragment.appendChild(el);

      model = { items: [{val: 0},{val: 1},{val: 2}] };
    });

    it("binds to the model creating a list item for each element in items", function() {
      var view = rivets.bind(fragment, model);

      // one child for each element in the model plus 1 for the comment placeholder
      Should(fragment.childNodes.length).be.exactly(model.items.length + 1);
    });

    it("reflects changes to the model into the DOM", function() {
      var view = rivets.bind(fragment, model);
      Should(fragment.childNodes[1].textContent).be.exactly("0");

      model.items[0].val = "howdy";
      Should(fragment.childNodes[1].textContent).be.exactly("howdy");
    });

    it("reflects changes to the model into the DOM after unbind/bind", function() {
      var view = rivets.bind(fragment, model);
      Should(fragment.childNodes[1].textContent).be.exactly("0");

      view.unbind();
      view.bind();
      model.items[0].val = "howdy";
      Should(fragment.childNodes[1].textContent).be.exactly("howdy");
    });

    it("lets you push an item", function() {
      var view = rivets.bind(fragment, model);
      var originalLength  = model.items.length;

      // one child for each element in the model plus 1 for the comment placeholder
      Should(fragment.childNodes.length).be.exactly(model.items.length + 1);

      model.items.push({val: 3});
      Should(model.items.length).be.exactly(originalLength + 1);
      Should(fragment.childNodes.length).be.exactly(model.items.length + 1);
    });

    it("lets you push an item after unbind/bind", function() {
      var view = rivets.bind(fragment, model);
      var originalLength  = model.items.length;

      // one child for each element in the model plus 1 for the comment placeholder
      Should(fragment.childNodes.length).be.exactly(model.items.length + 1);

      view.unbind();
      view.bind();

      model.items.push({val: 3});
      Should(model.items.length).be.exactly(originalLength + 1);
      Should(fragment.childNodes.length).be.exactly(model.items.length + 1);
    });
  });

  describe("nested-each-*", function() {
    var fragment;
    var el;
    var nestedEl;
    var model;

    beforeEach(function() {
      fragment = document.createDocumentFragment();
      el = document.createElement("span");
      el.setAttribute("rv-each-item", "items");
      nestedEl = document.createElement("span");
      nestedEl.setAttribute("rv-each-nested", "item.val");
      nestedEl.textContent = "{%item%}-{%nested%}";
      el.appendChild(nestedEl);
      fragment.appendChild(el);

      model = { items: [{val: [{val: 0},{val: 1}]},{val: [{val: 2},{val: 3}]},{val: [{val: 4},{val: 5}]}] };
    });

    it("lets you get all the indexes", function() {
      var view = rivets.bind(el, model);

      Should(fragment.childNodes[1].childNodes[1].textContent).be.exactly('0-0');
      Should(fragment.childNodes[1].childNodes[2].textContent).be.exactly('0-1');
      Should(fragment.childNodes[2].childNodes[2].textContent).be.exactly('1-1');
    });
  });

  describe("if", function() {
    var fragment;
    var el;
    var model;

    beforeEach(function() {
      fragment = document.createDocumentFragment();
      el = document.createElement("div");
      el.setAttribute("rv-if", "data.show");
      el.innerHTML = "{ data.count }";

      fragment.appendChild(el);

      model = { data: {
        show: true,
        count: 1
      } };
    });

    it("shows element with bound key inside if the value is true", function() {
      var view = rivets.bind(fragment, model);

      // one child for the original div plus 1 for the comment placeholder
      Should(fragment.childNodes.length).be.exactly(2);
      Should(fragment.childNodes[1].innerHTML).be.exactly("1");
    });

    it("hides if the value is false", function() {
      var view = rivets.bind(fragment, model);

      model.data.show = false;

      // 1 for the comment placeholder
      Should(fragment.childNodes.length).be.exactly(1);
    });

    it("keeps binding when element becomes visible again", function() {
      var view = rivets.bind(fragment, model);

      model.data.show = false;
      model.data.count = 2;
      model.data.show = true;

      // one child for the original div plus 1 for the comment placeholder
      Should(fragment.childNodes.length).be.exactly(2);
      Should(fragment.childNodes[1].innerHTML).be.exactly("2");
    });

    it("hides if the value is falsey - zero", function() {
      var view = rivets.bind(fragment, model);

      model.data.show = 0;
      // 1 for the comment placeholder
      Should(fragment.childNodes.length).be.exactly(1);
    });

    it("hides if the value is falsey - empty string", function() {
      var view = rivets.bind(fragment, model);

      model.data.show = "";
      // 1 for the comment placeholder
      Should(fragment.childNodes.length).be.exactly(1);
    });

    it("hides if the value is falsey - undefined", function() {
      var view = rivets.bind(fragment, model);

      model.data.show = undefined;
      // 1 for the comment placeholder
      Should(fragment.childNodes.length).be.exactly(1);
    });
  });

  describe("Custom binder with no attribute value", function() {
    rivets.binders["custom-binder"] = function(el, value) {
      el.innerHTML = "received " + value;
    };
    beforeEach(function() {
      fragment = document.createDocumentFragment();
      el = document.createElement("div");

      fragment.appendChild(el);

      model = {};
    });

    it("receives undefined when html attribute is not specified", function() {
      el.innerHTML = "

";
      var view = rivets.bind(fragment, model);
      Should(el.children[0].innerHTML).be.exactly('received undefined');
    });
    it("receives undefined when html attribute is not specified", function() {
      el.innerHTML = "

";
      var view = rivets.bind(fragment, model);
      Should(el.children[0].innerHTML).be.exactly('received undefined');
    });
  });
});
<|endoftext|>


<commit_before>
const expect = require('chai').expect;
const RG = require('../../../client/src/battles');
const RGTest = require('../../roguetest');

const expectConnected = RGTest.expectConnected;

describe('Factory.World', function() {
    this.timeout(3000);
    let fact = null;

    beforeEach(() => {
        fact = new RG.Factory.World();
    });

    afterEach(() => {
        fact = null;
    });

    it('has scope, conf and hier name management', () => {
        const fact = new RG.Factory.World();
        const conf1 = {name: 'Top', myConf: 'Top_abc'};
        const conf2 = {name: 'Sub', constraint: 'abc'};
        const conf3 = {name: 'SubSub', myConf: 'SubSub_xxx'};
        const conf4 = {name: 'Bottom', constraint: 'xyz'};
        fact.pushScope(conf1);
        fact.pushScope(conf2);
        expect(fact.getHierName()).to.equal('Top.Sub');
        expect(fact.getConf('constraint')).to.equal('abc');
        expect(fact.getConf('myConf')).to.equal('Top_abc');

        fact.pushScope(conf3);
        expect(fact.getHierName()).to.equal('Top.Sub.SubSub');
        expect(fact.getConf('constraint')).to.equal('abc');
        expect(fact.getConf('myConf')).to.equal('SubSub_xxx');

        fact.pushScope(conf4);
        expect(fact.getConf('constraint')).to.equal('xyz');
        fact.popScope(conf4);
        expect(fact.getConf('constraint')).to.equal('abc');
        fact.popScope(conf3);
        expect(fact.getConf('constraint')).to.equal('abc');
    });

    it('can create cities', () => {
        const cityConf = {
            name: 'Arkham', nQuarters: 2,
            connectLevels: [
                ['Q1', 'Q2', 0, 0]
            ],
            quarter: [
                {name: 'Q1', nLevels: 1, entranceLevel: 0},
                {name: 'Q2', nLevels: 2}
            ]
        };
        const city = fact.createCity(cityConf);
        expect(city.getName()).to.equal(cityConf.name);

        const qs = city.getQuarters();
        expect(qs).to.have.length(2);

        const q1l0 = qs[0].getLevels()[0];
        const q2l0 = qs[1].getLevels()[0];

        const exitFilter = c => c.getName() === 'exit';
        const exits1 = q1l0.getConnections().filter(exitFilter);
        const exits2 = q2l0.getConnections().filter(exitFilter);

        RGTest.verifyConnectivity(exits1);
        RGTest.verifyConnectivity(exits2);

        expect(qs[0].getParent().getName()).to.equal('Arkham');
    });

    it('can create Branch using config object', () => {
        const brConf = {
            name: 'DangerousBranch',
            nLevels: 2,
            entranceLevel: 0,
            sqrPerItem: 20,
            sqrPerActor: 20
        };
        fact.setGlobalConf({});
        const br = fact.createBranch(brConf);
        expect(br.getName()).to.equal(brConf.name);
        expect(br.getEntrance()).to.not.be.empty;

        const l0 = br.getLevels()[0];

        // Should have entrance + stairs down == 2 stairs
        expect(l0.getStairs()).to.have.length(2);
    });

    it('can create elements to fixed positions', () => {
        const brConf = {
            name: 'DangerousBranch',
            nLevels: 2,
            entranceLevel: 0,
            sqrPerItem: 20,
            sqrPerActor: 20,
            create: {
                stairs: [{nLevel: 1, isDown: false, x: 10, y: 10}]
            }
        };
        fact.setGlobalConf({});
        const br = fact.createBranch(brConf);
        const l1 = br.getLevels()[1];
        const stairsL1 = l1.getStairs();
        expect(stairsL1).to.have.length(2);
    });

    it('Can create dungeon using config object', () => {
        const dungeonConf = {
            name: 'Cave',
            nBranches: 3,
            entrance: 'br2',
            sqrPerActor: 50,
            sqrPerItem: 50,
            connectLevels: [
                // Each connection is branch1, branch2, level1, level2
                ['br1', 'br2', 0, 1],
                ['br3', 'br2', 2, 0]
            ],
            branch: [
                { name: 'br1', nLevels: 1},
                { name: 'br2', nLevels: 2, entranceLevel: 0},
                { name: 'br3', nLevels: 3 }
            ]
        };
        fact.setGlobalConf({});
        const dungeon = fact.createDungeon(dungeonConf);
        const branches = dungeon.getBranches();
        expect(dungeon.getName()).to.equal('Cave');
        expect(dungeon.getLevels()).to.have.length(6);
        expect(dungeon.getEntrances()).to.have.length(1);
        expect(dungeon.getEntrances()[0]).not.to.be.empty;
        expectConnected(branches[0], branches[1], 1);
        expectConnected(branches[1], branches[2], 1);
        expect(branches[0].getParent().getName()).to.equal('Cave');
    });

    it('creates properly connected dungeons with branches', () => {
        const dConf = {
            x: 0, y: 0,
            name: 'BranchTest',
            sqrPerItem: 100,
            sqrPerActor: 100,
            nBranches: 3,
            connectLevels: [
                ['main', 'side', 0, 0],
                ['main', 'side2', 0, 0]
            ],
            branch: [
                {name: 'main', nLevels: 1},
                {name: 'side', nLevels: 1, entranceLevel: 0},
                {name: 'side2', nLevels: 1, entranceLevel: 0}
            ]
        };
        fact.setGlobalConf({}); // Use default configs
        const dungeon = fact.createDungeon(dConf);
        const branches = dungeon.getBranches();
        expectConnected(branches[0], branches[1], 1);
        expectConnected(branches[0], branches[2], 1);

        const entrB1 = branches[1].getEntrance();
        const entrB2 = branches[2].getEntrance();
        expect(entrB1).to.exist;
        expect(entrB1.getTargetStairs()).to.be.null;
        expect(entrB2).to.exist;
        expect(entrB2.getTargetStairs()).to.be.null;
    });

    it('can create cities within areas with given locations', () => {
        const worldConf = {
            name: 'ww',
            nAreas: 1,
            area: [
                { name: 'a1', maxX: 2, maxY: 2, nCities: 1,
                    city: [
                        { x: 0, y: 0, levelX: 4, levelY: 7,
                            name: 'Ravendark', nQuarters: 1,
                            connectToAreaXY: [
                                {name: 'Q1', nLevel: 1, levelX: 8, levelY: 9}
                            ],
                            quarter: [
                                {name: 'Q1', nLevels: 2, entranceLevel: 0}
                            ]
                        }
                    ]
                }
            ]
        };

        fact.setGlobalConf({});
        const world = fact.createWorld(worldConf);

        const cities = world.getZones('City');
        expect(cities).to.have.length(1);

        expect(cities[0].getParent().getName()).to.equal('a1');

        const area = world.getAreas()[0];
        expect(area.getParent().getName()).to.equal('ww');
        const areaLevel = area.getTileXY(0, 0).getLevel();

        const areaConns = areaLevel.getConnections();
        expect(areaConns.length).to.be.above(20);

        const cityConns = areaConns.filter(c => c.getName() === 'town');
        const townConnect0 = cityConns[0];
        expect(townConnect0.getX()).to.equal(4);
        expect(townConnect0.getY()).to.equal(7);
        expect(townConnect0.getName()).to.equal('town');

        const townConnect1 = cityConns[1];
        expect(townConnect1.getX()).to.equal(8);
        expect(townConnect1.getY()).to.equal(9);
        expect(townConnect1.getName()).to.equal('town');

    });

    it('can create a city with preset levels/created stairs', () => {
        const level = RG.FACT.createLevel('arena', 20, 20, {});
        const stairs1 = new RG.Element.Stairs('stairsDown', level);
        const stairs2 = new RG.Element.Stairs('stairsUp', level);
        level.addStairs(stairs1, 1, 1);
        level.addStairs(stairs2, 15, 15);

        const levelStub = {stub: true, new: 'arena', args: [40, 40]};

        const cityConf = {
            name: 'CapitalCity',
            x: 0, y: 0,
            nQuarters: 2,
            presetLevels: {
                'CapitalCity.MainQuarter': [{nLevel: 0, level}],
                'CapitalCity.SideQuarter': [{nLevel: 0, levelStub}]
            },
            quarter: [
                {name: 'MainQuarter', nLevels: 1},
                {name: 'SideQuarter', nLevels: 2}
            ],
            connectLevels: [
                ['MainQuarter', 'SideQuarter', 0, 1]
            ],
            connectToAreaXY: [
                {levelX: 0, levelY: 1, name: 'MainQuarter', nLevel: 0,
                    stairs: stairs1},
                {levelX: 3, levelY: 4, name: 'MainQuarter', nLevel: 0,
                    stairs: {getStairs: 1}},
                {levelX: 4, levelY: 4, name: 'SideQuarter', nLevel: 0,
                    stairs: {getStairs: 0}}
            ]
        };
        const areaLevel = RG.FACT.createLevel('empty', 100, 100, {});
        const areaLevels = [[areaLevel]];
        const areaConf = {
            name: 'Area1x1', maxX: 1, maxY: 1, nCities: 1,
            presetLevels: {
                Area1x1: areaLevels
            },
            city: [cityConf]
        };
        const fact = new RG.Factory.World();
        const area = fact.createArea(areaConf);
        expect(area.getZones('City')).to.have.length(1);
        const city = area.getZones('City')[0];
        expect(city.getLevels()).to.have.length(3);

        const stairs = level.getStairs();
        stairs.forEach(s => {expect(s.isConnected()).to.be.true;});

        const cityLevel = city.getLevels()[0];
        expect(cityLevel.getID()).to.equal(level.getID());

        const qSide = city.findSubZone('SideQuarter');
        const ql0 = qSide.getLevels()[0];
        const ql1 = qSide.getLevels()[1];

        expect(ql0.getStairs()).to.have.length(1);
        expect(ql1.getStairs()).to.have.length(1);

        // expect(l0.getConnections().length).to.be.above(10);
        expect(ql1.getConnections().length).to.be.above(10);

        // const qStairs = ql1.getStairs();

        const tile00 = area.getTileXY(0, 0);
        const tileLevel = tile00.getLevel();
        const tileConns = tileLevel.getConnections();
        const townConns = tileConns.filter(c => c.getName() === 'town');
        expect(townConns).to.have.length(3);

    });

    it('can create mountains with faces and summits', () => {
        const mountainConf = {
            name: 'Stormy Tower',
            nFaces: 1,
            nSummits: 2,
            maxDanger: 10,
            face: [
                {x: 50, y: 100, nLevels: 1, name: 'North face'}
            ],
            summit: [
                {cols: 80, rows: 50, name: 'Summit', nLevels: 1},
                {cols: 100, rows: 100, name: 'Summit2', nLevels: 2}
            ],
            connectLevels: [
                ['North face', 'Summit', 0, 0],
                ['Summit', 'Summit2', 0, 0],
                ['Summit2', 'Summit2', 0, 1]
            ]
        };
        const fact = new RG.Factory.World();
        const mountain = fact.createMountain(mountainConf);

        const summits = mountain.getSummits();
        const faces = mountain.getFaces();
        expect(summits[0].getName()).to.equal('Summit');
        expect(faces[0].getName()).to.equal('North face');

        const levels = mountain.getLevels();
        expect(levels, 'Face and summit created').to.have.length(4);

        const summitLevel = mountain.findLevel('Summit', 0);
        const faceLevel = mountain.findLevel('North face', 0);
        const summit2Level0 = mountain.findLevel('Summit2', 0);

        expect(summitLevel.getConnections()).to.have.length(2);
        expect(faceLevel.getConnections()).to.have.length(1);
        expect(summit2Level0.getConnections()).to.have.length(2);

    });

    it('has createPresetLevels for creating all levels using factory', () => {
        const fact = new RG.Factory.World();
        const nLevels = 5;
        const towerConf = {
            name: 'Black tower',
            nBranches: 1,
            branch: [{
                name: 'Main branch',
                nLevels: nLevels,
                createPresetLevels: {
                    new: 'BlackTower',
                    args: [180, 90]
                },
                create: {
                    actor: [
                        {name: 'goblin', nLevel: 2},
                        {name: 'Thabba, Son of Ice', nLevel: 4}
                    ]
                }
            }]
        };

        const tower = fact.createDungeon(towerConf);
        const levels = tower.getLevels();
        expect(levels).to.have.length(nLevels);

        const l0 = levels[0];
        expect(l0.getMap().cols, 'Cols correct').to.equal(180);
        expect(l0.getMap().rows, 'Rows correct').to.equal(90);

        // l0.debugPrintInASCII();

        const l4 = levels[nLevels - 1];
        // l4.debugPrintInASCII();

        // levels.map(ll => ll.getMap().debugPrintInASCII());
        const actors = l4.getActors();
        const boss = actors.find(actor => actor.getName().match(/Thabba/));
        expect(boss, 'Boss actor was created/found').to.not.be.empty;
        expect(boss.getName()).to.match(/Son of Ice/i);

        const elements0 = l0.getElements();
        expect(elements0.length).to.be.above(0);

        const lever = elements0.find(e => e.getType() === 'lever');
        const leverDoor = elements0.find(e => e.getType() === 'leverdoor');
        const door = elements0.find(e => e.getType() === 'door');
        // console.log(elements0);

        expect(lever).to.not.be.empty;
        expect(leverDoor).to.not.be.empty;
        expect(door).to.not.be.empty;
    });

});
<commit_msg>Added checn that tile connections are done properly.<commit_after>
const expect = require('chai').expect;
const RG = require('../../../client/src/battles');
const RGTest = require('../../roguetest');

const expectConnected = RGTest.expectConnected;

describe('Factory.World', function() {
    this.timeout(3000);
    let fact = null;

    beforeEach(() => {
        fact = new RG.Factory.World();
    });

    afterEach(() => {
        fact = null;
    });

    it('has scope, conf and hier name management', () => {
        const fact = new RG.Factory.World();
        const conf1 = {name: 'Top', myConf: 'Top_abc'};
        const conf2 = {name: 'Sub', constraint: 'abc'};
        const conf3 = {name: 'SubSub', myConf: 'SubSub_xxx'};
        const conf4 = {name: 'Bottom', constraint: 'xyz'};
        fact.pushScope(conf1);
        fact.pushScope(conf2);
        expect(fact.getHierName()).to.equal('Top.Sub');
        expect(fact.getConf('constraint')).to.equal('abc');
        expect(fact.getConf('myConf')).to.equal('Top_abc');

        fact.pushScope(conf3);
        expect(fact.getHierName()).to.equal('Top.Sub.SubSub');
        expect(fact.getConf('constraint')).to.equal('abc');
        expect(fact.getConf('myConf')).to.equal('SubSub_xxx');

        fact.pushScope(conf4);
        expect(fact.getConf('constraint')).to.equal('xyz');
        fact.popScope(conf4);
        expect(fact.getConf('constraint')).to.equal('abc');
        fact.popScope(conf3);
        expect(fact.getConf('constraint')).to.equal('abc');
    });

    it('can create cities', () => {
        const cityConf = {
            name: 'Arkham', nQuarters: 2,
            connectLevels: [
                ['Q1', 'Q2', 0, 0]
            ],
            quarter: [
                {name: 'Q1', nLevels: 1, entranceLevel: 0},
                {name: 'Q2', nLevels: 2}
            ]
        };
        const city = fact.createCity(cityConf);
        expect(city.getName()).to.equal(cityConf.name);

        const qs = city.getQuarters();
        expect(qs).to.have.length(2);

        const q1l0 = qs[0].getLevels()[0];
        const q2l0 = qs[1].getLevels()[0];

        const exitFilter = c => c.getName() === 'exit';
        const exits1 = q1l0.getConnections().filter(exitFilter);
        const exits2 = q2l0.getConnections().filter(exitFilter);

        RGTest.verifyConnectivity(exits1);
        RGTest.verifyConnectivity(exits2);

        expect(qs[0].getParent().getName()).to.equal('Arkham');
    });

    it('can create Branch using config object', () => {
        const brConf = {
            name: 'DangerousBranch',
            nLevels: 2,
            entranceLevel: 0,
            sqrPerItem: 20,
            sqrPerActor: 20
        };
        fact.setGlobalConf({});
        const br = fact.createBranch(brConf);
        expect(br.getName()).to.equal(brConf.name);
        expect(br.getEntrance()).to.not.be.empty;

        const l0 = br.getLevels()[0];

        // Should have entrance + stairs down == 2 stairs
        expect(l0.getStairs()).to.have.length(2);
    });

    it('can create elements to fixed positions', () => {
        const brConf = {
            name: 'DangerousBranch',
            nLevels: 2,
            entranceLevel: 0,
            sqrPerItem: 20,
            sqrPerActor: 20,
            create: {
                stairs: [{nLevel: 1, isDown: false, x: 10, y: 10}]
            }
        };
        fact.setGlobalConf({});
        const br = fact.createBranch(brConf);
        const l1 = br.getLevels()[1];
        const stairsL1 = l1.getStairs();
        expect(stairsL1).to.have.length(2);
    });

    it('Can create dungeon using config object', () => {
        const dungeonConf = {
            name: 'Cave',
            nBranches: 3,
            entrance: 'br2',
            sqrPerActor: 50,
            sqrPerItem: 50,
            connectLevels: [
                // Each connection is branch1, branch2, level1, level2
                ['br1', 'br2', 0, 1],
                ['br3', 'br2', 2, 0]
            ],
            branch: [
                { name: 'br1', nLevels: 1},
                { name: 'br2', nLevels: 2, entranceLevel: 0},
                { name: 'br3', nLevels: 3 }
            ]
        };
        fact.setGlobalConf({});
        const dungeon = fact.createDungeon(dungeonConf);
        const branches = dungeon.getBranches();
        expect(dungeon.getName()).to.equal('Cave');
        expect(dungeon.getLevels()).to.have.length(6);
        expect(dungeon.getEntrances()).to.have.length(1);
        expect(dungeon.getEntrances()[0]).not.to.be.empty;
        expectConnected(branches[0], branches[1], 1);
        expectConnected(branches[1], branches[2], 1);
        expect(branches[0].getParent().getName()).to.equal('Cave');
    });

    it('creates properly connected dungeons with branches', () => {
        const dConf = {
            x: 0, y: 0,
            name: 'BranchTest',
            sqrPerItem: 100,
            sqrPerActor: 100,
            nBranches: 3,
            connectLevels: [
                ['main', 'side', 0, 0],
                ['main', 'side2', 0, 0]
            ],
            branch: [
                {name: 'main', nLevels: 1},
                {name: 'side', nLevels: 1, entranceLevel: 0},
                {name: 'side2', nLevels: 1, entranceLevel: 0}
            ]
        };
        fact.setGlobalConf({}); // Use default configs
        const dungeon = fact.createDungeon(dConf);
        const branches = dungeon.getBranches();
        expectConnected(branches[0], branches[1], 1);
        expectConnected(branches[0], branches[2], 1);

        const entrB1 = branches[1].getEntrance();
        const entrB2 = branches[2].getEntrance();
        expect(entrB1).to.exist;
        expect(entrB1.getTargetStairs()).to.be.null;
        expect(entrB2).to.exist;
        expect(entrB2.getTargetStairs()).to.be.null;
    });

    it('can create cities within areas with given locations', () => {
        const worldConf = {
            name: 'ww',
            nAreas: 1,
            area: [
                { name: 'a1', maxX: 2, maxY: 2, nCities: 1,
                    city: [
                        { x: 0, y: 0, levelX: 4, levelY: 7,
                            name: 'Ravendark', nQuarters: 1,
                            connectToAreaXY: [
                                {name: 'Q1', nLevel: 1, levelX: 8, levelY: 9}
                            ],
                            quarter: [
                                {name: 'Q1', nLevels: 2, entranceLevel: 0}
                            ]
                        }
                    ]
                }
            ]
        };

        fact.setGlobalConf({});
        const world = fact.createWorld(worldConf);

        const cities = world.getZones('City');
        expect(cities).to.have.length(1);

        expect(cities[0].getParent().getName()).to.equal('a1');

        const area = world.getAreas()[0];
        expect(area.getParent().getName()).to.equal('ww');
        const areaLevel = area.getTileXY(0, 0).getLevel();

        const areaConns = areaLevel.getConnections();
        expect(areaConns.length).to.be.above(20);

        const cityConns = areaConns.filter(c => c.getName() === 'town');
        const townConnect0 = cityConns[0];
        expect(townConnect0.getX()).to.equal(4);
        expect(townConnect0.getY()).to.equal(7);
        expect(townConnect0.getName()).to.equal('town');

        const townConnect1 = cityConns[1];
        expect(townConnect1.getX()).to.equal(8);
        expect(townConnect1.getY()).to.equal(9);
        expect(townConnect1.getName()).to.equal('town');

    });

    it('can create a city with preset levels/created stairs', () => {
        const level = RG.FACT.createLevel('arena', 20, 20, {});
        const stairs1 = new RG.Element.Stairs('stairsDown', level);
        const stairs2 = new RG.Element.Stairs('stairsUp', level);
        level.addStairs(stairs1, 1, 1);
        level.addStairs(stairs2, 15, 15);

        const levelStub = {stub: true, new: 'arena', args: [40, 40]};

        const cityConf = {
            name: 'CapitalCity',
            x: 0, y: 0,
            nQuarters: 2,
            presetLevels: {
                'CapitalCity.MainQuarter': [{nLevel: 0, level}],
                'CapitalCity.SideQuarter': [{nLevel: 0, levelStub}]
            },
            quarter: [
                {name: 'MainQuarter', nLevels: 1},
                {name: 'SideQuarter', nLevels: 2}
            ],
            connectLevels: [
                ['MainQuarter', 'SideQuarter', 0, 1]
            ],
            connectToAreaXY: [
                {levelX: 0, levelY: 1, name: 'MainQuarter', nLevel: 0,
                    stairs: stairs1},
                {levelX: 3, levelY: 4, name: 'MainQuarter', nLevel: 0,
                    stairs: {getStairs: 1}},
                {levelX: 4, levelY: 4, name: 'SideQuarter', nLevel: 0,
                    stairs: {getStairs: 0}}
            ]
        };
        const areaLevel = RG.FACT.createLevel('empty', 100, 100, {});
        const areaLevels = [[areaLevel]];
        const areaConf = {
            name: 'Area1x1', maxX: 1, maxY: 1, nCities: 1,
            presetLevels: {
                Area1x1: areaLevels
            },
            city: [cityConf]
        };
        const fact = new RG.Factory.World();
        const area = fact.createArea(areaConf);
        expect(area.getZones('City')).to.have.length(1);
        const city = area.getZones('City')[0];
        expect(city.getLevels()).to.have.length(3);

        const stairs = level.getStairs();
        stairs.forEach(s => {expect(s.isConnected()).to.be.true;});

        const cityLevel = city.getLevels()[0];
        expect(cityLevel.getID()).to.equal(level.getID());

        const qSide = city.findSubZone('SideQuarter');
        const ql0 = qSide.getLevels()[0];
        const ql1 = qSide.getLevels()[1];

        expect(ql0.getStairs()).to.have.length(1);
        expect(ql1.getStairs()).to.have.length(1);

        // expect(l0.getConnections().length).to.be.above(10);
        expect(ql1.getConnections().length).to.be.above(10);

        // const qStairs = ql1.getStairs();

        const tile00 = area.getTileXY(0, 0);
        const tileLevel = tile00.getLevel();
        const tileConns = tileLevel.getConnections();
        const townConns = tileConns.filter(c => c.getName() === 'town');
        expect(townConns).to.have.length(3);

    });

    it('can create mountains with faces and summits', () => {
        const mountainConf = {
            name: 'Stormy Tower',
            nFaces: 1,
            nSummits: 2,
            maxDanger: 10,
            face: [
                {x: 50, y: 100, nLevels: 1, name: 'North face'}
            ],
            summit: [
                {cols: 80, rows: 50, name: 'Summit', nLevels: 1},
                {cols: 100, rows: 100, name: 'Summit2', nLevels: 2}
            ],
            connectLevels: [
                ['North face', 'Summit', 0, 0],
                ['Summit', 'Summit2', 0, 0],
                ['Summit2', 'Summit2', 0, 1]
            ]
        };
        const fact = new RG.Factory.World();
        const mountain = fact.createMountain(mountainConf);

        const summits = mountain.getSummits();
        const faces = mountain.getFaces();
        expect(summits[0].getName()).to.equal('Summit');
        expect(faces[0].getName()).to.equal('North face');

        const levels = mountain.getLevels();
        expect(levels, 'Face and summit created').to.have.length(4);

        const summitLevel = mountain.findLevel('Summit', 0);
        const faceLevel = mountain.findLevel('North face', 0);
        const summit2Level0 = mountain.findLevel('Summit2', 0);

        expect(summitLevel.getConnections()).to.have.length(2);
        expect(faceLevel.getConnections()).to.have.length(1);
        expect(summit2Level0.getConnections()).to.have.length(2);

    });

    it('has createPresetLevels for creating all levels using factory', () => {
        const fact = new RG.Factory.World();
        const nLevels = 5;
        const towerConf = {
            name: 'Black tower',
            nBranches: 1,
            branch: [{
                name: 'Main branch',
                nLevels: nLevels,
                createPresetLevels: {
                    new: 'BlackTower',
                    args: [180, 90]
                },
                create: {
                    actor: [
                        {name: 'goblin', nLevel: 2},
                        {name: 'Thabba, Son of Ice', nLevel: 4}
                    ]
                }
            }]
        };

        const tower = fact.createDungeon(towerConf);
        const levels = tower.getLevels();
        expect(levels).to.have.length(nLevels);

        levels.forEach((zoneLevel, i) => {
            console.log(zoneLevel);
            const conn = fact.createDungeonZoneConnect(tower, zoneLevel);
            if (i === 0) {
                expect(conn).to.have.property('length');
            }
        });

        const l0 = levels[0];
        const l1 = levels[1];
        expect(l0.getMap().cols, 'L0 Cols correct').to.be.above(180);
        expect(l0.getMap().rows, 'L0 Rows correct').to.be.above(90);
        expect(l1.getMap().cols, 'L1 Cols correct').to.be.equal(180);
        expect(l1.getMap().rows, 'L1 Rows correct').to.be.equal(90);

        l0.debugPrintInASCII();

        const l4 = levels[nLevels - 1];
        // l4.debugPrintInASCII();

        // levels.map(ll => ll.getMap().debugPrintInASCII());
        const actors = l4.getActors();
        const boss = actors.find(actor => actor.getName().match(/Thabba/));
        expect(boss, 'Boss actor was created/found').to.not.be.empty;
        expect(boss.getName()).to.match(/Son of Ice/i);

        const elements0 = l0.getElements();
        expect(elements0.length).to.be.above(0);

        const lever = elements0.find(e => e.getType() === 'lever');
        const leverDoor = elements0.find(e => e.getType() === 'leverdoor');
        const door = elements0.find(e => e.getType() === 'door');
        // console.log(elements0);

        expect(lever).to.not.be.empty;
        expect(leverDoor).to.not.be.empty;
        expect(door).to.not.be.empty;
    });

});
<|endoftext|>


<commit_before>const React = require('react');
const Header = require('components/Header');
const Classes = require('components/Header/styles.scss');
const ReactRouter = require('react-router-dom');
const Enzyme = require('enzyme');

describe('(Component) Header', () => {

    let _wrapper;

    beforeEach(() => {

        _wrapper = Enzyme.shallow(<Header />);
    });

    it('Renders a welcome message', () => {

        const welcome = _wrapper.find('h1');
        expect(welcome).to.exist;
        expect(welcome.text()).to.match(/Strangeluv/);
    });

    describe('Navigation links...', () => {

        it('Should render a Link to Home route', () => {

            expect(_wrapper.contains(
                <ReactRouter.IndexLink activeClassName={Classes.activeRoute} to='/'>
                    Home
                </ReactRouter.IndexLink>
            )).to.be.true;
        });

        it('Should render a Link to Counter route', () => {

            expect(_wrapper.contains(
                <ReactRouter.Link activeClassName={Classes.activeRoute} to='/counter'>
                    Counter
                </ReactRouter.Link>
            )).to.be.true;
        });
    });
});
<commit_msg>update tests to match current routing<commit_after>const React = require('react');
const Header = require('components/Header');
const Classes = require('components/Header/styles.scss');
const NavLink = require('react-router-dom').NavLink;
const Enzyme = require('enzyme');

describe('(Component) Header', () => {

    let _wrapper;

    beforeEach(() => {

        _wrapper = Enzyme.shallow(<Header />);
    });

    it('Renders a welcome message', () => {

        const welcome = _wrapper.find('h1');
        expect(welcome).to.exist;
        expect(welcome.text()).to.match(/Strangeluv/);
    });

    describe('Navigation links...', () => {

        it('Should render a Link to Home route', () => {

            expect(_wrapper.contains(
                <NavLink exact to='/' activeClassName={Classes.activeRoute}>
                    Home
                </NavLink>
            )).to.be.true;
        });

        it('Should render a Link to Counter route', () => {

            expect(_wrapper.contains(
                <NavLink to='/counter' activeClassName={Classes.activeRoute}>
                    Counter
                </NavLink>
            )).to.be.true;
        });
    });
});
<|endoftext|>


<commit_before>/*
   Copyright 2012 Igor Laborie

   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.
*/
// Define some default objets
// Utilities
if (typeof String.prototype.startsWith != "function") {
	// see below for better implementation!
	String.prototype.startsWith = function (str) {
		return this.indexOf(str) === 0;
	};
}

$.postJSON = function(url, data, callback, onError) {
	var fun = doOnError;
	if (onError && $.isFunction(onError)) {
		fun = onError;
	}
    return jQuery.ajax({
        type: "POST",
        url: url,
        contentType: "application/json",
        data: JSON.stringify(data),
        dataType: "json",
        success: callback,
        timeout: 3000,
		tryCount : 0,
		retryLimit : 3,
        onError: fun
    });
};

$.deleteJSON = function(url, data, callback, onError) {
	var fun = doOnError;
	if (onError && $.isFunction(onError)) {
		fun = onError;
	}
    return jQuery.ajax({
        type: "DELETE",
        url: url,
        contentType: "application/json",
        data: JSON.stringify(data),
        dataType: "json",
        success: callback,
        timeout: 3000,
		tryCount : 0,
		retryLimit : 3,
        onError: fun
    });
};

var doOnError = function(xhr, textStatus, errorThrown) {
	var msg = "Error: " +textStatus +"\n"+errorThrown;
	console.log(msg);
	createNotice({
		kind: "error",
		message: msg
	});
};

/**
 * Create a dynamic notice
 */
var createNotice = function(notice) {
	$(".top-right").notify({
		type: notice.kind,
		message: { html: notice.message }
	}).show();
};

/**
 * Open Modal
 */
var openModalDialog = function(title, message, buttons) {
	$("#modalDialog .modal-header h3").html(title);
	$("#modalDialog .modal-body p").empty().append(message);

	var $buttonsBar = $("#modalDialog .modal-footer");
	$buttonsBar.empty();
	if (typeof buttons === "undefined") {
		$buttonsBar.append(createButton({
			text: "Close",
			"data-dismiss" : "modal"
		}));
	} else if ($.isArray(buttons)) {
		for(var i=0; i< buttons.length; i++) {
			$buttonsBar.append(createButton(buttons[i]));
		}
	} else {
		$buttonsBar.append(createButton(buttons));
	}
	$("#modalDialog").unbind("shown").on("shown",function(){
		$("#modalDialog .modal-footer button:last-child").focus();
	}).modal("show");
};

/**
 * Create a button
 */
var createButton = function(props) {
	var text  = props.text;
	var click = props.click;
	var cssClass = "btn";
	if (props["class"]) {
		cssClass += " " +  props["class"];
	}

	var attrs = {};
	for (var p in props) {
		if ((p!== "text") && (p!== "click") && (p!== "class")) {
			attrs[p] = props[p];
		}
	}

	$btn = $("<button/>", attrs).addClass(cssClass).html(text);
	if (typeof click === "function") {
		$btn.click(click);
	}

	return $btn;
};

/**
 * Create an UUID
 */
this.createUuid = function() {
    var S4 = function() {
       return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    };
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
};

/**
 * isInteger
 */
var isInteger = function(s) {
  return ((""+s).search(/^-?[0-9]+$/) === 0);
};

var scollToBottom = function() {
	if ($(".score-left-container").is(":visible")) {
		var h = $(document).height();
		$("body").scrollTop(h);
	}
};

// TODO Board & Darts

// Player
var players = {
	db: [],
	addPlayer: function(player) {
		players.db.push({
			uuid: player.uuid,
			name: player.name,
			surname: player.surname,
			com: player.com,
			comLevel: player.comLevel,
			comTarget: player.comTarget
		});
		// Store to DB
		localStorage.setItem("players", JSON.stringify(players.db));
	},
	update: function(player) {
		var p;
		for (var i=0; i<players.db.length; i++) {
			p = players.db[i];
			if (p.uuid === player.uuid) {
				p.name = player.name;
				p.surname = player.surname;
				p.com = player.com;
				p.comLevel = player.comLevel;
				p.comTarget = player.comTarget;
			}
		}
		// Store to DB
		localStorage.setItem("players", JSON.stringify(players.db));
	},
	getPlayer: function(playerId) {
		var pId = playerId;
		if (pId.lastIndexOf("_")!=-1) {
			var idx = pId.lastIndexOf("_");
			pId = pId.substring(0,idx);
		}
		var p;
		var player;
		for (var i=0; i<players.db.length; i++) {
			p = players.db[i];
			if (p.uuid === pId) {
				player = new Player(p.name, p.surname);
				player.uuid = p.uuid;
				player.com = p.com;
				player.comLevel = p.comLevel;
				player.comTarget = p.comTarget;
				return player;
			}
		}
		player = new Player("Mr. X", null);
		this.addPlayer(player);
		return player;
	},
	getByPrefix : function(prefix) {
		var res = [];
		var player;
		var p;
		for (var i=0; i<players.db.length; i++) {
			p = players.db[i];
			if (prefix===null || prefix==="" || p.name.startsWith(prefix)) {
				player = new Player(p.name, p.surname);
				player.uuid = p.uuid;
				player.com = p.com;
				player.comLevel = p.comLevel;
				player.comTarget = p.comTarget;
				res.push(player);
			}
		}
		return res;
	},
	getPlayerByNameSurname : function(name, surname) {
		var player;
		for (var i=0; i<players.db.length; i++) {
			p = players.db[i];
			if ((p.name === name) && (p.surname===surname)) {
				player = new Player(p.name, p.surname);
				player.uuid = p.uuid;
				player.com = p.com;
				player.comLevel = p.comLevel;
				player.comTarget = p.comTarget;
				return player;
			}
		}
		player = new Player(name, surname);
		this.addPlayer(player);
		return player;
	}
};
// Load to DB
var playersDB = localStorage.getItem("players");
if (playersDB !== null) {
	players.db = JSON.parse(playersDB);
}

function Player(name, surname) {
	this.uuid = createUuid();
	this.name = name;
	this.surname = surname;

	this.com = false;
	this.comLevel = 0;
	this.comTarget = 20;

	// Name
	this.getName = function() {
		var res;
		if (this.name) {
			res = this.name;
		} else {
			res = this.id;
		}
		return res;
	};
	this.getFullName = function() {
		var res = this.getName();
		if (this.surname) {
			res +=  " «"+this.surname+"»";
		}
		return res;
	};
	this.getComputer = function() {
		if (this.com) {
			return ''+this.comLevel+' play ' + this.comTarget;
		} else {
			return '';
		}
	};
}
// Dialog for player selection
$("#diaPlayerSelect .input").keyup(function() {
	var prefix = $(this).val();
	updatePlayerList(prefix);
});
var updatePlayerList = function(prefix) {
	// unselect all & clear list
	$("#diaPlayerSelect .btn-primary").attr("disabled","disabled");
	$("#diaSelectedPlayer").val("");
	$("#diaPlayerSelect .playerList").empty();

	// Fill list
	var p = players.getByPrefix(prefix);
	$.each(p, function(idx, player) {
		$("#diaPlayerSelect .playerList").append(
			$("
").append(
				$("").attr("href", "#").append(player.getFullName()).click(function (event) {
					if ($(this).parent().hasClass("active")) {
						$("#diaSelectedPlayer").val("");
						$("#diaPlayerSelect .btn-primary").attr("disabled","disabled");
						$("#diaPlayerSelect .playerList li").removeClass("active");
					} else {
						$("#diaSelectedPlayer").val(player.uuid);
						$("#diaPlayerSelect .btn-primary").removeAttr("disabled");
						$("#diaPlayerSelect .playerList li").removeClass("active");
						$(this).parent().addClass("active");
					}
					return true;
				})
			)
		);
	});
};

$("#diaPlayerSelect").on("shown", function() {
	$("#diaPlayerSelect .input").focus();
});
var selectPlayer = function(callback) {
	updatePlayerList($("#diaPlayerSelect .input").val());

	$("#diaPlayerSelect .btn-primary").unbind("click").click(function(e) {
		var playerId = $("#diaSelectedPlayer").val();
		if (playerId!=="") {
			var player = players.getPlayer(playerId);
			$("#diaPlayerSelect").modal("hide");
			callback(player);
		}
	});
	$("#diaPlayerSelect").modal("show");
};

// Create player Dialog
$("#playerIsComputer").unbind("change").change(function() {
	if ($(this).is(":checked")) {
		$(".playerComputer").show();
		$(".humanPlayer").hide();
	} else {
		$(".playerComputer").hide();
		$(".humanPlayer").show();
	}
});

$("#diaPlayerCreation").on("shown", function(event) {
	$("#playerName").focus();
});
var createPlayer = function(callback) {
	$("#diaPlayerCreation .btn-success").unbind("click").click(function(event){
		doCreatePlayer(event, callback);
	});
	$("#diaPlayerCreation form").unbind("submit").submit(function(event){
		doCreatePlayer(event, callback);
	});
	$("#diaPlayerCreation").modal("show");
};

var doCreatePlayer = function(event, callback) {
	var name;
	var surname;

	var isComputer = $("#playerIsComputer").is(":checked");
	if (isComputer) {
		name = "Ishur #" + $("#playerLevel").val();
		surname = $("#diaPlayerCreation input[name=playerTarget]:checked").val();
	} else {
		name = $("#playerName").val();
		surname = $("#playerSurname").val();
		if (!name) {
			name = "Mr. X";
		}
	}

	// Create player
	var player;
	// Computer field
	if (isComputer) {
		player = players.getPlayerByNameSurname(name, surname);
		player.com = true;
		player.comLevel = $("#playerLevel").val();
		player.comTarget = $("#diaPlayerCreation input[name=playerTarget]:checked").val();
		players.update(player);
	} else {
		player = players.getPlayerByNameSurname(name, surname);
	}
	$("#diaPlayerCreation").modal("hide");

	// Callback
	if (callback && $.isFunction(callback)) {
		callback(player);
	}

	event.preventDefault();
	return false;
};<commit_msg>Fix Computer Player creation<commit_after>/*
   Copyright 2012 Igor Laborie

   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.
*/
// Define some default objets
// Utilities
if (typeof String.prototype.startsWith != "function") {
	// see below for better implementation!
	String.prototype.startsWith = function (str) {
		return this.indexOf(str) === 0;
	};
}

$.postJSON = function(url, data, callback, onError) {
	var fun = doOnError;
	if (onError && $.isFunction(onError)) {
		fun = onError;
	}
    return jQuery.ajax({
        type: "POST",
        url: url,
        contentType: "application/json",
        data: JSON.stringify(data),
        dataType: "json",
        success: callback,
        timeout: 3000,
		tryCount : 0,
		retryLimit : 3,
        onError: fun
    });
};

$.deleteJSON = function(url, data, callback, onError) {
	var fun = doOnError;
	if (onError && $.isFunction(onError)) {
		fun = onError;
	}
    return jQuery.ajax({
        type: "DELETE",
        url: url,
        contentType: "application/json",
        data: JSON.stringify(data),
        dataType: "json",
        success: callback,
        timeout: 3000,
		tryCount : 0,
		retryLimit : 3,
        onError: fun
    });
};

var doOnError = function(xhr, textStatus, errorThrown) {
	var msg = "Error: " +textStatus +"\n"+errorThrown;
	console.log(msg);
	createNotice({
		kind: "error",
		message: msg
	});
};

/**
 * Create a dynamic notice
 */
var createNotice = function(notice) {
	$(".top-right").notify({
		type: notice.kind,
		message: { html: notice.message }
	}).show();
};

/**
 * Open Modal
 */
var openModalDialog = function(title, message, buttons) {
	$("#modalDialog .modal-header h3").html(title);
	$("#modalDialog .modal-body p").empty().append(message);

	var $buttonsBar = $("#modalDialog .modal-footer");
	$buttonsBar.empty();
	if (typeof buttons === "undefined") {
		$buttonsBar.append(createButton({
			text: "Close",
			"data-dismiss" : "modal"
		}));
	} else if ($.isArray(buttons)) {
		for(var i=0; i< buttons.length; i++) {
			$buttonsBar.append(createButton(buttons[i]));
		}
	} else {
		$buttonsBar.append(createButton(buttons));
	}
	$("#modalDialog").unbind("shown").on("shown",function(){
		$("#modalDialog .modal-footer button:last-child").focus();
	}).modal("show");
};

/**
 * Create a button
 */
var createButton = function(props) {
	var text  = props.text;
	var click = props.click;
	var cssClass = "btn";
	if (props["class"]) {
		cssClass += " " +  props["class"];
	}

	var attrs = {};
	for (var p in props) {
		if ((p!== "text") && (p!== "click") && (p!== "class")) {
			attrs[p] = props[p];
		}
	}

	$btn = $("<button/>", attrs).addClass(cssClass).html(text);
	if (typeof click === "function") {
		$btn.click(click);
	}

	return $btn;
};

/**
 * Create an UUID
 */
this.createUuid = function() {
    var S4 = function() {
       return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    };
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
};

/**
 * isInteger
 */
var isInteger = function(s) {
  return ((""+s).search(/^-?[0-9]+$/) === 0);
};

var scollToBottom = function() {
	if ($(".score-left-container").is(":visible")) {
		var h = $(document).height();
		$("body").scrollTop(h);
	}
};

// TODO Board & Darts

// Player
var players = {
	db: [],
	addPlayer: function(player) {
		players.db.push({
			uuid: player.uuid,
			name: player.name,
			surname: player.surname,
			com: player.com,
			comLevel: player.comLevel,
			comTarget: player.comTarget
		});
		// Store to DB
		localStorage.setItem("players", JSON.stringify(players.db));
	},
	update: function(player) {
		var p;
		for (var i=0; i<players.db.length; i++) {
			p = players.db[i];
			if (p.uuid === player.uuid) {
				p.name = player.name;
				p.surname = player.surname;
				p.com = player.com;
				p.comLevel = player.comLevel;
				p.comTarget = player.comTarget;
			}
		}
		// Store to DB
		localStorage.setItem("players", JSON.stringify(players.db));
	},
	getPlayer: function(playerId) {
		var pId = playerId;
		if (pId.lastIndexOf("_")!=-1) {
			var idx = pId.lastIndexOf("_");
			pId = pId.substring(0,idx);
		}
		var p;
		var player;
		for (var i=0; i<players.db.length; i++) {
			p = players.db[i];
			if (p.uuid === pId) {
				player = new Player(p.name, p.surname);
				player.uuid = p.uuid;
				player.com = p.com;
				player.comLevel = p.comLevel;
				player.comTarget = p.comTarget;
				return player;
			}
		}
		player = new Player("Mr. X", null);
		this.addPlayer(player);
		return player;
	},
	getByPrefix : function(prefix) {
		var res = [];
		var player;
		var p;
		for (var i=0; i<players.db.length; i++) {
			p = players.db[i];
			if (prefix===null || prefix==="" || p.name.startsWith(prefix)) {
				player = new Player(p.name, p.surname);
				player.uuid = p.uuid;
				player.com = p.com;
				player.comLevel = p.comLevel;
				player.comTarget = p.comTarget;
				res.push(player);
			}
		}
		return res;
	},
	getPlayerByNameSurname : function(name, surname) {
		var player;
		for (var i=0; i<players.db.length; i++) {
			p = players.db[i];
			if ((p.name === name) && (p.surname===surname)) {
				player = new Player(p.name, p.surname);
				player.uuid = p.uuid;
				player.com = p.com;
				player.comLevel = p.comLevel;
				player.comTarget = p.comTarget;
				return player;
			}
		}
		player = new Player(name, surname);
		this.addPlayer(player);
		return player;
	}
};
// Load to DB
var playersDB = localStorage.getItem("players");
if (playersDB !== null) {
	players.db = JSON.parse(playersDB);
}

function Player(name, surname) {
	this.uuid = createUuid();
	this.name = name;
	this.surname = surname;

	this.com = false;
	this.comLevel = 0;
	this.comTarget = 20;

	// Name
	this.getName = function() {
		var res;
		if (this.name) {
			res = this.name;
		} else {
			res = this.id;
		}
		return res;
	};
	this.getFullName = function() {
		var res = this.getName();
		if (this.surname) {
			res +=  " «"+this.surname+"»";
		}
		return res;
	};
	this.getComputer = function() {
		if (this.com) {
			return ''+this.comLevel+' play ' + this.comTarget;
		} else {
			return '';
		}
	};
}
// Dialog for player selection
$("#diaPlayerSelect .input").keyup(function() {
	var prefix = $(this).val();
	updatePlayerList(prefix);
});
var updatePlayerList = function(prefix) {
	// unselect all & clear list
	$("#diaPlayerSelect .btn-primary").attr("disabled","disabled");
	$("#diaSelectedPlayer").val("");
	$("#diaPlayerSelect .playerList").empty();

	// Fill list
	var p = players.getByPrefix(prefix);
	$.each(p, function(idx, player) {
		$("#diaPlayerSelect .playerList").append(
			$("
").append(
				$("").attr("href", "#").append(player.getFullName()).click(function (event) {
					if ($(this).parent().hasClass("active")) {
						$("#diaSelectedPlayer").val("");
						$("#diaPlayerSelect .btn-primary").attr("disabled","disabled");
						$("#diaPlayerSelect .playerList li").removeClass("active");
					} else {
						$("#diaSelectedPlayer").val(player.uuid);
						$("#diaPlayerSelect .btn-primary").removeAttr("disabled");
						$("#diaPlayerSelect .playerList li").removeClass("active");
						$(this).parent().addClass("active");
					}
					return true;
				})
			)
		);
	});
};

$("#diaPlayerSelect").on("shown", function() {
	$("#diaPlayerSelect .input").focus();
});
var selectPlayer = function(callback) {
	updatePlayerList($("#diaPlayerSelect .input").val());

	$("#diaPlayerSelect .btn-primary").unbind("click").click(function(e) {
		var playerId = $("#diaSelectedPlayer").val();
		if (playerId!=="") {
			var player = players.getPlayer(playerId);
			$("#diaPlayerSelect").modal("hide");
			callback(player);
		}
	});
	$("#diaPlayerSelect").modal("show");
};

// Create player Dialog

$("#diaPlayerCreation").on("shown", function(event) {
	$("#playerName").focus();
});
var createPlayer = function(callback) {
	$("#playerIsComputer").unbind("click").click(function() {
		if ($(this).is(":checked")) {
			$(".playerComputer").show();
			$(".humanPlayer").hide();
		} else {
			$(".playerComputer").hide();
			$(".humanPlayer").show();
		}
	});

	$("#diaPlayerCreation .btn-success").unbind("click").click(function(event){
		doCreatePlayer(event, callback);
	});
	$("#diaPlayerCreation form").unbind("submit").submit(function(event){
		doCreatePlayer(event, callback);
	});
	$("#diaPlayerCreation").modal("show");
};

var doCreatePlayer = function(event, callback) {
	var name;
	var surname;

	var isComputer = $("#playerIsComputer").is(":checked");
	if (isComputer) {
		name = "Ishur #" + $("#playerLevel").val();
		surname = $("#diaPlayerCreation input[name=playerTarget]:checked").val();
	} else {
		name = $("#playerName").val();
		surname = $("#playerSurname").val();
		if (!name) {
			name = "Mr. X";
		}
	}

	// Create player
	var player;
	// Computer field
	if (isComputer) {
		player = players.getPlayerByNameSurname(name, surname);
		player.com = true;
		player.comLevel = $("#playerLevel").val();
		player.comTarget = $("#diaPlayerCreation input[name=playerTarget]:checked").val();
		players.update(player);
	} else {
		player = players.getPlayerByNameSurname(name, surname);
	}
	$("#diaPlayerCreation").modal("hide");

	// Callback
	if (callback && $.isFunction(callback)) {
		callback(player);
	}

	event.preventDefault();
	return false;
};<|endoftext|>