<commit_before>/**
 * @module ol/proj/Projection
 */
import {METERS_PER_UNIT} from '../proj/Units.js';

/**
 * @typedef {Object} Options
 * @property {string} code The SRS identifier code, e.g. `EPSG:4326`.
 * @property {module:ol/proj/Units|string} [units] Units. Required unless a
 * proj4 projection is defined for `code`.
 * @property {module:ol/extent~Extent} [extent] The validity extent for the SRS.
 * @property {string} [axisOrientation='enu'] The axis orientation as specified in Proj4.
 * @property {boolean} [global=false] Whether the projection is valid for the whole globe.
 * @property {number} [metersPerUnit] The meters per unit for the SRS.
 * If not provided, the `units` are used to get the meters per unit from the {@link module:ol/proj/Units~METERS_PER_UNIT}
 * lookup table.
 * @property {module:ol/extent~Extent} [worldExtent] The world extent for the SRS.
 * @property {function(number, module:ol/coordinate~Coordinate):number} [getPointResolution]
 * Function to determine resolution at a point. The function is called with a
 * `{number}` view resolution and an `{module:ol/coordinate~Coordinate}` as arguments, and returns
 * the `{number}` resolution at the passed coordinate. If this is `undefined`,
 * the default {@link module:ol/proj#getPointResolution} function will be used.
 */

/**
 * @classdesc
 * Projection definition class. One of these is created for each projection
 * supported in the application and stored in the {@link module:ol/proj} namespace.
 * You can use these in applications, but this is not required, as API params
 * and options use {@link module:ol/proj~ProjectionLike} which means the simple string
 * code will suffice.
 *
 * You can use {@link module:ol/proj~get} to retrieve the object for a particular
 * projection.
 *
 * The library includes definitions for `EPSG:4326` and `EPSG:3857`, together
 * with the following aliases:
 * * `EPSG:4326`: CRS:84, urn:ogc:def:crs:EPSG:6.6:4326,
 *     urn:ogc:def:crs:OGC:1.3:CRS84, urn:ogc:def:crs:OGC:2:84,
 *     http://www.opengis.net/gml/srs/epsg.xml#4326,
 *     urn:x-ogc:def:crs:EPSG:4326
 * * `EPSG:3857`: EPSG:102100, EPSG:102113, EPSG:900913,
 *     urn:ogc:def:crs:EPSG:6.18:3:3857,
 *     http://www.opengis.net/gml/srs/epsg.xml#3857
 *
 * If you use [proj4js](https://github.com/proj4js/proj4js), aliases can
 * be added using `proj4.defs()`, after all required projection definitions are
 * added, call the {@link module:ol/proj/proj4~register} function.
 *
 * @constructor
 * @param {module:ol/proj/Projection~Options} options Projection options.
 * @struct
 * @api
 */
const Projection = function(options) {
  /**
   * @private
   * @type {string}
   */
  this.code_ = options.code;

  /**
   * Units of projected coordinates. When set to `TILE_PIXELS`, a
   * `this.extent_` and `this.worldExtent_` must be configured properly for each
   * tile.
   * @private
   * @type {module:ol/proj/Units}
   */
  this.units_ = /** @type {module:ol/proj/Units} */ (options.units);

  /**
   * Validity extent of the projection in projected coordinates. For projections
   * with `TILE_PIXELS` units, this is the extent of the tile in
   * tile pixel space.
   * @private
   * @type {module:ol/extent~Extent}
   */
  this.extent_ = options.extent !== undefined ? options.extent : null;

  /**
   * Extent of the world in EPSG:4326. For projections with
   * `TILE_PIXELS` units, this is the extent of the tile in
   * projected coordinate space.
   * @private
   * @type {module:ol/extent~Extent}
   */
  this.worldExtent_ = options.worldExtent !== undefined ?
    options.worldExtent : null;

  /**
   * @private
   * @type {string}
   */
  this.axisOrientation_ = options.axisOrientation !== undefined ?
    options.axisOrientation : 'enu';

  /**
   * @private
   * @type {boolean}
   */
  this.global_ = options.global !== undefined ? options.global : false;

  /**
   * @private
   * @type {boolean}
   */
  this.canWrapX_ = !!(this.global_ && this.extent_);

  /**
   * @private
   * @type {function(number, module:ol/coordinate~Coordinate):number|undefined}
   */
  this.getPointResolutionFunc_ = options.getPointResolution;

  /**
   * @private
   * @type {module:ol/tilegrid/TileGrid}
   */
  this.defaultTileGrid_ = null;

  /**
   * @private
   * @type {number|undefined}
   */
  this.metersPerUnit_ = options.metersPerUnit;
};

/**
 * @return {boolean} The projection is suitable for wrapping the x-axis
 */
Projection.prototype.canWrapX = function() {
  return this.canWrapX_;
};

/**
 * Get the code for this projection, e.g. 'EPSG:4326'.
 * @return {string} Code.
 * @api
 */
Projection.prototype.getCode = function() {
  return this.code_;
};

/**
 * Get the validity extent for this projection.
 * @return {module:ol/extent~Extent} Extent.
 * @api
 */
Projection.prototype.getExtent = function() {
  return this.extent_;
};

/**
 * Get the units of this projection.
 * @return {module:ol/proj/Units} Units.
 * @api
 */
Projection.prototype.getUnits = function() {
  return this.units_;
};

/**
 * Get the amount of meters per unit of this projection.  If the projection is
 * not configured with `metersPerUnit` or a units identifier, the return is
 * `undefined`.
 * @return {number|undefined} Meters.
 * @api
 */
Projection.prototype.getMetersPerUnit = function() {
  return this.metersPerUnit_ || METERS_PER_UNIT[this.units_];
};

/**
 * Get the world extent for this projection.
 * @return {module:ol/extent~Extent} Extent.
 * @api
 */
Projection.prototype.getWorldExtent = function() {
  return this.worldExtent_;
};

/**
 * Get the axis orientation of this projection.
 * Example values are:
 * enu - the default easting, northing, elevation.
 * neu - northing, easting, up - useful for "lat/long" geographic coordinates,
 *     or south orientated transverse mercator.
 * wnu - westing, northing, up - some planetary coordinate systems have
 *     "west positive" coordinate systems
 * @return {string} Axis orientation.
 * @api
 */
Projection.prototype.getAxisOrientation = function() {
  return this.axisOrientation_;
};

/**
 * Is this projection a global projection which spans the whole world?
 * @return {boolean} Whether the projection is global.
 * @api
 */
Projection.prototype.isGlobal = function() {
  return this.global_;
};

/**
* Set if the projection is a global projection which spans the whole world
* @param {boolean} global Whether the projection is global.
* @api
*/
Projection.prototype.setGlobal = function(global) {
  this.global_ = global;
  this.canWrapX_ = !!(global && this.extent_);
};

/**
 * @return {module:ol/tilegrid/TileGrid} The default tile grid.
 */
Projection.prototype.getDefaultTileGrid = function() {
  return this.defaultTileGrid_;
};

/**
 * @param {module:ol/tilegrid/TileGrid} tileGrid The default tile grid.
 */
Projection.prototype.setDefaultTileGrid = function(tileGrid) {
  this.defaultTileGrid_ = tileGrid;
};

/**
 * Set the validity extent for this projection.
 * @param {module:ol/extent~Extent} extent Extent.
 * @api
 */
Projection.prototype.setExtent = function(extent) {
  this.extent_ = extent;
  this.canWrapX_ = !!(this.global_ && extent);
};

/**
 * Set the world extent for this projection.
 * @param {module:ol/extent~Extent} worldExtent World extent
 *     [minlon, minlat, maxlon, maxlat].
 * @api
 */
Projection.prototype.setWorldExtent = function(worldExtent) {
  this.worldExtent_ = worldExtent;
};

/**
 * Set the getPointResolution function (see {@link module:ol/proj~getPointResolution}
 * for this projection.
 * @param {function(number, module:ol/coordinate~Coordinate):number} func Function
 * @api
 */
Projection.prototype.setGetPointResolution = function(func) {
  this.getPointResolutionFunc_ = func;
};

/**
 * Get the custom point resolution function for this projection (if set).
 * @return {function(number, module:ol/coordinate~Coordinate):number|undefined} The custom point
 * resolution function (if set).
 */
Projection.prototype.getPointResolutionFunc = function() {
  return this.getPointResolutionFunc_;
};
export default Projection;
<commit_msg>Improve readability<commit_after>/**
 * @module ol/proj/Projection
 */
import {METERS_PER_UNIT} from '../proj/Units.js';

/**
 * @typedef {Object} Options
 * @property {string} code The SRS identifier code, e.g. `EPSG:4326`.
 * @property {module:ol/proj/Units|string} [units] Units. Required unless a
 * proj4 projection is defined for `code`.
 * @property {module:ol/extent~Extent} [extent] The validity extent for the SRS.
 * @property {string} [axisOrientation='enu'] The axis orientation as specified in Proj4.
 * @property {boolean} [global=false] Whether the projection is valid for the whole globe.
 * @property {number} [metersPerUnit] The meters per unit for the SRS.
 * If not provided, the `units` are used to get the meters per unit from the {@link module:ol/proj/Units~METERS_PER_UNIT}
 * lookup table.
 * @property {module:ol/extent~Extent} [worldExtent] The world extent for the SRS.
 * @property {function(number, module:ol/coordinate~Coordinate):number} [getPointResolution]
 * Function to determine resolution at a point. The function is called with a
 * `{number}` view resolution and an `{module:ol/coordinate~Coordinate}` as arguments, and returns
 * the `{number}` resolution at the passed coordinate. If this is `undefined`,
 * the default {@link module:ol/proj#getPointResolution} function will be used.
 */

/**
 * @classdesc
 * Projection definition class. One of these is created for each projection
 * supported in the application and stored in the {@link module:ol/proj} namespace.
 * You can use these in applications, but this is not required, as API params
 * and options use {@link module:ol/proj~ProjectionLike} which means the simple string
 * code will suffice.
 *
 * You can use {@link module:ol/proj~get} to retrieve the object for a particular
 * projection.
 *
 * The library includes definitions for `EPSG:4326` and `EPSG:3857`, together
 * with the following aliases:
 * * `EPSG:4326`: CRS:84, urn:ogc:def:crs:EPSG:6.6:4326,
 *     urn:ogc:def:crs:OGC:1.3:CRS84, urn:ogc:def:crs:OGC:2:84,
 *     http://www.opengis.net/gml/srs/epsg.xml#4326,
 *     urn:x-ogc:def:crs:EPSG:4326
 * * `EPSG:3857`: EPSG:102100, EPSG:102113, EPSG:900913,
 *     urn:ogc:def:crs:EPSG:6.18:3:3857,
 *     http://www.opengis.net/gml/srs/epsg.xml#3857
 *
 * If you use [proj4js](https://github.com/proj4js/proj4js), aliases can
 * be added using `proj4.defs()`. After all required projection definitions are
 * added, call the {@link module:ol/proj/proj4~register} function.
 *
 * @constructor
 * @param {module:ol/proj/Projection~Options} options Projection options.
 * @struct
 * @api
 */
