<commit_before>"use strict";

var CityTour = CityTour || {};
CityTour.Scene = CityTour.Scene || {};

CityTour.Scene.BuildingGeometryBuilder = function() {
  var buildMaterials = function() {
    var buildingMaterials = [];

    for (var i = 0; i < CityTour.Config.MAX_BUILDING_MATERIALS; i++) {
      var random = Math.random() * 0.7;
      var r = random;
      var g = random;
      var b = random;

      buildingMaterials.push(new THREE.MeshLambertMaterial({ color: new THREE.Color(r, g, b), }));
    }

    return buildingMaterials;
  };

  var buildEmptyGeometriesForBuildings = function() {
    var buildingGeometries = [];

    for (var i = 0; i < CityTour.Config.MAX_BUILDING_MATERIALS; i++) {
      buildingGeometries.push(new THREE.Geometry());
    }

    return buildingGeometries;
  };

  var generateBuildingGeometries = function(buildings, buildingGeometries) {
    var HALF_STREET_WIDTH = CityTour.Config.STREET_WIDTH / 2;
    var HALF_STREET_DEPTH = CityTour.Config.STREET_DEPTH / 2;

    var mapX, mapZ, sceneX, sceneZ;
    var block;
    var storyHeight, buildingHeight;
    var materialIndex;

    var reusableBuildingMesh = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1));

    for (mapX = -CityTour.Config.HALF_BLOCK_COLUMNS; mapX < CityTour.Config.HALF_BLOCK_COLUMNS; mapX++) {
      sceneX = CityTour.Coordinates.mapXToSceneX(mapX) + HALF_STREET_WIDTH;

      for (mapZ = -CityTour.Config.HALF_BLOCK_ROWS; mapZ < CityTour.Config.HALF_BLOCK_ROWS; mapZ++) {
        sceneZ = CityTour.Coordinates.mapZToSceneZ(mapZ) + HALF_STREET_DEPTH;

        block = buildings.blockAtCoordinates(mapX, mapZ);

        block.forEach(function(lot) {
          var mapLotWidth = lot.right - lot.left;
          var mapLotDepth = lot.bottom - lot.top;
          var mapLotXMidpoint = lot.left + (mapLotWidth / 2);
          var mapLotZMidpoint = lot.top + (mapLotDepth / 2);

          storyHeight = ((CityTour.Config.MAX_STORY_HEIGHT - CityTour.Config.MIN_STORY_HEIGHT) * Math.random()) + CityTour.Config.MIN_STORY_HEIGHT;
          buildingHeight = storyHeight * lot.stories + (lot.ySurface - lot.yFloor);

          reusableBuildingMesh.scale.x = mapLotWidth * CityTour.Config.BLOCK_WIDTH;
          reusableBuildingMesh.position.x = sceneX + (CityTour.Config.BLOCK_WIDTH * mapLotXMidpoint);

          reusableBuildingMesh.scale.y = buildingHeight;
          reusableBuildingMesh.position.y = (buildingHeight / 2) + lot.yFloor;

          reusableBuildingMesh.scale.z = mapLotDepth * CityTour.Config.BLOCK_WIDTH;
          reusableBuildingMesh.position.z = sceneZ + (CityTour.Config.BLOCK_DEPTH * mapLotZMidpoint);

          reusableBuildingMesh.updateMatrix();

          materialIndex = Math.floor(Math.random() * CityTour.Config.MAX_BUILDING_MATERIALS);
          buildingGeometries[materialIndex].merge(reusableBuildingMesh.geometry, reusableBuildingMesh.matrix);

          if (lot.stories > 25 && (Math.random() < 0.3)) {
            var cylinder = new THREE.Mesh(new THREE.CylinderGeometry(0.2, 0.2, 10, 4));
            cylinder.position.x = sceneX + (CityTour.Config.BLOCK_WIDTH * mapLotXMidpoint);
            cylinder.position.y = lot.yFloor + buildingHeight + 5;
            cylinder.position.z = sceneZ + (CityTour.Config.BLOCK_DEPTH * mapLotZMidpoint);
            cylinder.updateMatrix();
            buildingGeometries[materialIndex].merge(cylinder.geometry, cylinder.matrix);
          }
        });
      }
    }
  };

  var buildingGeometryBuilder = {};

  buildingGeometryBuilder.build = function(buildings) {
    var buildingMaterials = buildMaterials();
    var buildingGeometries = buildEmptyGeometriesForBuildings();

    generateBuildingGeometries(buildings, buildingGeometries);

    var buildingMeshes = [];
    for (var i = 0; i < CityTour.Config.MAX_BUILDING_MATERIALS; i++) {
      buildingMeshes.push(new THREE.Mesh(buildingGeometries[i], buildingMaterials[i]));
    }

    return buildingMeshes;
  };

  return buildingGeometryBuilder;
};
<commit_msg>Extracting constants, and adding comment<commit_after>"use strict";

var CityTour = CityTour || {};
CityTour.Scene = CityTour.Scene || {};

CityTour.Scene.BuildingGeometryBuilder = function() {
  var buildMaterials = function() {
    var buildingMaterials = [];

    for (var i = 0; i < CityTour.Config.MAX_BUILDING_MATERIALS; i++) {
      var random = Math.random() * 0.7;
      var r = random;
      var g = random;
      var b = random;

      buildingMaterials.push(new THREE.MeshLambertMaterial({ color: new THREE.Color(r, g, b), }));
    }

    return buildingMaterials;
  };

  var buildEmptyGeometriesForBuildings = function() {
    var buildingGeometries = [];

    for (var i = 0; i < CityTour.Config.MAX_BUILDING_MATERIALS; i++) {
      buildingGeometries.push(new THREE.Geometry());
    }

    return buildingGeometries;
  };

  var generateBuildingGeometries = function(buildings, buildingGeometries) {
    var HALF_STREET_WIDTH = CityTour.Config.STREET_WIDTH / 2;
    var HALF_STREET_DEPTH = CityTour.Config.STREET_DEPTH / 2;
    var MIN_STORIES_FOR_ANTENNA = 25;
    var PROBABILITY_OF_TALL_BUILDING_ANTENNA = 0.3;

    var mapX, mapZ, sceneX, sceneZ;
    var block;
    var storyHeight, buildingHeight;
    var materialIndex;

    var reusableBuildingMesh = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1));

    for (mapX = -CityTour.Config.HALF_BLOCK_COLUMNS; mapX < CityTour.Config.HALF_BLOCK_COLUMNS; mapX++) {
      sceneX = CityTour.Coordinates.mapXToSceneX(mapX) + HALF_STREET_WIDTH;

      for (mapZ = -CityTour.Config.HALF_BLOCK_ROWS; mapZ < CityTour.Config.HALF_BLOCK_ROWS; mapZ++) {
        sceneZ = CityTour.Coordinates.mapZToSceneZ(mapZ) + HALF_STREET_DEPTH;

        block = buildings.blockAtCoordinates(mapX, mapZ);

        block.forEach(function(lot) {
          var mapLotWidth = lot.right - lot.left;
          var mapLotDepth = lot.bottom - lot.top;
          var mapLotXMidpoint = lot.left + (mapLotWidth / 2);
          var mapLotZMidpoint = lot.top + (mapLotDepth / 2);

          storyHeight = ((CityTour.Config.MAX_STORY_HEIGHT - CityTour.Config.MIN_STORY_HEIGHT) * Math.random()) + CityTour.Config.MIN_STORY_HEIGHT;
          buildingHeight = storyHeight * lot.stories + (lot.ySurface - lot.yFloor);

          reusableBuildingMesh.scale.x = mapLotWidth * CityTour.Config.BLOCK_WIDTH;
          reusableBuildingMesh.position.x = sceneX + (CityTour.Config.BLOCK_WIDTH * mapLotXMidpoint);

          reusableBuildingMesh.scale.y = buildingHeight;
          reusableBuildingMesh.position.y = (buildingHeight / 2) + lot.yFloor;

          reusableBuildingMesh.scale.z = mapLotDepth * CityTour.Config.BLOCK_WIDTH;
          reusableBuildingMesh.position.z = sceneZ + (CityTour.Config.BLOCK_DEPTH * mapLotZMidpoint);

          reusableBuildingMesh.updateMatrix();

          materialIndex = Math.floor(Math.random() * CityTour.Config.MAX_BUILDING_MATERIALS);
          buildingGeometries[materialIndex].merge(reusableBuildingMesh.geometry, reusableBuildingMesh.matrix);

          // Add antenna to tall buildings
          if (lot.stories > MIN_STORIES_FOR_ANTENNA && (Math.random() < PROBABILITY_OF_TALL_BUILDING_ANTENNA)) {
            var cylinder = new THREE.Mesh(new THREE.CylinderGeometry(0.2, 0.2, 10, 4));
            cylinder.position.x = sceneX + (CityTour.Config.BLOCK_WIDTH * mapLotXMidpoint);
            cylinder.position.y = lot.yFloor + buildingHeight + 5;
            cylinder.position.z = sceneZ + (CityTour.Config.BLOCK_DEPTH * mapLotZMidpoint);
            cylinder.updateMatrix();
            buildingGeometries[materialIndex].merge(cylinder.geometry, cylinder.matrix);
          }
        });
      }
    }
  };

  var buildingGeometryBuilder = {};

  buildingGeometryBuilder.build = function(buildings) {
    var buildingMaterials = buildMaterials();
    var buildingGeometries = buildEmptyGeometriesForBuildings();

    generateBuildingGeometries(buildings, buildingGeometries);

    var buildingMeshes = [];
    for (var i = 0; i < CityTour.Config.MAX_BUILDING_MATERIALS; i++) {
      buildingMeshes.push(new THREE.Mesh(buildingGeometries[i], buildingMaterials[i]));
    }

    return buildingMeshes;
  };

  return buildingGeometryBuilder;
};
<|endoftext|>


