<commit_before>/**
 * @module Events
 * @submodule Touch
 * @for p5
 * @requires core
 */

'use strict';

var p5 = require('../core/core');

/*
 * This is a flag which is false until the first time
 * we receive a touch event. The ptouchX and ptouchY
 * values will match the touchX and touchY values until
 * this interaction takes place.
 */
p5.prototype._hasTouchInteracted = false;

/**
 * The system variable touchX always contains the horizontal position of
 * one finger, relative to (0, 0) of the canvas. This is best used for
 * single touch interactions. For multi-touch interactions, use the
 * touches[] array.
 *
 * @property touchX
 * @method touchX
 * @example
 *

 *
 * // Touch and move  the finger in horizontally  across the canvas
 * function setup() {
 * createCanvas(100, 100);
 * }
 * function draw() {
 * background(51);
 * stroke(255, 204, 0);
 * strokeWeight(4);
 * rect(touchX,50,10, 10);
 * }
 *
 *

 */
p5.prototype.touchX = 0;

/**
 * The system variable touchY always contains the vertical position of
 * one finger, relative to (0, 0) of the canvas. This is best used for
 * single touch interactions. For multi-touch interactions, use the
 * touches[] array.
 *
 * @property touchY
 * @method touchY
 * @example
 *

 *
 * // Touch and move the finger vertically across the canvas
 * function setup() {
 * createCanvas(100, 100);
 * }
 * function draw() {
 * background(51);
 * stroke(255, 204, 0);
 * strokeWeight(4);
 * rect(50,touchY,10, 10);
 * }
 *
 *

 */
p5.prototype.touchY = 0;

/**
 * The system variable ptouchX always contains the horizontal position of
 * one finger, relative to (0, 0) of the canvas, in the frame previous to the
 * current frame.
 *
 * @property ptouchX
 */
p5.prototype.ptouchX = 0;

/**
 * The system variable ptouchY always contains the vertical position of
 * one finger, relative to (0, 0) of the canvas, in the frame previous to the
 * current frame.
 *
 * @property ptouchY
 */
p5.prototype.ptouchY = 0;

/**
 * The system variable touches[] contains an array of the positions of all
 * current touch points, relative to (0, 0) of the canvas, and IDs identifying a
 * unique touch as it moves. Each element in the array is an object with x, y,
 * and id properties.
 *
 * @property touches[]
 */
p5.prototype.touches = [];

/**
 * The boolean system variable touchIsDown is true if the screen is
 * touched and false if not.
 *
 * @property touchIsDown
 */
p5.prototype.touchIsDown = false;

p5.prototype._updateNextTouchCoords = function(e) {
  var x = this.touchX;
  var y = this.touchY;
  if(e.type === 'mousedown' ||
     e.type === 'mousemove' ||
     e.type === 'mouseup' || !e.touches) {
    x = this.mouseX;
    y = this.mouseY;
  } else {
    if(this._curElement !== null) {
      var touchInfo = getTouchInfo(this._curElement.elt, e, 0);
      x = touchInfo.x;
      y = touchInfo.y;

      var touches = [];
      for(var i = 0; i < e.touches.length; i++){
        touches[i] = getTouchInfo(this._curElement.elt, e, i);
      }
      this._setProperty('touches', touches);
    }
  }
  this._setProperty('touchX', x);
  this._setProperty('touchY', y);
  if (!this._hasTouchInteracted) {
    // For first draw, make previous and next equal
    this._updateTouchCoords();
    this._setProperty('_hasTouchInteracted', true);
  }
};

p5.prototype._updateTouchCoords = function() {
  this._setProperty('ptouchX', this.touchX);
  this._setProperty('ptouchY', this.touchY);
};

function getTouchInfo(canvas, e, i) {
  i = i || 0;
  var rect = canvas.getBoundingClientRect();
  var touch = e.touches[i] || e.changedTouches[i];
  return {
    x: touch.clientX - rect.left,
    y: touch.clientY - rect.top,
    id: touch.identifier
  };
}

/**
 * The touchStarted() function is called once after every time a touch is
 * registered. If no touchStarted() function is defined, the mousePressed()
 * function will be called instead if it is defined.

 * Browsers may have different default behaviors attached to various touch
 * events. To prevent any default behavior for this event, add "return false"
 * to the end of the method.
 *
 * @method touchStarted
 * @example
 *

 *
 * // Touch within the image to change
 * // the value of the rectangle
 *
 * var value = 0;
 * function draw() {
 *   fill(value);
 *   rect(25, 25, 50, 50);
 * }
 * function touchStarted() {
 *   if (value == 0) {
 *     value = 255;
 *   } else {
 *     value = 0;
 *   }
 * }
 *
 *

 *
 *

 *
 * function touchStarted() {
 *   ellipse(touchX, touchY, 5, 5);
 *   // prevent default
 *   return false;
 * }
 *
 *

 */
p5.prototype._ontouchstart = function(e) {
  var context = this._isGlobal ? window : this;
  var executeDefault;
  this._updateNextTouchCoords(e);
  this._updateNextMouseCoords(e);
  this._setProperty('touchIsDown', true);
  if(typeof context.touchStarted === 'function') {
    executeDefault = context.touchStarted(e);
    if(executeDefault === false) {
      e.preventDefault();
    }
  } else if (typeof context.mousePressed === 'function') {
    executeDefault = context.mousePressed(e);
    if(executeDefault === false) {
      e.preventDefault();
    }
    //this._setMouseButton(e);
  }
};

/**
 * The touchMoved() function is called every time a touch move is registered.
 * If no touchMoved() function is defined, the mouseDragged() function will
 * be called instead if it is defined.

 * Browsers may have different default behaviors attached to various touch
 * events. To prevent any default behavior for this event, add "return false"
 * to the end of the method.
 *
 * @method touchMoved
 * @example
 *

 *
 * // Move your finger across the page
 * // to change its value
 *
 * var value = 0;
 * function draw() {
 *   fill(value);
 *   rect(25, 25, 50, 50);
 * }
 * function touchMoved() {
 *   value = value + 5;
 *   if (value > 255) {
 *     value = 0;
 *   }
 * }
 *
 *

 *
 *

 *
 * function touchMoved() {
 *   ellipse(touchX, touchY, 5, 5);
 *   // prevent default
 *   return false;
 * }
 *
 *

 */
p5.prototype._ontouchmove = function(e) {
  var context = this._isGlobal ? window : this;
  var executeDefault;
  this._updateNextTouchCoords(e);
  this._updateNextMouseCoords(e);
  if (typeof context.touchMoved === 'function') {
    executeDefault = context.touchMoved(e);
    if(executeDefault === false) {
      e.preventDefault();
    }
  } else if (typeof context.mouseDragged === 'function') {
    executeDefault = context.mouseDragged(e);
    if(executeDefault === false) {
      e.preventDefault();
    }
  }
};

/**
 * The touchEnded() function is called every time a touch ends. If no
 * touchEnded() function is defined, the mouseReleased() function will be
 * called instead if it is defined.

 * Browsers may have different default behaviors attached to various touch
 * events. To prevent any default behavior for this event, add "return false"
 * to the end of the method.
 *
 * @method touchEnded
 * @example
 *

 *
 * // Release touch within the image to
 * // change the value of the rectangle
 *
 * var value = 0;
 * function draw() {
 *   fill(value);
 *   rect(25, 25, 50, 50);
 * }
 * function touchEnded() {
 *   if (value == 0) {
 *     value = 255;
 *   } else {
 *     value = 0;
 *   }
 * }
 *
 *

 *
 *

 *
 * function touchEnded() {
 *   ellipse(touchX, touchY, 5, 5);
 *   // prevent default
 *   return false;
 * }
 *
 *

 */
p5.prototype._ontouchend = function(e) {
  this._updateNextTouchCoords(e);
  this._updateNextMouseCoords(e);
  if (this.touches.length === 0) {
    this._setProperty('touchIsDown', false);
  }
  var context = this._isGlobal ? window : this;
  var executeDefault;
  if (typeof context.touchEnded === 'function') {
    executeDefault = context.touchEnded(e);
    if(executeDefault === false) {
      e.preventDefault();
    }
  } else if (typeof context.mouseReleased === 'function') {
    executeDefault = context.mouseReleased(e);
    if(executeDefault === false) {
      e.preventDefault();
    }
  }
};

module.exports = p5;
<commit_msg>fixing formatting for touchx/y examples<commit_after>/**
 * @module Events
 * @submodule Touch
 * @for p5
 * @requires core
 */

'use strict';

var p5 = require('../core/core');

/*
 * This is a flag which is false until the first time
 * we receive a touch event. The ptouchX and ptouchY
 * values will match the touchX and touchY values until
 * this interaction takes place.
 */
p5.prototype._hasTouchInteracted = false;

/**
 * The system variable touchX always contains the horizontal position of
 * one finger, relative to (0, 0) of the canvas. This is best used for
 * single touch interactions. For multi-touch interactions, use the
 * touches[] array.
 *
 * @property touchX
 * @method touchX
 * @example
 *

 *
 * // Touch and move  the finger in horizontally  across the canvas
 * function setup() {
 *   createCanvas(100, 100);
 * }
 *
 * function draw() {
 *   background(51);
 *   stroke(255, 204, 0);
 *   strokeWeight(4);
 *   rect(touchX, 50, 10, 10);
 * }
 *
 *

 */
p5.prototype.touchX = 0;

/**
 * The system variable touchY always contains the vertical position of
 * one finger, relative to (0, 0) of the canvas. This is best used for
 * single touch interactions. For multi-touch interactions, use the
 * touches[] array.
 *
 * @property touchY
 * @method touchY
 * @example
 *

 *
 * // Touch and move the finger vertically across the canvas
 * function setup() {
 *   createCanvas(100, 100);
 * }
 *
 * function draw() {
 *   background(51);
 *   stroke(255, 204, 0);
 *   strokeWeight(4);
 *   rect(50, touchY, 10, 10);
 * }
 *
 *

 */
p5.prototype.touchY = 0;

/**
 * The system variable ptouchX always contains the horizontal position of
 * one finger, relative to (0, 0) of the canvas, in the frame previous to the
 * current frame.
 *
 * @property ptouchX
 */
p5.prototype.ptouchX = 0;

/**
 * The system variable ptouchY always contains the vertical position of
 * one finger, relative to (0, 0) of the canvas, in the frame previous to the
 * current frame.
 *
 * @property ptouchY
 */
p5.prototype.ptouchY = 0;

/**
 * The system variable touches[] contains an array of the positions of all
 * current touch points, relative to (0, 0) of the canvas, and IDs identifying a
 * unique touch as it moves. Each element in the array is an object with x, y,
 * and id properties.
 *
 * @property touches[]
 */
p5.prototype.touches = [];

/**
 * The boolean system variable touchIsDown is true if the screen is
 * touched and false if not.
 *
 * @property touchIsDown
 */
