<commit_before>import Check from "./Check.js";
import defined from "./defined.js";
import DeveloperError from "./DeveloperError.js";

/**
 * Morton Order (aka Z-Order Curve) helper functions.
 * @see {@link https://en.wikipedia.org/wiki/Z-order_curve}
 *
 * @namespace MortonOrder
 */
var MortonOrder = {};

/**
 * Inserts one 0 bit of spacing between a number's bits. This is the opposite of removeOneSpacing.
 *
 * Example:
 *  input: 6
 *  input (binary):  110
 *  output (binary): 10100
 *                    ^ ^ (added)
 *  output: 20
 *
 * @private
 * @param {Number} v A 16-bit unsigned integer.
 * @returns {Number} A 32-bit unsigned integer.
 * @see {@link https://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/}
 */
function insertOneSpacing(v) {
  v = (v ^ (v << 8)) & 0x00ff00ff;
  v = (v ^ (v << 4)) & 0x0f0f0f0f;
  v = (v ^ (v << 2)) & 0x33333333;
  v = (v ^ (v << 1)) & 0x55555555;
  return v;
}

/**
 * Inserts two 0 bits of spacing between a number's bits. This is the opposite of removeTwoSpacing.
 *
 * Example:
 *  input: 6
 *  input (binary):  110
 *  output (binary): 1001000
 *                    ^^ ^^ (added)
 *  output: 72
 *
 * @private
 * @param {Number} v A 10-bit unsigned integer.
 * @returns {Number} A 30-bit unsigned integer.
 * @see {@link https://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/}
 */
function insertTwoSpacing(v) {
  v = (v ^ (v << 16)) & 0x030000ff;
  v = (v ^ (v << 8)) & 0x0300f00f;
  v = (v ^ (v << 4)) & 0x030c30c3;
  v = (v ^ (v << 2)) & 0x09249249;
  return v;
}

/**
 * Removes one bit of spacing between bits. This is the opposite of insertOneSpacing.
 *
 * Example:
 *  input: 20
 *  input (binary):  10100
 *                    ^ ^ (removed)
 *  output (binary): 110
 *  output: 6
 *
 * @private
 * @param {Number} v A 32-bit unsigned integer.
 * @returns {Number} A 16-bit unsigned integer.
 * @see {@link https://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/}
 */
function removeOneSpacing(v) {
  v &= 0x55555555;
  v = (v ^ (v >> 1)) & 0x33333333;
  v = (v ^ (v >> 2)) & 0x0f0f0f0f;
  v = (v ^ (v >> 4)) & 0x00ff00ff;
  v = (v ^ (v >> 8)) & 0x0000ffff;
  return v;
}

/**
 * Removes two bits of spacing between bits. This is the opposite of insertTwoSpacing.
 *
 * Example:
 *  input: 72
 *  input (binary):  1001000
 *                    ^^ ^^ (removed)
 *  output (binary): 110
 *  output: 6
 *
 * @private
 * @param {Number} v A 30-bit unsigned integer.
 * @returns {Number} A 10-bit unsigned integer.
 * @see {@link https://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/}
 */
function removeTwoSpacing(v) {
  v &= 0x09249249;
  v = (v ^ (v >> 2)) & 0x030c30c3;
  v = (v ^ (v >> 4)) & 0x0300f00f;
  v = (v ^ (v >> 8)) & 0xff0000ff;
  v = (v ^ (v >> 16)) & 0x000003ff;
  return v;
}

/**
 * Computes the Morton index from 2D coordinates. This is equivalent to interleaving their bits.
 * The inputs must be 16-bit unsigned integers (resulting in 32-bit Morton index) due to 32-bit bitwise operator limitation in JavaScript.
 *
 * @param {Number} x The X coordinate in the range [0, (2^16)-1].
 * @param {Number} y The Y coordinate in the range [0, (2^16)-1].
 * @returns {Number} The Morton index.
 */
MortonOrder.encode2D = function (x, y) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.number("x", x);
  Check.typeOf.number("y", y);
  if (x < 0 || x > 65535 || y < 0 || y > 65535) {
    throw new DeveloperError("inputs must be 16-bit unsigned integers");
  }
  //>>includeEnd('debug');

  return (insertOneSpacing(x) | (insertOneSpacing(y) << 1)) >>> 0;
};

/**
 * Computes the 2D coordinates from a Morton index. This is equivalent to deinterleaving their bits.
 * The input must be a 32-bit unsigned integer (resulting in 16 bits per coordinate) due to 32-bit bitwise operator limitation in JavaScript.
 *
 * @param {Number} mortonIndex The Morton index in the range [0, (2^32)-1].
 * @param {Number[]} [result] The array onto which to store the result.
 * @returns {Number[]} An array containing the 2D coordinates correspoding to the Morton index.
 */
MortonOrder.decode2D = function (mortonIndex, result) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.number("mortonIndex", mortonIndex);
  if (mortonIndex < 0 || mortonIndex > 4294967295) {
    throw new DeveloperError("input must be a 32-bit unsigned integer");
  }
  //>>includeEnd('debug');

  if (!defined(result)) {
    result = new Array(2);
  }

  result[0] = removeOneSpacing(mortonIndex);
  result[1] = removeOneSpacing(mortonIndex >> 1);
  return result;
};

/**
 * Computes the Morton index from 3D coordinates. This is equivalent to interleaving their bits.
 * The inputs must be 10-bit unsigned integers (resulting in 30-bit Morton index) due to 32-bit bitwise operator limitation in JavaScript.
 *
 * @param {Number} x The X coordinate in the range [0, (2^10)-1].
 * @param {Number} y The Y coordinate in the range [0, (2^10)-1].
 * @param {Number} z The Z coordinate in the range [0, (2^10)-1].
 * @returns {Number} The Morton index.
 */
MortonOrder.encode3D = function (x, y, z) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.number("x", x);
  Check.typeOf.number("y", y);
  Check.typeOf.number("z", z);
  if (x < 0 || x > 1023 || y < 0 || y > 1023 || z < 0 || z > 1023) {
    throw new DeveloperError("inputs must be 10-bit unsigned integers");
  }
  //>>includeEnd('debug');

  return (
    insertTwoSpacing(x) |
    (insertTwoSpacing(y) << 1) |
    (insertTwoSpacing(z) << 2)
  );
};

/**
 * Computes the 3D coordinates from a Morton index. This is equivalent to deinterleaving their bits.
 * The input must be a 30-bit unsigned integer (resulting in 10 bits per coordinate) due to 32-bit bitwise operator limitation in JavaScript.
 *
 * @param {Number} mortonIndex The Morton index in the range [0, (2^30)-1].
 * @param {Number[]} [result] The array onto which to store the result.
 * @returns {Number[]} An array containing the 3D coordinates correspoding to the Morton index.
 */
MortonOrder.decode3D = function (mortonIndex, result) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.number("mortonIndex", mortonIndex);
  if (mortonIndex < 0 || mortonIndex > 1073741823) {
    throw new DeveloperError("input must be 30-bit unsigned integer");
  }
  //>>includeEnd('debug');

  if (!defined(result)) {
    result = new Array(3);
  }

  result[0] = removeTwoSpacing(mortonIndex);
  result[1] = removeTwoSpacing(mortonIndex >> 1);
  result[2] = removeTwoSpacing(mortonIndex >> 2);
  return result;
};

export default MortonOrder;
<commit_msg>grammar<commit_after>import Check from "./Check.js";
import defined from "./defined.js";
import DeveloperError from "./DeveloperError.js";

/**
 * Morton Order (aka Z-Order Curve) helper functions.
 * @see {@link https://en.wikipedia.org/wiki/Z-order_curve}
 *
 * @namespace MortonOrder
 */
var MortonOrder = {};

/**
 * Inserts one 0 bit of spacing between a number's bits. This is the opposite of removeOneSpacing.
 *
 * Example:
 *  input: 6
 *  input (binary):  110
 *  output (binary): 10100
 *                    ^ ^ (added)
 *  output: 20
 *
 * @private
 * @param {Number} v A 16-bit unsigned integer.
 * @returns {Number} A 32-bit unsigned integer.
 * @see {@link https://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/}
 */
function insertOneSpacing(v) {
  v = (v ^ (v << 8)) & 0x00ff00ff;
  v = (v ^ (v << 4)) & 0x0f0f0f0f;
  v = (v ^ (v << 2)) & 0x33333333;
  v = (v ^ (v << 1)) & 0x55555555;
  return v;
}

/**
 * Inserts two 0 bits of spacing between a number's bits. This is the opposite of removeTwoSpacing.
 *
 * Example:
 *  input: 6
 *  input (binary):  110
 *  output (binary): 1001000
 *                    ^^ ^^ (added)
 *  output: 72
 *
 * @private
 * @param {Number} v A 10-bit unsigned integer.
 * @returns {Number} A 30-bit unsigned integer.
 * @see {@link https://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/}
 */
function insertTwoSpacing(v) {
  v = (v ^ (v << 16)) & 0x030000ff;
  v = (v ^ (v << 8)) & 0x0300f00f;
  v = (v ^ (v << 4)) & 0x030c30c3;
  v = (v ^ (v << 2)) & 0x09249249;
  return v;
}

/**
 * Removes one bit of spacing between bits. This is the opposite of insertOneSpacing.
 *
 * Example:
 *  input: 20
 *  input (binary):  10100
 *                    ^ ^ (removed)
 *  output (binary): 110
 *  output: 6
 *
 * @private
 * @param {Number} v A 32-bit unsigned integer.
 * @returns {Number} A 16-bit unsigned integer.
 * @see {@link https://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/}
 */
function removeOneSpacing(v) {
  v &= 0x55555555;
  v = (v ^ (v >> 1)) & 0x33333333;
  v = (v ^ (v >> 2)) & 0x0f0f0f0f;
  v = (v ^ (v >> 4)) & 0x00ff00ff;
  v = (v ^ (v >> 8)) & 0x0000ffff;
  return v;
}

/**
 * Removes two bits of spacing between bits. This is the opposite of insertTwoSpacing.
 *
 * Example:
 *  input: 72
 *  input (binary):  1001000
 *                    ^^ ^^ (removed)
 *  output (binary): 110
 *  output: 6
 *
 * @private
 * @param {Number} v A 30-bit unsigned integer.
 * @returns {Number} A 10-bit unsigned integer.
 * @see {@link https://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/}
 */
function removeTwoSpacing(v) {
  v &= 0x09249249;
  v = (v ^ (v >> 2)) & 0x030c30c3;
  v = (v ^ (v >> 4)) & 0x0300f00f;
  v = (v ^ (v >> 8)) & 0xff0000ff;
  v = (v ^ (v >> 16)) & 0x000003ff;
  return v;
}

/**
 * Computes the Morton index from 2D coordinates. This is equivalent to interleaving their bits.
 * The inputs must be 16-bit unsigned integers (resulting in 32-bit Morton index) due to 32-bit bitwise operator limitation in JavaScript.
 *
 * @param {Number} x The X coordinate in the range [0, (2^16)-1].
 * @param {Number} y The Y coordinate in the range [0, (2^16)-1].
 * @returns {Number} The Morton index.
 */