<commit_before>/* global define:true */
define([
    'pixi',
    'explore/issues-mode',
    'explore/issue'
], function (
    PIXI,
    IssuesMode,
    Issue
) {
    'use strict';

    var TagIssuesMode = function (canvas) {
        this._canvas = canvas;

        return this;
    };

    TagIssuesMode.prototype = new IssuesMode();
    TagIssuesMode.prototype.constructor = TagIssuesMode;

    TagIssuesMode.prototype.init = function () {
        IssuesMode.prototype.init.call(this);

        this._drawCloseButton();

        this._margin.top += this._issueMargin + 100;
        this._updateScroll();

    };

     TagIssuesMode.prototype._drawCloseButton = function () {
        this._closeButton = new PIXI.DisplayObjectContainer();

        // TODO: use close button sprite
        var bg = new PIXI.Graphics();
        bg.beginFill(0xFFFFFF);
        bg.drawCircle(0, 0, 25);
        bg.endFill();
        this._closeButton.addChild(bg);

        this._closeButton.x = (this._canvas.canvasSize.x / 2) - 65;
        this._closeButton.y = -(this._canvas.canvasSize.y / 2) + 65;
        this._closeButton.alpha = 0;
        this._closeButton.elm = this._closeButton; // hack
        this._closeButton.interactive = true;
        this._closeButton.buttonMode = true;
        this._closeButton.mousedown = this._closeButton.tap = this._onPressClose.bind(this);

        this._closeButtonContainer = new PIXI.DisplayObjectContainer();
        this._closeButtonContainer.x = this._canvas.canvasSize.x / 2;
        this._closeButtonContainer.y = this._canvas.canvasSize.y / 2;
        this._closeButtonContainer.addChild(this._closeButton);
        this._canvas.addChild(this._closeButtonContainer);
     };

    TagIssuesMode.prototype.setTag = function (data) {
        this._tag = this._canvas.getElementByData(data);

        this._issues = [];
        var related = data.getRelated();
        for (var i = 0; i < related.length; i ++) {
            this._issues.push(this._canvas.getElementByData(related[i]));
        }

        this._updateScroll();
    };

    TagIssuesMode.prototype._onPressClose = function () {
        this.hide();
    };

    TagIssuesMode.prototype._drawLines = function () {
        var i;
        var issue;
        var relatedItem;

        this._canvas.clearLines();

        this._canvas.drawLine(this._closeButton, this._tag, 0xFFFFFF, 0.10);
        this._canvas.drawLine(this._tag, this._issues[0], 0xFFFFFF, 0.10);

        for (i = 0; i < this._issues.length - 1; i ++) {
            issue = this._issues[i];
            relatedItem = this._issues[i + 1];

            this._canvas.drawLine(issue, relatedItem, 0xFFFFFF, 0.10);
        }
    };

    TagIssuesMode.prototype._scrollTo = function (delta) {
        IssuesMode.prototype._scrollTo.call(this, delta);
        this._tag.elm.y = Math.round(this._tag.issueY + this._scrollPosition);
    };

    TagIssuesMode.prototype._onStartShow = function () {
        var i;
        var issue;

        this._scrollPosition = this._scrollFinalPosition = 0;

        for (i = 0; i < this._canvas.issues.length; i ++) {
            issue = this._canvas.issues[i];
            issue.explode();
        }

        for (i = 0; i < this._issues.length; i ++) {
            issue = this._issues[i];
            issue.setMode(Issue.MODE_TAG_ISSUES);
            issue.moveTo(issue.issueX, issue.issueY);
            // so mouse over doesnt block animation
            setTimeout(this._setIssueMouseEvents.bind(this), 500, issue);
        }

        var x0 = this._tag._x0;
        var y0 = this._tag._y0;
        this._tag.setMode(Issue.MODE_TAG_TITLE);
        this._tag.issueX = this._scrollArea.x - 40;
        this._tag.issueY = this._scrollArea.y - this._issueMargin;
        this._tag.moveTo(this._tag.issueX, this._tag.issueY);
        this._tag._x0 = x0;
        this._tag._y0 = y0;

        this._closeButton.alpha = 1;

        this._drawLinesBind = this._drawLines.bind(this);
        this._canvas.renderStartS.add(this._drawLinesBind);

        $(document).on('mousewheel', this._onMouseWheel.bind(this));
        this._canvas._stage.touchstart = this._onTouchStart.bind(this);
        this._canvas._stage.touchend = this._onTouchEnd.bind(this);
        this._canvas._stage.touchmove = this._onTouching.bind(this);

        setTimeout(this._onShow.bind(this), 500);
    };

    TagIssuesMode.prototype._onStartHide = function () {
        var i;
        var issue;

        for (i = 0; i < this._canvas.issues.length; i ++) {
            issue = this._canvas.issues[i];
            issue.elm.alpha = 1;
        }

        this._closeButton.alpha = 0;
        this._canvas.renderStartS.remove(this._drawLinesBind);

        setTimeout(this._onHide.bind(this), 100);
    };

    return TagIssuesMode;
});<commit_msg>updated close button sprite<commit_after>/* global define:true */
define([
    'pixi',
    'explore/issues-mode',
    'explore/issue'
], function (
    PIXI,
    IssuesMode,
    Issue
) {
    'use strict';

    var TagIssuesMode = function (canvas) {
        this._canvas = canvas;

        return this;
    };

    TagIssuesMode.prototype = new IssuesMode();
    TagIssuesMode.prototype.constructor = TagIssuesMode;

    TagIssuesMode.prototype.init = function () {
        IssuesMode.prototype.init.call(this);

        this._drawCloseButton();

        this._margin.top += this._issueMargin + 100;
        this._updateScroll();

    };

     TagIssuesMode.prototype._drawCloseButton = function () {
        this._closeButton = new PIXI.DisplayObjectContainer();

        var texture = PIXI.Texture.fromImage('/images/icons/png/close.png');
        var img = new PIXI.Sprite(texture);
        img.x = -25;
        img.y = -25;
        this._closeButton.addChild(img);

        this._closeButton.x = (this._canvas.canvasSize.x / 2) - 65;
        this._closeButton.y = -(this._canvas.canvasSize.y / 2) + 65;
        this._closeButton.alpha = 0;
        this._closeButton.elm = this._closeButton; // hack
        this._closeButton.interactive = true;
        this._closeButton.buttonMode = true;
        this._closeButton.mousedown = this._closeButton.tap = this._onPressClose.bind(this);

        this._closeButtonContainer = new PIXI.DisplayObjectContainer();
        this._closeButtonContainer.x = this._canvas.canvasSize.x / 2;
        this._closeButtonContainer.y = this._canvas.canvasSize.y / 2;
        this._closeButtonContainer.addChild(this._closeButton);
        this._canvas.addChild(this._closeButtonContainer);
     };

    TagIssuesMode.prototype.setTag = function (data) {
        this._tag = this._canvas.getElementByData(data);

        this._issues = [];
        var related = data.getRelated();
        for (var i = 0; i < related.length; i ++) {
            this._issues.push(this._canvas.getElementByData(related[i]));
        }

        this._updateScroll();
    };

    TagIssuesMode.prototype._onPressClose = function () {
        this.hide();
    };

    TagIssuesMode.prototype._drawLines = function () {
        var i;
        var issue;
        var relatedItem;

        this._canvas.clearLines();

        this._canvas.drawLine(this._closeButton, this._tag, 0xFFFFFF, 0.10);
        this._canvas.drawLine(this._tag, this._issues[0], 0xFFFFFF, 0.10);

        for (i = 0; i < this._issues.length - 1; i ++) {
            issue = this._issues[i];
            relatedItem = this._issues[i + 1];

            this._canvas.drawLine(issue, relatedItem, 0xFFFFFF, 0.10);
        }
    };

    TagIssuesMode.prototype._scrollTo = function (delta) {
        IssuesMode.prototype._scrollTo.call(this, delta);
        this._tag.elm.y = Math.round(this._tag.issueY + this._scrollPosition);
    };

    TagIssuesMode.prototype._onStartShow = function () {
        var i;
        var issue;

        this._scrollPosition = this._scrollFinalPosition = 0;

        for (i = 0; i < this._canvas.issues.length; i ++) {
            issue = this._canvas.issues[i];
            issue.explode();
        }

        for (i = 0; i < this._issues.length; i ++) {
            issue = this._issues[i];
            issue.setMode(Issue.MODE_TAG_ISSUES);
            issue.moveTo(issue.issueX, issue.issueY);
            // so mouse over doesnt block animation
            setTimeout(this._setIssueMouseEvents.bind(this), 500, issue);
        }

        var x0 = this._tag._x0;
        var y0 = this._tag._y0;
        this._tag.setMode(Issue.MODE_TAG_TITLE);
        this._tag.issueX = this._scrollArea.x - 40;
        this._tag.issueY = this._scrollArea.y - this._issueMargin;
        this._tag.moveTo(this._tag.issueX, this._tag.issueY);
        this._tag._x0 = x0;
        this._tag._y0 = y0;

        this._closeButton.alpha = 1;

        this._drawLinesBind = this._drawLines.bind(this);
        this._canvas.renderStartS.add(this._drawLinesBind);

        $(document).on('mousewheel', this._onMouseWheel.bind(this));
        this._canvas._stage.touchstart = this._onTouchStart.bind(this);
        this._canvas._stage.touchend = this._onTouchEnd.bind(this);
        this._canvas._stage.touchmove = this._onTouching.bind(this);

        setTimeout(this._onShow.bind(this), 500);
    };

    TagIssuesMode.prototype._onStartHide = function () {
        var i;
        var issue;

        for (i = 0; i < this._canvas.issues.length; i ++) {
            issue = this._canvas.issues[i];
            issue.elm.alpha = 1;
        }

        this._closeButton.alpha = 0;
        this._canvas.renderStartS.remove(this._drawLinesBind);

        setTimeout(this._onHide.bind(this), 100);
    };

    return TagIssuesMode;
});<|endoftext|>