p5.prototype.touchIsDown = false;

p5.prototype._updateNextTouchCoords = function(e) {
  var x = this.touchX;
  var y = this.touchY;
  if(e.type === 'mousedown' ||
     e.type === 'mousemove' ||
     e.type === 'mouseup' || !e.touches) {
    x = this.mouseX;
    y = this.mouseY;
  } else {
    if(this._curElement !== null) {
      var touchInfo = getTouchInfo(this._curElement.elt, e, 0);
      x = touchInfo.x;
      y = touchInfo.y;

      var touches = [];
      for(var i = 0; i < e.touches.length; i++){
        touches[i] = getTouchInfo(this._curElement.elt, e, i);
      }
      this._setProperty('touches', touches);
    }
  }
  this._setProperty('touchX', x);
  this._setProperty('touchY', y);
  if (!this._hasTouchInteracted) {
    // For first draw, make previous and next equal
    this._updateTouchCoords();
    this._setProperty('_hasTouchInteracted', true);
  }
};

p5.prototype._updateTouchCoords = function() {
  this._setProperty('ptouchX', this.touchX);
  this._setProperty('ptouchY', this.touchY);
};

function getTouchInfo(canvas, e, i) {
  i = i || 0;
  var rect = canvas.getBoundingClientRect();
  var touch = e.touches[i] || e.changedTouches[i];
  return {
    x: touch.clientX - rect.left,
    y: touch.clientY - rect.top,
    id: touch.identifier
  };
}

/**
 * The touchStarted() function is called once after every time a touch is
 * registered. If no touchStarted() function is defined, the mousePressed()
 * function will be called instead if it is defined.

 * Browsers may have different default behaviors attached to various touch
 * events. To prevent any default behavior for this event, add "return false"
 * to the end of the method.
 *
 * @method touchStarted
 * @example
 *

 *
 * // Touch within the image to change
 * // the value of the rectangle
 *
 * var value = 0;
 * function draw() {
 *   fill(value);
 *   rect(25, 25, 50, 50);
 * }
 * function touchStarted() {
 *   if (value == 0) {
 *     value = 255;
 *   } else {
 *     value = 0;
 *   }
 * }
 *
 *

 *
 *

 *
 * function touchStarted() {
 *   ellipse(touchX, touchY, 5, 5);
 *   // prevent default
 *   return false;
 * }
 *
 *

 */
p5.prototype._ontouchstart = function(e) {
  var context = this._isGlobal ? window : this;
  var executeDefault;
  this._updateNextTouchCoords(e);
  this._updateNextMouseCoords(e);
  this._setProperty('touchIsDown', true);
  if(typeof context.touchStarted === 'function') {
    executeDefault = context.touchStarted(e);
    if(executeDefault === false) {
      e.preventDefault();
    }
  } else if (typeof context.mousePressed === 'function') {
    executeDefault = context.mousePressed(e);
    if(executeDefault === false) {
      e.preventDefault();
    }
    //this._setMouseButton(e);
  }
};

/**
 * The touchMoved() function is called every time a touch move is registered.
 * If no touchMoved() function is defined, the mouseDragged() function will
 * be called instead if it is defined.

 * Browsers may have different default behaviors attached to various touch
 * events. To prevent any default behavior for this event, add "return false"
 * to the end of the method.
 *
 * @method touchMoved
 * @example
 *

 *
 * // Move your finger across the page
 * // to change its value
 *
 * var value = 0;
 * function draw() {
 *   fill(value);
 *   rect(25, 25, 50, 50);
 * }
 * function touchMoved() {
 *   value = value + 5;
 *   if (value > 255) {
 *     value = 0;
 *   }
 * }
 *
 *

 *
 *

 *
 * function touchMoved() {
 *   ellipse(touchX, touchY, 5, 5);
 *   // prevent default
 *   return false;
 * }
 *
 *

 */
p5.prototype._ontouchmove = function(e) {
  var context = this._isGlobal ? window : this;
  var executeDefault;
  this._updateNextTouchCoords(e);
  this._updateNextMouseCoords(e);
  if (typeof context.touchMoved === 'function') {
    executeDefault = context.touchMoved(e);
    if(executeDefault === false) {
      e.preventDefault();
    }
  } else if (typeof context.mouseDragged === 'function') {
    executeDefault = context.mouseDragged(e);
    if(executeDefault === false) {
      e.preventDefault();
    }
  }
};

/**
 * The touchEnded() function is called every time a touch ends. If no
 * touchEnded() function is defined, the mouseReleased() function will be
 * called instead if it is defined.

 * Browsers may have different default behaviors attached to various touch
 * events. To prevent any default behavior for this event, add "return false"
 * to the end of the method.
 *
 * @method touchEnded
 * @example
 *

 *
 * // Release touch within the image to
 * // change the value of the rectangle
 *
 * var value = 0;
 * function draw() {
 *   fill(value);
 *   rect(25, 25, 50, 50);
 * }
 * function touchEnded() {
 *   if (value == 0) {
 *     value = 255;
 *   } else {
 *     value = 0;
 *   }
 * }
 *
 *

 *
 *

 *
 * function touchEnded() {
 *   ellipse(touchX, touchY, 5, 5);
 *   // prevent default
 *   return false;
 * }
 *
 *

 */
p5.prototype._ontouchend = function(e) {
  this._updateNextTouchCoords(e);
  this._updateNextMouseCoords(e);
  if (this.touches.length === 0) {
    this._setProperty('touchIsDown', false);
  }
  var context = this._isGlobal ? window : this;
  var executeDefault;
  if (typeof context.touchEnded === 'function') {
    executeDefault = context.touchEnded(e);
    if(executeDefault === false) {
      e.preventDefault();
    }
  } else if (typeof context.mouseReleased === 'function') {
    executeDefault = context.mouseReleased(e);
    if(executeDefault === false) {
      e.preventDefault();
    }
  }
};

module.exports = p5;
<|endoftext|>


<commit_before>/**
 * @module Events
 * @submodule Touch
 * @for p5
 * @requires core
 */

'use strict';

var p5 = require('../core/core');

/**
 * The system variable touches[] contains an array of the positions of all
 * current touch points, relative to (0, 0) of the canvas, and IDs identifying a
 * unique touch as it moves. Each element in the array is an object with x, y,
 * and id properties.
 *
 * The touches[] array is not supported on Safari and IE on touch-based
 * desktops (laptops).
 *
 * @property {Object[]} touches
 * @readOnly
 */
p5.prototype.touches = [];

p5.prototype._updateTouchCoords = function(e) {
  if (this._curElement !== null) {
    var touches = [];
    for (var i = 0; i < e.touches.length; i++) {
      touches[i] = getTouchInfo(
        this._curElement.elt,
        this.width,
        this.height,
        e,
        i
      );
    }
    this._setProperty('touches', touches);
  }
};

function getTouchInfo(canvas, w, h, e, i) {
  i = i || 0;
  var rect = canvas.getBoundingClientRect();
  var sx = canvas.scrollWidth / w;
  var sy = canvas.scrollHeight / h;
  var touch = e.touches[i] || e.changedTouches[i];
  return {
    x: (touch.clientX - rect.left) / sx,
    y: (touch.clientY - rect.top) / sy,
    winX: touch.clientX,
    winY: touch.clientY,
    id: touch.identifier
  };
}

/**
 * The touchStarted() function is called once after every time a touch is
 * registered. If no touchStarted() function is defined, the mousePressed()
 * function will be called instead if it is defined.

 * Browsers may have different default behaviors attached to various touch
 * events. To prevent any default behavior for this event, add "return false"
 * to the end of the method.
 *
 * @method touchStarted
 * @example
 *

 *
 * // Touch within the image to change
 * // the value of the rectangle
 *
 * var value = 0;
 * function draw() {
 *   fill(value);
 *   rect(25, 25, 50, 50);
 * }
 * function touchStarted() {
 *   if (value === 0) {
 *     value = 255;
 *   } else {
 *     value = 0;
 *   }
 * }
 *
 *

 *
 *

 *
 * function touchStarted() {
 *   ellipse(mouseX, mouseY, 5, 5);
 *   // prevent default
 *   return false;
 * }
 *
 *

 *
 * @alt
 * 50x50 black rect turns white with touch event.
 * no image displayed
 */
p5.prototype._ontouchstart = function(e) {
  var context = this._isGlobal ? window : this;
  var executeDefault;
  this._setProperty('mouseIsPressed', true);
  this._updateTouchCoords(e);
  this._updateNextMouseCoords(e);
  if (typeof context.touchStarted === 'function') {
    executeDefault = context.touchStarted(e);
    if (executeDefault === false) {
      e.preventDefault();
    }
  } else if (typeof context.mousePressed === 'function') {
    executeDefault = context.mousePressed(e);
    if (executeDefault === false) {
      e.preventDefault();
    }
  }
};

/**
 * The touchMoved() function is called every time a touch move is registered.
 * If no touchMoved() function is defined, the mouseDragged() function will
 * be called instead if it is defined.

 * Browsers may have different default behaviors attached to various touch
 * events. To prevent any default behavior for this event, add "return false"
 * to the end of the method.
 *
 * @method touchMoved
 * @example
 *

 *
 * // Move your finger across the page
 * // to change its value
 *
 * var value = 0;
 * function draw() {
 *   fill(value);
 *   rect(25, 25, 50, 50);
 * }
 * function touchMoved() {
 *   value = value + 5;
 *   if (value > 255) {
 *     value = 0;
 *   }
 * }
 *
 *

 *
 *

 *
 * function touchMoved() {
 *   ellipse(mouseX, mouseY, 5, 5);
 *   // prevent default
 *   return false;
 * }
 *
 *

 *
 * @alt
 * 50x50 black rect turns lighter with touch until white. resets
 * no image displayed
 *
 */
p5.prototype._ontouchmove = function(e) {
  var context = this._isGlobal ? window : this;
  var executeDefault;
  this._updateTouchCoords(e);
  this._updateNextMouseCoords(e);
  if (typeof context.touchMoved === 'function') {
    executeDefault = context.touchMoved(e);
    if (executeDefault === false) {
      e.preventDefault();
    }
  } else if (typeof context.mouseDragged === 'function') {
    executeDefault = context.mouseDragged(e);
    if (executeDefault === false) {
      e.preventDefault();
    }
  }
};

/**
 * The touchEnded() function is called every time a touch ends. If no
 * touchEnded() function is defined, the mouseReleased() function will be
 * called instead if it is defined.

 * Browsers may have different default behaviors attached to various touch
 * events. To prevent any default behavior for this event, add "return false"
 * to the end of the method.
 *
 * @method touchEnded
 * @example
 *

 *
 * // Release touch within the image to
 * // change the value of the rectangle
 *
 * var value = 0;
 * function draw() {
 *   fill(value);
 *   rect(25, 25, 50, 50);
 * }
 * function touchEnded() {
 *   if (value === 0) {
 *     value = 255;
 *   } else {
 *     value = 0;
 *   }
 * }
 *
 *

 *
 *

 *
 * function touchEnded() {
 *   ellipse(mouseX, mouseY, 5, 5);
 *   // prevent default
 *   return false;
 * }
 *
 *

 *
 * @alt
 * 50x50 black rect turns white with touch.
 * no image displayed
 *
 */
