<commit_before>;
(function(mag) {

  "use strict";

  var mod = {
    modules: [],
    promises: [],
    deferreds: [],
    controllers: [],
    elements: []
  }

  mod.getController = function(module, element, fill) {
    //var controller

    // FireFox support only
    // Removing since we are now native with Object.observe which is only Chrome & Opera

    /*
    if (typeof Proxy !== 'undefined') {
      controller = new Proxy(new module.controller, {
        get: function(target, prop) {
          //more default props like willload, didload, willupdate, didupdate, isupdate
          if (target[prop] === undefined && ['watchers', 'toJSON', 'called', 'onload', 'onunload'].indexOf(prop) === -1) {
            var a = fill.find(element, prop),
              greedy = prop[0] === '$',
              v, // can be an array, object or string
              // for each
              tmp = []
            a.forEach(function(item, index) {
              if (a[index]) {
                if (a[index].value && a[index].value.length > 0) {
                  v = a[index].value
                  if (a[index].type && (a[index].type == 'checkbox' || a[index].type == 'radio')) {
                    v = {
                      _text: v,
                      _checked: a[index].checked
                    }
                    tmp.push(v)
                  }
                } else if (a[index].innerText && a[index].innerText.length > 0) {
                  v = a[index].innerText
                } else if (a[0].innerHTML && a[index].innerHTML.length > 0) {
                  v = a[index].innerHTML
                }
              }
            })
            if (tmp.length > 0 && greedy) return tmp
            return v
          }
          return target[prop]
        }
      })
    } else {
      controller = new module.controller
    }
    */
    return new module.controller
  }

  // function deepFreeze(o) {
  //   var prop, propKey;
  //   Object.freeze(o); // First freeze the object.
  //   for (propKey in o) {
  //     prop = o[propKey];
  //     if (!o.hasOwnProperty(propKey) || !(typeof prop === 'object') || Object.isFrozen(prop)) {
  //       // If the object is on the prototype, not an object, or is already frozen,
  //       // skip it. Note that this might leave an unfrozen reference somewhere in the
  //       // object if there is an already frozen object containing an unfrozen object.
  //       continue;
  //     }

  //     deepFreeze(prop); // Recursively call deepFreeze.
  //   }
  // }

  mod.submodule = function(module, args) {
    // do we need/want this? view/controller will always get the same args
    // difference is that that can't be changed within those functions - does that matter?
    //deepFreeze(args)

    var controller = function() {
        return (module.controller || function() {}).apply(this, args) || this
      },
      view = function(ctrl, ele) {

        if (arguments.length > 1) var nargs = args.concat([].slice.call(arguments, 1))
        module.view.apply(module, nargs ? [ctrl].concat(nargs) : [ctrl])

      },
      output = {
        controller: controller,
        view: view
      }
      // why do we need these?

    //controller.$original = module.controller
    //view.$original = module.view
    controller.$$args = args
    return output
  }

  mod.getArgs = function(i) {
    var args = mod.modules[i] && mod.modules[i].controller && mod.modules[i].controller.$$args ? [mod.controllers[i]].concat(mod.modules[i].controller.$$args) : [mod.controllers[i]]
      // args that contaian circular references will throw an exception up the chain

    attachToArgs(i, args[0], this.elements[i]);

    return args
  }

  var getParent = function(parts, parentElement) {
    for (var i = 1; i < parts.length; i += 2) {
      var key = parts[i];
      var index = parts[i + 1];
      parentElement = mag.fill.find(parentElement, key);
      // console.log(key, index, parentElement[index])
      parentElement = parentElement[index];
    }
    return parentElement;
  };
  var getElement = function(obj, k, i, parentElement) {

    // search within _key if there
    var parts = i.toString().split('.'),
      found;

    if (parts.length >= 3) {
      // recurse
      parentElement = getParent(parts, parentElement)
      found = mag.fill.find(parentElement, k);

    } else {

      var last = parseInt(parts.pop()),
        index = !isNaN(last) ? last : 0;
      found = mag.fill.find(parentElement[index] ? parentElement[index] : parentElement, k);
    }
    // first user input field
    var founder = isInput(found);
    if (founder && !founder.eventOnFocus) {

      var onfocus = function() {
        if (!this.classList.contains('mag-dirty')) {
          this.classList.add('mag-dirty');
        }
      }

      founder.addEventListener("focus", onfocus, false);
      founder.eventOnFocus = true;
    }
    return founder;
  }

  function isInput(items) {

    for (var k in items) {
      if (items[k] && ['INPUT', 'SELECT', 'TEXTAREA'].indexOf(items[k].tagName) !== -1) {
        return items[k];
      }
    }
    return false;
  }
  var attacher = function(i, k, obj, element) {
    var oval = obj[k];
    // if k =='_value' use parent
    if (k === '_value') k = i.split('.').pop();

    // only for user input fields
    var found = mag.fill.find(element, k);
    var founder = isInput(found);
    if (typeof oval !== 'function' && founder) {

      var founderCall = getElement.bind({}, obj, k, i, element);
      founderCall();
      Object.defineProperty(obj, k, {
        configurable: true,
        get: function() {
          var founder = founderCall();

          // set on focus listener once
          if (founder && founder.value !== 'undefined' && founder.classList.contains('mag-dirty') && founder.value !== oval) {
            oval = founder.value;
            return founder.value;
          }
          return oval;
        },
        set: function(newValue) {
          var founder = founderCall();

          if (founder && founder.value !== 'undefined' && founder.value !== newValue && newValue !== oval) {
            founder.value = newValue;
            oval = newValue;
          }
        }
      });
    }
  };

  function attachToArgs(i, args, element) {

    // for each property set accessor property

    // get notification when accessed

    // call fill to get and assign

    //if (!added[i]) added[i] = [];

    for (var k in args) {

      var value = args[k]

      if (Array.isArray(value) && value[0] && !value[0].__$$i && typeof value[0].then !== 'undefined' && typeof value[0].type != 'fun') {
        value[0].__$$i = 1
        Promise.all(value).then(function(args, k, val) {
          if (val) {
            value[0].__$$i == 0
            args[k] = val
            mag.redraw()
          }
        }.bind(this, args, k))

      } else if (typeof value === 'object' && (!value || typeof value.then === 'undefined')) {
        // recurse
        attachToArgs(i + '.' + k, value, element);
      } else {
        if (value && !Array.isArray(value) && !value.__$$i && typeof value.then !== 'undefined' && typeof value.type != 'fun') {
          value.__$$i = 1
            // promise
          value.then(function(args, k, val) {
            if (val) {
              value.__$$i = 0
              args[k] = val
              mag.redraw()
            }
          }.bind(this, args, k))

        }

        //if (!added[i][k]) {
        attacher(i, k, args, element);
        //  added[i][k] = true;
        // }
      }
    }
  }

  mag.mod = mod

})(window.mag || {})
<commit_msg>Update module.js<commit_after>;
(function(mag) {

  "use strict";

  var mod = {
    modules: [],
    promises: [],
    deferreds: [],
    controllers: [],
    elements: []
  }

  mod.getController = function(module, element, fill) {
    //var controller

    // FireFox support only
    // Removing since we are now native with Object.observe which is only Chrome & Opera

    /*
    if (typeof Proxy !== 'undefined') {
      controller = new Proxy(new module.controller, {
        get: function(target, prop) {
          //more default props like willload, didload, willupdate, didupdate, isupdate
          if (target[prop] === undefined && ['watchers', 'toJSON', 'called', 'onload', 'onunload'].indexOf(prop) === -1) {
            var a = fill.find(element, prop),
              greedy = prop[0] === '$',
              v, // can be an array, object or string
              // for each
              tmp = []
            a.forEach(function(item, index) {
              if (a[index]) {
                if (a[index].value && a[index].value.length > 0) {
                  v = a[index].value
                  if (a[index].type && (a[index].type == 'checkbox' || a[index].type == 'radio')) {
                    v = {
                      _text: v,
                      _checked: a[index].checked
                    }
                    tmp.push(v)
                  }
                } else if (a[index].innerText && a[index].innerText.length > 0) {
                  v = a[index].innerText
                } else if (a[0].innerHTML && a[index].innerHTML.length > 0) {
                  v = a[index].innerHTML
                }
              }
            })
            if (tmp.length > 0 && greedy) return tmp
            return v
          }
          return target[prop]
        }
      })
    } else {
      controller = new module.controller
    }
    */
    return new module.controller
  }

  // function deepFreeze(o) {
  //   var prop, propKey;
  //   Object.freeze(o); // First freeze the object.
  //   for (propKey in o) {
  //     prop = o[propKey];
  //     if (!o.hasOwnProperty(propKey) || !(typeof prop === 'object') || Object.isFrozen(prop)) {
  //       // If the object is on the prototype, not an object, or is already frozen,
  //       // skip it. Note that this might leave an unfrozen reference somewhere in the
  //       // object if there is an already frozen object containing an unfrozen object.
  //       continue;
  //     }

  //     deepFreeze(prop); // Recursively call deepFreeze.
  //   }
  // }

  mod.submodule = function(module, args) {
    // do we need/want this? view/controller will always get the same args
    // difference is that that can't be changed within those functions - does that matter?
    //deepFreeze(args)

    var controller = function() {
        return (module.controller || function() {}).apply(this, args) || this
      },
      view = function(ctrl, ele) {

        if (arguments.length > 1) var nargs = args.concat([].slice.call(arguments, 1))
        module.view.apply(module, nargs ? [ctrl].concat(nargs) : [ctrl])

      },
      output = {
        controller: controller,
        view: view
      }
      // why do we need these?

    //controller.$original = module.controller
    //view.$original = module.view
    controller.$$args = args
    return output
  }

  mod.getArgs = function(i) {
    var args = mod.modules[i] && mod.modules[i].controller && mod.modules[i].controller.$$args ? [mod.controllers[i]].concat(mod.modules[i].controller.$$args) : [mod.controllers[i]]
      // args that contaian circular references will throw an exception up the chain

    attachToArgs(i, args[0], this.elements[i]);

    return args
  }

  var getParent = function(parts, parentElement) {
    for (var i = 1; i < parts.length; i += 2) {
      var key = parts[i];
      var index = parts[i + 1];
      parentElement = mag.fill.find(parentElement, key);
      // console.log(key, index, parentElement[index])
      parentElement = parentElement[index];
    }
    return parentElement;
  };
  var getElement = function(obj, k, i, parentElement) {

    // search within _key if there
    var parts = i.toString().split('.'),
      found;

    if (parts.length >= 3) {
      // recurse
      parentElement = getParent(parts, parentElement)
      found = mag.fill.find(parentElement, k);

    } else {

      var last = parseInt(parts.pop()),
        index = !isNaN(last) ? last : 0;
      found = mag.fill.find(parentElement[index] ? parentElement[index] : parentElement, k);
    }
    // first user input field
    var founder = isInput(found);
    if (founder && !founder.eventOnFocus) {

      var onfocus = function() {
        if (!this.classList.contains('mag-dirty')) {
          this.classList.add('mag-dirty');
        }
      }

      founder.addEventListener("focus", onfocus, false);
      founder.eventOnFocus = true;
    }
    return founder;
  }

  function isInput(items) {

    for (var k in items) {
      if (items[k] && ['INPUT', 'SELECT', 'TEXTAREA'].indexOf(items[k].tagName) !== -1) {
        return items[k];
      }
    }
    return false;
  }
  var attacher = function(i, k, obj, element) {
    var oval = obj[k];
    // if k =='_value' use parent
    if (k === '_value') k = i.split('.').pop();

    // only for user input fields
    var found = mag.fill.find(element, k);
    var founder = isInput(found);
    if (typeof oval !== 'function' && founder) {

      var founderCall = getElement.bind({}, obj, k, i, element);
      founderCall();
      Object.defineProperty(obj, k, {
        configurable: true,
        get: function() {
          var founder = founderCall();

          // set on focus listener once
          if (founder && founder.value !== 'undefined' && founder.classList.contains('mag-dirty') && founder.value !== oval) {
            oval = founder.value;
            return founder.value;
          }
          return oval;
        },
        set: function(newValue) {
          var founder = founderCall();

          if (founder && founder.value !== 'undefined' && founder.value !== newValue && newValue !== oval) {
            founder.value = newValue;
            oval = newValue;
          }
        }
      });
    }
  };

  function attachToArgs(i, args, element) {

    // for each property set accessor property

    // get notification when accessed

    // call fill to get and assign

    //if (!added[i]) added[i] = [];

    for (var k in args) {

      var value = args[k]

      if (Array.isArray(value) && value[0] && !value[0].__$$i && typeof value[0].then !== 'undefined' && typeof value[0].type != 'fun') {
        value[0].__$$i = 1
        Promise.all(value).then(function(args, k, val) {
          if (val) {
            value[0].__$$i == 0
            args[k] = val
            mag.redraw()
          }
        }.bind(this, args, k))

      } else if (typeof value === 'object' && (!value || typeof value.then === 'undefined')) {
        // recurse
        attachToArgs(i + '.' + k, value, element);
      } else {
        if (value && !Array.isArray(value) && !value.__$$i && typeof value.then !== 'undefined' && typeof value.type != 'fun') {
          value.__$$i = 1
            // promise
          value.then(function(args, k, val) {
            if (val) {
              args[k].__$$i = 0
              args[k] = val
              mag.redraw()
            }
          }.bind(this, args, k))

        }

        //if (!added[i][k]) {
        attacher(i, k, args, element);
        //  added[i][k] = true;
        // }
      }
    }
  }

  mag.mod = mod

})(window.mag || {})
<|endoftext|>


