<commit_before>// This file contains a package.json for the dependencies of the command-line
// tool.

// We put this in a JS file so that it can contain comments. It is processed
// into a package.json file by generate-dev-bundle.sh.

var packageJson = {
  name: "meteor-dev-bundle-tool",
  // Version is not important but is needed to prevent warnings.
  version: "0.0.0",
  dependencies: {
    // Explicit dependency because we are replacing it with a bundled version
    // and we want to make sure there are no dependencies on a higher version
    npm: "3.9.6",
    "node-gyp": "3.3.1",
    "node-pre-gyp": "0.6.26",
    "meteor-babel": "0.11.6",
    "meteor-promise": "0.7.2",
    fibers: "1.0.13",
    promise: "7.1.1",
    // So that Babel 6 can emit require("babel-runtime/helpers/...") calls.
    "babel-runtime": "6.9.2",
    // For various ES2015 polyfills, such as Map and Set.
    "meteor-ecmascript-runtime": "0.2.6",
    // Not yet upgrading Underscore from 1.5.2 to 1.7.0 (which should be done
    // in the package too) because we should consider using lodash instead
    // (and there are backwards-incompatible changes either way).
    underscore: "1.5.2",
    "source-map-support": "https://github.com/meteor/node-source-map-support/tarball/1912478769d76e5df4c365e147f25896aee6375e",
    semver: "4.1.0",
    request: "2.47.0",
    fstream: "https://github.com/meteor/fstream/tarball/d11b9ec4a13918447c8af7559c243c190744dd1c",
    tar: "1.0.2",
    kexec: "2.0.2",
    "source-map": "0.5.3",
    "browserstack-webdriver": "2.41.1",
    "node-inspector": "0.7.4",
    chalk: "0.5.1",
    sqlite3: "3.1.3",
    netroute: "1.0.2",
    "http-proxy": "1.11.1",
    "wordwrap": "0.0.2",
    "moment": "2.8.4",
    "rimraf": "2.4.3",
    // XXX: When we update this, see if it fixes this Github issue:
    // https://github.com/jgm/CommonMark/issues/276 . If it does, remove the
    // workaround from the tool.
    "commonmark": "0.15.0",
    escope: "3.2.0",
    // 2.4.0 (more or less, the package.json change isn't committed) plus our PR
    // https://github.com/williamwicks/node-eachline/pull/4
    eachline: "https://github.com/meteor/node-eachline/tarball/ff89722ff94e6b6a08652bf5f44c8fffea8a21da",
    pathwatcher: "6.7.0",
    runas: "3.1.1",
    'lru-cache': '2.6.4',
    'cordova-lib': "6.0.0",
    longjohn: '0.2.11'
  }
};

if (process.platform === 'win32') {
  // Remove dependencies that do not work on Windows
  delete packageJson.dependencies.netroute;
  delete packageJson.dependencies.kexec;
}

process.stdout.write(JSON.stringify(packageJson, null, 2) + '\n');
<commit_msg>Upgrade fstream dev bundle dependency to version 1.0.8.<commit_after>// This file contains a package.json for the dependencies of the command-line
// tool.

// We put this in a JS file so that it can contain comments. It is processed
// into a package.json file by generate-dev-bundle.sh.

var packageJson = {
  name: "meteor-dev-bundle-tool",
  // Version is not important but is needed to prevent warnings.
  version: "0.0.0",
  dependencies: {
    // Explicit dependency because we are replacing it with a bundled version
    // and we want to make sure there are no dependencies on a higher version
    npm: "3.9.6",
    "node-gyp": "3.3.1",
    "node-pre-gyp": "0.6.26",
    "meteor-babel": "0.11.6",
    "meteor-promise": "0.7.2",
    fibers: "1.0.13",
    promise: "7.1.1",
    // So that Babel 6 can emit require("babel-runtime/helpers/...") calls.
    "babel-runtime": "6.9.2",
    // For various ES2015 polyfills, such as Map and Set.
    "meteor-ecmascript-runtime": "0.2.6",
    // Not yet upgrading Underscore from 1.5.2 to 1.7.0 (which should be done
    // in the package too) because we should consider using lodash instead
    // (and there are backwards-incompatible changes either way).
    underscore: "1.5.2",
    "source-map-support": "https://github.com/meteor/node-source-map-support/tarball/1912478769d76e5df4c365e147f25896aee6375e",
    semver: "4.1.0",
    request: "2.47.0",
    fstream: "https://github.com/meteor/fstream/tarball/cf4ea6c175355cec7bee38311e170d08c4078a5d",
    tar: "1.0.2",
    kexec: "2.0.2",
    "source-map": "0.5.3",
    "browserstack-webdriver": "2.41.1",
    "node-inspector": "0.7.4",
    chalk: "0.5.1",
    sqlite3: "3.1.3",
    netroute: "1.0.2",
    "http-proxy": "1.11.1",
    "wordwrap": "0.0.2",
    "moment": "2.8.4",
    "rimraf": "2.4.3",
    // XXX: When we update this, see if it fixes this Github issue:
    // https://github.com/jgm/CommonMark/issues/276 . If it does, remove the
    // workaround from the tool.
    "commonmark": "0.15.0",
    escope: "3.2.0",
    // 2.4.0 (more or less, the package.json change isn't committed) plus our PR
    // https://github.com/williamwicks/node-eachline/pull/4
    eachline: "https://github.com/meteor/node-eachline/tarball/ff89722ff94e6b6a08652bf5f44c8fffea8a21da",
    pathwatcher: "6.7.0",
    runas: "3.1.1",
    'lru-cache': '2.6.4',
    'cordova-lib': "6.0.0",
    longjohn: '0.2.11'
  }
};

if (process.platform === 'win32') {
  // Remove dependencies that do not work on Windows
  delete packageJson.dependencies.netroute;
  delete packageJson.dependencies.kexec;
}

process.stdout.write(JSON.stringify(packageJson, null, 2) + '\n');
<|endoftext|>


<commit_before>function OverlayEffect() {
  // Do note that everything in this function (semantically called a
  // constructor) is called only once; it is when `new OverflayEffect()` is
// evaluated, and only then.

  this.canvas = new MEDIA.Canvas();
  this.name = 'Overlay';
  this.controls = {}

  // Since there isn't any way to get pixel data from an `Image` object (which
  // we will see, below), we have no choice but to draw images to a canvas
  // object, and then extract the pixel data from there. This will serve as our
  // canvas to draw images on.
  this.otherCanvas = new MEDIA.Canvas();

  // This is to keep tabs of the scope of the current constructor, in case we
  // need to refer to it, later.
  //
  // When we are inside of a dynamically-generated function, it typically isn't
  // bound to the parent function (or constructor), and so the `this` keyword
  // will not refer to the parent funtion. Hence, we are creating a `self`
  // variable to keep tabs of the parent function.
  var self = this;

  // We initialize a new instance of an Image object, and "tell" it to load
  // Chris Hansen's image. We do so implicitly, by setting its `src` property
  // to the location of Chris Hansen's image. We will also attach an event
  // listener, so that we know when the image has loaded, and that we are then
  // able to draw the image onto our canvas.
  this.img = new Image();
  this.img.onload = function () {
    // We are now inside a function, which is bound to our `Image` instance,
    // and hence the `this` keyword will refere to the `Image` instance, and not
    // to the `OverflayEffect` instance.
    //
    // Do note that the code being run here is entirely asynchronous, and so the
    // code in the parent function will *always* run first, and *then* the code
    // inside of this function.

    // We'll just draw the image to our canvas, once.
    //
    // However, if we want to implement time-based post-processing, it would be
    // ideal to draw the image to our other canvas *at every frame*. In other
    // words, you would call `this.otherCanvas.context.drawImage` in the `draw`
    // method, below.
    self.otherCanvas.context.drawImage(
      self.img, 0, 0, MEDIA.width, MEDIA.height
    );
  }
  this.img.src = 'chris_hansen.jpg';
}

OverlayEffect.prototype = {
  draw: function () {
    var canvas = this.canvas;

    APP.drawImage(canvas);

    var backgroundImage = canvas.getImageData();
    var foregroundImage = this.otherCanvas.getImageData();

    var backgroundPixels = new Uint32Array(backgroundImage.data.buffer);
    var foregroundPixels = new Uint32Array(foregroundImage.data.buffer);

    var len = backgroundPixels.length;

    for (var i = 0; i < len; i++) {
      var foregroundPixel = foregroundPixels[i];

      // Get the brightness of our pixel.
      var luma =
        (
          ((foregroundPixel)       & 255) +
          ((foregroundPixel >> 8 ) & 255) +
          ((foregroundPixel >> 16) & 255)
        ) / 3;

      // If the foreground pixel is dark enough, then this means we can replace
      // the background pixel with the foreground pixel.
      if (luma < 220) {
        backgroundPixels[i] = foregroundPixel;
      }
    }

    // Let's not forget to draw the resulting image to our main canvas.
    canvas.putImageData(backgroundImage);
  }
};

var size = {
  small:{w:160, h:120},
  medium:{w:320, h:240},
  large:{w:640, h:480}
}
//setup app
APP.setup(size.large);
//add effects
APP.effects = [];
APP.effects.push(new OverlayEffect());
//setup controls
APP.setupControls();<commit_msg>Fixed an indentation<commit_after>function OverlayEffect() {
  // Do note that everything in this function (semantically called a
  // constructor) is called only once; it is when `new OverflayEffect()` is
  // evaluated, and only then.

  this.canvas = new MEDIA.Canvas();
  this.name = 'Overlay';
  this.controls = {}

  // Since there isn't any way to get pixel data from an `Image` object (which
  // we will see, below), we have no choice but to draw images to a canvas
  // object, and then extract the pixel data from there. This will serve as our
  // canvas to draw images on.
  this.otherCanvas = new MEDIA.Canvas();

  // This is to keep tabs of the scope of the current constructor, in case we
  // need to refer to it, later.
  //
  // When we are inside of a dynamically-generated function, it typically isn't
  // bound to the parent function (or constructor), and so the `this` keyword
  // will not refer to the parent funtion. Hence, we are creating a `self`
  // variable to keep tabs of the parent function.
  var self = this;

  // We initialize a new instance of an Image object, and "tell" it to load
  // Chris Hansen's image. We do so implicitly, by setting its `src` property
  // to the location of Chris Hansen's image. We will also attach an event
  // listener, so that we know when the image has loaded, and that we are then
  // able to draw the image onto our canvas.
  this.img = new Image();
  this.img.onload = function () {
    // We are now inside a function, which is bound to our `Image` instance,
    // and hence the `this` keyword will refere to the `Image` instance, and not
    // to the `OverflayEffect` instance.
    //
    // Do note that the code being run here is entirely asynchronous, and so the
    // code in the parent function will *always* run first, and *then* the code
    // inside of this function.

    // We'll just draw the image to our canvas, once.
    //
    // However, if we want to implement time-based post-processing, it would be
    // ideal to draw the image to our other canvas *at every frame*. In other
    // words, you would call `this.otherCanvas.context.drawImage` in the `draw`
    // method, below.
    self.otherCanvas.context.drawImage(
      self.img, 0, 0, MEDIA.width, MEDIA.height
    );
  }
  this.img.src = 'chris_hansen.jpg';
}

OverlayEffect.prototype = {
  draw: function () {
    var canvas = this.canvas;

    APP.drawImage(canvas);

    var backgroundImage = canvas.getImageData();
    var foregroundImage = this.otherCanvas.getImageData();

    var backgroundPixels = new Uint32Array(backgroundImage.data.buffer);
    var foregroundPixels = new Uint32Array(foregroundImage.data.buffer);

    var len = backgroundPixels.length;

    for (var i = 0; i < len; i++) {
      var foregroundPixel = foregroundPixels[i];

      // Get the brightness of our pixel.
      var luma =
        (
          ((foregroundPixel)       & 255) +
          ((foregroundPixel >> 8 ) & 255) +
          ((foregroundPixel >> 16) & 255)
        ) / 3;

      // If the foreground pixel is dark enough, then this means we can replace
      // the background pixel with the foreground pixel.
      if (luma < 220) {
        backgroundPixels[i] = foregroundPixel;
      }
    }

    // Let's not forget to draw the resulting image to our main canvas.
    canvas.putImageData(backgroundImage);
  }
};