p5.prototype._ontouchend = function(e) {
  this._setProperty('mouseIsPressed', false);
  this._updateTouchCoords(e);
  this._updateNextMouseCoords(e);
  var context = this._isGlobal ? window : this;
  var executeDefault;
  if (typeof context.touchEnded === 'function') {
    executeDefault = context.touchEnded(e);
    if (executeDefault === false) {
      e.preventDefault();
    }
  } else if (typeof context.mouseReleased === 'function') {
    executeDefault = context.mouseReleased(e);
    if (executeDefault === false) {
      e.preventDefault();
    }
  }
};

module.exports = p5;
<commit_msg>add example for touches property<commit_after>/**
 * @module Events
 * @submodule Touch
 * @for p5
 * @requires core
 */

'use strict';

var p5 = require('../core/core');

/**
 * The system variable touches[] contains an array of the positions of all
 * current touch points, relative to (0, 0) of the canvas, and IDs identifying a
 * unique touch as it moves. Each element in the array is an object with x, y,
 * and id properties.
 *
 * The touches[] array is not supported on Safari and IE on touch-based
 * desktops (laptops).
 *
 * @property {Object[]} touches
 * @readOnly
 *
 * @example
 *

 *
 * // On a touchscreen device, touch
 * // the canvas using one or more fingers
 * // at the same time
 * function draw() {
 *   clear();
 *   var display = touches.length + ' touches';
 *   text(display, 5, 10);
 * }
 *
 *

 *
 * @alt
 * Number of touches currently registered are displayed on the canvas
 */
p5.prototype.touches = [];

p5.prototype._updateTouchCoords = function(e) {
  if (this._curElement !== null) {
    var touches = [];
    for (var i = 0; i < e.touches.length; i++) {
      touches[i] = getTouchInfo(
        this._curElement.elt,
        this.width,
        this.height,
        e,
        i
      );
    }
    this._setProperty('touches', touches);
  }
};

function getTouchInfo(canvas, w, h, e, i) {
  i = i || 0;
  var rect = canvas.getBoundingClientRect();
  var sx = canvas.scrollWidth / w;
  var sy = canvas.scrollHeight / h;
  var touch = e.touches[i] || e.changedTouches[i];
  return {
    x: (touch.clientX - rect.left) / sx,
    y: (touch.clientY - rect.top) / sy,
    winX: touch.clientX,
    winY: touch.clientY,
    id: touch.identifier
  };
}

/**
 * The touchStarted() function is called once after every time a touch is
 * registered. If no touchStarted() function is defined, the mousePressed()
 * function will be called instead if it is defined.

 * Browsers may have different default behaviors attached to various touch
 * events. To prevent any default behavior for this event, add "return false"
 * to the end of the method.
 *
 * @method touchStarted
 * @example
 *

 *
 * // Touch within the image to change
 * // the value of the rectangle
 *
 * var value = 0;
 * function draw() {
 *   fill(value);
 *   rect(25, 25, 50, 50);
 * }
 * function touchStarted() {
 *   if (value === 0) {
 *     value = 255;
 *   } else {
 *     value = 0;
 *   }
 * }
 *
 *

 *
 *

 *
 * function touchStarted() {
 *   ellipse(mouseX, mouseY, 5, 5);
 *   // prevent default
 *   return false;
 * }
 *
 *

 *
 * @alt
 * 50x50 black rect turns white with touch event.
 * no image displayed
 */
p5.prototype._ontouchstart = function(e) {
  var context = this._isGlobal ? window : this;
  var executeDefault;
  this._setProperty('mouseIsPressed', true);
  this._updateTouchCoords(e);
  this._updateNextMouseCoords(e);
  if (typeof context.touchStarted === 'function') {
    executeDefault = context.touchStarted(e);
    if (executeDefault === false) {
      e.preventDefault();
    }
  } else if (typeof context.mousePressed === 'function') {
    executeDefault = context.mousePressed(e);
    if (executeDefault === false) {
      e.preventDefault();
    }
  }
};

/**
 * The touchMoved() function is called every time a touch move is registered.
 * If no touchMoved() function is defined, the mouseDragged() function will
 * be called instead if it is defined.

 * Browsers may have different default behaviors attached to various touch
 * events. To prevent any default behavior for this event, add "return false"
 * to the end of the method.
 *
 * @method touchMoved
 * @example
 *

 *
 * // Move your finger across the page
 * // to change its value
 *
 * var value = 0;
 * function draw() {
 *   fill(value);
 *   rect(25, 25, 50, 50);
 * }
 * function touchMoved() {
 *   value = value + 5;
 *   if (value > 255) {
 *     value = 0;
 *   }
 * }
 *
 *

 *
 *

 *
 * function touchMoved() {
 *   ellipse(mouseX, mouseY, 5, 5);
 *   // prevent default
 *   return false;
 * }
 *
 *

 *
 * @alt
 * 50x50 black rect turns lighter with touch until white. resets
 * no image displayed
 *
 */
p5.prototype._ontouchmove = function(e) {
  var context = this._isGlobal ? window : this;
  var executeDefault;
  this._updateTouchCoords(e);
  this._updateNextMouseCoords(e);
  if (typeof context.touchMoved === 'function') {
    executeDefault = context.touchMoved(e);
    if (executeDefault === false) {
      e.preventDefault();
    }
  } else if (typeof context.mouseDragged === 'function') {
    executeDefault = context.mouseDragged(e);
    if (executeDefault === false) {
      e.preventDefault();
    }
  }
};

/**
 * The touchEnded() function is called every time a touch ends. If no
 * touchEnded() function is defined, the mouseReleased() function will be
 * called instead if it is defined.

 * Browsers may have different default behaviors attached to various touch
 * events. To prevent any default behavior for this event, add "return false"
 * to the end of the method.
 *
 * @method touchEnded
 * @example
 *

 *
 * // Release touch within the image to
 * // change the value of the rectangle
 *
 * var value = 0;
 * function draw() {
 *   fill(value);
 *   rect(25, 25, 50, 50);
 * }
 * function touchEnded() {
 *   if (value === 0) {
 *     value = 255;
 *   } else {
 *     value = 0;
 *   }
 * }
 *
 *

 *
 *

 *
 * function touchEnded() {
 *   ellipse(mouseX, mouseY, 5, 5);
 *   // prevent default
 *   return false;
 * }
 *
 *

 *
 * @alt
 * 50x50 black rect turns white with touch.
 * no image displayed
 *
 */
p5.prototype._ontouchend = function(e) {
  this._setProperty('mouseIsPressed', false);
  this._updateTouchCoords(e);
  this._updateNextMouseCoords(e);
  var context = this._isGlobal ? window : this;
  var executeDefault;
  if (typeof context.touchEnded === 'function') {
    executeDefault = context.touchEnded(e);
    if (executeDefault === false) {
      e.preventDefault();
    }
  } else if (typeof context.mouseReleased === 'function') {
    executeDefault = context.mouseReleased(e);
    if (executeDefault === false) {
      e.preventDefault();
    }
  }
};

module.exports = p5;
<|endoftext|>


<commit_before>'use strict';

var game = new Phaser.Game(1366, 768, Phaser.AUTO, '', null, false, false);

var Ship = function() {};
Ship.prototype = {
    speed: 0,
    acceleration: 0.05,
    position: 0,
    move: function() {
        this.position += this.speed;
    },
    thrust: function() {
        this.speed += this.acceleration;
    },
    update: function() {
        this.move();
    },
    reset: function() {
        this.speed = 0;
        this.position = 0;
    }
};

var Asteroid = function(position, velocity) {
    this.position = position;
    this.velocity = velocity;
};
Asteroid.prototype = {
    move: function() {
        this.position += this.velocity;
    },
    update: function() {
        this.move();
    }
};

var ship = new Ship();
var asteroids = [
    new Asteroid(800, -1)
]

var MainState = function() {};
MainState.prototype = {
    worldLength: 20,
    tileSize: 64,
    xOffset: 43,
    yPosition: (768 / 2) - 32,
    tileScale: undefined,

    gameover: false,

    blopp2SFX: undefined,

    thrusting: false,

    shootRate: 250, // time must pass between shots
    shootLast: 0,
    bullets: [],

    preload: function() {
        // allow the player to right click without the menu popping up
        game.canvas.oncontextmenu = function (e) { e.preventDefault(); }

        this.tileScale = this.tileSize / 16;
        game.load.image('bg',         'assets/sprites/bg.png');
        game.load.image('asteroid_l', 'assets/sprites/asteroid_big.png');
        game.load.image('asteroid_m', 'assets/sprites/asteroid_med.png');
        game.load.image('asteroid_s', 'assets/sprites/asteroid_small.png');
        game.load.image('bullet',     'assets/sprites/bullet.png');
        game.load.image('ship',       'assets/sprites/ship.png');
        game.load.image('thrust',     'assets/sprites/thrust.png');

        game.load.audio('blopp2',    'assets/sfx/blopp2.wav');
        game.load.audio('explosion', 'assets/sfx/explosion.wav');

	    game.load.script('utilScript',          '../js/util.js');
	    game.load.script('directionEnumScript', '../js/direction.enum.js');
	    game.load.script('keycodesScript',      '../js/keycodes.js');

        // necessary to preload the font lol
        game.add.text(0, 0, "", {font: '56px pixelbug', fill: '#ffffff'});
    },
    create: function() {
        var self = this;
        game.add.sprite(0, 0, 'bg');
        game.stage.backgroundColor = "#AAAAAA";
        game.scale.pageAlignHorizontally = true;
        game.scale.pageAlignVertically = true;

        this.shootSFX = game.add.audio('blopp2');
        this.thrustSFX = game.add.audio('thrust');
        this.explosionSFX = game.add.audio('explosion');
        this.winSFX = game.add.audio('thrust');
        this.loseSFX = game.add.audio('thrust');

        this.shipSprite = game.add.sprite(ship.position + this.xOffset, this.yPosition, 'ship');
        this.shipSprite.scale.set(this.tileScale, this.tileScale);

        this.thrustSprite = game.add.sprite(ship.position + this.xOffset - 64, this.yPosition, 'thrust');
        this.thrustSprite.scale.set(this.tileScale, this.tileScale);
        this.thrustSprite.visible = false;

        game.input.keyboard.onDownCallback = function(event) {
            if(keycodes.right.includes(event.key) || keycodes.up.includes(event.key)) {
                self.thrusting = true;
            }
            if(keycodes.space.includes(event.key)) {
                if(self.mayShoot) {
                }
            }
            else if(keycodes.restart.includes(event.key)) {
                // R restart
                ship.reset();
                game.stage.backgroundColor = "#FFFFFF";
                game.state.start('MainState');
            }
        };
        game.input.keyboard.onUpCallback = function(event) {
            if(keycodes.right.includes(event.key) || keycodes.up.includes(event.key)) {
                self.thrusting = false;
            }
        }
    },
    update: function() {
        if(!this.gameover) {
            ship.update();
            this.shipSprite.position.x = ship.position + this.xOffset;
            if(this.thrusting) {
                this.thrustSprite.position.x = this.shipSprite.position.x - 64;
                this.thrustSprite.visible = true;
                this.thrustSFX.play();
                ship.thrust();
            }
            else {
                this.thrustSprite.visible = false;
            }
            if(this.checkWin()) {
                this.win();
            }
            else if(this.checkLose()) {
                this.lose();
            }
        }
    },
    mayShoot: function() {
        var ja = false;
        if(Date.now() - this.shootLast >= this.ShootRate) {
            this.shootLast = Date.now();
            ja = true;
        }
        return ja;
    },
    shoot: function() {
    },
    checkBulletCollisions: function() {
        this.bullets.forEach(function(bullet) {
            asteroids.forEach(function(asteroid) {
                //if(m
            })
        })
    },
    checkShipCollisions: function() {
    },
    checkLose: function() {
        return this.shipDestroyed;
    },
    checkWin: function() {
        return this.asteroidsDestroyed >= 7;
    },
    win: function() {
        var gameOverText = game.add.text(game.world.width / 2, yPos, "YOU WIN!",
            {font: '56px pixelbug', fill: '#ffffff'});
        util.recentreText(gameOverText);
        this.gameover = true;
        this.winSFX.play();
    },
    lose: function(index) {
        var gameOverText = game.add.text(game.world.width / 2, yPos, "YOU LOSE!",
            {font: '56px pixelbug', fill: '#ffffff'});
        util.recentreText(gameOverText);
        this.gameover = true;
        this.loseSFX.play();
    },
};