const Projection = function(options) {
  /**
   * @private
   * @type {string}
   */
  this.code_ = options.code;

  /**
   * Units of projected coordinates. When set to `TILE_PIXELS`, a
   * `this.extent_` and `this.worldExtent_` must be configured properly for each
   * tile.
   * @private
   * @type {module:ol/proj/Units}
   */
  this.units_ = /** @type {module:ol/proj/Units} */ (options.units);

  /**
   * Validity extent of the projection in projected coordinates. For projections
   * with `TILE_PIXELS` units, this is the extent of the tile in
   * tile pixel space.
   * @private
   * @type {module:ol/extent~Extent}
   */
  this.extent_ = options.extent !== undefined ? options.extent : null;

  /**
   * Extent of the world in EPSG:4326. For projections with
   * `TILE_PIXELS` units, this is the extent of the tile in
   * projected coordinate space.
   * @private
   * @type {module:ol/extent~Extent}
   */
  this.worldExtent_ = options.worldExtent !== undefined ?
    options.worldExtent : null;

  /**
   * @private
   * @type {string}
   */
  this.axisOrientation_ = options.axisOrientation !== undefined ?
    options.axisOrientation : 'enu';

  /**
   * @private
   * @type {boolean}
   */
  this.global_ = options.global !== undefined ? options.global : false;

  /**
   * @private
   * @type {boolean}
   */
  this.canWrapX_ = !!(this.global_ && this.extent_);

  /**
   * @private
   * @type {function(number, module:ol/coordinate~Coordinate):number|undefined}
   */
  this.getPointResolutionFunc_ = options.getPointResolution;

  /**
   * @private
   * @type {module:ol/tilegrid/TileGrid}
   */
  this.defaultTileGrid_ = null;

  /**
   * @private
   * @type {number|undefined}
   */
  this.metersPerUnit_ = options.metersPerUnit;
};

/**
 * @return {boolean} The projection is suitable for wrapping the x-axis
 */
Projection.prototype.canWrapX = function() {
  return this.canWrapX_;
};

/**
 * Get the code for this projection, e.g. 'EPSG:4326'.
 * @return {string} Code.
 * @api
 */
Projection.prototype.getCode = function() {
  return this.code_;
};

/**
 * Get the validity extent for this projection.
 * @return {module:ol/extent~Extent} Extent.
 * @api
 */
Projection.prototype.getExtent = function() {
  return this.extent_;
};

/**
 * Get the units of this projection.
 * @return {module:ol/proj/Units} Units.
 * @api
 */
Projection.prototype.getUnits = function() {
  return this.units_;
};

/**
 * Get the amount of meters per unit of this projection.  If the projection is
 * not configured with `metersPerUnit` or a units identifier, the return is
 * `undefined`.
 * @return {number|undefined} Meters.
 * @api
 */
Projection.prototype.getMetersPerUnit = function() {
  return this.metersPerUnit_ || METERS_PER_UNIT[this.units_];
};

/**
 * Get the world extent for this projection.
 * @return {module:ol/extent~Extent} Extent.
 * @api
 */
Projection.prototype.getWorldExtent = function() {
  return this.worldExtent_;
};

/**
 * Get the axis orientation of this projection.
 * Example values are:
 * enu - the default easting, northing, elevation.
 * neu - northing, easting, up - useful for "lat/long" geographic coordinates,
 *     or south orientated transverse mercator.
 * wnu - westing, northing, up - some planetary coordinate systems have
 *     "west positive" coordinate systems
 * @return {string} Axis orientation.
 * @api
 */
Projection.prototype.getAxisOrientation = function() {
  return this.axisOrientation_;
};

/**
 * Is this projection a global projection which spans the whole world?
 * @return {boolean} Whether the projection is global.
 * @api
 */
Projection.prototype.isGlobal = function() {
  return this.global_;
};

/**
* Set if the projection is a global projection which spans the whole world
* @param {boolean} global Whether the projection is global.
* @api
*/
Projection.prototype.setGlobal = function(global) {
  this.global_ = global;
  this.canWrapX_ = !!(global && this.extent_);
};

/**
 * @return {module:ol/tilegrid/TileGrid} The default tile grid.
 */
Projection.prototype.getDefaultTileGrid = function() {
  return this.defaultTileGrid_;
};

/**
 * @param {module:ol/tilegrid/TileGrid} tileGrid The default tile grid.
 */
Projection.prototype.setDefaultTileGrid = function(tileGrid) {
  this.defaultTileGrid_ = tileGrid;
};

/**
 * Set the validity extent for this projection.
 * @param {module:ol/extent~Extent} extent Extent.
 * @api
 */
Projection.prototype.setExtent = function(extent) {
  this.extent_ = extent;
  this.canWrapX_ = !!(this.global_ && extent);
};

/**
 * Set the world extent for this projection.
 * @param {module:ol/extent~Extent} worldExtent World extent
 *     [minlon, minlat, maxlon, maxlat].
 * @api
 */
Projection.prototype.setWorldExtent = function(worldExtent) {
  this.worldExtent_ = worldExtent;
};

/**
 * Set the getPointResolution function (see {@link module:ol/proj~getPointResolution}
 * for this projection.
 * @param {function(number, module:ol/coordinate~Coordinate):number} func Function
 * @api
 */
Projection.prototype.setGetPointResolution = function(func) {
  this.getPointResolutionFunc_ = func;
};

/**
 * Get the custom point resolution function for this projection (if set).
 * @return {function(number, module:ol/coordinate~Coordinate):number|undefined} The custom point
 * resolution function (if set).
 */
Projection.prototype.getPointResolutionFunc = function() {
  return this.getPointResolutionFunc_;
};
export default Projection;
<|endoftext|>


<commit_before>'use strict'

/* @flow */

import Path from 'path'
import FS from 'fs'
import invariant from 'assert'
import promisify from 'sb-promisify'
import { exec } from 'sb-exec'
import semver from 'semver'
import { versionFromRange, getManifestPath } from './helpers'
import { readJSON } from 'motion-fs'

type Installer$Options = {
  rootDirectory: string,
  filter: Function
}

class Installer {
  options: Installer$Options;

  constructor({rootDirectory, filter}: Installer$Options) {
    invariant(typeof rootDirectory === 'string', 'rootDirectory must be a string')
    invariant(!filter || typeof filter === 'function', 'filter must be a function')

    this.options = { rootDirectory, filter }
  }
  async install(name: string): Promise<void> {
    await exec('npm', ['install', '--save', name], { cwd: this.options.rootDirectory })
  }
  async uninstall(name: string): Promise<void> {
    await exec('npm', ['uninstall', '--save', name], { cwd: this.options.rootDirectory })
  }
  async installPeerDependencies(
    name: string,
    onStarted?: ((packages: Array<Array<string>>) => void),
    onProgress?: ((packageName: string, error: ?Error) => void),
    onComplete?: (() => void)
  ): Promise<void> {
    const rootDirectory = this.options.rootDirectory
    const manifestPath = await getManifestPath(rootDirectory, name)
    const manifestContents = readJSON(manifestPath)
    const peerDependencies = manifestContents && manifestContents.peerDependencies || {}

    if (peerDependencies && typeof peerDependencies === 'object') {
      let dependencies = Object.keys(peerDependencies)
      if (this.options.filter) {
        dependencies = this.options.filter(dependencies)
      }
      const versions = dependencies.map(function(name) {
        const range = peerDependencies[name]
        const version = semver.maxSatisfying(versionFromRange(range), range)
        return [name, version]
      })

      if (onStarted) {
        onStarted(versions)
      }

      await Promise.all(versions.map(async function([name, version]) {
        try {
          await exec('npm', ['install', `${name}@${version}`], { cwd: rootDirectory })
          if (onProgress) {
            onProgress(name, null)
          }
        } catch (_) {
          if (onProgress) {
            onProgress(name, _)
          } else throw _
        }
      }))

      if (onComplete) {
        onComplete()
      }
    }
  }
}

module.exports = Installer
<commit_msg>:new: Make npm dependencies filter optional to flow<commit_after>'use strict'

/* @flow */

import Path from 'path'
import FS from 'fs'
import invariant from 'assert'
import promisify from 'sb-promisify'
import { exec } from 'sb-exec'
import semver from 'semver'
import { versionFromRange, getManifestPath } from './helpers'
import { readJSON } from 'motion-fs'

type Installer$Options = {
  rootDirectory: string,
  filter: ?Function
}

class Installer {
  options: Installer$Options;

  constructor({rootDirectory, filter}: Installer$Options) {
    invariant(typeof rootDirectory === 'string', 'rootDirectory must be a string')
    invariant(!filter || typeof filter === 'function', 'filter must be a function')

    this.options = { rootDirectory, filter }
  }
  async install(name: string): Promise<void> {
    await exec('npm', ['install', '--save', name], { cwd: this.options.rootDirectory })
  }
  async uninstall(name: string): Promise<void> {
    await exec('npm', ['uninstall', '--save', name], { cwd: this.options.rootDirectory })
  }
  async installPeerDependencies(
    name: string,
    onStarted?: ((packages: Array<Array<string>>) => void),
    onProgress?: ((packageName: string, error: ?Error) => void),
    onComplete?: (() => void)
  ): Promise<void> {
    const rootDirectory = this.options.rootDirectory
    const manifestPath = await getManifestPath(rootDirectory, name)
    const manifestContents = readJSON(manifestPath)
    const peerDependencies = manifestContents && manifestContents.peerDependencies || {}

    if (peerDependencies && typeof peerDependencies === 'object') {
      let dependencies = Object.keys(peerDependencies)
      if (this.options.filter) {
        dependencies = this.options.filter(dependencies)
      }
      const versions = dependencies.map(function(name) {
        const range = peerDependencies[name]
        const version = semver.maxSatisfying(versionFromRange(range), range)
        return [name, version]
      })

      if (onStarted) {
        onStarted(versions)
      }

      await Promise.all(versions.map(async function([name, version]) {
        try {
          await exec('npm', ['install', `${name}@${version}`], { cwd: rootDirectory })
          if (onProgress) {
            onProgress(name, null)
          }
        } catch (_) {
          if (onProgress) {
            onProgress(name, _)
          } else throw _
        }
      }))

      if (onComplete) {
        onComplete()
      }
    }
  }
}

module.exports = Installer
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
//var git-info = require('../');

// test 1
assert(true);
<commit_msg>[GIT-INFO] - :corn: tests added<commit_after>'use strict';

var assert = require('assert');
var gi = require('../');

// First argument as a string
gi('name', function(err, result) {
  assert(!err);
  assert(!Array.isArray(result));
  assert('name' in result);
  assert.equal(result.name, 'git-info');
});
<|endoftext|>