var size = {
  small:{w:160, h:120},
  medium:{w:320, h:240},
  large:{w:640, h:480}
}
//setup app
APP.setup(size.large);
//add effects
APP.effects = [];
APP.effects.push(new OverlayEffect());
//setup controls
APP.setupControls();<|endoftext|>


<commit_before>import Vector3 from '../../math/Vector3';
import Vector4 from '../../math/Vector4';
import GLBoostObject from '../../core/GLBoostObject';
import Matrix33 from '../../math/Matrix33';
import M_AbstractCamera from  '../../../middle_level/elements/cameras/M_AbstractCamera';
import MathUtil from '../../math/MathUtil';

export default class L_CameraController extends GLBoostObject {
  constructor(glBoostContext, isSymmetryMode = true, doResetWhenCameraSettingChanged = false, isForceGrab = false, efficiency = 1.0) {
    super(glBoostContext);

    this._camaras = new Set();

    this._isKeyUp = true;
    this._isForceGrab = isForceGrab;
    this._isSymmetryMode = isSymmetryMode;

    this._efficiency = 0.5 * efficiency;

    this._rot_bgn_x = 0;
    this._rot_bgn_y = 0;
    this._rot_x = 0;
    this._rot_y = 0;
    this._clickedMouseYOnCanvas = 0;
    this._clickedMouseXOnCanvas = 0;

    this._verticalAngleOfVectors = 0;

    this._verticalAngleThrethold = 90;

    this._wheel_y = 1;
    this._mouse_translate_y = 0;
    this._mouse_translate_x = 0;

    this._mouseTranslateVec = new Vector3(0, 0, 0);

    this._newUpVec = new Vector3(0, 0, 0);

    this._target = null;

    this._lengthCenterToCorner = 10;
    this._lengthOfCenterToEye = 10;
    this._scaleOfTraslation = 5.0;
    this._scaleOfLengthCameraToCenter = 0.5;
    this._foyvBias = 1.0;
    this._zFarAdjustingFactorBasedOnAABB = 1.0;

    this._doResetWhenCameraSettingChanged = doResetWhenCameraSettingChanged;

    this._shiftCameraTo = null;

    this._onMouseDown = (evt) => {
      let rect = evt.target.getBoundingClientRect();
      this._clickedMouseXOnCanvas = evt.clientX - rect.left;
      this._clickedMouseYOnCanvas = evt.clientY - rect.top;
      this._movedMouseYOnCanvas = -1;
      this._movedMouseXOnCanvas = -1;
      this._rot_bgn_x = this._rot_x;
      this._rot_bgn_y = this._rot_y;

      this._isKeyUp = false;

      if (typeof evt.buttons !== 'undefined') {
        this._camaras.forEach(function (camera) {
          camera._needUpdateView(false);
          camera._needUpdateProjection();
        });
      }
      return false;
    };

    this._onMouseUp = (evt) => {
      this._isKeyUp = true;
      this._movedMouseYOnCanvas = -1;
      this._movedMouseXOnCanvas = -1;
    };

    this._onMouseMove = (evt) => {
      if (this._isKeyUp) {
        return;
      }

      let rect = evt.target.getBoundingClientRect();
      this._movedMouseXOnCanvas = evt.clientX - rect.left;
      this._movedMouseYOnCanvas = evt.clientY - rect.top;

      if (typeof evt.buttons !== 'undefined') {
        let data = evt.buttons;
        let button_l = ((data & 0x0001) ? true : false);
        let button_c = ((data & 0x0004) ? true : false);
        if (button_c) {
          this._mouse_translate_y = (this._movedMouseYOnCanvas - this._clickedMouseYOnCanvas) / 1000 * this._efficiency;
          this._mouse_translate_x = (this._movedMouseXOnCanvas - this._clickedMouseXOnCanvas) / 1000 * this._efficiency;

          let scale = this._lengthOfCenterToEye * this._foyvBias * this._scaleOfTraslation;
          if (evt.shiftKey) {
            this._mouseTranslateVec = Vector3.add(this._mouseTranslateVec, Vector3.normalize(this._newEyeToCenterVec).multiply(-this._mouse_translate_y).multiply(scale));
          } else {
            this._mouseTranslateVec = Vector3.add(this._mouseTranslateVec, Vector3.normalize(this._newUpVec).multiply(this._mouse_translate_y).multiply(scale));
          }
          this._mouseTranslateVec = Vector3.add(this._mouseTranslateVec, Vector3.normalize(this._newTangentVec).multiply(this._mouse_translate_x).multiply(scale));

          this._clickedMouseYOnCanvas = this._movedMouseYOnCanvas;
          this._clickedMouseXOnCanvas = this._movedMouseXOnCanvas;
        }

        this._camaras.forEach(function (camera) {
          camera._needUpdateView(false);
          camera._needUpdateProjection();
        });

        if (!button_l) {
          return;
        }
      }

      // calc rotation angle
      let delta_y = (this._movedMouseYOnCanvas - this._clickedMouseYOnCanvas) * this._efficiency;
      let delta_x = (this._movedMouseXOnCanvas - this._clickedMouseXOnCanvas) * this._efficiency;
      this._rot_y = this._rot_bgn_y - delta_y;
      this._rot_x = this._rot_bgn_x - delta_x;

      // check if rotation angle is within range
      if (this._verticalAngleThrethold - this._verticalAngleOfVectors < this._rot_y) {
        this._rot_y = this._verticalAngleThrethold + this._verticalAngleOfVectors;
      }

      if (this._rot_y < -this._verticalAngleThrethold + this._verticalAngleOfVectors) {
        this._rot_y = -this._verticalAngleThrethold - this._verticalAngleOfVectors;
      }

      this._camaras.forEach(function (camera) {
        camera._needUpdateView(false);
        camera._needUpdateProjection();
      });

    };

    this._onMouseWheel = (evt) => {
      evt.preventDefault();
      this._wheel_y += evt.deltaY / 600;
      this._wheel_y = Math.min(this._wheel_y, 3);
      this._wheel_y = Math.max(this._wheel_y, 0.4);

      this._camaras.forEach(function (camera) {
        camera._needUpdateView(false);
        camera._needUpdateProjection();
      });
    };

    this._onContexMenu = (evt) => {
      if (evt.preventDefault) {
        evt.preventDefault();
      } else {
        event.returnValue = false;
      }
    };

    this._onMouseDblClick = (evt) => {
      if (evt.shiftKey) {
        this._mouseTranslateVec = new Vector3(0, 0, 0);
      } else {
        this._rot_y = 0;
        this._rot_x = 0;
        this._rot_bgn_y = 0;
        this._rot_bgn_x = 0;
      }
      this._camaras.forEach(function (camera) {
        camera._needUpdateView(false);
        camera._needUpdateProjection();
      });
    };

    if (this._glContext.canvas) {
      this._glContext.canvas.addEventListener('mousedown', this._onMouseDown);
      this._glContext.canvas.addEventListener('mouseup', this._onMouseUp);
      this._glContext.canvas.addEventListener('mousemove', this._onMouseMove);
      if (window.WheelEvent) {
        this._glContext.canvas.addEventListener("wheel", this._onMouseWheel);
      }
      this._glContext.canvas.addEventListener('contextmenu', this._onContexMenu, false);
      this._glContext.canvas.addEventListener("dblclick", this._onMouseDblClick);
    }
  }

  _getFovyFromCamera(camera) {
    if (camera.fovy) {
      return camera.fovy;
    } else {
      return MathUtil.radianToDegree(2 * Math.atan(Math.abs(camera.top - camera.bottom) / (2 * camera.zNear)));
    }
  }

  convert(camera) {
    let newEyeVec = null;
    let newCenterVec = null;
    let newUpVec = null;

    if (this._isKeyUp || !this._isForceGrab) {
      this._eyeVec = (this._shiftCameraTo !== null) ? Vector3.add(Vector3.subtract(this._shiftCameraTo, camera.center), camera.eye) : camera.eye;
      this._centerVec = (this._shiftCameraTo !== null) ? this._shiftCameraTo : camera.center;
      this._upVec = camera.up;
    }

    let fovy = this._getFovyFromCamera(camera);

    if (this._isSymmetryMode) {
      let centerToEyeVec = Vector3.subtract(this._eyeVec, this._centerVec).multiply(this._wheel_y * 1.0/Math.tan(MathUtil.degreeToRadian(fovy/2.0)));
      this._lengthOfCenterToEye = centerToEyeVec.length();
      let horizontalAngleOfVectors = Vector3.angleOfVectors(new Vector3(centerToEyeVec.x, 0, centerToEyeVec.z), new Vector3(0, 0, 1));
      let horizontalSign = Vector3.cross(new Vector3(centerToEyeVec.x, 0, centerToEyeVec.z), new Vector3(0, 0, 1)).y;
      if (horizontalSign >= 0) {
        horizontalSign = 1;
      } else {
        horizontalSign = -1;
      }
      horizontalAngleOfVectors *= horizontalSign;
      let rotateM_Reset = Matrix33.rotateY(horizontalAngleOfVectors);
      let rotateM_X = Matrix33.rotateX(this._rot_y);
      let rotateM_Y = Matrix33.rotateY(this._rot_x);
      let rotateM_Revert = Matrix33.rotateY(-horizontalAngleOfVectors);
      let rotateM = Matrix33.multiply(rotateM_Revert, Matrix33.multiply(rotateM_Y, Matrix33.multiply(rotateM_X, rotateM_Reset)));

      newUpVec = rotateM.multiplyVector(this._upVec);
      this._newUpVec = newUpVec;
      newEyeVec = rotateM.multiplyVector(centerToEyeVec).add(this._centerVec);
      newCenterVec = this._centerVec.clone();
      this._newEyeToCenterVec = Vector3.subtract(newCenterVec, newEyeVec);
      this._newTangentVec = Vector3.cross(this._newUpVec, this._newEyeToCenterVec);

      newEyeVec.add(this._mouseTranslateVec);
      newCenterVec.add(this._mouseTranslateVec);

      let horizonResetVec = rotateM_Reset.multiplyVector(centerToEyeVec);
      this._verticalAngleOfVectors = Vector3.angleOfVectors(horizonResetVec, new Vector3(0, 0, 1));
      let verticalSign = Vector3.cross(horizonResetVec, new Vector3(0, 0, 1)).x;
      if (verticalSign >= 0) {
        verticalSign = 1;
      } else {
        verticalSign = -1;
      }
      this._verticalAngleOfVectors *= verticalSign;

    } else {
      let centerToEyeVec = Vector3.subtract(this._eyeVec, this._centerVec).multiply(this._wheel_y * 1.0/Math.tan(MathUtil.degreeToRadian(fovy/2.0)));
      let rotateM_X = Matrix33.rotateX(this._rot_y);
      let rotateM_Y = Matrix33.rotateY(this._rot_x);
      let rotateM = rotateM_Y.multiply(rotateM_X);

      newUpVec = rotateM.multiplyVector(this._upVec);
      this._newUpVec = newUpVec;
      newEyeVec = rotateM.multiplyVector(centerToEyeVec).add(this._centerVec);
      newCenterVec = this._centerVec.clone();
      this._newEyeToCenterVec = Vector3.subtract(newCenterVec, newEyeVec);
      this._newTangentVec = Vector3.cross(this._newUpVec, this._newEyeToCenterVec);

      newEyeVec.add(this._mouseTranslateVec);
      newCenterVec.add(this._mouseTranslateVec);
    }

    let newZNear = camera.zNear;
    let newZFar = camera.zNear + Vector3.subtract(newCenterVec, newEyeVec).length();
    if (this._target) {
      newZFar += this._getTargetAABB().lengthCenterToCorner * this._zFarAdjustingFactorBasedOnAABB;
    }

    this._foyvBias = Math.tan(MathUtil.degreeToRadian(fovy/2.0));

    return [newEyeVec, newCenterVec, newUpVec, newZNear, newZFar];
  }