game.state.add('MainState', MainState);
game.state.start('MainState');
<commit_msg>Collisions almost working<commit_after>'use strict';
// lol don't judge I wrote this as quickly as I could

var game = new Phaser.Game(1366, 768, Phaser.AUTO, '', null, false, false);

var Ship = function() {};
Ship.prototype = {
    speed: 0,
    acceleration: 0.05,
    position: 43,
    move: function() {
        this.position += this.speed;
    },
    thrust: function() {
        this.speed += this.acceleration;
    },
    update: function() {
        this.move();
    },
    reset: function() {
        this.speed = 0;
        this.position = 0;
    }
};

var Asteroid = function(position, velocity, type) {
    this.type = type || 'asteroid_l';
    this.sprite = undefined;
    this.position = position;
    this.velocity = velocity;
    this.yOffset = 32;
    if(this.type == 'asteroid_l') {
        this.radius = 7;
    }
    else if(this.type == 'asteroid_m') {
        this.radius = 4.5;
    }
    else if(this.type == 'asteroid_s') {
        this.radius = 2.5;
    }
};
Asteroid.prototype = {
    move: function() {
        this.position += this.velocity;
    },
    update: function() {
        this.move();
        this.sprite.position.x = this.position;
    }
};

var ship = new Ship();
var asteroids = [
    new Asteroid(1000, -1),
]

var MainState = function() {};
MainState.prototype = {
    worldLength: 20,
    tileSize: 64,
    xOffset: 43,
    yPosition: (768 / 2) - 32,
    tileScale: undefined,

    gameover: false,

    blopp2SFX: undefined,

    thrusting: false,

    shootRate: 250, // time must pass between shots
    shootLast: 0,
    bullets: [],
    bulletSpeed: 5,

    preload: function() {
        // allow the player to right click without the menu popping up
        game.canvas.oncontextmenu = function (e) { e.preventDefault(); }

        this.tileScale = this.tileSize / 16;
        game.load.image('bg',         'assets/sprites/bg.png');
        game.load.image('asteroid_l', 'assets/sprites/asteroid_big.png');
        game.load.image('asteroid_m', 'assets/sprites/asteroid_med.png');
        game.load.image('asteroid_s', 'assets/sprites/asteroid_small.png');
        game.load.image('bullet',     'assets/sprites/bullet.png');
        game.load.image('ship',       'assets/sprites/ship.png');
        game.load.image('thrust',     'assets/sprites/thrust.png');

        game.load.audio('blopp2',    'assets/sfx/blopp2.wav');
        game.load.audio('explosion', 'assets/sfx/explosion.wav');

	    game.load.script('utilScript',          '../js/util.js');
	    game.load.script('directionEnumScript', '../js/direction.enum.js');
	    game.load.script('keycodesScript',      '../js/keycodes.js');

        // necessary to preload the font lol
        game.add.text(0, 0, "", {font: '56px pixelbug', fill: '#ffffff'});
    },
    create: function() {
        var self = this;
        game.add.sprite(0, 0, 'bg');
        game.stage.backgroundColor = "#AAAAAA";
        game.scale.pageAlignHorizontally = true;
        game.scale.pageAlignVertically = true;

        this.shootSFX = game.add.audio('blopp2');
        this.thrustSFX = game.add.audio('thrust');
        this.explosionSFX = game.add.audio('explosion');
        this.winSFX = game.add.audio('thrust');
        this.loseSFX = game.add.audio('thrust');

        this.shipSprite = game.add.sprite(ship.position + this.xOffset, this.yPosition, 'ship');
        this.shipSprite.scale.set(this.tileScale, this.tileScale);

        this.thrustSprite = game.add.sprite(ship.position + this.xOffset - 64, this.yPosition, 'thrust');
        this.thrustSprite.scale.set(this.tileScale, this.tileScale);
        this.thrustSprite.visible = false;

        asteroids.forEach(function(asteroid) {
            var asteroidSprite = game.add.sprite(asteroid.position, self.yPosition + asteroid.yOffset, asteroid.type);
            asteroidSprite.scale.set(self.tileScale, self.tileScale);
            asteroidSprite.anchor.setTo(0.5, 0.5);
            asteroidSprite.angle = util.randomInt(-180, 180);
            asteroid.sprite = asteroidSprite;
        })

        game.input.keyboard.onDownCallback = function(event) {
            if(keycodes.right.includes(event.key) || keycodes.up.includes(event.key)) {
                self.thrusting = true;
            }
            if(keycodes.space.includes(event.key)) {
                if(self.mayShoot()) {
                    self.shoot();
                }
            }
            else if(keycodes.restart.includes(event.key)) {
                // R restart
                ship.reset();
                game.stage.backgroundColor = "#FFFFFF";
                game.state.start('MainState');
            }
        };
        game.input.keyboard.onUpCallback = function(event) {
            if(keycodes.right.includes(event.key) || keycodes.up.includes(event.key)) {
                self.thrusting = false;
            }
        }
    },
    update: function() {
        if(!this.gameover) {
            ship.update();
            this.shipSprite.position.x = ship.position;
            if(this.thrusting) {
                this.thrustSprite.position.x = this.shipSprite.position.x - 64;
                this.thrustSprite.visible = true;
                this.thrustSFX.play();
                ship.thrust();
            }
            else {
                this.thrustSprite.visible = false;
            }

            this.updateBullets();
            this.updateAsteroids();
            this.updateCollisions();

            if(this.checkWin()) {
                this.win();
            }
            else if(this.checkLose()) {
                this.lose();
            }
        }
    },
    mayShoot: function() {
        var ja = false;
        if(Date.now() - this.shootLast >= this.shootRate) {
            this.shootLast = Date.now();
            ja = true;
        }
        return ja;
    },
    shoot: function() {
        var bullet = game.add.sprite(ship.position + 60, this.yPosition + 28, 'bullet');
        bullet.scale.set(this.tileScale, this.tileScale);
        this.bullets.push(bullet);
        this.shootSFX.play();
    },
    updateAsteroids: function() {
        var self = this;
        asteroids.forEach(function(asteroid) {
            asteroid.update();
        })
    },
    updateBullets: function() {
        var self = this;
        this.bullets.forEach(function(bullet) {
            bullet.position.x += self.bulletSpeed;
            if(bullet.position.x > 1500) {
                // clear
            }
        })
    },
    checkBulletCollisions: function() {
        var asteroidsToDestroy = [];
        this.bullets.forEach(function(bullet) {
            asteroids.forEach(function(asteroid) {
                if(bullet.x + 2 > asteroid.position - asteroid.radius) {
                    asteroidsToDestroy.push(asteroid);
                    bullet.destroy();
                }
            })
        })
        asteroidsToDestroy.forEach(function(asteroid) {
            if(asteroid.type == 'asteroid_l') {
                var a_1 = new Asteroid(asteroid.position, -1);
                var sprite1 = game.add.sprite(asteroid.position, self.yPosition + asteroid.yOffset, 'asteroid_m');
                sprite1.scale.set(self.tileScale, self.tileScale);
                sprite1.anchor.setTo(0.5, 0.5);
                sprite1.angle = util.randomInt(-180, 180);
                a_1.sprite = sprite1;

                var a_2 = new Asteroid(asteroid.position, 1);
                var sprite2 = game.add.sprite(asteroid.position, self.yPosition + asteroid.yOffset, 'asteroid_m');
                sprite2.scale.set(self.tileScale, self.tileScale);
                sprite2.anchor.setTo(0.5, 0.5);
                sprite2.angle = util.randomInt(-180, 180);
                a_2.sprite = sprite2;

                asteroids.push(a_1)
                asteroids.push(a_2)
            }
            else if(asteroid.type == 'asteroid_m') {
                var a_1 = new Asteroid(asteroid.position, -1);
                var sprite1 = game.add.sprite(asteroid.position, self.yPosition + asteroid.yOffset, 'asteroid_s');
                sprite1.scale.set(self.tileScale, self.tileScale);
                sprite1.anchor.setTo(0.5, 0.5);
                sprite1.angle = util.randomInt(-180, 180);
                a_1.sprite = sprite1;

                var a_2 = new Asteroid(asteroid.position, 1);
                var sprite2 = game.add.sprite(asteroid.position, self.yPosition + asteroid.yOffset, 'asteroid_s');
                sprite2.scale.set(self.tileScale, self.tileScale);
                sprite2.anchor.setTo(0.5, 0.5);
                sprite2.angle = util.randomInt(-180, 180);
                a_2.sprite = sprite2;

                asteroids.push(a_1)
                asteroids.push(a_2)
            }
            else if(asteroid.type == 'asteroid_s') {
                this.asteroidsDestroyed++;
            }
            asteroid.sprite.destroy();
            var index = asteroids.indexOf(asteroid);
            asteroids.splice(index, 1);
            this.explosionSFX.play();
        })
        asteroidsToDestroy = [];
    },
    checkShipCollisions: function() {
    },
    updateCollisions: function() {
        this.checkBulletCollisions();
        this.checkShipCollisions();
    },
    checkLose: function() {
        return this.shipDestroyed;
    },
    checkWin: function() {
        return this.asteroidsDestroyed >= 7;
    },
    win: function() {
        var gameOverText = game.add.text(game.world.width / 2, yPos, "YOU WIN!",
            {font: '56px pixelbug', fill: '#ffffff'});
        util.recentreText(gameOverText);
        this.gameover = true;
        this.winSFX.play();
    },
    lose: function(index) {
        var gameOverText = game.add.text(game.world.width / 2, yPos, "YOU LOSE!",
            {font: '56px pixelbug', fill: '#ffffff'});
        util.recentreText(gameOverText);
        this.gameover = true;
        this.loseSFX.play();
    },
};