<commit_before>//requirements
var c               = require("../config/constantes");
var world           = require("../world");
var input           = require("../controllers/inputs");
var addRenderSystem = require("../modules/render");
var Bullet          = require("../models/bullet");
var EXPLOSION       = require("../models/explosion");
var EventEmitter    = require("../../lib/events-emitter.js");

var Player = function Player(params)
{
    this.id                = world.gameObjects.length;
    this.tag               = params.tag;
    this.layer             = "player";
    this.playerID          = params.playerID;
    this.gamepad           = input.gamepads[this.playerID];
    this.position          = params.position         || { x : 0, y : 0 };
    this.size              = params.size             || { width : 50, height : 50 };
    this.speed             = params.speed            || 10;
    this.zIndex            = params.zIndex           || 1000;
    this.context           = params.context          || world.context;
    this.angle             = params.startAngle       || 0;
    this.vecDir            = { x : Math.cos(this.angle), y : Math.sin(this.angle) };

    this.attackLimit       = params.attackLimit      || 100;
    this.attackDelay       = params.attackDelay      || 100;
    this.prevShot          = 0;

    this.hitPoints         = params.hitPoints        || 10;
    this.maxHitPoints      = this.hitPoints;
    this.shielded          = false;
    this.respawnRange      = params.respawnRange     || 200;

    this.dashSpeed         = params.dashSpeed        || 100;
    this.dashDelay         = params.dashDelay        || 5000;
    this.prevDash          = 0;

    this.spritesheet       = params.spritesheet;
    this.spritesheetBullet = params.spritesheetBullet;
    this.spriteSize        = params.spriteSize || { width : 128, height : 128 };
    this.anims             = params.anims;
    this.activeAnim        = this.anims[params.activeAnim] || this.anims['idle'];
    this.animY             = this.activeAnim["animY"];

    // this.createGauge();

    this.colliderPadding   = params.colliderPadding || 20;

    if (this.playerID === 1)
    {
        this.frameNum = 2;
    }

    var self = this;
    this.on("set animation", function(name) {
        if (self.activeAnim != self.anims[name])
        {
            self.activeAnim  = self.anims[name];
            self.animY       = self.activeAnim["animY"];
            self.frameNum    = 0;
            self.frameCount  = 0;
            self.isAnimating = true;
        }
    });

    this.shield();

    this.run = function()
    {
        this.rotate();
        this.move();
        this.dash();
        this.limits();
        this.shoot();
        this.collisions();
        this.animate();
    }
}

// Player.prototype.createGauge = function()
// {
//     world.create(new Gauge({playerID : this.playerID}));
// }

Player.prototype.rotate = function()
{
    var axisX = input.getAxis("RIGHT_HORIZONTAL", this.playerID);
    var axisY = input.getAxis("RIGHT_VERTICAL", this.playerID);

    if ((axisX < -c.ANALOG_DEAD || axisX > c.ANALOG_DEAD) || (axisY < -c.ANALOG_DEAD || axisY > c.ANALOG_DEAD))
    {
        this.angle  = (Math.atan2(axisX, axisY) - Math.PI/2) * -1;
        this.vecDir = { x : Math.cos(this.angle), y : Math.sin(this.angle) };
    }
}

Player.prototype.move = function()
{
    this.prevPos =
    {
        x : this.position.x,
        y : this.position.y
    }

    var axisX = input.getAxis("LEFT_HORIZONTAL", this.playerID);
    var axisY = input.getAxis("LEFT_VERTICAL", this.playerID);

    this.moving = false;

    if (axisX < -c.ANALOG_DEAD || axisX > c.ANALOG_DEAD)
    {
        this.position.x += this.speed * axisX;
        this.moving = true;
    }

    if (axisY < -c.ANALOG_DEAD || axisY > c.ANALOG_DEAD)
    {
        this.position.y += this.speed * axisY;
        this.moving = true;
    }

    if (!this.shielded)
    {
        if (this.moving)
        {
            this.trigger("set animation", "fly");
        }
        else
        {
            this.trigger("set animation", "idle");
        }
    }
}

Player.prototype.limits = function()
{
    if (this.position.x < 0 || this.position.x + this.size.width > c.GAME_WIDTH)
    {
        this.position.x = this.prevPos.x;
    }
    if (this.position.y < 0 || this.position.y + this.size.height > c.GAME_HEIGHT)
    {
        this.position.y = this.prevPos.y;
    }
}

Player.prototype.dash = function()
{
    var datTime = new Date().getTime();

    if (datTime - this.prevDash > this.dashDelay)
    {
        if (input.getKeyDown("LB", this.playerID))
        {
            this.position.x += Math.sin(this.angle) * this.dashSpeed;
            this.position.y += - Math.cos(this.angle) * this.dashSpeed;
            this.prevDash = new Date().getTime();
        }

        if (input.getKeyDown("RB", this.playerID))
        {
            this.position.x += - Math.sin(this.angle) * this.dashSpeed;
            this.position.y += Math.cos(this.angle) * this.dashSpeed;
            this.prevDash = new Date().getTime();
        }
    }
}

Player.prototype.shoot = function()
{
    if (input.getButtonDown("Fire", this.playerID) && !this.shielded)
    {
        var datTime = new Date().getTime();

        this.animY = this.activeAnim["animY"] + 256;

        if (datTime - this.prevShot > this.attackDelay)
        {

            if (this.moving)
            {
                var canonDistance = this.size.width / 2;
            }
            else
            {
                var canonDistance = this.size.width / 2 - 10;
            }

            world.create(new Bullet(
                {
                    playerID : this.playerID,
                    position : {
                        x : (this.position.x + this.size.width / 2)  + this.vecDir.x * canonDistance - 15,
                        y : (this.position.y + this.size.height / 2) + this.vecDir.y * canonDistance - 7
                    },
                    size : { width : 40, height : 20 },
                    layer : this.layer,
                    startAngle : this.angle,
                    spritesheet : this.spritesheetBullet,
                    speed : 20,
                    anims : c.ANIMATIONS["BULLET_FIRE"],
                }));

            this.prevShot = new Date().getTime();
            this.attackLimit -= 10;
        }
    }
    else
    {
        this.animY = this.activeAnim["animY"];
    }
}

Player.prototype.collisions = function()
{
    for (var i = 0; i < world.gameObjects.length; i++)
    {
        var other = world.gameObjects[i];

        if (other.layer === "enemy" || (other.layer === "player" && other.playerID !== this.playerID))
        {
            if (other.position.x + other.size.width  > this.position.x + this.colliderPadding &&
                other.position.x < this.position.x + this.size.width - this.colliderPadding  &&
                other.position.y + other.size.width > this.position.y + this.colliderPadding &&
                other.position.y < this.position.y + this.size.width - this.colliderPadding)
            {
                if (!this.shielded)
                {
                    this.hitPoints -= other.damage;
                }
                if (other.layer === "enemy")
                {
                    other.dead = true;
                    world.create(new EXPLOSION({
                        position : { x : other.position.x, y : other.position.y },
                        size : { width  : other.size.width, height : other.size.width },
                        zIndex : this.zIndex+1,
                        spritesheet : world.manifest.images["dragon_explosion.png"],
                        anims  : c.ANIMATIONS["EXPLOSION"],
                        spriteSize : { width : 380, height : 380 }
                    }));
                }

                if (this.isDead())
                {
                    this.respawn();
                }
            }
        }
    }
}

Player.prototype.respawn = function()
{
    world.create(new EXPLOSION({
        position : { x : this.position.x - 100, y : this.position.y - 100 },
        size : { width  : this.size.width + 200, height : this.size.width + 200 },
        zIndex : this.zIndex+1,
        spritesheet : world.manifest.images["dragon_explosion.png"],
        anims  : c.ANIMATIONS["EXPLOSION"],
        spriteSize : { width : 380, height : 380 }
    }));

    this.hitPoints = this.maxHitPoints;

    //random respawn pos : TO DO

    this.shield();
}

Player.prototype.shield = function()
{
    this.shielded = true;
    this.trigger("set animation", "shield");
    var self = this;
    setTimeout(function() {
        self.shielded = false;
        self.trigger("set animation", (this.moving) ? "fly" : "idle");
    }, 3000);
}

Player.prototype.isDead = function()
{
    if (this.hitPoints <= 0)
        return true;
}

EventEmitter.mixins(Player.prototype);
addRenderSystem(Player.prototype);

module.exports = Player;<commit_msg>fix canon player<commit_after>//requirements
var c               = require("../config/constantes");
var world           = require("../world");
var input           = require("../controllers/inputs");
var addRenderSystem = require("../modules/render");
var Bullet          = require("../models/bullet");
var EXPLOSION       = require("../models/explosion");
var EventEmitter    = require("../../lib/events-emitter.js");