  _getTargetAABB() {
    let targetAABB = null;
    if (typeof this._target.updateAABB !== 'undefined') {
      targetAABB = this._target.updateAABB();
    } else {
      targetAABB = this._target.AABB;
    }
    return targetAABB;
  }

  _updateTargeting(camera, eyeVec, centerVec, upVec, fovy) {
    if (this._target === null) {
      return [eyeVec, centerVec, upVec];
    }

    let targetAABB = this._getTargetAABB();

    this._lengthCenterToCorner = targetAABB.lengthCenterToCorner;
    let lengthCameraToObject = targetAABB.lengthCenterToCorner / Math.sin((fovy*Math.PI/180)/2) * this._scaleOfLengthCameraToCenter;

    let newCenterVec = targetAABB.centerPoint;

    let centerToCameraVec = Vector3.subtract(eyeVec, centerVec);
    let centerToCameraVecNormalized = Vector3.normalize(centerToCameraVec);

    let newEyeVec = Vector3.multiply(centerToCameraVecNormalized, lengthCameraToObject).add(newCenterVec);

    let newUpVec = null;
    if (camera instanceof M_AbstractCamera) {
      let mat = camera.inverseTransformMatrixAccumulatedAncestryWithoutMySelf;
      newEyeVec = mat.multiplyVector(new Vector4(newEyeVec.x, newEyeVec.y, newEyeVec.z, 1)).toVector3();
      newCenterVec = mat.multiplyVector(new Vector4(newCenterVec.x, newCenterVec.y, newCenterVec.z, 1)).toVector3();
      newUpVec = mat.multiplyVector(new Vector4(upVec.x, upVec.y, upVec.z, 1)).toVector3();
    } else {
      newUpVec = upVec;
    }

    return [newEyeVec, newCenterVec, newUpVec];
  }

  tryReset() {
    if (this._doResetWhenCameraSettingChanged) {
      if (this._isKeyUp) {
        this._rot_y = 0;
        this._rot_x = 0;
        this._rot_bgn_y = 0;
        this._rot_bgn_x = 0;
      }
    }
  }

  reset() {
    this._rot_y = 0;
    this._rot_x = 0;
    this._rot_bgn_y = 0;
    this._rot_bgn_x = 0;
    this._wheel_y = 1;
    this._mouseTranslateVec = new Vector3(0, 0, 0);

    this._camaras.forEach(function (camera) {
      camera._needUpdateView(false);
    });
  }

  updateTargeting() {
    this._camaras.forEach((camera)=>{
      let vectors = this._updateTargeting(camera, camera.eye, camera.center, camera.up, this._getFovyFromCamera(camera));
      camera.eye = vectors[0];
      camera.center = vectors[1];
      camera.up = vectors[2];
    });
  }

  addCamera(camera) {
    this._camaras.add(camera);
  }

  set target(object) {
    this._target = object;
    this.updateTargeting();
  }

  set zFarAdjustingFactorBasedOnAABB(value) {
    this._zFarAdjustingFactorBasedOnAABB = value;
  }

  get zFarAdjustingFactorBasedOnAABB() {
    return this._zFarAdjustingFactorBasedOnAABB;
  }

  set shiftCameraTo(value) {
    this._shiftCameraTo = value;
  }

  get shiftCameraTo() {
    return this._shiftCameraTo;
  }
}
<commit_msg>Fix Mouse Manipulate<commit_after>import Vector3 from '../../math/Vector3';
import Vector4 from '../../math/Vector4';
import GLBoostObject from '../../core/GLBoostObject';
import Matrix33 from '../../math/Matrix33';
import M_AbstractCamera from  '../../../middle_level/elements/cameras/M_AbstractCamera';
import MathUtil from '../../math/MathUtil';

export default class L_CameraController extends GLBoostObject {
  constructor(glBoostContext, isSymmetryMode = true, doResetWhenCameraSettingChanged = false, isForceGrab = false, efficiency = 1.0) {
    super(glBoostContext);

    this._camaras = new Set();

    this._isKeyUp = true;
    this._isForceGrab = isForceGrab;
    this._isSymmetryMode = isSymmetryMode;

    this._efficiency = 0.5 * efficiency;

    this._rot_bgn_x = 0;
    this._rot_bgn_y = 0;
    this._rot_x = 0;
    this._rot_y = 0;
    this._clickedMouseYOnCanvas = 0;
    this._clickedMouseXOnCanvas = 0;

    this._verticalAngleOfVectors = 0;

    this._verticalAngleThrethold = 90;

    this._wheel_y = 1;
    this._mouse_translate_y = 0;
    this._mouse_translate_x = 0;

    this._mouseTranslateVec = new Vector3(0, 0, 0);

    this._newUpVec = new Vector3(0, 0, 0);

    this._target = null;

    this._lengthCenterToCorner = 10;
    this._lengthOfCenterToEye = 10;
    this._scaleOfTraslation = 5.0;
    this._scaleOfLengthCameraToCenter = 0.5;
    this._foyvBias = 1.0;
    this._zFarAdjustingFactorBasedOnAABB = 1.0;

    this._doResetWhenCameraSettingChanged = doResetWhenCameraSettingChanged;

    this._shiftCameraTo = null;

    this._onMouseDown = (evt) => {
      let rect = evt.target.getBoundingClientRect();
      this._clickedMouseXOnCanvas = evt.clientX - rect.left;
      this._clickedMouseYOnCanvas = evt.clientY - rect.top;
      this._movedMouseYOnCanvas = -1;
      this._movedMouseXOnCanvas = -1;
      this._rot_bgn_x = this._rot_x;
      this._rot_bgn_y = this._rot_y;

      this._isKeyUp = false;

      if (typeof evt.buttons !== 'undefined') {
        this._camaras.forEach(function (camera) {
          camera._needUpdateView(false);
          camera._needUpdateProjection();
        });
      }
      return false;
    };

    this._onMouseUp = (evt) => {
      this._isKeyUp = true;
      this._movedMouseYOnCanvas = -1;
      this._movedMouseXOnCanvas = -1;
    };

    this._onMouseMove = (evt) => {
      if (this._isKeyUp) {
        return;
      }

      let rect = evt.target.getBoundingClientRect();
      this._movedMouseXOnCanvas = evt.clientX - rect.left;
      this._movedMouseYOnCanvas = evt.clientY - rect.top;

      if (typeof evt.buttons !== 'undefined') {
        let data = evt.buttons;
        let button_l = ((data & 0x0001) ? true : false);
        let button_c = ((data & 0x0004) ? true : false);
        if (button_c) {
          this._mouse_translate_y = (this._movedMouseYOnCanvas - this._clickedMouseYOnCanvas) / 1000 * this._efficiency;
          this._mouse_translate_x = (this._movedMouseXOnCanvas - this._clickedMouseXOnCanvas) / 1000 * this._efficiency;

          let scale = this._lengthOfCenterToEye * this._foyvBias * this._scaleOfTraslation;
          if (evt.shiftKey) {
            this._mouseTranslateVec = Vector3.add(this._mouseTranslateVec, Vector3.normalize(this._newEyeToCenterVec).multiply(-this._mouse_translate_y).multiply(scale));
          } else {
            this._mouseTranslateVec = Vector3.add(this._mouseTranslateVec, Vector3.normalize(this._newUpVec).multiply(this._mouse_translate_y).multiply(scale));
          }
          this._mouseTranslateVec = Vector3.add(this._mouseTranslateVec, Vector3.normalize(this._newTangentVec).multiply(this._mouse_translate_x).multiply(scale));

          this._clickedMouseYOnCanvas = this._movedMouseYOnCanvas;
          this._clickedMouseXOnCanvas = this._movedMouseXOnCanvas;
        }

        this._camaras.forEach(function (camera) {
          camera._needUpdateView(false);
          camera._needUpdateProjection();
        });

        if (!button_l) {
          return;
        }
      }

      // calc rotation angle
      let delta_y = (this._movedMouseYOnCanvas - this._clickedMouseYOnCanvas) * this._efficiency;
      let delta_x = (this._movedMouseXOnCanvas - this._clickedMouseXOnCanvas) * this._efficiency;
      this._rot_y = this._rot_bgn_y - delta_y;
      this._rot_x = this._rot_bgn_x - delta_x;

      // check if rotation angle is within range
      if (this._verticalAngleThrethold - this._verticalAngleOfVectors < this._rot_y) {
        this._rot_y = this._verticalAngleThrethold + this._verticalAngleOfVectors;
      }

      if (this._rot_y < -this._verticalAngleThrethold + this._verticalAngleOfVectors) {
        this._rot_y = -this._verticalAngleThrethold - this._verticalAngleOfVectors;
      }

      this._camaras.forEach(function (camera) {
        camera._needUpdateView(false);
        camera._needUpdateProjection();
      });

    };

    this._onMouseWheel = (evt) => {
      evt.preventDefault();
      this._wheel_y += evt.deltaY / 600;
      this._wheel_y = Math.min(this._wheel_y, 3);
      this._wheel_y = Math.max(this._wheel_y, 0.4);

      this._camaras.forEach(function (camera) {
        camera._needUpdateView(false);
        camera._needUpdateProjection();
      });
    };

    this._onContexMenu = (evt) => {
      if (evt.preventDefault) {
        evt.preventDefault();
      } else {
        event.returnValue = false;
      }
    };

    this._onMouseDblClick = (evt) => {
      if (evt.shiftKey) {
        this._mouseTranslateVec = new Vector3(0, 0, 0);
      } else {
        this._rot_y = 0;
        this._rot_x = 0;
        this._rot_bgn_y = 0;
        this._rot_bgn_x = 0;
      }
      this._camaras.forEach(function (camera) {
        camera._needUpdateView(false);
        camera._needUpdateProjection();
      });
    };

    if (document) {
      document.addEventListener('mousedown', this._onMouseDown);
      document.addEventListener('mouseup', this._onMouseUp);
      document.addEventListener('mousemove', this._onMouseMove);
      if (window.WheelEvent) {
        document.addEventListener("wheel", this._onMouseWheel);
      }
      document.addEventListener('contextmenu', this._onContexMenu, false);
      document.addEventListener("dblclick", this._onMouseDblClick);
    }
  }

  _getFovyFromCamera(camera) {
    if (camera.fovy) {
      return camera.fovy;
    } else {
      return MathUtil.radianToDegree(2 * Math.atan(Math.abs(camera.top - camera.bottom) / (2 * camera.zNear)));
    }
  }