game.state.add('MainState', MainState);
game.state.start('MainState');
<|endoftext|>


<commit_before>var path = require('path');
var AssetsPlugin = require('assets-webpack-plugin')
var CompressionPlugin = require('compression-webpack-plugin')
var assetsPluginInstance = new AssetsPlugin({
  filename: 'static/prd/assets.js',
  processOutput: function (assets) {
    return 'window.WEBPACK_ASSETS = ' + JSON.stringify(assets);
  }
})
var config = require('../config.json');

var compressPlugin = new CompressionPlugin({
  asset: "[path].gz[query]",
  algorithm: "gzip",
  test: /\.(js|css)$/,
  threshold: 10240,
  minRatio: 0.8
});

function fileExist (filePath){
  try {
      return fs.statSync(filePath).isFile();
  } catch (err) {
      return false;
  }
};

function initPlugins(){
  var scripts = [] ;
  if(config.plugins && Array.isArray(config.plugins) && config.plugins.length){
    config.plugins = config.plugins.filter(item=>{
      return fileExist(path.resolve(__dirname, 'node_modules/yapi-plugin-' + item + '/client.js'))
    })
    config.plugins.forEach((plugin)=>{
      scripts.push(`${plugin} : require('plugins/yapi-plugin-${plugin}/client.js')`)
    })
    scripts = "module.exports = {" + scripts.join(",") + "}";
    fs.writeFileSync('client/plugin-module.js', scripts);
  }
}

initPlugins();

module.exports = {
  plugins: [{
    name: 'antd',
    options: {
      modifyQuery: function (defaultQuery) { // 可查看和编辑 defaultQuery
        defaultQuery.plugins = [];
        defaultQuery.plugins.push(["transform-runtime", {
          "polyfill": false,
          "regenerator": true
        }]);
        defaultQuery.plugins.push('transform-decorators-legacy');
        defaultQuery.plugins.push(["import", { libraryName: "antd"}])
        return defaultQuery;
      },
      exclude: /node_modules\/(?!yapi-plugin)/
    }
  }],
  // devtool:  'cheap-source-map',
  config: function (ykit) {
    return {
      exports: [
        './index.js'
      ],
      commonsChunk: {
        vendors: {
          lib: ['react', 'redux',
            'redux-thunk',
            'react-dom',
            'redux-promise',
            'react-router',
            'react-router-dom',
            'prop-types',
            'axios',
            'moment',
            'react-dnd-html5-backend',
            'react-dnd',
            'reactabular-table',
            'reactabular-dnd',
            'table-resolver'
          ],
          lib2: [
            'brace',
            'mockjs',
            'json5',
            'url'
          ]
        }
      },
      modifyWebpackConfig: function (baseConfig) {

        var ENV_PARAMS = {};
        switch (this.env) {
          case 'local':
            ENV_PARAMS = 'dev';
            break;
          case 'dev':
            ENV_PARAMS = 'dev';
            break;
          case 'prd':
            ENV_PARAMS = 'production';
            break;
          default:
        }

        baseConfig.plugins.push(new this.webpack.DefinePlugin({
          'process.env.NODE_ENV': JSON.stringify(ENV_PARAMS),
          'process.env.config': JSON.stringify(config)
        }))

        //初始化配置
        baseConfig.devtool = 'cheap-module-eval-source-map'
        baseConfig.context = path.resolve(__dirname, './client');
        baseConfig.resolve.alias.client = '/client';
        baseConfig.resolve.alias.common = '/common';
        baseConfig.resolve.alias.plugins = '/node_modules';
        baseConfig.resolve.alias.exts = '/exts';
        baseConfig.output.prd.path = 'static/prd';
        baseConfig.output.prd.publicPath = '';
        baseConfig.output.prd.filename = '[name]@[chunkhash][ext]'

        baseConfig.module.loaders.push({
          test: /\.less$/,
          loader: ykit.ExtractTextPlugin.extract(
            require.resolve('style-loader'),
            require.resolve('css-loader')
            + '?sourceMap!'
            + require.resolve('less-loader') + '?sourceMap'
          )
        })
        baseConfig.module.loaders.push({
          test: /\.(sass|scss)$/,
          loader: ykit.ExtractTextPlugin.extract(
            require.resolve('css-loader')
            + '?sourceMap!'
            + require.resolve('fast-sass-loader-china') + '?sourceMap'
          )
        })
        baseConfig.module.preLoaders.push({
          test: /\.(js|jsx)$/,
          exclude: /node_modules/,
          loader: "eslint-loader"
        });

        if (this.env == 'prd') {
          baseConfig.plugins.push(assetsPluginInstance)
          baseConfig.plugins.push(compressPlugin)

        }
        return baseConfig;
      }
    }
  },
  server: {
    // true/false，默认 false，效果相当于 ykit server --hot
    hot: true,
    // true/false，默认 false，开启后可在当前打开的页面提示打包错误
    overlay: false
  },
  hooks: {},
  commands: []
};
<commit_msg>fix: plugin-module bug<commit_after>var path = require('path');
var AssetsPlugin = require('assets-webpack-plugin')
var CompressionPlugin = require('compression-webpack-plugin')
var assetsPluginInstance = new AssetsPlugin({
  filename: 'static/prd/assets.js',
  processOutput: function (assets) {
    return 'window.WEBPACK_ASSETS = ' + JSON.stringify(assets);
  }
})
var config = require('../config.json');

var compressPlugin = new CompressionPlugin({
  asset: "[path].gz[query]",
  algorithm: "gzip",
  test: /\.(js|css)$/,
  threshold: 10240,
  minRatio: 0.8
});

function fileExist (filePath){
  try {
      return fs.statSync(filePath).isFile();
  } catch (err) {
      return false;
  }
};

function initPlugins(){
  var scripts = [] ;
  if(config.plugins && Array.isArray(config.plugins) && config.plugins.length){
    config.plugins = config.plugins.filter(item=>{
      return fileExist(path.resolve(__dirname, 'node_modules/yapi-plugin-' + item + '/client.js'))
    })
    config.plugins.forEach((plugin)=>{
      scripts.push(`${plugin} : require('plugins/yapi-plugin-${plugin}/client.js')`)
    })
    scripts = "module.exports = {" + scripts.join(",") + "}";
    fs.writeFileSync('client/plugin-module.js', scripts);
  }else{
    fs.writeFileSync('client/plugin-module.js', 'module.exports = {}');
  }
}

initPlugins();

module.exports = {
  plugins: [{
    name: 'antd',
    options: {
      modifyQuery: function (defaultQuery) { // 可查看和编辑 defaultQuery
        defaultQuery.plugins = [];
        defaultQuery.plugins.push(["transform-runtime", {
          "polyfill": false,
          "regenerator": true
        }]);
        defaultQuery.plugins.push('transform-decorators-legacy');
        defaultQuery.plugins.push(["import", { libraryName: "antd"}])
        return defaultQuery;
      },
      exclude: /node_modules\/(?!yapi-plugin)/
    }
  }],
  // devtool:  'cheap-source-map',
  config: function (ykit) {
    return {
      exports: [
        './index.js'
      ],
      commonsChunk: {
        vendors: {
          lib: ['react', 'redux',
            'redux-thunk',
            'react-dom',
            'redux-promise',
            'react-router',
            'react-router-dom',
            'prop-types',
            'axios',
            'moment',
            'react-dnd-html5-backend',
            'react-dnd',
            'reactabular-table',
            'reactabular-dnd',
            'table-resolver'
          ],
          lib2: [
            'brace',
            'mockjs',
            'json5',
            'url'
          ]
        }
      },
      modifyWebpackConfig: function (baseConfig) {

        var ENV_PARAMS = {};
        switch (this.env) {
          case 'local':
            ENV_PARAMS = 'dev';
            break;
          case 'dev':
            ENV_PARAMS = 'dev';
            break;
          case 'prd':
            ENV_PARAMS = 'production';
            break;
          default:
        }

        baseConfig.plugins.push(new this.webpack.DefinePlugin({
          'process.env.NODE_ENV': JSON.stringify(ENV_PARAMS),
          'process.env.config': JSON.stringify(config)
        }))

        //初始化配置
        baseConfig.devtool = 'cheap-module-eval-source-map'
        baseConfig.context = path.resolve(__dirname, './client');
        baseConfig.resolve.alias.client = '/client';
        baseConfig.resolve.alias.common = '/common';
        baseConfig.resolve.alias.plugins = '/node_modules';
        baseConfig.resolve.alias.exts = '/exts';
        baseConfig.output.prd.path = 'static/prd';
        baseConfig.output.prd.publicPath = '';
        baseConfig.output.prd.filename = '[name]@[chunkhash][ext]'

        baseConfig.module.loaders.push({
          test: /\.less$/,
          loader: ykit.ExtractTextPlugin.extract(
            require.resolve('style-loader'),
            require.resolve('css-loader')
            + '?sourceMap!'
            + require.resolve('less-loader') + '?sourceMap'
          )
        })
        baseConfig.module.loaders.push({
          test: /\.(sass|scss)$/,
          loader: ykit.ExtractTextPlugin.extract(
            require.resolve('css-loader')
            + '?sourceMap!'
            + require.resolve('fast-sass-loader-china') + '?sourceMap'
          )
        })
        baseConfig.module.preLoaders.push({
          test: /\.(js|jsx)$/,
          exclude: /node_modules/,
          loader: "eslint-loader"
        });

        if (this.env == 'prd') {
          baseConfig.plugins.push(assetsPluginInstance)
          baseConfig.plugins.push(compressPlugin)

        }
        return baseConfig;
      }
    }
  },
  server: {
    // true/false，默认 false，效果相当于 ykit server --hot
    hot: true,
    // true/false，默认 false，开启后可在当前打开的页面提示打包错误
    overlay: false
  },
  hooks: {},
  commands: []
};
<|endoftext|>