var Player = function Player(params)
{
    this.id                = world.gameObjects.length;
    this.tag               = params.tag;
    this.layer             = "player";
    this.playerID          = params.playerID;
    this.gamepad           = input.gamepads[this.playerID];
    this.position          = params.position         || { x : 0, y : 0 };
    this.size              = params.size             || { width : 50, height : 50 };
    this.speed             = params.speed            || 10;
    this.zIndex            = params.zIndex           || 1000;
    this.context           = params.context          || world.context;
    this.angle             = params.startAngle       || 0;
    this.vecDir            = { x : Math.cos(this.angle), y : Math.sin(this.angle) };

    this.attackLimit       = params.attackLimit      || 100;
    this.attackDelay       = params.attackDelay      || 100;
    this.prevShot          = 0;

    this.hitPoints         = params.hitPoints        || 10;
    this.maxHitPoints      = this.hitPoints;
    this.shielded          = false;
    this.respawnRange      = params.respawnRange     || 200;

    this.dashSpeed         = params.dashSpeed        || 100;
    this.dashDelay         = params.dashDelay        || 5000;
    this.prevDash          = 0;

    this.spritesheet       = params.spritesheet;
    this.spritesheetBullet = params.spritesheetBullet;
    this.spriteSize        = params.spriteSize || { width : 128, height : 128 };
    this.anims             = params.anims;
    this.activeAnim        = this.anims[params.activeAnim] || this.anims['idle'];
    this.animY             = this.activeAnim["animY"];

    // this.createGauge();

    this.colliderPadding   = params.colliderPadding || 20;

    if (this.playerID === 1)
    {
        this.frameNum = 2;
    }

    var self = this;
    this.on("set animation", function(name) {
        if (self.activeAnim != self.anims[name])
        {
            self.activeAnim  = self.anims[name];
            self.animY       = self.activeAnim["animY"];
            self.frameNum    = 0;
            self.frameCount  = 0;
            self.isAnimating = true;
        }
    });

    this.shield();

    this.run = function()
    {
        this.rotate();
        this.move();
        this.dash();
        this.limits();
        this.shoot();
        this.collisions();
        this.animate();
    }
}

// Player.prototype.createGauge = function()
// {
//     world.create(new Gauge({playerID : this.playerID}));
// }

Player.prototype.rotate = function()
{
    var axisX = input.getAxis("RIGHT_HORIZONTAL", this.playerID);
    var axisY = input.getAxis("RIGHT_VERTICAL", this.playerID);

    if ((axisX < -c.ANALOG_DEAD || axisX > c.ANALOG_DEAD) || (axisY < -c.ANALOG_DEAD || axisY > c.ANALOG_DEAD))
    {
        this.angle  = (Math.atan2(axisX, axisY) - Math.PI/2) * -1;
        this.vecDir = { x : Math.cos(this.angle), y : Math.sin(this.angle) };
    }
}

Player.prototype.move = function()
{
    this.prevPos =
    {
        x : this.position.x,
        y : this.position.y
    }

    var axisX = input.getAxis("LEFT_HORIZONTAL", this.playerID);
    var axisY = input.getAxis("LEFT_VERTICAL", this.playerID);

    this.moving = false;

    if (axisX < -c.ANALOG_DEAD || axisX > c.ANALOG_DEAD)
    {
        this.position.x += this.speed * axisX;
        this.moving = true;
    }

    if (axisY < -c.ANALOG_DEAD || axisY > c.ANALOG_DEAD)
    {
        this.position.y += this.speed * axisY;
        this.moving = true;
    }

    if (!this.shielded)
    {
        if (this.moving)
        {
            this.trigger("set animation", "fly");
        }
        else
        {
            this.trigger("set animation", "idle");
        }
    }
}

Player.prototype.limits = function()
{
    if (this.position.x < 0 || this.position.x + this.size.width > c.GAME_WIDTH)
    {
        this.position.x = this.prevPos.x;
    }
    if (this.position.y < 0 || this.position.y + this.size.height > c.GAME_HEIGHT)
    {
        this.position.y = this.prevPos.y;
    }
}

Player.prototype.dash = function()
{
    var datTime = new Date().getTime();

    if (datTime - this.prevDash > this.dashDelay)
    {
        if (input.getKeyDown("LB", this.playerID))
        {
            this.position.x += Math.sin(this.angle) * this.dashSpeed;
            this.position.y += - Math.cos(this.angle) * this.dashSpeed;
            this.prevDash = new Date().getTime();
        }

        if (input.getKeyDown("RB", this.playerID))
        {
            this.position.x += - Math.sin(this.angle) * this.dashSpeed;
            this.position.y += Math.cos(this.angle) * this.dashSpeed;
            this.prevDash = new Date().getTime();
        }
    }
}

Player.prototype.shoot = function()
{
    if (input.getButtonDown("Fire", this.playerID) && !this.shielded)
    {
        var datTime = new Date().getTime();

        this.animY = this.activeAnim["animY"] + 256;

        if (datTime - this.prevShot > this.attackDelay)
        {

            if (this.moving)
            {
                var canonDistance = this.size.width / 2;
            }
            else
            {
                var canonDistance = this.size.width / 2 - 10;
            }

            world.create(new Bullet(
                {
                    playerID : this.playerID,
                    position : {
                        x : (this.position.x + this.size.width / 2)  + this.vecDir.x * canonDistance - 20,
                        y : (this.position.y + this.size.height / 2) + this.vecDir.y * canonDistance - 10
                    },
                    size : { width : 40, height : 20 },
                    layer : this.layer,
                    startAngle : this.angle,
                    spritesheet : this.spritesheetBullet,
                    speed : 20,
                    anims : c.ANIMATIONS["BULLET_FIRE"],
                }));

            this.prevShot = new Date().getTime();
            this.attackLimit -= 10;
        }
    }
    else
    {
        this.animY = this.activeAnim["animY"];
    }
}

Player.prototype.collisions = function()
{
    for (var i = 0; i < world.gameObjects.length; i++)
    {
        var other = world.gameObjects[i];

        if (other.layer === "enemy" || (other.layer === "player" && other.playerID !== this.playerID))
        {
            if (other.position.x + other.size.width  > this.position.x + this.colliderPadding &&
                other.position.x < this.position.x + this.size.width - this.colliderPadding  &&
                other.position.y + other.size.width > this.position.y + this.colliderPadding &&
                other.position.y < this.position.y + this.size.width - this.colliderPadding)
            {
                if (!this.shielded)
                {
                    this.hitPoints -= other.damage;
                }
                if (other.layer === "enemy")
                {
                    other.dead = true;
                    world.create(new EXPLOSION({
                        position : { x : other.position.x, y : other.position.y },
                        size : { width  : other.size.width, height : other.size.width },
                        zIndex : this.zIndex+1,
                        spritesheet : world.manifest.images["dragon_explosion.png"],
                        anims  : c.ANIMATIONS["EXPLOSION"],
                        spriteSize : { width : 380, height : 380 }
                    }));
                }

                if (this.isDead())
                {
                    this.respawn();
                }
            }
        }
    }
}

Player.prototype.respawn = function()
{
    world.create(new EXPLOSION({
        position : { x : this.position.x - 100, y : this.position.y - 100 },
        size : { width  : this.size.width + 200, height : this.size.width + 200 },
        zIndex : this.zIndex+1,
        spritesheet : world.manifest.images["dragon_explosion.png"],
        anims  : c.ANIMATIONS["EXPLOSION"],
        spriteSize : { width : 380, height : 380 }
    }));

    this.hitPoints = this.maxHitPoints;

    //random respawn pos : TO DO

    this.shield();
}

Player.prototype.shield = function()
{
    this.shielded = true;
    this.trigger("set animation", "shield");
    var self = this;
    setTimeout(function() {
        self.shielded = false;
        self.trigger("set animation", (this.moving) ? "fly" : "idle");
    }, 3000);
}

Player.prototype.isDead = function()
{
    if (this.hitPoints <= 0)
        return true;
}

EventEmitter.mixins(Player.prototype);
addRenderSystem(Player.prototype);

module.exports = Player;<|endoftext|>


<commit_before>/**
 * module.js - The core of module loader
 */

var cachedModules = seajs.cache = {}

var STATUS = {
  'LOADING': 1,   // The module file is loading
  'SAVED': 2,     // The module data has been saved to cachedModules
  'LOADED': 3,    // The module and all its dependencies are ready to compile
  'COMPILING': 4, // The module is being compiled
  'COMPILED': 5   // The module is compiled and `module.exports` is available
}

function Module(uri, status) {
  this.uri = uri
  this.status = status || STATUS.LOADING
  this.dependencies = []
  this.waitings = []
}

Module.prototype.load = function(ids, callback) {
  var uris = resolve(isArray(ids) ? ids : [ids], this.uri)

  load(uris, function() {
    var exports = map(uris, function(uri) {
      return compile(cachedModules[uri])
    })

    if (callback) {
      callback.apply(global, exports)
    }
  })
}

function resolve(ids, refUri) {
  if (isArray(ids)) {
    return map(ids, function(id) {
      return resolve(id, refUri)
    })
  }

  var id = ids, uri
  id = emitData('resolve', { id: id, refUri: refUri }, 'id')
  uri = id2Uri(id, refUri)
  uri = emitData('resolved', { uri: uri })
  return uri
}

function load(uris, callback, options) {
  options = options || {}
  var unloadedUris = options.filtered ? uris : getUnloadedUris(uris)

  if (unloadedUris.length === 0) {
    callback()
    return
  }

  // Emit load event for plugins such as combo plugin
  emit('load', unloadedUris)

  var len = unloadedUris.length
  var remain = len

  for (var i = 0; i < len; i++) {
    (function(uri) {

      var mod = cachedModules[uri]
      mod.status < STATUS.SAVED ? fetch(uri, onFetched) : onFetched()

      function onFetched() {
        // Maybe failed to fetch successfully, such as 404 error
        // In these cases, just call `cb` function directly
        if (mod.status < STATUS.SAVED) {
          done()
          return
        }

        // Break circular waiting callbacks
        if (isCircularWaiting(mod)) {
          printCircularLog(circularStack)
          circularStack.length = 0
          done(mod)
          return
        }

        // Load all unloaded dependencies
        var waitings = mod.waitings = getUnloadedUris(mod.dependencies)
        if (waitings.length === 0) {
          done(mod)
          return
        }

        load(waitings, function() {
          done(mod)
        }, { filtered: true })
      }

    })(unloadedUris[i])
  }

  function done(mod) {
    if (mod && mod.status < STATUS.LOADED) {
      mod.status = STATUS.LOADED
    }

    if (--remain === 0) {
      callback()
    }
  }
}

var fetchingList = {}
var fetchedList = {}
var callbackList = {}
var anonymousModuleMeta = null

function fetch(uri, callback) {
  // Emit `fetch` event. Plugins could use this event to
  // modify uri or do other magic things
  var requestUri = emitData('fetch',
      { uri: uri, fetchedList: fetchedList },
      'uri')

  if (fetchedList[requestUri]) {
    callback()
    return
  }

  if (fetchingList[requestUri]) {
    callbackList[requestUri].push(callback)
    return
  }

  fetchingList[requestUri] = true
  callbackList[requestUri] = [callback]

  // Send request
  var charset = config.charset
  var requested = emitData('request',
      { uri: requestUri, callback: onRequested, charset: charset },
      'requested')

  if (!requested) {
    request(requestUri, onRequested, charset)
  }

  function onRequested() {
    delete fetchingList[requestUri]
    fetchedList[requestUri] = true

    // Save meta data of anonymous module
    if (anonymousModuleMeta) {
      save(uri, anonymousModuleMeta)
      anonymousModuleMeta = null
    }

    // Call callbacks
    var fn, fns = callbackList[requestUri]
    delete callbackList[requestUri]
    while ((fn = fns.shift())) fn()
  }
}