  convert(camera) {
    let newEyeVec = null;
    let newCenterVec = null;
    let newUpVec = null;

    if (this._isKeyUp || !this._isForceGrab) {
      this._eyeVec = (this._shiftCameraTo !== null) ? Vector3.add(Vector3.subtract(this._shiftCameraTo, camera.center), camera.eye) : camera.eye;
      this._centerVec = (this._shiftCameraTo !== null) ? this._shiftCameraTo : camera.center;
      this._upVec = camera.up;
    }

    let fovy = this._getFovyFromCamera(camera);

    if (this._isSymmetryMode) {
      let centerToEyeVec = Vector3.subtract(this._eyeVec, this._centerVec).multiply(this._wheel_y * 1.0/Math.tan(MathUtil.degreeToRadian(fovy/2.0)));
      this._lengthOfCenterToEye = centerToEyeVec.length();
      let horizontalAngleOfVectors = Vector3.angleOfVectors(new Vector3(centerToEyeVec.x, 0, centerToEyeVec.z), new Vector3(0, 0, 1));
      let horizontalSign = Vector3.cross(new Vector3(centerToEyeVec.x, 0, centerToEyeVec.z), new Vector3(0, 0, 1)).y;
      if (horizontalSign >= 0) {
        horizontalSign = 1;
      } else {
        horizontalSign = -1;
      }
      horizontalAngleOfVectors *= horizontalSign;
      let rotateM_Reset = Matrix33.rotateY(horizontalAngleOfVectors);
      let rotateM_X = Matrix33.rotateX(this._rot_y);
      let rotateM_Y = Matrix33.rotateY(this._rot_x);
      let rotateM_Revert = Matrix33.rotateY(-horizontalAngleOfVectors);
      let rotateM = Matrix33.multiply(rotateM_Revert, Matrix33.multiply(rotateM_Y, Matrix33.multiply(rotateM_X, rotateM_Reset)));

      newUpVec = rotateM.multiplyVector(this._upVec);
      this._newUpVec = newUpVec;
      newEyeVec = rotateM.multiplyVector(centerToEyeVec).add(this._centerVec);
      newCenterVec = this._centerVec.clone();
      this._newEyeToCenterVec = Vector3.subtract(newCenterVec, newEyeVec);
      this._newTangentVec = Vector3.cross(this._newUpVec, this._newEyeToCenterVec);

      newEyeVec.add(this._mouseTranslateVec);
      newCenterVec.add(this._mouseTranslateVec);

      let horizonResetVec = rotateM_Reset.multiplyVector(centerToEyeVec);
      this._verticalAngleOfVectors = Vector3.angleOfVectors(horizonResetVec, new Vector3(0, 0, 1));
      let verticalSign = Vector3.cross(horizonResetVec, new Vector3(0, 0, 1)).x;
      if (verticalSign >= 0) {
        verticalSign = 1;
      } else {
        verticalSign = -1;
      }
      this._verticalAngleOfVectors *= verticalSign;

    } else {
      let centerToEyeVec = Vector3.subtract(this._eyeVec, this._centerVec).multiply(this._wheel_y * 1.0/Math.tan(MathUtil.degreeToRadian(fovy/2.0)));
      let rotateM_X = Matrix33.rotateX(this._rot_y);
      let rotateM_Y = Matrix33.rotateY(this._rot_x);
      let rotateM = rotateM_Y.multiply(rotateM_X);

      newUpVec = rotateM.multiplyVector(this._upVec);
      this._newUpVec = newUpVec;
      newEyeVec = rotateM.multiplyVector(centerToEyeVec).add(this._centerVec);
      newCenterVec = this._centerVec.clone();
      this._newEyeToCenterVec = Vector3.subtract(newCenterVec, newEyeVec);
      this._newTangentVec = Vector3.cross(this._newUpVec, this._newEyeToCenterVec);

      newEyeVec.add(this._mouseTranslateVec);
      newCenterVec.add(this._mouseTranslateVec);
    }

    let newZNear = camera.zNear;
    let newZFar = camera.zNear + Vector3.subtract(newCenterVec, newEyeVec).length();
    if (this._target) {
      newZFar += this._getTargetAABB().lengthCenterToCorner * this._zFarAdjustingFactorBasedOnAABB;
    }

    this._foyvBias = Math.tan(MathUtil.degreeToRadian(fovy/2.0));

    return [newEyeVec, newCenterVec, newUpVec, newZNear, newZFar];
  }

  _getTargetAABB() {
    let targetAABB = null;
    if (typeof this._target.updateAABB !== 'undefined') {
      targetAABB = this._target.updateAABB();
    } else {
      targetAABB = this._target.AABB;
    }
    return targetAABB;
  }

  _updateTargeting(camera, eyeVec, centerVec, upVec, fovy) {
    if (this._target === null) {
      return [eyeVec, centerVec, upVec];
    }

    let targetAABB = this._getTargetAABB();

    this._lengthCenterToCorner = targetAABB.lengthCenterToCorner;
    let lengthCameraToObject = targetAABB.lengthCenterToCorner / Math.sin((fovy*Math.PI/180)/2) * this._scaleOfLengthCameraToCenter;

    let newCenterVec = targetAABB.centerPoint;

    let centerToCameraVec = Vector3.subtract(eyeVec, centerVec);
    let centerToCameraVecNormalized = Vector3.normalize(centerToCameraVec);

    let newEyeVec = Vector3.multiply(centerToCameraVecNormalized, lengthCameraToObject).add(newCenterVec);

    let newUpVec = null;
    if (camera instanceof M_AbstractCamera) {
      let mat = camera.inverseTransformMatrixAccumulatedAncestryWithoutMySelf;
      newEyeVec = mat.multiplyVector(new Vector4(newEyeVec.x, newEyeVec.y, newEyeVec.z, 1)).toVector3();
      newCenterVec = mat.multiplyVector(new Vector4(newCenterVec.x, newCenterVec.y, newCenterVec.z, 1)).toVector3();
      newUpVec = mat.multiplyVector(new Vector4(upVec.x, upVec.y, upVec.z, 1)).toVector3();
    } else {
      newUpVec = upVec;
    }

    return [newEyeVec, newCenterVec, newUpVec];
  }

  tryReset() {
    if (this._doResetWhenCameraSettingChanged) {
      if (this._isKeyUp) {
        this._rot_y = 0;
        this._rot_x = 0;
        this._rot_bgn_y = 0;
        this._rot_bgn_x = 0;
      }
    }
  }

  reset() {
    this._rot_y = 0;
    this._rot_x = 0;
    this._rot_bgn_y = 0;
    this._rot_bgn_x = 0;
    this._wheel_y = 1;
    this._mouseTranslateVec = new Vector3(0, 0, 0);

    this._camaras.forEach(function (camera) {
      camera._needUpdateView(false);
    });
  }

  updateTargeting() {
    this._camaras.forEach((camera)=>{
      let vectors = this._updateTargeting(camera, camera.eye, camera.center, camera.up, this._getFovyFromCamera(camera));
      camera.eye = vectors[0];
      camera.center = vectors[1];
      camera.up = vectors[2];
    });
  }

  addCamera(camera) {
    this._camaras.add(camera);
  }

  set target(object) {
    this._target = object;
    this.updateTargeting();
  }

  set zFarAdjustingFactorBasedOnAABB(value) {
    this._zFarAdjustingFactorBasedOnAABB = value;
  }

  get zFarAdjustingFactorBasedOnAABB() {
    return this._zFarAdjustingFactorBasedOnAABB;
  }

  set shiftCameraTo(value) {
    this._shiftCameraTo = value;
  }

  get shiftCameraTo() {
    return this._shiftCameraTo;
  }
}
<|endoftext|>


<commit_before>'use strict';

(function(module) {

  var googleMapping = {};

  googleMapping.map;
  googleMapping.currentLocation = {};
  googleMapping.userLocationInput = {};
  googleMapping.locations = [];
  googleMapping.locationsParsed = [];
  //placeholder until we can import the data
  googleMapping.locationsAddresses = [
    '620 SW 5th Ave, Portland, OR 97204',
    '300-398 SW Market St, Portland, OR 97201',
    '1800 SW Montgomery St, Portland, OR 97201',
    '1028 SE Water Ave, Portland, OR 97214',
    '1202-1210 Southeast Hawthorne Boulevard, Portland'
  ];

  //placeholder of lat/lng of above addresses...again for testing map api
  googleMapping.locationsAddressesLatLng = [
    // {lat:45.5190046,lng:-122.67688190000001},
    // {lat:45.5122623,lng:-122.67883110000002},
    // {lat:45.5115165,lng:-122.68207330000001},
    // {lat:45.5153234,lng:-122.6655189},
    // {lat:45.5122046,lng:-122.65358530000003}
  ];

  // googleMapping.getCurrentLocation = function(callbackFunction) {
  //   if (navigator.geolocation) {
  //     navigator.geolocation.getCurrentPosition(function(position) {
  //       googleMapping.currentLocation = {
  //         lat: position.coords.latitude,
  //         lng: position.coords.longitude
  //       };
  //       //uberObject.updateInfo(googleMapping.currentLocation);
  //       //lyftObject.updateInfo(googleMapping.currentLocation);
  //       googleMapping.map = googleMapping.createMap(filterData.zoom, googleMapping.currentLocation);
  //       callbackFunction(googleMapping.map);
  //     }, function() {
  //       googleMapping.handleLocationError(true, mapViews.map, mapViews.map.getCenter());
  //     });
  //   } else {
  //     //Browser doesn't support Geolocation :(
  //     googleMapping.currentLocation = {lat: 45.5231, lng: -122.6765};
  //     googleMapping.map = googleMapping.createMap(filterData.zoom, googleMapping.currentLocation);
  //     callbackFunction(googleMapping.map);
  //     handleLocationError(false, mapViews.map, mapViews.map.getCenter());
  //   };
  // };

  googleMapping.getUpdatedLocation = function(selectionObject) {
    $('.bike-map').empty();
    etaObject.buildCanvas();
    if (0 < selectionObject.address.length) {
      new google.maps.Geocoder()
      .geocode({address: selectionObject.address}, function(results) {
        googleMapping.currentLocation = {
          lat: results[0].geometry.location.lat(),
          lng: results[0].geometry.location.lng()
        };
        if (filterData.Uber) {
          uberObject.getInfo(etaObject.drawLogo, googleMapping.currentLocation);
        }
        if (filterData.Lyft) {
          lyftObject.getInfo(etaObject.drawLogo,googleMapping.currentLocation);
        }
        if (filterData.Biketown) {
          biketownObject.getStationInfo(mapViews.createMarkers);
        };
        //update with current location
        //uberObject.updateInfo(googleMapping.currentLocation);
        //lyftObject.updateInfo(googleMapping.currentLocation);
      });
    } else if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        googleMapping.currentLocation = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };
        if (filterData.Uber) {
          uberObject.getInfo(etaObject.drawLogo, googleMapping.currentLocation);
        }
        if (filterData.Lyft) {
          lyftObject.getInfo(etaObject.drawLogo,googleMapping.currentLocation);
        }
        if (filterData.Biketown) {
          biketownObject.getStationInfo(mapViews.createMarkers);
        };
            //uberObject.updateInfo(googleMapping.currentLocation);
            //lyftObject.updateInfo(googleMapping.currentLocation);
      }, function() {
        googleMapping.handleLocationError(true, googleMapping.map, googleMapping.map.getCenter());
      });

    } else {
      //update with current location
      googleMapping.currentLocation = {lat: 45.5231, lng: -122.6765};
      if (filterData.Uber) {
        uberObject.getInfo(etaObject.drawLogo, googleMapping.currentLocation);
      }
      if (filterData.Lyft) {
        lyftObject.getInfo(etaObject.drawLogo,googleMapping.currentLocation);
      }
      if (filterData.Biketown) {
        biketownObject.getStationInfo(mapViews.createMarkers);
      };
      handleLocationError(false, googleMapping.map, googleMapping.map.getCenter());
    };
  };

  googleMapping.handleLocationError = function(browserHasGeolocation, map, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
      'Error: The Geolocation service failed.' :
      'Error: Your browser doesn\'t support geolocation :('
    );
  };

  //call googles api to parse address strings into lat and lng data to be mapped to the actual map
  googleMapping.parseAddressString = function() {
    googleMapping.locations.forEach(function(addressString) {
      new google.maps.Geocoder()
      .geocode({address: addressString}, function(results) {
        googleMapping.locationsParsed.push({
          lat: results[0].geometry.location.lat(),
          lng: results[0].geometry.location.lng()
        });
      });
    });
  };

  googleMapping.createMap = function(zoomVal, latLng) {
    var map = new google.maps.Map(document.querySelectorAll('.bike-map')[0], {
      zoom: zoomVal,
      center: latLng
    });
    return map;
  };

  // googleMapping.initMap = function() {
  //   googleMapping.getCurrentLocation(mapViews.setMapOnAll);
  //   //firstFunction(, secondFunction);
  // };

  module.googleMapping = googleMapping;
})(window);
<commit_msg>deprecated navigator geolocation function until ssl encryption is up on our app<commit_after>'use strict';