<commit_before>window.m = ( function( mithril ){
  // Registry of controllers and corresponding root nodes
  var roots     = new Map()
  // A record of recent view outputs for every root-level component
  var history   = new WeakMap()
  // Whether the current draw is being used to revert to its previous state
  var reverting = false

  // Register views to bind their roots to the above
  function register( view ){
    return function registeredView( ctrl ){
      var output = view.apply( this, arguments )

      if( ctrl.exit ){
        var node = output

        while( node.length )
          node = node[ 0 ]

        var config = node.attrs.config

        node.attrs.config = function superConfig( el ){
          roots.set( ctrl, el )

          if( config )
            return config.apply( this, arguments )
        }
      }

      return output
    }
  }

  // Root components (those mounted or routed) are the source of redraws.
  // Before they draw, there is no stateful virtual DOM.
  // Therefore their view execution is the source of all truth in what is currently rendered.
  function root( component ){
    var view = component.view

    component.view = rootView

    return component

    function rootView( ctrl ){
      // If we are in the middle of a reversion, we just want to patch
      // Mithril's internal virtual DOM HEAD to what it was before the
      // last output
      if( reverting )
        return history.get( ctrl )

      // All previously registered exitable components are saved here
      var previous = array( roots )

      // Then we reset
      roots.clear()

      // Execute the view, registering all exitables
      var output   = register( view ).apply( this, arguments )

        // Record the output, we will need to return to this state if the next draw has exits
      history.set( ctrl, output )

      // Now, set up a list of confirmed exits
      var exits    = []

      // For every previous exitable instance...
      for( var i = 0; i < previous.length; i++ )
        // ...if it hasn't re-registered...
        if( !roots.has( previous[ i ][ 0 ] ) )
          // It's gone! Call the exit method and keep its output.
          exits.push( previous[ i ][ 0 ].exit( previous[ i ][ 1 ] ) )

      // If we have exits...
      if( exits.length ){
        // Noop this draw
        output = { subtree : 'retain' }

        // ...and all subsequent ones...
        mithril.startComputation()

        // ...until all exits have resolved
        mithril.sync( exits ).then( function(){
          // We now need to revert Mithril's internal virtual DOM head so that
          // it will correctly patch the live DOM to match the state in which
          // components are removed: it currently believes that already happend
          // Because it ran the diff before we told it to retain the subtree at
          // the last minute
          reverting = true

          // Next draw should not patch, only diff
          m.redraw.strategy( 'none' )

          // Force a synchronous draw despite being frozen
          m.redraw( true )

          // Now it's as if we were never here to begin with
          reverting = false

          // Resume business as usual
          m.endComputation()
        } )
      }

      return output
    }
  }

  // Helper: transform each value in an object. Even in ES7, this is painfully contrived.
  function reduce( object, transformer ){
    var output = {}

    for( var key in object )
      if( Object.prototype.hasOwnProperty.call( object, key ) )
        output[ key ] = transformer( object[ key ] )

    return output
  }

  function array( map ){
    var array   = []
    var entries = map.entries()

    while( true ){
      var entry = entries.next()

      if( entry.done )
        break

      array.push( entry.value )
    }

    return array
  }

  // Export a patched Mithril API

  // Core m function needs to sniff out components...
  function m(){
    var output = mithril.apply( this, arguments )

    for( var i = 0; i < output.children.length; i++ )
      if( output.children[ i ].view )
        output.children[ i ].view = register( output.children[ i ].view )

    return output
  }

  // Then we have all the m methods
  for( var key in mithril )
    if( Object.prototype.hasOwnProperty.call( mithril, key ) )
      m[ key ] = mithril[ key ]

  // Mount and Route need to register root components for snapshot logic
  m.mount = function( el, component ){
    return mithril.mount( el, root( component ) )
  }

  m.route = function( el, path, map ){
    if( map ){
      return mithril.route( el, path, reduce( map, root ) )
    }
    else {
      return mithril.route.apply( this, arguments )
    }
  }

  return m
}( m ) );
<commit_msg>:zap:  works in ES3<commit_after>window.m = ( function( mithril ){
  // Registry of controllers and corresponding root nodes
  var roots     = new Map()
  // A record of recent view outputs for every root-level component
  var history   = new WeakMap()
  // Whether the current draw is being used to revert to its previous state
  var reverting = false

  // Register views to bind their roots to the above
  function register( view ){
    return function registeredView( ctrl ){
      var output = view.apply( this, arguments )

      if( ctrl.exit ){
        var node = output

        while( node.length )
          node = node[ 0 ]

        var config = node.attrs.config

        node.attrs.config = function superConfig( el ){
          roots.set( ctrl, el )

          if( config )
            return config.apply( this, arguments )
        }
      }

      return output
    }
  }

  // Root components (those mounted or routed) are the source of redraws.
  // Before they draw, there is no stateful virtual DOM.
  // Therefore their view execution is the source of all truth in what is currently rendered.
  function root( component ){
    var view = component.view

    component.view = rootView

    return component

    function rootView( ctrl ){
      // If we are in the middle of a reversion, we just want to patch
      // Mithril's internal virtual DOM HEAD to what it was before the
      // last output
      if( reverting )
        return history.get( ctrl )

      // All previously registered exitable components are saved here
      var previous = array( roots )

      // Then we reset
      roots.clear()

      // Execute the view, registering all exitables
      var output   = register( view ).apply( this, arguments )

        // Record the output, we will need to return to this state if the next draw has exits
      history.set( ctrl, output )

      // Now, set up a list of confirmed exits
      var exits    = []

      // For every previous exitable instance...
      for( var i = 0; i < previous.length; i++ )
        // ...if it hasn't re-registered...
        if( !roots.has( previous[ i ][ 0 ] ) )
          // It's gone! Call the exit method and keep its output.
          exits.push( previous[ i ][ 0 ].exit( previous[ i ][ 1 ] ) )

      // If we have exits...
      if( exits.length ){
        // Noop this draw
        output = { subtree : 'retain' }

        // ...and all subsequent ones...
        mithril.startComputation()

        // ...until all exits have resolved
        mithril.sync( exits ).then( function(){
          // We now need to revert Mithril's internal virtual DOM head so that
          // it will correctly patch the live DOM to match the state in which
          // components are removed: it currently believes that already happend
          // Because it ran the diff before we told it to retain the subtree at
          // the last minute
          reverting = true

          // Next draw should not patch, only diff
          m.redraw.strategy( 'none' )

          // Force a synchronous draw despite being frozen
          m.redraw( true )

          // Now it's as if we were never here to begin with
          reverting = false

          // Resume business as usual
          m.endComputation()
        } )
      }

      return output
    }
  }

  // Helper: transform each value in an object. Even in ES7, this is painfully contrived.
  function reduce( object, transformer ){
    var output = {}

    for( var key in object )
      if( Object.prototype.hasOwnProperty.call( object, key ) )
        output[ key ] = transformer( object[ key ] )

    return output
  }

  function array( map ){
    var array   = []
    var entries = map.entries()

    while( true ){
      var entry = entries.next()

      if( entry.done )
        break

      array.push( entry.value )
    }

    return array
  }

  // Export a patched Mithril API

  // Core m function needs to sniff out components...
  function m(){
    var output = mithril.apply( this, arguments )

    for( var i = 0; i < output.children.length; i++ )
      if( output.children[ i ].view )
        output.children[ i ].view = register( output.children[ i ].view )

    return output
  }

  // Then we have all the m methods
  for( var key in mithril )
    if( Object.prototype.hasOwnProperty.call( mithril, key ) )
      m[ key ] = mithril[ key ]

  m.component = function( component ){
    component.view = register( component.view )

    // I don't know how I coped without ES6 spread operator....
    return mithril.component.apply( mithril, [ component ].concat( [].slice.call( arguments, 1 ) ) )
  }

  // Mount and Route need to register root components for snapshot logic
  m.mount = function( el, component ){
    return mithril.mount( el, root( component ) )
  }

  m.route = function( el, path, map ){
    if( map ){
      return mithril.route( el, path, reduce( map, root ) )
    }
    else {
      return mithril.route.apply( this, arguments )
    }
  }

  return m
}( m ) );
<|endoftext|>