MortonOrder.encode2D = function (x, y) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.number("x", x);
  Check.typeOf.number("y", y);
  if (x < 0 || x > 65535 || y < 0 || y > 65535) {
    throw new DeveloperError("inputs must be 16-bit unsigned integers");
  }
  //>>includeEnd('debug');

  return (insertOneSpacing(x) | (insertOneSpacing(y) << 1)) >>> 0;
};

/**
 * Computes the 2D coordinates from a Morton index. This is equivalent to deinterleaving their bits.
 * The input must be a 32-bit unsigned integer (resulting in 16 bits per coordinate) due to 32-bit bitwise operator limitation in JavaScript.
 *
 * @param {Number} mortonIndex The Morton index in the range [0, (2^32)-1].
 * @param {Number[]} [result] The array onto which to store the result.
 * @returns {Number[]} An array containing the 2D coordinates correspoding to the Morton index.
 */
MortonOrder.decode2D = function (mortonIndex, result) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.number("mortonIndex", mortonIndex);
  if (mortonIndex < 0 || mortonIndex > 4294967295) {
    throw new DeveloperError("input must be a 32-bit unsigned integer");
  }
  //>>includeEnd('debug');

  if (!defined(result)) {
    result = new Array(2);
  }

  result[0] = removeOneSpacing(mortonIndex);
  result[1] = removeOneSpacing(mortonIndex >> 1);
  return result;
};

/**
 * Computes the Morton index from 3D coordinates. This is equivalent to interleaving their bits.
 * The inputs must be 10-bit unsigned integers (resulting in 30-bit Morton index) due to 32-bit bitwise operator limitation in JavaScript.
 *
 * @param {Number} x The X coordinate in the range [0, (2^10)-1].
 * @param {Number} y The Y coordinate in the range [0, (2^10)-1].
 * @param {Number} z The Z coordinate in the range [0, (2^10)-1].
 * @returns {Number} The Morton index.
 */
MortonOrder.encode3D = function (x, y, z) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.number("x", x);
  Check.typeOf.number("y", y);
  Check.typeOf.number("z", z);
  if (x < 0 || x > 1023 || y < 0 || y > 1023 || z < 0 || z > 1023) {
    throw new DeveloperError("inputs must be 10-bit unsigned integers");
  }
  //>>includeEnd('debug');

  return (
    insertTwoSpacing(x) |
    (insertTwoSpacing(y) << 1) |
    (insertTwoSpacing(z) << 2)
  );
};

/**
 * Computes the 3D coordinates from a Morton index. This is equivalent to deinterleaving their bits.
 * The input must be a 30-bit unsigned integer (resulting in 10 bits per coordinate) due to 32-bit bitwise operator limitation in JavaScript.
 *
 * @param {Number} mortonIndex The Morton index in the range [0, (2^30)-1].
 * @param {Number[]} [result] The array onto which to store the result.
 * @returns {Number[]} An array containing the 3D coordinates correspoding to the Morton index.
 */
MortonOrder.decode3D = function (mortonIndex, result) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.number("mortonIndex", mortonIndex);
  if (mortonIndex < 0 || mortonIndex > 1073741823) {
    throw new DeveloperError("input must be a 30-bit unsigned integer");
  }
  //>>includeEnd('debug');

  if (!defined(result)) {
    result = new Array(3);
  }

  result[0] = removeTwoSpacing(mortonIndex);
  result[1] = removeTwoSpacing(mortonIndex >> 1);
  result[2] = removeTwoSpacing(mortonIndex >> 2);
  return result;
};

export default MortonOrder;
<|endoftext|>


<commit_before>import L from 'leaflet';
import {cors} from '../Support';

var Overlay = L.ImageOverlay.extend({
  onAdd: function (map) {
    this._topLeft = map.getPixelBounds().min;
    L.ImageOverlay.prototype.onAdd.call(this, map);
  },
  _reset: function () {
    if (this._map.options.crs === L.CRS.EPSG3857) {
      L.ImageOverlay.prototype._reset.call(this);
    } else {
      L.DomUtil.setPosition(this._image, this._topLeft.subtract(this._map.getPixelOrigin()));
    }
  }
});

export var RasterLayer = L.Layer.extend({

  options: {
    opacity: 1,
    position: 'front',
    f: 'image',
    useCors: cors,
    attribution: null,
    interactive: false,
    alt: ''
  },

  onAdd: function (map) {
    this._update = L.Util.throttle(this._update, this.options.updateInterval, this);

    map.on('moveend', this._update, this);

    // if we had an image loaded and it matches the
    // current bounds show the image otherwise remove it
    if (this._currentImage && this._currentImage._bounds.equals(this._map.getBounds())) {
      map.addLayer(this._currentImage);
    } else if (this._currentImage) {
      this._map.removeLayer(this._currentImage);
      this._currentImage = null;
    }

    this._update();

    if (this._popup) {
      this._map.on('click', this._getPopupData, this);
      this._map.on('dblclick', this._resetPopupState, this);
    }
  },

  onRemove: function (map) {
    if (this._currentImage) {
      this._map.removeLayer(this._currentImage);
    }

    if (this._popup) {
      this._map.off('click', this._getPopupData, this);
      this._map.off('dblclick', this._resetPopupState, this);
    }

    this._map.off('moveend', this._update, this);
  },

  getEvents: function () {
    return {
      moveend: this._update
    };
  },

  bindPopup: function (fn, popupOptions) {
    this._shouldRenderPopup = false;
    this._lastClick = false;
    this._popup = L.popup(popupOptions);
    this._popupFunction = fn;
    if (this._map) {
      this._map.on('click', this._getPopupData, this);
      this._map.on('dblclick', this._resetPopupState, this);
    }
    return this;
  },

  unbindPopup: function () {
    if (this._map) {
      this._map.closePopup(this._popup);
      this._map.off('click', this._getPopupData, this);
      this._map.off('dblclick', this._resetPopupState, this);
    }
    this._popup = false;
    return this;
  },

  bringToFront: function () {
    this.options.position = 'front';
    if (this._currentImage) {
      this._currentImage.bringToFront();
    }
    return this;
  },

  bringToBack: function () {
    this.options.position = 'back';
    if (this._currentImage) {
      this._currentImage.bringToBack();
    }
    return this;
  },

  getAttribution: function () {
    return this.options.attribution;
  },

  getOpacity: function () {
    return this.options.opacity;
  },

  setOpacity: function (opacity) {
    this.options.opacity = opacity;
    this._currentImage.setOpacity(opacity);
    return this;
  },

  getTimeRange: function () {
    return [this.options.from, this.options.to];
  },

  setTimeRange: function (from, to) {
    this.options.from = from;
    this.options.to = to;
    this._update();
    return this;
  },

  metadata: function (callback, context) {
    this.service.metadata(callback, context);
    return this;
  },

  authenticate: function (token) {
    this.service.authenticate(token);
    return this;
  },

  _renderImage: function (url, bounds) {
    if (this._map) {
      // create a new image overlay and add it to the map
      // to start loading the image
      // opacity is 0 while the image is loading
      var image = new Overlay(url, bounds, {
        opacity: 0,
        crossOrigin: this.options.useCors,
        alt: this.options.alt,
        pane: this.options.pane || this.getPane(),
        interactive: this.options.interactive
      }).addTo(this._map);

      // once the image loads
      image.once('load', function (e) {
        if (this._map) {
          var newImage = e.target;
          var oldImage = this._currentImage;

          // if the bounds of this image matches the bounds that
          // _renderImage was called with and we have a map with the same bounds
          // hide the old image if there is one and set the opacity
          // of the new image otherwise remove the new image
          if (newImage._bounds.equals(bounds) && newImage._bounds.equals(this._map.getBounds())) {
            this._currentImage = newImage;

            if (this.options.position === 'front') {
              this.bringToFront();
            } else {
              this.bringToBack();
            }

            if (this._map && this._currentImage._map) {
              this._currentImage.setOpacity(this.options.opacity);
            } else {
              this._currentImage._map.removeLayer(this._currentImage);
            }

            if (oldImage && this._map) {
              this._map.removeLayer(oldImage);
            }

            if (oldImage && oldImage._map) {
              oldImage._map.removeLayer(oldImage);
            }
          } else {
            this._map.removeLayer(newImage);
          }
        }

        this.fire('load', {
          bounds: bounds
        });
      }, this);

      this.fire('loading', {
        bounds: bounds
      });
    }
  },

  _update: function () {
    if (!this._map) {
      return;
    }

    var zoom = this._map.getZoom();
    var bounds = this._map.getBounds();

    if (this._animatingZoom) {
      return;
    }

    if (this._map._panTransition && this._map._panTransition._inProgress) {
      return;
    }

    if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
      return;
    }

    var params = this._buildExportParams();

    this._requestExport(params, bounds);
  },

  _renderPopup: function (latlng, error, results, response) {
    latlng = L.latLng(latlng);
    if (this._shouldRenderPopup && this._lastClick.equals(latlng)) {
      // add the popup to the map where the mouse was clicked at
      var content = this._popupFunction(error, results, response);
      if (content) {
        this._popup.setLatLng(latlng).setContent(content).openOn(this._map);
      }
    }
  },

  _resetPopupState: function (e) {
    this._shouldRenderPopup = false;
    this._lastClick = e.latlng;
  }
});
<commit_msg>RasterLayer.getEvents deleted<commit_after>import L from 'leaflet';
import {cors} from '../Support';

var Overlay = L.ImageOverlay.extend({
  onAdd: function (map) {
    this._topLeft = map.getPixelBounds().min;
    L.ImageOverlay.prototype.onAdd.call(this, map);
  },
  _reset: function () {
    if (this._map.options.crs === L.CRS.EPSG3857) {
      L.ImageOverlay.prototype._reset.call(this);
    } else {
      L.DomUtil.setPosition(this._image, this._topLeft.subtract(this._map.getPixelOrigin()));
    }
  }
});