function define(id, deps, factory) {
  var argsLen = arguments.length

  // HANDLE: define(factory)
  if (argsLen === 1) {
    factory = id
    id = undefined
  }
  // HANDLE: define(id || deps, factory)
  else if (argsLen === 2) {
    factory = deps
    deps = undefined

    // HANDLE: define(deps, factory)
    if (isArray(id)) {
      deps = id
      id = undefined
    }
  }

  // Parse dependencies according to the module factory code
  if (!isArray(deps) && isFunction(factory)) {
    deps = parseDependencies(factory.toString())
  }

  var meta = { id: id, dependencies: deps, factory: factory }
  var derivedUri

  // Try to derive uri in IE6-9 for anonymous modules
  if (!id && doc.attachEvent) {
    var script = getCurrentScript()

    if (script && script.src) {
      derivedUri = getScriptAbsoluteSrc(script)
      derivedUri = emitData('derived', { uri: derivedUri })
    }
    else {
      log('Failed to derive URI from interactive script for:',
          factory.toString(), 'warn')

      // NOTE: If the id-deriving methods above is failed, then falls back
      // to use onload event to get the uri
    }
  }

  var resolvedUri = id ? resolve(id) : derivedUri

  if (resolvedUri) {
    save(resolvedUri, meta)
  }
  else {
    // Save information for "memoizing" work in the script onload event
    anonymousModuleMeta = meta
  }

}

function save(uri, meta) {
  var mod = cachedModules[uri]

  // Do NOT override already saved modules
  if (mod.status < STATUS.SAVED) {
    mod.id = meta.id || uri // Let anonymous module id equal to its uri
    mod.dependencies = resolve(meta.dependencies || [], uri)
    mod.factory = meta.factory

    mod.status = STATUS.SAVED
  }
}

function compile(mod) {
  // When module is compiled, DO NOT compile it again. When module
  // is being compiled, just return `module.exports` too, for avoiding
  // circularly calling
  if (mod.status >= STATUS.COMPILING) {
    return mod.exports
  }

  emit('compile', mod)

  // Just return `null` when:
  //  1. the module file is 404
  //  2. the module file is not written with valid module format
  //  3. other error cases
  if (mod.status < STATUS.LOADED && mod.exports === undefined) {
    return null
  }

  mod.status = STATUS.COMPILING

  function require(id) {
    var child = cachedModules[require.resolve(id)]

    // Return `null` when `uri` is invalid
    if (child === undefined) {
      return null
    }

    child.parent = mod
    return compile(child)
  }

  require.async = function(ids, callback) {
    mod.load(ids, callback)
  }

  require.resolve = function(id) {
    return resolve(id, mod.uri)
  }

  require.cache = cachedModules

  mod.require = require
  mod.exports = mod.exports || {}
  delete mod.waitings

  var factory = mod.factory
  var exports = factory

  if (isFunction(factory)) {
    exports = factory(mod.require, mod.exports, mod)
  }

  if (exports !== undefined) {
    mod.exports = exports
  }

  mod.status = STATUS.COMPILED
  emit('compiled', mod)

  return mod.exports
}

// Helpers

function createModule(uri, status) {
  return cachedModules[uri] ||
      (cachedModules[uri] = new Module(uri, status))
}

function getUnloadedUris(uris) {
  return filter(uris, function(uri) {
    return createModule(uri).status < STATUS.LOADED
  })
}

var circularStack = []

function isCircularWaiting(mod) {
  var waitings = mod.waitings
  if (waitings.length === 0) {
    return false
  }

  circularStack.push(mod.uri)
  if (isOverlap(waitings, circularStack)) {
    return true
  }

  for (var i = 0; i < waitings.length; i++) {
    if (isCircularWaiting(cachedModules[waitings[i]])) {
      return true
    }
  }

  circularStack.pop()
  return false
}

function printCircularLog(stack) {
  stack.push(stack[0])
  log('Found circular dependencies:', stack.join(' --> '))
}

function isOverlap(arrA, arrB) {
  var arrC = arrA.concat(arrB)
  return  unique(arrC).length < arrC.length
}

// Public API

var globalModule = new Module(pageUri, STATUS.COMPILED)

function preload(callback) {
  var preloadModules = config.preload
  var len = preloadModules.length

  len ? globalModule.load(preloadModules.splice(0, len), callback) :
      callback()
}

seajs.use = function(ids, callback) {
  // Load preload modules before all other modules
  preload(function() {
    globalModule.load(ids, callback)
  })
  return seajs
}

global.define = define

<commit_msg>Fix saving bug for static included modules<commit_after>/**
 * module.js - The core of module loader
 */

var cachedModules = seajs.cache = {}

var STATUS = {
  'LOADING': 1,   // The module file is loading
  'SAVED': 2,     // The module data has been saved to cachedModules
  'LOADED': 3,    // The module and all its dependencies are ready to compile
  'COMPILING': 4, // The module is being compiled
  'COMPILED': 5   // The module is compiled and `module.exports` is available
}

function Module(uri, status) {
  this.uri = uri
  this.status = status || STATUS.LOADING
  this.dependencies = []
  this.waitings = []
}

Module.prototype.load = function(ids, callback) {
  var uris = resolve(isArray(ids) ? ids : [ids], this.uri)

  load(uris, function() {
    var exports = map(uris, function(uri) {
      return compile(cachedModules[uri])
    })

    if (callback) {
      callback.apply(global, exports)
    }
  })
}

function resolve(ids, refUri) {
  if (isArray(ids)) {
    return map(ids, function(id) {
      return resolve(id, refUri)
    })
  }

  var id = ids, uri
  id = emitData('resolve', { id: id, refUri: refUri }, 'id')
  uri = id2Uri(id, refUri)
  uri = emitData('resolved', { uri: uri })
  return uri
}

function load(uris, callback, options) {
  options = options || {}
  var unloadedUris = options.filtered ? uris : getUnloadedUris(uris)

  if (unloadedUris.length === 0) {
    callback()
    return
  }

  // Emit load event for plugins such as combo plugin
  emit('load', unloadedUris)

  var len = unloadedUris.length
  var remain = len

  for (var i = 0; i < len; i++) {
    (function(uri) {

      var mod = cachedModules[uri]
      mod.status < STATUS.SAVED ? fetch(uri, onFetched) : onFetched()

      function onFetched() {
        // Maybe failed to fetch successfully, such as 404 error
        // In these cases, just call `cb` function directly
        if (mod.status < STATUS.SAVED) {
          done()
          return
        }

        // Break circular waiting callbacks
        if (isCircularWaiting(mod)) {
          printCircularLog(circularStack)
          circularStack.length = 0
          done(mod)
          return
        }

        // Load all unloaded dependencies
        var waitings = mod.waitings = getUnloadedUris(mod.dependencies)
        if (waitings.length === 0) {
          done(mod)
          return
        }

        load(waitings, function() {
          done(mod)
        }, { filtered: true })
      }

    })(unloadedUris[i])
  }

  function done(mod) {
    if (mod && mod.status < STATUS.LOADED) {
      mod.status = STATUS.LOADED
    }

    if (--remain === 0) {
      callback()
    }
  }
}

var fetchingList = {}
var fetchedList = {}
var callbackList = {}
var anonymousModuleMeta = null

function fetch(uri, callback) {
  // Emit `fetch` event. Plugins could use this event to
  // modify uri or do other magic things
  var requestUri = emitData('fetch',
      { uri: uri, fetchedList: fetchedList },
      'uri')

  if (fetchedList[requestUri]) {
    callback()
    return
  }

  if (fetchingList[requestUri]) {
    callbackList[requestUri].push(callback)
    return
  }

  fetchingList[requestUri] = true
  callbackList[requestUri] = [callback]

  // Send request
  var charset = config.charset
  var requested = emitData('request',
      { uri: requestUri, callback: onRequested, charset: charset },
      'requested')

  if (!requested) {
    request(requestUri, onRequested, charset)
  }

  function onRequested() {
    delete fetchingList[requestUri]
    fetchedList[requestUri] = true

    // Save meta data of anonymous module
    if (anonymousModuleMeta) {
      save(uri, anonymousModuleMeta)
      anonymousModuleMeta = null
    }

    // Call callbacks
    var fn, fns = callbackList[requestUri]
    delete callbackList[requestUri]
    while ((fn = fns.shift())) fn()
  }
}

function define(id, deps, factory) {
  var argsLen = arguments.length

  // HANDLE: define(factory)
  if (argsLen === 1) {
    factory = id
    id = undefined
  }
  // HANDLE: define(id || deps, factory)
  else if (argsLen === 2) {
    factory = deps
    deps = undefined

    // HANDLE: define(deps, factory)
    if (isArray(id)) {
      deps = id
      id = undefined
    }
  }

  // Parse dependencies according to the module factory code
  if (!isArray(deps) && isFunction(factory)) {
    deps = parseDependencies(factory.toString())
  }

  var meta = { id: id, dependencies: deps, factory: factory }
  var derivedUri

  // Try to derive uri in IE6-9 for anonymous modules
  if (!id && doc.attachEvent) {
    var script = getCurrentScript()

    if (script && script.src) {
      derivedUri = getScriptAbsoluteSrc(script)
      derivedUri = emitData('derived', { uri: derivedUri })
    }
    else {
      log('Failed to derive URI from interactive script for:',
          factory.toString(), 'warn')

      // NOTE: If the id-deriving methods above is failed, then falls back
      // to use onload event to get the uri
    }
  }

  var resolvedUri = id ? resolve(id) : derivedUri

  if (resolvedUri) {
    save(resolvedUri, meta)
  }
  else {
    // Save information for "memoizing" work in the script onload event
    anonymousModuleMeta = meta
  }

}

function save(uri, meta) {
  var mod = createModule(uri)

  // Do NOT override already saved modules
  if (mod.status < STATUS.SAVED) {
    mod.id = meta.id || uri // Let anonymous module id equal to its uri
    mod.dependencies = resolve(meta.dependencies || [], uri)
    mod.factory = meta.factory

    mod.status = STATUS.SAVED
  }
}

function compile(mod) {
  // When module is compiled, DO NOT compile it again. When module
  // is being compiled, just return `module.exports` too, for avoiding
  // circularly calling
  if (mod.status >= STATUS.COMPILING) {
    return mod.exports
  }

  emit('compile', mod)

  // Just return `null` when:
  //  1. the module file is 404
  //  2. the module file is not written with valid module format
  //  3. other error cases
  if (mod.status < STATUS.LOADED && mod.exports === undefined) {
    return null
  }

  mod.status = STATUS.COMPILING

  function require(id) {
    var child = cachedModules[require.resolve(id)]

    // Return `null` when `uri` is invalid
    if (child === undefined) {
      return null
    }

    child.parent = mod
    return compile(child)
  }

  require.async = function(ids, callback) {
    mod.load(ids, callback)
  }

  require.resolve = function(id) {
    return resolve(id, mod.uri)
  }

  require.cache = cachedModules

  mod.require = require
  mod.exports = mod.exports || {}
  delete mod.waitings

  var factory = mod.factory
  var exports = factory

  if (isFunction(factory)) {
    exports = factory(mod.require, mod.exports, mod)
  }

  if (exports !== undefined) {
    mod.exports = exports
  }

  mod.status = STATUS.COMPILED
  emit('compiled', mod)

  return mod.exports
}

// Helpers

function createModule(uri, status) {
  return cachedModules[uri] ||
      (cachedModules[uri] = new Module(uri, status))
}

function getUnloadedUris(uris) {
  return filter(uris, function(uri) {
    return createModule(uri).status < STATUS.LOADED
  })
}

var circularStack = []