<commit_before>export default class Nativetable {

  /**
   * Data source filtered by filters
   * Getter
   *
   * @return {Object[]}
   */
  get filtered() {
    return this.sources
  }

  /**
   * Colum's nouns getter
   *
   * @return {string[]} - colum's nouns
   */
  get columns() {
    let headers = this.options.columns || []

    if (headers.length > 0) {
      return headers
    }

    this.filtered.forEach((el) => {
      let tmpHeaders = Object.keys(el)

      for (let col of tmpHeaders) {
        if (headers.indexOf(col) !== -1) {
          continue
        }

        headers.push(col)
      }
    })

    this.options.columns = headers
    return this.options.columns
  }

  /**
   * Colum's nouns setter
   *
   * @param {string[]} value - colum's nouns
   */
  set columns(value) {
    this.options.columns = []

    if (value == null) {
      return
    }

    for (let noun of value) {
      if (typeof noun === 'string') {
        this.options.columns.push(noun)
      }
    }
  }

  /**
   * @param {string}    id                  - identifiant of
 tag targeted
   * @param {Object}    options             - options of Nativetable
   * @param {Object[]}  options.datasource  - array of source values
   * @param {Object}    options.filters     - filters to applies
   * @param {string[]}  options.columns      - column's nouns
   *
   * @throws {TypeError} if the id parameter is invalid
   *
   * @return {Nativetable} - an instance of Nativetable
   */
  constructor(id, { sources = [], filters = {}, columns = [] } = {}) {
    this.options = {}

    if (typeof id !== 'string' || document.getElementById(id) == null) {
      throw new TypeError('First parameter of Nativetable need to be a valid tag ID.')
    }

    this.options.id = id
    this.options.box = document.getElementById(id)
    this.columns = columns
    this.sources = sources

    this.draw()
  }

  /**
   * Draw HTML table.
   */
  draw() {
    let headerstr = ''
    let bodystr = ''
    for (let name of this.columns) {
      headerstr += `

        ${name}
      	`
    }

    headerstr = `

      ${headerstr}

`

    for (let row of this.filtered) {
      let rowstr = ''
      for (let name of this.columns) {
        let val = typeof row[name] === 'undefined' ? '' : row[name]
        rowstr += `

          ${val}
        	`
      }

      bodystr += `

        ${rowstr}

`
    }

    this.options.box.innerHTML = `

        ${headerstr}

        ${bodystr}

`
  }

  /**
   * Return object signature in b64
   *
   * @param {Object} obj - object to sign
   *
   * @return {string} - object signature
   */
  objectSignature(obj) {
    return btoa(JSON.stringify(obj, this.columns))
  }
}
<commit_msg>paginedRows function<commit_after>export default class Nativetable {

  /**
   * Data source filtered by filters
   * Getter
   *
   * @return {Object[]}
   */
  get filtered() {
    return this.sources
  }

  /**
   * Colum's nouns getter
   *
   * @return {string[]} - colum's nouns
   */
  get columns() {
    let headers = this.options.columns || []

    if (headers.length > 0) {
      return headers
    }

    this.filtered.forEach((el) => {
      let tmpHeaders = Object.keys(el)

      for (let col of tmpHeaders) {
        if (headers.indexOf(col) !== -1) {
          continue
        }

        headers.push(col)
      }
    })

    this.options.columns = headers
    return this.options.columns
  }

  /**
   * Colum's nouns setter
   *
   * @param {string[]} value - colum's nouns
   */
  set columns(value) {
    this.options.columns = []

    if (value == null) {
      return
    }

    for (let noun of value) {
      if (typeof noun === 'string') {
        this.options.columns.push(noun)
      }
    }
  }

  /**
   * @param {string}    id                  - identifiant of
 tag targeted
   * @param {Object}    options             - options of Nativetable
   * @param {Object[]}  options.datasource  - array of source values
   * @param {Object}    options.filters     - filters to applies
   * @param {string[]}  options.columns      - column's nouns
   *
   * @throws {TypeError} if the id parameter is invalid
   *
   * @return {Nativetable} - an instance of Nativetable
   */
  constructor(id, { sources = [], filters = {}, columns = [], pagination = {} } = {}) {
    this.options = {}

    if (typeof id !== 'string' || document.getElementById(id) == null) {
      throw new TypeError('First parameter of Nativetable need to be a valid tag ID.')
    }

    this.options.id = id
    this.options.box = document.getElementById(id)
    this.options.pagination = {
      current: 0,
      nbElements: typeof pagination.nbElements === 'number' ? pagination.nbElements : -1
    }

    this.columns = columns
    this.sources = sources

    this.draw()
  }

  /**
   * Draw HTML table.
   *
   * @param {number} page - page to draw
   */
  draw(page = 0) {
    let headerstr = ''
    let bodystr = ''
    for (let name of this.columns) {
      headerstr += `

        ${name}
      	`
    }

    headerstr = `

      ${headerstr}

`

    for (let row of this.filtered) {
      let rowstr = ''
      for (let name of this.columns) {
        let val = typeof row[name] === 'undefined' ? '' : row[name]
        rowstr += `

          ${val}
        	`
      }

      bodystr += `

        ${rowstr}

`
    }

    this.options.box.innerHTML = `

        ${headerstr}

        ${bodystr}

`
  }

  paginatedRows(page = 0) {
    let nb = this.options.pagination.nbElements

    if (nb === -1) {
      return this.filtered
    }

    let firstEl = nb * page
    let elements = []

    for (let index = firstEl; index < firstEl + nb; index += 1) {
      elements.push(this.filtered[index])
    }

    return elements
  }

  /**
   * Return object signature in b64
   *
   * @param {Object} obj - object to sign
   *
   * @return {string} - object signature
   */
  objectSignature(obj) {
    return btoa(JSON.stringify(obj, this.columns))
  }
}
<|endoftext|>


<commit_before>
/**
 * Module requirements.
 */

var Transport = require('../transport')
  , parser = require('../parser')
  , debug = require('debug')('engine.transport')

/**
 * Exports the constructor.
 */

module.exports = Polling;

/**
 * HTTP polling constructor.
 *
 * @api public.
 */

function Polling (req) {
  Transport.call(this, req);
};

/**
 * Inherits from Transport.
 *
 * @api public.
 */

Polling.prototype.__proto__ = Transport.prototype;

/**
 * Transport name
 *
 * @api public
 */

Polling.prototype.name = 'polling';

/**
 * Overrides onRequest.
 *
 * @param {http.ServerRequest}
 * @api private
 */

Polling.prototype.onRequest = function (req) {
  var res = req.res;

  if ('GET' == req.method) {
    this.onPollRequest(req, res);
  } else if ('POST' == req.method) {
    this.onDataRequest(req, res);
  } else {
    res.writeHead(500);
    res.end();
  }
};

/**
 * The client sends a request awaiting for us to send data.
 *
 * @api private
 */

Polling.prototype.onPollRequest = function (req, res) {
  // if there's an ongoing poll
  if (this.req) {
    // assert: this.res, '.req and .res should be (un)set together'
    this.onError('poll overlap from client');
    res.writeHead(500);
  } else {
    this.req = req;
    this.res = res;

    var self = this;

    function onClose () {
      self.onError('poll connection closed prematurely');
    }

    function cleanup () {
      req.removeListener('close', onClose);
      self.req = self.res = null;
    }

    req.cleanup = cleanup;
    req.on('close', onClose);

    this.buffer = false;
    this.flush();
  }
};

/**
 * The client sends a request with data.
 *
 * @api private
 */

Polling.prototype.onDataRequest = function (req, res) {
  if (this.dataReq) {
    // assert: this.dataRes, '.dataReq and .dataRes should be (un)set together'
    this.onError('data request overlap from client');
    res.writeHead(500);
  } else {
    this.dataReq = req;
    this.dataRes = res;

    var chunks = ''
      , self = this

    function cleanup () {
      chunks = '';
      req.removeListener('data', onData);
      req.removeListener('end', onEnd);
      req.removeListener('close', cleanup);
      self.dataReq = self.dataRes = null;
    };

    function onClose () {
      cleanup();
      self.onError('data request connection closed prematurely');
    };

    function onData () {
      chunks += data;
    };

    function onEnd () {
      self.onData(chunks);
      res.writeHead(204);
      res.end();
      cleanup();
    };

    req.abort = cleanup;
    req.on('close', onClose);
    req.on('data', onData);
    req.on('end', onEnd);
    req.setEncoding('utf8');
  }
};

/**
 * Override end.
 *
 * @api private
 */

HTTPPolling.prototype.end = function () {
  this.clearPollTimeout();
  return HTTPTransport.prototype.end.call(this);
};

/**
 * Handles a request.
 *
 * @api private
 */

HTTPTransport.prototype.handleRequest = function (req) {
  if (req.method == 'POST') {
    var buffer = ''
      , res = req.res
      , origin = req.headers.origin
      , headers = { 'Content-Length': 1 }
      , self = this;

    req.on('data', function (data) {
      buffer += data;
    });

    req.on('end', function () {
      res.writeHead(200, headers);
      res.end('1');

      self.onData(self.postEncoded ? qs.parse(buffer).d : buffer);
    });

    if (origin) {
      // https://developer.mozilla.org/En/HTTP_Access_Control
      headers['Access-Control-Allow-Origin'] = '*';

      if (req.headers.cookie) {
        headers['Access-Control-Allow-Credentials'] = 'true';
      }
    }
  } else {
    this.response = req.res;

    if (req.method == 'GET') {
      var self = this;

      this.pollTimeout = setTimeout(function () {
        self.packet({ type: 'noop' });
        self.log.debug(self.name + ' closed due to exceeded duration');
      }, this.manager.get('polling duration') * 1000);

      this.log.debug('setting poll timeout');
    }
  }
};

/**
 * Handles data payload.
 *
 * @api private
 */

HTTPTransport.prototype.onData = function (data) {
  var messages = parser.decodePayload(data);
  this.log.debug(this.name + ' received data packet', data);

  for (var i = 0, l = messages.length; i < l; i++) {
    this.onMessage(messages[i]);
  }
};

/**
 * Closes the request-response cycle
 *
 * @api private
 */

HTTPTransport.prototype.doClose = function () {
  this.response.end();
};

/**
 * Writes a payload of messages
 *
 * @api private
 */

HTTPTransport.prototype.payload = function (msgs) {
  this.write(parser.encodePayload(msgs));
};
<commit_msg>Fixed docs<commit_after>
/**
 * Module requirements.
 */

var Transport = require('../transport')
  , parser = require('../parser')
  , debug = require('debug')('engine.transport')

/**
 * Exports the constructor.
 */

module.exports = Polling;

/**
 * HTTP polling constructor.
 *
 * @api public.
 */

function Polling (req) {
  Transport.call(this, req);
};

/**
 * Inherits from Transport.
 *
 * @api public.
 */

Polling.prototype.__proto__ = Transport.prototype;

/**
 * Transport name
 *
 * @api public
 */

Polling.prototype.name = 'polling';

/**
 * Overrides onRequest.
 *
 * @param {http.ServerRequest}
 * @api private
 */

Polling.prototype.onRequest = function (req) {
  var res = req.res;

  if ('GET' == req.method) {
    this.onPollRequest(req, res);
  } else if ('POST' == req.method) {
    this.onDataRequest(req, res);
  } else {
    res.writeHead(500);
    res.end();
  }
};

/**
 * The client sends a request awaiting for us to send data.
 *
 * @api private
 */

Polling.prototype.onPollRequest = function (req, res) {
  // if there's an ongoing poll
  if (this.req) {
    // assert: this.res, '.req and .res should be (un)set together'
    this.onError('poll overlap from client');
    res.writeHead(500);
  } else {
    this.req = req;
    this.res = res;

    var self = this;

    function onClose () {
      self.onError('poll connection closed prematurely');
    }

    function cleanup () {
      req.removeListener('close', onClose);
      self.req = self.res = null;
    }

    req.cleanup = cleanup;
    req.on('close', onClose);

    this.buffer = false;
    this.flush();
  }
};

/**
 * The client sends a request with data.
 *
 * @api private
 */

Polling.prototype.onDataRequest = function (req, res) {
  if (this.dataReq) {
    // assert: this.dataRes, '.dataReq and .dataRes should be (un)set together'
    this.onError('data request overlap from client');
    res.writeHead(500);
  } else {
    this.dataReq = req;
    this.dataRes = res;

    var chunks = ''
      , self = this

    function cleanup () {
      chunks = '';
      req.removeListener('data', onData);
      req.removeListener('end', onEnd);
      req.removeListener('close', cleanup);
      self.dataReq = self.dataRes = null;
    };

    function onClose () {
      cleanup();
      self.onError('data request connection closed prematurely');
    };

    function onData () {
      chunks += data;
    };

    function onEnd () {
      self.onData(chunks);
      res.writeHead(204);
      res.end();
      cleanup();
    };

    req.abort = cleanup;
    req.on('close', onClose);
    req.on('data', onData);
    req.on('end', onEnd);
    req.setEncoding('utf8');
  }
};