export var RasterLayer = L.Layer.extend({

  options: {
    opacity: 1,
    position: 'front',
    f: 'image',
    useCors: cors,
    attribution: null,
    interactive: false,
    alt: ''
  },

  onAdd: function (map) {
    this._update = L.Util.throttle(this._update, this.options.updateInterval, this);

    map.on('moveend', this._update, this);

    // if we had an image loaded and it matches the
    // current bounds show the image otherwise remove it
    if (this._currentImage && this._currentImage._bounds.equals(this._map.getBounds())) {
      map.addLayer(this._currentImage);
    } else if (this._currentImage) {
      this._map.removeLayer(this._currentImage);
      this._currentImage = null;
    }

    this._update();

    if (this._popup) {
      this._map.on('click', this._getPopupData, this);
      this._map.on('dblclick', this._resetPopupState, this);
    }
  },

  onRemove: function (map) {
    if (this._currentImage) {
      this._map.removeLayer(this._currentImage);
    }

    if (this._popup) {
      this._map.off('click', this._getPopupData, this);
      this._map.off('dblclick', this._resetPopupState, this);
    }

    this._map.off('moveend', this._update, this);
  },

  bindPopup: function (fn, popupOptions) {
    this._shouldRenderPopup = false;
    this._lastClick = false;
    this._popup = L.popup(popupOptions);
    this._popupFunction = fn;
    if (this._map) {
      this._map.on('click', this._getPopupData, this);
      this._map.on('dblclick', this._resetPopupState, this);
    }
    return this;
  },

  unbindPopup: function () {
    if (this._map) {
      this._map.closePopup(this._popup);
      this._map.off('click', this._getPopupData, this);
      this._map.off('dblclick', this._resetPopupState, this);
    }
    this._popup = false;
    return this;
  },

  bringToFront: function () {
    this.options.position = 'front';
    if (this._currentImage) {
      this._currentImage.bringToFront();
    }
    return this;
  },

  bringToBack: function () {
    this.options.position = 'back';
    if (this._currentImage) {
      this._currentImage.bringToBack();
    }
    return this;
  },

  getAttribution: function () {
    return this.options.attribution;
  },

  getOpacity: function () {
    return this.options.opacity;
  },

  setOpacity: function (opacity) {
    this.options.opacity = opacity;
    this._currentImage.setOpacity(opacity);
    return this;
  },

  getTimeRange: function () {
    return [this.options.from, this.options.to];
  },

  setTimeRange: function (from, to) {
    this.options.from = from;
    this.options.to = to;
    this._update();
    return this;
  },

  metadata: function (callback, context) {
    this.service.metadata(callback, context);
    return this;
  },

  authenticate: function (token) {
    this.service.authenticate(token);
    return this;
  },

  _renderImage: function (url, bounds) {
    if (this._map) {
      // create a new image overlay and add it to the map
      // to start loading the image
      // opacity is 0 while the image is loading
      var image = new Overlay(url, bounds, {
        opacity: 0,
        crossOrigin: this.options.useCors,
        alt: this.options.alt,
        pane: this.options.pane || this.getPane(),
        interactive: this.options.interactive
      }).addTo(this._map);

      // once the image loads
      image.once('load', function (e) {
        if (this._map) {
          var newImage = e.target;
          var oldImage = this._currentImage;

          // if the bounds of this image matches the bounds that
          // _renderImage was called with and we have a map with the same bounds
          // hide the old image if there is one and set the opacity
          // of the new image otherwise remove the new image
          if (newImage._bounds.equals(bounds) && newImage._bounds.equals(this._map.getBounds())) {
            this._currentImage = newImage;

            if (this.options.position === 'front') {
              this.bringToFront();
            } else {
              this.bringToBack();
            }

            if (this._map && this._currentImage._map) {
              this._currentImage.setOpacity(this.options.opacity);
            } else {
              this._currentImage._map.removeLayer(this._currentImage);
            }

            if (oldImage && this._map) {
              this._map.removeLayer(oldImage);
            }

            if (oldImage && oldImage._map) {
              oldImage._map.removeLayer(oldImage);
            }
          } else {
            this._map.removeLayer(newImage);
          }
        }

        this.fire('load', {
          bounds: bounds
        });
      }, this);

      this.fire('loading', {
        bounds: bounds
      });
    }
  },

  _update: function () {
    if (!this._map) {
      return;
    }

    var zoom = this._map.getZoom();
    var bounds = this._map.getBounds();

    if (this._animatingZoom) {
      return;
    }

    if (this._map._panTransition && this._map._panTransition._inProgress) {
      return;
    }

    if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
      return;
    }

    var params = this._buildExportParams();

    this._requestExport(params, bounds);
  },

  _renderPopup: function (latlng, error, results, response) {
    latlng = L.latLng(latlng);
    if (this._shouldRenderPopup && this._lastClick.equals(latlng)) {
      // add the popup to the map where the mouse was clicked at
      var content = this._popupFunction(error, results, response);
      if (content) {
        this._popup.setLatLng(latlng).setContent(content).openOn(this._map);
      }
    }
  },

  _resetPopupState: function (e) {
    this._shouldRenderPopup = false;
    this._lastClick = e.latlng;
  }
});
<|endoftext|>