<commit_before>/**
 * Featherlight - ultra slim jQuery lightbox
 * Version 0.4.9 - http://noelboss.github.io/featherlight/
 *
 * Copyright 2014, Noël Raoul Bossart (http://www.noelboss.com)
 * MIT Licensed.
**/
(function($) {
	"use strict";

	if('undefined' === typeof $) {
		if('console' in window){ window.console.info('Too much lightness, Featherlight needs jQuery.'); }
		return;
	}

	/* extend jQuery with standalone featherlight method  $.featherlight(elm, config); */
	var Fl = $.featherlight = function($content, config) {
			if(this.constructor === Fl) {  /* called with new */
				this.id = Fl.id++;
				this.setup($content, config);
			} else {
				var fl = new Fl($content, config);
				fl.open();
				return fl;
			}
		},

		/* document wide esc handler, attached in setup method */
		escapeHelper = function(event) {
			if (27 === event.keyCode && !event.isDefaultPrevented()) { // esc keycode
				var self = Fl.current();
				if(self && self.closeOnEsc) {
					self.$instance.find('.'+self.namespace+'-close:first').click();
					event.preventDefault();
				}
			}
		},

		/* read element's attributes starting with data-featherlight- */
		readElementConfigHelper = function(element) {
			var config = {};
			if (element && element.attributes) {
					$.each(element.attributes, function(){
					var match = this.name.match(/^data-featherlight-(.*)/);
					if (match) {
						var val = this.value;
						try {
							val = $.parseJSON(val);
						}
						catch(e) {}
						config[$.camelCase(match[1])] = val;
					}
				});
			}
			return config;
		};

	/* extend featherlight with defaults and methods */
	$.extend(Fl, {
		id: 0,                                    /* Used to id single featherlight instances */
		autoBind:       '[data-featherlight]',    /* Will automatically bind elements matching this selector. Clear or set before onReady */
		defaults: {                               /* You can access and override all defaults using $.featherlight.defaults */
			namespace:    'featherlight',         /* Name of the events and css class prefix */
			targetAttr:   'data-featherlight',    /* Attribute of the triggered element that contains the selector to the lightbox content */
			variant:      null,                   /* Class that will be added to change look of the lightbox */
			resetCss:     false,                  /* Reset all css */
			background:   null,                   /* Custom DOM for the background, wrapper and the closebutton */
			openTrigger:  'click',                /* Event that triggers the lightbox */
			closeTrigger: 'click',                /* Event that triggers the closing of the lightbox */
			filter:       null,                   /* Selector to filter events. Think $(...).on('click', filter, eventHandler) */
			root:         'body',                 /* Where to append featherlights */
			openSpeed:    250,                    /* Duration of opening animation */
			closeSpeed:   250,                    /* Duration of closing animation */
			closeOnClick: 'background',           /* Close lightbox on click ('background', 'anywhere' or false) */
			closeOnEsc:   true,                   /* Close lightbox when pressing esc */
			closeIcon:    '✕',             /* Close icon */
			otherClose:   null,                   /* Selector for alternate close buttons (e.g. "a.close") */
			beforeOpen:   $.noop,                 /* Called before open. can return false to prevent opening of lightbox. Gets event as parameter, this contains all data */
			beforeClose:  $.noop,                 /* Called before close. can return false to prevent opening of lightbox. Gets event as parameter, this contains all data */
			afterOpen:    $.noop,                 /* Called after open. Gets event as parameter, this contains all data */
			afterClose:   $.noop,                 /* Called after close. Gets event as parameter, this contains all data */
			type:         null,                   /* Specify type of lightbox. If unset, it will check for the targetAttrs value. */
			contentFilters: ['jquery', 'image', 'html', 'ajax', 'text'] /* List of content filters to use to determine the content */
		},
		/* you can access and override all methods using $.featherlight.methods */
		methods: {
			/* setup iterates over a single instance of featherlight and prepares the background and binds the events */
			setup: function(target, config){
				/* all arguments are optional */
				if (typeof target === 'object' && target instanceof $ === false && !config) {
					config = target;
					target = undefined;
				}

				var self = $.extend(this, Fl.defaults, config, {target: target}),
					css = !self.resetCss ? self.namespace : self.namespace+'-reset', /* by adding -reset to the classname, we reset all the default css */
					$background = $(self.background || '

'+self.closeIcon+'

'),
					closeButtonSelector = '.'+self.namespace+'-close' + (self.otherClose ? ',' + self.otherClose : '');

				self.$instance = $background.clone().addClass(self.variant); /* clone DOM for the background, wrapper and the close button */

				/* attach esc handler to document if configured */
				if(self.closeOnEsc && escapeHelper) {
					$(document).bind('keyup.'+Fl.defaults.namespace, escapeHelper);
					escapeHelper = null;
				}

				/* close when click on background/anywhere/null or closebox */
				self.$instance.on(self.closeTrigger+'.'+self.namespace, function(event) {
					var $target = $(event.target);
					if( ('background' === self.closeOnClick  && $target.is('.'+self.namespace))
						|| 'anywhere' === self.closeOnClick
						|| $target.is(closeButtonSelector) ){
						event.preventDefault();
						self.close();
					}
				});

				return this;
			},

			/* this method prepares the content and converts it into a jQuery object or a promise */
			getContent: function(){
				var self = this,
					sourceAttr = function(name){ return self.source && self.source.getAttribute(name); },
					targetValue = sourceAttr(self.targetAttr),
					data = self.target || targetValue || '';

				/* Find which filter applies */
				var filter = Fl.contentFilters[self.type]; /* check explicit type like {type: 'image'} */

				/* check explicit type like data-featherlight="image" */
				if(!filter && data in Fl.contentFilters) {
					filter = Fl.contentFilters[data];
					data = self.target && targetValue;
				}
				data = data || sourceAttr('href') || '';

				/* check explicity type & content like {image: 'photo.jpg'} */
				if(!filter) {
					for(var filterName in Fl.contentFilters) {
						if(self[filterName]) {
							filter = Fl.contentFilters[filterName];
							data = self[filterName];
						}
					}
				}

				/* otherwise it's implicit, run checks */
				if(!filter) {
					var target = data;
					data = null;
					$.each(self.contentFilters, function() {
						filter = Fl.contentFilters[this];
						if(filter.test)  {
							data = filter.test(target);
						}
						if(!data && filter.regex && target.match && target.match(filter.regex)) {
							data = target;
						}
						return !data;
					});
					if(!data) {
						if('console' in window){ window.console.error('Featherlight: no content filter found ' + (target ? ' for "' + target + '"' : ' (no target specified)')); }
						return false;
					}
				}
				/* Process it */
				return filter.process.call(self, data);
			},

			/* sets the content of $instance to $content */
			setContent: function($content){
				var self = this;
				/* we need a special class for the iframe */
				if($content.is('iframe') || $('iframe', $content).length > 0){
					self.$instance.addClass(self.namespace+'-iframe');
				}
				self.$content = $content.addClass(self.namespace+'-inner');

				/* remove existing content */
				self.$instance.find('.'+self.namespace+'-inner').remove();
				self.$instance.find('.'+self.namespace+'-content').append(self.$content);

				return self;
			},

			/* opens the lightbox. "this" contains $instance with the lightbox, and with the config */
			open: function(event){
				var self = this;
				if(event && !event.isDefaultPrevented()
					|| self.beforeOpen(event) !== false) {

					if(event){
						event.preventDefault();
					}
					var $content = self.getContent();

					if($content){
						/* Add to opened registry */
						self.constructor._opened.add(self._openedCallback = function(response){
							if(self.$instance.closest('body').length > 0) {
								response.currentFeatherlight = self;
							}
						});

						/* Set content and show */
						$.when($content).done(function($content){
							self.setContent($content)
								.$instance.appendTo(self.root).fadeIn(self.openSpeed);
							self.afterOpen(event);
						});
						return self;
					}
				}
				return false;
			},

			/* closes the lightbox. "this" contains $instance with the lightbox, and with the config */
			close: function(event){
				var self = this;
				if(self.beforeClose(event) === false) {
					return false;
				}
				self.constructor._opened.remove(self._openedCallback);
				self.$instance.fadeOut(self.closeSpeed,function(){
					self.$instance.detach();
					self.afterClose(event);
				});
			}
		},
		/* Contains the logic to determine content */
		contentFilters: {
			jquery: {
				regex: /^[#.]\w/,         /* Anything that starts with a class name or identifiers */
				test: function(elem)    { return elem instanceof $ && elem; },
				process: function(elem) { return $(elem).clone(true); }
			},
			image: {
				regex: /\.(png|jpg|jpeg|gif|tiff|bmp)(\?\S*)?$/i,
				process: function(url)  {
					var self = this,
						deferred = $.Deferred(),
						img = new Image();
					img.onload  = function() { deferred.resolve(
						$('')
					); };
					img.onerror = function() { deferred.reject(); };
					img.src = url;
					return deferred.promise();
				}
			},
			html: {
				regex: /^\s*<[\w!][^<]*>/, /* Anything that starts with some kind of valid tag */
				process: function(html) { return $(html); }
			},
			ajax: {
				regex: /./,            /* At this point, any content is assumed to be an URL */
				process: function(url)  {
					var self = this,
						deferred = $.Deferred();
					/* we are using load so one can specify a target with: url.html #targetelement */
					var $container = $('

').load(url, function(response, status){
						if ( status !== "error" ) {
							deferred.resolve($container.contents());
						}
						deferred.fail();
					});
					return deferred.promise();
				}
			},
			text: {
				process: function(text) { return $('
', {text: text}); }
			}
		},

		attach: function($source, $content, config) {
			if (typeof $content === 'object' && $content instanceof $ === false && !config) {
				config = $content;
				$content = undefined;
			}
			/* make a copy */
			config = $.extend({}, config);

			/* Only for openTrigger and namespace... */
			var tempConfig = $.extend({}, Fl.defaults, readElementConfigHelper($source[0]), config);

			$source.on(tempConfig.openTrigger+'.'+tempConfig.namespace, tempConfig.filter, function(event) {
				/* ... since we might as well compute the config on the actual target */
				var elemConfig = $.extend({source: this}, readElementConfigHelper(this), config);
				new $.featherlight($content, elemConfig).open(event);
			});
		},

		current: function() {
			var response = {};
			this._opened.fire(response);
			return response.currentFeatherlight;
		},

		close: function() {
			var cur = Fl.current();
			if(cur) { cur.close(); }
		},

		_opened: $.Callbacks()
	});

	Fl.prototype = $.extend({constructor: Fl}, Fl.methods);

	/* bind jQuery elements to trigger featherlight */
	$.fn.featherlight = function($content, config) {
		Fl.attach(this, $content, config);
		return this;
	};

	/* bind featherlight on ready if config autoBind is set */
	$(document).ready(function(){
		if(Fl.autoBind){
			$(document).featherlight({filter: Fl.autoBind});
		}
	});
}(jQuery));
<commit_msg>Rename local variable<commit_after>/**
 * Featherlight - ultra slim jQuery lightbox
 * Version 0.4.9 - http://noelboss.github.io/featherlight/
 *
 * Copyright 2014, Noël Raoul Bossart (http://www.noelboss.com)
 * MIT Licensed.
**/
(function($) {
	"use strict";

	if('undefined' === typeof $) {
		if('console' in window){ window.console.info('Too much lightness, Featherlight needs jQuery.'); }
		return;
	}

	/* extend jQuery with standalone featherlight method  $.featherlight(elm, config); */
	var Fl = $.featherlight = function($content, config) {
			if(this.constructor === Fl) {  /* called with new */
				this.id = Fl.id++;
				this.setup($content, config);
			} else {
				var fl = new Fl($content, config);
				fl.open();
				return fl;
			}
		},

		/* document wide esc handler, attached in setup method */
		escapeHelper = function(event) {
			if (27 === event.keyCode && !event.isDefaultPrevented()) { // esc keycode
				var self = Fl.current();
				if(self && self.closeOnEsc) {
					self.$instance.find('.'+self.namespace+'-close:first').click();
					event.preventDefault();
				}
			}
		},

		/* read element's attributes starting with data-featherlight- */
		readElementConfigHelper = function(element) {
			var config = {};
			if (element && element.attributes) {
					$.each(element.attributes, function(){
					var match = this.name.match(/^data-featherlight-(.*)/);
					if (match) {
						var val = this.value;
						try {
							val = $.parseJSON(val);
						}
						catch(e) {}
						config[$.camelCase(match[1])] = val;
					}
				});
			}
			return config;
		};

	/* extend featherlight with defaults and methods */
	$.extend(Fl, {
		id: 0,                                    /* Used to id single featherlight instances */
		autoBind:       '[data-featherlight]',    /* Will automatically bind elements matching this selector. Clear or set before onReady */
		defaults: {                               /* You can access and override all defaults using $.featherlight.defaults */
			namespace:    'featherlight',         /* Name of the events and css class prefix */
			targetAttr:   'data-featherlight',    /* Attribute of the triggered element that contains the selector to the lightbox content */
			variant:      null,                   /* Class that will be added to change look of the lightbox */
			resetCss:     false,                  /* Reset all css */
			background:   null,                   /* Custom DOM for the background, wrapper and the closebutton */
			openTrigger:  'click',                /* Event that triggers the lightbox */
			closeTrigger: 'click',                /* Event that triggers the closing of the lightbox */
			filter:       null,                   /* Selector to filter events. Think $(...).on('click', filter, eventHandler) */
			root:         'body',                 /* Where to append featherlights */
			openSpeed:    250,                    /* Duration of opening animation */
			closeSpeed:   250,                    /* Duration of closing animation */
			closeOnClick: 'background',           /* Close lightbox on click ('background', 'anywhere' or false) */
			closeOnEsc:   true,                   /* Close lightbox when pressing esc */
			closeIcon:    '✕',             /* Close icon */
			otherClose:   null,                   /* Selector for alternate close buttons (e.g. "a.close") */
			beforeOpen:   $.noop,                 /* Called before open. can return false to prevent opening of lightbox. Gets event as parameter, this contains all data */
			beforeClose:  $.noop,                 /* Called before close. can return false to prevent opening of lightbox. Gets event as parameter, this contains all data */
			afterOpen:    $.noop,                 /* Called after open. Gets event as parameter, this contains all data */
			afterClose:   $.noop,                 /* Called after close. Gets event as parameter, this contains all data */
			type:         null,                   /* Specify type of lightbox. If unset, it will check for the targetAttrs value. */
			contentFilters: ['jquery', 'image', 'html', 'ajax', 'text'] /* List of content filters to use to determine the content */
		},
		/* you can access and override all methods using $.featherlight.methods */
		methods: {
			/* setup iterates over a single instance of featherlight and prepares the background and binds the events */
			setup: function(target, config){
				/* all arguments are optional */
				if (typeof target === 'object' && target instanceof $ === false && !config) {
					config = target;
					target = undefined;
				}

				var self = $.extend(this, Fl.defaults, config, {target: target}),
					css = !self.resetCss ? self.namespace : self.namespace+'-reset', /* by adding -reset to the classname, we reset all the default css */
					$background = $(self.background || '

'+self.closeIcon+'

'),
					closeButtonSelector = '.'+self.namespace+'-close' + (self.otherClose ? ',' + self.otherClose : '');

				self.$instance = $background.clone().addClass(self.variant); /* clone DOM for the background, wrapper and the close button */

				/* attach esc handler to document if configured */
				if(self.closeOnEsc && escapeHelper) {
					$(document).bind('keyup.'+Fl.defaults.namespace, escapeHelper);
					escapeHelper = null;
				}

				/* close when click on background/anywhere/null or closebox */
				self.$instance.on(self.closeTrigger+'.'+self.namespace, function(event) {
					var $target = $(event.target);
					if( ('background' === self.closeOnClick  && $target.is('.'+self.namespace))
						|| 'anywhere' === self.closeOnClick
						|| $target.is(closeButtonSelector) ){
						event.preventDefault();
						self.close();
					}
				});

				return this;
			},

			/* this method prepares the content and converts it into a jQuery object or a promise */
			getContent: function(){
				var self = this,
					readTargetAttr = function(name){ return self.source && self.source.getAttribute(name); },
					targetValue = readTargetAttr(self.targetAttr),
					data = self.target || targetValue || '';

				/* Find which filter applies */
				var filter = Fl.contentFilters[self.type]; /* check explicit type like {type: 'image'} */

				/* check explicit type like data-featherlight="image" */
				if(!filter && data in Fl.contentFilters) {
					filter = Fl.contentFilters[data];
					data = self.target && targetValue;
				}
				data = data || readTargetAttr('href') || '';

				/* check explicity type & content like {image: 'photo.jpg'} */
				if(!filter) {
					for(var filterName in Fl.contentFilters) {
						if(self[filterName]) {
							filter = Fl.contentFilters[filterName];
							data = self[filterName];
						}
					}
				}

				/* otherwise it's implicit, run checks */
				if(!filter) {
					var target = data;
					data = null;
					$.each(self.contentFilters, function() {
						filter = Fl.contentFilters[this];
						if(filter.test)  {
							data = filter.test(target);
						}
						if(!data && filter.regex && target.match && target.match(filter.regex)) {
							data = target;
						}
						return !data;
					});
					if(!data) {
						if('console' in window){ window.console.error('Featherlight: no content filter found ' + (target ? ' for "' + target + '"' : ' (no target specified)')); }
						return false;
					}
				}
				/* Process it */
				return filter.process.call(self, data);
			},

			/* sets the content of $instance to $content */
			setContent: function($content){
				var self = this;
				/* we need a special class for the iframe */
				if($content.is('iframe') || $('iframe', $content).length > 0){
					self.$instance.addClass(self.namespace+'-iframe');
				}
				self.$content = $content.addClass(self.namespace+'-inner');

				/* remove existing content */
				self.$instance.find('.'+self.namespace+'-inner').remove();
				self.$instance.find('.'+self.namespace+'-content').append(self.$content);

				return self;
			},

			/* opens the lightbox. "this" contains $instance with the lightbox, and with the config */
			open: function(event){
				var self = this;
				if(event && !event.isDefaultPrevented()
					|| self.beforeOpen(event) !== false) {

					if(event){
						event.preventDefault();
					}
					var $content = self.getContent();

					if($content){
						/* Add to opened registry */
						self.constructor._opened.add(self._openedCallback = function(response){
							if(self.$instance.closest('body').length > 0) {
								response.currentFeatherlight = self;
							}
						});

						/* Set content and show */
						$.when($content).done(function($content){
							self.setContent($content)
								.$instance.appendTo(self.root).fadeIn(self.openSpeed);
							self.afterOpen(event);
						});
						return self;
					}
				}
				return false;
			},

			/* closes the lightbox. "this" contains $instance with the lightbox, and with the config */
			close: function(event){
				var self = this;
				if(self.beforeClose(event) === false) {
					return false;
				}
				self.constructor._opened.remove(self._openedCallback);
				self.$instance.fadeOut(self.closeSpeed,function(){
					self.$instance.detach();
					self.afterClose(event);
				});
			}
		},
		/* Contains the logic to determine content */
		contentFilters: {
			jquery: {
				regex: /^[#.]\w/,         /* Anything that starts with a class name or identifiers */
				test: function(elem)    { return elem instanceof $ && elem; },
				process: function(elem) { return $(elem).clone(true); }
			},
			image: {
				regex: /\.(png|jpg|jpeg|gif|tiff|bmp)(\?\S*)?$/i,
				process: function(url)  {
					var self = this,
						deferred = $.Deferred(),
						img = new Image();
					img.onload  = function() { deferred.resolve(
						$('')
					); };
					img.onerror = function() { deferred.reject(); };
					img.src = url;
					return deferred.promise();
				}
			},
			html: {
				regex: /^\s*<[\w!][^<]*>/, /* Anything that starts with some kind of valid tag */
				process: function(html) { return $(html); }
			},
			ajax: {
				regex: /./,            /* At this point, any content is assumed to be an URL */
				process: function(url)  {
					var self = this,
						deferred = $.Deferred();
					/* we are using load so one can specify a target with: url.html #targetelement */
					var $container = $('

').load(url, function(response, status){
						if ( status !== "error" ) {
							deferred.resolve($container.contents());
						}
						deferred.fail();
					});
					return deferred.promise();
				}
			},
			text: {
				process: function(text) { return $('
', {text: text}); }
			}
		},

		attach: function($source, $content, config) {
			if (typeof $content === 'object' && $content instanceof $ === false && !config) {
				config = $content;
				$content = undefined;
			}
			/* make a copy */
			config = $.extend({}, config);

			/* Only for openTrigger and namespace... */
			var tempConfig = $.extend({}, Fl.defaults, readElementConfigHelper($source[0]), config);

			$source.on(tempConfig.openTrigger+'.'+tempConfig.namespace, tempConfig.filter, function(event) {
				/* ... since we might as well compute the config on the actual target */
				var elemConfig = $.extend({source: this}, readElementConfigHelper(this), config);
				new $.featherlight($content, elemConfig).open(event);
			});
		},

		current: function() {
			var response = {};
			this._opened.fire(response);
			return response.currentFeatherlight;
		},

		close: function() {
			var cur = Fl.current();
			if(cur) { cur.close(); }
		},

		_opened: $.Callbacks()
	});

	Fl.prototype = $.extend({constructor: Fl}, Fl.methods);

	/* bind jQuery elements to trigger featherlight */
	$.fn.featherlight = function($content, config) {
		Fl.attach(this, $content, config);
		return this;
	};

	/* bind featherlight on ready if config autoBind is set */
	$(document).ready(function(){
		if(Fl.autoBind){
			$(document).featherlight({filter: Fl.autoBind});
		}
	});
}(jQuery));
<|endoftext|>


<commit_before>"use strict";

angular.module("nusPartimeApp").controller("companyProfileController",
	["$scope", "$location", "RegistrationService", "AuthService", "Session", "CompanyService", "UserService",
	function($scope, $location, RegistrationService, AuthService, Session, CompanyService, UserService) {
		AuthService.autoLogin().then(function(){
            CompanyService.getAllCompanies(Session.userId).then(function(res){
                $scope.companies = res;
				$(".personalInfo-button").addClass("active");

				UserService.getUserProfile(Session.userId).then(function(res){
					$scope.user = res;
				});
            });

        });

        $scope.editCompanyProfile = function(company){
            CompanyService.setCompany(company);
            $location.path("/companyProfileEdit");
        }

		$scope.showPersonalInfo = function() {
			$(".companyInfo").addClass("hidden");
			$(".companyInfo-button").removeClass("active");
			$(".personalInfo").removeClass("hidden");
			$(".personalInfo-button").addClass("active");
		}

		$scope.showCompanyInfo = function() {
			$(".companyInfo").removeClass("hidden");
			$(".companyInfo-button").addClass("active");
			$(".personalInfo").addClass("hidden");
			$(".personalInfo-button").removeClass("active");
		}
	}]);
<commit_msg>add user info to company profile page<commit_after>"use strict";

angular.module("nusPartimeApp").controller("companyProfileController",
	["$scope", "$location", "RegistrationService", "AuthService", "Session", "CompanyService", "UserService",
	function($scope, $location, RegistrationService, AuthService, Session, CompanyService, UserService) {
		AuthService.autoLogin().then(function(){
            CompanyService.getAllCompanies(Session.userId).then(function(res){
                $scope.companies = res;
				$(".personalInfo-button").addClass("active");

            });

			UserService.getUserProfile(Session.userId).then(function(res){
				$scope.user = res;
			});

        });

        $scope.editCompanyProfile = function(company){
            CompanyService.setCompany(company);
            $location.path("/companyProfileEdit");
        }

		$scope.showPersonalInfo = function() {
			$(".companyInfo").addClass("hidden");
			$(".companyInfo-button").removeClass("active");
			$(".personalInfo").removeClass("hidden");
			$(".personalInfo-button").addClass("active");
		}

		$scope.showCompanyInfo = function() {
			$(".companyInfo").removeClass("hidden");
			$(".companyInfo-button").addClass("active");
			$(".personalInfo").addClass("hidden");
			$(".personalInfo-button").removeClass("active");
		}
	}]);
<|endoftext|>