/**
 * Processes the incoming data payload.
 */

HTTPPolling.prototype.end = function () {
  this.clearPollTimeout();
  return HTTPTransport.prototype.end.call(this);
};

/**
 * Flushes buffers.
 *
 * @api private
 */

HTTPTransport.prototype.handleRequest = function (req) {
  if (req.method == 'POST') {
    var buffer = ''
      , res = req.res
      , origin = req.headers.origin
      , headers = { 'Content-Length': 1 }
      , self = this;

    req.on('data', function (data) {
      buffer += data;
    });

    req.on('end', function () {
      res.writeHead(200, headers);
      res.end('1');

      self.onData(self.postEncoded ? qs.parse(buffer).d : buffer);
    });

    if (origin) {
      // https://developer.mozilla.org/En/HTTP_Access_Control
      headers['Access-Control-Allow-Origin'] = '*';

      if (req.headers.cookie) {
        headers['Access-Control-Allow-Credentials'] = 'true';
      }
    }
  } else {
    this.response = req.res;

    if (req.method == 'GET') {
      var self = this;

      this.pollTimeout = setTimeout(function () {
        self.packet({ type: 'noop' });
        self.log.debug(self.name + ' closed due to exceeded duration');
      }, this.manager.get('polling duration') * 1000);

      this.log.debug('setting poll timeout');
    }
  }
};

/**
 * Handles data payload.
 *
 * @api private
 */

HTTPTransport.prototype.onData = function (data) {
  var messages = parser.decodePayload(data);
  this.log.debug(this.name + ' received data packet', data);

  for (var i = 0, l = messages.length; i < l; i++) {
    this.onMessage(messages[i]);
  }
};

/**
 * Closes the request-response cycle
 *
 * @api private
 */

HTTPTransport.prototype.doClose = function () {
  this.response.end();
};

/**
 * Writes a payload of messages
 *
 * @api private
 */

HTTPTransport.prototype.payload = function (msgs) {
  this.write(parser.encodePayload(msgs));
};
<|endoftext|>


<commit_before>import React, { Component } from "react";
import Modal                from "react-modal";
import NProgress            from "nprogress";

const modalStyle = {
  content : {
    top                   : "50%",
    left                  : "50%",
    right                 : "auto",
    bottom                : "auto",
    marginRight           : "-50%",
    transform             : "translate(-50%, -50%)",
  }
};

class Window extends Component {

  constructor(props) {

    super(props);

    this.state = {
      opened: this.props.opened,
      modalIsOpen: false
    }

    this.date = new Date().getDate()

  }

  canOpen() {

    return this.props.day <= this.date

  }

  loadImage(src) {

    if(document) {

      let image = document.createElement("img");

      NProgress.start();

      image.src = src

      image.onload = () => {

        NProgress.done();

      }
    }

  }

  openWindow() {

    if(this.canOpen()) {

      this.loadImage(this.props.content.url);

      this.state.opened = true

      this.setState({
        opened: true
      })

      setTimeout(() => {
        let { cover } = this.refs;
        cover.parentElement.removeChild(cover);
      }, 4000);

    }

  }

  closeModal() {

    this.state.modalIsOpen = false;
    this.setState({modalIsOpen: false});

  }

  showContent() {

    this.state.modalIsOpen = true;
    this.setState({modalIsOpen: true});

  }

  getModalContentStyle() {

    let rect = this.refs.window.getBoundingClientRect()

    return(
      {
        height: this.refs.window.offsetHeight,
        left: rect.left,
        top: rect.top,
        width: rect.width
      }
    );

  }

  render() {

    let style = this.state.opened ? { backgroundImage: "url(" + this.props.content.url + ")" } : {}

    return (

          { !this.state.opened && <svg fill="#c0392b" viewBox="0 0 200 200"><g><path d="M117.5180054 81.3359985h-4.3250046v-3.8669968c0-0.8120041-0.6579971-1.4690018-1.4700012-1.4690018s-1.4700012 0.6569977-1.4700012 1.4690018v3.8669968H89.7470016v-3.8669968C89.7470016 76.6569977 89.0889969 76 88.2770004 76c-0.810997 0-1.4690018 0.6569977-1.4690018 1.4690018v3.8669968h-4.3269958c-3.439003 0-6.2360001 2.9980011-6.2360001 6.6829987v29.2960052c0 3.685997 2.7969971 6.6849976 6.2360001 6.6849976h35.0369949c3.439003 0 6.2369995-2.9990005 6.2369995-6.6849976V88.0189972C123.7550049 84.3339996 120.9570007 81.3359985 117.5180054 81.3359985zM113.0530014 113.9550018c-0.1579971 0.3529968-0.5089951 0.5789948-0.8940048 0.5789948h-8.1469955v4.5670013c0 0.5420074-0.4379959 0.9800034-0.9789963 0.9800034h-6.0630035c-0.5419998 0-0.9790039-0.4379959-0.9790039-0.9800034v-4.5670013h-8.147995c-0.3860016 0-0.7360001-0.2269974-0.8939972-0.5789948 -0.1580048-0.352005-0.0950012-0.7630005 0.1619949-1.052002l5.9599991-6.701004h-3.2060013c-0.3769989 0-0.7210007-0.2179947-0.8839951-0.5579987 -0.163002-0.3409958-0.1150055-0.7460022 0.1230011-1.0390015l6.0379944-7.4519958h-1.7749939c-0.4029999 0-0.7630005-0.2460022-0.9120026-0.6210022 -0.1470032-0.3740005-0.0510025-0.8009949 0.2429962-1.0749969l6.6370087-6.1949997c0.3769989-0.3510056 0.9599915-0.3510056 1.336998 0l6.5250015 6.0949936c0.2649994 0.1750031 0.4379959 0.4760056 0.4379959 0.8170013 0 0.5410004-0.4379959 0.9790039-0.9789963 0.9790039 -0.0050049 0.0009995-0.0130005 0-0.0200043 0h-1.7750015l5.939003 7.3269958c0.2070007 0.1809998 0.3379974 0.4459991 0.3379974 0.7420044 0 0.5400009-0.4379959 0.9789963-0.9789963 0.9789963 -0.0049973 0.0009995-0.012001 0-0.0190048 0h-3.2049942l5.9569931 6.701004C113.1470032 113.1920013 113.2099991 113.6040039 113.0530014 113.9550018z"/></g></svg> }
          { this.state.opened &&
            <Modal
              className="c-modal"
              isOpen={this.state.modalIsOpen}
              onRequestClose={this.closeModal.bind(this)}
              overlayClassName="c-modal__overlay" >
              <button className="o-button--plain c-modal__close-button" onClick={this.closeModal.bind(this)}>×</button>

            </Modal>
          }

{this.props.day}

    );
  }
}

export default Window;<commit_msg>close modal on escape keypress<commit_after>import React, { Component } from "react";
import Modal                from "react-modal";
import NProgress            from "nprogress";

const modalStyle = {
  content : {
    top                   : "50%",
    left                  : "50%",
    right                 : "auto",
    bottom                : "auto",
    marginRight           : "-50%",
    transform             : "translate(-50%, -50%)",
  }
};

class Window extends Component {

  constructor(props) {

    super(props);

    this.state = {
      opened: this.props.opened,
      modalIsOpen: false
    }

    this.date = new Date().getDate()

  }

  canOpen() {

    return this.props.day <= this.date

  }

  loadImage(src) {

    if(document) {

      let image = document.createElement("img");

      NProgress.start();

      image.src = src

      image.onload = () => {

        NProgress.done();

      }
    }

  }

  openWindow() {

    if(this.canOpen()) {

      this.loadImage(this.props.content.url);

      this.state.opened = true

      this.setState({
        opened: true
      })

      setTimeout(() => {
        let { cover } = this.refs;
        cover.parentElement.removeChild(cover);
      }, 4000);

    }

  }

  closeModal() {

    this.state.modalIsOpen = false;
    this.setState({modalIsOpen: false});

  }

  showContent() {

    this.state.modalIsOpen = true;
    this.setState({modalIsOpen: true});

  }

  getModalContentStyle() {

    let rect = this.refs.window.getBoundingClientRect()

    return(
      {
        height: this.refs.window.offsetHeight,
        left: rect.left,
        top: rect.top,
        width: rect.width
      }
    );

  }

  modalOpened() {

    this.refs.modal.node.firstChild.firstChild.addEventListener("click", () => {
      this.closeModal();
    });

    if(document && window) {

      document.onkeydown = (e) => {

        e = e || window.event;

        if (e.keyCode == 27) {
          this.closeModal();
        }

      };

    }

  }

  render() {

    let style = this.state.opened ? { backgroundImage: "url(" + this.props.content.url + ")" } : {}

    return (

          { !this.state.opened && <svg fill="#c0392b" viewBox="0 0 200 200"><g><path d="M117.5180054 81.3359985h-4.3250046v-3.8669968c0-0.8120041-0.6579971-1.4690018-1.4700012-1.4690018s-1.4700012 0.6569977-1.4700012 1.4690018v3.8669968H89.7470016v-3.8669968C89.7470016 76.6569977 89.0889969 76 88.2770004 76c-0.810997 0-1.4690018 0.6569977-1.4690018 1.4690018v3.8669968h-4.3269958c-3.439003 0-6.2360001 2.9980011-6.2360001 6.6829987v29.2960052c0 3.685997 2.7969971 6.6849976 6.2360001 6.6849976h35.0369949c3.439003 0 6.2369995-2.9990005 6.2369995-6.6849976V88.0189972C123.7550049 84.3339996 120.9570007 81.3359985 117.5180054 81.3359985zM113.0530014 113.9550018c-0.1579971 0.3529968-0.5089951 0.5789948-0.8940048 0.5789948h-8.1469955v4.5670013c0 0.5420074-0.4379959 0.9800034-0.9789963 0.9800034h-6.0630035c-0.5419998 0-0.9790039-0.4379959-0.9790039-0.9800034v-4.5670013h-8.147995c-0.3860016 0-0.7360001-0.2269974-0.8939972-0.5789948 -0.1580048-0.352005-0.0950012-0.7630005 0.1619949-1.052002l5.9599991-6.701004h-3.2060013c-0.3769989 0-0.7210007-0.2179947-0.8839951-0.5579987 -0.163002-0.3409958-0.1150055-0.7460022 0.1230011-1.0390015l6.0379944-7.4519958h-1.7749939c-0.4029999 0-0.7630005-0.2460022-0.9120026-0.6210022 -0.1470032-0.3740005-0.0510025-0.8009949 0.2429962-1.0749969l6.6370087-6.1949997c0.3769989-0.3510056 0.9599915-0.3510056 1.336998 0l6.5250015 6.0949936c0.2649994 0.1750031 0.4379959 0.4760056 0.4379959 0.8170013 0 0.5410004-0.4379959 0.9790039-0.9789963 0.9790039 -0.0050049 0.0009995-0.0130005 0-0.0200043 0h-1.7750015l5.939003 7.3269958c0.2070007 0.1809998 0.3379974 0.4459991 0.3379974 0.7420044 0 0.5400009-0.4379959 0.9789963-0.9789963 0.9789963 -0.0049973 0.0009995-0.012001 0-0.0190048 0h-3.2049942l5.9569931 6.701004C113.1470032 113.1920013 113.2099991 113.6040039 113.0530014 113.9550018z"/></g></svg> }
          { this.state.opened &&
            <Modal
              className="c-modal"
              isOpen={this.state.modalIsOpen}
              onAfterOpen={this.modalOpened.bind(this)}
              onClick={this.closeModal.bind(this)}
              onRequestClose={this.closeModal.bind(this)}
              overlayClassName="c-modal__overlay"
              ref="modal" >
              <button className="o-button--plain c-modal__close-button" onClick={this.closeModal.bind(this)}>×</button>

            </Modal>
          }

{this.props.day}

    );
  }
}