function isCircularWaiting(mod) {
  var waitings = mod.waitings
  if (waitings.length === 0) {
    return false
  }

  circularStack.push(mod.uri)
  if (isOverlap(waitings, circularStack)) {
    return true
  }

  for (var i = 0; i < waitings.length; i++) {
    if (isCircularWaiting(cachedModules[waitings[i]])) {
      return true
    }
  }

  circularStack.pop()
  return false
}

function printCircularLog(stack) {
  stack.push(stack[0])
  log('Found circular dependencies:', stack.join(' --> '))
}

function isOverlap(arrA, arrB) {
  var arrC = arrA.concat(arrB)
  return  unique(arrC).length < arrC.length
}

// Public API

var globalModule = new Module(pageUri, STATUS.COMPILED)

function preload(callback) {
  var preloadModules = config.preload
  var len = preloadModules.length

  len ? globalModule.load(preloadModules.splice(0, len), callback) :
      callback()
}

seajs.use = function(ids, callback) {
  // Load preload modules before all other modules
  preload(function() {
    globalModule.load(ids, callback)
  })
  return seajs
}

global.define = define

<|endoftext|>


<commit_before>KityMinder.registerModule( "LayoutModule", function () {
	kity.extendClass( Minder, {
		addLayoutStyle: function ( name, style ) {
			if ( !this._layoutStyles ) this._layoutStyles = {};
			this._layoutStyles[ name ] = style;
		},
		getLayoutStyle: function ( name ) {
			return this._layoutStyles[ name ];
		},

		getLayoutStyleItems: function () {
			var items = [];
			for ( var key in this._layoutStyles ) {
				items.push( key );
			}
			return items;
		},
		getCurrentStyle: function () {
			var _root = this.getRoot();
			return _root.getData( "currentstyle" );
		},
		setCurrentStyle: function ( name ) {
			var _root = this.getRoot();
			_root.setData( "currentstyle", name );
			return name;
		},
		getCurrentLayoutStyle: function () {
			var curStyle = this.getCurrentStyle();
			return this.getLayoutStyle( curStyle ).getCurrentLayoutStyle.call( this );
		},
		highlightNode: function ( node ) {
			var curStyle = this.getCurrentStyle();
			this.getLayoutStyle( curStyle ).highlightNode.call( this, node );
		},
		initStyle: function ( expandall ) {
			var curStyle = this.getCurrentStyle();
			this._rc.remove();
			this._rc = new kity.Group();
			this._paper.addShape( this._rc );

			var _root = this.getRoot();
			_root.preTraverse( function ( n ) {
				n.clearLayout();
			} );
			this.getLayoutStyle( curStyle ).initStyle.call( this, expandall );
			this.fire( 'afterinitstyle' );
		},
		appendChildNode: function ( parent, node, focus, index ) {
			var curStyle = this.getCurrentStyle();
			this.getLayoutStyle( curStyle ).appendChildNode.call( this, parent, node, focus, index );
		},
		appendSiblingNode: function ( sibling, node, focus ) {
			var curStyle = this.getCurrentStyle();
			this.getLayoutStyle( curStyle ).appendSiblingNode.call( this, sibling, node, focus );
		},
		removeNode: function ( nodes ) {
			var curStyle = this.getCurrentStyle();
			this.getLayoutStyle( curStyle ).removeNode.call( this, nodes );
		},
		updateLayout: function ( node ) {
			var curStyle = this.getCurrentStyle();
			this.getLayoutStyle( curStyle ).updateLayout.call( this, node );
		},
		expandNode: function ( ico ) {
			var curStyle = this.getCurrentStyle();
			this.getLayoutStyle( curStyle ).expandNode.call( this, ico );
		}
	} );
	kity.extendClass( MinderNode, {
		setLayout: function ( k, v ) {
			if ( this._layout === undefined ) {
				this._layout = {};
			}
			var _pros = this.getLayout();
			Utils.extend( _pros, {
				k: v
			} );
			this._layout = _pros;
		},
		getLayout: function ( k ) {
			if ( k === undefined ) {
				return this._layout;
			}
			return this._layout[ k ];
		},
		clearLayout: function () {
			this._layout = {};
		}
	} );
	var switchLayout = function ( km, style ) {
		var _root = km.getRoot();
		_root.preTraverse( function ( n ) {
			n.setPoint();
			n.getBgRc().clear();
		} );
		km.setCurrentStyle( style );
		km.initStyle();
		return style;
	};
	var SwitchLayoutCommand = kity.createClass( "SwitchLayoutCommand", ( function () {
		return {
			base: Command,
			execute: switchLayout,
			queryValue: function ( km ) {
				return km.getCurrentStyle();
			}
		};
	} )() );
	var AppendChildNodeCommand = kity.createClass( "AppendChildNodeCommand", ( function () {
		return {
			base: Command,
			execute: function ( km, node, focus, silbling ) {
				var parent = km.getSelectedNode();

				if ( !parent ) {
					return null;
				}
				if ( parent.getType() !== "root" && parent.getChildren().length !== 0 && parent.getData( "expand" ) === false ) {
					km.expandNode( parent );
				}

				km.appendChildNode( parent, node, focus, silbling );
				km.select( node, true );
				return node;
			},
			queryState: function ( km ) {
				var selectedNode = km.getSelectedNode();
				if ( !selectedNode ) {
					return -1;
				} else {
					return 0;
				}
			}
		};
	} )() );
	var AppendSiblingNodeCommand = kity.createClass( "AppendSiblingNodeCommand", ( function () {
		return {
			base: Command,
			execute: function ( km, node, focus ) {
				var selectedNode = km.getSelectedNode();
				if ( !selectedNode ) {
					return null;
				}

				if ( selectedNode.isRoot() ) {
					node.setType( "main" );
					km.appendChildNode( selectedNode, node, focus );
				} else {
					km.appendSiblingNode( selectedNode, node, focus );
				}
				km.select( node, true );
				return node;
			},
			queryState: function ( km ) {
				var selectedNodes = km.getSelectedNodes();
				//没选中节点和单选root的时候返回不可执行
				if ( selectedNodes.length === 0 || ( selectedNodes.length === 1 && selectedNodes[ 0 ] === km.getRoot() ) ) {
					return -1;
				} else {
					return 0;
				}
			}
		};
	} )() );
	var RemoveNodeCommand = kity.createClass( "RemoveNodeCommand", ( function () {
		return {
			base: Command,
			execute: function ( km ) {

				if ( km.getRoot().children.length == 0 ) {
					return;
				}

				var selectedNodes = km.getSelectedNodes();
				var _root = km.getRoot();
				var _buffer = [];
				for ( var i = 0; i < selectedNodes.length; i++ ) {
					_buffer.push( selectedNodes[ i ] );
				}
				do {
					var parent = _buffer[ 0 ].getParent();
					if ( parent && _buffer.indexOf( parent ) === -1 ) _buffer.push( parent );
					_buffer.shift();
				} while ( _buffer.length > 1 );
				km.removeNode( selectedNodes );
				km.select( _buffer[ 0 ] );
			},
			queryState: function ( km ) {
				var selectedNodes = km.getSelectedNodes();
				if ( selectedNodes.length === 0 || ( selectedNodes.length === 1 && selectedNodes[ 0 ] === km.getRoot() ) ) {
					return -1;
				} else {
					return 0;
				}
			}
		};
	} )() );
	var EditNodeCommand = kity.createClass( "EditNodeCommand", ( function () {
		return {
			base: Command,
			execute: function ( km ) {
				var selectedNode = km.getSelectedNode();
				if ( !selectedNode ) {
					return null;
				}
				km.select( selectedNode, true );
			},
			queryState: function ( km ) {
				var selectedNode = km.getSelectedNode();
				if ( !selectedNode ) {
					return -1;
				} else {
					return 0;
				}
			},
			isNeedUndo: function () {
				return false;
			}
		};
	} )() );

	return {
		"commands": {
			"appendchildnode": AppendChildNodeCommand,
			"appendsiblingnode": AppendSiblingNodeCommand,
			"removenode": RemoveNodeCommand,
			"editnode": EditNodeCommand,
			"switchlayout": SwitchLayoutCommand
		},
		"events": {
			"ready": function () {
				this.setDefaultOptions( 'layoutstyle', this.getLayoutStyleItems() );
				switchLayout( this, this.getOptions( 'defaultlayoutstyle' ) );

			},
			"click": function ( e ) {
				var ico = e.kityEvent.targetShape && e.kityEvent.targetShape.container;
				if ( ico && ico.class === "shicon" ) {
					this.expandNode( ico );
				}
			},
			"resize": function ( e ) {
				clearTimeout( this._lastStyleResetTimeout );
				this._lastStyleResetTimeout = setTimeout( function () {
					this.updateLayout( this.getRoot() );
				}.bind( this ), 100 );
			},
			"import": function ( e ) {
				this.initStyle();
			},
			"cloneNode": function ( e ) {
				var target = e.targetNode;
				var source = e.sourceNode;
				target.clearLayout();
				var sourceLayout = source.getLayout();
				var targetLayout = target.getLayout();
				targetLayout.expand = sourceLayout.expand;
				console.log( targetLayout );
			}
		},
		'contextmenu': [ {
				label: this.getLang( 'node.appendsiblingnode' ),
				exec: function () {
					this.execCommand( 'appendsiblingnode', new MinderNode( this.getLang( 'topic' ) ) )
				},
				cmdName: 'appendsiblingnode'
			}, {
				label: this.getLang( 'node.appendchildnode' ),
				exec: function () {
					this.execCommand( 'appendchildnode', new MinderNode( this.getLang( 'topic' ) ) )
				},
				cmdName: 'appendchildnode'
			}, {
				label: this.getLang( 'node.editnode' ),
				exec: function () {
					this.execCommand( 'editnode', null );
				},
				cmdName: 'editnode'
			}, {
				label: this.getLang( 'node.removenode' ),
				cmdName: 'removenode'
			}, {
				divider: 1
			}

		],
		"defaultOptions": {
			"defaultlayoutstyle": "default",
			"node": {
				'appendsiblingnode': 'appendsiblingnode',
				'appendchildnode': 'appendchildnode',
				'editnode': 'editnode',
				'removenode': 'removenode'
			},
			'defaultExpand': {
				'defaultLayer': 0,
				'defaultSubShow': 0
			}
		}
	};
} );<commit_msg>object不能那么直接链接过来，要clone<commit_after>KityMinder.registerModule( "LayoutModule", function () {
	kity.extendClass( Minder, {
		addLayoutStyle: function ( name, style ) {
			if ( !this._layoutStyles ) this._layoutStyles = {};
			this._layoutStyles[ name ] = style;
		},
		getLayoutStyle: function ( name ) {
			return this._layoutStyles[ name ];
		},

		getLayoutStyleItems: function () {
			var items = [];
			for ( var key in this._layoutStyles ) {
				items.push( key );
			}
			return items;
		},
		getCurrentStyle: function () {
			var _root = this.getRoot();
			return _root.getData( "currentstyle" );
		},
		setCurrentStyle: function ( name ) {
			var _root = this.getRoot();
			_root.setData( "currentstyle", name );
			return name;
		},
		getCurrentLayoutStyle: function () {
			var curStyle = this.getCurrentStyle();
			return this.getLayoutStyle( curStyle ).getCurrentLayoutStyle.call( this );
		},
		highlightNode: function ( node ) {
			var curStyle = this.getCurrentStyle();
			this.getLayoutStyle( curStyle ).highlightNode.call( this, node );
		},
		initStyle: function ( expandall ) {
			var curStyle = this.getCurrentStyle();
			this._rc.remove();
			this._rc = new kity.Group();
			this._paper.addShape( this._rc );

			var _root = this.getRoot();
			_root.preTraverse( function ( n ) {
				n.clearLayout();
			} );
			this.getLayoutStyle( curStyle ).initStyle.call( this, expandall );
			this.fire( 'afterinitstyle' );
		},
		appendChildNode: function ( parent, node, focus, index ) {
			var curStyle = this.getCurrentStyle();
			this.getLayoutStyle( curStyle ).appendChildNode.call( this, parent, node, focus, index );
		},
		appendSiblingNode: function ( sibling, node, focus ) {
			var curStyle = this.getCurrentStyle();
			this.getLayoutStyle( curStyle ).appendSiblingNode.call( this, sibling, node, focus );
		},
		removeNode: function ( nodes ) {
			var curStyle = this.getCurrentStyle();
			this.getLayoutStyle( curStyle ).removeNode.call( this, nodes );
		},
		updateLayout: function ( node ) {
			var curStyle = this.getCurrentStyle();
			this.getLayoutStyle( curStyle ).updateLayout.call( this, node );
		},
		expandNode: function ( ico ) {
			var curStyle = this.getCurrentStyle();
			this.getLayoutStyle( curStyle ).expandNode.call( this, ico );
		}
	} );
	kity.extendClass( MinderNode, {
		setLayout: function ( k, v ) {
			if ( this._layout === undefined ) {
				this._layout = {};
			}
			var _pros = this.getLayout();
			Utils.extend( _pros, {
				k: v
			} );
			this._layout = _pros;
		},
		getLayout: function ( k ) {
			if ( k === undefined ) {
				return this._layout;
			}
			return this._layout[ k ];
		},
		clearLayout: function () {
			this._layout = {};
		}
	} );
	var switchLayout = function ( km, style ) {
		var _root = km.getRoot();
		_root.preTraverse( function ( n ) {
			n.setPoint();
			n.getBgRc().clear();
		} );
		km.setCurrentStyle( style );
		km.initStyle();
		return style;
	};
	var SwitchLayoutCommand = kity.createClass( "SwitchLayoutCommand", ( function () {
		return {
			base: Command,
			execute: switchLayout,
			queryValue: function ( km ) {
				return km.getCurrentStyle();
			}
		};
	} )() );
	var AppendChildNodeCommand = kity.createClass( "AppendChildNodeCommand", ( function () {
		return {
			base: Command,
			execute: function ( km, node, focus, silbling ) {
				var parent = km.getSelectedNode();

				if ( !parent ) {
					return null;
				}
				if ( parent.getType() !== "root" && parent.getChildren().length !== 0 && parent.getData( "expand" ) === false ) {
					km.expandNode( parent );
				}

				km.appendChildNode( parent, node, focus, silbling );
				km.select( node, true );
				return node;
			},
			queryState: function ( km ) {
				var selectedNode = km.getSelectedNode();
				if ( !selectedNode ) {
					return -1;
				} else {
					return 0;
				}
			}
		};
	} )() );
	var AppendSiblingNodeCommand = kity.createClass( "AppendSiblingNodeCommand", ( function () {
		return {
			base: Command,
			execute: function ( km, node, focus ) {
				var selectedNode = km.getSelectedNode();
				if ( !selectedNode ) {
					return null;
				}

				if ( selectedNode.isRoot() ) {
					node.setType( "main" );
					km.appendChildNode( selectedNode, node, focus );
				} else {
					km.appendSiblingNode( selectedNode, node, focus );
				}
				km.select( node, true );
				return node;
			},
			queryState: function ( km ) {
				var selectedNodes = km.getSelectedNodes();
				//没选中节点和单选root的时候返回不可执行
				if ( selectedNodes.length === 0 || ( selectedNodes.length === 1 && selectedNodes[ 0 ] === km.getRoot() ) ) {
					return -1;
				} else {
					return 0;
				}
			}
		};
	} )() );
	var RemoveNodeCommand = kity.createClass( "RemoveNodeCommand", ( function () {
		return {
			base: Command,
			execute: function ( km ) {

				if ( km.getRoot().children.length == 0 ) {
					return;
				}

				var selectedNodes = km.getSelectedNodes();
				var _root = km.getRoot();
				var _buffer = [];
				for ( var i = 0; i < selectedNodes.length; i++ ) {
					_buffer.push( selectedNodes[ i ] );
				}
				do {
					var parent = _buffer[ 0 ].getParent();
					if ( parent && _buffer.indexOf( parent ) === -1 ) _buffer.push( parent );
					_buffer.shift();
				} while ( _buffer.length > 1 );
				km.removeNode( selectedNodes );
				km.select( _buffer[ 0 ] );
			},
			queryState: function ( km ) {
				var selectedNodes = km.getSelectedNodes();
				if ( selectedNodes.length === 0 || ( selectedNodes.length === 1 && selectedNodes[ 0 ] === km.getRoot() ) ) {
					return -1;
				} else {
					return 0;
				}
			}
		};
	} )() );
	var EditNodeCommand = kity.createClass( "EditNodeCommand", ( function () {
		return {
			base: Command,
			execute: function ( km ) {
				var selectedNode = km.getSelectedNode();
				if ( !selectedNode ) {
					return null;
				}
				km.select( selectedNode, true );
			},
			queryState: function ( km ) {
				var selectedNode = km.getSelectedNode();
				if ( !selectedNode ) {
					return -1;
				} else {
					return 0;
				}
			},
			isNeedUndo: function () {
				return false;
			}
		};
	} )() );

	return {
		"commands": {
			"appendchildnode": AppendChildNodeCommand,
			"appendsiblingnode": AppendSiblingNodeCommand,
			"removenode": RemoveNodeCommand,
			"editnode": EditNodeCommand,
			"switchlayout": SwitchLayoutCommand
		},
		"events": {
			"ready": function () {
				this.setDefaultOptions( 'layoutstyle', this.getLayoutStyleItems() );
				switchLayout( this, this.getOptions( 'defaultlayoutstyle' ) );

			},
			"click": function ( e ) {
				var ico = e.kityEvent.targetShape && e.kityEvent.targetShape.container;
				if ( ico && ico.class === "shicon" ) {
					this.expandNode( ico );
				}
			},
			"resize": function ( e ) {
				clearTimeout( this._lastStyleResetTimeout );
				this._lastStyleResetTimeout = setTimeout( function () {
					this.updateLayout( this.getRoot() );
				}.bind( this ), 100 );
			},
			"import": function ( e ) {
				this.initStyle();
			},
			"cloneNode": function ( e ) {
				var target = e.targetNode;
				var source = e.sourceNode;
				target.clearLayout();
				var sourceLayout = source.getLayout();
				var targetLayout = target.getLayout();

				targetLayout.expand = utils.clone(sourceLayout.expand);
				console.log( targetLayout );
			}
		},
		'contextmenu': [ {
				label: this.getLang( 'node.appendsiblingnode' ),
				exec: function () {
					this.execCommand( 'appendsiblingnode', new MinderNode( this.getLang( 'topic' ) ) )
				},
				cmdName: 'appendsiblingnode'
			}, {
				label: this.getLang( 'node.appendchildnode' ),
				exec: function () {
					this.execCommand( 'appendchildnode', new MinderNode( this.getLang( 'topic' ) ) )
				},
				cmdName: 'appendchildnode'
			}, {
				label: this.getLang( 'node.editnode' ),
				exec: function () {
					this.execCommand( 'editnode', null );
				},
				cmdName: 'editnode'
			}, {
				label: this.getLang( 'node.removenode' ),
				cmdName: 'removenode'
			}, {
				divider: 1
			}

		],
		"defaultOptions": {
			"defaultlayoutstyle": "default",
			"node": {
				'appendsiblingnode': 'appendsiblingnode',
				'appendchildnode': 'appendchildnode',
				'editnode': 'editnode',
				'removenode': 'removenode'
			},
			'defaultExpand': {
				'defaultLayer': 0,
				'defaultSubShow': 0
			}
		}
	};
} );<|endoftext|>