(function(module) {

  var googleMapping = {};

  googleMapping.map;
  googleMapping.currentLocation = {};
  googleMapping.userLocationInput = {};
  googleMapping.locations = [];
  googleMapping.locationsParsed = [];
  //placeholder until we can import the data
  googleMapping.locationsAddresses = [
    '620 SW 5th Ave, Portland, OR 97204',
    '300-398 SW Market St, Portland, OR 97201',
    '1800 SW Montgomery St, Portland, OR 97201',
    '1028 SE Water Ave, Portland, OR 97214',
    '1202-1210 Southeast Hawthorne Boulevard, Portland'
  ];

  //placeholder of lat/lng of above addresses...again for testing map api
  googleMapping.locationsAddressesLatLng = [
    // {lat:45.5190046,lng:-122.67688190000001},
    // {lat:45.5122623,lng:-122.67883110000002},
    // {lat:45.5115165,lng:-122.68207330000001},
    // {lat:45.5153234,lng:-122.6655189},
    // {lat:45.5122046,lng:-122.65358530000003}
  ];

  // googleMapping.getCurrentLocation = function(callbackFunction) {
  //   if (navigator.geolocation) {
  //     navigator.geolocation.getCurrentPosition(function(position) {
  //       googleMapping.currentLocation = {
  //         lat: position.coords.latitude,
  //         lng: position.coords.longitude
  //       };
  //       //uberObject.updateInfo(googleMapping.currentLocation);
  //       //lyftObject.updateInfo(googleMapping.currentLocation);
  //       googleMapping.map = googleMapping.createMap(filterData.zoom, googleMapping.currentLocation);
  //       callbackFunction(googleMapping.map);
  //     }, function() {
  //       googleMapping.handleLocationError(true, mapViews.map, mapViews.map.getCenter());
  //     });
  //   } else {
  //     //Browser doesn't support Geolocation :(
  //     googleMapping.currentLocation = {lat: 45.5231, lng: -122.6765};
  //     googleMapping.map = googleMapping.createMap(filterData.zoom, googleMapping.currentLocation);
  //     callbackFunction(googleMapping.map);
  //     handleLocationError(false, mapViews.map, mapViews.map.getCenter());
  //   };
  // };

  googleMapping.getUpdatedLocation = function(selectionObject) {
    $('.bike-map').empty();
    etaObject.buildCanvas();
    if (0 < selectionObject.address.length) {
      new google.maps.Geocoder()
      .geocode({address: selectionObject.address}, function(results) {
        googleMapping.currentLocation = {
          lat: results[0].geometry.location.lat(),
          lng: results[0].geometry.location.lng()
        };
        if (filterData.Uber) {
          uberObject.getInfo(etaObject.drawLogo, googleMapping.currentLocation);
        }
        if (filterData.Lyft) {
          lyftObject.getInfo(etaObject.drawLogo,googleMapping.currentLocation);
        }
        if (filterData.Biketown) {
          biketownObject.getStationInfo(mapViews.createMarkers);
        };
        //update with current location
        //uberObject.updateInfo(googleMapping.currentLocation);
        //lyftObject.updateInfo(googleMapping.currentLocation);
      });

      /**TODO Navigator geolocation will be deprecated until ssl encryption can be used for this app**/
    // } else if (navigator.geolocation) {
    //   navigator.geolocation.getCurrentPosition(function(position) {
    //     googleMapping.currentLocation = {
    //       lat: position.coords.latitude,
    //       lng: position.coords.longitude
    //     };
    //     if (filterData.Uber) {
    //       uberObject.getInfo(etaObject.drawLogo, googleMapping.currentLocation);
    //     }
    //     if (filterData.Lyft) {
    //       lyftObject.getInfo(etaObject.drawLogo,googleMapping.currentLocation);
    //     }
    //     if (filterData.Biketown) {
    //       biketownObject.getStationInfo(mapViews.createMarkers);
    //     };
    //         //uberObject.updateInfo(googleMapping.currentLocation);
    //         //lyftObject.updateInfo(googleMapping.currentLocation);
    //   }, function() {
    //     googleMapping.handleLocationError(true, googleMapping.map, googleMapping.map.getCenter());
    //   });

    } else {
      //update with current location
      googleMapping.currentLocation = {lat: 45.5231, lng: -122.6765};
      if (filterData.Uber) {
        uberObject.getInfo(etaObject.drawLogo, googleMapping.currentLocation);
      }
      if (filterData.Lyft) {
        lyftObject.getInfo(etaObject.drawLogo,googleMapping.currentLocation);
      }
      if (filterData.Biketown) {
        biketownObject.getStationInfo(mapViews.createMarkers);
      };
      handleLocationError(false, googleMapping.map, googleMapping.map.getCenter());
    };
  };

  googleMapping.handleLocationError = function(browserHasGeolocation, map, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
      'Error: The Geolocation service failed.' :
      'Error: Your browser doesn\'t support geolocation :('
    );
  };

  //call googles api to parse address strings into lat and lng data to be mapped to the actual map
  googleMapping.parseAddressString = function() {
    googleMapping.locations.forEach(function(addressString) {
      new google.maps.Geocoder()
      .geocode({address: addressString}, function(results) {
        googleMapping.locationsParsed.push({
          lat: results[0].geometry.location.lat(),
          lng: results[0].geometry.location.lng()
        });
      });
    });
  };

  googleMapping.createMap = function(zoomVal, latLng) {
    var map = new google.maps.Map(document.querySelectorAll('.bike-map')[0], {
      zoom: zoomVal,
      center: latLng
    });
    return map;
  };

  // googleMapping.initMap = function() {
  //   googleMapping.getCurrentLocation(mapViews.setMapOnAll);
  //   //firstFunction(, secondFunction);
  // };

  module.googleMapping = googleMapping;
})(window);
<|endoftext|>


<commit_before>"use strict";

(function () {
    angular
        .module("piadinamia")
        .factory("cartService", cartService);

    cartService.$inject = ["$timeout", "sessionService"];

    function cartService($timeout, sessionService) {
        var service = {
                getItems: getItems,
                saveItem: saveItem,
                getTotalCount: getTotalCount,
                getTotalPrice: getTotalPrice,
                addItem: addItem,
                clearItem: clearItem
            },
            cartUrl,
            cartRef,
            myCart = [];

        sessionService.isLogged().then(activate);

        return service;

        function activate(userId) {
            var catalogNameRef = firebase.database().ref("/users/" +
                    userId + "/catalogs/default/name");

            catalogNameRef.once("value").then(function (catalogNameSnapshot) {
                var catalogName = catalogNameSnapshot.val();

                cartUrl = "/users/" + userId + "/catalogs/" +
                    catalogName + "/cart";
                cartRef = firebase.database().ref(cartUrl);
                cartRef.on("value", function (snapshot) {
                    var cart = snapshot.val(),
                        items = [];

                    Object.keys(cart).forEach(function (item) {
                        cart[item].$id = item;
                        items.push(cart[item]);
                    });

                    $timeout(function () {
                        angular.extend(myCart, items);
                    });
                });
            });
        }

        function getItems() {
            return myCart;
        }

        function saveItem(index) {
            var itemRef = cartRef.child(myCart[index].$id),
                newData = angular.copy(myCart[index]);

            delete newData.$id;
            itemRef.update(newData);
        }

        function getTotalCount() {
            var total = 0;

            myCart.forEach(function (item) {
                total += item.qty;
            });

            return total;
        }

        function getTotalPrice() {
            var total = 0;

            myCart.forEach(function (item) {
                total += item.price * item.qty;
            });

            return total;
        }

        function addItem(item, price, qty) {
            var found = false,
                newItem,
                newItemKey,
                newItemRef;

            qty = qty || 1;

            myCart.every(function (el, index) {
                var cart = myCart[index];

                if (el.item === item) {
                    found = true;

                    cart.qty += qty;

                    if (cart.qty === 0) {
                        service.clearItem(index);
                    } else {
                        cart.total = cart.price * cart.qty;
                        service.saveItem(index);
                    }

                    return false;
                }

                return true;
            });

            if (!found) {
                newItem = {
                    item: item,
                    price: price,
                    qty: 1,
                    total: price
                };
                newItemKey = cartRef.push().key;
                newItemRef = cartRef.child(newItemKey);

                newItemRef.update(newItem);
                newItem.$id = newItemKey;
                myCart.push(newItem);
            }
        }

        function clearItem(index) {
            var itemRef = cartRef.child(myCart[index].$id);

            itemRef.remove();
            myCart.splice(index, 1);
        }
    }

}());
<commit_msg>Fix cart when it is updated removing an item.<commit_after>"use strict";

(function () {
    angular
        .module("piadinamia")
        .factory("cartService", cartService);

    cartService.$inject = ["$timeout", "sessionService"];

    function cartService($timeout, sessionService) {
        var service = {
                getItems: getItems,
                saveItem: saveItem,
                getTotalCount: getTotalCount,
                getTotalPrice: getTotalPrice,
                addItem: addItem,
                clearItem: clearItem
            },
            cartUrl,
            cartRef,
            myCart = [];

        sessionService.isLogged().then(activate);

        return service;

        function activate(userId) {
            var catalogNameRef = firebase.database().ref("/users/" +
                    userId + "/catalogs/default/name");

            catalogNameRef.once("value").then(function (catalogNameSnapshot) {
                var catalogName = catalogNameSnapshot.val();

                cartUrl = "/users/" + userId + "/catalogs/" +
                    catalogName + "/cart";
                cartRef = firebase.database().ref(cartUrl);
                cartRef.on("value", function (snapshot) {
                    var cart = snapshot.val(),
                        items = [];

                    Object.keys(cart).forEach(function (item) {
                        cart[item].$id = item;
                        items.push(cart[item]);
                    });

                    $timeout(function () {
                        myCart.length = 0;
                        angular.extend(myCart, items);
                    });
                });
            });
        }

        function getItems() {
            return myCart;
        }

        function saveItem(index) {
            var itemRef = cartRef.child(myCart[index].$id),
                newData = angular.copy(myCart[index]);

            delete newData.$id;
            itemRef.update(newData);
        }

        function getTotalCount() {
            var total = 0;

            myCart.forEach(function (item) {
                total += item.qty;
            });

            return total;
        }

        function getTotalPrice() {
            var total = 0;

            myCart.forEach(function (item) {
                total += item.price * item.qty;
            });

            return total;
        }

        function addItem(item, price, qty) {
            var found = false,
                newItem,
                newItemKey,
                newItemRef;

            qty = qty || 1;

            myCart.every(function (el, index) {
                var cart = myCart[index];

                if (el.item === item) {
                    found = true;

                    cart.qty += qty;

                    if (cart.qty === 0) {
                        service.clearItem(index);
                    } else {
                        cart.total = cart.price * cart.qty;
                        service.saveItem(index);
                    }

                    return false;
                }

                return true;
            });

            if (!found) {
                newItem = {
                    item: item,
                    price: price,
                    qty: 1,
                    total: price
                };
                newItemKey = cartRef.push().key;
                newItemRef = cartRef.child(newItemKey);

                newItemRef.update(newItem);
                newItem.$id = newItemKey;
                myCart.push(newItem);
            }
        }

        function clearItem(index) {
            var itemRef = cartRef.child(myCart[index].$id);

            itemRef.remove();
            myCart.splice(index, 1);
        }
    }

}());
<|endoftext|>


<commit_before>foam.CLASS({
  name: 'PyTree',
  extends: 'foam.u2.Element',

  properties: [
    { class: 'Float', name: 'w', value: 80 },
    { class: 'Float', name: 'x' },
    { class: 'Float', name: 'y' },
    { class: 'String', name: 'rotate' },
    { name: 'heightFactor', value: 0.55 },
    { name: 'lean', value: 0 },
    { name: 'lvl', value: 1 },
    { name: 'maxlvl', value: 11 }
  ],

  methods: [
    function initE() {
      this.SUPER();

      this.setNodeName('g').
          attrs({transform: 'translate(' + this.x + ' ' + this.y + ') ' + this.rotate}).
          start('rect').
            attrs({width: this.w, height: this.w, x: 0, y: 0}).
            style({fill: 'hsl(' + this.lvl/this.maxlvl*180 + ',70%,70%)'}).
          end();

      if ( this.lvl < this.maxlvl ) {
        var lean      = this.lean, w = this.w;
        var trigH     = this.heightFactor * w;
        var nextRight = Math.sqrt(trigH**2 + (w * (.5+lean))**2);
        var nextLeft  = Math.sqrt(trigH**2 + (w * (.5-lean))**2);
        var A         = Math.atan(trigH / ((.5-lean) * w));
        var B         = Math.atan(trigH / ((.5+lean) * w));

        this.add(
            nextLeft > 1 && this.cls_.create({
              x: 0,
              y: -nextLeft,
              w: nextLeft,
              rotate: 'rotate(' + this.radToDeg(-A) + ' 0 ' + nextLeft + ')',
              lvl: this.lvl+1,
              maxlvl: this.maxlvl,
              heightFactor: this.heightFactor,
              lean: this.lean
            }),
            nextRight > 1 && this.cls_.create({
              x: Math.cos(A)*nextLeft,
              y: -nextRight - Math.sin(A)*nextLeft,
              w: nextRight,
              rotate: 'rotate(' + this.radToDeg(B) + ' 0 ' + nextRight + ')',
              lvl: this.lvl+1,
              maxlvl: this.maxlvl,
              heightFactor: this.heightFactor,
              lean: this.lean
            }));
      }
    },

    function radToDeg(r) { return 180*r/Math.PI; }
  ]
});