<commit_before>if(void 0===OGX)var OGX=function(){};OGX.FormTools=function(){"use strict";var l=this,t={container:!1,allowed:!1,forbidden:!1,submit_cb:!1,validate:!1,elem_types:["input","textarea"],wait:1e3},n={container:!1,allowed:/^[a-z0-9\\!\\.\\?\\#\\@\\$\\-\\:\\(\\)\\/_,;%'"’ ]$/gi,forbidden:!1,mask:!1,mask_char:"%",paste:!0,autocomplete:null,multiline:!1,input_cb:!1,change_cb:!1,val:null,changing:!1,wait:1e3,intv:null,max:2500,type:"string",params:null},u={},a={};function c(e,t){if(u[t].change_cb){var n=p(t);for(var a in n)u[t].hasOwnProperty("fields")&&u[t].fields.hasOwnProperty(a)&&u[t].fields[a].hasOwnProperty("type")?n[a]=s(u[t].fields[a].type,n[a]):u[t].hasOwnProperty("type")&&(n[a]=s(u[t].type,n[a]));u[t].change_cb(n)}}function s(e,t){switch(e){case"string":return String(t);case"number":return Number(t);case"int":return parseInt(t);case"bool":return"true"===e||1===e}}function p(e){return $(e).serializeArray().map(function(e){return this[e.name]=e.value,this}.bind({}))[0]}function f(e){return Object.assign({},e)}function m(e,t){for(var n in t)e.hasOwnProperty(n)&&(e[n]=t[n]);return e}this.bindForm=function(e){return!u.hasOwnProperty(e.container)&&(function(a){var r,i,o=m(f(t),a);console.log(o),$(a.container).on("submit",function(e){e.preventDefault(),e.stopImmediatePropagation();var t={obj:p(o.container),form:o.container};if(u[a.container].validate){var n=l.validateForm(o.container);!0===n?t.valid=!0:(t.valid=!1,t.error=n)}u[o.container].change_cb?u[o.container].change_cb(t):u[o.container].submit_cb?u[o.container].submit_cb(t):$(o.container).trigger("change",t)});for(var e=0;e<o.elem_types.length;e++)$(o.container).find(o.elem_types[e]).each(function(e,t){n(o,e,t)});function n(e,t,n){if(n.hasAttribute("name")){if(r=$(n).attr("name"),delete(i=f(e)).fields,delete i.container,delete i.elem_types,e.hasOwnProperty("fields")&&e.fields.hasOwnProperty(r))for(var a in e.fields[r])i[a]=e.fields[r][a];i.container=e.container+" "+n.tagName.toLowerCase()+'[name="'+r+'"]',i.change_cb=c,i.params=e.container,console.log("bind field",i),l.bindField(i)}}}(u[e.container]=e),!0)},this.unbindForm=function(e){u.hasOwnProperty(e)&&(!function(e){var t;$(document).off("submit",e);for(var n=0;n<__config.elem_types.length;n++)__el.hasAttribute("name")&&(t=$(__el).attr("name"),l.unbindField(e+" "+__config.elem_types[n]+'[name="'+t+'"]'));delete u[e]}(e),delete u[e])},this.bindField=function(e){if(u.hasOwnProperty(e.container))return!1;!function(e){var i=m(f(n),e),o=$(i.container),c=o.attr("name");o.on("input change",function(){var e=$(this).val();if(i.input_cb){var t={value:null,obj:{},el:null};e=s(i.type,e),t.el=o[0],t.value=e,t.property=c,t.obj[c]=e,options.input_cb(t,i.params)}u[i.container].intv||(u[i.container].intv=setInterval(function(){!function(e,t){var n=$(e).val(),a=u[e];if(a.val!==n&&(a.val=n,a.changing=(new Date).getTime()),a.changing&&(new Date).getTime()>a.wait+a.changing&&(clearInterval(a.intv),a.intv=!1,u[e].change_cb)){var r={value:null,obj:{},el:null};n=s(u[e].type,n),r.el=$(e)[0],r.property=$(e).attr("name"),r.value=n,r.obj[r.property]=n,u[e].change_cb(r,t)}}(i.container,i.params)},50))}),i.multiline||o.on("keypress",function(e){var t=$(this).val();if(13!==e.which&&i.mask){if(t.length>i.mask.length)return e.preventDefault(),e.stopImmediatePropagation(),!1;for(var n=i.mask,a=0;a<t.length;a++)i.mask.substr(a,1)===i.mask_char&&(n=n.replace(i.mask_char,t.substr(a,1)));-1!==(t=n).indexOf(i.mask_char)&&(t=t.substr(0,t.indexOf(i.mask_char))),o.val(t)}if(13===e.which){e.preventDefault(),e.stopImmediatePropagation();var t=$(this).val();if(u[i.container].intv&&(clearInterval(u[i.container].intv),u[i.container].intv=null),i.change_cb){var r={value:null,obj:{},el:null};t=s(i.type,t),r.el=o[0],r.property=c,r.value=t,r.obj[c]=t,i.change_cb(r,i.params)}else o.trigger("change",t)}});((u[i.container]=i).allowed||i.forbidden)&&l.restrictField(i)}(e)},this.unbindField=function(e){if(u.hasOwnProperty(e)){var t=$(e);t.off("input change"),u[e].multiline||t.off("keypress"),u[e].intv&&clearInterval(u[e].intv),a.hasOwnProperty(e)&&l.unrestrictField(e),delete u[e]}},this.restrictField=function(e){return!a.hasOwnProperty(e.container)&&(function(n){var e=$(n.container);a[n.container]=n,a[n.container].keys=[],null===n.autocomplete&&e[0].hasAttribute("autocomplete")&&"on"===e.attr("autocomplete")?n.autocomplete=!0:n.autocomplete=!1;n.autocomplete?n.hasOwnProperty("allowed")&&n.allowed&&(n.allowed=new RegExp(n.allowed.toString().replace("$/gi","+$").replace("/^","^"),"gi")):a[n.container].keys.push(229);-1!==["input","texarea"].indexOf(e.get(0).tagName.toLowerCase())?a[n.container].content="val":a[n.container].content="html";a[n.container].multiline||a[n.container].keys.push(13);e.on("textInput keydown",function(e){if("textInput"===e.type){var t=e.originalEvent.data;if(a[n.container].allowed){if(!t.match(a[n.container].allowed))return e.preventDefault(),e.stopImmediatePropagation(),!1}else if(a[n.container].forbidden&&t.match(a[n.container].forbidden))return e.preventDefault(),e.stopImmediatePropagation(),!1}if("keydown"===e.type){if(-1!==a[n.container].keys.indexOf(e.which))return e.preventDefault(),e.stopImmediatePropagation(),!1;if($(this)[a[n.container].content]().length>=a[n.container].max&&8!==e.which)return e.preventDefault(),e.stopImmediatePropagation(),!1}}),a[n.container].paste||e.on("paste",function(e){e.preventDefault(),e.stopImmediatePropagation()})}(e),!0)},this.unrestrictField=function(e){if(a.hasOwnProperty(e)){var t=$(e);return t.off("textInput keydown"),a[e].paste||t.off("paste"),delete a[e],!0}return!1},this.formToObj=function(e){return p(e)},this.populateForm=function(e,n){var a,t=$(e);function r(e,t){a=$(t).attr("name"),e.hasOwnProperty(a)&&$(t).val(e[a])}t.find("input").each(function(e,t){r(n,t)}),t.find("texarea").each(function(e,t){r(n,t)})},this.validateForm=function(e){var n,a,r,t=$(e),i={},o=!0;return t.find("input").each(function(e,t){n=$(t),t.hasAttribute("required")&&t.hasAttribute("pattern")&&"submit"!==n.attr("type")&&(a=n.attr("pattern"),r=n.val(),a&&((a=new RegExp(a,"g")).test(r)||(i[n.attr("name")]=!1,o=!1)))}),!!o||i}},OGX.FormTools=new OGX.FormTools;<commit_msg><commit_after>if(void 0===OGX)var OGX=function(){};OGX.FormTools=function(){"use strict";var l=this,t={container:!1,allowed:!1,forbidden:!1,submit_cb:!1,validate:!1,elem_types:["input","textarea"],wait:1e3},n={container:!1,allowed:/^[a-z0-9\\!\\.\\?\\#\\@\\$\\-\\:\\(\\)\\/_,;%'"’ ]$/gi,forbidden:!1,mask:!1,mask_char:"%",paste:!0,autocomplete:null,multiline:!1,input_cb:!1,change_cb:!1,val:null,changing:!1,wait:1e3,intv:null,max:2500,type:"string",params:null},u={},a={};function c(e,t){if(u[t].change_cb){var n=p(t);for(var a in n)u[t].hasOwnProperty("fields")&&u[t].fields.hasOwnProperty(a)&&u[t].fields[a].hasOwnProperty("type")?n[a]=s(u[t].fields[a].type,n[a]):u[t].hasOwnProperty("type")&&(n[a]=s(u[t].type,n[a]));u[t].change_cb(n)}}function s(e,t){switch(e){case"string":return String(t);case"number":return Number(t);case"int":return parseInt(t);case"bool":return"true"===e||1===e}}function p(e){return $(e).serializeArray().map(function(e){return this[e.name]=e.value,this}.bind({}))[0]}function f(e){return Object.assign({},e)}function m(e,t){for(var n in t)e.hasOwnProperty(n)&&(e[n]=t[n]);return e}this.bindForm=function(e){return!u.hasOwnProperty(e.container)&&(function(a){var r,i,o=m(f(t),a);$(a.container).on("submit",function(e){e.preventDefault(),e.stopImmediatePropagation();var t={obj:p(o.container),form:o.container};if(u[a.container].validate){var n=l.validateForm(o.container);!0===n?t.valid=!0:(t.valid=!1,t.error=n)}u[o.container].change_cb?u[o.container].change_cb(t):u[o.container].submit_cb?u[o.container].submit_cb(t):$(o.container).trigger("change",t)});for(var e=0;e<o.elem_types.length;e++)$(o.container).find(o.elem_types[e]).each(function(e,t){n(o,e,t)});function n(e,t,n){if(n.hasAttribute("name")){if(r=$(n).attr("name"),delete(i=f(e)).fields,delete i.container,delete i.elem_types,e.hasOwnProperty("fields")&&e.fields.hasOwnProperty(r))for(var a in e.fields[r])i[a]=e.fields[r][a];i.container=e.container+" "+n.tagName.toLowerCase()+'[name="'+r+'"]',i.change_cb=c,i.params=e.container,l.bindField(i)}}}(u[e.container]=e),!0)},this.unbindForm=function(e){u.hasOwnProperty(e)&&(!function(e){var t;$(document).off("submit",e);for(var n=0;n<__config.elem_types.length;n++)__el.hasAttribute("name")&&(t=$(__el).attr("name"),l.unbindField(e+" "+__config.elem_types[n]+'[name="'+t+'"]'));delete u[e]}(e),delete u[e])},this.bindField=function(e){if(u.hasOwnProperty(e.container))return!1;!function(e){var i=m(f(n),e),o=$(i.container),c=o.attr("name");o.on("input change",function(){var e=$(this).val();if(i.input_cb){var t={value:null,obj:{},el:null};e=s(i.type,e),t.el=o[0],t.value=e,t.property=c,t.obj[c]=e,options.input_cb(t,i.params)}u[i.container].intv||(u[i.container].intv=setInterval(function(){!function(e,t){var n=$(e).val(),a=u[e];if(a.val!==n&&(a.val=n,a.changing=(new Date).getTime()),a.changing&&(new Date).getTime()>a.wait+a.changing&&(clearInterval(a.intv),a.intv=!1,u[e].change_cb)){var r={value:null,obj:{},el:null};n=s(u[e].type,n),r.el=$(e)[0],r.property=$(e).attr("name"),r.value=n,r.obj[r.property]=n,u[e].change_cb(r,t)}}(i.container,i.params)},50))}),i.multiline||o.on("keypress",function(e){var t=$(this).val();if(13!==e.which&&i.mask){if(t.length>i.mask.length)return e.preventDefault(),e.stopImmediatePropagation(),!1;for(var n=i.mask,a=0;a<t.length;a++)i.mask.substr(a,1)===i.mask_char&&(n=n.replace(i.mask_char,t.substr(a,1)));-1!==(t=n).indexOf(i.mask_char)&&(t=t.substr(0,t.indexOf(i.mask_char))),o.val(t)}if(13===e.which){e.preventDefault(),e.stopImmediatePropagation();var t=$(this).val();if(u[i.container].intv&&(clearInterval(u[i.container].intv),u[i.container].intv=null),i.change_cb){var r={value:null,obj:{},el:null};t=s(i.type,t),r.el=o[0],r.property=c,r.value=t,r.obj[c]=t,i.change_cb(r,i.params)}else o.trigger("change",t)}});((u[i.container]=i).allowed||i.forbidden)&&l.restrictField(i)}(e)},this.unbindField=function(e){if(u.hasOwnProperty(e)){var t=$(e);t.off("input change"),u[e].multiline||t.off("keypress"),u[e].intv&&clearInterval(u[e].intv),a.hasOwnProperty(e)&&l.unrestrictField(e),delete u[e]}},this.restrictField=function(e){return!a.hasOwnProperty(e.container)&&(function(n){var e=$(n.container);a[n.container]=n,a[n.container].keys=[],null===n.autocomplete&&e[0].hasAttribute("autocomplete")&&"on"===e.attr("autocomplete")?n.autocomplete=!0:n.autocomplete=!1;n.autocomplete?n.hasOwnProperty("allowed")&&n.allowed&&(n.allowed=new RegExp(n.allowed.toString().replace("$/gi","+$").replace("/^","^"),"gi")):a[n.container].keys.push(229);-1!==["input","texarea"].indexOf(e.get(0).tagName.toLowerCase())?a[n.container].content="val":a[n.container].content="html";a[n.container].multiline||a[n.container].keys.push(13);e.on("textInput keydown",function(e){if("textInput"===e.type){var t=e.originalEvent.data;if(a[n.container].allowed){if(!t.match(a[n.container].allowed))return e.preventDefault(),e.stopImmediatePropagation(),!1}else if(a[n.container].forbidden&&t.match(a[n.container].forbidden))return e.preventDefault(),e.stopImmediatePropagation(),!1}if("keydown"===e.type){if(-1!==a[n.container].keys.indexOf(e.which))return e.preventDefault(),e.stopImmediatePropagation(),!1;if($(this)[a[n.container].content]().length>=a[n.container].max&&8!==e.which)return e.preventDefault(),e.stopImmediatePropagation(),!1}}),a[n.container].paste||e.on("paste",function(e){e.preventDefault(),e.stopImmediatePropagation()})}(e),!0)},this.unrestrictField=function(e){if(a.hasOwnProperty(e)){var t=$(e);return t.off("textInput keydown"),a[e].paste||t.off("paste"),delete a[e],!0}return!1},this.formToObj=function(e){return p(e)},this.populateForm=function(e,n){var a,t=$(e);function r(e,t){a=$(t).attr("name"),e.hasOwnProperty(a)&&$(t).val(e[a])}t.find("input").each(function(e,t){r(n,t)}),t.find("texarea").each(function(e,t){r(n,t)})},this.validateForm=function(e){var n,a,r,t=$(e),i={},o=!0;return t.find("input").each(function(e,t){n=$(t),t.hasAttribute("required")&&t.hasAttribute("pattern")&&"submit"!==n.attr("type")&&(a=n.attr("pattern"),r=n.val(),a&&((a=new RegExp(a,"g")).test(r)||(i[n.attr("name")]=!1,o=!1)))}),!!o||i}},OGX.FormTools=new OGX.FormTools;<|endoftext|>


<commit_before>'use strict';

var slugify = require('slugify');
var scrollTo = require('utils/scroll-to');

var item = function (texto, extra) {
  return m('li', {
    config: scrollTo('#' + slugify(texto)),
    style: {
      cursor: 'pointer',
      textTransform: 'uppercase',
      fontFamily: '"open_sansextrabold"',
      lineHeight: '3em'
    }
  }, [
    m('span.check.ok', {
      style: {
        marginRight: '1em'
      }
    }), texto, extra
  ]);
};

var etapas = function (lista) {
  return lista.map(function (e, i) {
    return m('li', {
        style: {
          fontFamily: '"open_sansregular"',
          textTransform: 'none',
          marginLeft: '2em'
        }
      },
      m('a', {
        config: scrollTo('#' + e.id)
      }, [
        m('span.check.ok', {
          style: {
            marginRight: '1em'
          }
        }),
        e.titulo() ? i + 1 + '. ' + e.titulo() : m('i', i + 1 + '. ' + '(sem título)')
      ])
    );
  });
};

module.exports = {

  controller: function (args) {
    this.servico = args.servico;
  },

  view: function (ctrl) {
    return m('nav', [
      m('ul', [
        item('Dados básicos'),
        item('Solicitantes'),
        item('Etapas do Serviço', m('ul', etapas(ctrl.servico().etapas()))),
        item('Outras Informações'),
      ]),
    ]);
  }

};
<commit_msg>Resolve #233<commit_after>'use strict';

var slugify = require('slugify');
var scrollTo = require('utils/scroll-to');

var item = function (texto, extra) {
  return m('li', {
    config: scrollTo('#' + slugify(texto)),
    style: {
      cursor: 'pointer',
      textTransform: 'uppercase',
      fontFamily: '"open_sansextrabold"',
      lineHeight: '3em'
    }
  }, [
    m('span.check.ok', {
      style: {
        marginRight: '1em'
      }
    }), texto, extra
  ]);
};

var etapas = function (lista) {
  return lista.map(function (e, i) {
    return m('li', {
        key: e.id
      }, {
        style: {
          fontFamily: '"open_sansregular"',
          textTransform: 'none',
          marginLeft: '2em'
        }
      },
      m('a', {
        config: scrollTo('#' + e.id)
      }, [
        m('span.check.ok', {
          style: {
            marginRight: '1em'
          }
        }),
        e.titulo() ? i + 1 + '. ' + e.titulo() : m('i', i + 1 + '. ' + '(sem título)')
      ])
    );
  });
};

module.exports = {

  controller: function (args) {
    this.servico = args.servico;
  },

  view: function (ctrl) {
    return m('nav', [
      m('ul', [
        item('Dados básicos'),
        item('Solicitantes'),
        item('Etapas do Serviço', m('ul', etapas(ctrl.servico().etapas()))),
        item('Outras Informações'),
      ]),
    ]);
  }

};
<|endoftext|>


<commit_before>'use strict';

import gulp from 'gulp';
import sass from 'gulp-sass';
import pug from 'gulp-pug';
import pugLint from 'gulp-pug-lint';
import browserSync from 'browser-sync';
import plumber from 'gulp-plumber';
import gitmojis from './src/data/gitmojis.json';
import ghPages from 'gulp-gh-pages';

const baseDirs = {
	src: 'src/',
	dist: 'dist/'
};

const routes = {
	templates: {
		pug: `${baseDirs.src}templates/*.pug`,
		_pug: `${baseDirs.src}templates/_includes/*.pug`
	},
	styles: {
		scss: `${baseDirs.src}styles/*.scss`,
		_scss: `${baseDirs.src}styles/_includes/*.scss`
	},
	files: {
		html: `${baseDirs.dist}`,
		css: `${baseDirs.dist}css/`,
		deploy: `${baseDirs.dist}**/*`
	}
};

gulp.task('templates', () => {
	return gulp.src([routes.templates.pug, '!' + routes.templates._pug])
		.pipe(plumber({}))
		.pipe(pug({
			locals: {
				'emojis': gitmojis
			}
		}))
		.pipe(gulp.dest(routes.files.html))
		.pipe(browserSync.stream())
});

gulp.task('styles', () => {
	return gulp.src(routes.styles.scss)
		.pipe(plumber({}))
		.pipe(sass({
			outputStyle: 'compressed'
		}))
		.pipe(gulp.dest(routes.files.css))
		.pipe(browserSync.stream())
});

gulp.task('test', () => {
	return gulp.src([routes.templates.pug, '!' + routes.templates._pug])
		.pipe(pugLint())
		.pipe(plumber({}))
		.pipe(pug({
			locals: {
				'emojis': gitmojis
			}
		}))
		.pipe(gulp.dest(routes.files.html))

	return gulp.src(routes.styles.scss)
		.pipe(plumber({}))
		.pipe(sass({
			outputStyle: 'compressed'
		}))
		.pipe(gulp.dest(routes.files.css))
});

gulp.task('serve', () => {
	browserSync.init({
		server: `${baseDirs.dist}`
	});

	gulp.watch([routes.templates.pug, routes.templates._pug], ['templates']);
	gulp.watch([routes.styles.scss, routes.styles._scss], ['styles']);
});

gulp.task('deploy', () => {
	return gulp.src(routes.files.deploy)
		.pipe(ghPages({
			message: ':rocket: gitmoji website'
		}))
});

gulp.task('dev', ['templates', 'styles', 'serve']);

gulp.task('default', () => {
	gulp.start('dev');
});
<commit_msg>:wrench: Update gulp test task<commit_after>'use strict';

import gulp from 'gulp';
import sass from 'gulp-sass';
import pug from 'gulp-pug';
import pugLint from 'gulp-pug-lint';
import browserSync from 'browser-sync';
import plumber from 'gulp-plumber';
import gitmojis from './src/data/gitmojis.json';
import ghPages from 'gulp-gh-pages';

const baseDirs = {
	src: 'src/',
	dist: 'dist/'
};

const routes = {
	templates: {
		pug: `${baseDirs.src}templates/*.pug`,
		_pug: `${baseDirs.src}templates/_includes/*.pug`
	},
	styles: {
		scss: `${baseDirs.src}styles/*.scss`,
		_scss: `${baseDirs.src}styles/_includes/*.scss`
	},
	files: {
		html: `${baseDirs.dist}`,
		css: `${baseDirs.dist}css/`,
		deploy: `${baseDirs.dist}**/*`
	}
};

gulp.task('templates', () => {
	return gulp.src([routes.templates.pug, '!' + routes.templates._pug])
		.pipe(plumber({}))
		.pipe(pug({
			locals: {
				'emojis': gitmojis
			}
		}))
		.pipe(gulp.dest(routes.files.html))
		.pipe(browserSync.stream())
});

gulp.task('styles', () => {
	return gulp.src(routes.styles.scss)
		.pipe(plumber({}))
		.pipe(sass({
			outputStyle: 'compressed'
		}))
		.pipe(gulp.dest(routes.files.css))
		.pipe(browserSync.stream())
});

gulp.task('test', () => {
	return gulp.src(routes.styles.scss)
		.pipe(plumber({}))
		.pipe(sass({
			outputStyle: 'compressed'
		}))
		.pipe(gulp.dest(routes.files.css))

	return gulp.src([routes.templates.pug, '!' + routes.templates._pug])
		.pipe(pugLint())
		.pipe(plumber({}))
		.pipe(pug({
			locals: {
				'emojis': gitmojis
			}
		}))
		.pipe(gulp.dest(routes.files.html))
});

gulp.task('serve', () => {
	browserSync.init({
		server: `${baseDirs.dist}`
	});

	gulp.watch([routes.templates.pug, routes.templates._pug], ['templates']);
	gulp.watch([routes.styles.scss, routes.styles._scss], ['styles']);
});

gulp.task('deploy', () => {
	return gulp.src(routes.files.deploy)
		.pipe(ghPages({
			message: ':rocket: gitmoji website'
		}))
});

gulp.task('dev', ['templates', 'styles', 'serve']);

gulp.task('default', () => {
	gulp.start('dev');
});
<|endoftext|>


<commit_before>import { document } from 'ssr-window';
import $ from 'dom7';
import Device from '../../utils/device';
import ViAd from './vi-class';

export default {
  name: 'vi',
  params: {
    vi: {
      enabled: false,
      autoplay: true,
      fallbackOverlay: true,
      fallbackOverlayText: 'Please watch this ad',
      showMute: true,
      startMuted: (Device.ios || Device.android) && !Device.cordova,
      appId: null,
      appVer: null,
      language: null,
      width: null,
      height: null,
      placementId: 'pltd4o7ibb9rc653x14',
      placementType: 'interstitial',
      videoSlot: null,
      showProgress: true,
      showBranding: true,
      os: null,
      osVersion: null,
      orientation: null,
      age: null,
      gender: null,
      advertiserId: null,
      latitude: null,
      longitude: null,
      accuracy: null,
      storeId: null,
      ip: null,
      manufacturer: null,
      model: null,
      connectionType: null,
      connectionProvider: null,
    },
  },
  create() {
    const app = this;
    app.vi = {
      sdkReady: false,
      createAd(adParams) {
        return new ViAd(app, adParams);
      },
      loadSdk() {
        if (app.vi.skdReady) return;
        const script = document.createElement('script');
        script.onload = function onload() {
          app.emit('viSdkReady');
          app.vi.skdReady = true;
        };
        script.src = 'https://c.vi-serve.com/viadshtml/vi.min.js';
        $('head').append(script);
      },
    };
  },
  on: {
    init() {
      const app = this;
      if (app.params.vi.enabled || (app.passedParams.vi && app.passedParams.vi.enabled !== false)) app.vi.loadSdk();
    },
  },
};
<commit_msg>Fix typo<commit_after>import { document } from 'ssr-window';
import $ from 'dom7';
import Device from '../../utils/device';
import ViAd from './vi-class';

export default {
  name: 'vi',
  params: {
    vi: {
      enabled: false,
      autoplay: true,
      fallbackOverlay: true,
      fallbackOverlayText: 'Please watch this ad',
      showMute: true,
      startMuted: (Device.ios || Device.android) && !Device.cordova,
      appId: null,
      appVer: null,
      language: null,
      width: null,
      height: null,
      placementId: 'pltd4o7ibb9rc653x14',
      placementType: 'interstitial',
      videoSlot: null,
      showProgress: true,
      showBranding: true,
      os: null,
      osVersion: null,
      orientation: null,
      age: null,
      gender: null,
      advertiserId: null,
      latitude: null,
      longitude: null,
      accuracy: null,
      storeId: null,
      ip: null,
      manufacturer: null,
      model: null,
      connectionType: null,
      connectionProvider: null,
    },
  },
  create() {
    const app = this;
    app.vi = {
      sdkReady: false,
      createAd(adParams) {
        return new ViAd(app, adParams);
      },
      loadSdk() {
        if (app.vi.sdkReady) return;
        const script = document.createElement('script');
        script.onload = function onload() {
          app.emit('viSdkReady');
          app.vi.sdkReady = true;
        };
        script.src = 'https://c.vi-serve.com/viadshtml/vi.min.js';
        $('head').append(script);
      },
    };
  },
  on: {
    init() {
      const app = this;
      if (app.params.vi.enabled || (app.passedParams.vi && app.passedParams.vi.enabled !== false)) app.vi.loadSdk();
    },
  },
};
<|endoftext|>


<commit_before>import classNames from 'classnames';
import React from 'react';

const ConfigurationMapValue = (props) => {
  let classes = classNames('configuration-map-value', {
    'configuration-map-value-stacked': props.stacked
  });

  return (

      {props.children}

  );
};

module.exports = ConfigurationMapValue;
<commit_msg>ConfigurationMapValue: Adding `value` property<commit_after>import classNames from 'classnames';
import React from 'react';

const ConfigurationMapValue = (props) => {
  let classes = classNames('configuration-map-value', {
    'configuration-map-value-stacked': props.stacked
  });

  return (

      {props.value || props.children}

  );
};

module.exports = ConfigurationMapValue;
<|endoftext|>


<commit_before>/**
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

const functions = require('firebase-functions');
const cookieParser = require('cookie-parser');
const crypto = require('crypto');

// Firebase Setup
const admin = require('firebase-admin');
const serviceAccount = require('./service-account.json');
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: `https://${process.env.GCLOUD_PROJECT}.firebaseio.com`,
});

const OAUTH_REDIRECT_URI = `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com/popup.html`;
const OAUTH_SCOPES = 'basic';

/**
 * Creates a configured simple-oauth2 client for Instagram.
 */
function instagramOAuth2Client() {
  // Instagram OAuth 2 setup
  // TODO: Configure the `instagram.client_id` and `instagram.client_secret` Google Cloud environment variables.
  const credentials = {
    client: {
      id: functions.config().instagram.client_id,
      secret: functions.config().instagram.client_secret,
    },
    auth: {
      tokenHost: 'https://api.instagram.com',
      tokenPath: '/oauth/access_token',
    },
  };
  return require('simple-oauth2').create(credentials);
}

/**
 * Redirects the User to the Instagram authentication consent screen. Also the 'state' cookie is set for later state
 * verification.
 */
exports.redirect = functions.https.onRequest((req, res) => {
  const oauth2 = instagramOAuth2Client();

  cookieParser()(req, res, () => {
    const state = req.cookies.state || crypto.randomBytes(20).toString('hex');
    console.log('Setting verification state:', state);
    res.cookie('state', state.toString(), {
      maxAge: 3600000,
      secure: true,
      httpOnly: true,
    });
    const redirectUri = oauth2.authorizationCode.authorizeURL({
      redirect_uri: OAUTH_REDIRECT_URI,
      scope: OAUTH_SCOPES,
      state: state,
    });
    console.log('Redirecting to:', redirectUri);
    res.redirect(redirectUri);
  });
});

/**
 * Exchanges a given Instagram auth code passed in the 'code' URL query parameter for a Firebase auth token.
 * The request also needs to specify a 'state' query parameter which will be checked against the 'state' cookie.
 * The Firebase custom auth token, display name, photo URL and Instagram acces token are sent back in a JSONP callback
 * function with function name defined by the 'callback' query parameter.
 */
exports.token = functions.https.onRequest((req, res) => {
  const oauth2 = instagramOAuth2Client();

  try {
    return cookieParser()(req, res, () => {
      console.log('Received verification state:', req.cookies.state);
      console.log('Received state:', req.query.state);
      if (!req.cookies.state) {
        throw new Error('State cookie not set or expired. Maybe you took too long to authorize. Please try again.');
      } else if (req.cookies.state !== req.query.state) {
        throw new Error('State validation failed');
      }
      console.log('Received auth code:', req.query.code);
      oauth2.authorizationCode.getToken({
        code: req.query.code,
        redirect_uri: OAUTH_REDIRECT_URI,
      });
    }).then((results) => {
      console.log('Auth code exchange result received:', results);

      // We have an Instagram access token and the user identity now.
      const accessToken = results.access_token;
      const instagramUserID = results.user.id;
      const profilePic = results.user.profile_picture;
      const userName = results.user.full_name;

      // Create a Firebase account and get the Custom Auth Token.
      return createFirebaseAccount(instagramUserID, userName, profilePic, accessToken);
    }).then((firebaseToken) => {
      // Serve an HTML page that signs the user in and updates the user profile.
      return res.jsonp({
        token: firebaseToken,
      });
    });
  } catch (error) {
    return res.jsonp({
      error: error.toString(),
    });
  }
});

/**
 * Creates a Firebase account with the given user profile and returns a custom auth token allowing
 * signing-in this account.
 * Also saves the accessToken to the datastore at /instagramAccessToken/$uid
 *
 * @returns {Promise<string>} The Firebase custom auth token in a promise.
 */
function createFirebaseAccount(instagramID, displayName, photoURL, accessToken) {
  // The UID we'll assign to the user.
  const uid = `instagram:${instagramID}`;

  // Save the access token tot he Firebase Realtime Database.
  const databaseTask = admin.database().ref(`/instagramAccessToken/${uid}`)
    .set(accessToken);
  // Create or update the user account.
  const userCreationTask = admin.auth().updateUser(uid, {
    displayName: displayName,
    photoURL: photoURL,
  }).catch((error) => {
    // If user does not exists we create it.
    if (error.code === 'auth/user-not-found') {
      return admin.auth().createUser({
        uid: uid,
        displayName: displayName,
        photoURL: photoURL,
      });
    }
    throw error;
  });

  // Wait for all async task to complete then generate and return a custom auth token.
  return Promise.all([userCreationTask, databaseTask]).then(() => {
    // Create a Firebase custom auth token.
    return admin.auth().createCustomToken(uid);
  }).then((token) => {
    console.log('Created Custom token for UID "', uid, '" Token:', token);
    return token;
  });
}
<commit_msg>Fix instagram-auth sample<commit_after>/**
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

const functions = require('firebase-functions');
const cookieParser = require('cookie-parser');
const crypto = require('crypto');

// Firebase Setup
const admin = require('firebase-admin');
const serviceAccount = require('./service-account.json');
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: `https://${process.env.GCLOUD_PROJECT}.firebaseio.com`,
});

const OAUTH_REDIRECT_URI = `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com/popup.html`;
const OAUTH_SCOPES = 'basic';

/**
 * Creates a configured simple-oauth2 client for Instagram.
 */
function instagramOAuth2Client() {
  // Instagram OAuth 2 setup
  // TODO: Configure the `instagram.client_id` and `instagram.client_secret` Google Cloud environment variables.
  const credentials = {
    client: {
      id: functions.config().instagram.client_id,
      secret: functions.config().instagram.client_secret,
    },
    auth: {
      tokenHost: 'https://api.instagram.com',
      tokenPath: '/oauth/access_token',
    },
  };
  return require('simple-oauth2').create(credentials);
}

/**
 * Redirects the User to the Instagram authentication consent screen. Also the 'state' cookie is set for later state
 * verification.
 */
exports.redirect = functions.https.onRequest((req, res) => {
  const oauth2 = instagramOAuth2Client();

  cookieParser()(req, res, () => {
    const state = req.cookies.state || crypto.randomBytes(20).toString('hex');
    console.log('Setting verification state:', state);
    res.cookie('state', state.toString(), {
      maxAge: 3600000,
      secure: true,
      httpOnly: true,
    });
    const redirectUri = oauth2.authorizationCode.authorizeURL({
      redirect_uri: OAUTH_REDIRECT_URI,
      scope: OAUTH_SCOPES,
      state: state,
    });
    console.log('Redirecting to:', redirectUri);
    res.redirect(redirectUri);
  });
});

/**
 * Exchanges a given Instagram auth code passed in the 'code' URL query parameter for a Firebase auth token.
 * The request also needs to specify a 'state' query parameter which will be checked against the 'state' cookie.
 * The Firebase custom auth token, display name, photo URL and Instagram acces token are sent back in a JSONP callback
 * function with function name defined by the 'callback' query parameter.
 */
exports.token = functions.https.onRequest((req, res) => {
  const oauth2 = instagramOAuth2Client();

  try {
    return cookieParser()(req, res, () => {
      console.log('Received verification state:', req.cookies.state);
      console.log('Received state:', req.query.state);
      if (!req.cookies.state) {
        throw new Error('State cookie not set or expired. Maybe you took too long to authorize. Please try again.');
      } else if (req.cookies.state !== req.query.state) {
        throw new Error('State validation failed');
      }
      console.log('Received auth code:', req.query.code);
      oauth2.authorizationCode.getToken({
        code: req.query.code,
        redirect_uri: OAUTH_REDIRECT_URI,
      }).then((results) => {
        console.log('Auth code exchange result received:', results);

        // We have an Instagram access token and the user identity now.
        const accessToken = results.access_token;
        const instagramUserID = results.user.id;
        const profilePic = results.user.profile_picture;
        const userName = results.user.full_name;

        // Create a Firebase account and get the Custom Auth Token.
        return createFirebaseAccount(instagramUserID, userName, profilePic, accessToken);
      }).then((firebaseToken) => {
        // Serve an HTML page that signs the user in and updates the user profile.
        return res.jsonp({
          token: firebaseToken,
        });
      });
    });
  } catch (error) {
    return res.jsonp({
      error: error.toString(),
    });
  }
});

/**
 * Creates a Firebase account with the given user profile and returns a custom auth token allowing
 * signing-in this account.
 * Also saves the accessToken to the datastore at /instagramAccessToken/$uid
 *
 * @returns {Promise<string>} The Firebase custom auth token in a promise.
 */
function createFirebaseAccount(instagramID, displayName, photoURL, accessToken) {
  // The UID we'll assign to the user.
  const uid = `instagram:${instagramID}`;

  // Save the access token tot he Firebase Realtime Database.
  const databaseTask = admin.database().ref(`/instagramAccessToken/${uid}`)
    .set(accessToken);
  // Create or update the user account.
  const userCreationTask = admin.auth().updateUser(uid, {
    displayName: displayName,
    photoURL: photoURL,
  }).catch((error) => {
    // If user does not exists we create it.
    if (error.code === 'auth/user-not-found') {
      return admin.auth().createUser({
        uid: uid,
        displayName: displayName,
        photoURL: photoURL,
      });
    }
    throw error;
  });

  // Wait for all async task to complete then generate and return a custom auth token.
  return Promise.all([userCreationTask, databaseTask]).then(() => {
    // Create a Firebase custom auth token.
    return admin.auth().createCustomToken(uid);
  }).then((token) => {
    console.log('Created Custom token for UID "', uid, '" Token:', token);
    return token;
  });
}
<|endoftext|>


<commit_before>/*
 * This plug-in adds another pagination option similar to full_numbers,
 * except it adds ellipses around the page numbers when applicable.
 * You can set how many page numbers should be displayed with the iShowPages option.
 * This plug-in extends the oStdClasses object with the following properties:
 * sPageEllipsis, sPageNumber and sPageNumbers.
 * It also extends the oSettings object with the following properties:
 * _iShowPages, _iShowPagesHalf, _iCurrentPage, _iTotalPages, _iFirstPage and _iLastPage.
 *
 * @name Ellipses
 * @anchor ellipses
 * @author Dave Kennedy
 * @example
 *     $('#my-table').dataTable({
 *         // Optional usage of extended oSettings object
 *         'fnInfoCallback': function(oSettings) {
 *             // Update stateful properties
 *             $.fn.dataTableExt.oPagination.ellipses.fnUpdateState(oSettings);
 *             return 'Viewing page ' + oSettings._iCurrentPage + ' of ' + oSettings._iTotalPages;
 *         },
 *         // Optional usage of iShowPages option
 *         'iShowPages': 15,
 *         // This is the only required option
 *         'sPaginationType': 'ellipses'
 *     });
 */

$.extend($.fn.dataTableExt.oStdClasses, {
    'sPageEllipsis': 'paginate_ellipsis',
    'sPageNumber': 'paginate_number',
    'sPageNumbers': 'paginate_numbers'
});

$.fn.dataTableExt.oPagination.ellipses = {
    'oDefaults': {
        'iShowPages': 5
    },
    'fnClickHandler': function(e) {
        var fnCallbackDraw = e.data.fnCallbackDraw,
            oSettings = e.data.oSettings,
            sPage = e.data.sPage;

        if ($(this).is('[disabled]')) {
            return false;
        }

        oSettings.oApi._fnPageChange(oSettings, sPage);
        fnCallbackDraw(oSettings);

        return true;
    },
    // fnInit is called once for each instance of pager
    'fnInit': function(oSettings, nPager, fnCallbackDraw) {
        var oClasses = oSettings.oClasses,
            oLang = oSettings.oLanguage.oPaginate,
            that = this;

        var iShowPages = oSettings.oInit.iShowPages || this.oDefaults.iShowPages,
            iShowPagesHalf = Math.floor(iShowPages / 2);

        $.extend(oSettings, {
            _iShowPages: iShowPages,
            _iShowPagesHalf: iShowPagesHalf,
        });

        var oFirst = $('' + oLang.sFirst + ''),
            oPrevious = $('' + oLang.sPrevious + ''),
            oNumbers = $(''),
            oNext = $('' + oLang.sNext + ''),
            oLast = $('' + oLang.sLast + '');

        oFirst.click({ 'fnCallbackDraw': fnCallbackDraw, 'oSettings': oSettings, 'sPage': 'first' }, that.fnClickHandler);
        oPrevious.click({ 'fnCallbackDraw': fnCallbackDraw, 'oSettings': oSettings, 'sPage': 'previous' }, that.fnClickHandler);
        oNext.click({ 'fnCallbackDraw': fnCallbackDraw, 'oSettings': oSettings, 'sPage': 'next' }, that.fnClickHandler);
        oLast.click({ 'fnCallbackDraw': fnCallbackDraw, 'oSettings': oSettings, 'sPage': 'last' }, that.fnClickHandler);

        // Draw
        $(nPager).append(oFirst, oPrevious, oNumbers, oNext, oLast);
    },
    // fnUpdate is only called once while table is rendered
    'fnUpdate': function(oSettings, fnCallbackDraw) {
        var oClasses = oSettings.oClasses,
            that = this;

        var tableWrapper = oSettings.nTableWrapper;

        // Update stateful properties
        this.fnUpdateState(oSettings);

        if (oSettings._iCurrentPage === 1) {
            $('.' + oClasses.sPageFirst, tableWrapper).attr('disabled', true);
            $('.' + oClasses.sPagePrevious, tableWrapper).attr('disabled', true);
        } else {
            $('.' + oClasses.sPageFirst, tableWrapper).removeAttr('disabled');
            $('.' + oClasses.sPagePrevious, tableWrapper).removeAttr('disabled');
        }

        if (oSettings._iTotalPages === 0 || oSettings._iCurrentPage === oSettings._iTotalPages) {
            $('.' + oClasses.sPageNext, tableWrapper).attr('disabled', true);
            $('.' + oClasses.sPageLast, tableWrapper).attr('disabled', true);
        } else {
            $('.' + oClasses.sPageNext, tableWrapper).removeAttr('disabled');
            $('.' + oClasses.sPageLast, tableWrapper).removeAttr('disabled');
        }

        var i, oNumber, oNumbers = $('.' + oClasses.sPageNumbers, tableWrapper);

        // Erase
        oNumbers.html('');

        for (i = oSettings._iFirstPage; i <= oSettings._iLastPage; i++) {
            oNumber = $('' + oSettings.fnFormatNumber(i) + '');

            if (oSettings._iCurrentPage === i) {
                oNumber.attr('active', true).attr('disabled', true);
            } else {
                oNumber.click({ 'fnCallbackDraw': fnCallbackDraw, 'oSettings': oSettings, 'sPage': i - 1 }, that.fnClickHandler);
            }

            // Draw
            oNumbers.append(oNumber);
        }

        // Add ellipses
        if (1 < oSettings._iFirstPage) {
            oNumbers.prepend('...');
        }

        if (oSettings._iLastPage < oSettings._iTotalPages) {
            oNumbers.append('...');
        }
    },
    // fnUpdateState used to be part of fnUpdate
    // The reason for moving is so we can access current state info before fnUpdate is called
    'fnUpdateState': function(oSettings) {
        var iCurrentPage = Math.ceil((oSettings._iDisplayStart + 1) / oSettings._iDisplayLength),
            iTotalPages = Math.ceil(oSettings.fnRecordsDisplay() / oSettings._iDisplayLength),
            iFirstPage = iCurrentPage - oSettings._iShowPagesHalf,
            iLastPage = iCurrentPage + oSettings._iShowPagesHalf;

        if (iTotalPages < oSettings._iShowPages) {
            iFirstPage = 1;
            iLastPage = iTotalPages;
        } else if (iFirstPage < 1) {
            iFirstPage = 1;
            iLastPage = oSettings._iShowPages;
        } else if (iLastPage > iTotalPages) {
            iFirstPage = (iTotalPages - oSettings._iShowPages) + 1;
            iLastPage = iTotalPages;
        }

        $.extend(oSettings, {
            _iCurrentPage: iCurrentPage,
            _iTotalPages: iTotalPages,
            _iFirstPage: iFirstPage,
            _iLastPage: iLastPage
        });
    }
};
<commit_msg>Simplified example<commit_after>/*
 * This plug-in adds another pagination option similar to full_numbers,
 * except it adds ellipses around the page numbers when applicable.
 * You can set how many page numbers should be displayed with the iShowPages option.
 * This plug-in extends the oStdClasses object with the following properties:
 * sPageEllipsis, sPageNumber and sPageNumbers.
 * It also extends the oSettings object with the following properties:
 * _iShowPages, _iShowPagesHalf, _iCurrentPage, _iTotalPages, _iFirstPage and _iLastPage.
 *
 * @name Ellipses
 * @anchor ellipses
 * @author Dave Kennedy
 * @example
 *     $(document).ready(function() {
 *         $('#example').dataTable({
 *             'sPaginationType': 'ellipses'
 *         });
 *     });
 */

$.extend($.fn.dataTableExt.oStdClasses, {
    'sPageEllipsis': 'paginate_ellipsis',
    'sPageNumber': 'paginate_number',
    'sPageNumbers': 'paginate_numbers'
});

$.fn.dataTableExt.oPagination.ellipses = {
    'oDefaults': {
        'iShowPages': 5
    },
    'fnClickHandler': function(e) {
        var fnCallbackDraw = e.data.fnCallbackDraw,
            oSettings = e.data.oSettings,
            sPage = e.data.sPage;

        if ($(this).is('[disabled]')) {
            return false;
        }

        oSettings.oApi._fnPageChange(oSettings, sPage);
        fnCallbackDraw(oSettings);

        return true;
    },
    // fnInit is called once for each instance of pager
    'fnInit': function(oSettings, nPager, fnCallbackDraw) {
        var oClasses = oSettings.oClasses,
            oLang = oSettings.oLanguage.oPaginate,
            that = this;

        var iShowPages = oSettings.oInit.iShowPages || this.oDefaults.iShowPages,
            iShowPagesHalf = Math.floor(iShowPages / 2);

        $.extend(oSettings, {
            _iShowPages: iShowPages,
            _iShowPagesHalf: iShowPagesHalf,
        });

        var oFirst = $('' + oLang.sFirst + ''),
            oPrevious = $('' + oLang.sPrevious + ''),
            oNumbers = $(''),
            oNext = $('' + oLang.sNext + ''),
            oLast = $('' + oLang.sLast + '');

        oFirst.click({ 'fnCallbackDraw': fnCallbackDraw, 'oSettings': oSettings, 'sPage': 'first' }, that.fnClickHandler);
        oPrevious.click({ 'fnCallbackDraw': fnCallbackDraw, 'oSettings': oSettings, 'sPage': 'previous' }, that.fnClickHandler);
        oNext.click({ 'fnCallbackDraw': fnCallbackDraw, 'oSettings': oSettings, 'sPage': 'next' }, that.fnClickHandler);
        oLast.click({ 'fnCallbackDraw': fnCallbackDraw, 'oSettings': oSettings, 'sPage': 'last' }, that.fnClickHandler);

        // Draw
        $(nPager).append(oFirst, oPrevious, oNumbers, oNext, oLast);
    },
    // fnUpdate is only called once while table is rendered
    'fnUpdate': function(oSettings, fnCallbackDraw) {
        var oClasses = oSettings.oClasses,
            that = this;

        var tableWrapper = oSettings.nTableWrapper;

        // Update stateful properties
        this.fnUpdateState(oSettings);

        if (oSettings._iCurrentPage === 1) {
            $('.' + oClasses.sPageFirst, tableWrapper).attr('disabled', true);
            $('.' + oClasses.sPagePrevious, tableWrapper).attr('disabled', true);
        } else {
            $('.' + oClasses.sPageFirst, tableWrapper).removeAttr('disabled');
            $('.' + oClasses.sPagePrevious, tableWrapper).removeAttr('disabled');
        }

        if (oSettings._iTotalPages === 0 || oSettings._iCurrentPage === oSettings._iTotalPages) {
            $('.' + oClasses.sPageNext, tableWrapper).attr('disabled', true);
            $('.' + oClasses.sPageLast, tableWrapper).attr('disabled', true);
        } else {
            $('.' + oClasses.sPageNext, tableWrapper).removeAttr('disabled');
            $('.' + oClasses.sPageLast, tableWrapper).removeAttr('disabled');
        }

        var i, oNumber, oNumbers = $('.' + oClasses.sPageNumbers, tableWrapper);

        // Erase
        oNumbers.html('');

        for (i = oSettings._iFirstPage; i <= oSettings._iLastPage; i++) {
            oNumber = $('' + oSettings.fnFormatNumber(i) + '');

            if (oSettings._iCurrentPage === i) {
                oNumber.attr('active', true).attr('disabled', true);
            } else {
                oNumber.click({ 'fnCallbackDraw': fnCallbackDraw, 'oSettings': oSettings, 'sPage': i - 1 }, that.fnClickHandler);
            }

            // Draw
            oNumbers.append(oNumber);
        }

        // Add ellipses
        if (1 < oSettings._iFirstPage) {
            oNumbers.prepend('...');
        }

        if (oSettings._iLastPage < oSettings._iTotalPages) {
            oNumbers.append('...');
        }
    },
    // fnUpdateState used to be part of fnUpdate
    // The reason for moving is so we can access current state info before fnUpdate is called
    'fnUpdateState': function(oSettings) {
        var iCurrentPage = Math.ceil((oSettings._iDisplayStart + 1) / oSettings._iDisplayLength),
            iTotalPages = Math.ceil(oSettings.fnRecordsDisplay() / oSettings._iDisplayLength),
            iFirstPage = iCurrentPage - oSettings._iShowPagesHalf,
            iLastPage = iCurrentPage + oSettings._iShowPagesHalf;

        if (iTotalPages < oSettings._iShowPages) {
            iFirstPage = 1;
            iLastPage = iTotalPages;
        } else if (iFirstPage < 1) {
            iFirstPage = 1;
            iLastPage = oSettings._iShowPages;
        } else if (iLastPage > iTotalPages) {
            iFirstPage = (iTotalPages - oSettings._iShowPages) + 1;
            iLastPage = iTotalPages;
        }

        $.extend(oSettings, {
            _iCurrentPage: iCurrentPage,
            _iTotalPages: iTotalPages,
            _iFirstPage: iFirstPage,
            _iLastPage: iLastPage
        });
    }
};
<|endoftext|>


<commit_before>define([
        '../ThirdParty/when',
        './Check',
        './defaultValue',
        './defined',
        './DeveloperError',
        './Request',
        './RequestErrorEvent',
        './RequestScheduler',
        './RuntimeError',
        './TrustedServers'
    ], function(
        when,
        Check,
        defaultValue,
        defined,
        DeveloperError,
        Request,
        RequestErrorEvent,
        RequestScheduler,
        RuntimeError,
        TrustedServers) {
    'use strict';

    /**
     * Asynchronously loads the given URL.  Returns a promise that will resolve to
     * the result once loaded, or reject if the URL failed to load.  The data is loaded
     * using XMLHttpRequest, which means that in order to make requests to another origin,
     * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
     *
     * @exports loadWithXhr
     *
     * @param {Object} options Object with the following properties:
     * @param {String} options.url The URL of the data.
     * @param {String} [options.responseType] The type of response.  This controls the type of item returned.
     * @param {String} [options.method='GET'] The HTTP method to use.
     * @param {String} [options.data] The data to send with the request, if any.
     * @param {Object} [options.headers] HTTP headers to send with the request, if any.
     * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
     * @param {Request} [options.request] The request object.
     * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if request.throttle is true and the request does not have high enough priority.
     *
     *
     * @example
     * // Load a single URL asynchronously. In real code, you should use loadBlob instead.
     * Cesium.loadWithXhr({
     *     url : 'some/url',
     *     responseType : 'blob'
     * }).then(function(blob) {
     *     // use the data
     * }).otherwise(function(error) {
     *     // an error occurred
     * });
     *
     * @see loadArrayBuffer
     * @see loadBlob
     * @see loadJson
     * @see loadText
     * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
     * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
     */
    function loadWithXhr(options) {
        options = defaultValue(options, defaultValue.EMPTY_OBJECT);

        //>>includeStart('debug', pragmas.debug);
        Check.defined('options.url', options.url);
        //>>includeEnd('debug');

        var url = options.url;

        var responseType = options.responseType;
        var method = defaultValue(options.method, 'GET');
        var data = options.data;
        var headers = options.headers;
        var overrideMimeType = options.overrideMimeType;
        url = defaultValue(url, options.url);

        var request = defined(options.request) ? options.request : new Request();
        request.url = url;
        request.requestFunction = function() {
            var deferred = when.defer();
            var xhr = loadWithXhr.load(url, responseType, method, data, headers, deferred, overrideMimeType);
            if (defined(xhr) && defined(xhr.abort)) {
                request.cancelFunction = function() {
                    xhr.abort();
                };
            }
            return deferred.promise;
        };

        return RequestScheduler.request(request);
    }

    var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;

    function decodeDataUriText(isBase64, data) {
        var result = decodeURIComponent(data);
        if (isBase64) {
            return atob(result);
        }
        return result;
    }

    function decodeDataUriArrayBuffer(isBase64, data) {
        var byteString = decodeDataUriText(isBase64, data);
        var buffer = new ArrayBuffer(byteString.length);
        var view = new Uint8Array(buffer);
        for (var i = 0; i < byteString.length; i++) {
            view[i] = byteString.charCodeAt(i);
        }
        return buffer;
    }

    function decodeDataUri(dataUriRegexResult, responseType) {
        responseType = defaultValue(responseType, '');
        var mimeType = dataUriRegexResult[1];
        var isBase64 = !!dataUriRegexResult[2];
        var data = dataUriRegexResult[3];

        switch (responseType) {
            case '':
            case 'text':
                return decodeDataUriText(isBase64, data);
            case 'arraybuffer':
                return decodeDataUriArrayBuffer(isBase64, data);
            case 'blob':
                var buffer = decodeDataUriArrayBuffer(isBase64, data);
                return new Blob([buffer], {
                    type : mimeType
                });
            case 'document':
                var parser = new DOMParser();
                return parser.parseFromString(decodeDataUriText(isBase64, data), mimeType);
            case 'json':
                return JSON.parse(decodeDataUriText(isBase64, data));
            default:
                //>>includeStart('debug', pragmas.debug);
                throw new DeveloperError('Unhandled responseType: ' + responseType);
                //>>includeEnd('debug');
        }
    }

    // This is broken out into a separate function so that it can be mocked for testing purposes.
    loadWithXhr.load = function(url, responseType, method, data, headers, deferred, overrideMimeType) {
        var dataUriRegexResult = dataUriRegex.exec(url);
        if (dataUriRegexResult !== null) {
            deferred.resolve(decodeDataUri(dataUriRegexResult, responseType));
            return;
        }

        var xhr = new XMLHttpRequest();

        if (TrustedServers.contains(url)) {
            xhr.withCredentials = true;
        }

        if (defined(overrideMimeType) && defined(xhr.overrideMimeType)) {
            xhr.overrideMimeType(overrideMimeType);
        }

        xhr.open(method, url, true);

        if (defined(headers)) {
            for (var key in headers) {
                if (headers.hasOwnProperty(key)) {
                    xhr.setRequestHeader(key, headers[key]);
                }
            }
        }

        if (defined(responseType)) {
            xhr.responseType = responseType;
        }

        // While non-standard, file protocol always returns a status of 0 on success
        var localFile = false;
        if (typeof url === 'string') {
            localFile = url.indexOf('file://') === 0;
        }

        xhr.onload = function() {
            if ((xhr.status < 200 || xhr.status >= 300) && !(localFile && xhr.status === 0)) {
                deferred.reject(new RequestErrorEvent(xhr.status, xhr.response, xhr.getAllResponseHeaders()));
                return;
            }

            var response = xhr.response;
            var browserResponseType = xhr.responseType;

            if (xhr.status === 204) { // accept no content
                deferred.resolve();
            } else if (defined(response) && (!defined(responseType) || (browserResponseType === responseType))) {
                //All modern browsers will go into either the first if block or last else block.
                //Other code paths support older browsers that either do not support the supplied responseType
                //or do not support the xhr.response property.
                deferred.resolve(response);
            } else if ((responseType === 'json') && typeof response === 'string') {
                try {
                    deferred.resolve(JSON.parse(response));
                } catch (e) {
                    deferred.reject(e);
                }
            } else if ((browserResponseType === '' || browserResponseType === 'document') && defined(xhr.responseXML) && xhr.responseXML.hasChildNodes()) {
                deferred.resolve(xhr.responseXML);
            } else if ((browserResponseType === '' || browserResponseType === 'text') && defined(xhr.responseText)) {
                deferred.resolve(xhr.responseText);
            } else {
                deferred.reject(new RuntimeError('Invalid XMLHttpRequest response type.'));
            }
        };

        xhr.onerror = function(e) {
            deferred.reject(new RequestErrorEvent());
        };

        xhr.send(data);

        return xhr;
    };

    loadWithXhr.defaultLoad = loadWithXhr.load;

    return loadWithXhr;
});
<commit_msg>fix comment<commit_after>define([
        '../ThirdParty/when',
        './Check',
        './defaultValue',
        './defined',
        './DeveloperError',
        './Request',
        './RequestErrorEvent',
        './RequestScheduler',
        './RuntimeError',
        './TrustedServers'
    ], function(
        when,
        Check,
        defaultValue,
        defined,
        DeveloperError,
        Request,
        RequestErrorEvent,
        RequestScheduler,
        RuntimeError,
        TrustedServers) {
    'use strict';

    /**
     * Asynchronously loads the given URL.  Returns a promise that will resolve to
     * the result once loaded, or reject if the URL failed to load.  The data is loaded
     * using XMLHttpRequest, which means that in order to make requests to another origin,
     * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
     *
     * @exports loadWithXhr
     *
     * @param {Object} options Object with the following properties:
     * @param {String} options.url The URL of the data.
     * @param {String} [options.responseType] The type of response.  This controls the type of item returned.
     * @param {String} [options.method='GET'] The HTTP method to use.
     * @param {String} [options.data] The data to send with the request, if any.
     * @param {Object} [options.headers] HTTP headers to send with the request, if any.
     * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
     * @param {Request} [options.request] The request object.
     * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if request.throttle is true and the request does not have high enough priority.
     *
     *
     * @example
     * // Load a single URL asynchronously. In real code, you should use loadBlob instead.
     * Cesium.loadWithXhr({
     *     url : 'some/url',
     *     responseType : 'blob'
     * }).then(function(blob) {
     *     // use the data
     * }).otherwise(function(error) {
     *     // an error occurred
     * });
     *
     * @see loadArrayBuffer
     * @see loadBlob
     * @see loadJson
     * @see loadText
     * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
     * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
     */
    function loadWithXhr(options) {
        options = defaultValue(options, defaultValue.EMPTY_OBJECT);

        //>>includeStart('debug', pragmas.debug);
        Check.defined('options.url', options.url);
        //>>includeEnd('debug');

        var url = options.url;

        var responseType = options.responseType;
        var method = defaultValue(options.method, 'GET');
        var data = options.data;
        var headers = options.headers;
        var overrideMimeType = options.overrideMimeType;
        url = defaultValue(url, options.url);

        var request = defined(options.request) ? options.request : new Request();
        request.url = url;
        request.requestFunction = function() {
            var deferred = when.defer();
            var xhr = loadWithXhr.load(url, responseType, method, data, headers, deferred, overrideMimeType);
            if (defined(xhr) && defined(xhr.abort)) {
                request.cancelFunction = function() {
                    xhr.abort();
                };
            }
            return deferred.promise;
        };

        return RequestScheduler.request(request);
    }

    var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;

    function decodeDataUriText(isBase64, data) {
        var result = decodeURIComponent(data);
        if (isBase64) {
            return atob(result);
        }
        return result;
    }

    function decodeDataUriArrayBuffer(isBase64, data) {
        var byteString = decodeDataUriText(isBase64, data);
        var buffer = new ArrayBuffer(byteString.length);
        var view = new Uint8Array(buffer);
        for (var i = 0; i < byteString.length; i++) {
            view[i] = byteString.charCodeAt(i);
        }
        return buffer;
    }

    function decodeDataUri(dataUriRegexResult, responseType) {
        responseType = defaultValue(responseType, '');
        var mimeType = dataUriRegexResult[1];
        var isBase64 = !!dataUriRegexResult[2];
        var data = dataUriRegexResult[3];

        switch (responseType) {
            case '':
            case 'text':
                return decodeDataUriText(isBase64, data);
            case 'arraybuffer':
                return decodeDataUriArrayBuffer(isBase64, data);
            case 'blob':
                var buffer = decodeDataUriArrayBuffer(isBase64, data);
                return new Blob([buffer], {
                    type : mimeType
                });
            case 'document':
                var parser = new DOMParser();
                return parser.parseFromString(decodeDataUriText(isBase64, data), mimeType);
            case 'json':
                return JSON.parse(decodeDataUriText(isBase64, data));
            default:
                //>>includeStart('debug', pragmas.debug);
                throw new DeveloperError('Unhandled responseType: ' + responseType);
                //>>includeEnd('debug');
        }
    }

    // This is broken out into a separate function so that it can be mocked for testing purposes.
    loadWithXhr.load = function(url, responseType, method, data, headers, deferred, overrideMimeType) {
        var dataUriRegexResult = dataUriRegex.exec(url);
        if (dataUriRegexResult !== null) {
            deferred.resolve(decodeDataUri(dataUriRegexResult, responseType));
            return;
        }

        var xhr = new XMLHttpRequest();

        if (TrustedServers.contains(url)) {
            xhr.withCredentials = true;
        }

        if (defined(overrideMimeType) && defined(xhr.overrideMimeType)) {
            xhr.overrideMimeType(overrideMimeType);
        }

        xhr.open(method, url, true);

        if (defined(headers)) {
            for (var key in headers) {
                if (headers.hasOwnProperty(key)) {
                    xhr.setRequestHeader(key, headers[key]);
                }
            }
        }

        if (defined(responseType)) {
            xhr.responseType = responseType;
        }

        // While non-standard, file protocol always returns a status of 0 on success
        var localFile = false;
        if (typeof url === 'string') {
            localFile = url.indexOf('file://') === 0;
        }

        xhr.onload = function() {
            if ((xhr.status < 200 || xhr.status >= 300) && !(localFile && xhr.status === 0)) {
                deferred.reject(new RequestErrorEvent(xhr.status, xhr.response, xhr.getAllResponseHeaders()));
                return;
            }

            var response = xhr.response;
            var browserResponseType = xhr.responseType;

            //All modern browsers will go into either the first or second if block or last else block.
            //Other code paths support older browsers that either do not support the supplied responseType
            //or do not support the xhr.response property.
            if (xhr.status === 204) {
                // accept no content
                deferred.resolve();
            } else if (defined(response) && (!defined(responseType) || (browserResponseType === responseType))) {
                deferred.resolve(response);
            } else if ((responseType === 'json') && typeof response === 'string') {
                try {
                    deferred.resolve(JSON.parse(response));
                } catch (e) {
                    deferred.reject(e);
                }
            } else if ((browserResponseType === '' || browserResponseType === 'document') && defined(xhr.responseXML) && xhr.responseXML.hasChildNodes()) {
                deferred.resolve(xhr.responseXML);
            } else if ((browserResponseType === '' || browserResponseType === 'text') && defined(xhr.responseText)) {
                deferred.resolve(xhr.responseText);
            } else {
                deferred.reject(new RuntimeError('Invalid XMLHttpRequest response type.'));
            }
        };

        xhr.onerror = function(e) {
            deferred.reject(new RequestErrorEvent());
        };

        xhr.send(data);

        return xhr;
    };

    loadWithXhr.defaultLoad = loadWithXhr.load;

    return loadWithXhr;
});
<|endoftext|>