<commit_before>/**
 *  API for DB Collection objects
 *
 *
 * @fileOverview dbutil.js - 10gen Database Collection  API
 * @name 10gen Database Collection API
 */

 /**
  * Database collection  API
 *  @class 10gen Database Collection  API
 */
 var DBCollection = function(){}

/**
 *
Drop all indexes on the specified collection.

 *
 *
Note : alpha: space is not reclaimed

 *
 * @return SOMETHING_FIXME
 */
DBCollection.prototype.dropIndexes = function() {
    var res = this._dbCommand( { deleteIndexes: this.getName(), index: "*" } );
    if( res && res.ok && res.ok == 1 ) {
        this.getDB().system.indexes.remove( { ns: this.getFullName() } );
		this.getDB().system.namespaces.remove( { name: RegExp(this.getFullName() + "[.][$].*") } );
    }

    this.resetIndexCache();

    return res;
}

/**
 *
Drop a specified index.

 *
 *

 * Name is the name of the index in the system.indexes name field. (Run db.system.indexes.find() to
 *  see example data.)
 *

 *
 *
Note :  alpha: space is not reclaimed

 * @param {String} name of index to delete.
 * @return SOMETHING_FIXME
 */
 DBCollection.prototype.dropIndex =  function(index) {
    assert(index);

    if ( ! isString( index ) && isObject( index ) )
    	index = this.genIndexName( index );

    var res = this._dbCommand( { deleteIndexes: this.getName(), index: index } );
    if( res && res.ok && res.ok == 1 ) {
        this.getDB().system.indexes.remove( { ns: this.getFullName(), name: index } );
		this.getDB().system.namespaces.remove( { name: this.getFullName() + ".$"+index } );
    }

    this.resetIndexCache();

    return res;
}

/**
 * Validate the data in a collection, returning some stats.
 * @return SOMETHING_FIXME
 */
DBCollection.prototype.validate = function() {
    var res = this._dbCommand( { validate: this.getName() } );

    res.valid = false;

    if ( res.result ){
        var str = "-" + tojson( res.result );
        res.valid = ! ( str.match( /exception/ ) || str.match( /corrupt/ ) );
    }

    return res;
}

/**
 *
drops all objects in the collection

 *
Note :  alpha: space not reclaimed.

 *
 * @return SOMETHING_FIXME
 */
DBCollection.prototype.drop = function()
{
    var res = this._dbCommand( { drop: this.getName() } );
    if( res && res.ok && res.ok == 1 ) {
        this.getDB().system.indexes.remove( { ns: this.getFullName() } );
		this.getDB().system.namespaces.remove( { name: this.getFullName() } );
		this.getDB().system.namespaces.remove( { name: RegExp(this.getFullName() + "[.][$].*") } );
    }
    return res;
}

/**
 *  Drop free lists. Normally not used.
 */
DBCollection.prototype.clean = function() {
    return this._dbCommand( { clean: this.getName() } );
}

/**
 *

 *  count # of objects in a collection
 *

 *
 *
  You can specify a filter for counting through the optional  parameter.
 *      This parameter specifies condition that must be true for the objects to
 *        be counted.
 *

 *
Example:

 *
 *   c = count({active:true});
 *
 * @param {Object} query Optional query to use to filter objects for counting
 * @return number of objects in the collection that optionally match the filter condition
 */
DBCollection.prototype.count = function(query) {
    var countFunction = function() {
	var c = db[args[0]].find(args[1]||{}, {_id:ObjId()});
        var i = 0;
        while ( c.hasNext() ){
            c.next();
            i++;
        }
        return i;
    }
   return this.getDB().dbEval(countFunction, this.getName(), query);
}