export default Window;<|endoftext|>


<commit_before>var imageType = require('image-type'),
    getTemporaryFilePath = require('gettemporaryfilepath'),
    _ = require('underscore'),
    fs = require('fs'),
    resemble;

try {
    resemble = require('resemble');
} catch (e) {
    resemble = require('resemblejs');
}

module.exports = {
    name: 'unexpected-resemble',
    installInto: function (expect) {
        expect.addAssertion('to resemble', function (expect, subject, otherImage, value) {
            return expect.promise(function (resolve, reject) {
                if (typeof value === 'number') {
                    value = {
                        isSameDimensions: true,
                        misMatchPercentage: expect.it('to be less than', value)
                    };
                }
                var resemblance = resemble.resemble(subject).compareTo(otherImage);
                value = value ? _.extend({}, value) : {
                    isSameDimensions: true,
                    misMatchPercentage: expect.it('to be less than', 1)
                };
                ['ignoreColors', 'ignoreAntialiasing'].forEach(function (optionName) {
                    if (value[optionName]) {
                        resemblance[optionName]();
                        delete value[optionName];
                    }
                });
                resemblance.onComplete(function (data) {
                    resolve(data);
                });
            }).then(function (data) {
                var getImageDataUrl = data.getImageDataUrl;
                // These are noisy in the 'to satisfy' diff output
                delete data.getImageDataUrl;
                delete data.pngStream;
                return expect.withError(function () {
                    return expect(data, 'to satisfy', value);
                }, function (err) {
                    expect.fail({
                        diff: function (output, diff, inspect, equal) {
                            var imageByName = {
                                actual: subject,
                                expected: otherImage,
                                diff: getImageDataUrl.call(data)
                            };

                            var longestLabelLength = Object.keys(imageByName).reduce(function (longestSeenLabelLength, label) {
                                return Math.max(longestSeenLabelLength, label.length);
                            }, 0);

                            var originalDiff = (err.getDiff && err.getDiff()) || err.createDiff(output.clone(), diff, inspect, equal);
                            output.append(originalDiff.diff).nl(2);

                            Object.keys(imageByName).forEach(function (imageName) {
                                output.text(imageName, 'cyan').text(':').sp(longestLabelLength - imageName.length).sp();

                                output.block(function () {
                                    this.raw({
                                        html: function () {
                                            var image = imageByName[imageName];
                                            if (typeof image === 'string') {
                                                return '';
                                            } else {
                                                return inspect(image);
                                            }
                                        },
                                        fallback: function () {
                                            var image = imageByName[imageName];
                                            if (typeof image === 'string' && /^data:/.test(image)) {
                                                image = new Buffer(image.replace(/^data:image\/png;base64/, ''), 'base64');
                                            }
                                            if (Buffer.isBuffer(image)) {
                                                var imageInfo = imageType(image);
                                                if (fs.writeFileSync) {
                                                    var fileName = getTemporaryFilePath({ prefix: imageName + '-', suffix: '.' + imageInfo.ext });
                                                    fs.writeFileSync(fileName, image);
                                                    this.text(fileName);
                                                } else {
                                                    this.append(inspect(image));
                                                }
                                            } else {
                                                // File name or url
                                                this.text(image);
                                            }
                                        }
                                    });
                                }).nl(); // FIXME when .raw supports chaining
                            });

                            return {
                                inline: false,
                                diff: output
                            };
                        }
                    });
                });
            });
        });
    }
};
<commit_msg>Unstringify the mismatch percentage.<commit_after>var imageType = require('image-type'),
    getTemporaryFilePath = require('gettemporaryfilepath'),
    _ = require('underscore'),
    fs = require('fs'),
    resemble;

try {
    resemble = require('resemble');
} catch (e) {
    resemble = require('resemblejs');
}

module.exports = {
    name: 'unexpected-resemble',
    installInto: function (expect) {
        expect.addAssertion('to resemble', function (expect, subject, otherImage, value) {
            return expect.promise(function (resolve, reject) {
                if (typeof value === 'number') {
                    value = {
                        isSameDimensions: true,
                        misMatchPercentage: expect.it('to be less than', value)
                    };
                }
                var resemblance = resemble.resemble(subject).compareTo(otherImage);
                value = value ? _.extend({}, value) : {
                    isSameDimensions: true,
                    misMatchPercentage: expect.it('to be less than', 1)
                };
                ['ignoreColors', 'ignoreAntialiasing'].forEach(function (optionName) {
                    if (value[optionName]) {
                        resemblance[optionName]();
                        delete value[optionName];
                    }
                });
                resemblance.onComplete(resolve);
            }).then(function (data) {
                if (typeof data.misMatchPercentage === 'string') {
                    data.misMatchPercentage = parseFloat(data.misMatchPercentage);
                }

                var getImageDataUrl = data.getImageDataUrl;
                // These are noisy in the 'to satisfy' diff output
                delete data.getImageDataUrl;
                delete data.pngStream;
                return expect.withError(function () {
                    return expect(data, 'to satisfy', value);
                }, function (err) {
                    expect.fail({
                        diff: function (output, diff, inspect, equal) {
                            var imageByName = {
                                actual: subject,
                                expected: otherImage,
                                diff: getImageDataUrl.call(data)
                            };

                            var longestLabelLength = Object.keys(imageByName).reduce(function (longestSeenLabelLength, label) {
                                return Math.max(longestSeenLabelLength, label.length);
                            }, 0);

                            var originalDiff = (err.getDiff && err.getDiff()) || err.createDiff(output.clone(), diff, inspect, equal);
                            output.append(originalDiff.diff).nl(2);

                            Object.keys(imageByName).forEach(function (imageName) {
                                output.text(imageName, 'cyan').text(':').sp(longestLabelLength - imageName.length).sp();

                                output.block(function () {
                                    this.raw({
                                        html: function () {
                                            var image = imageByName[imageName];
                                            if (typeof image === 'string') {
                                                return '';
                                            } else {
                                                return inspect(image);
                                            }
                                        },
                                        fallback: function () {
                                            var image = imageByName[imageName];
                                            if (typeof image === 'string' && /^data:/.test(image)) {
                                                image = new Buffer(image.replace(/^data:image\/png;base64/, ''), 'base64');
                                            }
                                            if (Buffer.isBuffer(image)) {
                                                var imageInfo = imageType(image);
                                                if (fs.writeFileSync) {
                                                    var fileName = getTemporaryFilePath({ prefix: imageName + '-', suffix: '.' + imageInfo.ext });
                                                    fs.writeFileSync(fileName, image);
                                                    this.text(fileName);
                                                } else {
                                                    this.append(inspect(image));
                                                }
                                            } else {
                                                // File name or url
                                                this.text(image);
                                            }
                                        }
                                    });
                                }).nl(); // FIXME when .raw supports chaining
                            });

                            return {
                                inline: false,
                                diff: output
                            };
                        }
                    });
                });
            });
        });
    }
};
<|endoftext|>


<commit_before>'use strict';

const buildException = require('../exceptions/exception_factory').buildException,
    exceptions = require('../exceptions/exception_factory').exceptions;

module.exports = {
  merge: merge,
  values: values,
  areEntitiesEqual: areEntitiesEqual
};

/**
 * Merge two objects.
 * The order is important here: o1.merge(o2) means that the keys values of o2
 * will replace those identical to o1.
 * The keys that don't belong to the other object will be added.
 * @param object2 the object to be merged with.
 * @returns {Object} the object result of the merge
 */
function merge(object1, object2) {
  if (!object1 || Object.keys(object1).length === 0) {
    return object2;
  }
  if (!object2 || Object.keys(object2).length === 0) {
    return object1;
  }
  var merged = {};
  for (let key in object1) {
    if (object1.hasOwnProperty(key)) {
      merged[key] = object1[key];
    }
  }
  for (let key in object2) {
    if (object2.hasOwnProperty(key)) {
      merged[key] = object2[key];
    }
  }
  return merged;
}

function values(object) {
  if (object == null) {
    throw new buildException(exceptions.NullPointer, 'The passed object must not be nil.');
  }
  var values = [];
  for (let i = 0, keys = Object.keys(object); i < keys.length; i++) {
    values.push(object[keys[i]]);
  }
  return values;
}

/**
 * Checks whether two entities are equal
 * @param {object} first entity object
 * @param {object} second entity object
 * @return {boolean}
 */
function areEntitiesEqual(firstEntity, secondEntity) {
  if (firstEntity.fields.length !== secondEntity.fields.length
      || firstEntity.relationships.length !== secondEntity.relationships.length) {
    return false;
  }
  return areFieldsEqual(firstEntity.fields, secondEntity.fields)
    && areRelationshipsEqual(firstEntity.relationships, secondEntity.relationships);
}

/* private methods */
function areFieldsEqual(firstFields, secondFields) {
  return firstFields.every(function(field, index) {
    if (Object.keys(field).length !== Object.keys(secondFields[index]).length) {
      return false;
    }
    var secondEntityField = secondFields[index];
    return Object.keys(field).every(function(key) {
      return field[key] === secondEntityField[key];
    });
  });
}

function areRelationshipsEqual(firstRelationships, secondRelationships) {
  return firstRelationships.every(function(relationship, index) {
    if (Object.keys(relationship).length !== Object.keys(secondRelationships[index]).length) {
      return false;
    }
    var secondEntityRelationship = secondRelationships[index];
    return Object.keys(relationship).every(function(key) {
      return relationship[key] === secondEntityRelationship[key];
    });
  });
}
<commit_msg>Removed unused functions<commit_after>'use strict';

const buildException = require('../exceptions/exception_factory').buildException,
    exceptions = require('../exceptions/exception_factory').exceptions;

module.exports = {
  merge: merge,
  values: values
};