<commit_before>/*
 *  gulpfile.js
 *  ===========
 *
 *  Rather than manage one giant configuration file responsible
 *  for creating multiple tasks, each task has been broken out into
 *  its own file in gulp/tasks. Any files in that directory get
 *  automatically required below.
 *
 *  To add a new task, simply add a new task file in that directory.
 *  gulp/tasks/default.js specifies the default set of tasks to run
 *  when you run `gulp`.
 *
 */

var gulp        = require('gulp'),
    requireDir  = require('require-dir');

// Specify game project paths for tasks.
global.paths = {
    src: './src',
    out: './dist',

    get scripts() { return this.src + '/**/*.js'; },
    get jsEntry() { return this.src + '/index'; }
};

// Require all tasks in gulp/tasks, including subfolders
requireDir('./gulp/tasks', { recurse: true });

// default task
gulp.task('default', ['build']);
<commit_msg>run jshint in default task<commit_after>/*
 *  gulpfile.js
 *  ===========
 *
 *  Rather than manage one giant configuration file responsible
 *  for creating multiple tasks, each task has been broken out into
 *  its own file in gulp/tasks. Any files in that directory get
 *  automatically required below.
 *
 *  To add a new task, simply add a new task file in that directory.
 *  gulp/tasks/default.js specifies the default set of tasks to run
 *  when you run `gulp`.
 *
 */

var gulp        = require('gulp'),
    requireDir  = require('require-dir');

// Specify game project paths for tasks.
global.paths = {
    src: './src',
    out: './dist',

    get scripts() { return this.src + '/**/*.js'; },
    get jsEntry() { return this.src + '/index'; }
};

// Require all tasks in gulp/tasks, including subfolders
requireDir('./gulp/tasks', { recurse: true });

// default task
gulp.task('default', ['jshint', 'build']);
<|endoftext|>


<commit_before>//=require ./slideshow/atmo
//=require ./slideshow/lazy_page_widget
//=require ./slideshow/page_widget
//=require ./slideshow/scroller_widget
//=require ./slideshow/scroll_indicator
//=require ./slideshow/scroll_indicator_widget
//=require ./slideshow/hidden_text_indicator_widget
//=require ./slideshow/progressive_preload
//=require ./slideshow/adjacent_preparer
//=require ./slideshow/swipe_gesture
//=require ./slideshow/hide_text
//=require ./slideshow/hide_text_on_swipe
//=require ./slideshow/dom_order_scroll_navigator

pageflow.Slideshow = function($el, configurations) {
  var transitioning = false,
      preload = new pageflow.ProgressivePreload(),
      currentPage = $(),
      pages = $(),
      that = this,
      currentPageIndex;

  configurations = configurations || {};

  function transitionMutex(fn, context) {
    if (transitioning) { return; }
    transitioning = true;

    var transitionDuration = fn.call(context);

    setTimeout(function() {
      transitioning = false;
    }, transitionDuration);
  }

  function nearestPage(index) {
    var result = $(pages.get(index));

    if (!result.length) {
      return pages.last();
    }

    return result;
  }

  function currentPagePermaId() {
    return parseInt(currentPage.attr('id'), 10);
  }

  this.nextPageExists = function() {
    return this.scrollNavigator.nextPageExists(currentPage, pages);
  };

  this.previousPageExists = function() {
    return this.scrollNavigator.previousPageExists(currentPage, pages);
  };

  this.isOnLandingPage = function() {
    return currentPage.is(this.scrollNavigator.getLandingPage(pages));
  };

  this.goToLandingPage = function() {
    this.goTo(this.scrollNavigator.getLandingPage(pages));
  };

  this.back = function() {
    this.scrollNavigator.back(currentPage, pages);
  };

  this.next = function() {
    this.scrollNavigator.next(currentPage, pages);
  };

  this.parentPageExists = function() {
    return !!pageflow.entryData.getParentPagePermaIdByPagePermaId(currentPagePermaId());
  };

  this.goToParentPage = function() {
    this.goToByPermaId(pageflow.entryData.getParentPagePermaIdByPagePermaId(currentPagePermaId()));
  };

  this.goToById = function(id, options) {
    return this.goTo($el.find('[data-id=' + id + ']'), options);
  };

  this.goToByPermaId = function(permaId, options) {
    if (permaId) {
      return this.goTo($el.find('#' + permaId), options);
    }
  };

  this.goTo = function(page, options) {
    options = options || {};

    if (page.length && !page.is(currentPage)) {
      transitionMutex(function() {
        var previousPage = currentPage;
        currentPage = page;
        currentPageIndex = currentPage.index();

        var transition = options.transition ||
          this.scrollNavigator.getDefaultTransition(previousPage, currentPage, pages);

        var direction =
          this.scrollNavigator.getTransitionDirection(previousPage, currentPage, options);

        var outDuration = previousPage.page('deactivate', {
          direction: direction,
          transition: transition
        });

        var inDuration = currentPage.page('activate', {
          direction: direction,
          position: options.position,
          transition: transition
        });

        preload.start(currentPage);
        $el.trigger('slideshowchangepage', [options]);

        return Math.max(outDuration, inDuration);
      }, this);

      return true;
    }
  };

  this.goToFirstPage = function() {
    return this.goTo(pages.first());
  };

  this.update = function() {
    pages = $el.find('section.page');

    pages.each(function(index) {
      var $page = $(this);

      $page.page({
        index: index,
        configuration: configurations[$page.data('id')]
      });
    });

    ensureCurrentPage();
  };

  this.currentPage = function() {
    return currentPage;
  };

  this.currentPageConfiguration = function() {
    return currentPage.page('getConfiguration');
  };

  function ensureCurrentPage() {
    var newCurrentPage = findNewCurrentPage();

    if (newCurrentPage) {
      currentPage = newCurrentPage;
      currentPageIndex = currentPage.index();

      currentPage.page('activateAsLandingPage');
      preload.start(currentPage);
    }
  }

  function findNewCurrentPage() {
    if (!currentPage.length) {
      return that.scrollNavigator.getLandingPage(pages);
    }
    else if (!currentPage.parent().length) {
      return nearestPage(currentPageIndex);
    }
  }

  this.on = function() {
    $el.on.apply($el, arguments);
  };

  this.triggerResizeHooks = function() {
    currentPage.page('resize');
  };

  $el.on('scrollerbumpup', _.bind(function(event) {
    this.back();
  }, this));

  $el.on('scrollerbumpdown', _.bind(function(event) {
    this.next();
  }, this));

  $el.on('click', 'a.to_top', _.bind(function() {
    this.goToLandingPage();
  }, this));

  $(window).on('resize', this.triggerResizeHooks);

  pageflow.nativeScrolling.preventScrollBouncing($el);

  $el.addClass('slideshow');

  $el.find('.hidden_text_indicator').hiddenTextIndicator({parent : $('body')});
  this.on('slideshowchangepage', function() {
    pageflow.hideText.deactivate();
  });

  $el.find('.scroll_indicator').scrollIndicator({parent: this});

  this.scrollNavigator = new pageflow.DomOrderScrollNavigator(this, pageflow.entryData);
  this.preparer = pageflow.AdjacentPreparer.create(function() { return pages; }, this.scrollNavigator).attach(pageflow.events);
};

pageflow.Slideshow.setup = function(options) {
  function configurationsById(pages) {
    return _.reduce(pages, function(memo, page) {
      memo[page.id] = page.configuration;
      return memo;
    }, {});
  }

  pageflow.slides = new pageflow.Slideshow(
    options.element,
    configurationsById(options.pages)
  );

  pageflow.features.enable('slideshow', options.enabledFeatureNames || []);

  pageflow.atmo = pageflow.Atmo.create(
    pageflow.slides,
    pageflow.events,
    pageflow.audio
  );

  pageflow.history = pageflow.History.create(
    pageflow.slides,
    {simulate: options.simulateHistory}
  );

  if (options.beforeFirstUpdate) {
    options.beforeFirstUpdate();
  }

  pageflow.slides.update();
  pageflow.history.start();

  return pageflow.slides;
};
<commit_msg>Trigger event when slideshow is resized<commit_after>//=require ./slideshow/atmo
//=require ./slideshow/lazy_page_widget
//=require ./slideshow/page_widget
//=require ./slideshow/scroller_widget
//=require ./slideshow/scroll_indicator
//=require ./slideshow/scroll_indicator_widget
//=require ./slideshow/hidden_text_indicator_widget
//=require ./slideshow/progressive_preload
//=require ./slideshow/adjacent_preparer
//=require ./slideshow/swipe_gesture
//=require ./slideshow/hide_text
//=require ./slideshow/hide_text_on_swipe
//=require ./slideshow/dom_order_scroll_navigator

pageflow.Slideshow = function($el, configurations) {
  var transitioning = false,
      preload = new pageflow.ProgressivePreload(),
      currentPage = $(),
      pages = $(),
      that = this,
      currentPageIndex;

  configurations = configurations || {};

  function transitionMutex(fn, context) {
    if (transitioning) { return; }
    transitioning = true;

    var transitionDuration = fn.call(context);

    setTimeout(function() {
      transitioning = false;
    }, transitionDuration);
  }

  function nearestPage(index) {
    var result = $(pages.get(index));

    if (!result.length) {
      return pages.last();
    }

    return result;
  }

  function currentPagePermaId() {
    return parseInt(currentPage.attr('id'), 10);
  }

  this.nextPageExists = function() {
    return this.scrollNavigator.nextPageExists(currentPage, pages);
  };

  this.previousPageExists = function() {
    return this.scrollNavigator.previousPageExists(currentPage, pages);
  };

  this.isOnLandingPage = function() {
    return currentPage.is(this.scrollNavigator.getLandingPage(pages));
  };

  this.goToLandingPage = function() {
    this.goTo(this.scrollNavigator.getLandingPage(pages));
  };

  this.back = function() {
    this.scrollNavigator.back(currentPage, pages);
  };

  this.next = function() {
    this.scrollNavigator.next(currentPage, pages);
  };

  this.parentPageExists = function() {
    return !!pageflow.entryData.getParentPagePermaIdByPagePermaId(currentPagePermaId());
  };

  this.goToParentPage = function() {
    this.goToByPermaId(pageflow.entryData.getParentPagePermaIdByPagePermaId(currentPagePermaId()));
  };

  this.goToById = function(id, options) {
    return this.goTo($el.find('[data-id=' + id + ']'), options);
  };

  this.goToByPermaId = function(permaId, options) {
    if (permaId) {
      return this.goTo($el.find('#' + permaId), options);
    }
  };

  this.goTo = function(page, options) {
    options = options || {};

    if (page.length && !page.is(currentPage)) {
      transitionMutex(function() {
        var previousPage = currentPage;
        currentPage = page;
        currentPageIndex = currentPage.index();

        var transition = options.transition ||
          this.scrollNavigator.getDefaultTransition(previousPage, currentPage, pages);

        var direction =
          this.scrollNavigator.getTransitionDirection(previousPage, currentPage, options);

        var outDuration = previousPage.page('deactivate', {
          direction: direction,
          transition: transition
        });

        var inDuration = currentPage.page('activate', {
          direction: direction,
          position: options.position,
          transition: transition
        });

        preload.start(currentPage);
        $el.trigger('slideshowchangepage', [options]);

        return Math.max(outDuration, inDuration);
      }, this);

      return true;
    }
  };

  this.goToFirstPage = function() {
    return this.goTo(pages.first());
  };

  this.update = function() {
    pages = $el.find('section.page');

    pages.each(function(index) {
      var $page = $(this);

      $page.page({
        index: index,
        configuration: configurations[$page.data('id')]
      });
    });

    ensureCurrentPage();
  };

  this.currentPage = function() {
    return currentPage;
  };

  this.currentPageConfiguration = function() {
    return currentPage.page('getConfiguration');
  };

  function ensureCurrentPage() {
    var newCurrentPage = findNewCurrentPage();

    if (newCurrentPage) {
      currentPage = newCurrentPage;
      currentPageIndex = currentPage.index();

      currentPage.page('activateAsLandingPage');
      preload.start(currentPage);
    }
  }

  function findNewCurrentPage() {
    if (!currentPage.length) {
      return that.scrollNavigator.getLandingPage(pages);
    }
    else if (!currentPage.parent().length) {
      return nearestPage(currentPageIndex);
    }
  }

  this.on = function() {
    $el.on.apply($el, arguments);
  };

  this.triggerResizeHooks = function() {
    currentPage.page('resize');
    pageflow.events.trigger('resize');
  };

  $el.on('scrollerbumpup', _.bind(function(event) {
    this.back();
  }, this));

  $el.on('scrollerbumpdown', _.bind(function(event) {
    this.next();
  }, this));

  $el.on('click', 'a.to_top', _.bind(function() {
    this.goToLandingPage();
  }, this));

  $(window).on('resize', this.triggerResizeHooks);

  pageflow.nativeScrolling.preventScrollBouncing($el);

  $el.addClass('slideshow');

  $el.find('.hidden_text_indicator').hiddenTextIndicator({parent : $('body')});
  this.on('slideshowchangepage', function() {
    pageflow.hideText.deactivate();
  });

  $el.find('.scroll_indicator').scrollIndicator({parent: this});

  this.scrollNavigator = new pageflow.DomOrderScrollNavigator(this, pageflow.entryData);
  this.preparer = pageflow.AdjacentPreparer.create(function() { return pages; }, this.scrollNavigator).attach(pageflow.events);
};