/* Run the specified database "command" object.
*/
DBCollection.prototype._dbCommand = function( cmdObj ) {
    return this.getDB().$cmd.findOne(cmdObj);
}

DBCollection.prototype.sample = function( num , query , fields ){
    var r = this.getDB().dbEval(
        function(){
            var a = db[args[0]].find( args[2] || {} , args[3] ).limit(10000).toArray();
            a.shuffle();
            return a.splice( 0 , args[1] );
        } ,
        this.getName() , num , query , fields
    );
    var a = [];
    for ( var k in r ){
        a.push( r[k] );
    }
    return a;
}

var mydb  = arguments[0];

if (!mydb) {
       throw "Error : no db object passed to augmentor for Collection";
}

Object.extend( mydb.getCollectionPrototype() , DBCollection.prototype );

return null;

//
//  other stuff
//

/**
 *  RESET - FOLLOWING IS FOR DOCUMENTATION PURPOSES ONLY
 */
DBCollection.prototype = {};

/**
 *
Returns the name of the collection.

 *
 * @return {String} Name of the collection
 */
DBCollection.prototype.name = function() {
    throw {exception : "Native Call name() : shouldn't have JS implementation"};
}

//       _entries.put( "base" , _base.getName() );

 /**
 *

 * Saves an object in the collection, or update if the object (as identified by _id)
 * is already there.
 *

 *
 *

 * If your object has a presave $TODO_DOC method, that method will be called
 * before the object is saved to the db (before both updates and inserts).
 *

 * @return SOMETHING_FIXME
 */
DBCollection.prototype.save = function(obj) {
    throw {exception : "Native Call save() : shouldn't have JS implementation"};
}

 /**
 *

 * Update an object in the database, based on supplied query criteria and options.  Normally
 * you should just use the save() method.
 *

 *

 * Current options include :
 *

 *

 *
upsert:true - perform an update if exists, or insert new if doesn't exist

 *
ids : false - do not add an object _id field

 *

 *
 *

 * Example :
 *

 * db.myColl.update( { name: "Joe" }, { name: "Joe", age: 20 }, { upsert: true } );
 *
 *
 @see  http://admin.10gen.com/wiki/pub.db.update

 *
 * @param {Object} criteria  query which selects the record @TODO{more than one?} to update
 * @param {Object} obj  updated object
 * @param {Object} options  optional options object to use in the update
 * @return SOMETHING_FIXME
 */
DBCollection.prototype.update = function(criteria, obj, options) {
    throw {exception : "Native Call update() : shouldn't have JS implementation"};
}

 /**
 *

 * Removes all objects from the collection that match the optional criteria.
 *

 *

 * Example :
 *

 * db.myColl.remove( { name: "Joe" });
 *
 * @param {Object} criteria  query which selects the records  to be removed from the collection
 * @return SOMETHING_FIXME
 */
DBCollection.prototype.remove = function(criteria) {
    throw {exception : "Native Call remove() : shouldn't have JS implementation"};
}

/**
 *

 *    @TODO - does something
 *

 *
 *   @param {Object} obj obj to apply
 *   @return SOMETHING_FIXME
 */
DBCollection.prototype.apply = function(obj) {
    throw {exception : "Native Call apply() : shouldn't have JS implementation"};
}

/**
 *

 *    Finds one or more objects in the collection based on the optional specified criteria.
 *

 *
 *

 *   Example :
 *

 *   db.blogposts.find();
 *

 *   db.blogposts.find({title : /10gen/} );
 *

 *   In addition to the criteria, a field selector may be applied to limit the fields that
 *   are returned in the objects.
 *

 *

 *   Example :
 *

 *   db.blogposts.find({}, {comments:true});
 *
 *

 *   The Cursor returned by find can have modifiers applied for more advanced functionalty.
 *   See @see $TODO-LINK_TO_CURSOR_DOC for more informatiion.
 *

 *   @param {Object} criteria Optional criteria for selection of object(s) to be returned
 *   @param {Object} selector Optional selector to specify the fields that should be returned in each object
 *   @return {Cursor} Cursor for the found object set
 */
DBCollection.prototype.find = function(criteria, selector) {
    throw {exception : "Native Call find() : shouldn't have JS implementation"};
}

/**
 *

 *    Finds a single objects in the collection based on the specified criteria.
 *

 *
 *

 *   Example :
 *

 *   db.blogposts.findOne({title : /10gen/} );
 *   @param {Object} criteria Criteria for selection of object to be returned
 *   @return {Object} Found object or null if no objects match the criteria
 */
DBCollection.prototype.findOne = function(criteria) {
    throw {exception : "Native Call findOne(): shouldn't have JS implementation"};
}

/**
 *

 *    Returns an array of the indexes for the collection.
 *

 *

 *   Each entry in the array is an index descriptor object than contains the
 *   following properties :
 *

 *

 *
 name : name of the index

 *
 ns : name of the namespace the index is in

 *
 key : object property that's being indexed

 *

 *
 *   @return {Array} Array of index descriptor objects
 */
DBCollection.prototype.getIndexes = function() {
    throw {exception : "Native Call getIndexes() : shouldn't have JS implementation"};
}

/**
 *

 *    Returns a JSON representation of the collection.
 *
 *   @return {String} JSON representation of the collection
 */
DBCollection.prototype.tojson = function() {
    throw {exception : "Native Call tojson() : shouldn't have JS implementation"};
}
<commit_msg>reIndex function<commit_after>/**
 *  API for DB Collection objects
 *
 *
 * @fileOverview dbutil.js - 10gen Database Collection  API
 * @name 10gen Database Collection API
 */

 /**
  * Database collection  API
 *  @class 10gen Database Collection  API
 */
 var DBCollection = function(){}

/**
 *
Drop all indexes on the specified collection.

 *
 *
Note : alpha: space is not reclaimed

 *
 * @return SOMETHING_FIXME
 */
DBCollection.prototype.dropIndexes = function() {
    var res = this._dbCommand( { deleteIndexes: this.getName(), index: "*" } );
    if( res && res.ok && res.ok == 1 ) {
        this.getDB().system.indexes.remove( { ns: this.getFullName() } );
		this.getDB().system.namespaces.remove( { name: RegExp(this.getFullName() + "[.][$].*") } );
    }

    this.resetIndexCache();

    return res;
}

/**
 *
Drop a specified index.

 *
 *

 * Name is the name of the index in the system.indexes name field. (Run db.system.indexes.find() to
 *  see example data.)
 *

 *
 *
Note :  alpha: space is not reclaimed

 * @param {String} name of index to delete.
 * @return SOMETHING_FIXME
 */
 DBCollection.prototype.dropIndex =  function(index) {
    assert(index);

    if ( ! isString( index ) && isObject( index ) )
    	index = this.genIndexName( index );

    var res = this._dbCommand( { deleteIndexes: this.getName(), index: index } );
    if( res && res.ok && res.ok == 1 ) {
        this.getDB().system.indexes.remove( { ns: this.getFullName(), name: index } );
		this.getDB().system.namespaces.remove( { name: this.getFullName() + ".$"+index } );
    }

    this.resetIndexCache();

    return res;
}

DBCollection.prototype.getIndexes = function(){
    return this.getDB().system.indexes.find( { name : RegExp( this.getFullName() + "[.][$]" ) } );
}

DBCollection.prototype.reIndex = function(){

    var coll = this;

    var all = this.getDB().system.indexes.find( { ns : this.getFullName() } ).toArray();

    all.forEach(
        function(z){
            coll.dropIndex( z.name );
            coll.ensureIndex( z.key );
        }
    );
}

/**
 * Validate the data in a collection, returning some stats.
 * @return SOMETHING_FIXME
 */
DBCollection.prototype.validate = function() {
    var res = this._dbCommand( { validate: this.getName() } );

    res.valid = false;

    if ( res.result ){
        var str = "-" + tojson( res.result );
        res.valid = ! ( str.match( /exception/ ) || str.match( /corrupt/ ) );
    }

    return res;
}

/**
 *
drops all objects in the collection

 *
Note :  alpha: space not reclaimed.

 *
 * @return SOMETHING_FIXME
 */
DBCollection.prototype.drop = function()
{
    var res = this._dbCommand( { drop: this.getName() } );
    if( res && res.ok && res.ok == 1 ) {
        this.getDB().system.indexes.remove( { ns: this.getFullName() } );
		this.getDB().system.namespaces.remove( { name: this.getFullName() } );
		this.getDB().system.namespaces.remove( { name: RegExp(this.getFullName() + "[.][$].*") } );
    }
    return res;
}

/**
 *  Drop free lists. Normally not used.
 */
DBCollection.prototype.clean = function() {
    return this._dbCommand( { clean: this.getName() } );
}

/**
 *

 *  count # of objects in a collection
 *

 *
 *
  You can specify a filter for counting through the optional  parameter.
 *      This parameter specifies condition that must be true for the objects to
 *        be counted.
 *

 *
Example:

 *
 *   c = count({active:true});
 *
 * @param {Object} query Optional query to use to filter objects for counting
 * @return number of objects in the collection that optionally match the filter condition
 */
DBCollection.prototype.count = function(query) {
    var countFunction = function() {
	var c = db[args[0]].find(args[1]||{}, {_id:ObjId()});
        var i = 0;
        while ( c.hasNext() ){
            c.next();
            i++;
        }
        return i;
    }
   return this.getDB().dbEval(countFunction, this.getName(), query);
}

/* Run the specified database "command" object.
*/
DBCollection.prototype._dbCommand = function( cmdObj ) {
    return this.getDB().$cmd.findOne(cmdObj);
}

DBCollection.prototype.sample = function( num , query , fields ){
    var r = this.getDB().dbEval(
        function(){
            var a = db[args[0]].find( args[2] || {} , args[3] ).limit(10000).toArray();
            a.shuffle();
            return a.splice( 0 , args[1] );
        } ,
        this.getName() , num , query , fields
    );
    var a = [];
    for ( var k in r ){
        a.push( r[k] );
    }
    return a;
}

var mydb  = arguments[0];

if (!mydb) {
       throw "Error : no db object passed to augmentor for Collection";
}

Object.extend( mydb.getCollectionPrototype() , DBCollection.prototype );

return null;

//
//  other stuff
//

/**
 *  RESET - FOLLOWING IS FOR DOCUMENTATION PURPOSES ONLY
 */
DBCollection.prototype = {};

/**
 *
Returns the name of the collection.

 *
 * @return {String} Name of the collection
 */
DBCollection.prototype.name = function() {
    throw {exception : "Native Call name() : shouldn't have JS implementation"};
}

//       _entries.put( "base" , _base.getName() );

 /**
 *

 * Saves an object in the collection, or update if the object (as identified by _id)
 * is already there.
 *

 *
 *

 * If your object has a presave $TODO_DOC method, that method will be called
 * before the object is saved to the db (before both updates and inserts).
 *

 * @return SOMETHING_FIXME
 */
DBCollection.prototype.save = function(obj) {
    throw {exception : "Native Call save() : shouldn't have JS implementation"};
}

 /**
 *

 * Update an object in the database, based on supplied query criteria and options.  Normally
 * you should just use the save() method.
 *

 *

 * Current options include :
 *

 *

 *
upsert:true - perform an update if exists, or insert new if doesn't exist

 *
ids : false - do not add an object _id field

 *

 *
 *

 * Example :
 *

 * db.myColl.update( { name: "Joe" }, { name: "Joe", age: 20 }, { upsert: true } );
 *
 *
 @see  http://admin.10gen.com/wiki/pub.db.update

 *
 * @param {Object} criteria  query which selects the record @TODO{more than one?} to update
 * @param {Object} obj  updated object
 * @param {Object} options  optional options object to use in the update
 * @return SOMETHING_FIXME
 */