/**
 * Merge two objects.
 * The order is important here: o1.merge(o2) means that the keys values of o2
 * will replace those identical to o1.
 * The keys that don't belong to the other object will be added.
 * @param object2 the object to be merged with.
 * @returns {Object} the object result of the merge
 */
function merge(object1, object2) {
  if (!object1 || Object.keys(object1).length === 0) {
    return object2;
  }
  if (!object2 || Object.keys(object2).length === 0) {
    return object1;
  }
  var merged = {};
  for (let key in object1) {
    if (object1.hasOwnProperty(key)) {
      merged[key] = object1[key];
    }
  }
  for (let key in object2) {
    if (object2.hasOwnProperty(key)) {
      merged[key] = object2[key];
    }
  }
  return merged;
}

function values(object) {
  if (object == null) {
    throw new buildException(exceptions.NullPointer, 'The passed object must not be nil.');
  }
  var values = [];
  for (let i = 0, keys = Object.keys(object); i < keys.length; i++) {
    values.push(object[keys[i]]);
  }
  return values;
}
<|endoftext|>


<commit_before>class SettingsPage {
  constructor() {
    this._url = '/#/settings/domain-manager';
    this._togglerDomainInputButton = $('.domain--title-container .domain--input-toggler');
    this._confirmAddDomainButton = $('.domain--input-container button');
    this._domainInputContainer = $('.domain--input-container');
    this._domainsListItems = element.all(by.css('.domain--list-container table .column-records'));
    this._domainInput = $('.domain--default-container input');
    this._domainInputButton = $('.domain--default-container button');
    this._domainsSetDefaultButtonList = element.all(by.css('.domain--default-action'));
    this._domainDeleteButtons = element.all(by.css('.domain--erase-button'));
    this._defaultDomain = $('.domain--default-container .default-domain');
    this._activateButtons = element.all(by.css('.domain--activate-action'));
    this._disableButtons = element.all(by.css('.domain--disable-action'));
    this._dKimInformationButtons = element.all(by.css('.domain--dkim-info-action'));
  }

  getUrl(){
    return this._url;
  }
  clickInputToggler(){
    return this._togglerDomainInputButton.click();
  }
  clickAddDomainButton(){
    return this._confirmAddDomainButton.click();
  }
  getDomainInputContainer(){
    return this._domainInputContainer;
  }
  isDomainInputVisible(){
    var hasActiveClass = this.getDomainInputContainer()
      .getAttribute('class')
      .then(function(className) {
        return className.indexOf('active') >= 0;
      });
    var hasZeroHeight = this.getDomainInputContainer()
      .getCssValue('height')
      .then(function(heightSize) {
        return heightSize != '0px';
      });
    return Promise.all([hasActiveClass, hasZeroHeight])
      .then(function(results) {
        return results[0] && results[1];
      });
  }
  countDomainListItems(){
    return this._domainsListItems.count();
  }
  setDomain(domain){
    return this._domainInput.sendKeys(domain);
  }
  submitAddDomain(){
    return this._domainInputButton.click();
  }
  clickFirstDeleteButton(){
    return this._domainDeleteButtons.then(function(val){
      return val[1].click();
    });
  }
  getDefaultDomain(){
    return this._defaultDomain.getText();
  }
  clickSetAsDefault(){
    return this._domainsSetDefaultButtonList.then(function(val){
      return val[0].click();
    });
  }
  countActivateButtons(){
    return this._activateButtons.count();
  }
  clickFirstActivateButton (){
    return this._activateButtons.then(function(val){
      return val[0].click();
    });
  }
  countDisableButtons(){
    return this._disableButtons.count();
  }
  clickFirstDisableButton (){
    return this._disableButtons.then(function(val){
      return val[0].click();
    });
  }
  clickFirstDkimInformationButton(){
    return this._dKimInformationButtons.then(function(val){
      return val[0].click();
    });
  }
}
exports.SettingsPage = SettingsPage;
<commit_msg>DR-1036 Change how it selects the delete button<commit_after>class SettingsPage {
  constructor() {
    this._url = '/#/settings/domain-manager';
    this._togglerDomainInputButton = $('.domain--title-container .domain--input-toggler');
    this._confirmAddDomainButton = $('.domain--input-container button');
    this._domainInputContainer = $('.domain--input-container');
    this._domainsListItems = element.all(by.css('.domain--list-container table .column-records'));
    this._domainInput = $('.domain--default-container input');
    this._domainInputButton = $('.domain--default-container button');
    this._domainsSetDefaultButtonList = element.all(by.css('.domain--default-action'));
    this._domainDeleteButtons = element.all(by.css('.domain--erase-button.default'));
    this._defaultDomain = $('.domain--default-container .default-domain');
    this._activateButtons = element.all(by.css('.domain--activate-action'));
    this._disableButtons = element.all(by.css('.domain--disable-action'));
    this._dKimInformationButtons = element.all(by.css('.domain--dkim-info-action'));
  }

  getUrl(){
    return this._url;
  }
  clickInputToggler(){
    return this._togglerDomainInputButton.click();
  }
  clickAddDomainButton(){
    return this._confirmAddDomainButton.click();
  }
  getDomainInputContainer(){
    return this._domainInputContainer;
  }
  isDomainInputVisible(){
    var hasActiveClass = this.getDomainInputContainer()
      .getAttribute('class')
      .then(function(className) {
        return className.indexOf('active') >= 0;
      });
    var hasZeroHeight = this.getDomainInputContainer()
      .getCssValue('height')
      .then(function(heightSize) {
        return heightSize != '0px';
      });
    return Promise.all([hasActiveClass, hasZeroHeight])
      .then(function(results) {
        return results[0] && results[1];
      });
  }
  countDomainListItems(){
    return this._domainsListItems.count();
  }
  setDomain(domain){
    return this._domainInput.sendKeys(domain);
  }
  submitAddDomain(){
    return this._domainInputButton.click();
  }
  clickFirstDeleteButton(){
    return this._domainDeleteButtons.then(function(val){
      return val[0].click();
    });
  }
  getDefaultDomain(){
    return this._defaultDomain.getText();
  }
  clickSetAsDefault(){
    return this._domainsSetDefaultButtonList.then(function(val){
      return val[0].click();
    });
  }
  countActivateButtons(){
    return this._activateButtons.count();
  }
  clickFirstActivateButton (){
    return this._activateButtons.then(function(val){
      return val[0].click();
    });
  }
  countDisableButtons(){
    return this._disableButtons.count();
  }
  clickFirstDisableButton (){
    return this._disableButtons.then(function(val){
      return val[0].click();
    });
  }
  clickFirstDkimInformationButton(){
    return this._dKimInformationButtons.then(function(val){
      return val[0].click();
    });
  }
}
exports.SettingsPage = SettingsPage;
<|endoftext|>


<commit_before>/** @jsx etch.dom */
/* eslint react/no-unknown-property: "off" */

import etch from 'etch';
import {autobind} from 'core-decorators';
import cx from 'classnames';

import StagingView from './staging-view';
import GitLogo from './git-logo';
import CommitViewController from '../controllers/commit-view-controller';

export default class GitTabView {
  static focus = {
    ...StagingView.focus,
    ...CommitViewController.focus,
  }

  constructor(props) {
    this.props = props;
    etch.initialize(this);

    this.subscriptions = this.props.commandRegistry.add(this.element, {
      'tool-panel:unfocus': this.blur,
      'core:focus-next': this.advanceFocus,
      'core:focus-previous': this.retreatFocus,
    });
  }

  update(props) {
    this.props = props;
    return etch.update(this);
  }

  render() {
    if (this.props.repository.showGitTabInit()) {
      const inProgress = this.props.repository.showGitTabInitInProgress();
      const message = this.props.repository.hasDirectory() ?
        'Initialize this project directory with a git repository' :
        'Initialize a new project directory with a git repository';

      return (

              <GitLogo />

{message}

            <button onclick={this.initializeRepo} disabled={inProgress} className="btn btn-primary">
              {inProgress ? 'Creating repository...' : 'Create repository'}
            </button>

      );
    } else {
      const isLoading = this.props.fetchInProgress || this.props.repository.showGitTabLoading();

      return (

          <StagingView
            ref="stagingView"
            commandRegistry={this.props.commandRegistry}
            stagedChanges={this.props.stagedChanges}
            unstagedChanges={this.props.unstagedChanges}
            mergeConflicts={this.props.mergeConflicts}
            workingDirectoryPath={this.props.workingDirectoryPath}
            resolutionProgress={this.props.resolutionProgress}
            didSelectFilePath={this.props.didSelectFilePath}
            didSelectMergeConflictFile={this.props.didSelectMergeConflictFile}
            didDiveIntoFilePath={this.props.didDiveIntoFilePath}
            didDiveIntoMergeConflictPath={this.props.didDiveIntoMergeConflictPath}
            openFiles={this.props.openFiles}
            discardWorkDirChangesForPaths={this.props.discardWorkDirChangesForPaths}
            focusFilePatchView={this.props.focusFilePatchView}
            attemptFileStageOperation={this.props.attemptFileStageOperation}
            undoLastDiscard={this.props.undoLastDiscard}
            abortMerge={this.props.abortMerge}
            resolveAsOurs={this.props.resolveAsOurs}
            resolveAsTheirs={this.props.resolveAsTheirs}
            lastCommit={this.props.lastCommit}
            isLoading={this.props.isLoading}
            isAmending={this.props.isAmending}
            hasUndoHistory={this.props.hasUndoHistory}
            isMerging={this.props.isMerging}
          />
          <CommitViewController
            ref="commitViewController"
            stagedChangesExist={this.props.stagedChanges.length > 0}
            mergeConflictsExist={this.props.mergeConflicts.length > 0}
            prepareToCommit={this.props.prepareToCommit}
            commit={this.props.commit}
            amending={this.props.amending}
            setAmending={this.props.setAmending}
            abortMerge={this.props.abortMerge}
            branchName={this.props.branchName}
            commandRegistry={this.props.commandRegistry}
            notificationManager={this.props.notificationManager}
            mergeMessage={this.props.mergeMessage}
            isMerging={this.props.isMerging}
            isAmending={this.props.isAmending}
            isLoading={this.props.isLoading}
            lastCommit={this.props.lastCommit}
            repository={this.props.repository}
          />

      );
    }
  }

  destroy() {
    this.subscriptions.dispose();
    return etch.destroy(this);
  }

  @autobind
  async initializeRepo(event) {
    event.preventDefault();
    await this.props.initializeRepo();
  }

  rememberFocus(event) {
    let currentFocus = null;

    if (this.refs.stagingView) {
      currentFocus = this.refs.stagingView.rememberFocus(event);
    }

    if (!currentFocus && this.refs.commitViewController) {
      currentFocus = this.refs.commitViewController.rememberFocus(event);
    }

    return currentFocus;
  }

  setFocus(focus) {
    return this.refs.stagingView.setFocus(focus) ||
      this.refs.commitViewController.setFocus(focus);
  }