pageflow.Slideshow.setup = function(options) {
  function configurationsById(pages) {
    return _.reduce(pages, function(memo, page) {
      memo[page.id] = page.configuration;
      return memo;
    }, {});
  }

  pageflow.slides = new pageflow.Slideshow(
    options.element,
    configurationsById(options.pages)
  );

  pageflow.features.enable('slideshow', options.enabledFeatureNames || []);

  pageflow.atmo = pageflow.Atmo.create(
    pageflow.slides,
    pageflow.events,
    pageflow.audio
  );

  pageflow.history = pageflow.History.create(
    pageflow.slides,
    {simulate: options.simulateHistory}
  );

  if (options.beforeFirstUpdate) {
    options.beforeFirstUpdate();
  }

  pageflow.slides.update();
  pageflow.history.start();

  return pageflow.slides;
};
<|endoftext|>


<commit_before>jQuery(document).ready(function($) {

    $('#space-move-trash').click(function() {
      $(this).addClass('disabled');
      $('form').submit();
    });

    $('#space-save-draft').click(function() {
      $('select[name=space_status]').val('draft');
      $(this).addClass('disabled');
      $('form').submit();
    });

    $('#space-save-publish').click(function() {
      $('select[name=space_status]').val('published');
      $(this).addClass('disabled');
      $('form').submit();
    });

    $('#space-save-update').click(function() {
      $(this).addClass('disabled');
      $('form').submit();
    });

    $('#space-status-change').click(function() {
      $(this).addClass('disabled');
      $('form').submit();
    });

    $('.space-add-content').click(function() {
      $(this).addClass('disabled');
      /* set content type key for redirection */
      $('#contenttype_key').val($(this).attr('data-contenttype-key'));
      $('form').submit();
    });

    $("#space-embed-code").focus(function() {
      var $this = $(this);
      $this.select();
      $this.mouseup(function() {
        /* Prevent further mouseup intervention */
        $this.unbind("mouseup");
        return false;
      });
    });

    $('.field-title').hover(function() {
        $(this).find('.field-actions').show();
        $(this).parent().find('.fa').css('display', 'block');
    }, function() {
        $(this).find('.field-actions').hide();
        $(this).parent().find('.fa').hide();
    });

    $('.field-drag').hover(function() {
        $(this).parent().find('.field-actions').show();
        $(this).find('.fa').css('display', 'block');
    }, function() {
        $(this).parent().find('.field-actions').hide();
        $(this).find('.fa').hide();
    });

  /* helper function to keep table row from collapsing when being sorted */
  var fixHelperModified = function(e, tr) {
      var $originals = tr.children();
      var $helper = tr.clone();
      $helper.children().each(function(index) {
          $(this).width($originals.eq(index).width())
      });
      return $helper;
  };

  /* make diagnosis table sortable */
  $('.table-responsive').each(function(i, obj) {
      $(this).find('tbody').sortable({
          helper: fixHelperModified,
          stop: function(event, ui) {
              weight_table($(this))
          }
      }).disableSelection();
  });

  function weight_table(tbody) {
      var weight_order = [];
      tbody.find('tr').each(function() {
          count = $(this).parent().children().index($(this)) + 1;
          //console.log(count);
          $(this).find('.weight').val(count);
          //weight_order[count] = $(this).find('.id').val();
          weight_order.push({ 'id': $(this).find('.id').val(), 'weight': count });
      });
      /* submit */
      $.ajax({
          url: 'weight-order',
          type: 'post',
          cache: false,
          headers: { 'X-CSRF-TOKEN': $('input[name=_token]').val() },
          data: { 'space_id': $('input[name="space_id"]').val(), 'weight_order': weight_order },
          success: function(return_data) {
              if (return_data.success == 'true') {
                  $('#space-edit-headline').after(
                      '
' +
                      '
' +
                      '
' +
                      return_data.message +
                      '
' +
                      '
' +
                      '
');
                  $('.alert-success').delay(3000).fadeOut();
              }
          }
      });
  }

});

<commit_msg>submit token which is stored in header meta tag<commit_after>jQuery(document).ready(function($) {

    $('#space-move-trash').click(function() {
      $(this).addClass('disabled');
      $('form').submit();
    });

    $('#space-save-draft').click(function() {
      $('select[name=space_status]').val('draft');
      $(this).addClass('disabled');
      $('form').submit();
    });

    $('#space-save-publish').click(function() {
      $('select[name=space_status]').val('published');
      $(this).addClass('disabled');
      $('form').submit();
    });

    $('#space-save-update').click(function() {
      $(this).addClass('disabled');
      $('form').submit();
    });

    $('#space-status-change').click(function() {
      $(this).addClass('disabled');
      $('form').submit();
    });

    $('.space-add-content').click(function() {
      $(this).addClass('disabled');
      /* set content type key for redirection */
      $('#contenttype_key').val($(this).attr('data-contenttype-key'));
      $('form').submit();
    });

    $("#space-embed-code").focus(function() {
      var $this = $(this);
      $this.select();
      $this.mouseup(function() {
        /* Prevent further mouseup intervention */
        $this.unbind("mouseup");
        return false;
      });
    });

    $('.field-title').hover(function() {
        $(this).find('.field-actions').show();
        $(this).parent().find('.fa').css('display', 'block');
    }, function() {
        $(this).find('.field-actions').hide();
        $(this).parent().find('.fa').hide();
    });

    $('.field-drag').hover(function() {
        $(this).parent().find('.field-actions').show();
        $(this).find('.fa').css('display', 'block');
    }, function() {
        $(this).parent().find('.field-actions').hide();
        $(this).find('.fa').hide();
    });

  /* helper function to keep table row from collapsing when being sorted */
  var fixHelperModified = function(e, tr) {
      var $originals = tr.children();
      var $helper = tr.clone();
      $helper.children().each(function(index) {
          $(this).width($originals.eq(index).width())
      });
      return $helper;
  };

  /* make diagnosis table sortable */
  $('.table-responsive').each(function(i, obj) {
      $(this).find('tbody').sortable({
          helper: fixHelperModified,
          stop: function(event, ui) {
              weight_table($(this))
          }
      }).disableSelection();
  });

  function weight_table(tbody) {
      var weight_order = [];
      tbody.find('tr').each(function() {
          count = $(this).parent().children().index($(this)) + 1;
          //console.log(count);
          $(this).find('.weight').val(count);
          //weight_order[count] = $(this).find('.id').val();
          weight_order.push({ 'id': $(this).find('.id').val(), 'weight': count });
      });
      /* submit */
      $.ajax({
          url: 'weight-order',
          type: 'post',
          cache: false,
          headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
          data: { 'space_id': $('input[name="space_id"]').val(), 'weight_order': weight_order },
          success: function(return_data) {
              if (return_data.success == 'true') {
                  $('#space-edit-headline').after(
                      '
' +
                      '
' +
                      '
' +
                      return_data.message +
                      '
' +
                      '
' +
                      '
');
                  $('.alert-success').delay(3000).fadeOut();
              }
          }
      });
  }

});

<|endoftext|>


<commit_before>(function() {
  'use strict';
  angular.module('civic.services')
    .factory('VariantRevisionsResource', VariantRevisionsResource)
    .factory('VariantRevisions', VariantRevisionsService);

  function VariantRevisionsResource($resource, $cacheFactory) {
    var cache = $cacheFactory.get('$http');

    // adding this interceptor to a route will remove cached record
    var cacheResponseInterceptor = function(response) {
      cache.remove(response.config.url);
      return response.$promise;
    };

    return $resource('/api/variants/:variantId/suggested_changes/:revisionId',
      {
        variantId: '@variantId',
        revisionId: '@revisionId'
      },
      {
        // Base Variant Revisions Resources
        query: {
          method: 'GET',
          isArray: true,
          cache: cache
        },

        get: {
          method: 'GET',
          isArray: false,
          cache: cache
        },

        getPendingFields: {
          method: 'GET',
          url: '/api/variants/:variantId/fields_with_pending_changes',
          params: {
            variantId: '@variantId'
          },
          cache: false
        },

        submitRevision: {
          method: 'POST',
          cache: false
        },

        acceptRevision: {
          method: 'POST',
          url: '/api/variants/:variantId/suggested_changes/:revisionId/accept',
          params: {
            variantId: '@variantId',
            revisionId: '@revisionId',
            force: true
          },
          cache: false
        },

        rejectRevision: {
          method: 'POST',
          url: '/api/variants/:variantId/suggested_changes/:revisionId/reject',
          params: {
            variantId: '@variantId',
            revisionId: '@revisionId',
            force: true
          },
          cache: cache
        },

        // Variant Revisions Comments Resources
        submitComment: {
          method: 'POST',
          url: '/api/variants/:variantId/suggested_changes/:revisionId/comments',
          params: {
            variantId: '@variantId',
            revisionId: '@revisionId'
          },
          cache: false
        },

        updateComment: {
          method: 'PATCH',
          url: '/api/variants/:variantId/suggested_changes/:revisionId/comments/:commentId',
          params: {
            variantId: '@variantId',
            revisionId: '@revisionId',
            commentId: '@commentId'
          },
          interceptor: {
            response: cacheResponseInterceptor
          }
        },

        queryComments: {
          method: 'GET',
          url: '/api/variants/:variantId/suggested_changes/:revisionId/comments',
          params: {
            variantId: '@variantId',
            revisionId: '@revisionId'
          },
          isArray: true,
          cache: cache
        },

        getComment: {
          method: 'GET',
          url: '/api/variants/:variantId/suggested_changes/:revisionId/comments/:commentId',
          params: {
            variantId: '@variantId',
            revisionId: '@revisionId',
            commentId: '@commentId'
          },
          isArray: false,
          cache: cache
        },

        deleteComment: {
          method: 'DELETE',
          url: '/api/variants/:variantId/suggested_changes/:revisionId/comments/:commentId',
          params: {
            variantId: '@variantId',
            revisionId: '@revisionId',
            commentId: '@commentId'
          },
          cache: false
        }
      }
    );
  }

  function VariantRevisionsService(VariantRevisionsResource,
                                   Variants,
                                   Genes,
                                   Subscriptions,
                                   $cacheFactory,
                                   $q) {
    // fetch variants cache, need to delete variant record when revision is submitted
    var cache = $cacheFactory.get('$http');

    // Base Variant Revision and Variant Revisions Collection
    var item = {};
    var parent = Variants.data.item;
    var collection = [];

    // Variant Revisions Comments
    var comment = {};
    var comments = [];

    var pendingFields = {};

    return {
      initBase: initBase,
      initRevisions: initRevisions,
      initComments: initComments,
      data: {
        item: item,
        parent: parent,
        collection: collection,
        comment: comment,
        comments: comments,
        pendingFields: pendingFields
      },

      // Variant Revisions Base
      query: query,
      get: get,
      getPendingFields: getPendingFields,
      submitRevision: submitRevision,
      acceptRevision: acceptRevision,
      rejectRevision: rejectRevision,

      // Variant Revisions Comments
      queryComments: queryComments,
      getComment: getComment,
      submitComment: submitComment,
      updateComment: updateComment,
      deleteComment: deleteComment
    };

    function initBase(variantId, revisionId) {
      return $q.all([
        query(variantId, revisionId)
      ]);
    }

    function initRevisions(variantId) {
      return $q.all([
        query(variantId)
      ]);
    }

    function initComments(variantId, revisionId) {
      return $q.all([
        query(variantId, revisionId)
      ]);
    }

    // Variant Revisions Base
    function query(variantId) {
      return VariantRevisionsResource.query({ variantId: variantId }).$promise
        .then(function(response) {
          angular.copy(response, collection);
          return response.$promise;
        });
    }
    function get(variantId, revisionId) {
      return VariantRevisionsResource.get({ variantId: variantId, revisionId: revisionId }).$promise
        .then(function(response) {
          angular.copy(response, item);
          return response.$promise;
        });
    }

    function getPendingFields(variantId) {
      return VariantRevisionsResource.getPendingFields({ variantId: variantId }).$promise
        .then(function(response) {
          angular.copy(response.toJSON(), pendingFields);
          return response.$promise;
        });
    }

    function submitRevision(reqObj) {
      return VariantRevisionsResource.submitRevision(reqObj).$promise.then(
        function(response) { // success
          cache.remove('/api/variants/' + reqObj.id + '/suggested_changes/');

          // flush gene variants and refresh (for variant menu)
          cache.remove('/api/genes/' + reqObj.gene_id + '/variants?count=999');
          Genes.queryVariants(reqObj.gene_id);

          // flush subscriptions and refresh
          cache.remove('/api/subscriptions?count=999');
          Subscriptions.query();

          return $q.when(response);
        },
        function(error) { //fail
          return $q.reject(error);
        });
    }

    function acceptRevision(variantId, revisionId) {
      return VariantRevisionsResource.acceptRevision({
        variantId: variantId,
        revisionId: revisionId
      }).$promise.then(
        function(response) {
          // flush variant cache and refresh
          cache.remove('/api/variants/' + variantId );
          Variants.get(variantId);

          // flush variant suggested_changes and refresh
          cache.remove('/api/variants/' + variantId + '/suggested_changes/');
          query(variantId);

          // flush revision and refresh
          cache.remove('/api/variants/' + variantId + '/suggested_changes/' + revisionId);
          get(variantId, revisionId);

          // flush gene variants and refresh (for variant menu)
          cache.remove('/api/genes/' + response.gene_id + '/variants?count=999');
          Genes.queryVariants(response.gene_id);

          // flush gene variant groups and refresh (for variant menu)
          cache.remove('/api/genes/' + response.gene_id + '/variant_groups');
          Genes.queryVariantGroups(response.gene_id);

          // flush subscriptions and refresh
          cache.remove('/api/subscriptions?count=999');
          Subscriptions.query();

          return $q.when(response);
        },
        function(error) {
          return $q.reject(error);
        });
    }

    function rejectRevision(variantId, revisionId) {
      return VariantRevisionsResource.rejectRevision({ variantId: variantId, revisionId: revisionId }).$promise.then(
        function(response) {
          // flush variant suggested_changes and refresh
          cache.remove('/api/variants/' + variantId + '/suggested_changes/');
          query(variantId);

          // flush revision and refresh
          cache.remove('/api/variants/' + variantId + '/suggested_changes/' + revisionId);
          get(variantId, revisionId);

          // flush gene variants and refresh (for variant menu)
          cache.remove('/api/genes/' + response.gene_id + '/variants?count=999');
          Genes.queryVariants(response.gene_id);

          // flush subscriptions and refresh
          cache.remove('/api/subscriptions?count=999');
          Subscriptions.query();

          return $q.when(response);
        },
        function(error) {
          return $q.reject(error);
        });
    }

    // Variant Revisions Comments
    function queryComments(variantId, revisionId) {
      return VariantRevisionsResource.queryComments({ variantId: variantId, revisionId: revisionId }).$promise
        .then(function(response) {
          angular.copy(response, comments);
          return response.$promise;
        });
    }
    function getComment(variantId, revisionId, commentId) {
      return VariantRevisionsResource.getComment({ variantId: variantId, revisionId: revisionId, commentId: commentId }).$promise
        .then(function(response) {
          return response.$promise;
        });
    }
    function submitComment(reqObj) {
      return VariantRevisionsResource.submitComment(reqObj).$promise
        .then(function(response) {
          cache.remove('/api/variants/' + reqObj.variantId + '/suggested_changes/' + reqObj.revisionId + '/comments');
          queryComments(reqObj.variantId, reqObj.revisionId);

          // flush subscriptions and refresh
          cache.remove('/api/subscriptions?count=999');
          Subscriptions.query();

          return response.$promise;
        });
    }
    function updateComment(reqObj) {
      return VariantRevisionsResource.updateComment(reqObj).$promise
        .then(function(response) {
          cache.remove('/api/variants/' + reqObj.variantId + '/suggested_changes/' + reqObj.revisionId + '/comments/' + reqObj.commentId );
          queryComments(reqObj.variantId, reqObj.revisionId);
          return response.$promise;
        });
    }
    function deleteComment(commentId) {
      return VariantRevisionsResource.deleteComment({ variantId: parent.id, revisionId: item.id, commentId: commentId }).$promise
        .then(function(response) {
          cache.remove('/api/variants/' + parent.id + '/suggested_changes/' + item.id + '/comments');
          queryComments(parent.id, item.id);
          return response.$promise;
        });
    }
  }
})();
<commit_msg>more cache clearing<commit_after>(function() {
  'use strict';
  angular.module('civic.services')
    .factory('VariantRevisionsResource', VariantRevisionsResource)
    .factory('VariantRevisions', VariantRevisionsService);

  function VariantRevisionsResource($resource, $cacheFactory) {
    var cache = $cacheFactory.get('$http');

    // adding this interceptor to a route will remove cached record
    var cacheResponseInterceptor = function(response) {
      cache.remove(response.config.url);
      return response.$promise;
    };

    return $resource('/api/variants/:variantId/suggested_changes/:revisionId',
      {
        variantId: '@variantId',
        revisionId: '@revisionId'
      },
      {
        // Base Variant Revisions Resources
        query: {
          method: 'GET',
          isArray: true,
          cache: cache
        },

        get: {
          method: 'GET',
          isArray: false,
          cache: cache
        },

        getPendingFields: {
          method: 'GET',
          url: '/api/variants/:variantId/fields_with_pending_changes',
          params: {
            variantId: '@variantId'
          },
          cache: false
        },

        submitRevision: {
          method: 'POST',
          cache: false
        },

        acceptRevision: {
          method: 'POST',
          url: '/api/variants/:variantId/suggested_changes/:revisionId/accept',
          params: {
            variantId: '@variantId',
            revisionId: '@revisionId',
            force: true
          },
          cache: false
        },

        rejectRevision: {
          method: 'POST',
          url: '/api/variants/:variantId/suggested_changes/:revisionId/reject',
          params: {
            variantId: '@variantId',
            revisionId: '@revisionId',
            force: true
          },
          cache: cache
        },

        // Variant Revisions Comments Resources
        submitComment: {
          method: 'POST',
          url: '/api/variants/:variantId/suggested_changes/:revisionId/comments',
          params: {
            variantId: '@variantId',
            revisionId: '@revisionId'
          },
          cache: false
        },

        updateComment: {
          method: 'PATCH',
          url: '/api/variants/:variantId/suggested_changes/:revisionId/comments/:commentId',
          params: {
            variantId: '@variantId',
            revisionId: '@revisionId',
            commentId: '@commentId'
          },
          interceptor: {
            response: cacheResponseInterceptor
          }
        },

        queryComments: {
          method: 'GET',
          url: '/api/variants/:variantId/suggested_changes/:revisionId/comments',
          params: {
            variantId: '@variantId',
            revisionId: '@revisionId'
          },
          isArray: true,
          cache: cache
        },

        getComment: {
          method: 'GET',
          url: '/api/variants/:variantId/suggested_changes/:revisionId/comments/:commentId',
          params: {
            variantId: '@variantId',
            revisionId: '@revisionId',
            commentId: '@commentId'
          },
          isArray: false,
          cache: cache
        },

        deleteComment: {
          method: 'DELETE',
          url: '/api/variants/:variantId/suggested_changes/:revisionId/comments/:commentId',
          params: {
            variantId: '@variantId',
            revisionId: '@revisionId',
            commentId: '@commentId'
          },
          cache: false
        }
      }
    );
  }

  function VariantRevisionsService(VariantRevisionsResource,
                                   Variants,
                                   Genes,
                                   Subscriptions,
                                   $cacheFactory,
                                   $q) {
    // fetch variants cache, need to delete variant record when revision is submitted
    var cache = $cacheFactory.get('$http');

    // Base Variant Revision and Variant Revisions Collection
    var item = {};
    var parent = Variants.data.item;
    var collection = [];

    // Variant Revisions Comments
    var comment = {};
    var comments = [];

    var pendingFields = {};

    return {
      initBase: initBase,
      initRevisions: initRevisions,
      initComments: initComments,
      data: {
        item: item,
        parent: parent,
        collection: collection,
        comment: comment,
        comments: comments,
        pendingFields: pendingFields
      },

      // Variant Revisions Base
      query: query,
      get: get,
      getPendingFields: getPendingFields,
      submitRevision: submitRevision,
      acceptRevision: acceptRevision,
      rejectRevision: rejectRevision,

      // Variant Revisions Comments
      queryComments: queryComments,
      getComment: getComment,
      submitComment: submitComment,
      updateComment: updateComment,
      deleteComment: deleteComment
    };

    function initBase(variantId, revisionId) {
      return $q.all([
        query(variantId, revisionId)
      ]);
    }

    function initRevisions(variantId) {
      return $q.all([
        query(variantId)
      ]);
    }

    function initComments(variantId, revisionId) {
      return $q.all([
        query(variantId, revisionId)
      ]);
    }

    // Variant Revisions Base
    function query(variantId) {
      return VariantRevisionsResource.query({ variantId: variantId }).$promise
        .then(function(response) {
          angular.copy(response, collection);
          return response.$promise;
        });
    }
    function get(variantId, revisionId) {
      return VariantRevisionsResource.get({ variantId: variantId, revisionId: revisionId }).$promise
        .then(function(response) {
          angular.copy(response, item);
          return response.$promise;
        });
    }

    function getPendingFields(variantId) {
      return VariantRevisionsResource.getPendingFields({ variantId: variantId }).$promise
        .then(function(response) {
          angular.copy(response.toJSON(), pendingFields);
          return response.$promise;
        });
    }

    function submitRevision(reqObj) {
      return VariantRevisionsResource.submitRevision(reqObj).$promise.then(
        function(response) { // success
          cache.remove('/api/variants/' + reqObj.id + '/suggested_changes/');

          // flush variants status and refresh (for variant menu)
          cache.remove('/api/genes/' + response.gene_id + '/variants_status');
          Genes.getVariantsStatus(response.gene_id);

          // flush subscriptions and refresh
          cache.remove('/api/subscriptions?count=999');
          Subscriptions.query();

          return $q.when(response);
        },
        function(error) { //fail
          return $q.reject(error);
        });
    }

    function acceptRevision(variantId, revisionId) {
      return VariantRevisionsResource.acceptRevision({
        variantId: variantId,
        revisionId: revisionId
      }).$promise.then(
        function(response) {
          // flush variant cache and refresh
          cache.remove('/api/variants/' + variantId );
          Variants.get(variantId);

          // flush variant suggested_changes and refresh
          cache.remove('/api/variants/' + variantId + '/suggested_changes/');
          query(variantId);

          // flush revision and refresh
          cache.remove('/api/variants/' + variantId + '/suggested_changes/' + revisionId);
          get(variantId, revisionId);

          // flush variants status and refresh (for variant menu)
          cache.remove('/api/genes/' + response.gene_id + '/variants_status');
          Genes.getVariantsStatus(response.gene_id);

          // flush subscriptions and refresh
          cache.remove('/api/subscriptions?count=999');
          Subscriptions.query();

          return $q.when(response);
        },
        function(error) {
          return $q.reject(error);
        });
    }

    function rejectRevision(variantId, revisionId) {
      return VariantRevisionsResource.rejectRevision({ variantId: variantId, revisionId: revisionId }).$promise.then(
        function(response) {
          // flush variant suggested_changes and refresh
          cache.remove('/api/variants/' + variantId + '/suggested_changes/');
          query(variantId);

          // flush revision and refresh
          cache.remove('/api/variants/' + variantId + '/suggested_changes/' + revisionId);
          get(variantId, revisionId);

          // flush variants status and refresh (for variant menu)
          cache.remove('/api/genes/' + response.gene_id + '/variants_status');
          Genes.getVariantsStatus(response.gene_id);

          // flush subscriptions and refresh
          cache.remove('/api/subscriptions?count=999');
          Subscriptions.query();

          return $q.when(response);
        },
        function(error) {
          return $q.reject(error);
        });
    }

    // Variant Revisions Comments
    function queryComments(variantId, revisionId) {
      return VariantRevisionsResource.queryComments({ variantId: variantId, revisionId: revisionId }).$promise
        .then(function(response) {
          angular.copy(response, comments);
          return response.$promise;
        });
    }
    function getComment(variantId, revisionId, commentId) {
      return VariantRevisionsResource.getComment({ variantId: variantId, revisionId: revisionId, commentId: commentId }).$promise
        .then(function(response) {
          return response.$promise;
        });
    }
    function submitComment(reqObj) {
      return VariantRevisionsResource.submitComment(reqObj).$promise
        .then(function(response) {
          cache.remove('/api/variants/' + reqObj.variantId + '/suggested_changes/' + reqObj.revisionId + '/comments');
          queryComments(reqObj.variantId, reqObj.revisionId);

          // flush subscriptions and refresh
          cache.remove('/api/subscriptions?count=999');
          Subscriptions.query();

          return response.$promise;
        });
    }
    function updateComment(reqObj) {
      return VariantRevisionsResource.updateComment(reqObj).$promise
        .then(function(response) {
          cache.remove('/api/variants/' + reqObj.variantId + '/suggested_changes/' + reqObj.revisionId + '/comments/' + reqObj.commentId );
          queryComments(reqObj.variantId, reqObj.revisionId);
          return response.$promise;
        });
    }
    function deleteComment(commentId) {
      return VariantRevisionsResource.deleteComment({ variantId: parent.id, revisionId: item.id, commentId: commentId }).$promise
        .then(function(response) {
          cache.remove('/api/variants/' + parent.id + '/suggested_changes/' + item.id + '/comments');
          queryComments(parent.id, item.id);
          return response.$promise;
        });
    }
  }
})();
<|endoftext|>


<commit_before>goog.provide('ol.VectorImageTile');

goog.require('ol');
goog.require('ol.Tile');
goog.require('ol.TileState');
goog.require('ol.array');
goog.require('ol.dom');
goog.require('ol.events');
goog.require('ol.extent');
goog.require('ol.events.EventType');
goog.require('ol.featureloader');

/**
 * @constructor
 * @extends {ol.Tile}
 * @param {ol.TileCoord} tileCoord Tile coordinate.
 * @param {ol.TileState} state State.
 * @param {string} src Data source url.
 * @param {ol.format.Feature} format Feature format.
 * @param {ol.TileLoadFunctionType} tileLoadFunction Tile load function.
 * @param {ol.TileCoord} urlTileCoord Wrapped tile coordinate for source urls.
 * @param {ol.TileUrlFunctionType} tileUrlFunction Tile url function.
 * @param {ol.tilegrid.TileGrid} sourceTileGrid Tile grid of the source.
 * @param {ol.tilegrid.TileGrid} tileGrid Tile grid of the renderer.
 * @param {Object.<string,ol.VectorTile>} sourceTiles Source tiles.
 * @param {number} pixelRatio Pixel ratio.
 * @param {ol.proj.Projection} projection Projection.
 * @param {function(new: ol.VectorTile, ol.TileCoord, ol.TileState, string,
 *     ol.format.Feature, ol.TileLoadFunctionType)} tileClass Class to
 *     instantiate for source tiles.
 */
ol.VectorImageTile = function(tileCoord, state, src, format, tileLoadFunction,
    urlTileCoord, tileUrlFunction, sourceTileGrid, tileGrid, sourceTiles,
    pixelRatio, projection, tileClass) {

  ol.Tile.call(this, tileCoord, state);

  /**
   * @private
   * @type {CanvasRenderingContext2D}
   */
  this.context_ = null;

  /**
   * @private
   * @type {ol.format.Feature}
   */
  this.format_ = format;

  /**
   * @private
   * @type {ol.FeatureLoader}
   */
  this.loader_;

  /**
   * @private
   * @type {ol.TileReplayState}
   */
  this.replayState_ = {
    dirty: false,
    renderedRenderOrder: null,
    renderedRevision: -1,
    renderedTileRevision: -1
  };

  /**
   * @private
   * @type {Object.<string,ol.VectorTile>}
   */
  this.sourceTiles_ = sourceTiles;

  /**
   * Keys of source tiles used by this tile. Use with {@link #getTile}.
   * @type {Array.<string>}
   */
  this.tileKeys = [];

  /**
   * @type {string}
   */
  this.src_ = src;

  /**
   * @type {ol.TileCoord}
   */
  this.wrappedTileCoord = urlTileCoord;

  /**
   * @type {Array.<ol.EventsKey>}
   */
  this.loadListenerKeys_ = [];

  if (urlTileCoord) {
    var extent = tileGrid.getTileCoordExtent(urlTileCoord);
    var resolution = tileGrid.getResolution(tileCoord[0]);
    var sourceZ = sourceTileGrid.getZForResolution(resolution);
    sourceTileGrid.forEachTileCoord(extent, sourceZ, function(sourceTileCoord) {
      var sharedExtent = ol.extent.getIntersection(extent,
          sourceTileGrid.getTileCoordExtent(sourceTileCoord));
      if (ol.extent.getWidth(sharedExtent) / resolution >= 0.5 &&
          ol.extent.getHeight(sharedExtent) / resolution >= 0.5) {
        // only include source tile if overlap is at least 1 pixel
        var sourceTileKey = sourceTileCoord.toString();
        var sourceTile = sourceTiles[sourceTileKey];
        if (!sourceTile) {
          var tileUrl = tileUrlFunction(sourceTileCoord, pixelRatio, projection);
          sourceTile = sourceTiles[sourceTileKey] = new tileClass(sourceTileCoord,
              tileUrl == undefined ? ol.TileState.EMPTY : ol.TileState.IDLE,
              tileUrl == undefined ? '' : tileUrl,
              format, tileLoadFunction);
        }
        sourceTile.consumers++;
        this.tileKeys.push(sourceTileKey);
      }
    }.bind(this));
  }

};
ol.inherits(ol.VectorImageTile, ol.Tile);

/**
 * @inheritDoc
 */
ol.VectorImageTile.prototype.disposeInternal = function() {
  for (var i = 0, ii = this.tileKeys.length; i < ii; ++i) {
    var sourceTileKey = this.tileKeys[i];
    var sourceTile = this.getTile(sourceTileKey);
    sourceTile.consumers--;
    if (sourceTile.consumers == 0) {
      delete this.sourceTiles_[sourceTileKey];
      sourceTile.dispose();
    }
  }
  this.tileKeys.length = 0;
  this.sourceTiles_ = null;
  if (this.state == ol.TileState.LOADING) {
    this.loadListenerKeys_.forEach(ol.events.unlistenByKey);
    this.loadListenerKeys_.length = 0;
  }
  if (this.interimTile) {
    this.interimTile.dispose();
  }
  this.state = ol.TileState.ABORT;
  this.changed();
  ol.Tile.prototype.disposeInternal.call(this);
};

/**
 * @return {CanvasRenderingContext2D} The rendering context.
 */
ol.VectorImageTile.prototype.getContext = function() {
  if (!this.context_) {
    this.context_ = ol.dom.createCanvasContext2D();
  }
  return this.context_;
};

/**
 * Get the Canvas for this tile.
 * @return {HTMLCanvasElement} Canvas.
 * @api
 */
ol.VectorImageTile.prototype.getImage = function() {
  return this.replayState_.renderedTileRevision == -1 ?
      null : this.context_.canvas;
};

/**
 * Get the feature format assigned for reading this tile's features.
 * @return {ol.format.Feature} Feature format.
 * @api
 */
ol.VectorImageTile.prototype.getFormat = function() {
  return this.format_;
};

/**
 * @return {ol.TileReplayState} The replay state.
 */
ol.VectorImageTile.prototype.getReplayState = function() {
  return this.replayState_;
};

/**
 * @inheritDoc
 */
ol.VectorImageTile.prototype.getKey = function() {
  return this.tileKeys.join('/') + '/' + this.src_;
};

/**
 * @param {string} tileKey Key (tileCoord) of the source tile.
 * @return {ol.VectorTile} Source tile.
 */
ol.VectorImageTile.prototype.getTile = function(tileKey) {
  return this.sourceTiles_[tileKey];
};

/**
 * @inheritDoc
 */
ol.VectorImageTile.prototype.load = function() {
  var leftToLoad = 0;
  var errors = false;
  if (this.state == ol.TileState.IDLE) {
    this.setState(ol.TileState.LOADING);
  }
  if (this.state == ol.TileState.LOADING) {
    this.tileKeys.forEach(function(sourceTileKey) {
      var sourceTile = this.getTile(sourceTileKey);
      if (sourceTile.state == ol.TileState.IDLE) {
        sourceTile.setLoader(this.loader_);
        sourceTile.load();
      } else if (sourceTile.state == ol.TileState.ERROR) {
        errors = true;
      } else if (sourceTile.state == ol.TileState.EMPTY) {
        ol.array.remove(this.tileKeys, sourceTileKey);
      }
      if (sourceTile.state == ol.TileState.LOADING) {
        var key = ol.events.listen(sourceTile, ol.events.EventType.CHANGE, function(e) {
          var state = sourceTile.getState();
          if (state == ol.TileState.LOADED ||
              state == ol.TileState.ERROR) {
            --leftToLoad;
            ol.events.unlistenByKey(key);
            ol.array.remove(this.loadListenerKeys_, key);
            if (state == ol.TileState.ERROR) {
              ol.array.remove(this.tileKeys, sourceTileKey);
              errors = true;
            }
            if (leftToLoad == 0) {
              this.setState(this.tileKeys.length > 0 ?
                  ol.TileState.LOADED : ol.TileState.ERROR);
            }
          }
        }.bind(this));
        this.loadListenerKeys_.push(key);
        ++leftToLoad;
      }
    }.bind(this));
  }
  if (leftToLoad == 0) {
    setTimeout(function() {
      this.setState(this.tileKeys.length > 0 ?
          ol.TileState.LOADED :
          (errors ? ol.TileState.ERROR : ol.TileState.EMPTY));
    }.bind(this), 0);
  }
};

/**
 * @param {ol.TileState} tileState Tile state.
 */
ol.VectorImageTile.prototype.setState = function(tileState) {
  this.state = tileState;
  this.changed();
};

/**
 * Sets the loader for a tile.
 * @param {ol.VectorTile} tile Vector tile.
 * @param {string} url URL.
 */
ol.VectorImageTile.defaultLoadFunction = function(tile, url) {
  var loader = ol.featureloader.loadFeaturesXhr(
      url, tile.getFormat(), tile.onLoad_.bind(tile), tile.onError_.bind(tile));

  tile.setLoader(loader);
};
<commit_msg>Remove unused getFormat() method and format_ member<commit_after>goog.provide('ol.VectorImageTile');

goog.require('ol');
goog.require('ol.Tile');
goog.require('ol.TileState');
goog.require('ol.array');
goog.require('ol.dom');
goog.require('ol.events');
goog.require('ol.extent');
goog.require('ol.events.EventType');
goog.require('ol.featureloader');

/**
 * @constructor
 * @extends {ol.Tile}
 * @param {ol.TileCoord} tileCoord Tile coordinate.
 * @param {ol.TileState} state State.
 * @param {string} src Data source url.
 * @param {ol.format.Feature} format Feature format.
 * @param {ol.TileLoadFunctionType} tileLoadFunction Tile load function.
 * @param {ol.TileCoord} urlTileCoord Wrapped tile coordinate for source urls.
 * @param {ol.TileUrlFunctionType} tileUrlFunction Tile url function.
 * @param {ol.tilegrid.TileGrid} sourceTileGrid Tile grid of the source.
 * @param {ol.tilegrid.TileGrid} tileGrid Tile grid of the renderer.
 * @param {Object.<string,ol.VectorTile>} sourceTiles Source tiles.
 * @param {number} pixelRatio Pixel ratio.
 * @param {ol.proj.Projection} projection Projection.
 * @param {function(new: ol.VectorTile, ol.TileCoord, ol.TileState, string,
 *     ol.format.Feature, ol.TileLoadFunctionType)} tileClass Class to
 *     instantiate for source tiles.
 */
ol.VectorImageTile = function(tileCoord, state, src, format, tileLoadFunction,
    urlTileCoord, tileUrlFunction, sourceTileGrid, tileGrid, sourceTiles,
    pixelRatio, projection, tileClass) {

  ol.Tile.call(this, tileCoord, state);

  /**
   * @private
   * @type {CanvasRenderingContext2D}
   */
  this.context_ = null;

  /**
   * @private
   * @type {ol.FeatureLoader}
   */
  this.loader_;

  /**
   * @private
   * @type {ol.TileReplayState}
   */
  this.replayState_ = {
    dirty: false,
    renderedRenderOrder: null,
    renderedRevision: -1,
    renderedTileRevision: -1
  };

  /**
   * @private
   * @type {Object.<string,ol.VectorTile>}
   */
  this.sourceTiles_ = sourceTiles;

  /**
   * Keys of source tiles used by this tile. Use with {@link #getTile}.
   * @type {Array.<string>}
   */
  this.tileKeys = [];

  /**
   * @type {string}
   */
  this.src_ = src;

  /**
   * @type {ol.TileCoord}
   */
  this.wrappedTileCoord = urlTileCoord;

  /**
   * @type {Array.<ol.EventsKey>}
   */
  this.loadListenerKeys_ = [];

  if (urlTileCoord) {
    var extent = tileGrid.getTileCoordExtent(urlTileCoord);
    var resolution = tileGrid.getResolution(tileCoord[0]);
    var sourceZ = sourceTileGrid.getZForResolution(resolution);
    sourceTileGrid.forEachTileCoord(extent, sourceZ, function(sourceTileCoord) {
      var sharedExtent = ol.extent.getIntersection(extent,
          sourceTileGrid.getTileCoordExtent(sourceTileCoord));
      if (ol.extent.getWidth(sharedExtent) / resolution >= 0.5 &&
          ol.extent.getHeight(sharedExtent) / resolution >= 0.5) {
        // only include source tile if overlap is at least 1 pixel
        var sourceTileKey = sourceTileCoord.toString();
        var sourceTile = sourceTiles[sourceTileKey];
        if (!sourceTile) {
          var tileUrl = tileUrlFunction(sourceTileCoord, pixelRatio, projection);
          sourceTile = sourceTiles[sourceTileKey] = new tileClass(sourceTileCoord,
              tileUrl == undefined ? ol.TileState.EMPTY : ol.TileState.IDLE,
              tileUrl == undefined ? '' : tileUrl,
              format, tileLoadFunction);
        }
        sourceTile.consumers++;
        this.tileKeys.push(sourceTileKey);
      }
    }.bind(this));
  }

};
ol.inherits(ol.VectorImageTile, ol.Tile);

/**
 * @inheritDoc
 */
ol.VectorImageTile.prototype.disposeInternal = function() {
  for (var i = 0, ii = this.tileKeys.length; i < ii; ++i) {
    var sourceTileKey = this.tileKeys[i];
    var sourceTile = this.getTile(sourceTileKey);
    sourceTile.consumers--;
    if (sourceTile.consumers == 0) {
      delete this.sourceTiles_[sourceTileKey];
      sourceTile.dispose();
    }
  }
  this.tileKeys.length = 0;
  this.sourceTiles_ = null;
  if (this.state == ol.TileState.LOADING) {
    this.loadListenerKeys_.forEach(ol.events.unlistenByKey);
    this.loadListenerKeys_.length = 0;
  }
  if (this.interimTile) {
    this.interimTile.dispose();
  }
  this.state = ol.TileState.ABORT;
  this.changed();
  ol.Tile.prototype.disposeInternal.call(this);
};

/**
 * @return {CanvasRenderingContext2D} The rendering context.
 */
ol.VectorImageTile.prototype.getContext = function() {
  if (!this.context_) {
    this.context_ = ol.dom.createCanvasContext2D();
  }
  return this.context_;
};

/**
 * Get the Canvas for this tile.
 * @return {HTMLCanvasElement} Canvas.
 * @api
 */
ol.VectorImageTile.prototype.getImage = function() {
  return this.replayState_.renderedTileRevision == -1 ?
      null : this.context_.canvas;
};

/**
 * @return {ol.TileReplayState} The replay state.
 */
ol.VectorImageTile.prototype.getReplayState = function() {
  return this.replayState_;
};

/**
 * @inheritDoc
 */
ol.VectorImageTile.prototype.getKey = function() {
  return this.tileKeys.join('/') + '/' + this.src_;
};

/**
 * @param {string} tileKey Key (tileCoord) of the source tile.
 * @return {ol.VectorTile} Source tile.
 */
ol.VectorImageTile.prototype.getTile = function(tileKey) {
  return this.sourceTiles_[tileKey];
};

/**
 * @inheritDoc
 */
ol.VectorImageTile.prototype.load = function() {
  var leftToLoad = 0;
  var errors = false;
  if (this.state == ol.TileState.IDLE) {
    this.setState(ol.TileState.LOADING);
  }
  if (this.state == ol.TileState.LOADING) {
    this.tileKeys.forEach(function(sourceTileKey) {
      var sourceTile = this.getTile(sourceTileKey);
      if (sourceTile.state == ol.TileState.IDLE) {
        sourceTile.setLoader(this.loader_);
        sourceTile.load();
      } else if (sourceTile.state == ol.TileState.ERROR) {
        errors = true;
      } else if (sourceTile.state == ol.TileState.EMPTY) {
        ol.array.remove(this.tileKeys, sourceTileKey);
      }
      if (sourceTile.state == ol.TileState.LOADING) {
        var key = ol.events.listen(sourceTile, ol.events.EventType.CHANGE, function(e) {
          var state = sourceTile.getState();
          if (state == ol.TileState.LOADED ||
              state == ol.TileState.ERROR) {
            --leftToLoad;
            ol.events.unlistenByKey(key);
            ol.array.remove(this.loadListenerKeys_, key);
            if (state == ol.TileState.ERROR) {
              ol.array.remove(this.tileKeys, sourceTileKey);
              errors = true;
            }
            if (leftToLoad == 0) {
              this.setState(this.tileKeys.length > 0 ?
                  ol.TileState.LOADED : ol.TileState.ERROR);
            }
          }
        }.bind(this));
        this.loadListenerKeys_.push(key);
        ++leftToLoad;
      }
    }.bind(this));
  }
  if (leftToLoad == 0) {
    setTimeout(function() {
      this.setState(this.tileKeys.length > 0 ?
          ol.TileState.LOADED :
          (errors ? ol.TileState.ERROR : ol.TileState.EMPTY));
    }.bind(this), 0);
  }
};

/**
 * @param {ol.TileState} tileState Tile state.
 */
ol.VectorImageTile.prototype.setState = function(tileState) {
  this.state = tileState;
  this.changed();
};

/**
 * Sets the loader for a tile.
 * @param {ol.VectorTile} tile Vector tile.
 * @param {string} url URL.
 */
ol.VectorImageTile.defaultLoadFunction = function(tile, url) {
  var loader = ol.featureloader.loadFeaturesXhr(
      url, tile.getFormat(), tile.onLoad_.bind(tile), tile.onError_.bind(tile));

  tile.setLoader(loader);
};
<|endoftext|>


<commit_before>/**
 * PostCSS webpack block.
 *
 * @see https://github.com/postcss/postcss-loader
 */

module.exports = postcss

/**
 * @param {PostCSSPlugin[]} [plugins]                   Will read `postcss.config.js` file if not supplied.
 * @param {object}          [options]
 * @param {RegExp|Function|string}  [options.exclude]     Directories to exclude.
 * @param {string}                  [options.parser]      Package name of custom PostCSS parser to use.
 * @param {string}                  [options.stringifier] Package name of custom PostCSS stringifier to use.
 * @param {string}                  [options.syntax]      Package name of custom PostCSS parser/stringifier to use.
 * @return {Function}
 */
function postcss (plugins, options) {
  options = options || {}

  // https://github.com/postcss/postcss-loader#options
  const postcssOptions = Object.assign(
    {},
    options.parser && { parser: options.parser },
    options.stringifier && { stringifier: options.stringifier },
    options.syntax && { syntax: options.syntax }
  )

  return (context) => Object.assign(
    {
      module: {
        loaders: [
          Object.assign({
            test: context.fileType('text/css'),
            loaders: [ 'style-loader', 'css-loader', 'postcss-loader?' + JSON.stringify(postcssOptions) ]
          }, options.exclude ? {
            exclude: Array.isArray(options.exclude) ? options.exclude : [ options.exclude ]
          } : {})
        ]
      }
    },
    plugins ? createPostcssPluginsConfig(context.webpack, plugins) : {}
  )
}

function createPostcssPluginsConfig (webpack, plugins) {
  const isWebpack2 = typeof webpack.validateSchema !== 'undefined'

  if (isWebpack2) {
    return {
      plugins: [
        new webpack.LoaderOptionsPlugin({
          options: { postcss: plugins }
        })
      ]
    }
  } else {
    return {
      postcss: plugins
    }
  }
}
<commit_msg>Fix optionalness of plugins param<commit_after>/**
 * PostCSS webpack block.
 *
 * @see https://github.com/postcss/postcss-loader
 */

module.exports = postcss

/**
 * @param {PostCSSPlugin[]} [plugins]                   Will read `postcss.config.js` file if not supplied.
 * @param {object}          [options]
 * @param {RegExp|Function|string}  [options.exclude]     Directories to exclude.
 * @param {string}                  [options.parser]      Package name of custom PostCSS parser to use.
 * @param {string}                  [options.stringifier] Package name of custom PostCSS stringifier to use.
 * @param {string}                  [options.syntax]      Package name of custom PostCSS parser/stringifier to use.
 * @return {Function}
 */
function postcss (plugins, options) {
  plugins = plugins || []
  options = options || {}

  // https://github.com/postcss/postcss-loader#options
  const postcssOptions = Object.assign(
    {},
    options.parser && { parser: options.parser },
    options.stringifier && { stringifier: options.stringifier },
    options.syntax && { syntax: options.syntax }
  )

  return (context) => Object.assign(
    {
      module: {
        loaders: [
          Object.assign({
            test: context.fileType('text/css'),
            loaders: [ 'style-loader', 'css-loader', 'postcss-loader?' + JSON.stringify(postcssOptions) ]
          }, options.exclude ? {
            exclude: Array.isArray(options.exclude) ? options.exclude : [ options.exclude ]
          } : {})
        ]
      }
    },
    plugins ? createPostcssPluginsConfig(context.webpack, plugins) : {}
  )
}

function createPostcssPluginsConfig (webpack, plugins) {
  const isWebpack2 = typeof webpack.validateSchema !== 'undefined'

  if (isWebpack2) {
    return {
      plugins: [
        new webpack.LoaderOptionsPlugin({
          options: { postcss: plugins }
        })
      ]
    }
  } else {
    return {
      postcss: plugins
    }
  }
}
<|endoftext|>


<commit_before>var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');
var coveralls = require('gulp-coveralls');
var babel = require('gulp-babel');
var isparta = require('isparta');

// Initialize the babel transpiler so ES2015 files gets compiled
// when they're loaded
require('babel-core/register');

gulp.task('static', function () {
    return gulp.src('**/*.js')
        .pipe(excludeGitignore())
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task('nsp', function (cb) {
    nsp('package.json', cb);
});

gulp.task('pre-test', function () {
    return gulp.src('lib/**/*.js')
        .pipe(istanbul({
            includeUntested: true,
            instrumenter: isparta.Instrumenter
        }))
        .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function (cb) {
    var mochaErr;

    gulp.src('test/**/*.js')
        .pipe(plumber())
        .pipe(mocha({reporter: 'spec'}))
        .on('error', function (err) {
            mochaErr = err;
        })
        .pipe(istanbul.writeReports())
        .on('end', function () {
            cb(mochaErr);
        });
});

gulp.task('coveralls', ['test'], function () {
    if (!process.env.CI) {
        return;
    }

    return gulp.src(path.join(__dirname, 'coverage/lcov.info'))
        .pipe(coveralls());
});

gulp.task('babel', function () {
    return gulp.src('lib/**/*.js')
        .pipe(babel())
        .pipe(gulp.dest('dist'));
});

gulp.task('prepublish', ['nsp', 'babel']);
gulp.task('default', ['static', 'test', 'coveralls']);
<commit_msg>[bugfix] nsp package is broken right now<commit_after>var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');
var coveralls = require('gulp-coveralls');
var babel = require('gulp-babel');
var isparta = require('isparta');

// Initialize the babel transpiler so ES2015 files gets compiled
// when they're loaded
require('babel-core/register');

gulp.task('static', function () {
    return gulp.src('**/*.js')
        .pipe(excludeGitignore())
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task('nsp', function (cb) {
    nsp('package.json', cb);
});

gulp.task('pre-test', function () {
    return gulp.src('lib/**/*.js')
        .pipe(istanbul({
            includeUntested: true,
            instrumenter: isparta.Instrumenter
        }))
        .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function (cb) {
    var mochaErr;

    gulp.src('test/**/*.js')
        .pipe(plumber())
        .pipe(mocha({reporter: 'spec'}))
        .on('error', function (err) {
            mochaErr = err;
        })
        .pipe(istanbul.writeReports())
        .on('end', function () {
            cb(mochaErr);
        });
});

gulp.task('coveralls', ['test'], function () {
    if (!process.env.CI) {
        return;
    }

    return gulp.src(path.join(__dirname, 'coverage/lcov.info'))
        .pipe(coveralls());
});

gulp.task('babel', function () {
    return gulp.src('lib/**/*.js')
        .pipe(babel())
        .pipe(gulp.dest('dist'));
});

// nsp is broke right now
gulp.task('prepublish', [/* 'nsp',*/'babel']);
gulp.task('default', ['static', 'test', 'coveralls']);
<|endoftext|>


<commit_before>// THIS FILE IS NOT PART OF THE DISTRIBUTED MONACO EDITOR
// DON'T DELETE IT WHEN UPDATING!!!

// it has to be loaded after monaco-editor/loader.js

// Set the correct root path
require.config({ paths: { 'vs': 'vs' }});

// Allow localisation

// All languages in monaco-editor
var availableLanguages = ['de', 'en', 'fr', 'es', 'it', 'ja', 'ru', 'ko', 'zh-tw', 'zh-cn'];
// find the best match
function findLanguage() {
    if (navigator.languages && Array.isArray(navigator.languages)) {
        return navigator.languages.find(function (lang) {return availableLanguages.indexOf(lang) > -1});
    }
    var lang = navigator.language || navigator.userLanguage;
    if (typeof lang === 'string') {
        // first try the long version
        if (availableLanguages.indexOf(lang) > -1) return lang;
        // then the short one
        lang = lang.substr(0, 2);
        if (availableLanguages.indexOf(lang) > -1) return lang;
    }
}

var language = findLanguage();
// if we have a match, configure the editor
if (language != null) {
    require.config({
        'vs/nls': {
            availableLanguages: {
                '*': language
            }
        }
    });
}

// And load the editor itself
require(['vs/editor/editor.main'], function () { });
<commit_msg>Don't translate english<commit_after>// THIS FILE IS NOT PART OF THE DISTRIBUTED MONACO EDITOR
// DON'T DELETE IT WHEN UPDATING!!!

// it has to be loaded after monaco-editor/loader.js

// Set the correct root path
require.config({ paths: { 'vs': 'vs' }});

// Allow localisation

// All languages in monaco-editor
var availableLanguages = ['de', 'en', 'fr', 'es', 'it', 'ja', 'ru', 'ko', 'zh-tw', 'zh-cn'];
// find the best match
function findLanguage() {
    if (navigator.languages && Array.isArray(navigator.languages)) {
        return navigator.languages.find(function (lang) {return availableLanguages.indexOf(lang) > -1});
    }
    var lang = navigator.language || navigator.userLanguage;
    if (typeof lang === 'string') {
        // first try the long version
        if (availableLanguages.indexOf(lang) > -1) return lang;
        // then the short one
        lang = lang.substr(0, 2);
        if (availableLanguages.indexOf(lang) > -1) return lang;
    }
}

var language = findLanguage();
// if we have a match, configure the editor
if (language != null && language !== 'en') {
    require.config({
        'vs/nls': {
            availableLanguages: {
                '*': language
            }
        }
    });
}

// And load the editor itself
require(['vs/editor/editor.main'], function () { });
<|endoftext|>