foam.CLASS({
  name: 'PyTreeController',
  extends: 'foam.u2.Element',

  requires: [ 'PyTree' ],

  properties: [
    { name: 'heightFactor', value: 0.55 },
    { name: 'lean', value: 0 }
  ],

  methods: [
    function initE() {
      this.SUPER();

      this.setNodeName('svg').
        attrs({width: 1600, height: 800}).
        on('mousemove', this.onMouseMove).
        add(this.slot(function(heightFactor, lean) {
          return this.PyTree.create({x: 800, y: 500, heightFactor: heightFactor, lean: lean});
        }));
    }
  ],

  listeners: [
    {
      name: 'onMouseMove',
      isFramed: true,
      code: function(e) {
        var x = e.clientX, y = e.clientY;
        this.heightFactor = y / this.getAttribute('height') * 0.8;
        this.lean         = x / this.getAttribute('width') - 0.5;
      }
    }
  ]
});

//var tree = PyTree.create();
//foam.__context__.E('svg').style({padding: 500}).add(tree).write();

var treeCtrl = PyTreeController.create();
treeCtrl.write();

<commit_msg>PyTree demo.<commit_after>foam.CLASS({
  name: 'PyTree',
  extends: 'foam.u2.Element',

  properties: [
    { class: 'Float', name: 'w', value: 80 },
    { class: 'Float', name: 'x' },
    { class: 'Float', name: 'y' },
    { class: 'String', name: 'rotate' },
    { name: 'heightFactor', value: 0.55 },
    { name: 'lean', value: 0 },
    { name: 'lvl', value: 1 },
    { name: 'maxlvl', value: 11 }
  ],

  methods: [
    function initE() {
      this.SUPER();

      this.setNodeName('g').
          attrs({transform: 'translate(' + this.x + ' ' + this.y + ') ' + this.rotate}).
          start('rect').
            attrs({width: this.w, height: this.w, x: 0, y: 0}).
            style({fill: 'hsl(' + this.lvl/this.maxlvl*180 + ',70%,70%)'}).
          end();

      if ( this.lvl < this.maxlvl ) {
        var lean      = this.lean, w = this.w;
        var trigH     = this.heightFactor * w;
        var nextRight = Math.sqrt(trigH**2 + (w * (.5+lean))**2);
        var nextLeft  = Math.sqrt(trigH**2 + (w * (.5-lean))**2);
        var A         = Math.atan(trigH / ((.5-lean) * w));
        var B         = Math.atan(trigH / ((.5+lean) * w));

        this.add(
            nextLeft > 1 && this.cls_.create({
              x: 0,
              y: -nextLeft,
              w: nextLeft,
              rotate: 'rotate(' + this.radToDeg(-A) + ' 0 ' + nextLeft + ')',
              lvl: this.lvl+1,
              maxlvl: this.maxlvl,
              heightFactor: this.heightFactor,
              lean: this.lean
            }),
            nextRight > 1 && this.cls_.create({
              x: Math.cos(A)*nextLeft,
              y: -nextRight - Math.sin(A)*nextLeft,
              w: nextRight,
              rotate: 'rotate(' + this.radToDeg(B) + ' 0 ' + nextRight + ')',
              lvl: this.lvl+1,
              maxlvl: this.maxlvl,
              heightFactor: this.heightFactor,
              lean: this.lean
            }));
      }
    },

    function radToDeg(r) { return 180*r/Math.PI; }
  ]
});

foam.CLASS({
  name: 'PyTreeController',
  extends: 'foam.u2.Element',

  requires: [ 'PyTree' ],

  properties: [
    { name: 'heightFactor', value: 0.55 },
    { name: 'lean', value: 0 }
  ],

  methods: [
    function initE() {
      this.SUPER();

      this.setNodeName('svg').
        attrs({width: 1600, height: 800}).
        on('mousemove', this.onMouseMove).
        add(this.slot(function(heightFactor, lean) {
          return this.PyTree.create({x: 800, y: 500, heightFactor: heightFactor, lean: lean});
        }));
    }
  ],

  listeners: [
    {
      name: 'onMouseMove',
//      isFramed: true,
      code: function(e) {
        var x = e.clientX, y = e.clientY;
        this.heightFactor = y / this.getAttribute('height') * 0.8;
        this.lean         = x / this.getAttribute('width') - 0.5;
      }
    }
  ]
});

//var tree = PyTree.create();
//foam.__context__.E('svg').style({padding: 500}).add(tree).write();

var treeCtrl = PyTreeController.create();
treeCtrl.write();
<|endoftext|>


<commit_before>(function() {
	"use strict";

	var module = angular.module("boardAPIModule", ["serverAPIModule"]);

	module.factory("boardAPI", ["serverAPI", "$log", "$q", function(serverAPI, $log, $q) {
		var user, board, boards, boardUsers;

		var boardInterface = {

			getBoardSync: function() {
				return board;
			},

			getBoard: function(boardId) {
				var defer = $q.defer();

				serverAPI
					.getBoard(boardId)
					.then(function(res) {
						board = res;
						defer.resolve(res);
					}, function(err) {
						$log.error(err);
						defer.reject(err);
					});

				return defer.promise;
			},

			updateBoard: function(_board_) {
				var board = board || _board_;

				var defer = $q.defer();

				serverAPI
					.updateBoard(board)
					.then(function() {
						board._v++;
						defer.resolve();
					}, function(err) {
						$log.error(err);
						defer.reject(err);
					});

				return defer.promise;
			},

			getBoardUsersSync: function() {
				boardUsers = board.admins.concat(board.members);
				return boardUsers;
			},

			addMemberToUserSelection: function(userEmail) {
				var defer = $q.defer();

				serverAPI
					.addMemberToUserSelection(board, userEmail)
					.then(function(res) {
						board.members.push(res);
						boardUsers.push(res);
						defer.resolve(res);
					}, function(err) {
						$log.error(err);
						defer.reject(err);
					});

				return defer;
			},

			createComment: function(content, user, task, cat) {
				var defer = $q.defer();

				serverAPI
					.createComment(
						content,
						user.username,
						user.pictureUrl,
						task._id,
						cat._id,
						board._id)
					.then(function(res) {
						task.comments.unshift(res);
						defer.resolve(res);
					}, function(err) {
						$log.error(err);
						defer.reject(err);
					});

				return defer;
			},

			createTask: function(name, cat) {
				var defer = $q.defer();

				serverAPI
					.createTask(
						name,
						cat._id,
						board._id)
					.then(function(res) {
						cat.tasks.push(res);
						defer.resolve(res);
					}, function(err) {
						$log.error(err);
						defer.reject(err);
					});

				return defer.promise;
			},

			createCategory: function(name) {
				var defer = $q.defer();

				serverAPI
					.createCategory(board._id, name)
					.then(function(res) {
						board.categories.push(res);
						defer.resolve(res);
					}, function(err) {
						$log.error(err);
						defer.reject(err);
					});

				return defer.promise;
			},

			deleteCategory: function(cat) {
				var defer = $q.defer();

				serverAPI
					.deleteCategory(board._id, cat._id)
					.then(function() {
						for (var i = 0; i < board.categories.length; i++) {
							if (board.categories[i]._id === cat._id) {
								board.categories.splice(i, 1);
							}
						}
						defer.resolve(res);
					}, function(err) {
						$log.error(err);
						defer.reject(err);
					});

				return defer.promise;
			},

			deleteTask: function(cat, task) {
				var defer = $q.defer();

				serverAPI
					.deleteTask(board._id, cat._id, task._id)
					.then(function() {
						for (var i = 0; i < cat.tasks.length; i++) {
							if (cat.tasks[i]._id === task._id) {
								cat.tasks.splice(i, 1);
							}
						}
						defer.resolve(res);
					}, function(err) {
						$log.error(err);
						defer.reject(err);
					});
				return defer.promise;
			}
		};

		return boardInterface;
	}]);
})();
<commit_msg>clean up/refac boardapi<commit_after>(function() {
	"use strict";

	var module = angular.module("boardAPIModule", ["serverAPIModule"]);

	module.factory("boardAPI", ["serverAPI", "$log", "$q", function(serverAPI, $log, $q) {
		var board, boardUsers;

		var boardInterface = {
			getBoardSync: function() {
				return board;
			},

			getBoard: function(boardId) {
				var defer = $q.defer();

				serverAPI
					.getBoard(boardId)
					.then(function(res) {
						board = res;
						defer.resolve(res);
					}, function(err) {
						$log.error(err);
						defer.reject(err);
					});

				return defer.promise;
			},

			updateBoard: function(_board_) {
				var board = board || _board_;

				var defer = $q.defer();

				serverAPI
					.updateBoard(board)
					.then(function() {
						board._v++;
						defer.resolve();
					}, function(err) {
						$log.error(err);
						defer.reject(err);
					});

				return defer.promise;
			},

			getBoardUsersSync: function() {
				boardUsers = board.admins.concat(board.members);
				return boardUsers;
			},

			addMemberToUserSelection: function(userEmail) {
				var defer = $q.defer();

				serverAPI
					.addMemberToUserSelection(board, userEmail)
					.then(function(res) {
						board.members.push(res);
						boardUsers.push(res);
						defer.resolve(res);
					}, function(err) {
						$log.error(err);
						defer.reject(err);
					});

				return defer;
			},

			createComment: function(content, user, task, cat) {
				var defer = $q.defer();

				serverAPI
					.createComment(
						content,
						user.username,
						user.pictureUrl,
						task._id,
						cat._id,
						board._id)
					.then(function(res) {
						task.comments.unshift(res);
						defer.resolve(res);
					}, function(err) {
						$log.error(err);
						defer.reject(err);
					});

				return defer;
			},

			createTask: function(name, cat) {
				var defer = $q.defer();

				serverAPI
					.createTask(
						name,
						cat._id,
						board._id)
					.then(function(res) {
						cat.tasks.push(res);
						defer.resolve(res);
					}, function(err) {
						$log.error(err);
						defer.reject(err);
					});

				return defer.promise;
			},

			createCategory: function(name) {
				var defer = $q.defer();

				serverAPI
					.createCategory(board._id, name)
					.then(function(res) {
						board.categories.push(res);
						defer.resolve(res);
					}, function(err) {
						$log.error(err);
						defer.reject(err);
					});

				return defer.promise;
			},

			deleteCategory: function(cat) {
				var defer = $q.defer();

				serverAPI
					.deleteCategory(board._id, cat._id)
					.then(function() {
						for (var i = 0; i < board.categories.length; i++) {
							if (board.categories[i]._id === cat._id) {
								board.categories.splice(i, 1);
							}
						}
						defer.resolve(res);
					}, function(err) {
						$log.error(err);
						defer.reject(err);
					});

				return defer.promise;
			},

			deleteTask: function(cat, task) {
				var defer = $q.defer();

				serverAPI
					.deleteTask(board._id, cat._id, task._id)
					.then(function() {
						for (var i = 0; i < cat.tasks.length; i++) {
							if (cat.tasks[i]._id === task._id) {
								cat.tasks.splice(i, 1);
							}
						}
						defer.resolve(res);
					}, function(err) {
						$log.error(err);
						defer.reject(err);
					});
				return defer.promise;
			}
		};

		return boardInterface;
	}]);
})();
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {
  Container,
  Menu,
} from 'semantic-ui-react';
import PropTypes from 'prop-types';