DBCollection.prototype.update = function(criteria, obj, options) {
    throw {exception : "Native Call update() : shouldn't have JS implementation"};
}

 /**
 *

 * Removes all objects from the collection that match the optional criteria.
 *

 *

 * Example :
 *

 * db.myColl.remove( { name: "Joe" });
 *
 * @param {Object} criteria  query which selects the records  to be removed from the collection
 * @return SOMETHING_FIXME
 */
DBCollection.prototype.remove = function(criteria) {
    throw {exception : "Native Call remove() : shouldn't have JS implementation"};
}

/**
 *

 *    @TODO - does something
 *

 *
 *   @param {Object} obj obj to apply
 *   @return SOMETHING_FIXME
 */
DBCollection.prototype.apply = function(obj) {
    throw {exception : "Native Call apply() : shouldn't have JS implementation"};
}

/**
 *

 *    Finds one or more objects in the collection based on the optional specified criteria.
 *

 *
 *

 *   Example :
 *

 *   db.blogposts.find();
 *

 *   db.blogposts.find({title : /10gen/} );
 *

 *   In addition to the criteria, a field selector may be applied to limit the fields that
 *   are returned in the objects.
 *

 *

 *   Example :
 *

 *   db.blogposts.find({}, {comments:true});
 *
 *

 *   The Cursor returned by find can have modifiers applied for more advanced functionalty.
 *   See @see $TODO-LINK_TO_CURSOR_DOC for more informatiion.
 *

 *   @param {Object} criteria Optional criteria for selection of object(s) to be returned
 *   @param {Object} selector Optional selector to specify the fields that should be returned in each object
 *   @return {Cursor} Cursor for the found object set
 */
DBCollection.prototype.find = function(criteria, selector) {
    throw {exception : "Native Call find() : shouldn't have JS implementation"};
}

/**
 *

 *    Finds a single objects in the collection based on the specified criteria.
 *

 *
 *

 *   Example :
 *

 *   db.blogposts.findOne({title : /10gen/} );
 *   @param {Object} criteria Criteria for selection of object to be returned
 *   @return {Object} Found object or null if no objects match the criteria
 */
DBCollection.prototype.findOne = function(criteria) {
    throw {exception : "Native Call findOne(): shouldn't have JS implementation"};
}

/**
 *

 *    Returns an array of the indexes for the collection.
 *

 *

 *   Each entry in the array is an index descriptor object than contains the
 *   following properties :
 *

 *

 *
 name : name of the index

 *
 ns : name of the namespace the index is in

 *
 key : object property that's being indexed

 *

 *
 *   @return {Array} Array of index descriptor objects
 */
DBCollection.prototype.getIndexes = function() {
    throw {exception : "Native Call getIndexes() : shouldn't have JS implementation"};
}

/**
 *

 *    Returns a JSON representation of the collection.
 *
 *   @return {String} JSON representation of the collection
 */
DBCollection.prototype.tojson = function() {
    throw {exception : "Native Call tojson() : shouldn't have JS implementation"};
}
<|endoftext|>


<commit_before>import { get, has, isFunction } from 'lodash';

function nested({ column }) {
  return (rowData) => {
    const { property } = column;

    if (!property) {
      return {};
    }

    // if users provide a custom getter instead of a
    // path for _.get, use that getter ...
    if (isFunction(property)) {
      return {
        ...rowData,
        [property]: property(rowData)
      };
    }

    // ... otherwise, make sure property exists, then _.get it
    if (!has(rowData, property)) {
      console.warn( // eslint-disable-line no-console
        `resolve.nested - Failed to find "${property}" property from`,
        rowData
      );

      return {};
    }

    return {
      ...rowData,
      [property]: get(rowData, property)
    };
  };
}

export default nested;
<commit_msg>nested: remove warning<commit_after>import { get, has, isFunction } from 'lodash';

function nested({ column }) {
  return (rowData) => {
    const { property } = column;

    if (!property) {
      return {};
    }

    // if users provide a custom getter instead of a
    // path for _.get, use that getter ...
    if (isFunction(property)) {
      return {
        ...rowData,
        [property]: property(rowData)
      };
    }

    // ... otherwise, make sure property exists, then _.get it
    if (!has(rowData, property)) {
      return {};
    }

    return {
      ...rowData,
      [property]: get(rowData, property)
    };
  };
}

export default nested;
<|endoftext|>


<commit_before>'use strict';

angular.module('ng-geotooltip', [])
	.directive('geotooltip', ['$timeout', '$window', function ($timeout, $window) {
		// The container is shared between directives to avoid performance issues
		var container = angular.element('

');
		var map = null;
		var layerGroup = null;

		var displayTooltip = function(tippedElement, width, height, coords, geoJson) {
			// Make the container the right size
			var resized = false;
			if (width !== container.css('width') || height !== container.css('height')) {
				resized = true;
			}
			container.css('width', width);
			container.css('height', height);

			// Position it at the right place
			container.css('top', tippedElement.prop('offsetTop')+tippedElement.prop('offsetHeight')+'px');
			container.css('left', tippedElement.prop('offsetLeft')+tippedElement.prop('offsetWidth')+'px');
			tippedElement.after(container);

			if (map == null) {
				map = new L.map(container[0]);
				var tilesUrl = 'http://otile{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png';
                var attrib = 'Tiles Courtesy of MapQuest  - Map data © OpenStreetMap contributors';
                var tileLayer = new L.TileLayer(tilesUrl, {minZoom: 1, maxZoom: 18, attribution: attrib, subdomains: "1234"});
                map.addLayer(tileLayer);
            } else if (resized) {
            	map.invalidateSize();
            }

            if (layerGroup !== null) {
            	map.removeLayer(layerGroup);
            }
            layerGroup = L.layerGroup();
            var bounds = new L.LatLngBounds();

            if (coords) {
            	var point = new L.LatLng(coords[0], coords[1]);
            	var pointLayer = L.marker(point);
            	layerGroup.addLayer(pointLayer);
            	bounds.extend(point);
            }

            if (geoJson) {
            	var geoJsonLayer = L.geoJson(geoJson);
            	layerGroup.addLayer(geoJsonLayer);
            	bounds.extend(geoJsonLayer.getBounds());
            }
            //map.setView(point, 12);
            layerGroup.addTo(map);
            map.fitBounds(bounds);
            container.css('visibility', 'visible');
		};

		var hideTooltip = function() {
			container.css('visibility', 'hidden');
		}

		return {
			template: '',
			replace: true,
			restrict: 'E',
			transclude: true,
			scope: {
				'coords': '=',
				'width': '@',
				'height': '@',
				'delay': '@',
				'geojson': '='
			},
			link: function(scope, element, attrs) {
				var tooltipWidth = '200px';
				var tooltipHeight = '200px';
				var tooltipPop = null;

				var delay = attrs.delay || 1000;
				if (attrs.height) {
					tooltipHeight = attrs.height+'px';
				}
				if (attrs.width) {
					tooltipWidth = attrs.width+'px';
				}

				// Events
				element.bind('mouseenter', function(e) {
					tooltipPop = $timeout(function() {
						displayTooltip(element, tooltipWidth, tooltipHeight, scope.coords, scope.geojson);
						tooltipPop = null;
					}, delay);
				});
				element.bind('click', function(e) {
					displayTooltip(element, tooltipWidth, tooltipHeight, scope.coords, scope.geojson);
					if (tooltipPop !== null) {
						// Chances are we triggered the original timer
						$timeout.cancel(tooltipPop);
						tooltipPop = null;
					}
				})
				element.bind('mouseleave', function(e) {
					hideTooltip();
					if (tooltipPop !== null) {
						// We are currently counting down until the tooltip appearance, let's forget it
						$timeout.cancel(tooltipPop);
						tooltipPop = null;
					}

				});
			}
		};
	}]);
<commit_msg>Changed mouseenter to mouseover<commit_after>'use strict';

angular.module('ng-geotooltip', [])
	.directive('geotooltip', ['$timeout', '$window', function ($timeout, $window) {
		// The container is shared between directives to avoid performance issues
		var container = angular.element('

');
		var map = null;
		var layerGroup = null;

		var displayTooltip = function(tippedElement, width, height, coords, geoJson) {
			// Make the container the right size
			var resized = false;
			if (width !== container.css('width') || height !== container.css('height')) {
				resized = true;
			}
			container.css('width', width);
			container.css('height', height);

			// Position it at the right place
			container.css('top', tippedElement.prop('offsetTop')+tippedElement.prop('offsetHeight')+'px');
			container.css('left', tippedElement.prop('offsetLeft')+tippedElement.prop('offsetWidth')+'px');
			tippedElement.after(container);

			if (map == null) {
				map = new L.map(container[0]);
				var tilesUrl = 'http://otile{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png';
                var attrib = 'Tiles Courtesy of MapQuest  - Map data © OpenStreetMap contributors';
                var tileLayer = new L.TileLayer(tilesUrl, {minZoom: 1, maxZoom: 18, attribution: attrib, subdomains: "1234"});
                map.addLayer(tileLayer);
            } else if (resized) {
            	map.invalidateSize();
            }

            if (layerGroup !== null) {
            	map.removeLayer(layerGroup);
            }
            layerGroup = L.layerGroup();
            var bounds = new L.LatLngBounds();

            if (coords) {
            	var point = new L.LatLng(coords[0], coords[1]);
            	var pointLayer = L.marker(point);
            	layerGroup.addLayer(pointLayer);
            	bounds.extend(point);
            }

            if (geoJson) {
            	var geoJsonLayer = L.geoJson(geoJson);
            	layerGroup.addLayer(geoJsonLayer);
            	bounds.extend(geoJsonLayer.getBounds());
            }
            //map.setView(point, 12);
            layerGroup.addTo(map);
            map.fitBounds(bounds);
            container.css('visibility', 'visible');
		};

		var hideTooltip = function() {
			container.css('visibility', 'hidden');
		}

		return {
			template: '',
			replace: true,
			restrict: 'E',
			transclude: true,
			scope: {
				'coords': '=',
				'width': '@',
				'height': '@',
				'delay': '@',
				'geojson': '='
			},
			link: function(scope, element, attrs) {
				var tooltipWidth = '200px';
				var tooltipHeight = '200px';
				var tooltipPop = null;

				var delay = attrs.delay || 1000;
				if (attrs.height) {
					tooltipHeight = attrs.height+'px';
				}
				if (attrs.width) {
					tooltipWidth = attrs.width+'px';
				}

				// Events
				element.bind('mouseover', function(e) {
					tooltipPop = $timeout(function() {
						displayTooltip(element, tooltipWidth, tooltipHeight, scope.coords, scope.geojson);
						tooltipPop = null;
					}, delay);
				});
				element.bind('click', function(e) {
					displayTooltip(element, tooltipWidth, tooltipHeight, scope.coords, scope.geojson);
					if (tooltipPop !== null) {
						// Chances are we triggered the original timer
						$timeout.cancel(tooltipPop);
						tooltipPop = null;
					}
				})
				element.bind('mouseout', function(e) {
					hideTooltip();
					if (tooltipPop !== null) {
						// We are currently counting down until the tooltip appearance, let's forget it
						$timeout.cancel(tooltipPop);
						tooltipPop = null;
					}

				});
			}
		};
	}]);
<|endoftext|>