  @autobind
  blur() {
    this.props.workspace.getActivePane().activate();
  }

  @autobind
  advanceFocus() {
    if (!this.refs.stagingView.activateNextList()) {
      this.refs.commitViewController.setFocus(GitTabView.focus.EDITOR);
    }
  }

  @autobind
  retreatFocus() {
    const {stagingView, commitViewController} = this.refs;

    if (commitViewController.hasFocus()) {
      if (stagingView.activateLastList()) {
        this.setFocus(GitTabView.focus.STAGING);
      }
    } else {
      stagingView.activatePreviousList();
    }
  }

  async focusAndSelectStagingItem(filePath, stagingStatus) {
    await this.refs.stagingView.quietlySelectItem(filePath, stagingStatus);
    this.setFocus(GitTabView.focus.STAGING);
  }

  hasFocus() {
    return this.element.contains(document.activeElement);
  }

  @autobind
  quitelySelectItem(filePath, stagingStatus) {
    return this.refs.stagingView.quietlySelectItem(filePath, stagingStatus);
  }
}
<commit_msg>setFocus() tests for ref presence<commit_after>/** @jsx etch.dom */
/* eslint react/no-unknown-property: "off" */

import etch from 'etch';
import {autobind} from 'core-decorators';
import cx from 'classnames';

import StagingView from './staging-view';
import GitLogo from './git-logo';
import CommitViewController from '../controllers/commit-view-controller';

export default class GitTabView {
  static focus = {
    ...StagingView.focus,
    ...CommitViewController.focus,
  }

  constructor(props) {
    this.props = props;
    etch.initialize(this);

    this.subscriptions = this.props.commandRegistry.add(this.element, {
      'tool-panel:unfocus': this.blur,
      'core:focus-next': this.advanceFocus,
      'core:focus-previous': this.retreatFocus,
    });
  }

  update(props) {
    this.props = props;
    return etch.update(this);
  }

  render() {
    if (this.props.repository.showGitTabInit()) {
      const inProgress = this.props.repository.showGitTabInitInProgress();
      const message = this.props.repository.hasDirectory() ?
        'Initialize this project directory with a git repository' :
        'Initialize a new project directory with a git repository';

      return (

              <GitLogo />

{message}

            <button onclick={this.initializeRepo} disabled={inProgress} className="btn btn-primary">
              {inProgress ? 'Creating repository...' : 'Create repository'}
            </button>

      );
    } else {
      const isLoading = this.props.fetchInProgress || this.props.repository.showGitTabLoading();

      return (

          <StagingView
            ref="stagingView"
            commandRegistry={this.props.commandRegistry}
            stagedChanges={this.props.stagedChanges}
            unstagedChanges={this.props.unstagedChanges}
            mergeConflicts={this.props.mergeConflicts}
            workingDirectoryPath={this.props.workingDirectoryPath}
            resolutionProgress={this.props.resolutionProgress}
            didSelectFilePath={this.props.didSelectFilePath}
            didSelectMergeConflictFile={this.props.didSelectMergeConflictFile}
            didDiveIntoFilePath={this.props.didDiveIntoFilePath}
            didDiveIntoMergeConflictPath={this.props.didDiveIntoMergeConflictPath}
            openFiles={this.props.openFiles}
            discardWorkDirChangesForPaths={this.props.discardWorkDirChangesForPaths}
            focusFilePatchView={this.props.focusFilePatchView}
            attemptFileStageOperation={this.props.attemptFileStageOperation}
            undoLastDiscard={this.props.undoLastDiscard}
            abortMerge={this.props.abortMerge}
            resolveAsOurs={this.props.resolveAsOurs}
            resolveAsTheirs={this.props.resolveAsTheirs}
            lastCommit={this.props.lastCommit}
            isLoading={this.props.isLoading}
            isAmending={this.props.isAmending}
            hasUndoHistory={this.props.hasUndoHistory}
            isMerging={this.props.isMerging}
          />
          <CommitViewController
            ref="commitViewController"
            stagedChangesExist={this.props.stagedChanges.length > 0}
            mergeConflictsExist={this.props.mergeConflicts.length > 0}
            prepareToCommit={this.props.prepareToCommit}
            commit={this.props.commit}
            amending={this.props.amending}
            setAmending={this.props.setAmending}
            abortMerge={this.props.abortMerge}
            branchName={this.props.branchName}
            commandRegistry={this.props.commandRegistry}
            notificationManager={this.props.notificationManager}
            mergeMessage={this.props.mergeMessage}
            isMerging={this.props.isMerging}
            isAmending={this.props.isAmending}
            isLoading={this.props.isLoading}
            lastCommit={this.props.lastCommit}
            repository={this.props.repository}
          />

      );
    }
  }

  destroy() {
    this.subscriptions.dispose();
    return etch.destroy(this);
  }

  @autobind
  async initializeRepo(event) {
    event.preventDefault();
    await this.props.initializeRepo();
  }

  rememberFocus(event) {
    let currentFocus = null;

    if (this.refs.stagingView) {
      currentFocus = this.refs.stagingView.rememberFocus(event);
    }

    if (!currentFocus && this.refs.commitViewController) {
      currentFocus = this.refs.commitViewController.rememberFocus(event);
    }

    return currentFocus;
  }

  setFocus(focus) {
    if (this.refs.stagingView) {
      if (this.refs.stagingView.setFocus(focus)) {
        return true;
      }
    }

    if (this.refs.commitViewController) {
      if (this.refs.commitViewController.setFocus(focus)) {
        return true;
      }
    }

    return false;
  }

  @autobind
  blur() {
    this.props.workspace.getActivePane().activate();
  }

  @autobind
  advanceFocus() {
    if (!this.refs.stagingView.activateNextList()) {
      this.refs.commitViewController.setFocus(GitTabView.focus.EDITOR);
    }
  }

  @autobind
  retreatFocus() {
    const {stagingView, commitViewController} = this.refs;

    if (commitViewController.hasFocus()) {
      if (stagingView.activateLastList()) {
        this.setFocus(GitTabView.focus.STAGING);
      }
    } else {
      stagingView.activatePreviousList();
    }
  }

  async focusAndSelectStagingItem(filePath, stagingStatus) {
    await this.refs.stagingView.quietlySelectItem(filePath, stagingStatus);
    this.setFocus(GitTabView.focus.STAGING);
  }

  hasFocus() {
    return this.element.contains(document.activeElement);
  }

  @autobind
  quitelySelectItem(filePath, stagingStatus) {
    return this.refs.stagingView.quietlySelectItem(filePath, stagingStatus);
  }
}
<|endoftext|>


<commit_before>/** @jsx etch.dom */
/* eslint react/no-unknown-property: "off" */

import etch from 'etch';
import {autobind} from 'core-decorators';
import cx from 'classnames';

import StagingView from './staging-view';
import GitLogo from './git-logo';
import CommitViewController from '../controllers/commit-view-controller';

export default class GitTabView {
  static focus = {
    ...StagingView.focus,
    ...CommitViewController.focus,
  }

  constructor(props) {
    this.props = props;
    etch.initialize(this);

    this.subscriptions = this.props.commandRegistry.add(this.element, {
      'tool-panel:unfocus': this.blur,
      'core:focus-next': this.advanceFocus,
      'core:focus-previous': this.retreatFocus,
    });
  }

  update(props) {
    this.props = props;
    return etch.update(this);
  }

  render() {
    if (this.props.repository.showGitTabInit()) {
      const inProgress = this.props.repository.showGitTabInitInProgress();
      const message = this.props.repository.hasDirectory() ?
        'Initialize this project directory with a git repository' :
        'Initialize a new project directory with a git repository';

      return (

              <GitLogo />

{message}

            <button onclick={this.initializeRepo} disabled={inProgress} className="btn btn-primary">
              {inProgress ? 'Creating repository...' : 'Create repository'}
            </button>

      );
    } else {
      const isLoading = this.props.fetchInProgress || this.props.repository.showGitTabLoading();

      return (

          <StagingView
            ref="stagingView"
            commandRegistry={this.props.commandRegistry}
            stagedChanges={this.props.stagedChanges}
            unstagedChanges={this.props.unstagedChanges}
            mergeConflicts={this.props.mergeConflicts}
            workingDirectoryPath={this.props.workingDirectoryPath}
            resolutionProgress={this.props.resolutionProgress}
            didSelectFilePath={this.props.didSelectFilePath}
            didSelectMergeConflictFile={this.props.didSelectMergeConflictFile}
            didDiveIntoFilePath={this.props.didDiveIntoFilePath}
            didDiveIntoMergeConflictPath={this.props.didDiveIntoMergeConflictPath}
            openFiles={this.props.openFiles}
            discardWorkDirChangesForPaths={this.props.discardWorkDirChangesForPaths}
            focusFilePatchView={this.props.focusFilePatchView}
            attemptFileStageOperation={this.props.attemptFileStageOperation}
            undoLastDiscard={this.props.undoLastDiscard}
            abortMerge={this.props.abortMerge}
            resolveAsOurs={this.props.resolveAsOurs}
            resolveAsTheirs={this.props.resolveAsTheirs}
            lastCommit={this.props.lastCommit}
            isLoading={this.props.isLoading}
            isAmending={this.props.isAmending}
            hasUndoHistory={this.props.hasUndoHistory}
            isMerging={this.props.isMerging}
          />
          <CommitViewController
            ref="commitViewController"
            stagedChangesExist={this.props.stagedChanges.length > 0}
            mergeConflictsExist={this.props.mergeConflicts.length > 0}
            prepareToCommit={this.props.prepareToCommit}
            commit={this.props.commit}
            amending={this.props.amending}
            setAmending={this.props.setAmending}
            abortMerge={this.props.abortMerge}
            branchName={this.props.branchName}
            commandRegistry={this.props.commandRegistry}
            mergeMessage={this.props.mergeMessage}
            isMerging={this.props.isMerging}
            isAmending={this.props.isAmending}
            isLoading={this.props.isLoading}
            lastCommit={this.props.lastCommit}
            repository={this.props.repository}
          />

      );
    }
  }

  destroy() {
    this.subscriptions.dispose();
    return etch.destroy(this);
  }

  @autobind
  async initializeRepo(event) {
    event.preventDefault();
    await this.props.initializeRepo();
  }

  rememberFocus(event) {
    return this.refs.stagingView.rememberFocus(event) || this.refs.commitViewController.rememberFocus(event);
  }

  setFocus(focus) {
    return this.refs.stagingView.setFocus(focus) ||
      this.refs.commitViewController.setFocus(focus);
  }

  @autobind
  blur() {
    this.props.workspace.getActivePane().activate();
  }

  @autobind
  advanceFocus() {
    if (!this.refs.stagingView.activateNextList()) {
      this.refs.commitViewController.setFocus(GitTabView.focus.EDITOR);
    }
  }