import NavigationRoutes from './NavigationRoutes';
import SiteLogo from './SiteLogo';

class NavigationBar extends Component {
  render() {
    const { activeRoute } = this.props;
    const { navigationRoutes } = this.props;
    const { siteLogo } = this.props;

    return (
      <Container>
        <Menu
          inverted
          pointing
          secondary
          defaultActiveIndex={0}
          size={'large'}
          stackable
          style={styles.menu}
        >
          <Menu.Item style={styles.menuItem}>
            <SiteLogo src={siteLogo}/>
          </Menu.Item>
          <NavigationRoutes
            active={activeRoute}
            routes={navigationRoutes}
          />
        </Menu>
      </Container>
    );
  }
}

NavigationBar.propTypes = {
  activeRoute: PropTypes.string.isRequired,
  navigationRoutes: PropTypes.array.isRequired,
  siteLogo: PropTypes.string.isRequired,
};

const styles = {
  menu: {
    borderWidth: 0,
  },
  menuItem: {
    padding: 0,
  },
};

export default NavigationBar;
<commit_msg>add site logo<commit_after>import React, { Component } from 'react';
import {
  Container,
  Menu,
} from 'semantic-ui-react';
import PropTypes from 'prop-types';

import NavigationRoutes from './NavigationRoutes';
import SiteLogo from './SiteLogo';

class NavigationBar extends Component {
  render() {
    const { activeRoute } = this.props;
    const { navigationRoutes } = this.props;
    const { siteLogo } = this.props;

    return (
      <Container>
        <Menu
          inverted
          pointing
          secondary
          defaultActiveIndex={0}
          size={'large'}
          stackable
          style={styles.menu}
        >
          <Menu.Item style={styles.menuItem}>
            <SiteLogo src={siteLogo} />
          </Menu.Item>
          <NavigationRoutes
            active={activeRoute}
            routes={navigationRoutes}
          />
        </Menu>
      </Container>
    );
  }
}

NavigationBar.propTypes = {
  activeRoute: PropTypes.string.isRequired,
  navigationRoutes: PropTypes.array.isRequired,
  siteLogo: PropTypes.string.isRequired,
};

const styles = {
  menu: {
    borderWidth: 0,
  },
  menuItem: {
    padding: 0,
  },
};

export default NavigationBar;
<|endoftext|>


<commit_before><commit_msg>make footer height dynamic<commit_after>angular.module('gokibitz.directives')
.directive('footer', function (debounce, $window, $document) {
		return {
			restrict: 'E',
			link: function(scope, element, attrs) {
				var $body = angular.element($document.body);

				// Set the margin-bottom on body to accomodate a footer of arbitrary height
				function setMargin() {
					var height = element.outerHeight(true);
					$document[0].body.setAttribute('style', 'margin-bottom: ' + height + 'px');
				}

				$document.ready(function () {
					setMargin();
				});

				var w = angular.element($window);
				w.bind('resize', debounce(1000, setMargin));
			}
		};
});
<|endoftext|>


<commit_before><commit_msg>domain change<commit_after><|endoftext|>


<commit_before>raw.charts.alluvial = function(){

	return {

		title : 'Alluvial diagram (fineo-like)',
		image : 'charts/imgs/alluvial.png',
		description : 'Alluvial diagrams allow to represent flows and to see correlations between categorical dimensions, visually linking to the number of elements sharing the same categories. It is useful to see the evolution of cluster (such as the number of people belonging to a specific group). It can also be used to represent bipartite graphs, using each node group as dimensions.
Mainly based on our previous work with Fineo, it is inspired by on http://bost.ocks.org/mike/sankey/.',
		model : raw.models.graph({}),

		options : {
			width : {
		      value : 800,
		      title : 'Width',
		      type : 'number'
		    },
		    height : {
		      value : 400,
		      title : 'Height',
		      type : 'number'
		    },
		    margin : {
		      value : 5,
		      title : 'Margin',
		      type : 'number'
		    },
		    nodeWidth : {
		      value : 15,
		      title : 'Node width',
		      type : 'number'
		    },
		    nodePadding : {
		      value : 10,
		      title : 'Node padding',
		      type : 'number'
		    }

		},

		render : function(data, target) {

			var model = this.model,
				options = this.options

			var formatNumber = d3.format(",.0f"),
			    format = function(d) { return formatNumber(d); },
			    width = options.width.value - options.margin.value,
			    height = options.height.value - options.margin.value;

			var svg = target.append("svg")
			    .attr("width", width + options.margin.value +1 )
			    .attr("height", height + options.margin.value +1 )
			  	.append("g")
			    .attr("transform", "translate(" + options.margin.value + "," + options.margin.value + ")");

			var sankey = d3.sankey()
			    .nodeWidth(options.nodeWidth.value)
			    .nodePadding(options.nodePadding.value)
			    .size([width, height]);

			var path = sankey.link();

			var nodes = model.applyOn(data).nodes,
				links = model.applyOn(data).links;

			sankey
			    .nodes(nodes)
			    .links(links)
			    .layout(32);

			var link = svg.append("g").selectAll(".link")
			    .data(links)
			   	.enter().append("path")
			    .attr("class", "link")
			    .attr("d", path )
			    .style("stroke-width", function(d) { return Math.max(1, d.dy); })
			    .style("fill","none")
			    .style("stroke","#000")
			    .style("stroke-opacity",".2")
			    .sort(function(a, b) { return b.dy - a.dy; });

			link.append("title")
			    .text(function(d) { return d.source.name + " → " + d.target.name + "\n" + format(d.value); });

			var node = svg.append("g").selectAll(".node")
			    .data(nodes)
			    .enter().append("g")
			      	.attr("class", "node")
			      	.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
			    	.call(d3.behavior.drag()
			      		.origin(function(d) { return d; })
			      		.on("dragstart", function() { this.parentNode.appendChild(this); })
			      		.on("drag", dragmove));

			var color = raw.diverging(raw.countUnique(nodes.map(function(d){ return { name: d.name.replace(/ .*/, "") }; }), "name"));

			node.append("rect")
			    .attr("height", function(d) { return d.dy; })
			    .attr("width", sankey.nodeWidth())
			    .style("fill", function(d) { return d.color = color(d.name.replace(/ .*/, "")); })
			    .style("stroke", function(d) { return d3.rgb(d.color).darker(2); })
			    .style("shape-rendering","crispEdges")
			    .style("cursor","ns-resize")
			    .append("title")
			    .text(function(d) { return d.name + "\n" + format(d.value); });

			node.append("text")
			    .attr("x", -6)
		      	.attr("y", function(d) { return d.dy / 2; })
		      	.attr("dy", ".35em")
		      	.attr("text-anchor", "end")
		      	.attr("transform", null)
			    .text(function(d) { return d.name; })
			    .style("font-size","11px")
				.style("font-family","Arial, Helvetica, sans-serif")
			    .style("pointer-events","none")
			    .filter(function(d) { return d.x < width / 2; })
			    	.attr("x", 6 + sankey.nodeWidth())
			     	.attr("text-anchor", "start");

			function dragmove(d) {
			    d3.select(this).attr("transform", "translate(" + d.x + "," + (d.y = Math.max(0, Math.min(height - d.dy, d3.event.y))) + ")");
			    sankey.relayout();
			    link.attr("d", path);
			}

			return this;
		}

	}
};
<commit_msg>Fixed Typo in description for alluvial chart<commit_after>raw.charts.alluvial = function(){

	return {

		title : 'Alluvial diagram (fineo-like)',
		image : 'charts/imgs/alluvial.png',
		description : 'Alluvial diagrams allow to represent flows and to see correlations between categorical dimensions, visually linking to the number of elements sharing the same categories. It is useful to see the evolution of cluster (such as the number of people belonging to a specific group). It can also be used to represent bipartite graphs, using each node group as dimensions.
Mainly based on our previous work with Fineo, it is inspired by http://bost.ocks.org/mike/sankey/.',
		model : raw.models.graph({}),

		options : {
			width : {
		      value : 800,
		      title : 'Width',
		      type : 'number'
		    },
		    height : {
		      value : 400,
		      title : 'Height',
		      type : 'number'
		    },
		    margin : {
		      value : 5,
		      title : 'Margin',
		      type : 'number'
		    },
		    nodeWidth : {
		      value : 15,
		      title : 'Node width',
		      type : 'number'
		    },
		    nodePadding : {
		      value : 10,
		      title : 'Node padding',
		      type : 'number'
		    }

		},

		render : function(data, target) {

			var model = this.model,
				options = this.options

			var formatNumber = d3.format(",.0f"),
			    format = function(d) { return formatNumber(d); },
			    width = options.width.value - options.margin.value,
			    height = options.height.value - options.margin.value;

			var svg = target.append("svg")
			    .attr("width", width + options.margin.value +1 )
			    .attr("height", height + options.margin.value +1 )
			  	.append("g")
			    .attr("transform", "translate(" + options.margin.value + "," + options.margin.value + ")");

			var sankey = d3.sankey()
			    .nodeWidth(options.nodeWidth.value)
			    .nodePadding(options.nodePadding.value)
			    .size([width, height]);

			var path = sankey.link();

			var nodes = model.applyOn(data).nodes,
				links = model.applyOn(data).links;

			sankey
			    .nodes(nodes)
			    .links(links)
			    .layout(32);

			var link = svg.append("g").selectAll(".link")
			    .data(links)
			   	.enter().append("path")
			    .attr("class", "link")
			    .attr("d", path )
			    .style("stroke-width", function(d) { return Math.max(1, d.dy); })
			    .style("fill","none")
			    .style("stroke","#000")
			    .style("stroke-opacity",".2")
			    .sort(function(a, b) { return b.dy - a.dy; });

			link.append("title")
			    .text(function(d) { return d.source.name + " → " + d.target.name + "\n" + format(d.value); });

			var node = svg.append("g").selectAll(".node")
			    .data(nodes)
			    .enter().append("g")
			      	.attr("class", "node")
			      	.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
			    	.call(d3.behavior.drag()
			      		.origin(function(d) { return d; })
			      		.on("dragstart", function() { this.parentNode.appendChild(this); })
			      		.on("drag", dragmove));

			var color = raw.diverging(raw.countUnique(nodes.map(function(d){ return { name: d.name.replace(/ .*/, "") }; }), "name"));

			node.append("rect")
			    .attr("height", function(d) { return d.dy; })
			    .attr("width", sankey.nodeWidth())
			    .style("fill", function(d) { return d.color = color(d.name.replace(/ .*/, "")); })
			    .style("stroke", function(d) { return d3.rgb(d.color).darker(2); })
			    .style("shape-rendering","crispEdges")
			    .style("cursor","ns-resize")
			    .append("title")
			    .text(function(d) { return d.name + "\n" + format(d.value); });

			node.append("text")
			    .attr("x", -6)
		      	.attr("y", function(d) { return d.dy / 2; })
		      	.attr("dy", ".35em")
		      	.attr("text-anchor", "end")
		      	.attr("transform", null)
			    .text(function(d) { return d.name; })
			    .style("font-size","11px")
				.style("font-family","Arial, Helvetica, sans-serif")
			    .style("pointer-events","none")
			    .filter(function(d) { return d.x < width / 2; })
			    	.attr("x", 6 + sankey.nodeWidth())
			     	.attr("text-anchor", "start");

			function dragmove(d) {
			    d3.select(this).attr("transform", "translate(" + d.x + "," + (d.y = Math.max(0, Math.min(height - d.dy, d3.event.y))) + ")");
			    sankey.relayout();
			    link.attr("d", path);
			}

			return this;
		}

	}
};
<|endoftext|>


<commit_before>/* globals moment */

/**
 * This widget provides a text input field to specify a date/time. The user
 * chooses the date/time using a popup picker.
 */