  @autobind
  retreatFocus() {
    const {stagingView, commitViewController} = this.refs;

    if (commitViewController.hasFocus()) {
      if (stagingView.activateLastList()) {
        this.setFocus(GitTabView.focus.STAGING);
      }
    } else {
      stagingView.activatePreviousList();
    }
  }

  async focusAndSelectStagingItem(filePath, stagingStatus) {
    await this.refs.stagingView.quietlySelectItem(filePath, stagingStatus);
    this.setFocus(GitTabView.focus.STAGING);
  }

  isFocused() {
    return this.element.contains(document.activeElement);
  }

  @autobind
  quitelySelectItem(filePath, stagingStatus) {
    return this.refs.stagingView.quietlySelectItem(filePath, stagingStatus);
  }
}
<commit_msg>Rename to hasFocus() for consistency<commit_after>/** @jsx etch.dom */
/* eslint react/no-unknown-property: "off" */

import etch from 'etch';
import {autobind} from 'core-decorators';
import cx from 'classnames';

import StagingView from './staging-view';
import GitLogo from './git-logo';
import CommitViewController from '../controllers/commit-view-controller';

export default class GitTabView {
  static focus = {
    ...StagingView.focus,
    ...CommitViewController.focus,
  }

  constructor(props) {
    this.props = props;
    etch.initialize(this);

    this.subscriptions = this.props.commandRegistry.add(this.element, {
      'tool-panel:unfocus': this.blur,
      'core:focus-next': this.advanceFocus,
      'core:focus-previous': this.retreatFocus,
    });
  }

  update(props) {
    this.props = props;
    return etch.update(this);
  }

  render() {
    if (this.props.repository.showGitTabInit()) {
      const inProgress = this.props.repository.showGitTabInitInProgress();
      const message = this.props.repository.hasDirectory() ?
        'Initialize this project directory with a git repository' :
        'Initialize a new project directory with a git repository';

      return (

              <GitLogo />

{message}

            <button onclick={this.initializeRepo} disabled={inProgress} className="btn btn-primary">
              {inProgress ? 'Creating repository...' : 'Create repository'}
            </button>

      );
    } else {
      const isLoading = this.props.fetchInProgress || this.props.repository.showGitTabLoading();

      return (

          <StagingView
            ref="stagingView"
            commandRegistry={this.props.commandRegistry}
            stagedChanges={this.props.stagedChanges}
            unstagedChanges={this.props.unstagedChanges}
            mergeConflicts={this.props.mergeConflicts}
            workingDirectoryPath={this.props.workingDirectoryPath}
            resolutionProgress={this.props.resolutionProgress}
            didSelectFilePath={this.props.didSelectFilePath}
            didSelectMergeConflictFile={this.props.didSelectMergeConflictFile}
            didDiveIntoFilePath={this.props.didDiveIntoFilePath}
            didDiveIntoMergeConflictPath={this.props.didDiveIntoMergeConflictPath}
            openFiles={this.props.openFiles}
            discardWorkDirChangesForPaths={this.props.discardWorkDirChangesForPaths}
            focusFilePatchView={this.props.focusFilePatchView}
            attemptFileStageOperation={this.props.attemptFileStageOperation}
            undoLastDiscard={this.props.undoLastDiscard}
            abortMerge={this.props.abortMerge}
            resolveAsOurs={this.props.resolveAsOurs}
            resolveAsTheirs={this.props.resolveAsTheirs}
            lastCommit={this.props.lastCommit}
            isLoading={this.props.isLoading}
            isAmending={this.props.isAmending}
            hasUndoHistory={this.props.hasUndoHistory}
            isMerging={this.props.isMerging}
          />
          <CommitViewController
            ref="commitViewController"
            stagedChangesExist={this.props.stagedChanges.length > 0}
            mergeConflictsExist={this.props.mergeConflicts.length > 0}
            prepareToCommit={this.props.prepareToCommit}
            commit={this.props.commit}
            amending={this.props.amending}
            setAmending={this.props.setAmending}
            abortMerge={this.props.abortMerge}
            branchName={this.props.branchName}
            commandRegistry={this.props.commandRegistry}
            mergeMessage={this.props.mergeMessage}
            isMerging={this.props.isMerging}
            isAmending={this.props.isAmending}
            isLoading={this.props.isLoading}
            lastCommit={this.props.lastCommit}
            repository={this.props.repository}
          />

      );
    }
  }

  destroy() {
    this.subscriptions.dispose();
    return etch.destroy(this);
  }

  @autobind
  async initializeRepo(event) {
    event.preventDefault();
    await this.props.initializeRepo();
  }

  rememberFocus(event) {
    return this.refs.stagingView.rememberFocus(event) || this.refs.commitViewController.rememberFocus(event);
  }

  setFocus(focus) {
    return this.refs.stagingView.setFocus(focus) ||
      this.refs.commitViewController.setFocus(focus);
  }

  @autobind
  blur() {
    this.props.workspace.getActivePane().activate();
  }

  @autobind
  advanceFocus() {
    if (!this.refs.stagingView.activateNextList()) {
      this.refs.commitViewController.setFocus(GitTabView.focus.EDITOR);
    }
  }

  @autobind
  retreatFocus() {
    const {stagingView, commitViewController} = this.refs;

    if (commitViewController.hasFocus()) {
      if (stagingView.activateLastList()) {
        this.setFocus(GitTabView.focus.STAGING);
      }
    } else {
      stagingView.activatePreviousList();
    }
  }

  async focusAndSelectStagingItem(filePath, stagingStatus) {
    await this.refs.stagingView.quietlySelectItem(filePath, stagingStatus);
    this.setFocus(GitTabView.focus.STAGING);
  }

  hasFocus() {
    return this.element.contains(document.activeElement);
  }

  @autobind
  quitelySelectItem(filePath, stagingStatus) {
    return this.refs.stagingView.quietlySelectItem(filePath, stagingStatus);
  }
}
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.CollectionView.extend(Ember.TargetActionSupport, {
  disabled: false,

  tagName: 'ul',

  destroySortable: Ember.on('willDestroyElement', function() {
    this.removeObserver('disabled', this, this._disabledDidChange);

    this.$().sortable('destroy');
  }),

  initSortable: Ember.on('didInsertElement', function() {
    var opts = {};

    Ember.EnumerableUtils.forEach(['start', 'update'], function(callback) {
      opts[callback] = Ember.run.bind(this, callback);
    }, this);

    this.$().sortable(opts);

    this.addObserver('disabled', this, this._disabledDidChange);
    this._disabledDidChange();
  }),

  move: function(oldIndex, newIndex) {
    var content = this.get('content');

    if (content) {
      var item = content.objectAt(oldIndex);
      content.removeAt(oldIndex);
      content.insertAt(newIndex, item);

      this.sendAction('moved', item, oldIndex, newIndex);
    }
  },

  /**
   * Copied from `Ember.Component`. Read the `sendAction` documentation there
   * for more information.
   *
   * @method sendAction
   */
  sendAction: function(action) {
    var actionName;
    var contexts = Array.prototype.slice.call(arguments, 1);

    if (action === undefined) {
      actionName = this.get('action');
      Ember.assert('The default action was triggered on the component ' + this.toString() +
                   ', but the action name (' + actionName + ') was not a string.',
                   Ember.isNone(actionName) || typeof actionName === 'string');
    } else {
      actionName = this.get(action);
      Ember.assert('The ' + action + ' action was triggered on the component ' +
                   this.toString() + ', but the action name (' + actionName +
                   ') was not a string.',
                   Ember.isNone(actionName) || typeof actionName === 'string');
    }

    // If no action name for that action could be found, just abort.
    if (actionName === undefined) { return; }

    this.triggerAction({
      action: actionName,
      actionContext: contexts
    });
  },

  start: function(event, ui) {
    ui.item.data('oldIndex', ui.item.index());
  },

  targetObject: Ember.computed(function() {
    var parentView = this.get('_parentView');
    return parentView ? parentView.get('controller') : null;
  }).property('_parentView'),

  update: function(event, ui) {
    var oldIndex = ui.item.data('oldIndex');
    var newIndex = ui.item.index();

    this.move(oldIndex, newIndex);
  },

  _disabledDidChange: function() {
    this.$().sortable(this.get('disabled') ? 'disable' : 'enable');
  }
});
<commit_msg>Fix Morph-related errors in Ember 1.8.<commit_after>import Ember from 'ember';

export default Ember.CollectionView.extend(Ember.TargetActionSupport, {
  disabled: false,

  tagName: 'ul',

  destroySortable: Ember.on('willDestroyElement', function() {
    this.removeObserver('disabled', this, this._disabledDidChange);

    this.$().sortable('destroy');
  }),

  initSortable: Ember.on('didInsertElement', function() {
    var opts = {};

    Ember.EnumerableUtils.forEach(['start', 'update'], function(callback) {
      opts[callback] = Ember.run.bind(this, callback);
    }, this);

    this.$().sortable(opts);

    this.addObserver('disabled', this, this._disabledDidChange);
    this._disabledDidChange();
  }),

  move: function(oldIndex, newIndex) {
    var content = this.get('content');

    if (content) {
      var item = content.objectAt(oldIndex);

      this._disableArrayObservers(content, function() {
        content.removeAt(oldIndex);
        content.insertAt(newIndex, item);
      });

      this.sendAction('moved', item, oldIndex, newIndex);
    }
  },

  /**
   * Copied from `Ember.Component`. Read the `sendAction` documentation there
   * for more information.
   *
   * @method sendAction
   */
  sendAction: function(action) {
    var actionName;
    var contexts = Array.prototype.slice.call(arguments, 1);

    if (action === undefined) {
      actionName = this.get('action');
      Ember.assert('The default action was triggered on the component ' + this.toString() +
                   ', but the action name (' + actionName + ') was not a string.',
                   Ember.isNone(actionName) || typeof actionName === 'string');
    } else {
      actionName = this.get(action);
      Ember.assert('The ' + action + ' action was triggered on the component ' +
                   this.toString() + ', but the action name (' + actionName +
                   ') was not a string.',
                   Ember.isNone(actionName) || typeof actionName === 'string');
    }

    // If no action name for that action could be found, just abort.
    if (actionName === undefined) { return; }

    this.triggerAction({
      action: actionName,
      actionContext: contexts
    });
  },

  start: function(event, ui) {
    ui.item.data('oldIndex', ui.item.index());
  },

  targetObject: Ember.computed(function() {
    var parentView = this.get('_parentView');
    return parentView ? parentView.get('controller') : null;
  }).property('_parentView'),

  update: function(event, ui) {
    var oldIndex = ui.item.data('oldIndex');
    var newIndex = ui.item.index();

    this.move(oldIndex, newIndex);
  },

  _disableArrayObservers: function(content, callback) {
    content.removeArrayObserver(this);
    try {
      callback.call(this);
    } finally {
      content.addArrayObserver(this);
    }
  },

  _disabledDidChange: function() {
    this.$().sortable(this.get('disabled') ? 'disable' : 'enable');
  }
});
<|endoftext|>