girder.views.DateTimeWidget = girder.View.extend({

    /**
     * @param [settings.prefix='default'] Prefix for element IDs in case
     *     multiple DateTimeWidgets are rendered simultaneously.
     */
    initialize: function (settings) {
        this.prefix = settings.prefix || 'default';
        this.dateTimeId = '#' + this.prefix + '-datetime';
    },

    render: function () {
        this.$el.html(girder.templates.dateTimeWidget({
            prefix: this.prefix
        }));

        this.$(this.dateTimeId).datetimepicker({
            showClear: true,
            showTodayButton: true,
            useCurrent: 'day',
            icons: {
                time: 'icon-clock',
                date: 'icon-calendar',
                up: 'icon-up-open',
                down: 'icon-down-open',
                previous: 'icon-left-open',
                next: 'icon-right-open',
                clear: 'icon-trash',
                close: 'icon-cancel',
                today: 'icon-target'
            }
        });

        return this;
    },

    /**
     * Set date/time. Argument can be an ISO 8601-formatted date string, a
     * moment object, or a Date object. Call with null or the empty string to
     * clear. When called with a string, the widget displays in local time.
     *
     * @param date Date/time to display.
     */
    setDate: function (date) {
        var picker = this._picker();
        if (_.isEmpty(date)) {
            picker.clear();
        } else if (_.isString(date)) {
            var localDate = moment.utc(date).local();
            picker.date(localDate);
        } else {
            picker.date(date);
        }
    },

    /**
     * Get the date/time as a moment object in UTC. Returns null if no date is
     * set.
     */
    date: function () {
        var picker = this._picker();
        var date = picker.date();
        if (date !== null) {
            date = moment(date);
            date.utc();
        }
        return date;
    },

    /**
     * Convenience function to return the date/time as a string in UTC. Returns
     * the empty string if no date is set.
     */
    dateString: function () {
        var date = this.date();
        if (date === null) {
            return '';
        }
        return date.format();
    },

    /**
     * Convenience function to access the datetimepicker on an element.
     */
    _picker: function () {
        var picker = this.$(this.dateTimeId).data('DateTimePicker');
        return picker;
    }
});

/**
 * This widget provides text input fields to specify a range of dates/times.
 * That is, the first field specifies "from" and the second field specifies
 * "to." The user chooses each date/time using a popup picker.
 */
girder.views.DateTimeRangeWidget = girder.View.extend({

    /**
     * @param [settings.prefix='default'] Prefix for element IDs in case
     *     multiple DateTimeRangeWidgets are rendered simultaneously.
     */
    initialize: function (settings) {
        this.prefix = settings.prefix || 'default';
        this.dateTimeFromId = '#' + this.prefix + '-datetime-from';
        this.dateTimeToId = '#' + this.prefix + '-datetime-to';
    },

    render: function () {
        this.$el.html(girder.templates.dateTimeRangeWidget({
            prefix: this.prefix
        }));

        // Link datetimepickers to disallow choosing range where "from" date is
        // after "to" date

        var options = {
            showClear: true,
            showTodayButton: true,
            useCurrent: 'day',
            icons: {
                time: 'icon-clock',
                date: 'icon-calendar',
                up: 'icon-up-open',
                down: 'icon-down-open',
                previous: 'icon-left-open',
                next: 'icon-right-open',
                clear: 'icon-trash',
                close: 'icon-cancel',
                today: 'icon-target'
            }
        };
        this.$(this.dateTimeFromId).datetimepicker(options);

        options['useCurrent'] = false;
        this.$(this.dateTimeToId).datetimepicker(options);

        $(this.dateTimeFromId).on('dp.change', _.bind(function (e) {
            var picker = this._picker(this.dateTimeToId);
            picker.minDate(e.date);
        }, this));
        $(this.dateTimeToId).on('dp.change', _.bind(function (e) {
            var picker = this._picker(this.dateTimeFromId);
            picker.maxDate(e.date);
        }, this));

        return this;
    },

    /**
     * Set "from" date/time. Argument can be an ISO 8601-formatted date string,
     * a moment object, or a Date object. Call with null or the empty string to
     * clear. When called with a string, the widget displays in local time.
     *
     * @param date From date/time to display.
     */
    setFromDate: function (date) {
        this._setDate(this.dateTimeFromId, date);
    },

    /**
     * Set "to" date/time. Argument can be an ISO 8601-formatted date string,
     * a moment object, or a Date object. Call with null or the empty string to
     * clear. When called with a string, the widget displays in local time.
     *
     * @param date To date/time to display.
     */
    setToDate: function (date) {
        this._setDate(this.dateTimeToId, date);
    },

    /*
     * Convenience function to set date/time for a specified datetimepicker.
     *
     * @param [id] Element ID on which to access the datetimepicker.
     */
    _setDate: function (id, date) {
        var picker = this._picker(id);
        if (_.isEmpty(date)) {
            picker.clear();
        } else if (_.isString(date)) {
            var localDate = moment.utc(date).local();
            picker.date(localDate);
        } else {
            picker.date(date);
        }
    },

    /**
     * Get the "from" date/time as a moment object in UTC. Returns null if no
     * date is set.
     */
    fromDate: function () {
        return this._date(this.dateTimeFromId);
    },

    /**
     * Get the "to" date/time as a moment object in UTC. Returns null if no date
     * is set.
     */
    toDate: function () {
        return this._date(this.dateTimeToId);
    },

    /**
     * Convenience function to return "from" the date/time as a string in UTC.
     * Returns the empty string if no date is set.
     */
    fromDateString: function () {
        return this._dateString(this.dateTimeFromId);
    },

    /**
     * Convenience function to return the "to" date/time as a string in UTC.
     * Returns the empty string if no date is set.
     */
    toDateString: function () {
        return this._dateString(this.dateTimeToId);
    },

    _picker: function (id) {
        var picker = this.$(id).data('DateTimePicker');
        return picker;
    },

    _date: function (id) {
        var picker = this._picker(id);
        var date = picker.date();
        if (date !== null) {
            date = moment(date);
            date.utc();
        }
        return date;
    },

    _dateString: function (id) {
        var date = this._date(id);
        if (date === null) {
            return '';
        }
        return date.format();
    }
});
<commit_msg>DateTimeWidget: fix failing test: jsstyle_core<commit_after>/* globals moment */

/**
 * This widget provides a text input field to specify a date/time. The user
 * chooses the date/time using a popup picker.
 */
girder.views.DateTimeWidget = girder.View.extend({

    /**
     * @param [settings.prefix='default'] Prefix for element IDs in case
     *     multiple DateTimeWidgets are rendered simultaneously.
     */
    initialize: function (settings) {
        this.prefix = settings.prefix || 'default';
        this.dateTimeId = '#' + this.prefix + '-datetime';
    },

    render: function () {
        this.$el.html(girder.templates.dateTimeWidget({
            prefix: this.prefix
        }));

        this.$(this.dateTimeId).datetimepicker({
            showClear: true,
            showTodayButton: true,
            useCurrent: 'day',
            icons: {
                time: 'icon-clock',
                date: 'icon-calendar',
                up: 'icon-up-open',
                down: 'icon-down-open',
                previous: 'icon-left-open',
                next: 'icon-right-open',
                clear: 'icon-trash',
                close: 'icon-cancel',
                today: 'icon-target'
            }
        });

        return this;
    },

    /**
     * Set date/time. Argument can be an ISO 8601-formatted date string, a
     * moment object, or a Date object. Call with null or the empty string to
     * clear. When called with a string, the widget displays in local time.
     *
     * @param date Date/time to display.
     */
    setDate: function (date) {
        var picker = this._picker();
        if (_.isEmpty(date)) {
            picker.clear();
        } else if (_.isString(date)) {
            var localDate = moment.utc(date).local();
            picker.date(localDate);
        } else {
            picker.date(date);
        }
    },

    /**
     * Get the date/time as a moment object in UTC. Returns null if no date is
     * set.
     */
    date: function () {
        var picker = this._picker();
        var date = picker.date();
        if (date !== null) {
            date = moment(date);
            date.utc();
        }
        return date;
    },

    /**
     * Convenience function to return the date/time as a string in UTC. Returns
     * the empty string if no date is set.
     */
    dateString: function () {
        var date = this.date();
        if (date === null) {
            return '';
        }
        return date.format();
    },

    /**
     * Convenience function to access the datetimepicker on an element.
     */
    _picker: function () {
        var picker = this.$(this.dateTimeId).data('DateTimePicker');
        return picker;
    }
});

/**
 * This widget provides text input fields to specify a range of dates/times.
 * That is, the first field specifies "from" and the second field specifies
 * "to." The user chooses each date/time using a popup picker.
 */
girder.views.DateTimeRangeWidget = girder.View.extend({

    /**
     * @param [settings.prefix='default'] Prefix for element IDs in case
     *     multiple DateTimeRangeWidgets are rendered simultaneously.
     */
    initialize: function (settings) {
        this.prefix = settings.prefix || 'default';
        this.dateTimeFromId = '#' + this.prefix + '-datetime-from';
        this.dateTimeToId = '#' + this.prefix + '-datetime-to';
    },

    render: function () {
        this.$el.html(girder.templates.dateTimeRangeWidget({
            prefix: this.prefix
        }));

        // Link datetimepickers to disallow choosing range where "from" date is
        // after "to" date

        var options = {
            showClear: true,
            showTodayButton: true,
            useCurrent: 'day',
            icons: {
                time: 'icon-clock',
                date: 'icon-calendar',
                up: 'icon-up-open',
                down: 'icon-down-open',
                previous: 'icon-left-open',
                next: 'icon-right-open',
                clear: 'icon-trash',
                close: 'icon-cancel',
                today: 'icon-target'
            }
        };
        this.$(this.dateTimeFromId).datetimepicker(options);

        options.useCurrent = false;
        this.$(this.dateTimeToId).datetimepicker(options);

        $(this.dateTimeFromId).on('dp.change', _.bind(function (e) {
            var picker = this._picker(this.dateTimeToId);
            picker.minDate(e.date);
        }, this));
        $(this.dateTimeToId).on('dp.change', _.bind(function (e) {
            var picker = this._picker(this.dateTimeFromId);
            picker.maxDate(e.date);
        }, this));

        return this;
    },

    /**
     * Set "from" date/time. Argument can be an ISO 8601-formatted date string,
     * a moment object, or a Date object. Call with null or the empty string to
     * clear. When called with a string, the widget displays in local time.
     *
     * @param date From date/time to display.
     */
    setFromDate: function (date) {
        this._setDate(this.dateTimeFromId, date);
    },

    /**
     * Set "to" date/time. Argument can be an ISO 8601-formatted date string,
     * a moment object, or a Date object. Call with null or the empty string to
     * clear. When called with a string, the widget displays in local time.
     *
     * @param date To date/time to display.
     */
    setToDate: function (date) {
        this._setDate(this.dateTimeToId, date);
    },

    /*
     * Convenience function to set date/time for a specified datetimepicker.
     *
     * @param [id] Element ID on which to access the datetimepicker.
     */
    _setDate: function (id, date) {
        var picker = this._picker(id);
        if (_.isEmpty(date)) {
            picker.clear();
        } else if (_.isString(date)) {
            var localDate = moment.utc(date).local();
            picker.date(localDate);
        } else {
            picker.date(date);
        }
    },

    /**
     * Get the "from" date/time as a moment object in UTC. Returns null if no
     * date is set.
     */
    fromDate: function () {
        return this._date(this.dateTimeFromId);
    },

    /**
     * Get the "to" date/time as a moment object in UTC. Returns null if no date
     * is set.
     */
    toDate: function () {
        return this._date(this.dateTimeToId);
    },

    /**
     * Convenience function to return "from" the date/time as a string in UTC.
     * Returns the empty string if no date is set.
     */
    fromDateString: function () {
        return this._dateString(this.dateTimeFromId);
    },

    /**
     * Convenience function to return the "to" date/time as a string in UTC.
     * Returns the empty string if no date is set.
     */
    toDateString: function () {
        return this._dateString(this.dateTimeToId);
    },

    _picker: function (id) {
        var picker = this.$(id).data('DateTimePicker');
        return picker;
    },

    _date: function (id) {
        var picker = this._picker(id);
        var date = picker.date();
        if (date !== null) {
            date = moment(date);
            date.utc();
        }
        return date;
    },

    _dateString: function (id) {
        var date = this._date(id);
        if (date === null) {
            return '';
        }
        return date.format();
    }
});
<|endoftext|>